ngram
listlengths 0
67.8k
|
|---|
[
"yet.\") with open(peerLogFile, \"a\") as f: print(str(data)) f.write(str(data) + \"\\n\") f.close() send_response() def",
"handler_class=Server): print(\"Start server on port 8000.\") server_address = ('', 8000) httpd = server_class(server_address,",
"import sys class Server(BaseHTTPRequestHandler) : def _set_response(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() def do_POST(self):",
"= str(dataSplit[0]) count = str(dataSplit[-1]) peerLogFile = \"server-\"+peerId+\".log\" def send_response(): self.send_response(200) self.send_header(\"Content-type\", \"text/html\")",
"def do_POST(self): content_length = int(self.headers['Content-Length']) data = self.rfile.read(content_length).decode('utf-8') dataSplit = data.split(\" \") peerId",
"as f: lastEntry = f.readlines()[-1] lastId = str(lastEntry.split(\" \")[-1]) if int(lastId) > int(count):",
"print(str(data)) f.write(str(data) + \"\\n\") f.close() send_response() def stop_server(server): print(\"Stop server.\") server.server_close() sys.exit(0) def",
"return except (FileNotFoundError, IndexError): print(\"No server.log file available yet.\") with open(peerLogFile, \"a\") as",
"\"text/html\") self.end_headers() self.wfile.write((\"ACK \"+count).encode(\"utf-8\")) try: with open(peerLogFile, \"r\") as f: lastEntry = f.readlines()[-1]",
"self.end_headers() self.wfile.write((\"ACK \"+count).encode(\"utf-8\")) try: with open(peerLogFile, \"r\") as f: lastEntry = f.readlines()[-1] lastId",
"(FileNotFoundError, IndexError): print(\"No server.log file available yet.\") with open(peerLogFile, \"a\") as f: print(str(data))",
"= str(lastEntry.split(\" \")[-1]) if int(lastId) > int(count): send_response() return except (FileNotFoundError, IndexError): print(\"No",
": def _set_response(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() def do_POST(self): content_length = int(self.headers['Content-Length']) data",
"str(lastEntry.split(\" \")[-1]) if int(lastId) > int(count): send_response() return except (FileNotFoundError, IndexError): print(\"No server.log",
"as f: print(str(data)) f.write(str(data) + \"\\n\") f.close() send_response() def stop_server(server): print(\"Stop server.\") server.server_close()",
"'text/html') self.end_headers() def do_POST(self): content_length = int(self.headers['Content-Length']) data = self.rfile.read(content_length).decode('utf-8') dataSplit = data.split(\"",
"file available yet.\") with open(peerLogFile, \"a\") as f: print(str(data)) f.write(str(data) + \"\\n\") f.close()",
"= ('', 8000) httpd = server_class(server_address, handler_class) httpd.handle_request() try: httpd.serve_forever() except KeyboardInterrupt :",
"\"server-\"+peerId+\".log\" def send_response(): self.send_response(200) self.send_header(\"Content-type\", \"text/html\") self.end_headers() self.wfile.write((\"ACK \"+count).encode(\"utf-8\")) try: with open(peerLogFile, \"r\")",
"send_response(): self.send_response(200) self.send_header(\"Content-type\", \"text/html\") self.end_headers() self.wfile.write((\"ACK \"+count).encode(\"utf-8\")) try: with open(peerLogFile, \"r\") as f:",
"server.log file available yet.\") with open(peerLogFile, \"a\") as f: print(str(data)) f.write(str(data) + \"\\n\")",
"IndexError): print(\"No server.log file available yet.\") with open(peerLogFile, \"a\") as f: print(str(data)) f.write(str(data)",
"run(server_class=HTTPServer, handler_class=Server): print(\"Start server on port 8000.\") server_address = ('', 8000) httpd =",
"server_class(server_address, handler_class) httpd.handle_request() try: httpd.serve_forever() except KeyboardInterrupt : stop_server(httpd) if __name__ == \"__main__\":",
"httpd.handle_request() try: httpd.serve_forever() except KeyboardInterrupt : stop_server(httpd) if __name__ == \"__main__\": print(\"Create server\")",
"self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() def do_POST(self): content_length = int(self.headers['Content-Length']) data = self.rfile.read(content_length).decode('utf-8') dataSplit",
"= f.readlines()[-1] lastId = str(lastEntry.split(\" \")[-1]) if int(lastId) > int(count): send_response() return except",
"HTTPServer,BaseHTTPRequestHandler import signal import sys class Server(BaseHTTPRequestHandler) : def _set_response(self): self.send_response(200) self.send_header('Content-type', 'text/html')",
"sys class Server(BaseHTTPRequestHandler) : def _set_response(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() def do_POST(self): content_length",
"data = self.rfile.read(content_length).decode('utf-8') dataSplit = data.split(\" \") peerId = str(dataSplit[0]) count = str(dataSplit[-1])",
"8000) httpd = server_class(server_address, handler_class) httpd.handle_request() try: httpd.serve_forever() except KeyboardInterrupt : stop_server(httpd) if",
"except (FileNotFoundError, IndexError): print(\"No server.log file available yet.\") with open(peerLogFile, \"a\") as f:",
"data.split(\" \") peerId = str(dataSplit[0]) count = str(dataSplit[-1]) peerLogFile = \"server-\"+peerId+\".log\" def send_response():",
"self.send_response(200) self.send_header(\"Content-type\", \"text/html\") self.end_headers() self.wfile.write((\"ACK \"+count).encode(\"utf-8\")) try: with open(peerLogFile, \"r\") as f: lastEntry",
"peerLogFile = \"server-\"+peerId+\".log\" def send_response(): self.send_response(200) self.send_header(\"Content-type\", \"text/html\") self.end_headers() self.wfile.write((\"ACK \"+count).encode(\"utf-8\")) try: with",
"int(lastId) > int(count): send_response() return except (FileNotFoundError, IndexError): print(\"No server.log file available yet.\")",
"signal import sys class Server(BaseHTTPRequestHandler) : def _set_response(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() def",
"= str(dataSplit[-1]) peerLogFile = \"server-\"+peerId+\".log\" def send_response(): self.send_response(200) self.send_header(\"Content-type\", \"text/html\") self.end_headers() self.wfile.write((\"ACK \"+count).encode(\"utf-8\"))",
"httpd = server_class(server_address, handler_class) httpd.handle_request() try: httpd.serve_forever() except KeyboardInterrupt : stop_server(httpd) if __name__",
"def stop_server(server): print(\"Stop server.\") server.server_close() sys.exit(0) def run(server_class=HTTPServer, handler_class=Server): print(\"Start server on port",
"self.end_headers() def do_POST(self): content_length = int(self.headers['Content-Length']) data = self.rfile.read(content_length).decode('utf-8') dataSplit = data.split(\" \")",
"def _set_response(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() def do_POST(self): content_length = int(self.headers['Content-Length']) data =",
"do_POST(self): content_length = int(self.headers['Content-Length']) data = self.rfile.read(content_length).decode('utf-8') dataSplit = data.split(\" \") peerId =",
"+ \"\\n\") f.close() send_response() def stop_server(server): print(\"Stop server.\") server.server_close() sys.exit(0) def run(server_class=HTTPServer, handler_class=Server):",
"int(self.headers['Content-Length']) data = self.rfile.read(content_length).decode('utf-8') dataSplit = data.split(\" \") peerId = str(dataSplit[0]) count =",
"lastEntry = f.readlines()[-1] lastId = str(lastEntry.split(\" \")[-1]) if int(lastId) > int(count): send_response() return",
"server.\") server.server_close() sys.exit(0) def run(server_class=HTTPServer, handler_class=Server): print(\"Start server on port 8000.\") server_address =",
"f: print(str(data)) f.write(str(data) + \"\\n\") f.close() send_response() def stop_server(server): print(\"Stop server.\") server.server_close() sys.exit(0)",
"f: lastEntry = f.readlines()[-1] lastId = str(lastEntry.split(\" \")[-1]) if int(lastId) > int(count): send_response()",
"with open(peerLogFile, \"a\") as f: print(str(data)) f.write(str(data) + \"\\n\") f.close() send_response() def stop_server(server):",
"http.server import HTTPServer,BaseHTTPRequestHandler import signal import sys class Server(BaseHTTPRequestHandler) : def _set_response(self): self.send_response(200)",
"import signal import sys class Server(BaseHTTPRequestHandler) : def _set_response(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers()",
"= data.split(\" \") peerId = str(dataSplit[0]) count = str(dataSplit[-1]) peerLogFile = \"server-\"+peerId+\".log\" def",
"handler_class) httpd.handle_request() try: httpd.serve_forever() except KeyboardInterrupt : stop_server(httpd) if __name__ == \"__main__\": print(\"Create",
"self.send_header('Content-type', 'text/html') self.end_headers() def do_POST(self): content_length = int(self.headers['Content-Length']) data = self.rfile.read(content_length).decode('utf-8') dataSplit =",
"content_length = int(self.headers['Content-Length']) data = self.rfile.read(content_length).decode('utf-8') dataSplit = data.split(\" \") peerId = str(dataSplit[0])",
"str(dataSplit[0]) count = str(dataSplit[-1]) peerLogFile = \"server-\"+peerId+\".log\" def send_response(): self.send_response(200) self.send_header(\"Content-type\", \"text/html\") self.end_headers()",
"def run(server_class=HTTPServer, handler_class=Server): print(\"Start server on port 8000.\") server_address = ('', 8000) httpd",
"send_response() def stop_server(server): print(\"Stop server.\") server.server_close() sys.exit(0) def run(server_class=HTTPServer, handler_class=Server): print(\"Start server on",
"try: with open(peerLogFile, \"r\") as f: lastEntry = f.readlines()[-1] lastId = str(lastEntry.split(\" \")[-1])",
"import HTTPServer,BaseHTTPRequestHandler import signal import sys class Server(BaseHTTPRequestHandler) : def _set_response(self): self.send_response(200) self.send_header('Content-type',",
"print(\"Stop server.\") server.server_close() sys.exit(0) def run(server_class=HTTPServer, handler_class=Server): print(\"Start server on port 8000.\") server_address",
"try: httpd.serve_forever() except KeyboardInterrupt : stop_server(httpd) if __name__ == \"__main__\": print(\"Create server\") run()",
"open(peerLogFile, \"r\") as f: lastEntry = f.readlines()[-1] lastId = str(lastEntry.split(\" \")[-1]) if int(lastId)",
"def send_response(): self.send_response(200) self.send_header(\"Content-type\", \"text/html\") self.end_headers() self.wfile.write((\"ACK \"+count).encode(\"utf-8\")) try: with open(peerLogFile, \"r\") as",
"\")[-1]) if int(lastId) > int(count): send_response() return except (FileNotFoundError, IndexError): print(\"No server.log file",
"\"r\") as f: lastEntry = f.readlines()[-1] lastId = str(lastEntry.split(\" \")[-1]) if int(lastId) >",
"open(peerLogFile, \"a\") as f: print(str(data)) f.write(str(data) + \"\\n\") f.close() send_response() def stop_server(server): print(\"Stop",
"available yet.\") with open(peerLogFile, \"a\") as f: print(str(data)) f.write(str(data) + \"\\n\") f.close() send_response()",
"print(\"Start server on port 8000.\") server_address = ('', 8000) httpd = server_class(server_address, handler_class)",
"\") peerId = str(dataSplit[0]) count = str(dataSplit[-1]) peerLogFile = \"server-\"+peerId+\".log\" def send_response(): self.send_response(200)",
"count = str(dataSplit[-1]) peerLogFile = \"server-\"+peerId+\".log\" def send_response(): self.send_response(200) self.send_header(\"Content-type\", \"text/html\") self.end_headers() self.wfile.write((\"ACK",
"from http.server import HTTPServer,BaseHTTPRequestHandler import signal import sys class Server(BaseHTTPRequestHandler) : def _set_response(self):",
"= int(self.headers['Content-Length']) data = self.rfile.read(content_length).decode('utf-8') dataSplit = data.split(\" \") peerId = str(dataSplit[0]) count",
"send_response() return except (FileNotFoundError, IndexError): print(\"No server.log file available yet.\") with open(peerLogFile, \"a\")",
"> int(count): send_response() return except (FileNotFoundError, IndexError): print(\"No server.log file available yet.\") with",
"_set_response(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() def do_POST(self): content_length = int(self.headers['Content-Length']) data = self.rfile.read(content_length).decode('utf-8')",
"lastId = str(lastEntry.split(\" \")[-1]) if int(lastId) > int(count): send_response() return except (FileNotFoundError, IndexError):",
"server_address = ('', 8000) httpd = server_class(server_address, handler_class) httpd.handle_request() try: httpd.serve_forever() except KeyboardInterrupt",
"f.write(str(data) + \"\\n\") f.close() send_response() def stop_server(server): print(\"Stop server.\") server.server_close() sys.exit(0) def run(server_class=HTTPServer,",
"sys.exit(0) def run(server_class=HTTPServer, handler_class=Server): print(\"Start server on port 8000.\") server_address = ('', 8000)",
"if int(lastId) > int(count): send_response() return except (FileNotFoundError, IndexError): print(\"No server.log file available",
"int(count): send_response() return except (FileNotFoundError, IndexError): print(\"No server.log file available yet.\") with open(peerLogFile,",
"\"+count).encode(\"utf-8\")) try: with open(peerLogFile, \"r\") as f: lastEntry = f.readlines()[-1] lastId = str(lastEntry.split(\"",
"self.send_header(\"Content-type\", \"text/html\") self.end_headers() self.wfile.write((\"ACK \"+count).encode(\"utf-8\")) try: with open(peerLogFile, \"r\") as f: lastEntry =",
"on port 8000.\") server_address = ('', 8000) httpd = server_class(server_address, handler_class) httpd.handle_request() try:",
"with open(peerLogFile, \"r\") as f: lastEntry = f.readlines()[-1] lastId = str(lastEntry.split(\" \")[-1]) if",
"f.readlines()[-1] lastId = str(lastEntry.split(\" \")[-1]) if int(lastId) > int(count): send_response() return except (FileNotFoundError,",
"stop_server(server): print(\"Stop server.\") server.server_close() sys.exit(0) def run(server_class=HTTPServer, handler_class=Server): print(\"Start server on port 8000.\")",
"= \"server-\"+peerId+\".log\" def send_response(): self.send_response(200) self.send_header(\"Content-type\", \"text/html\") self.end_headers() self.wfile.write((\"ACK \"+count).encode(\"utf-8\")) try: with open(peerLogFile,",
"peerId = str(dataSplit[0]) count = str(dataSplit[-1]) peerLogFile = \"server-\"+peerId+\".log\" def send_response(): self.send_response(200) self.send_header(\"Content-type\",",
"Server(BaseHTTPRequestHandler) : def _set_response(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() def do_POST(self): content_length = int(self.headers['Content-Length'])",
"\"a\") as f: print(str(data)) f.write(str(data) + \"\\n\") f.close() send_response() def stop_server(server): print(\"Stop server.\")",
"\"\\n\") f.close() send_response() def stop_server(server): print(\"Stop server.\") server.server_close() sys.exit(0) def run(server_class=HTTPServer, handler_class=Server): print(\"Start",
"8000.\") server_address = ('', 8000) httpd = server_class(server_address, handler_class) httpd.handle_request() try: httpd.serve_forever() except",
"server.server_close() sys.exit(0) def run(server_class=HTTPServer, handler_class=Server): print(\"Start server on port 8000.\") server_address = ('',",
"port 8000.\") server_address = ('', 8000) httpd = server_class(server_address, handler_class) httpd.handle_request() try: httpd.serve_forever()",
"class Server(BaseHTTPRequestHandler) : def _set_response(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() def do_POST(self): content_length =",
"str(dataSplit[-1]) peerLogFile = \"server-\"+peerId+\".log\" def send_response(): self.send_response(200) self.send_header(\"Content-type\", \"text/html\") self.end_headers() self.wfile.write((\"ACK \"+count).encode(\"utf-8\")) try:",
"f.close() send_response() def stop_server(server): print(\"Stop server.\") server.server_close() sys.exit(0) def run(server_class=HTTPServer, handler_class=Server): print(\"Start server",
"self.wfile.write((\"ACK \"+count).encode(\"utf-8\")) try: with open(peerLogFile, \"r\") as f: lastEntry = f.readlines()[-1] lastId =",
"self.rfile.read(content_length).decode('utf-8') dataSplit = data.split(\" \") peerId = str(dataSplit[0]) count = str(dataSplit[-1]) peerLogFile =",
"server on port 8000.\") server_address = ('', 8000) httpd = server_class(server_address, handler_class) httpd.handle_request()",
"('', 8000) httpd = server_class(server_address, handler_class) httpd.handle_request() try: httpd.serve_forever() except KeyboardInterrupt : stop_server(httpd)",
"print(\"No server.log file available yet.\") with open(peerLogFile, \"a\") as f: print(str(data)) f.write(str(data) +",
"dataSplit = data.split(\" \") peerId = str(dataSplit[0]) count = str(dataSplit[-1]) peerLogFile = \"server-\"+peerId+\".log\"",
"= self.rfile.read(content_length).decode('utf-8') dataSplit = data.split(\" \") peerId = str(dataSplit[0]) count = str(dataSplit[-1]) peerLogFile",
"= server_class(server_address, handler_class) httpd.handle_request() try: httpd.serve_forever() except KeyboardInterrupt : stop_server(httpd) if __name__ =="
] |
[
"if obj.image: return obj.image return 'https://image.flaticon.com/icons/svg/1738/1738691.svg' def get_following(self,instance): request = self.context.get('request',None) if request",
"image = serializers.SerializerMethodField() following = serializers.SerializerMethodField() class Meta: model = Profile fields =",
"return 'https://image.flaticon.com/icons/svg/1738/1738691.svg' def get_following(self,instance): request = self.context.get('request',None) if request is None: return False",
"get_image(self,obj): if obj.image: return obj.image return 'https://image.flaticon.com/icons/svg/1738/1738691.svg' def get_following(self,instance): request = self.context.get('request',None) if",
"get_following(self,instance): request = self.context.get('request',None) if request is None: return False if not request.user.is_authenticated:",
"request is None: return False if not request.user.is_authenticated: return False follower = request.user.profile",
"return False if not request.user.is_authenticated: return False follower = request.user.profile followee = instance",
"fields = ('last_name','bio','image','following')#,'work_domain') read_only_fields = ('last_name',) def get_image(self,obj): if obj.image: return obj.image return",
"'https://image.flaticon.com/icons/svg/1738/1738691.svg' def get_following(self,instance): request = self.context.get('request',None) if request is None: return False if",
"from rest_framework import serializers from .models import Profile class ProfileSerializer(serializers.ModelSerializer): last_name = serializers.CharField(source='user.last_name')",
".models import Profile class ProfileSerializer(serializers.ModelSerializer): last_name = serializers.CharField(source='user.last_name') bio = serializers.CharField(allow_blank=True,required=False) #work_domain =",
"False if not request.user.is_authenticated: return False follower = request.user.profile followee = instance return",
"= serializers.CharField(max_length=50) image = serializers.SerializerMethodField() following = serializers.SerializerMethodField() class Meta: model = Profile",
"obj.image: return obj.image return 'https://image.flaticon.com/icons/svg/1738/1738691.svg' def get_following(self,instance): request = self.context.get('request',None) if request is",
"is None: return False if not request.user.is_authenticated: return False follower = request.user.profile followee",
"#work_domain = serializers.CharField(max_length=50) image = serializers.SerializerMethodField() following = serializers.SerializerMethodField() class Meta: model =",
"= self.context.get('request',None) if request is None: return False if not request.user.is_authenticated: return False",
"self.context.get('request',None) if request is None: return False if not request.user.is_authenticated: return False follower",
"from .models import Profile class ProfileSerializer(serializers.ModelSerializer): last_name = serializers.CharField(source='user.last_name') bio = serializers.CharField(allow_blank=True,required=False) #work_domain",
"last_name = serializers.CharField(source='user.last_name') bio = serializers.CharField(allow_blank=True,required=False) #work_domain = serializers.CharField(max_length=50) image = serializers.SerializerMethodField() following",
"= ('last_name',) def get_image(self,obj): if obj.image: return obj.image return 'https://image.flaticon.com/icons/svg/1738/1738691.svg' def get_following(self,instance): request",
"if request is None: return False if not request.user.is_authenticated: return False follower =",
"serializers.SerializerMethodField() class Meta: model = Profile fields = ('last_name','bio','image','following')#,'work_domain') read_only_fields = ('last_name',) def",
"serializers.CharField(source='user.last_name') bio = serializers.CharField(allow_blank=True,required=False) #work_domain = serializers.CharField(max_length=50) image = serializers.SerializerMethodField() following = serializers.SerializerMethodField()",
"serializers from .models import Profile class ProfileSerializer(serializers.ModelSerializer): last_name = serializers.CharField(source='user.last_name') bio = serializers.CharField(allow_blank=True,required=False)",
"Profile class ProfileSerializer(serializers.ModelSerializer): last_name = serializers.CharField(source='user.last_name') bio = serializers.CharField(allow_blank=True,required=False) #work_domain = serializers.CharField(max_length=50) image",
"rest_framework import serializers from .models import Profile class ProfileSerializer(serializers.ModelSerializer): last_name = serializers.CharField(source='user.last_name') bio",
"Meta: model = Profile fields = ('last_name','bio','image','following')#,'work_domain') read_only_fields = ('last_name',) def get_image(self,obj): if",
"following = serializers.SerializerMethodField() class Meta: model = Profile fields = ('last_name','bio','image','following')#,'work_domain') read_only_fields =",
"model = Profile fields = ('last_name','bio','image','following')#,'work_domain') read_only_fields = ('last_name',) def get_image(self,obj): if obj.image:",
"('last_name','bio','image','following')#,'work_domain') read_only_fields = ('last_name',) def get_image(self,obj): if obj.image: return obj.image return 'https://image.flaticon.com/icons/svg/1738/1738691.svg' def",
"('last_name',) def get_image(self,obj): if obj.image: return obj.image return 'https://image.flaticon.com/icons/svg/1738/1738691.svg' def get_following(self,instance): request =",
"= serializers.SerializerMethodField() following = serializers.SerializerMethodField() class Meta: model = Profile fields = ('last_name','bio','image','following')#,'work_domain')",
"import serializers from .models import Profile class ProfileSerializer(serializers.ModelSerializer): last_name = serializers.CharField(source='user.last_name') bio =",
"= serializers.CharField(allow_blank=True,required=False) #work_domain = serializers.CharField(max_length=50) image = serializers.SerializerMethodField() following = serializers.SerializerMethodField() class Meta:",
"bio = serializers.CharField(allow_blank=True,required=False) #work_domain = serializers.CharField(max_length=50) image = serializers.SerializerMethodField() following = serializers.SerializerMethodField() class",
"import Profile class ProfileSerializer(serializers.ModelSerializer): last_name = serializers.CharField(source='user.last_name') bio = serializers.CharField(allow_blank=True,required=False) #work_domain = serializers.CharField(max_length=50)",
"class Meta: model = Profile fields = ('last_name','bio','image','following')#,'work_domain') read_only_fields = ('last_name',) def get_image(self,obj):",
"= ('last_name','bio','image','following')#,'work_domain') read_only_fields = ('last_name',) def get_image(self,obj): if obj.image: return obj.image return 'https://image.flaticon.com/icons/svg/1738/1738691.svg'",
"request = self.context.get('request',None) if request is None: return False if not request.user.is_authenticated: return",
"obj.image return 'https://image.flaticon.com/icons/svg/1738/1738691.svg' def get_following(self,instance): request = self.context.get('request',None) if request is None: return",
"= serializers.CharField(source='user.last_name') bio = serializers.CharField(allow_blank=True,required=False) #work_domain = serializers.CharField(max_length=50) image = serializers.SerializerMethodField() following =",
"serializers.CharField(max_length=50) image = serializers.SerializerMethodField() following = serializers.SerializerMethodField() class Meta: model = Profile fields",
"= serializers.SerializerMethodField() class Meta: model = Profile fields = ('last_name','bio','image','following')#,'work_domain') read_only_fields = ('last_name',)",
"return obj.image return 'https://image.flaticon.com/icons/svg/1738/1738691.svg' def get_following(self,instance): request = self.context.get('request',None) if request is None:",
"Profile fields = ('last_name','bio','image','following')#,'work_domain') read_only_fields = ('last_name',) def get_image(self,obj): if obj.image: return obj.image",
"serializers.SerializerMethodField() following = serializers.SerializerMethodField() class Meta: model = Profile fields = ('last_name','bio','image','following')#,'work_domain') read_only_fields",
"ProfileSerializer(serializers.ModelSerializer): last_name = serializers.CharField(source='user.last_name') bio = serializers.CharField(allow_blank=True,required=False) #work_domain = serializers.CharField(max_length=50) image = serializers.SerializerMethodField()",
"read_only_fields = ('last_name',) def get_image(self,obj): if obj.image: return obj.image return 'https://image.flaticon.com/icons/svg/1738/1738691.svg' def get_following(self,instance):",
"= Profile fields = ('last_name','bio','image','following')#,'work_domain') read_only_fields = ('last_name',) def get_image(self,obj): if obj.image: return",
"def get_following(self,instance): request = self.context.get('request',None) if request is None: return False if not",
"serializers.CharField(allow_blank=True,required=False) #work_domain = serializers.CharField(max_length=50) image = serializers.SerializerMethodField() following = serializers.SerializerMethodField() class Meta: model",
"None: return False if not request.user.is_authenticated: return False follower = request.user.profile followee =",
"if not request.user.is_authenticated: return False follower = request.user.profile followee = instance return follower.is_following(followee)",
"class ProfileSerializer(serializers.ModelSerializer): last_name = serializers.CharField(source='user.last_name') bio = serializers.CharField(allow_blank=True,required=False) #work_domain = serializers.CharField(max_length=50) image =",
"def get_image(self,obj): if obj.image: return obj.image return 'https://image.flaticon.com/icons/svg/1738/1738691.svg' def get_following(self,instance): request = self.context.get('request',None)"
] |
[
"NA_Fiora_Mid_Karma(Ratings): pass class NA_Fiora_Mid_Karthus(Ratings): pass class NA_Fiora_Mid_Kassadin(Ratings): pass class NA_Fiora_Mid_Katarina(Ratings): pass class NA_Fiora_Mid_Kayle(Ratings):",
"NA_Fiora_Mid_Akali(Ratings): pass class NA_Fiora_Mid_Alistar(Ratings): pass class NA_Fiora_Mid_Amumu(Ratings): pass class NA_Fiora_Mid_Anivia(Ratings): pass class NA_Fiora_Mid_Annie(Ratings):",
"NA_Fiora_Mid_Irelia(Ratings): pass class NA_Fiora_Mid_Ivern(Ratings): pass class NA_Fiora_Mid_Janna(Ratings): pass class NA_Fiora_Mid_JarvanIV(Ratings): pass class NA_Fiora_Mid_Jax(Ratings):",
"pass class NA_Fiora_Mid_Gragas(Ratings): pass class NA_Fiora_Mid_Graves(Ratings): pass class NA_Fiora_Mid_Hecarim(Ratings): pass class NA_Fiora_Mid_Heimerdinger(Ratings): pass",
"pass class NA_Fiora_Mid_Ezreal(Ratings): pass class NA_Fiora_Mid_Fiddlesticks(Ratings): pass class NA_Fiora_Mid_Fiora(Ratings): pass class NA_Fiora_Mid_Fizz(Ratings): pass",
"NA_Fiora_Mid_Skarner(Ratings): pass class NA_Fiora_Mid_Sona(Ratings): pass class NA_Fiora_Mid_Soraka(Ratings): pass class NA_Fiora_Mid_Swain(Ratings): pass class NA_Fiora_Mid_Syndra(Ratings):",
"class NA_Fiora_Mid_Camille(Ratings): pass class NA_Fiora_Mid_Cassiopeia(Ratings): pass class NA_Fiora_Mid_Chogath(Ratings): pass class NA_Fiora_Mid_Corki(Ratings): pass class",
"class NA_Fiora_Mid_Xayah(Ratings): pass class NA_Fiora_Mid_Xerath(Ratings): pass class NA_Fiora_Mid_XinZhao(Ratings): pass class NA_Fiora_Mid_Yasuo(Ratings): pass class",
"class NA_Fiora_Mid_Caitlyn(Ratings): pass class NA_Fiora_Mid_Camille(Ratings): pass class NA_Fiora_Mid_Cassiopeia(Ratings): pass class NA_Fiora_Mid_Chogath(Ratings): pass class",
"NA_Fiora_Mid_Shyvana(Ratings): pass class NA_Fiora_Mid_Singed(Ratings): pass class NA_Fiora_Mid_Sion(Ratings): pass class NA_Fiora_Mid_Sivir(Ratings): pass class NA_Fiora_Mid_Skarner(Ratings):",
"class NA_Fiora_Mid_Anivia(Ratings): pass class NA_Fiora_Mid_Annie(Ratings): pass class NA_Fiora_Mid_Ashe(Ratings): pass class NA_Fiora_Mid_AurelionSol(Ratings): pass class",
"class NA_Fiora_Mid_Chogath(Ratings): pass class NA_Fiora_Mid_Corki(Ratings): pass class NA_Fiora_Mid_Darius(Ratings): pass class NA_Fiora_Mid_Diana(Ratings): pass class",
"NA_Fiora_Mid_Poppy(Ratings): pass class NA_Fiora_Mid_Quinn(Ratings): pass class NA_Fiora_Mid_Rakan(Ratings): pass class NA_Fiora_Mid_Rammus(Ratings): pass class NA_Fiora_Mid_RekSai(Ratings):",
"class NA_Fiora_Mid_Shaco(Ratings): pass class NA_Fiora_Mid_Shen(Ratings): pass class NA_Fiora_Mid_Shyvana(Ratings): pass class NA_Fiora_Mid_Singed(Ratings): pass class",
"class NA_Fiora_Mid_LeeSin(Ratings): pass class NA_Fiora_Mid_Leona(Ratings): pass class NA_Fiora_Mid_Lissandra(Ratings): pass class NA_Fiora_Mid_Lucian(Ratings): pass class",
"class NA_Fiora_Mid_Brand(Ratings): pass class NA_Fiora_Mid_Braum(Ratings): pass class NA_Fiora_Mid_Caitlyn(Ratings): pass class NA_Fiora_Mid_Camille(Ratings): pass class",
"pass class NA_Fiora_Mid_Kennen(Ratings): pass class NA_Fiora_Mid_Khazix(Ratings): pass class NA_Fiora_Mid_Kindred(Ratings): pass class NA_Fiora_Mid_Kled(Ratings): pass",
"NA_Fiora_Mid_Tryndamere(Ratings): pass class NA_Fiora_Mid_TwistedFate(Ratings): pass class NA_Fiora_Mid_Twitch(Ratings): pass class NA_Fiora_Mid_Udyr(Ratings): pass class NA_Fiora_Mid_Urgot(Ratings):",
"pass class NA_Fiora_Mid_Nasus(Ratings): pass class NA_Fiora_Mid_Nautilus(Ratings): pass class NA_Fiora_Mid_Nidalee(Ratings): pass class NA_Fiora_Mid_Nocturne(Ratings): pass",
"class NA_Fiora_Mid_Jayce(Ratings): pass class NA_Fiora_Mid_Jhin(Ratings): pass class NA_Fiora_Mid_Jinx(Ratings): pass class NA_Fiora_Mid_Kalista(Ratings): pass class",
"NA_Fiora_Mid_MonkeyKing(Ratings): pass class NA_Fiora_Mid_Mordekaiser(Ratings): pass class NA_Fiora_Mid_Morgana(Ratings): pass class NA_Fiora_Mid_Nami(Ratings): pass class NA_Fiora_Mid_Nasus(Ratings):",
"class NA_Fiora_Mid_Rakan(Ratings): pass class NA_Fiora_Mid_Rammus(Ratings): pass class NA_Fiora_Mid_RekSai(Ratings): pass class NA_Fiora_Mid_Renekton(Ratings): pass class",
"class NA_Fiora_Mid_Zac(Ratings): pass class NA_Fiora_Mid_Zed(Ratings): pass class NA_Fiora_Mid_Ziggs(Ratings): pass class NA_Fiora_Mid_Zilean(Ratings): pass class",
"pass class NA_Fiora_Mid_Braum(Ratings): pass class NA_Fiora_Mid_Caitlyn(Ratings): pass class NA_Fiora_Mid_Camille(Ratings): pass class NA_Fiora_Mid_Cassiopeia(Ratings): pass",
"class NA_Fiora_Mid_Nocturne(Ratings): pass class NA_Fiora_Mid_Nunu(Ratings): pass class NA_Fiora_Mid_Olaf(Ratings): pass class NA_Fiora_Mid_Orianna(Ratings): pass class",
"class NA_Fiora_Mid_Khazix(Ratings): pass class NA_Fiora_Mid_Kindred(Ratings): pass class NA_Fiora_Mid_Kled(Ratings): pass class NA_Fiora_Mid_KogMaw(Ratings): pass class",
"class NA_Fiora_Mid_Singed(Ratings): pass class NA_Fiora_Mid_Sion(Ratings): pass class NA_Fiora_Mid_Sivir(Ratings): pass class NA_Fiora_Mid_Skarner(Ratings): pass class",
"pass class NA_Fiora_Mid_Quinn(Ratings): pass class NA_Fiora_Mid_Rakan(Ratings): pass class NA_Fiora_Mid_Rammus(Ratings): pass class NA_Fiora_Mid_RekSai(Ratings): pass",
"class NA_Fiora_Mid_DrMundo(Ratings): pass class NA_Fiora_Mid_Ekko(Ratings): pass class NA_Fiora_Mid_Elise(Ratings): pass class NA_Fiora_Mid_Evelynn(Ratings): pass class",
"NA_Fiora_Mid_Cassiopeia(Ratings): pass class NA_Fiora_Mid_Chogath(Ratings): pass class NA_Fiora_Mid_Corki(Ratings): pass class NA_Fiora_Mid_Darius(Ratings): pass class NA_Fiora_Mid_Diana(Ratings):",
"class NA_Fiora_Mid_Taliyah(Ratings): pass class NA_Fiora_Mid_Talon(Ratings): pass class NA_Fiora_Mid_Taric(Ratings): pass class NA_Fiora_Mid_Teemo(Ratings): pass class",
"pass class NA_Fiora_Mid_Vayne(Ratings): pass class NA_Fiora_Mid_Veigar(Ratings): pass class NA_Fiora_Mid_Velkoz(Ratings): pass class NA_Fiora_Mid_Vi(Ratings): pass",
"pass class NA_Fiora_Mid_Corki(Ratings): pass class NA_Fiora_Mid_Darius(Ratings): pass class NA_Fiora_Mid_Diana(Ratings): pass class NA_Fiora_Mid_Draven(Ratings): pass",
"NA_Fiora_Mid_Nocturne(Ratings): pass class NA_Fiora_Mid_Nunu(Ratings): pass class NA_Fiora_Mid_Olaf(Ratings): pass class NA_Fiora_Mid_Orianna(Ratings): pass class NA_Fiora_Mid_Ornn(Ratings):",
"class NA_Fiora_Mid_Fizz(Ratings): pass class NA_Fiora_Mid_Galio(Ratings): pass class NA_Fiora_Mid_Gangplank(Ratings): pass class NA_Fiora_Mid_Garen(Ratings): pass class",
"NA_Fiora_Mid_Kayle(Ratings): pass class NA_Fiora_Mid_Kayn(Ratings): pass class NA_Fiora_Mid_Kennen(Ratings): pass class NA_Fiora_Mid_Khazix(Ratings): pass class NA_Fiora_Mid_Kindred(Ratings):",
"pass class NA_Fiora_Mid_Nidalee(Ratings): pass class NA_Fiora_Mid_Nocturne(Ratings): pass class NA_Fiora_Mid_Nunu(Ratings): pass class NA_Fiora_Mid_Olaf(Ratings): pass",
"NA_Fiora_Mid_Kalista(Ratings): pass class NA_Fiora_Mid_Karma(Ratings): pass class NA_Fiora_Mid_Karthus(Ratings): pass class NA_Fiora_Mid_Kassadin(Ratings): pass class NA_Fiora_Mid_Katarina(Ratings):",
"class NA_Fiora_Mid_Volibear(Ratings): pass class NA_Fiora_Mid_Warwick(Ratings): pass class NA_Fiora_Mid_Xayah(Ratings): pass class NA_Fiora_Mid_Xerath(Ratings): pass class",
"pass class NA_Fiora_Mid_Soraka(Ratings): pass class NA_Fiora_Mid_Swain(Ratings): pass class NA_Fiora_Mid_Syndra(Ratings): pass class NA_Fiora_Mid_TahmKench(Ratings): pass",
"pass class NA_Fiora_Mid_Singed(Ratings): pass class NA_Fiora_Mid_Sion(Ratings): pass class NA_Fiora_Mid_Sivir(Ratings): pass class NA_Fiora_Mid_Skarner(Ratings): pass",
"pass class NA_Fiora_Mid_Riven(Ratings): pass class NA_Fiora_Mid_Rumble(Ratings): pass class NA_Fiora_Mid_Ryze(Ratings): pass class NA_Fiora_Mid_Sejuani(Ratings): pass",
"pass class NA_Fiora_Mid_Rengar(Ratings): pass class NA_Fiora_Mid_Riven(Ratings): pass class NA_Fiora_Mid_Rumble(Ratings): pass class NA_Fiora_Mid_Ryze(Ratings): pass",
"NA_Fiora_Mid_Quinn(Ratings): pass class NA_Fiora_Mid_Rakan(Ratings): pass class NA_Fiora_Mid_Rammus(Ratings): pass class NA_Fiora_Mid_RekSai(Ratings): pass class NA_Fiora_Mid_Renekton(Ratings):",
"pass class NA_Fiora_Mid_Camille(Ratings): pass class NA_Fiora_Mid_Cassiopeia(Ratings): pass class NA_Fiora_Mid_Chogath(Ratings): pass class NA_Fiora_Mid_Corki(Ratings): pass",
"pass class NA_Fiora_Mid_Renekton(Ratings): pass class NA_Fiora_Mid_Rengar(Ratings): pass class NA_Fiora_Mid_Riven(Ratings): pass class NA_Fiora_Mid_Rumble(Ratings): pass",
"class NA_Fiora_Mid_MasterYi(Ratings): pass class NA_Fiora_Mid_MissFortune(Ratings): pass class NA_Fiora_Mid_MonkeyKing(Ratings): pass class NA_Fiora_Mid_Mordekaiser(Ratings): pass class",
"pass class NA_Fiora_Mid_Blitzcrank(Ratings): pass class NA_Fiora_Mid_Brand(Ratings): pass class NA_Fiora_Mid_Braum(Ratings): pass class NA_Fiora_Mid_Caitlyn(Ratings): pass",
"NA_Fiora_Mid_Malzahar(Ratings): pass class NA_Fiora_Mid_Maokai(Ratings): pass class NA_Fiora_Mid_MasterYi(Ratings): pass class NA_Fiora_Mid_MissFortune(Ratings): pass class NA_Fiora_Mid_MonkeyKing(Ratings):",
"class NA_Fiora_Mid_Teemo(Ratings): pass class NA_Fiora_Mid_Thresh(Ratings): pass class NA_Fiora_Mid_Tristana(Ratings): pass class NA_Fiora_Mid_Trundle(Ratings): pass class",
"class NA_Fiora_Mid_Twitch(Ratings): pass class NA_Fiora_Mid_Udyr(Ratings): pass class NA_Fiora_Mid_Urgot(Ratings): pass class NA_Fiora_Mid_Varus(Ratings): pass class",
"pass class NA_Fiora_Mid_Varus(Ratings): pass class NA_Fiora_Mid_Vayne(Ratings): pass class NA_Fiora_Mid_Veigar(Ratings): pass class NA_Fiora_Mid_Velkoz(Ratings): pass",
"NA_Fiora_Mid_Kindred(Ratings): pass class NA_Fiora_Mid_Kled(Ratings): pass class NA_Fiora_Mid_KogMaw(Ratings): pass class NA_Fiora_Mid_Leblanc(Ratings): pass class NA_Fiora_Mid_LeeSin(Ratings):",
"pass class NA_Fiora_Mid_Graves(Ratings): pass class NA_Fiora_Mid_Hecarim(Ratings): pass class NA_Fiora_Mid_Heimerdinger(Ratings): pass class NA_Fiora_Mid_Illaoi(Ratings): pass",
"pass class NA_Fiora_Mid_Morgana(Ratings): pass class NA_Fiora_Mid_Nami(Ratings): pass class NA_Fiora_Mid_Nasus(Ratings): pass class NA_Fiora_Mid_Nautilus(Ratings): pass",
"pass class NA_Fiora_Mid_Kassadin(Ratings): pass class NA_Fiora_Mid_Katarina(Ratings): pass class NA_Fiora_Mid_Kayle(Ratings): pass class NA_Fiora_Mid_Kayn(Ratings): pass",
"pass class NA_Fiora_Mid_Talon(Ratings): pass class NA_Fiora_Mid_Taric(Ratings): pass class NA_Fiora_Mid_Teemo(Ratings): pass class NA_Fiora_Mid_Thresh(Ratings): pass",
"class NA_Fiora_Mid_Skarner(Ratings): pass class NA_Fiora_Mid_Sona(Ratings): pass class NA_Fiora_Mid_Soraka(Ratings): pass class NA_Fiora_Mid_Swain(Ratings): pass class",
"class NA_Fiora_Mid_Kindred(Ratings): pass class NA_Fiora_Mid_Kled(Ratings): pass class NA_Fiora_Mid_KogMaw(Ratings): pass class NA_Fiora_Mid_Leblanc(Ratings): pass class",
"class NA_Fiora_Mid_Morgana(Ratings): pass class NA_Fiora_Mid_Nami(Ratings): pass class NA_Fiora_Mid_Nasus(Ratings): pass class NA_Fiora_Mid_Nautilus(Ratings): pass class",
"NA_Fiora_Mid_Blitzcrank(Ratings): pass class NA_Fiora_Mid_Brand(Ratings): pass class NA_Fiora_Mid_Braum(Ratings): pass class NA_Fiora_Mid_Caitlyn(Ratings): pass class NA_Fiora_Mid_Camille(Ratings):",
"pass class NA_Fiora_Mid_Shyvana(Ratings): pass class NA_Fiora_Mid_Singed(Ratings): pass class NA_Fiora_Mid_Sion(Ratings): pass class NA_Fiora_Mid_Sivir(Ratings): pass",
"class NA_Fiora_Mid_Rammus(Ratings): pass class NA_Fiora_Mid_RekSai(Ratings): pass class NA_Fiora_Mid_Renekton(Ratings): pass class NA_Fiora_Mid_Rengar(Ratings): pass class",
"class NA_Fiora_Mid_Mordekaiser(Ratings): pass class NA_Fiora_Mid_Morgana(Ratings): pass class NA_Fiora_Mid_Nami(Ratings): pass class NA_Fiora_Mid_Nasus(Ratings): pass class",
"class NA_Fiora_Mid_RekSai(Ratings): pass class NA_Fiora_Mid_Renekton(Ratings): pass class NA_Fiora_Mid_Rengar(Ratings): pass class NA_Fiora_Mid_Riven(Ratings): pass class",
"pass class NA_Fiora_Mid_Elise(Ratings): pass class NA_Fiora_Mid_Evelynn(Ratings): pass class NA_Fiora_Mid_Ezreal(Ratings): pass class NA_Fiora_Mid_Fiddlesticks(Ratings): pass",
"NA_Fiora_Mid_Nunu(Ratings): pass class NA_Fiora_Mid_Olaf(Ratings): pass class NA_Fiora_Mid_Orianna(Ratings): pass class NA_Fiora_Mid_Ornn(Ratings): pass class NA_Fiora_Mid_Pantheon(Ratings):",
"NA_Fiora_Mid_Vladimir(Ratings): pass class NA_Fiora_Mid_Volibear(Ratings): pass class NA_Fiora_Mid_Warwick(Ratings): pass class NA_Fiora_Mid_Xayah(Ratings): pass class NA_Fiora_Mid_Xerath(Ratings):",
"NA_Fiora_Mid_Aatrox(Ratings): pass class NA_Fiora_Mid_Ahri(Ratings): pass class NA_Fiora_Mid_Akali(Ratings): pass class NA_Fiora_Mid_Alistar(Ratings): pass class NA_Fiora_Mid_Amumu(Ratings):",
"class NA_Fiora_Mid_Irelia(Ratings): pass class NA_Fiora_Mid_Ivern(Ratings): pass class NA_Fiora_Mid_Janna(Ratings): pass class NA_Fiora_Mid_JarvanIV(Ratings): pass class",
"pass class NA_Fiora_Mid_Leblanc(Ratings): pass class NA_Fiora_Mid_LeeSin(Ratings): pass class NA_Fiora_Mid_Leona(Ratings): pass class NA_Fiora_Mid_Lissandra(Ratings): pass",
"class NA_Fiora_Mid_Malzahar(Ratings): pass class NA_Fiora_Mid_Maokai(Ratings): pass class NA_Fiora_Mid_MasterYi(Ratings): pass class NA_Fiora_Mid_MissFortune(Ratings): pass class",
"pass class NA_Fiora_Mid_Nocturne(Ratings): pass class NA_Fiora_Mid_Nunu(Ratings): pass class NA_Fiora_Mid_Olaf(Ratings): pass class NA_Fiora_Mid_Orianna(Ratings): pass",
"NA_Fiora_Mid_Velkoz(Ratings): pass class NA_Fiora_Mid_Vi(Ratings): pass class NA_Fiora_Mid_Viktor(Ratings): pass class NA_Fiora_Mid_Vladimir(Ratings): pass class NA_Fiora_Mid_Volibear(Ratings):",
"pass class NA_Fiora_Mid_KogMaw(Ratings): pass class NA_Fiora_Mid_Leblanc(Ratings): pass class NA_Fiora_Mid_LeeSin(Ratings): pass class NA_Fiora_Mid_Leona(Ratings): pass",
"class NA_Fiora_Mid_Shen(Ratings): pass class NA_Fiora_Mid_Shyvana(Ratings): pass class NA_Fiora_Mid_Singed(Ratings): pass class NA_Fiora_Mid_Sion(Ratings): pass class",
"pass class NA_Fiora_Mid_Darius(Ratings): pass class NA_Fiora_Mid_Diana(Ratings): pass class NA_Fiora_Mid_Draven(Ratings): pass class NA_Fiora_Mid_DrMundo(Ratings): pass",
"NA_Fiora_Mid_Katarina(Ratings): pass class NA_Fiora_Mid_Kayle(Ratings): pass class NA_Fiora_Mid_Kayn(Ratings): pass class NA_Fiora_Mid_Kennen(Ratings): pass class NA_Fiora_Mid_Khazix(Ratings):",
"NA_Fiora_Mid_Bard(Ratings): pass class NA_Fiora_Mid_Blitzcrank(Ratings): pass class NA_Fiora_Mid_Brand(Ratings): pass class NA_Fiora_Mid_Braum(Ratings): pass class NA_Fiora_Mid_Caitlyn(Ratings):",
"NA_Fiora_Mid_Shaco(Ratings): pass class NA_Fiora_Mid_Shen(Ratings): pass class NA_Fiora_Mid_Shyvana(Ratings): pass class NA_Fiora_Mid_Singed(Ratings): pass class NA_Fiora_Mid_Sion(Ratings):",
"class NA_Fiora_Mid_Fiora(Ratings): pass class NA_Fiora_Mid_Fizz(Ratings): pass class NA_Fiora_Mid_Galio(Ratings): pass class NA_Fiora_Mid_Gangplank(Ratings): pass class",
"NA_Fiora_Mid_Graves(Ratings): pass class NA_Fiora_Mid_Hecarim(Ratings): pass class NA_Fiora_Mid_Heimerdinger(Ratings): pass class NA_Fiora_Mid_Illaoi(Ratings): pass class NA_Fiora_Mid_Irelia(Ratings):",
"pass class NA_Fiora_Mid_MissFortune(Ratings): pass class NA_Fiora_Mid_MonkeyKing(Ratings): pass class NA_Fiora_Mid_Mordekaiser(Ratings): pass class NA_Fiora_Mid_Morgana(Ratings): pass",
"NA_Fiora_Mid_Nidalee(Ratings): pass class NA_Fiora_Mid_Nocturne(Ratings): pass class NA_Fiora_Mid_Nunu(Ratings): pass class NA_Fiora_Mid_Olaf(Ratings): pass class NA_Fiora_Mid_Orianna(Ratings):",
"class NA_Fiora_Mid_XinZhao(Ratings): pass class NA_Fiora_Mid_Yasuo(Ratings): pass class NA_Fiora_Mid_Yorick(Ratings): pass class NA_Fiora_Mid_Zac(Ratings): pass class",
"NA_Fiora_Mid_Orianna(Ratings): pass class NA_Fiora_Mid_Ornn(Ratings): pass class NA_Fiora_Mid_Pantheon(Ratings): pass class NA_Fiora_Mid_Poppy(Ratings): pass class NA_Fiora_Mid_Quinn(Ratings):",
"pass class NA_Fiora_Mid_Lucian(Ratings): pass class NA_Fiora_Mid_Lulu(Ratings): pass class NA_Fiora_Mid_Lux(Ratings): pass class NA_Fiora_Mid_Malphite(Ratings): pass",
"pass class NA_Fiora_Mid_Gangplank(Ratings): pass class NA_Fiora_Mid_Garen(Ratings): pass class NA_Fiora_Mid_Gnar(Ratings): pass class NA_Fiora_Mid_Gragas(Ratings): pass",
"class NA_Fiora_Mid_Kennen(Ratings): pass class NA_Fiora_Mid_Khazix(Ratings): pass class NA_Fiora_Mid_Kindred(Ratings): pass class NA_Fiora_Mid_Kled(Ratings): pass class",
"NA_Fiora_Mid_Ornn(Ratings): pass class NA_Fiora_Mid_Pantheon(Ratings): pass class NA_Fiora_Mid_Poppy(Ratings): pass class NA_Fiora_Mid_Quinn(Ratings): pass class NA_Fiora_Mid_Rakan(Ratings):",
"getratings.models.ratings import Ratings class NA_Fiora_Mid_Aatrox(Ratings): pass class NA_Fiora_Mid_Ahri(Ratings): pass class NA_Fiora_Mid_Akali(Ratings): pass class",
"class NA_Fiora_Mid_Vayne(Ratings): pass class NA_Fiora_Mid_Veigar(Ratings): pass class NA_Fiora_Mid_Velkoz(Ratings): pass class NA_Fiora_Mid_Vi(Ratings): pass class",
"pass class NA_Fiora_Mid_Swain(Ratings): pass class NA_Fiora_Mid_Syndra(Ratings): pass class NA_Fiora_Mid_TahmKench(Ratings): pass class NA_Fiora_Mid_Taliyah(Ratings): pass",
"pass class NA_Fiora_Mid_Azir(Ratings): pass class NA_Fiora_Mid_Bard(Ratings): pass class NA_Fiora_Mid_Blitzcrank(Ratings): pass class NA_Fiora_Mid_Brand(Ratings): pass",
"pass class NA_Fiora_Mid_Orianna(Ratings): pass class NA_Fiora_Mid_Ornn(Ratings): pass class NA_Fiora_Mid_Pantheon(Ratings): pass class NA_Fiora_Mid_Poppy(Ratings): pass",
"class NA_Fiora_Mid_MissFortune(Ratings): pass class NA_Fiora_Mid_MonkeyKing(Ratings): pass class NA_Fiora_Mid_Mordekaiser(Ratings): pass class NA_Fiora_Mid_Morgana(Ratings): pass class",
"NA_Fiora_Mid_Ezreal(Ratings): pass class NA_Fiora_Mid_Fiddlesticks(Ratings): pass class NA_Fiora_Mid_Fiora(Ratings): pass class NA_Fiora_Mid_Fizz(Ratings): pass class NA_Fiora_Mid_Galio(Ratings):",
"pass class NA_Fiora_Mid_Kled(Ratings): pass class NA_Fiora_Mid_KogMaw(Ratings): pass class NA_Fiora_Mid_Leblanc(Ratings): pass class NA_Fiora_Mid_LeeSin(Ratings): pass",
"pass class NA_Fiora_Mid_LeeSin(Ratings): pass class NA_Fiora_Mid_Leona(Ratings): pass class NA_Fiora_Mid_Lissandra(Ratings): pass class NA_Fiora_Mid_Lucian(Ratings): pass",
"pass class NA_Fiora_Mid_Volibear(Ratings): pass class NA_Fiora_Mid_Warwick(Ratings): pass class NA_Fiora_Mid_Xayah(Ratings): pass class NA_Fiora_Mid_Xerath(Ratings): pass",
"class NA_Fiora_Mid_Udyr(Ratings): pass class NA_Fiora_Mid_Urgot(Ratings): pass class NA_Fiora_Mid_Varus(Ratings): pass class NA_Fiora_Mid_Vayne(Ratings): pass class",
"class NA_Fiora_Mid_Lux(Ratings): pass class NA_Fiora_Mid_Malphite(Ratings): pass class NA_Fiora_Mid_Malzahar(Ratings): pass class NA_Fiora_Mid_Maokai(Ratings): pass class",
"NA_Fiora_Mid_Taric(Ratings): pass class NA_Fiora_Mid_Teemo(Ratings): pass class NA_Fiora_Mid_Thresh(Ratings): pass class NA_Fiora_Mid_Tristana(Ratings): pass class NA_Fiora_Mid_Trundle(Ratings):",
"class NA_Fiora_Mid_JarvanIV(Ratings): pass class NA_Fiora_Mid_Jax(Ratings): pass class NA_Fiora_Mid_Jayce(Ratings): pass class NA_Fiora_Mid_Jhin(Ratings): pass class",
"pass class NA_Fiora_Mid_Viktor(Ratings): pass class NA_Fiora_Mid_Vladimir(Ratings): pass class NA_Fiora_Mid_Volibear(Ratings): pass class NA_Fiora_Mid_Warwick(Ratings): pass",
"pass class NA_Fiora_Mid_Fiora(Ratings): pass class NA_Fiora_Mid_Fizz(Ratings): pass class NA_Fiora_Mid_Galio(Ratings): pass class NA_Fiora_Mid_Gangplank(Ratings): pass",
"NA_Fiora_Mid_MasterYi(Ratings): pass class NA_Fiora_Mid_MissFortune(Ratings): pass class NA_Fiora_Mid_MonkeyKing(Ratings): pass class NA_Fiora_Mid_Mordekaiser(Ratings): pass class NA_Fiora_Mid_Morgana(Ratings):",
"pass class NA_Fiora_Mid_RekSai(Ratings): pass class NA_Fiora_Mid_Renekton(Ratings): pass class NA_Fiora_Mid_Rengar(Ratings): pass class NA_Fiora_Mid_Riven(Ratings): pass",
"pass class NA_Fiora_Mid_Malzahar(Ratings): pass class NA_Fiora_Mid_Maokai(Ratings): pass class NA_Fiora_Mid_MasterYi(Ratings): pass class NA_Fiora_Mid_MissFortune(Ratings): pass",
"NA_Fiora_Mid_Sona(Ratings): pass class NA_Fiora_Mid_Soraka(Ratings): pass class NA_Fiora_Mid_Swain(Ratings): pass class NA_Fiora_Mid_Syndra(Ratings): pass class NA_Fiora_Mid_TahmKench(Ratings):",
"class NA_Fiora_Mid_Azir(Ratings): pass class NA_Fiora_Mid_Bard(Ratings): pass class NA_Fiora_Mid_Blitzcrank(Ratings): pass class NA_Fiora_Mid_Brand(Ratings): pass class",
"NA_Fiora_Mid_Syndra(Ratings): pass class NA_Fiora_Mid_TahmKench(Ratings): pass class NA_Fiora_Mid_Taliyah(Ratings): pass class NA_Fiora_Mid_Talon(Ratings): pass class NA_Fiora_Mid_Taric(Ratings):",
"pass class NA_Fiora_Mid_Tryndamere(Ratings): pass class NA_Fiora_Mid_TwistedFate(Ratings): pass class NA_Fiora_Mid_Twitch(Ratings): pass class NA_Fiora_Mid_Udyr(Ratings): pass",
"NA_Fiora_Mid_Galio(Ratings): pass class NA_Fiora_Mid_Gangplank(Ratings): pass class NA_Fiora_Mid_Garen(Ratings): pass class NA_Fiora_Mid_Gnar(Ratings): pass class NA_Fiora_Mid_Gragas(Ratings):",
"class NA_Fiora_Mid_Kassadin(Ratings): pass class NA_Fiora_Mid_Katarina(Ratings): pass class NA_Fiora_Mid_Kayle(Ratings): pass class NA_Fiora_Mid_Kayn(Ratings): pass class",
"NA_Fiora_Mid_Brand(Ratings): pass class NA_Fiora_Mid_Braum(Ratings): pass class NA_Fiora_Mid_Caitlyn(Ratings): pass class NA_Fiora_Mid_Camille(Ratings): pass class NA_Fiora_Mid_Cassiopeia(Ratings):",
"pass class NA_Fiora_Mid_MonkeyKing(Ratings): pass class NA_Fiora_Mid_Mordekaiser(Ratings): pass class NA_Fiora_Mid_Morgana(Ratings): pass class NA_Fiora_Mid_Nami(Ratings): pass",
"pass class NA_Fiora_Mid_Poppy(Ratings): pass class NA_Fiora_Mid_Quinn(Ratings): pass class NA_Fiora_Mid_Rakan(Ratings): pass class NA_Fiora_Mid_Rammus(Ratings): pass",
"class NA_Fiora_Mid_Garen(Ratings): pass class NA_Fiora_Mid_Gnar(Ratings): pass class NA_Fiora_Mid_Gragas(Ratings): pass class NA_Fiora_Mid_Graves(Ratings): pass class",
"pass class NA_Fiora_Mid_Zac(Ratings): pass class NA_Fiora_Mid_Zed(Ratings): pass class NA_Fiora_Mid_Ziggs(Ratings): pass class NA_Fiora_Mid_Zilean(Ratings): pass",
"pass class NA_Fiora_Mid_Karma(Ratings): pass class NA_Fiora_Mid_Karthus(Ratings): pass class NA_Fiora_Mid_Kassadin(Ratings): pass class NA_Fiora_Mid_Katarina(Ratings): pass",
"pass class NA_Fiora_Mid_Nami(Ratings): pass class NA_Fiora_Mid_Nasus(Ratings): pass class NA_Fiora_Mid_Nautilus(Ratings): pass class NA_Fiora_Mid_Nidalee(Ratings): pass",
"NA_Fiora_Mid_Morgana(Ratings): pass class NA_Fiora_Mid_Nami(Ratings): pass class NA_Fiora_Mid_Nasus(Ratings): pass class NA_Fiora_Mid_Nautilus(Ratings): pass class NA_Fiora_Mid_Nidalee(Ratings):",
"class NA_Fiora_Mid_Riven(Ratings): pass class NA_Fiora_Mid_Rumble(Ratings): pass class NA_Fiora_Mid_Ryze(Ratings): pass class NA_Fiora_Mid_Sejuani(Ratings): pass class",
"NA_Fiora_Mid_Nautilus(Ratings): pass class NA_Fiora_Mid_Nidalee(Ratings): pass class NA_Fiora_Mid_Nocturne(Ratings): pass class NA_Fiora_Mid_Nunu(Ratings): pass class NA_Fiora_Mid_Olaf(Ratings):",
"class NA_Fiora_Mid_Lucian(Ratings): pass class NA_Fiora_Mid_Lulu(Ratings): pass class NA_Fiora_Mid_Lux(Ratings): pass class NA_Fiora_Mid_Malphite(Ratings): pass class",
"NA_Fiora_Mid_Renekton(Ratings): pass class NA_Fiora_Mid_Rengar(Ratings): pass class NA_Fiora_Mid_Riven(Ratings): pass class NA_Fiora_Mid_Rumble(Ratings): pass class NA_Fiora_Mid_Ryze(Ratings):",
"NA_Fiora_Mid_Vi(Ratings): pass class NA_Fiora_Mid_Viktor(Ratings): pass class NA_Fiora_Mid_Vladimir(Ratings): pass class NA_Fiora_Mid_Volibear(Ratings): pass class NA_Fiora_Mid_Warwick(Ratings):",
"pass class NA_Fiora_Mid_Veigar(Ratings): pass class NA_Fiora_Mid_Velkoz(Ratings): pass class NA_Fiora_Mid_Vi(Ratings): pass class NA_Fiora_Mid_Viktor(Ratings): pass",
"class NA_Fiora_Mid_TahmKench(Ratings): pass class NA_Fiora_Mid_Taliyah(Ratings): pass class NA_Fiora_Mid_Talon(Ratings): pass class NA_Fiora_Mid_Taric(Ratings): pass class",
"class NA_Fiora_Mid_Nunu(Ratings): pass class NA_Fiora_Mid_Olaf(Ratings): pass class NA_Fiora_Mid_Orianna(Ratings): pass class NA_Fiora_Mid_Ornn(Ratings): pass class",
"pass class NA_Fiora_Mid_Skarner(Ratings): pass class NA_Fiora_Mid_Sona(Ratings): pass class NA_Fiora_Mid_Soraka(Ratings): pass class NA_Fiora_Mid_Swain(Ratings): pass",
"pass class NA_Fiora_Mid_Ryze(Ratings): pass class NA_Fiora_Mid_Sejuani(Ratings): pass class NA_Fiora_Mid_Shaco(Ratings): pass class NA_Fiora_Mid_Shen(Ratings): pass",
"class NA_Fiora_Mid_Pantheon(Ratings): pass class NA_Fiora_Mid_Poppy(Ratings): pass class NA_Fiora_Mid_Quinn(Ratings): pass class NA_Fiora_Mid_Rakan(Ratings): pass class",
"pass class NA_Fiora_Mid_Karthus(Ratings): pass class NA_Fiora_Mid_Kassadin(Ratings): pass class NA_Fiora_Mid_Katarina(Ratings): pass class NA_Fiora_Mid_Kayle(Ratings): pass",
"class NA_Fiora_Mid_Jinx(Ratings): pass class NA_Fiora_Mid_Kalista(Ratings): pass class NA_Fiora_Mid_Karma(Ratings): pass class NA_Fiora_Mid_Karthus(Ratings): pass class",
"pass class NA_Fiora_Mid_Ekko(Ratings): pass class NA_Fiora_Mid_Elise(Ratings): pass class NA_Fiora_Mid_Evelynn(Ratings): pass class NA_Fiora_Mid_Ezreal(Ratings): pass",
"NA_Fiora_Mid_Alistar(Ratings): pass class NA_Fiora_Mid_Amumu(Ratings): pass class NA_Fiora_Mid_Anivia(Ratings): pass class NA_Fiora_Mid_Annie(Ratings): pass class NA_Fiora_Mid_Ashe(Ratings):",
"class NA_Fiora_Mid_Trundle(Ratings): pass class NA_Fiora_Mid_Tryndamere(Ratings): pass class NA_Fiora_Mid_TwistedFate(Ratings): pass class NA_Fiora_Mid_Twitch(Ratings): pass class",
"pass class NA_Fiora_Mid_Udyr(Ratings): pass class NA_Fiora_Mid_Urgot(Ratings): pass class NA_Fiora_Mid_Varus(Ratings): pass class NA_Fiora_Mid_Vayne(Ratings): pass",
"NA_Fiora_Mid_Mordekaiser(Ratings): pass class NA_Fiora_Mid_Morgana(Ratings): pass class NA_Fiora_Mid_Nami(Ratings): pass class NA_Fiora_Mid_Nasus(Ratings): pass class NA_Fiora_Mid_Nautilus(Ratings):",
"NA_Fiora_Mid_Volibear(Ratings): pass class NA_Fiora_Mid_Warwick(Ratings): pass class NA_Fiora_Mid_Xayah(Ratings): pass class NA_Fiora_Mid_Xerath(Ratings): pass class NA_Fiora_Mid_XinZhao(Ratings):",
"pass class NA_Fiora_Mid_Janna(Ratings): pass class NA_Fiora_Mid_JarvanIV(Ratings): pass class NA_Fiora_Mid_Jax(Ratings): pass class NA_Fiora_Mid_Jayce(Ratings): pass",
"class NA_Fiora_Mid_Blitzcrank(Ratings): pass class NA_Fiora_Mid_Brand(Ratings): pass class NA_Fiora_Mid_Braum(Ratings): pass class NA_Fiora_Mid_Caitlyn(Ratings): pass class",
"pass class NA_Fiora_Mid_Sejuani(Ratings): pass class NA_Fiora_Mid_Shaco(Ratings): pass class NA_Fiora_Mid_Shen(Ratings): pass class NA_Fiora_Mid_Shyvana(Ratings): pass",
"NA_Fiora_Mid_Singed(Ratings): pass class NA_Fiora_Mid_Sion(Ratings): pass class NA_Fiora_Mid_Sivir(Ratings): pass class NA_Fiora_Mid_Skarner(Ratings): pass class NA_Fiora_Mid_Sona(Ratings):",
"pass class NA_Fiora_Mid_Annie(Ratings): pass class NA_Fiora_Mid_Ashe(Ratings): pass class NA_Fiora_Mid_AurelionSol(Ratings): pass class NA_Fiora_Mid_Azir(Ratings): pass",
"class NA_Fiora_Mid_Velkoz(Ratings): pass class NA_Fiora_Mid_Vi(Ratings): pass class NA_Fiora_Mid_Viktor(Ratings): pass class NA_Fiora_Mid_Vladimir(Ratings): pass class",
"NA_Fiora_Mid_LeeSin(Ratings): pass class NA_Fiora_Mid_Leona(Ratings): pass class NA_Fiora_Mid_Lissandra(Ratings): pass class NA_Fiora_Mid_Lucian(Ratings): pass class NA_Fiora_Mid_Lulu(Ratings):",
"class NA_Fiora_Mid_Alistar(Ratings): pass class NA_Fiora_Mid_Amumu(Ratings): pass class NA_Fiora_Mid_Anivia(Ratings): pass class NA_Fiora_Mid_Annie(Ratings): pass class",
"pass class NA_Fiora_Mid_Yasuo(Ratings): pass class NA_Fiora_Mid_Yorick(Ratings): pass class NA_Fiora_Mid_Zac(Ratings): pass class NA_Fiora_Mid_Zed(Ratings): pass",
"NA_Fiora_Mid_Urgot(Ratings): pass class NA_Fiora_Mid_Varus(Ratings): pass class NA_Fiora_Mid_Vayne(Ratings): pass class NA_Fiora_Mid_Veigar(Ratings): pass class NA_Fiora_Mid_Velkoz(Ratings):",
"NA_Fiora_Mid_Jhin(Ratings): pass class NA_Fiora_Mid_Jinx(Ratings): pass class NA_Fiora_Mid_Kalista(Ratings): pass class NA_Fiora_Mid_Karma(Ratings): pass class NA_Fiora_Mid_Karthus(Ratings):",
"NA_Fiora_Mid_Ekko(Ratings): pass class NA_Fiora_Mid_Elise(Ratings): pass class NA_Fiora_Mid_Evelynn(Ratings): pass class NA_Fiora_Mid_Ezreal(Ratings): pass class NA_Fiora_Mid_Fiddlesticks(Ratings):",
"pass class NA_Fiora_Mid_Jax(Ratings): pass class NA_Fiora_Mid_Jayce(Ratings): pass class NA_Fiora_Mid_Jhin(Ratings): pass class NA_Fiora_Mid_Jinx(Ratings): pass",
"pass class NA_Fiora_Mid_Anivia(Ratings): pass class NA_Fiora_Mid_Annie(Ratings): pass class NA_Fiora_Mid_Ashe(Ratings): pass class NA_Fiora_Mid_AurelionSol(Ratings): pass",
"pass class NA_Fiora_Mid_Diana(Ratings): pass class NA_Fiora_Mid_Draven(Ratings): pass class NA_Fiora_Mid_DrMundo(Ratings): pass class NA_Fiora_Mid_Ekko(Ratings): pass",
"class NA_Fiora_Mid_Urgot(Ratings): pass class NA_Fiora_Mid_Varus(Ratings): pass class NA_Fiora_Mid_Vayne(Ratings): pass class NA_Fiora_Mid_Veigar(Ratings): pass class",
"NA_Fiora_Mid_Jax(Ratings): pass class NA_Fiora_Mid_Jayce(Ratings): pass class NA_Fiora_Mid_Jhin(Ratings): pass class NA_Fiora_Mid_Jinx(Ratings): pass class NA_Fiora_Mid_Kalista(Ratings):",
"NA_Fiora_Mid_Rengar(Ratings): pass class NA_Fiora_Mid_Riven(Ratings): pass class NA_Fiora_Mid_Rumble(Ratings): pass class NA_Fiora_Mid_Ryze(Ratings): pass class NA_Fiora_Mid_Sejuani(Ratings):",
"NA_Fiora_Mid_Khazix(Ratings): pass class NA_Fiora_Mid_Kindred(Ratings): pass class NA_Fiora_Mid_Kled(Ratings): pass class NA_Fiora_Mid_KogMaw(Ratings): pass class NA_Fiora_Mid_Leblanc(Ratings):",
"class NA_Fiora_Mid_Braum(Ratings): pass class NA_Fiora_Mid_Caitlyn(Ratings): pass class NA_Fiora_Mid_Camille(Ratings): pass class NA_Fiora_Mid_Cassiopeia(Ratings): pass class",
"NA_Fiora_Mid_Sivir(Ratings): pass class NA_Fiora_Mid_Skarner(Ratings): pass class NA_Fiora_Mid_Sona(Ratings): pass class NA_Fiora_Mid_Soraka(Ratings): pass class NA_Fiora_Mid_Swain(Ratings):",
"NA_Fiora_Mid_Yasuo(Ratings): pass class NA_Fiora_Mid_Yorick(Ratings): pass class NA_Fiora_Mid_Zac(Ratings): pass class NA_Fiora_Mid_Zed(Ratings): pass class NA_Fiora_Mid_Ziggs(Ratings):",
"pass class NA_Fiora_Mid_Kindred(Ratings): pass class NA_Fiora_Mid_Kled(Ratings): pass class NA_Fiora_Mid_KogMaw(Ratings): pass class NA_Fiora_Mid_Leblanc(Ratings): pass",
"NA_Fiora_Mid_Ivern(Ratings): pass class NA_Fiora_Mid_Janna(Ratings): pass class NA_Fiora_Mid_JarvanIV(Ratings): pass class NA_Fiora_Mid_Jax(Ratings): pass class NA_Fiora_Mid_Jayce(Ratings):",
"NA_Fiora_Mid_Annie(Ratings): pass class NA_Fiora_Mid_Ashe(Ratings): pass class NA_Fiora_Mid_AurelionSol(Ratings): pass class NA_Fiora_Mid_Azir(Ratings): pass class NA_Fiora_Mid_Bard(Ratings):",
"class NA_Fiora_Mid_Talon(Ratings): pass class NA_Fiora_Mid_Taric(Ratings): pass class NA_Fiora_Mid_Teemo(Ratings): pass class NA_Fiora_Mid_Thresh(Ratings): pass class",
"NA_Fiora_Mid_Riven(Ratings): pass class NA_Fiora_Mid_Rumble(Ratings): pass class NA_Fiora_Mid_Ryze(Ratings): pass class NA_Fiora_Mid_Sejuani(Ratings): pass class NA_Fiora_Mid_Shaco(Ratings):",
"class NA_Fiora_Mid_Orianna(Ratings): pass class NA_Fiora_Mid_Ornn(Ratings): pass class NA_Fiora_Mid_Pantheon(Ratings): pass class NA_Fiora_Mid_Poppy(Ratings): pass class",
"class NA_Fiora_Mid_Vladimir(Ratings): pass class NA_Fiora_Mid_Volibear(Ratings): pass class NA_Fiora_Mid_Warwick(Ratings): pass class NA_Fiora_Mid_Xayah(Ratings): pass class",
"class NA_Fiora_Mid_Vi(Ratings): pass class NA_Fiora_Mid_Viktor(Ratings): pass class NA_Fiora_Mid_Vladimir(Ratings): pass class NA_Fiora_Mid_Volibear(Ratings): pass class",
"pass class NA_Fiora_Mid_TahmKench(Ratings): pass class NA_Fiora_Mid_Taliyah(Ratings): pass class NA_Fiora_Mid_Talon(Ratings): pass class NA_Fiora_Mid_Taric(Ratings): pass",
"class NA_Fiora_Mid_Janna(Ratings): pass class NA_Fiora_Mid_JarvanIV(Ratings): pass class NA_Fiora_Mid_Jax(Ratings): pass class NA_Fiora_Mid_Jayce(Ratings): pass class",
"class NA_Fiora_Mid_Jhin(Ratings): pass class NA_Fiora_Mid_Jinx(Ratings): pass class NA_Fiora_Mid_Kalista(Ratings): pass class NA_Fiora_Mid_Karma(Ratings): pass class",
"class NA_Fiora_Mid_Karma(Ratings): pass class NA_Fiora_Mid_Karthus(Ratings): pass class NA_Fiora_Mid_Kassadin(Ratings): pass class NA_Fiora_Mid_Katarina(Ratings): pass class",
"pass class NA_Fiora_Mid_Trundle(Ratings): pass class NA_Fiora_Mid_Tryndamere(Ratings): pass class NA_Fiora_Mid_TwistedFate(Ratings): pass class NA_Fiora_Mid_Twitch(Ratings): pass",
"pass class NA_Fiora_Mid_Chogath(Ratings): pass class NA_Fiora_Mid_Corki(Ratings): pass class NA_Fiora_Mid_Darius(Ratings): pass class NA_Fiora_Mid_Diana(Ratings): pass",
"NA_Fiora_Mid_Shen(Ratings): pass class NA_Fiora_Mid_Shyvana(Ratings): pass class NA_Fiora_Mid_Singed(Ratings): pass class NA_Fiora_Mid_Sion(Ratings): pass class NA_Fiora_Mid_Sivir(Ratings):",
"class NA_Fiora_Mid_Veigar(Ratings): pass class NA_Fiora_Mid_Velkoz(Ratings): pass class NA_Fiora_Mid_Vi(Ratings): pass class NA_Fiora_Mid_Viktor(Ratings): pass class",
"pass class NA_Fiora_Mid_Taric(Ratings): pass class NA_Fiora_Mid_Teemo(Ratings): pass class NA_Fiora_Mid_Thresh(Ratings): pass class NA_Fiora_Mid_Tristana(Ratings): pass",
"pass class NA_Fiora_Mid_Velkoz(Ratings): pass class NA_Fiora_Mid_Vi(Ratings): pass class NA_Fiora_Mid_Viktor(Ratings): pass class NA_Fiora_Mid_Vladimir(Ratings): pass",
"pass class NA_Fiora_Mid_DrMundo(Ratings): pass class NA_Fiora_Mid_Ekko(Ratings): pass class NA_Fiora_Mid_Elise(Ratings): pass class NA_Fiora_Mid_Evelynn(Ratings): pass",
"import Ratings class NA_Fiora_Mid_Aatrox(Ratings): pass class NA_Fiora_Mid_Ahri(Ratings): pass class NA_Fiora_Mid_Akali(Ratings): pass class NA_Fiora_Mid_Alistar(Ratings):",
"pass class NA_Fiora_Mid_Shaco(Ratings): pass class NA_Fiora_Mid_Shen(Ratings): pass class NA_Fiora_Mid_Shyvana(Ratings): pass class NA_Fiora_Mid_Singed(Ratings): pass",
"pass class NA_Fiora_Mid_Rumble(Ratings): pass class NA_Fiora_Mid_Ryze(Ratings): pass class NA_Fiora_Mid_Sejuani(Ratings): pass class NA_Fiora_Mid_Shaco(Ratings): pass",
"pass class NA_Fiora_Mid_Kayle(Ratings): pass class NA_Fiora_Mid_Kayn(Ratings): pass class NA_Fiora_Mid_Kennen(Ratings): pass class NA_Fiora_Mid_Khazix(Ratings): pass",
"pass class NA_Fiora_Mid_Amumu(Ratings): pass class NA_Fiora_Mid_Anivia(Ratings): pass class NA_Fiora_Mid_Annie(Ratings): pass class NA_Fiora_Mid_Ashe(Ratings): pass",
"class NA_Fiora_Mid_Cassiopeia(Ratings): pass class NA_Fiora_Mid_Chogath(Ratings): pass class NA_Fiora_Mid_Corki(Ratings): pass class NA_Fiora_Mid_Darius(Ratings): pass class",
"class NA_Fiora_Mid_Xerath(Ratings): pass class NA_Fiora_Mid_XinZhao(Ratings): pass class NA_Fiora_Mid_Yasuo(Ratings): pass class NA_Fiora_Mid_Yorick(Ratings): pass class",
"NA_Fiora_Mid_Talon(Ratings): pass class NA_Fiora_Mid_Taric(Ratings): pass class NA_Fiora_Mid_Teemo(Ratings): pass class NA_Fiora_Mid_Thresh(Ratings): pass class NA_Fiora_Mid_Tristana(Ratings):",
"class NA_Fiora_Mid_Rengar(Ratings): pass class NA_Fiora_Mid_Riven(Ratings): pass class NA_Fiora_Mid_Rumble(Ratings): pass class NA_Fiora_Mid_Ryze(Ratings): pass class",
"pass class NA_Fiora_Mid_JarvanIV(Ratings): pass class NA_Fiora_Mid_Jax(Ratings): pass class NA_Fiora_Mid_Jayce(Ratings): pass class NA_Fiora_Mid_Jhin(Ratings): pass",
"NA_Fiora_Mid_Caitlyn(Ratings): pass class NA_Fiora_Mid_Camille(Ratings): pass class NA_Fiora_Mid_Cassiopeia(Ratings): pass class NA_Fiora_Mid_Chogath(Ratings): pass class NA_Fiora_Mid_Corki(Ratings):",
"pass class NA_Fiora_Mid_Ahri(Ratings): pass class NA_Fiora_Mid_Akali(Ratings): pass class NA_Fiora_Mid_Alistar(Ratings): pass class NA_Fiora_Mid_Amumu(Ratings): pass",
"NA_Fiora_Mid_Viktor(Ratings): pass class NA_Fiora_Mid_Vladimir(Ratings): pass class NA_Fiora_Mid_Volibear(Ratings): pass class NA_Fiora_Mid_Warwick(Ratings): pass class NA_Fiora_Mid_Xayah(Ratings):",
"NA_Fiora_Mid_Fiddlesticks(Ratings): pass class NA_Fiora_Mid_Fiora(Ratings): pass class NA_Fiora_Mid_Fizz(Ratings): pass class NA_Fiora_Mid_Galio(Ratings): pass class NA_Fiora_Mid_Gangplank(Ratings):",
"pass class NA_Fiora_Mid_Pantheon(Ratings): pass class NA_Fiora_Mid_Poppy(Ratings): pass class NA_Fiora_Mid_Quinn(Ratings): pass class NA_Fiora_Mid_Rakan(Ratings): pass",
"pass class NA_Fiora_Mid_Sivir(Ratings): pass class NA_Fiora_Mid_Skarner(Ratings): pass class NA_Fiora_Mid_Sona(Ratings): pass class NA_Fiora_Mid_Soraka(Ratings): pass",
"pass class NA_Fiora_Mid_Evelynn(Ratings): pass class NA_Fiora_Mid_Ezreal(Ratings): pass class NA_Fiora_Mid_Fiddlesticks(Ratings): pass class NA_Fiora_Mid_Fiora(Ratings): pass",
"pass class NA_Fiora_Mid_Nunu(Ratings): pass class NA_Fiora_Mid_Olaf(Ratings): pass class NA_Fiora_Mid_Orianna(Ratings): pass class NA_Fiora_Mid_Ornn(Ratings): pass",
"NA_Fiora_Mid_Evelynn(Ratings): pass class NA_Fiora_Mid_Ezreal(Ratings): pass class NA_Fiora_Mid_Fiddlesticks(Ratings): pass class NA_Fiora_Mid_Fiora(Ratings): pass class NA_Fiora_Mid_Fizz(Ratings):",
"class NA_Fiora_Mid_TwistedFate(Ratings): pass class NA_Fiora_Mid_Twitch(Ratings): pass class NA_Fiora_Mid_Udyr(Ratings): pass class NA_Fiora_Mid_Urgot(Ratings): pass class",
"class NA_Fiora_Mid_Darius(Ratings): pass class NA_Fiora_Mid_Diana(Ratings): pass class NA_Fiora_Mid_Draven(Ratings): pass class NA_Fiora_Mid_DrMundo(Ratings): pass class",
"NA_Fiora_Mid_Xerath(Ratings): pass class NA_Fiora_Mid_XinZhao(Ratings): pass class NA_Fiora_Mid_Yasuo(Ratings): pass class NA_Fiora_Mid_Yorick(Ratings): pass class NA_Fiora_Mid_Zac(Ratings):",
"pass class NA_Fiora_Mid_Garen(Ratings): pass class NA_Fiora_Mid_Gnar(Ratings): pass class NA_Fiora_Mid_Gragas(Ratings): pass class NA_Fiora_Mid_Graves(Ratings): pass",
"NA_Fiora_Mid_Warwick(Ratings): pass class NA_Fiora_Mid_Xayah(Ratings): pass class NA_Fiora_Mid_Xerath(Ratings): pass class NA_Fiora_Mid_XinZhao(Ratings): pass class NA_Fiora_Mid_Yasuo(Ratings):",
"NA_Fiora_Mid_Ashe(Ratings): pass class NA_Fiora_Mid_AurelionSol(Ratings): pass class NA_Fiora_Mid_Azir(Ratings): pass class NA_Fiora_Mid_Bard(Ratings): pass class NA_Fiora_Mid_Blitzcrank(Ratings):",
"NA_Fiora_Mid_Ryze(Ratings): pass class NA_Fiora_Mid_Sejuani(Ratings): pass class NA_Fiora_Mid_Shaco(Ratings): pass class NA_Fiora_Mid_Shen(Ratings): pass class NA_Fiora_Mid_Shyvana(Ratings):",
"class NA_Fiora_Mid_Graves(Ratings): pass class NA_Fiora_Mid_Hecarim(Ratings): pass class NA_Fiora_Mid_Heimerdinger(Ratings): pass class NA_Fiora_Mid_Illaoi(Ratings): pass class",
"class NA_Fiora_Mid_Nasus(Ratings): pass class NA_Fiora_Mid_Nautilus(Ratings): pass class NA_Fiora_Mid_Nidalee(Ratings): pass class NA_Fiora_Mid_Nocturne(Ratings): pass class",
"class NA_Fiora_Mid_Shyvana(Ratings): pass class NA_Fiora_Mid_Singed(Ratings): pass class NA_Fiora_Mid_Sion(Ratings): pass class NA_Fiora_Mid_Sivir(Ratings): pass class",
"pass class NA_Fiora_Mid_Sion(Ratings): pass class NA_Fiora_Mid_Sivir(Ratings): pass class NA_Fiora_Mid_Skarner(Ratings): pass class NA_Fiora_Mid_Sona(Ratings): pass",
"pass class NA_Fiora_Mid_Draven(Ratings): pass class NA_Fiora_Mid_DrMundo(Ratings): pass class NA_Fiora_Mid_Ekko(Ratings): pass class NA_Fiora_Mid_Elise(Ratings): pass",
"NA_Fiora_Mid_Jayce(Ratings): pass class NA_Fiora_Mid_Jhin(Ratings): pass class NA_Fiora_Mid_Jinx(Ratings): pass class NA_Fiora_Mid_Kalista(Ratings): pass class NA_Fiora_Mid_Karma(Ratings):",
"pass class NA_Fiora_Mid_Fizz(Ratings): pass class NA_Fiora_Mid_Galio(Ratings): pass class NA_Fiora_Mid_Gangplank(Ratings): pass class NA_Fiora_Mid_Garen(Ratings): pass",
"pass class NA_Fiora_Mid_Maokai(Ratings): pass class NA_Fiora_Mid_MasterYi(Ratings): pass class NA_Fiora_Mid_MissFortune(Ratings): pass class NA_Fiora_Mid_MonkeyKing(Ratings): pass",
"class NA_Fiora_Mid_MonkeyKing(Ratings): pass class NA_Fiora_Mid_Mordekaiser(Ratings): pass class NA_Fiora_Mid_Morgana(Ratings): pass class NA_Fiora_Mid_Nami(Ratings): pass class",
"NA_Fiora_Mid_Veigar(Ratings): pass class NA_Fiora_Mid_Velkoz(Ratings): pass class NA_Fiora_Mid_Vi(Ratings): pass class NA_Fiora_Mid_Viktor(Ratings): pass class NA_Fiora_Mid_Vladimir(Ratings):",
"NA_Fiora_Mid_JarvanIV(Ratings): pass class NA_Fiora_Mid_Jax(Ratings): pass class NA_Fiora_Mid_Jayce(Ratings): pass class NA_Fiora_Mid_Jhin(Ratings): pass class NA_Fiora_Mid_Jinx(Ratings):",
"class NA_Fiora_Mid_Leblanc(Ratings): pass class NA_Fiora_Mid_LeeSin(Ratings): pass class NA_Fiora_Mid_Leona(Ratings): pass class NA_Fiora_Mid_Lissandra(Ratings): pass class",
"pass class NA_Fiora_Mid_Yorick(Ratings): pass class NA_Fiora_Mid_Zac(Ratings): pass class NA_Fiora_Mid_Zed(Ratings): pass class NA_Fiora_Mid_Ziggs(Ratings): pass",
"pass class NA_Fiora_Mid_Lux(Ratings): pass class NA_Fiora_Mid_Malphite(Ratings): pass class NA_Fiora_Mid_Malzahar(Ratings): pass class NA_Fiora_Mid_Maokai(Ratings): pass",
"NA_Fiora_Mid_Chogath(Ratings): pass class NA_Fiora_Mid_Corki(Ratings): pass class NA_Fiora_Mid_Darius(Ratings): pass class NA_Fiora_Mid_Diana(Ratings): pass class NA_Fiora_Mid_Draven(Ratings):",
"pass class NA_Fiora_Mid_Xerath(Ratings): pass class NA_Fiora_Mid_XinZhao(Ratings): pass class NA_Fiora_Mid_Yasuo(Ratings): pass class NA_Fiora_Mid_Yorick(Ratings): pass",
"NA_Fiora_Mid_KogMaw(Ratings): pass class NA_Fiora_Mid_Leblanc(Ratings): pass class NA_Fiora_Mid_LeeSin(Ratings): pass class NA_Fiora_Mid_Leona(Ratings): pass class NA_Fiora_Mid_Lissandra(Ratings):",
"NA_Fiora_Mid_Rammus(Ratings): pass class NA_Fiora_Mid_RekSai(Ratings): pass class NA_Fiora_Mid_Renekton(Ratings): pass class NA_Fiora_Mid_Rengar(Ratings): pass class NA_Fiora_Mid_Riven(Ratings):",
"NA_Fiora_Mid_Gangplank(Ratings): pass class NA_Fiora_Mid_Garen(Ratings): pass class NA_Fiora_Mid_Gnar(Ratings): pass class NA_Fiora_Mid_Gragas(Ratings): pass class NA_Fiora_Mid_Graves(Ratings):",
"pass class NA_Fiora_Mid_Alistar(Ratings): pass class NA_Fiora_Mid_Amumu(Ratings): pass class NA_Fiora_Mid_Anivia(Ratings): pass class NA_Fiora_Mid_Annie(Ratings): pass",
"NA_Fiora_Mid_Lulu(Ratings): pass class NA_Fiora_Mid_Lux(Ratings): pass class NA_Fiora_Mid_Malphite(Ratings): pass class NA_Fiora_Mid_Malzahar(Ratings): pass class NA_Fiora_Mid_Maokai(Ratings):",
"class NA_Fiora_Mid_Warwick(Ratings): pass class NA_Fiora_Mid_Xayah(Ratings): pass class NA_Fiora_Mid_Xerath(Ratings): pass class NA_Fiora_Mid_XinZhao(Ratings): pass class",
"NA_Fiora_Mid_Gnar(Ratings): pass class NA_Fiora_Mid_Gragas(Ratings): pass class NA_Fiora_Mid_Graves(Ratings): pass class NA_Fiora_Mid_Hecarim(Ratings): pass class NA_Fiora_Mid_Heimerdinger(Ratings):",
"NA_Fiora_Mid_Zac(Ratings): pass class NA_Fiora_Mid_Zed(Ratings): pass class NA_Fiora_Mid_Ziggs(Ratings): pass class NA_Fiora_Mid_Zilean(Ratings): pass class NA_Fiora_Mid_Zyra(Ratings):",
"NA_Fiora_Mid_Leblanc(Ratings): pass class NA_Fiora_Mid_LeeSin(Ratings): pass class NA_Fiora_Mid_Leona(Ratings): pass class NA_Fiora_Mid_Lissandra(Ratings): pass class NA_Fiora_Mid_Lucian(Ratings):",
"NA_Fiora_Mid_Taliyah(Ratings): pass class NA_Fiora_Mid_Talon(Ratings): pass class NA_Fiora_Mid_Taric(Ratings): pass class NA_Fiora_Mid_Teemo(Ratings): pass class NA_Fiora_Mid_Thresh(Ratings):",
"NA_Fiora_Mid_Karthus(Ratings): pass class NA_Fiora_Mid_Kassadin(Ratings): pass class NA_Fiora_Mid_Katarina(Ratings): pass class NA_Fiora_Mid_Kayle(Ratings): pass class NA_Fiora_Mid_Kayn(Ratings):",
"class NA_Fiora_Mid_Jax(Ratings): pass class NA_Fiora_Mid_Jayce(Ratings): pass class NA_Fiora_Mid_Jhin(Ratings): pass class NA_Fiora_Mid_Jinx(Ratings): pass class",
"pass class NA_Fiora_Mid_Leona(Ratings): pass class NA_Fiora_Mid_Lissandra(Ratings): pass class NA_Fiora_Mid_Lucian(Ratings): pass class NA_Fiora_Mid_Lulu(Ratings): pass",
"NA_Fiora_Mid_Braum(Ratings): pass class NA_Fiora_Mid_Caitlyn(Ratings): pass class NA_Fiora_Mid_Camille(Ratings): pass class NA_Fiora_Mid_Cassiopeia(Ratings): pass class NA_Fiora_Mid_Chogath(Ratings):",
"NA_Fiora_Mid_Lissandra(Ratings): pass class NA_Fiora_Mid_Lucian(Ratings): pass class NA_Fiora_Mid_Lulu(Ratings): pass class NA_Fiora_Mid_Lux(Ratings): pass class NA_Fiora_Mid_Malphite(Ratings):",
"pass class NA_Fiora_Mid_Vladimir(Ratings): pass class NA_Fiora_Mid_Volibear(Ratings): pass class NA_Fiora_Mid_Warwick(Ratings): pass class NA_Fiora_Mid_Xayah(Ratings): pass",
"class NA_Fiora_Mid_Sivir(Ratings): pass class NA_Fiora_Mid_Skarner(Ratings): pass class NA_Fiora_Mid_Sona(Ratings): pass class NA_Fiora_Mid_Soraka(Ratings): pass class",
"class NA_Fiora_Mid_Ezreal(Ratings): pass class NA_Fiora_Mid_Fiddlesticks(Ratings): pass class NA_Fiora_Mid_Fiora(Ratings): pass class NA_Fiora_Mid_Fizz(Ratings): pass class",
"NA_Fiora_Mid_Anivia(Ratings): pass class NA_Fiora_Mid_Annie(Ratings): pass class NA_Fiora_Mid_Ashe(Ratings): pass class NA_Fiora_Mid_AurelionSol(Ratings): pass class NA_Fiora_Mid_Azir(Ratings):",
"pass class NA_Fiora_Mid_Shen(Ratings): pass class NA_Fiora_Mid_Shyvana(Ratings): pass class NA_Fiora_Mid_Singed(Ratings): pass class NA_Fiora_Mid_Sion(Ratings): pass",
"pass class NA_Fiora_Mid_Warwick(Ratings): pass class NA_Fiora_Mid_Xayah(Ratings): pass class NA_Fiora_Mid_Xerath(Ratings): pass class NA_Fiora_Mid_XinZhao(Ratings): pass",
"NA_Fiora_Mid_TwistedFate(Ratings): pass class NA_Fiora_Mid_Twitch(Ratings): pass class NA_Fiora_Mid_Udyr(Ratings): pass class NA_Fiora_Mid_Urgot(Ratings): pass class NA_Fiora_Mid_Varus(Ratings):",
"NA_Fiora_Mid_Leona(Ratings): pass class NA_Fiora_Mid_Lissandra(Ratings): pass class NA_Fiora_Mid_Lucian(Ratings): pass class NA_Fiora_Mid_Lulu(Ratings): pass class NA_Fiora_Mid_Lux(Ratings):",
"pass class NA_Fiora_Mid_Zed(Ratings): pass class NA_Fiora_Mid_Ziggs(Ratings): pass class NA_Fiora_Mid_Zilean(Ratings): pass class NA_Fiora_Mid_Zyra(Ratings): pass",
"class NA_Fiora_Mid_Gragas(Ratings): pass class NA_Fiora_Mid_Graves(Ratings): pass class NA_Fiora_Mid_Hecarim(Ratings): pass class NA_Fiora_Mid_Heimerdinger(Ratings): pass class",
"pass class NA_Fiora_Mid_Taliyah(Ratings): pass class NA_Fiora_Mid_Talon(Ratings): pass class NA_Fiora_Mid_Taric(Ratings): pass class NA_Fiora_Mid_Teemo(Ratings): pass",
"class NA_Fiora_Mid_Draven(Ratings): pass class NA_Fiora_Mid_DrMundo(Ratings): pass class NA_Fiora_Mid_Ekko(Ratings): pass class NA_Fiora_Mid_Elise(Ratings): pass class",
"class NA_Fiora_Mid_Annie(Ratings): pass class NA_Fiora_Mid_Ashe(Ratings): pass class NA_Fiora_Mid_AurelionSol(Ratings): pass class NA_Fiora_Mid_Azir(Ratings): pass class",
"pass class NA_Fiora_Mid_Jinx(Ratings): pass class NA_Fiora_Mid_Kalista(Ratings): pass class NA_Fiora_Mid_Karma(Ratings): pass class NA_Fiora_Mid_Karthus(Ratings): pass",
"NA_Fiora_Mid_Trundle(Ratings): pass class NA_Fiora_Mid_Tryndamere(Ratings): pass class NA_Fiora_Mid_TwistedFate(Ratings): pass class NA_Fiora_Mid_Twitch(Ratings): pass class NA_Fiora_Mid_Udyr(Ratings):",
"NA_Fiora_Mid_Sion(Ratings): pass class NA_Fiora_Mid_Sivir(Ratings): pass class NA_Fiora_Mid_Skarner(Ratings): pass class NA_Fiora_Mid_Sona(Ratings): pass class NA_Fiora_Mid_Soraka(Ratings):",
"NA_Fiora_Mid_Diana(Ratings): pass class NA_Fiora_Mid_Draven(Ratings): pass class NA_Fiora_Mid_DrMundo(Ratings): pass class NA_Fiora_Mid_Ekko(Ratings): pass class NA_Fiora_Mid_Elise(Ratings):",
"NA_Fiora_Mid_Gragas(Ratings): pass class NA_Fiora_Mid_Graves(Ratings): pass class NA_Fiora_Mid_Hecarim(Ratings): pass class NA_Fiora_Mid_Heimerdinger(Ratings): pass class NA_Fiora_Mid_Illaoi(Ratings):",
"class NA_Fiora_Mid_Nautilus(Ratings): pass class NA_Fiora_Mid_Nidalee(Ratings): pass class NA_Fiora_Mid_Nocturne(Ratings): pass class NA_Fiora_Mid_Nunu(Ratings): pass class",
"NA_Fiora_Mid_Sejuani(Ratings): pass class NA_Fiora_Mid_Shaco(Ratings): pass class NA_Fiora_Mid_Shen(Ratings): pass class NA_Fiora_Mid_Shyvana(Ratings): pass class NA_Fiora_Mid_Singed(Ratings):",
"pass class NA_Fiora_Mid_Vi(Ratings): pass class NA_Fiora_Mid_Viktor(Ratings): pass class NA_Fiora_Mid_Vladimir(Ratings): pass class NA_Fiora_Mid_Volibear(Ratings): pass",
"class NA_Fiora_Mid_Varus(Ratings): pass class NA_Fiora_Mid_Vayne(Ratings): pass class NA_Fiora_Mid_Veigar(Ratings): pass class NA_Fiora_Mid_Velkoz(Ratings): pass class",
"class NA_Fiora_Mid_Sion(Ratings): pass class NA_Fiora_Mid_Sivir(Ratings): pass class NA_Fiora_Mid_Skarner(Ratings): pass class NA_Fiora_Mid_Sona(Ratings): pass class",
"Ratings class NA_Fiora_Mid_Aatrox(Ratings): pass class NA_Fiora_Mid_Ahri(Ratings): pass class NA_Fiora_Mid_Akali(Ratings): pass class NA_Fiora_Mid_Alistar(Ratings): pass",
"pass class NA_Fiora_Mid_AurelionSol(Ratings): pass class NA_Fiora_Mid_Azir(Ratings): pass class NA_Fiora_Mid_Bard(Ratings): pass class NA_Fiora_Mid_Blitzcrank(Ratings): pass",
"NA_Fiora_Mid_Vayne(Ratings): pass class NA_Fiora_Mid_Veigar(Ratings): pass class NA_Fiora_Mid_Velkoz(Ratings): pass class NA_Fiora_Mid_Vi(Ratings): pass class NA_Fiora_Mid_Viktor(Ratings):",
"class NA_Fiora_Mid_Nidalee(Ratings): pass class NA_Fiora_Mid_Nocturne(Ratings): pass class NA_Fiora_Mid_Nunu(Ratings): pass class NA_Fiora_Mid_Olaf(Ratings): pass class",
"pass class NA_Fiora_Mid_Irelia(Ratings): pass class NA_Fiora_Mid_Ivern(Ratings): pass class NA_Fiora_Mid_Janna(Ratings): pass class NA_Fiora_Mid_JarvanIV(Ratings): pass",
"class NA_Fiora_Mid_Ashe(Ratings): pass class NA_Fiora_Mid_AurelionSol(Ratings): pass class NA_Fiora_Mid_Azir(Ratings): pass class NA_Fiora_Mid_Bard(Ratings): pass class",
"class NA_Fiora_Mid_Lissandra(Ratings): pass class NA_Fiora_Mid_Lucian(Ratings): pass class NA_Fiora_Mid_Lulu(Ratings): pass class NA_Fiora_Mid_Lux(Ratings): pass class",
"class NA_Fiora_Mid_Sona(Ratings): pass class NA_Fiora_Mid_Soraka(Ratings): pass class NA_Fiora_Mid_Swain(Ratings): pass class NA_Fiora_Mid_Syndra(Ratings): pass class",
"pass class NA_Fiora_Mid_TwistedFate(Ratings): pass class NA_Fiora_Mid_Twitch(Ratings): pass class NA_Fiora_Mid_Udyr(Ratings): pass class NA_Fiora_Mid_Urgot(Ratings): pass",
"class NA_Fiora_Mid_Galio(Ratings): pass class NA_Fiora_Mid_Gangplank(Ratings): pass class NA_Fiora_Mid_Garen(Ratings): pass class NA_Fiora_Mid_Gnar(Ratings): pass class",
"class NA_Fiora_Mid_Ornn(Ratings): pass class NA_Fiora_Mid_Pantheon(Ratings): pass class NA_Fiora_Mid_Poppy(Ratings): pass class NA_Fiora_Mid_Quinn(Ratings): pass class",
"class NA_Fiora_Mid_KogMaw(Ratings): pass class NA_Fiora_Mid_Leblanc(Ratings): pass class NA_Fiora_Mid_LeeSin(Ratings): pass class NA_Fiora_Mid_Leona(Ratings): pass class",
"NA_Fiora_Mid_Rakan(Ratings): pass class NA_Fiora_Mid_Rammus(Ratings): pass class NA_Fiora_Mid_RekSai(Ratings): pass class NA_Fiora_Mid_Renekton(Ratings): pass class NA_Fiora_Mid_Rengar(Ratings):",
"pass class NA_Fiora_Mid_Kayn(Ratings): pass class NA_Fiora_Mid_Kennen(Ratings): pass class NA_Fiora_Mid_Khazix(Ratings): pass class NA_Fiora_Mid_Kindred(Ratings): pass",
"pass class NA_Fiora_Mid_Illaoi(Ratings): pass class NA_Fiora_Mid_Irelia(Ratings): pass class NA_Fiora_Mid_Ivern(Ratings): pass class NA_Fiora_Mid_Janna(Ratings): pass",
"NA_Fiora_Mid_Jinx(Ratings): pass class NA_Fiora_Mid_Kalista(Ratings): pass class NA_Fiora_Mid_Karma(Ratings): pass class NA_Fiora_Mid_Karthus(Ratings): pass class NA_Fiora_Mid_Kassadin(Ratings):",
"pass class NA_Fiora_Mid_Mordekaiser(Ratings): pass class NA_Fiora_Mid_Morgana(Ratings): pass class NA_Fiora_Mid_Nami(Ratings): pass class NA_Fiora_Mid_Nasus(Ratings): pass",
"pass class NA_Fiora_Mid_Cassiopeia(Ratings): pass class NA_Fiora_Mid_Chogath(Ratings): pass class NA_Fiora_Mid_Corki(Ratings): pass class NA_Fiora_Mid_Darius(Ratings): pass",
"NA_Fiora_Mid_Camille(Ratings): pass class NA_Fiora_Mid_Cassiopeia(Ratings): pass class NA_Fiora_Mid_Chogath(Ratings): pass class NA_Fiora_Mid_Corki(Ratings): pass class NA_Fiora_Mid_Darius(Ratings):",
"NA_Fiora_Mid_Fiora(Ratings): pass class NA_Fiora_Mid_Fizz(Ratings): pass class NA_Fiora_Mid_Galio(Ratings): pass class NA_Fiora_Mid_Gangplank(Ratings): pass class NA_Fiora_Mid_Garen(Ratings):",
"pass class NA_Fiora_Mid_Rammus(Ratings): pass class NA_Fiora_Mid_RekSai(Ratings): pass class NA_Fiora_Mid_Renekton(Ratings): pass class NA_Fiora_Mid_Rengar(Ratings): pass",
"pass class NA_Fiora_Mid_Rakan(Ratings): pass class NA_Fiora_Mid_Rammus(Ratings): pass class NA_Fiora_Mid_RekSai(Ratings): pass class NA_Fiora_Mid_Renekton(Ratings): pass",
"class NA_Fiora_Mid_Thresh(Ratings): pass class NA_Fiora_Mid_Tristana(Ratings): pass class NA_Fiora_Mid_Trundle(Ratings): pass class NA_Fiora_Mid_Tryndamere(Ratings): pass class",
"class NA_Fiora_Mid_AurelionSol(Ratings): pass class NA_Fiora_Mid_Azir(Ratings): pass class NA_Fiora_Mid_Bard(Ratings): pass class NA_Fiora_Mid_Blitzcrank(Ratings): pass class",
"NA_Fiora_Mid_TahmKench(Ratings): pass class NA_Fiora_Mid_Taliyah(Ratings): pass class NA_Fiora_Mid_Talon(Ratings): pass class NA_Fiora_Mid_Taric(Ratings): pass class NA_Fiora_Mid_Teemo(Ratings):",
"NA_Fiora_Mid_Olaf(Ratings): pass class NA_Fiora_Mid_Orianna(Ratings): pass class NA_Fiora_Mid_Ornn(Ratings): pass class NA_Fiora_Mid_Pantheon(Ratings): pass class NA_Fiora_Mid_Poppy(Ratings):",
"pass class NA_Fiora_Mid_Brand(Ratings): pass class NA_Fiora_Mid_Braum(Ratings): pass class NA_Fiora_Mid_Caitlyn(Ratings): pass class NA_Fiora_Mid_Camille(Ratings): pass",
"NA_Fiora_Mid_Teemo(Ratings): pass class NA_Fiora_Mid_Thresh(Ratings): pass class NA_Fiora_Mid_Tristana(Ratings): pass class NA_Fiora_Mid_Trundle(Ratings): pass class NA_Fiora_Mid_Tryndamere(Ratings):",
"class NA_Fiora_Mid_Diana(Ratings): pass class NA_Fiora_Mid_Draven(Ratings): pass class NA_Fiora_Mid_DrMundo(Ratings): pass class NA_Fiora_Mid_Ekko(Ratings): pass class",
"class NA_Fiora_Mid_Lulu(Ratings): pass class NA_Fiora_Mid_Lux(Ratings): pass class NA_Fiora_Mid_Malphite(Ratings): pass class NA_Fiora_Mid_Malzahar(Ratings): pass class",
"class NA_Fiora_Mid_Gangplank(Ratings): pass class NA_Fiora_Mid_Garen(Ratings): pass class NA_Fiora_Mid_Gnar(Ratings): pass class NA_Fiora_Mid_Gragas(Ratings): pass class",
"NA_Fiora_Mid_Heimerdinger(Ratings): pass class NA_Fiora_Mid_Illaoi(Ratings): pass class NA_Fiora_Mid_Irelia(Ratings): pass class NA_Fiora_Mid_Ivern(Ratings): pass class NA_Fiora_Mid_Janna(Ratings):",
"NA_Fiora_Mid_Lucian(Ratings): pass class NA_Fiora_Mid_Lulu(Ratings): pass class NA_Fiora_Mid_Lux(Ratings): pass class NA_Fiora_Mid_Malphite(Ratings): pass class NA_Fiora_Mid_Malzahar(Ratings):",
"class NA_Fiora_Mid_Hecarim(Ratings): pass class NA_Fiora_Mid_Heimerdinger(Ratings): pass class NA_Fiora_Mid_Illaoi(Ratings): pass class NA_Fiora_Mid_Irelia(Ratings): pass class",
"NA_Fiora_Mid_Tristana(Ratings): pass class NA_Fiora_Mid_Trundle(Ratings): pass class NA_Fiora_Mid_Tryndamere(Ratings): pass class NA_Fiora_Mid_TwistedFate(Ratings): pass class NA_Fiora_Mid_Twitch(Ratings):",
"NA_Fiora_Mid_Lux(Ratings): pass class NA_Fiora_Mid_Malphite(Ratings): pass class NA_Fiora_Mid_Malzahar(Ratings): pass class NA_Fiora_Mid_Maokai(Ratings): pass class NA_Fiora_Mid_MasterYi(Ratings):",
"NA_Fiora_Mid_AurelionSol(Ratings): pass class NA_Fiora_Mid_Azir(Ratings): pass class NA_Fiora_Mid_Bard(Ratings): pass class NA_Fiora_Mid_Blitzcrank(Ratings): pass class NA_Fiora_Mid_Brand(Ratings):",
"pass class NA_Fiora_Mid_Ivern(Ratings): pass class NA_Fiora_Mid_Janna(Ratings): pass class NA_Fiora_Mid_JarvanIV(Ratings): pass class NA_Fiora_Mid_Jax(Ratings): pass",
"class NA_Fiora_Mid_Kayle(Ratings): pass class NA_Fiora_Mid_Kayn(Ratings): pass class NA_Fiora_Mid_Kennen(Ratings): pass class NA_Fiora_Mid_Khazix(Ratings): pass class",
"class NA_Fiora_Mid_Ryze(Ratings): pass class NA_Fiora_Mid_Sejuani(Ratings): pass class NA_Fiora_Mid_Shaco(Ratings): pass class NA_Fiora_Mid_Shen(Ratings): pass class",
"pass class NA_Fiora_Mid_Kalista(Ratings): pass class NA_Fiora_Mid_Karma(Ratings): pass class NA_Fiora_Mid_Karthus(Ratings): pass class NA_Fiora_Mid_Kassadin(Ratings): pass",
"pass class NA_Fiora_Mid_Tristana(Ratings): pass class NA_Fiora_Mid_Trundle(Ratings): pass class NA_Fiora_Mid_Tryndamere(Ratings): pass class NA_Fiora_Mid_TwistedFate(Ratings): pass",
"NA_Fiora_Mid_MissFortune(Ratings): pass class NA_Fiora_Mid_MonkeyKing(Ratings): pass class NA_Fiora_Mid_Mordekaiser(Ratings): pass class NA_Fiora_Mid_Morgana(Ratings): pass class NA_Fiora_Mid_Nami(Ratings):",
"NA_Fiora_Mid_Hecarim(Ratings): pass class NA_Fiora_Mid_Heimerdinger(Ratings): pass class NA_Fiora_Mid_Illaoi(Ratings): pass class NA_Fiora_Mid_Irelia(Ratings): pass class NA_Fiora_Mid_Ivern(Ratings):",
"class NA_Fiora_Mid_Ekko(Ratings): pass class NA_Fiora_Mid_Elise(Ratings): pass class NA_Fiora_Mid_Evelynn(Ratings): pass class NA_Fiora_Mid_Ezreal(Ratings): pass class",
"NA_Fiora_Mid_Elise(Ratings): pass class NA_Fiora_Mid_Evelynn(Ratings): pass class NA_Fiora_Mid_Ezreal(Ratings): pass class NA_Fiora_Mid_Fiddlesticks(Ratings): pass class NA_Fiora_Mid_Fiora(Ratings):",
"pass class NA_Fiora_Mid_Akali(Ratings): pass class NA_Fiora_Mid_Alistar(Ratings): pass class NA_Fiora_Mid_Amumu(Ratings): pass class NA_Fiora_Mid_Anivia(Ratings): pass",
"class NA_Fiora_Mid_Evelynn(Ratings): pass class NA_Fiora_Mid_Ezreal(Ratings): pass class NA_Fiora_Mid_Fiddlesticks(Ratings): pass class NA_Fiora_Mid_Fiora(Ratings): pass class",
"pass class NA_Fiora_Mid_Jhin(Ratings): pass class NA_Fiora_Mid_Jinx(Ratings): pass class NA_Fiora_Mid_Kalista(Ratings): pass class NA_Fiora_Mid_Karma(Ratings): pass",
"class NA_Fiora_Mid_Kayn(Ratings): pass class NA_Fiora_Mid_Kennen(Ratings): pass class NA_Fiora_Mid_Khazix(Ratings): pass class NA_Fiora_Mid_Kindred(Ratings): pass class",
"NA_Fiora_Mid_Soraka(Ratings): pass class NA_Fiora_Mid_Swain(Ratings): pass class NA_Fiora_Mid_Syndra(Ratings): pass class NA_Fiora_Mid_TahmKench(Ratings): pass class NA_Fiora_Mid_Taliyah(Ratings):",
"pass class NA_Fiora_Mid_Lulu(Ratings): pass class NA_Fiora_Mid_Lux(Ratings): pass class NA_Fiora_Mid_Malphite(Ratings): pass class NA_Fiora_Mid_Malzahar(Ratings): pass",
"class NA_Fiora_Mid_Sejuani(Ratings): pass class NA_Fiora_Mid_Shaco(Ratings): pass class NA_Fiora_Mid_Shen(Ratings): pass class NA_Fiora_Mid_Shyvana(Ratings): pass class",
"NA_Fiora_Mid_Amumu(Ratings): pass class NA_Fiora_Mid_Anivia(Ratings): pass class NA_Fiora_Mid_Annie(Ratings): pass class NA_Fiora_Mid_Ashe(Ratings): pass class NA_Fiora_Mid_AurelionSol(Ratings):",
"pass class NA_Fiora_Mid_Caitlyn(Ratings): pass class NA_Fiora_Mid_Camille(Ratings): pass class NA_Fiora_Mid_Cassiopeia(Ratings): pass class NA_Fiora_Mid_Chogath(Ratings): pass",
"class NA_Fiora_Mid_Amumu(Ratings): pass class NA_Fiora_Mid_Anivia(Ratings): pass class NA_Fiora_Mid_Annie(Ratings): pass class NA_Fiora_Mid_Ashe(Ratings): pass class",
"class NA_Fiora_Mid_Corki(Ratings): pass class NA_Fiora_Mid_Darius(Ratings): pass class NA_Fiora_Mid_Diana(Ratings): pass class NA_Fiora_Mid_Draven(Ratings): pass class",
"pass class NA_Fiora_Mid_Twitch(Ratings): pass class NA_Fiora_Mid_Udyr(Ratings): pass class NA_Fiora_Mid_Urgot(Ratings): pass class NA_Fiora_Mid_Varus(Ratings): pass",
"class NA_Fiora_Mid_Taric(Ratings): pass class NA_Fiora_Mid_Teemo(Ratings): pass class NA_Fiora_Mid_Thresh(Ratings): pass class NA_Fiora_Mid_Tristana(Ratings): pass class",
"class NA_Fiora_Mid_Syndra(Ratings): pass class NA_Fiora_Mid_TahmKench(Ratings): pass class NA_Fiora_Mid_Taliyah(Ratings): pass class NA_Fiora_Mid_Talon(Ratings): pass class",
"NA_Fiora_Mid_Twitch(Ratings): pass class NA_Fiora_Mid_Udyr(Ratings): pass class NA_Fiora_Mid_Urgot(Ratings): pass class NA_Fiora_Mid_Varus(Ratings): pass class NA_Fiora_Mid_Vayne(Ratings):",
"NA_Fiora_Mid_Kennen(Ratings): pass class NA_Fiora_Mid_Khazix(Ratings): pass class NA_Fiora_Mid_Kindred(Ratings): pass class NA_Fiora_Mid_Kled(Ratings): pass class NA_Fiora_Mid_KogMaw(Ratings):",
"pass class NA_Fiora_Mid_Nautilus(Ratings): pass class NA_Fiora_Mid_Nidalee(Ratings): pass class NA_Fiora_Mid_Nocturne(Ratings): pass class NA_Fiora_Mid_Nunu(Ratings): pass",
"class NA_Fiora_Mid_Heimerdinger(Ratings): pass class NA_Fiora_Mid_Illaoi(Ratings): pass class NA_Fiora_Mid_Irelia(Ratings): pass class NA_Fiora_Mid_Ivern(Ratings): pass class",
"pass class NA_Fiora_Mid_Khazix(Ratings): pass class NA_Fiora_Mid_Kindred(Ratings): pass class NA_Fiora_Mid_Kled(Ratings): pass class NA_Fiora_Mid_KogMaw(Ratings): pass",
"NA_Fiora_Mid_Udyr(Ratings): pass class NA_Fiora_Mid_Urgot(Ratings): pass class NA_Fiora_Mid_Varus(Ratings): pass class NA_Fiora_Mid_Vayne(Ratings): pass class NA_Fiora_Mid_Veigar(Ratings):",
"class NA_Fiora_Mid_Viktor(Ratings): pass class NA_Fiora_Mid_Vladimir(Ratings): pass class NA_Fiora_Mid_Volibear(Ratings): pass class NA_Fiora_Mid_Warwick(Ratings): pass class",
"class NA_Fiora_Mid_Karthus(Ratings): pass class NA_Fiora_Mid_Kassadin(Ratings): pass class NA_Fiora_Mid_Katarina(Ratings): pass class NA_Fiora_Mid_Kayle(Ratings): pass class",
"pass class NA_Fiora_Mid_Heimerdinger(Ratings): pass class NA_Fiora_Mid_Illaoi(Ratings): pass class NA_Fiora_Mid_Irelia(Ratings): pass class NA_Fiora_Mid_Ivern(Ratings): pass",
"NA_Fiora_Mid_Janna(Ratings): pass class NA_Fiora_Mid_JarvanIV(Ratings): pass class NA_Fiora_Mid_Jax(Ratings): pass class NA_Fiora_Mid_Jayce(Ratings): pass class NA_Fiora_Mid_Jhin(Ratings):",
"NA_Fiora_Mid_Draven(Ratings): pass class NA_Fiora_Mid_DrMundo(Ratings): pass class NA_Fiora_Mid_Ekko(Ratings): pass class NA_Fiora_Mid_Elise(Ratings): pass class NA_Fiora_Mid_Evelynn(Ratings):",
"pass class NA_Fiora_Mid_Olaf(Ratings): pass class NA_Fiora_Mid_Orianna(Ratings): pass class NA_Fiora_Mid_Ornn(Ratings): pass class NA_Fiora_Mid_Pantheon(Ratings): pass",
"pass class NA_Fiora_Mid_Syndra(Ratings): pass class NA_Fiora_Mid_TahmKench(Ratings): pass class NA_Fiora_Mid_Taliyah(Ratings): pass class NA_Fiora_Mid_Talon(Ratings): pass",
"from getratings.models.ratings import Ratings class NA_Fiora_Mid_Aatrox(Ratings): pass class NA_Fiora_Mid_Ahri(Ratings): pass class NA_Fiora_Mid_Akali(Ratings): pass",
"NA_Fiora_Mid_Varus(Ratings): pass class NA_Fiora_Mid_Vayne(Ratings): pass class NA_Fiora_Mid_Veigar(Ratings): pass class NA_Fiora_Mid_Velkoz(Ratings): pass class NA_Fiora_Mid_Vi(Ratings):",
"NA_Fiora_Mid_Yorick(Ratings): pass class NA_Fiora_Mid_Zac(Ratings): pass class NA_Fiora_Mid_Zed(Ratings): pass class NA_Fiora_Mid_Ziggs(Ratings): pass class NA_Fiora_Mid_Zilean(Ratings):",
"NA_Fiora_Mid_Rumble(Ratings): pass class NA_Fiora_Mid_Ryze(Ratings): pass class NA_Fiora_Mid_Sejuani(Ratings): pass class NA_Fiora_Mid_Shaco(Ratings): pass class NA_Fiora_Mid_Shen(Ratings):",
"pass class NA_Fiora_Mid_Ashe(Ratings): pass class NA_Fiora_Mid_AurelionSol(Ratings): pass class NA_Fiora_Mid_Azir(Ratings): pass class NA_Fiora_Mid_Bard(Ratings): pass",
"pass class NA_Fiora_Mid_Sona(Ratings): pass class NA_Fiora_Mid_Soraka(Ratings): pass class NA_Fiora_Mid_Swain(Ratings): pass class NA_Fiora_Mid_Syndra(Ratings): pass",
"pass class NA_Fiora_Mid_Jayce(Ratings): pass class NA_Fiora_Mid_Jhin(Ratings): pass class NA_Fiora_Mid_Jinx(Ratings): pass class NA_Fiora_Mid_Kalista(Ratings): pass",
"pass class NA_Fiora_Mid_Urgot(Ratings): pass class NA_Fiora_Mid_Varus(Ratings): pass class NA_Fiora_Mid_Vayne(Ratings): pass class NA_Fiora_Mid_Veigar(Ratings): pass",
"NA_Fiora_Mid_Nami(Ratings): pass class NA_Fiora_Mid_Nasus(Ratings): pass class NA_Fiora_Mid_Nautilus(Ratings): pass class NA_Fiora_Mid_Nidalee(Ratings): pass class NA_Fiora_Mid_Nocturne(Ratings):",
"class NA_Fiora_Mid_Rumble(Ratings): pass class NA_Fiora_Mid_Ryze(Ratings): pass class NA_Fiora_Mid_Sejuani(Ratings): pass class NA_Fiora_Mid_Shaco(Ratings): pass class",
"NA_Fiora_Mid_Thresh(Ratings): pass class NA_Fiora_Mid_Tristana(Ratings): pass class NA_Fiora_Mid_Trundle(Ratings): pass class NA_Fiora_Mid_Tryndamere(Ratings): pass class NA_Fiora_Mid_TwistedFate(Ratings):",
"class NA_Fiora_Mid_Katarina(Ratings): pass class NA_Fiora_Mid_Kayle(Ratings): pass class NA_Fiora_Mid_Kayn(Ratings): pass class NA_Fiora_Mid_Kennen(Ratings): pass class",
"NA_Fiora_Mid_Kayn(Ratings): pass class NA_Fiora_Mid_Kennen(Ratings): pass class NA_Fiora_Mid_Khazix(Ratings): pass class NA_Fiora_Mid_Kindred(Ratings): pass class NA_Fiora_Mid_Kled(Ratings):",
"class NA_Fiora_Mid_Illaoi(Ratings): pass class NA_Fiora_Mid_Irelia(Ratings): pass class NA_Fiora_Mid_Ivern(Ratings): pass class NA_Fiora_Mid_Janna(Ratings): pass class",
"NA_Fiora_Mid_Ahri(Ratings): pass class NA_Fiora_Mid_Akali(Ratings): pass class NA_Fiora_Mid_Alistar(Ratings): pass class NA_Fiora_Mid_Amumu(Ratings): pass class NA_Fiora_Mid_Anivia(Ratings):",
"class NA_Fiora_Mid_Bard(Ratings): pass class NA_Fiora_Mid_Blitzcrank(Ratings): pass class NA_Fiora_Mid_Brand(Ratings): pass class NA_Fiora_Mid_Braum(Ratings): pass class",
"class NA_Fiora_Mid_Fiddlesticks(Ratings): pass class NA_Fiora_Mid_Fiora(Ratings): pass class NA_Fiora_Mid_Fizz(Ratings): pass class NA_Fiora_Mid_Galio(Ratings): pass class",
"pass class NA_Fiora_Mid_Malphite(Ratings): pass class NA_Fiora_Mid_Malzahar(Ratings): pass class NA_Fiora_Mid_Maokai(Ratings): pass class NA_Fiora_Mid_MasterYi(Ratings): pass",
"NA_Fiora_Mid_Fizz(Ratings): pass class NA_Fiora_Mid_Galio(Ratings): pass class NA_Fiora_Mid_Gangplank(Ratings): pass class NA_Fiora_Mid_Garen(Ratings): pass class NA_Fiora_Mid_Gnar(Ratings):",
"NA_Fiora_Mid_Xayah(Ratings): pass class NA_Fiora_Mid_Xerath(Ratings): pass class NA_Fiora_Mid_XinZhao(Ratings): pass class NA_Fiora_Mid_Yasuo(Ratings): pass class NA_Fiora_Mid_Yorick(Ratings):",
"class NA_Fiora_Mid_Gnar(Ratings): pass class NA_Fiora_Mid_Gragas(Ratings): pass class NA_Fiora_Mid_Graves(Ratings): pass class NA_Fiora_Mid_Hecarim(Ratings): pass class",
"class NA_Fiora_Mid_Nami(Ratings): pass class NA_Fiora_Mid_Nasus(Ratings): pass class NA_Fiora_Mid_Nautilus(Ratings): pass class NA_Fiora_Mid_Nidalee(Ratings): pass class",
"pass class NA_Fiora_Mid_Teemo(Ratings): pass class NA_Fiora_Mid_Thresh(Ratings): pass class NA_Fiora_Mid_Tristana(Ratings): pass class NA_Fiora_Mid_Trundle(Ratings): pass",
"class NA_Fiora_Mid_Kalista(Ratings): pass class NA_Fiora_Mid_Karma(Ratings): pass class NA_Fiora_Mid_Karthus(Ratings): pass class NA_Fiora_Mid_Kassadin(Ratings): pass class",
"pass class NA_Fiora_Mid_XinZhao(Ratings): pass class NA_Fiora_Mid_Yasuo(Ratings): pass class NA_Fiora_Mid_Yorick(Ratings): pass class NA_Fiora_Mid_Zac(Ratings): pass",
"pass class NA_Fiora_Mid_Katarina(Ratings): pass class NA_Fiora_Mid_Kayle(Ratings): pass class NA_Fiora_Mid_Kayn(Ratings): pass class NA_Fiora_Mid_Kennen(Ratings): pass",
"class NA_Fiora_Mid_Elise(Ratings): pass class NA_Fiora_Mid_Evelynn(Ratings): pass class NA_Fiora_Mid_Ezreal(Ratings): pass class NA_Fiora_Mid_Fiddlesticks(Ratings): pass class",
"pass class NA_Fiora_Mid_Galio(Ratings): pass class NA_Fiora_Mid_Gangplank(Ratings): pass class NA_Fiora_Mid_Garen(Ratings): pass class NA_Fiora_Mid_Gnar(Ratings): pass",
"class NA_Fiora_Mid_Ivern(Ratings): pass class NA_Fiora_Mid_Janna(Ratings): pass class NA_Fiora_Mid_JarvanIV(Ratings): pass class NA_Fiora_Mid_Jax(Ratings): pass class",
"class NA_Fiora_Mid_Kled(Ratings): pass class NA_Fiora_Mid_KogMaw(Ratings): pass class NA_Fiora_Mid_Leblanc(Ratings): pass class NA_Fiora_Mid_LeeSin(Ratings): pass class",
"pass class NA_Fiora_Mid_Xayah(Ratings): pass class NA_Fiora_Mid_Xerath(Ratings): pass class NA_Fiora_Mid_XinZhao(Ratings): pass class NA_Fiora_Mid_Yasuo(Ratings): pass",
"class NA_Fiora_Mid_Yorick(Ratings): pass class NA_Fiora_Mid_Zac(Ratings): pass class NA_Fiora_Mid_Zed(Ratings): pass class NA_Fiora_Mid_Ziggs(Ratings): pass class",
"pass class NA_Fiora_Mid_Fiddlesticks(Ratings): pass class NA_Fiora_Mid_Fiora(Ratings): pass class NA_Fiora_Mid_Fizz(Ratings): pass class NA_Fiora_Mid_Galio(Ratings): pass",
"pass class NA_Fiora_Mid_Lissandra(Ratings): pass class NA_Fiora_Mid_Lucian(Ratings): pass class NA_Fiora_Mid_Lulu(Ratings): pass class NA_Fiora_Mid_Lux(Ratings): pass",
"NA_Fiora_Mid_Pantheon(Ratings): pass class NA_Fiora_Mid_Poppy(Ratings): pass class NA_Fiora_Mid_Quinn(Ratings): pass class NA_Fiora_Mid_Rakan(Ratings): pass class NA_Fiora_Mid_Rammus(Ratings):",
"class NA_Fiora_Mid_Swain(Ratings): pass class NA_Fiora_Mid_Syndra(Ratings): pass class NA_Fiora_Mid_TahmKench(Ratings): pass class NA_Fiora_Mid_Taliyah(Ratings): pass class",
"class NA_Fiora_Mid_Maokai(Ratings): pass class NA_Fiora_Mid_MasterYi(Ratings): pass class NA_Fiora_Mid_MissFortune(Ratings): pass class NA_Fiora_Mid_MonkeyKing(Ratings): pass class",
"NA_Fiora_Mid_Swain(Ratings): pass class NA_Fiora_Mid_Syndra(Ratings): pass class NA_Fiora_Mid_TahmKench(Ratings): pass class NA_Fiora_Mid_Taliyah(Ratings): pass class NA_Fiora_Mid_Talon(Ratings):",
"pass class NA_Fiora_Mid_MasterYi(Ratings): pass class NA_Fiora_Mid_MissFortune(Ratings): pass class NA_Fiora_Mid_MonkeyKing(Ratings): pass class NA_Fiora_Mid_Mordekaiser(Ratings): pass",
"NA_Fiora_Mid_Darius(Ratings): pass class NA_Fiora_Mid_Diana(Ratings): pass class NA_Fiora_Mid_Draven(Ratings): pass class NA_Fiora_Mid_DrMundo(Ratings): pass class NA_Fiora_Mid_Ekko(Ratings):",
"pass class NA_Fiora_Mid_Gnar(Ratings): pass class NA_Fiora_Mid_Gragas(Ratings): pass class NA_Fiora_Mid_Graves(Ratings): pass class NA_Fiora_Mid_Hecarim(Ratings): pass",
"class NA_Fiora_Mid_Olaf(Ratings): pass class NA_Fiora_Mid_Orianna(Ratings): pass class NA_Fiora_Mid_Ornn(Ratings): pass class NA_Fiora_Mid_Pantheon(Ratings): pass class",
"pass class NA_Fiora_Mid_Bard(Ratings): pass class NA_Fiora_Mid_Blitzcrank(Ratings): pass class NA_Fiora_Mid_Brand(Ratings): pass class NA_Fiora_Mid_Braum(Ratings): pass",
"pass class NA_Fiora_Mid_Thresh(Ratings): pass class NA_Fiora_Mid_Tristana(Ratings): pass class NA_Fiora_Mid_Trundle(Ratings): pass class NA_Fiora_Mid_Tryndamere(Ratings): pass",
"NA_Fiora_Mid_Azir(Ratings): pass class NA_Fiora_Mid_Bard(Ratings): pass class NA_Fiora_Mid_Blitzcrank(Ratings): pass class NA_Fiora_Mid_Brand(Ratings): pass class NA_Fiora_Mid_Braum(Ratings):",
"NA_Fiora_Mid_Garen(Ratings): pass class NA_Fiora_Mid_Gnar(Ratings): pass class NA_Fiora_Mid_Gragas(Ratings): pass class NA_Fiora_Mid_Graves(Ratings): pass class NA_Fiora_Mid_Hecarim(Ratings):",
"pass class NA_Fiora_Mid_Hecarim(Ratings): pass class NA_Fiora_Mid_Heimerdinger(Ratings): pass class NA_Fiora_Mid_Illaoi(Ratings): pass class NA_Fiora_Mid_Irelia(Ratings): pass",
"NA_Fiora_Mid_Kassadin(Ratings): pass class NA_Fiora_Mid_Katarina(Ratings): pass class NA_Fiora_Mid_Kayle(Ratings): pass class NA_Fiora_Mid_Kayn(Ratings): pass class NA_Fiora_Mid_Kennen(Ratings):",
"class NA_Fiora_Mid_Quinn(Ratings): pass class NA_Fiora_Mid_Rakan(Ratings): pass class NA_Fiora_Mid_Rammus(Ratings): pass class NA_Fiora_Mid_RekSai(Ratings): pass class",
"NA_Fiora_Mid_Kled(Ratings): pass class NA_Fiora_Mid_KogMaw(Ratings): pass class NA_Fiora_Mid_Leblanc(Ratings): pass class NA_Fiora_Mid_LeeSin(Ratings): pass class NA_Fiora_Mid_Leona(Ratings):",
"class NA_Fiora_Mid_Tristana(Ratings): pass class NA_Fiora_Mid_Trundle(Ratings): pass class NA_Fiora_Mid_Tryndamere(Ratings): pass class NA_Fiora_Mid_TwistedFate(Ratings): pass class",
"class NA_Fiora_Mid_Poppy(Ratings): pass class NA_Fiora_Mid_Quinn(Ratings): pass class NA_Fiora_Mid_Rakan(Ratings): pass class NA_Fiora_Mid_Rammus(Ratings): pass class",
"NA_Fiora_Mid_RekSai(Ratings): pass class NA_Fiora_Mid_Renekton(Ratings): pass class NA_Fiora_Mid_Rengar(Ratings): pass class NA_Fiora_Mid_Riven(Ratings): pass class NA_Fiora_Mid_Rumble(Ratings):",
"class NA_Fiora_Mid_Soraka(Ratings): pass class NA_Fiora_Mid_Swain(Ratings): pass class NA_Fiora_Mid_Syndra(Ratings): pass class NA_Fiora_Mid_TahmKench(Ratings): pass class",
"class NA_Fiora_Mid_Ahri(Ratings): pass class NA_Fiora_Mid_Akali(Ratings): pass class NA_Fiora_Mid_Alistar(Ratings): pass class NA_Fiora_Mid_Amumu(Ratings): pass class",
"NA_Fiora_Mid_DrMundo(Ratings): pass class NA_Fiora_Mid_Ekko(Ratings): pass class NA_Fiora_Mid_Elise(Ratings): pass class NA_Fiora_Mid_Evelynn(Ratings): pass class NA_Fiora_Mid_Ezreal(Ratings):",
"class NA_Fiora_Mid_Aatrox(Ratings): pass class NA_Fiora_Mid_Ahri(Ratings): pass class NA_Fiora_Mid_Akali(Ratings): pass class NA_Fiora_Mid_Alistar(Ratings): pass class",
"NA_Fiora_Mid_Maokai(Ratings): pass class NA_Fiora_Mid_MasterYi(Ratings): pass class NA_Fiora_Mid_MissFortune(Ratings): pass class NA_Fiora_Mid_MonkeyKing(Ratings): pass class NA_Fiora_Mid_Mordekaiser(Ratings):",
"NA_Fiora_Mid_Corki(Ratings): pass class NA_Fiora_Mid_Darius(Ratings): pass class NA_Fiora_Mid_Diana(Ratings): pass class NA_Fiora_Mid_Draven(Ratings): pass class NA_Fiora_Mid_DrMundo(Ratings):",
"NA_Fiora_Mid_Malphite(Ratings): pass class NA_Fiora_Mid_Malzahar(Ratings): pass class NA_Fiora_Mid_Maokai(Ratings): pass class NA_Fiora_Mid_MasterYi(Ratings): pass class NA_Fiora_Mid_MissFortune(Ratings):",
"class NA_Fiora_Mid_Renekton(Ratings): pass class NA_Fiora_Mid_Rengar(Ratings): pass class NA_Fiora_Mid_Riven(Ratings): pass class NA_Fiora_Mid_Rumble(Ratings): pass class",
"NA_Fiora_Mid_XinZhao(Ratings): pass class NA_Fiora_Mid_Yasuo(Ratings): pass class NA_Fiora_Mid_Yorick(Ratings): pass class NA_Fiora_Mid_Zac(Ratings): pass class NA_Fiora_Mid_Zed(Ratings):",
"class NA_Fiora_Mid_Akali(Ratings): pass class NA_Fiora_Mid_Alistar(Ratings): pass class NA_Fiora_Mid_Amumu(Ratings): pass class NA_Fiora_Mid_Anivia(Ratings): pass class",
"NA_Fiora_Mid_Illaoi(Ratings): pass class NA_Fiora_Mid_Irelia(Ratings): pass class NA_Fiora_Mid_Ivern(Ratings): pass class NA_Fiora_Mid_Janna(Ratings): pass class NA_Fiora_Mid_JarvanIV(Ratings):",
"NA_Fiora_Mid_Nasus(Ratings): pass class NA_Fiora_Mid_Nautilus(Ratings): pass class NA_Fiora_Mid_Nidalee(Ratings): pass class NA_Fiora_Mid_Nocturne(Ratings): pass class NA_Fiora_Mid_Nunu(Ratings):",
"class NA_Fiora_Mid_Yasuo(Ratings): pass class NA_Fiora_Mid_Yorick(Ratings): pass class NA_Fiora_Mid_Zac(Ratings): pass class NA_Fiora_Mid_Zed(Ratings): pass class",
"class NA_Fiora_Mid_Leona(Ratings): pass class NA_Fiora_Mid_Lissandra(Ratings): pass class NA_Fiora_Mid_Lucian(Ratings): pass class NA_Fiora_Mid_Lulu(Ratings): pass class",
"class NA_Fiora_Mid_Malphite(Ratings): pass class NA_Fiora_Mid_Malzahar(Ratings): pass class NA_Fiora_Mid_Maokai(Ratings): pass class NA_Fiora_Mid_MasterYi(Ratings): pass class",
"class NA_Fiora_Mid_Tryndamere(Ratings): pass class NA_Fiora_Mid_TwistedFate(Ratings): pass class NA_Fiora_Mid_Twitch(Ratings): pass class NA_Fiora_Mid_Udyr(Ratings): pass class",
"pass class NA_Fiora_Mid_Ornn(Ratings): pass class NA_Fiora_Mid_Pantheon(Ratings): pass class NA_Fiora_Mid_Poppy(Ratings): pass class NA_Fiora_Mid_Quinn(Ratings): pass"
] |
[
"ProcessDoc: def __init__(self, path, lemma, stem): self.collection_dic = {} self.doc_info = [] self.lemma",
"{} self.doc_info = [] self.lemma = lemma self.stem = stem self.path = path",
"class ProcessDoc: def __init__(self, path, lemma, stem): self.collection_dic = {} self.doc_info = []",
"= self.load_file(os.path.join(self.path, filename)) for key, value in doc_dic.items(): # add token to dictionary",
"value, doclen, max_tf]) def load_file(self, url): # parse xml doc from the url",
"parse xml doc from the url mydoc = minidom.parse(url) # read doc NO",
"run(self): for filename in os.listdir(self.path): doc_no, doclen, max_tf, doc_dic = self.load_file(os.path.join(self.path, filename)) for",
"read doc text file text = mydoc.getElementsByTagName('TEXT')[0] data = text.firstChild.data token = Token.Token()",
"mydoc = minidom.parse(url) # read doc NO doc = mydoc.getElementsByTagName('DOCNO')[0] doc_no = int(doc.firstChild.data)",
"import minidom class ProcessDoc: def __init__(self, path, lemma, stem): self.collection_dic = {} self.doc_info",
"path, lemma, stem): self.collection_dic = {} self.doc_info = [] self.lemma = lemma self.stem",
"value in doc_dic.items(): # add token to dictionary if not exist if key",
"one if exist in the dictionary else: self.collection_dic[key][0] += 1 self.collection_dic[key][1] += value",
"doc_dic = self.load_file(os.path.join(self.path, filename)) for key, value in doc_dic.items(): # add token to",
"not in self.collection_dic: self.collection_dic[key] = [1, value, [doc_no, value, doclen, max_tf]] # increase",
"text = mydoc.getElementsByTagName('TEXT')[0] data = text.firstChild.data token = Token.Token() if self.lemma == 1:",
"doc_no, doclen, max_tf, doc_dic = self.load_file(os.path.join(self.path, filename)) for key, value in doc_dic.items(): #",
"increase the frequency by one if exist in the dictionary else: self.collection_dic[key][0] +=",
"self.collection_dic[key] = [1, value, [doc_no, value, doclen, max_tf]] # increase the frequency by",
"+= value self.collection_dic[key].append([doc_no, value, doclen, max_tf]) def load_file(self, url): # parse xml doc",
"[] self.lemma = lemma self.stem = stem self.path = path def run(self): for",
"file text = mydoc.getElementsByTagName('TEXT')[0] data = text.firstChild.data token = Token.Token() if self.lemma ==",
"in doc_dic.items(): # add token to dictionary if not exist if key not",
"mydoc.getElementsByTagName('TEXT')[0] data = text.firstChild.data token = Token.Token() if self.lemma == 1: token.apply_lemma() elif",
"self.collection_dic = {} self.doc_info = [] self.lemma = lemma self.stem = stem self.path",
"dictionary if not exist if key not in self.collection_dic: self.collection_dic[key] = [1, value,",
"by one if exist in the dictionary else: self.collection_dic[key][0] += 1 self.collection_dic[key][1] +=",
"for filename in os.listdir(self.path): doc_no, doclen, max_tf, doc_dic = self.load_file(os.path.join(self.path, filename)) for key,",
"xml doc from the url mydoc = minidom.parse(url) # read doc NO doc",
"doc = mydoc.getElementsByTagName('DOCNO')[0] doc_no = int(doc.firstChild.data) # read doc text file text =",
"doclen, max_tf]] # increase the frequency by one if exist in the dictionary",
"self.load_file(os.path.join(self.path, filename)) for key, value in doc_dic.items(): # add token to dictionary if",
"__init__(self, path, lemma, stem): self.collection_dic = {} self.doc_info = [] self.lemma = lemma",
"from the url mydoc = minidom.parse(url) # read doc NO doc = mydoc.getElementsByTagName('DOCNO')[0]",
"max_tf]] # increase the frequency by one if exist in the dictionary else:",
"not exist if key not in self.collection_dic: self.collection_dic[key] = [1, value, [doc_no, value,",
"text.firstChild.data token = Token.Token() if self.lemma == 1: token.apply_lemma() elif self.stem == 1:",
"os import Token from xml.dom import minidom class ProcessDoc: def __init__(self, path, lemma,",
"data = text.firstChild.data token = Token.Token() if self.lemma == 1: token.apply_lemma() elif self.stem",
"exist if key not in self.collection_dic: self.collection_dic[key] = [1, value, [doc_no, value, doclen,",
"= mydoc.getElementsByTagName('DOCNO')[0] doc_no = int(doc.firstChild.data) # read doc text file text = mydoc.getElementsByTagName('TEXT')[0]",
"= path def run(self): for filename in os.listdir(self.path): doc_no, doclen, max_tf, doc_dic =",
"= Token.Token() if self.lemma == 1: token.apply_lemma() elif self.stem == 1: token.apply_stemming() return",
"frequency by one if exist in the dictionary else: self.collection_dic[key][0] += 1 self.collection_dic[key][1]",
"minidom.parse(url) # read doc NO doc = mydoc.getElementsByTagName('DOCNO')[0] doc_no = int(doc.firstChild.data) # read",
"if self.lemma == 1: token.apply_lemma() elif self.stem == 1: token.apply_stemming() return token.tokenize(data, doc_no)",
"self.collection_dic[key][1] += value self.collection_dic[key].append([doc_no, value, doclen, max_tf]) def load_file(self, url): # parse xml",
"key, value in doc_dic.items(): # add token to dictionary if not exist if",
"Token from xml.dom import minidom class ProcessDoc: def __init__(self, path, lemma, stem): self.collection_dic",
"else: self.collection_dic[key][0] += 1 self.collection_dic[key][1] += value self.collection_dic[key].append([doc_no, value, doclen, max_tf]) def load_file(self,",
"int(doc.firstChild.data) # read doc text file text = mydoc.getElementsByTagName('TEXT')[0] data = text.firstChild.data token",
"lemma self.stem = stem self.path = path def run(self): for filename in os.listdir(self.path):",
"self.collection_dic[key].append([doc_no, value, doclen, max_tf]) def load_file(self, url): # parse xml doc from the",
"= mydoc.getElementsByTagName('TEXT')[0] data = text.firstChild.data token = Token.Token() if self.lemma == 1: token.apply_lemma()",
"url mydoc = minidom.parse(url) # read doc NO doc = mydoc.getElementsByTagName('DOCNO')[0] doc_no =",
"text file text = mydoc.getElementsByTagName('TEXT')[0] data = text.firstChild.data token = Token.Token() if self.lemma",
"url): # parse xml doc from the url mydoc = minidom.parse(url) # read",
"os.listdir(self.path): doc_no, doclen, max_tf, doc_dic = self.load_file(os.path.join(self.path, filename)) for key, value in doc_dic.items():",
"filename)) for key, value in doc_dic.items(): # add token to dictionary if not",
"stem self.path = path def run(self): for filename in os.listdir(self.path): doc_no, doclen, max_tf,",
"= {} self.doc_info = [] self.lemma = lemma self.stem = stem self.path =",
"doc text file text = mydoc.getElementsByTagName('TEXT')[0] data = text.firstChild.data token = Token.Token() if",
"read doc NO doc = mydoc.getElementsByTagName('DOCNO')[0] doc_no = int(doc.firstChild.data) # read doc text",
"import os import Token from xml.dom import minidom class ProcessDoc: def __init__(self, path,",
"dictionary else: self.collection_dic[key][0] += 1 self.collection_dic[key][1] += value self.collection_dic[key].append([doc_no, value, doclen, max_tf]) def",
"exist in the dictionary else: self.collection_dic[key][0] += 1 self.collection_dic[key][1] += value self.collection_dic[key].append([doc_no, value,",
"if key not in self.collection_dic: self.collection_dic[key] = [1, value, [doc_no, value, doclen, max_tf]]",
"filename in os.listdir(self.path): doc_no, doclen, max_tf, doc_dic = self.load_file(os.path.join(self.path, filename)) for key, value",
"stem): self.collection_dic = {} self.doc_info = [] self.lemma = lemma self.stem = stem",
"if exist in the dictionary else: self.collection_dic[key][0] += 1 self.collection_dic[key][1] += value self.collection_dic[key].append([doc_no,",
"# parse xml doc from the url mydoc = minidom.parse(url) # read doc",
"max_tf]) def load_file(self, url): # parse xml doc from the url mydoc =",
"in the dictionary else: self.collection_dic[key][0] += 1 self.collection_dic[key][1] += value self.collection_dic[key].append([doc_no, value, doclen,",
"+= 1 self.collection_dic[key][1] += value self.collection_dic[key].append([doc_no, value, doclen, max_tf]) def load_file(self, url): #",
"doc NO doc = mydoc.getElementsByTagName('DOCNO')[0] doc_no = int(doc.firstChild.data) # read doc text file",
"in self.collection_dic: self.collection_dic[key] = [1, value, [doc_no, value, doclen, max_tf]] # increase the",
"value self.collection_dic[key].append([doc_no, value, doclen, max_tf]) def load_file(self, url): # parse xml doc from",
"# read doc NO doc = mydoc.getElementsByTagName('DOCNO')[0] doc_no = int(doc.firstChild.data) # read doc",
"mydoc.getElementsByTagName('DOCNO')[0] doc_no = int(doc.firstChild.data) # read doc text file text = mydoc.getElementsByTagName('TEXT')[0] data",
"minidom class ProcessDoc: def __init__(self, path, lemma, stem): self.collection_dic = {} self.doc_info =",
"load_file(self, url): # parse xml doc from the url mydoc = minidom.parse(url) #",
"= text.firstChild.data token = Token.Token() if self.lemma == 1: token.apply_lemma() elif self.stem ==",
"= minidom.parse(url) # read doc NO doc = mydoc.getElementsByTagName('DOCNO')[0] doc_no = int(doc.firstChild.data) #",
"self.stem = stem self.path = path def run(self): for filename in os.listdir(self.path): doc_no,",
"doc from the url mydoc = minidom.parse(url) # read doc NO doc =",
"= stem self.path = path def run(self): for filename in os.listdir(self.path): doc_no, doclen,",
"self.collection_dic: self.collection_dic[key] = [1, value, [doc_no, value, doclen, max_tf]] # increase the frequency",
"lemma, stem): self.collection_dic = {} self.doc_info = [] self.lemma = lemma self.stem =",
"= int(doc.firstChild.data) # read doc text file text = mydoc.getElementsByTagName('TEXT')[0] data = text.firstChild.data",
"the dictionary else: self.collection_dic[key][0] += 1 self.collection_dic[key][1] += value self.collection_dic[key].append([doc_no, value, doclen, max_tf])",
"doc_dic.items(): # add token to dictionary if not exist if key not in",
"= [1, value, [doc_no, value, doclen, max_tf]] # increase the frequency by one",
"self.lemma = lemma self.stem = stem self.path = path def run(self): for filename",
"def load_file(self, url): # parse xml doc from the url mydoc = minidom.parse(url)",
"self.collection_dic[key][0] += 1 self.collection_dic[key][1] += value self.collection_dic[key].append([doc_no, value, doclen, max_tf]) def load_file(self, url):",
"self.doc_info = [] self.lemma = lemma self.stem = stem self.path = path def",
"token = Token.Token() if self.lemma == 1: token.apply_lemma() elif self.stem == 1: token.apply_stemming()",
"= lemma self.stem = stem self.path = path def run(self): for filename in",
"from xml.dom import minidom class ProcessDoc: def __init__(self, path, lemma, stem): self.collection_dic =",
"the frequency by one if exist in the dictionary else: self.collection_dic[key][0] += 1",
"1 self.collection_dic[key][1] += value self.collection_dic[key].append([doc_no, value, doclen, max_tf]) def load_file(self, url): # parse",
"doclen, max_tf, doc_dic = self.load_file(os.path.join(self.path, filename)) for key, value in doc_dic.items(): # add",
"def run(self): for filename in os.listdir(self.path): doc_no, doclen, max_tf, doc_dic = self.load_file(os.path.join(self.path, filename))",
"the url mydoc = minidom.parse(url) # read doc NO doc = mydoc.getElementsByTagName('DOCNO')[0] doc_no",
"key not in self.collection_dic: self.collection_dic[key] = [1, value, [doc_no, value, doclen, max_tf]] #",
"def __init__(self, path, lemma, stem): self.collection_dic = {} self.doc_info = [] self.lemma =",
"for key, value in doc_dic.items(): # add token to dictionary if not exist",
"token to dictionary if not exist if key not in self.collection_dic: self.collection_dic[key] =",
"import Token from xml.dom import minidom class ProcessDoc: def __init__(self, path, lemma, stem):",
"value, [doc_no, value, doclen, max_tf]] # increase the frequency by one if exist",
"self.path = path def run(self): for filename in os.listdir(self.path): doc_no, doclen, max_tf, doc_dic",
"add token to dictionary if not exist if key not in self.collection_dic: self.collection_dic[key]",
"Token.Token() if self.lemma == 1: token.apply_lemma() elif self.stem == 1: token.apply_stemming() return token.tokenize(data,",
"path def run(self): for filename in os.listdir(self.path): doc_no, doclen, max_tf, doc_dic = self.load_file(os.path.join(self.path,",
"if not exist if key not in self.collection_dic: self.collection_dic[key] = [1, value, [doc_no,",
"max_tf, doc_dic = self.load_file(os.path.join(self.path, filename)) for key, value in doc_dic.items(): # add token",
"value, doclen, max_tf]] # increase the frequency by one if exist in the",
"# increase the frequency by one if exist in the dictionary else: self.collection_dic[key][0]",
"# read doc text file text = mydoc.getElementsByTagName('TEXT')[0] data = text.firstChild.data token =",
"NO doc = mydoc.getElementsByTagName('DOCNO')[0] doc_no = int(doc.firstChild.data) # read doc text file text",
"xml.dom import minidom class ProcessDoc: def __init__(self, path, lemma, stem): self.collection_dic = {}",
"[1, value, [doc_no, value, doclen, max_tf]] # increase the frequency by one if",
"# add token to dictionary if not exist if key not in self.collection_dic:",
"to dictionary if not exist if key not in self.collection_dic: self.collection_dic[key] = [1,",
"doclen, max_tf]) def load_file(self, url): # parse xml doc from the url mydoc",
"doc_no = int(doc.firstChild.data) # read doc text file text = mydoc.getElementsByTagName('TEXT')[0] data =",
"in os.listdir(self.path): doc_no, doclen, max_tf, doc_dic = self.load_file(os.path.join(self.path, filename)) for key, value in",
"[doc_no, value, doclen, max_tf]] # increase the frequency by one if exist in",
"= [] self.lemma = lemma self.stem = stem self.path = path def run(self):"
] |
[
"elif i['emotion']['anger'] > maximum: maximum = i['emotion']['anger'] keywords_sentiments_emotions_buffer['emotion'] = 'anger' keywords_sentiments_emotions.append( keywords_sentiments_emotions_buffer) myJsonDict.update({\"sentiments\":",
"stopwords = set(STOPWORDS) for val in verbs: val = str(val) tokens = val.split()",
"plt.axis(\"off\") plt.tight_layout(pad=0) plt.savefig(nounsAdjWC, title=True) wordclouds = [nounsAdjWC, verbsWC] myJsonDict.update({\"wordclouds\": wordclouds}) except: myJsonDict.update({\"wordclouds\": \"Text",
"ibm_cloud_sdk_core.authenticators import IAMAuthenticator from flask import request, jsonify from operator import itemgetter from",
"key=itemgetter('relevance'), reverse=True) keywords_sentiments_emotions = [] for i in keywords: keywords_sentiments_emotions_buffer = { 'keyword':",
"''' Extract Concepts with NLU ''' if options.get('concepts') == \"True\": try: response =",
"except: myJsonDict.update({\"sentiments\": \"Text too small to extract sentiments\"}) else: pass ''' Analyse tone",
"options.get('category') == \"True\": try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(categories=CategoriesOptions(limit=1))).get_result() category = response['categories'][0]",
"text_file.read() ''' Initialize a return variable ''' myJsonDict = {} ''' Extract Category",
"keywords_sentiments_emotions_buffer['emotion'] = 'anger' keywords_sentiments_emotions.append( keywords_sentiments_emotions_buffer) myJsonDict.update({\"sentiments\": keywords_sentiments_emotions}) except: myJsonDict.update({\"sentiments\": \"Text too small to",
"sentiments\"}) else: pass ''' Analyse tone to get top 5 positive sentences '''",
"NLU ''' if options.get('entity') == \"True\": try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(entities=EntitiesOptions(limit=1))).get_result()",
"range(len(tokens)): tokens[i] = tokens[i].lower() for words in tokens: comment_words_verbs = comment_words_verbs + words",
"' ' stopwords = set(STOPWORDS) for val in verbs: val = str(val) tokens",
"small to extract concepts\"}) else: pass ''' Extract Entity with NLU ''' if",
"title=True) wordclouds = [nounsAdjWC, verbsWC] myJsonDict.update({\"wordclouds\": wordclouds}) except: myJsonDict.update({\"wordclouds\": \"Text too small to",
"in range(len(tokens)): tokens[i] = tokens[i].lower() for words in tokens: comment_words_nouns_adj = comment_words_nouns_adj +",
"i['emotion']['disgust'] > maximum: maximum = i['emotion']['disgust'] keywords_sentiments_emotions_buffer['emotion'] = 'disguest' elif i['emotion']['anger'] > maximum:",
"credentials2.get('apikey') self.TONE_URL = credentials2.get('url') tone_analyzer_authenticator = IAMAuthenticator(self.TONE_API_KEY_ID) tone_analyzer = ToneAnalyzerV3( version='2017-09-21', authenticator=tone_analyzer_authenticator )",
"extract category\"}) else: pass ''' Extract Concepts with NLU ''' if options.get('concepts') ==",
"\"\" TONE_URL = \"\" def __init__(self): try: with open('naturallanguageunderstanding.json', 'r') as credentialsFile: credentials1",
"document.', \"score\": '100'} myJsonDict.update( {\"positiveSentences\": [tempDict]}) # return sentences_with_joy[:5] ['text'] ['score'] else: pass",
"keywords_sentiments_emotions_buffer['emotion'] = 'fear' elif i['emotion']['disgust'] > maximum: maximum = i['emotion']['disgust'] keywords_sentiments_emotions_buffer['emotion'] = 'disguest'",
"sentences=True, tokens=SyntaxOptionsTokens( lemma=True, part_of_speech=True, )))).get_result() verbs = [] for i in response['syntax']['tokens']: if",
"= natural_language_understanding except json.decoder.JSONDecodeError: print(\"Natural Language Understanding credentials file is empty, please enter",
"enter the credentials and try again.\") try: with open('toneanalyzer.json', 'r') as credentialsFile: credentials2",
"myJsonDict.update({\"entity\": \"Text too small to extract entity\"}) else: pass ''' Extract Sentiments and",
"= body.get('filename') ''' Prepare the text for Analysis''' with open('static/transcripts/'+fileName, 'r') as text_file:",
"except: tempDict = {\"sentence_id\": '', \"text\": 'Text file too small to get positive",
"myJsonDict.update({\"category\": \"Text too small to extract category\"}) else: pass ''' Extract Concepts with",
"plt.savefig(verbsWC, title=True) nounsAdjWC = \"static/images/nouns_adjectives\"+todayDate+'.png' plt.switch_backend('Agg') plt.figure(figsize=(5, 5), facecolor=None) plt.imshow(wordcloud_nouns_adj) plt.axis(\"off\") plt.tight_layout(pad=0) plt.savefig(nounsAdjWC,",
"if options.get('concepts') == \"True\": try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(concepts=ConceptsOptions(limit=3))).get_result() concepts =",
"text=text, features=Features(keywords=KeywordsOptions(sentiment=True, emotion=True, limit=10))).get_result() keywords = sorted(response['keywords'], key=itemgetter('relevance'), reverse=True) keywords_sentiments_emotions = [] for",
"entity = sorted(response['entities'], key=itemgetter('relevance'), reverse=True) myJsonDict.update({\"entity\": entity[0]}) except: myJsonDict.update({\"entity\": \"Text too small to",
"'joy' elif i['emotion']['fear'] > maximum: maximum = i['emotion']['fear'] keywords_sentiments_emotions_buffer['emotion'] = 'fear' elif i['emotion']['disgust']",
"' ' wordcloud_verbs = WordCloud(width=800, height=800, background_color='white', stopwords=stopwords, min_font_size=10, max_font_size=150, random_state=42).generate(comment_words_verbs) wordcloud_nouns_adj =",
"text=text, features=Features(categories=CategoriesOptions(limit=1))).get_result() category = response['categories'][0] myJsonDict.update({\"category\": category}) except: myJsonDict.update({\"category\": \"Text too small to",
"for tone in tone_analysis['sentences_tone']: try: if tone['tones'][0]['tone_name'] == \"Joy\": tempDict = {\"sentence_id\": tone['sentence_id'],",
"\"score\": '100'} myJsonDict.update( {\"positiveSentences\": [tempDict]}) # return sentences_with_joy[:5] ['text'] ['score'] else: pass '''",
"Features, EntitiesOptions, KeywordsOptions, \\ SyntaxOptions, SyntaxOptionsTokens, CategoriesOptions, ConceptsOptions from ibm_cloud_sdk_core.authenticators import IAMAuthenticator from",
"json.decoder.JSONDecodeError: print(\"Natural Language Understanding credentials file is empty, please enter the credentials and",
"myJsonDict.update( {\"positiveSentences\": sentences_with_joy[:5]}) except: tempDict = {\"sentence_id\": '', \"text\": 'Text file too small",
"extract sentiments\"}) else: pass ''' Analyse tone to get top 5 positive sentences",
"''' if options.get('concepts') == \"True\": try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(concepts=ConceptsOptions(limit=3))).get_result() concepts",
"''' if options.get('entity') == \"True\": try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(entities=EntitiesOptions(limit=1))).get_result() entity",
"= json.loads(request.get_data()) options = body fileName = body.get('filename') ''' Prepare the text for",
"i['emotion']['fear'] > maximum: maximum = i['emotion']['fear'] keywords_sentiments_emotions_buffer['emotion'] = 'fear' elif i['emotion']['disgust'] > maximum:",
"self.tone_analyzer = tone_analyzer except json.decoder.JSONDecodeError: print(\"Tone Analyzer credentials file is empty, please enter",
"IAMAuthenticator from flask import request, jsonify from operator import itemgetter from wordcloud import",
"comment_words_verbs = ' ' comment_words_nouns_adj = ' ' stopwords = set(STOPWORDS) for val",
"speech to plot Word Cloud ''' try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(",
"sorted( sentences_with_joy, key=itemgetter('score'), reverse=True) myJsonDict.update( {\"positiveSentences\": sentences_with_joy[:5]}) except: tempDict = {\"sentence_id\": '', \"text\":",
"val.split() for i in range(len(tokens)): tokens[i] = tokens[i].lower() for words in tokens: comment_words_verbs",
"''' Initialize a return variable ''' myJsonDict = {} ''' Extract Category with",
"todayDate = datetime.today().strftime('%m-%d-%Y-%s') verbsWC = \"static/images/verbs\"+todayDate+'.png' plt.switch_backend('Agg') plt.figure(figsize=(5, 5), facecolor=None) plt.imshow(wordcloud_verbs) plt.axis(\"off\") plt.tight_layout(pad=0)",
"elif i['emotion']['fear'] > maximum: maximum = i['emotion']['fear'] keywords_sentiments_emotions_buffer['emotion'] = 'fear' elif i['emotion']['disgust'] >",
"\"Text too small to extract category\"}) else: pass ''' Extract Concepts with NLU",
"= json.loads(credentialsFile.read()) self.TONE_API_KEY_ID = credentials2.get('apikey') self.TONE_URL = credentials2.get('url') tone_analyzer_authenticator = IAMAuthenticator(self.TONE_API_KEY_ID) tone_analyzer =",
"tone['text'], \"score\": tone['tones'][0]['score']} sentences_with_joy.append(tempDict) except: continue sentences_with_joy = sorted( sentences_with_joy, key=itemgetter('score'), reverse=True) myJsonDict.update(",
"== \"True\": try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(entities=EntitiesOptions(limit=1))).get_result() entity = sorted(response['entities'], key=itemgetter('relevance'),",
"# print(json.dumps(tone_analysis, indent=2)) try: for tone in tone_analysis['sentences_tone']: try: if tone['tones'][0]['tone_name'] == \"Joy\":",
"concepts}) except: myJsonDict.update({\"concepts\": \"Text too small to extract concepts\"}) else: pass ''' Extract",
"features=Features(categories=CategoriesOptions(limit=1))).get_result() category = response['categories'][0] myJsonDict.update({\"category\": category}) except: myJsonDict.update({\"category\": \"Text too small to extract",
"Word Cloud ''' try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features( syntax=SyntaxOptions( sentences=True, tokens=SyntaxOptionsTokens(",
"i['part_of_speech'] == 'ADJ': adj.append(i['text']) nouns_adjectives = [] for x in nouns: nouns_adjectives.append(x) for",
"> maximum: maximum = i['emotion']['joy'] keywords_sentiments_emotions_buffer['emotion'] = 'joy' elif i['emotion']['fear'] > maximum: maximum",
"= i['emotion']['anger'] keywords_sentiments_emotions_buffer['emotion'] = 'anger' keywords_sentiments_emotions.append( keywords_sentiments_emotions_buffer) myJsonDict.update({\"sentiments\": keywords_sentiments_emotions}) except: myJsonDict.update({\"sentiments\": \"Text too",
"self.NLU_API_KEY_ID = credentials1.get('apikey') self.NLU_URL = credentials1.get('url') nlu_authenticator = IAMAuthenticator(self.NLU_API_KEY_ID) natural_language_understanding = NaturalLanguageUnderstandingV1( version='2021-08-01',",
"empty, please enter the credentials and try again.\") try: with open('toneanalyzer.json', 'r') as",
"\"True\": try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(keywords=KeywordsOptions(sentiment=True, emotion=True, limit=10))).get_result() keywords = sorted(response['keywords'],",
"= datetime.today().strftime('%m-%d-%Y-%s') verbsWC = \"static/images/verbs\"+todayDate+'.png' plt.switch_backend('Agg') plt.figure(figsize=(5, 5), facecolor=None) plt.imshow(wordcloud_verbs) plt.axis(\"off\") plt.tight_layout(pad=0) plt.savefig(verbsWC,",
"credentials file is empty, please enter the credentials and try again.\") def get(self):",
"nouns_adjectives.append(y) comment_words_verbs = ' ' comment_words_nouns_adj = ' ' stopwords = set(STOPWORDS) for",
"Extract Entity with NLU ''' if options.get('entity') == \"True\": try: response = self.natural_language_understanding.analyze(",
"\"Text too small to extract concepts\"}) else: pass ''' Extract Entity with NLU",
").get_result() sentences_with_joy = [] # print(json.dumps(tone_analysis, indent=2)) try: for tone in tone_analysis['sentences_tone']: try:",
"if i['part_of_speech'] == 'VERB': verbs.append(i['text']) nouns = [] for i in response['syntax']['tokens']: if",
"i['text'], 'sentiment': i['sentiment']['label'], 'emotion': '' } maximum = i['emotion']['sadness'] keywords_sentiments_emotions_buffer['emotion'] = 'sadness' if",
"== 'ADJ': adj.append(i['text']) nouns_adjectives = [] for x in nouns: nouns_adjectives.append(x) for y",
"try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(categories=CategoriesOptions(limit=1))).get_result() category = response['categories'][0] myJsonDict.update({\"category\": category}) except:",
"val in verbs: val = str(val) tokens = val.split() for i in range(len(tokens)):",
"concepts\"}) else: pass ''' Extract Entity with NLU ''' if options.get('entity') == \"True\":",
"wordcloud import WordCloud, STOPWORDS import matplotlib.pyplot as plt from datetime import datetime class",
"the credentials and try again.\") def get(self): pass def post(self): if request.method ==",
"'' } maximum = i['emotion']['sadness'] keywords_sentiments_emotions_buffer['emotion'] = 'sadness' if i['emotion']['joy'] > maximum: maximum",
"elif i['emotion']['disgust'] > maximum: maximum = i['emotion']['disgust'] keywords_sentiments_emotions_buffer['emotion'] = 'disguest' elif i['emotion']['anger'] >",
"comment_words_nouns_adj + words + ' ' wordcloud_verbs = WordCloud(width=800, height=800, background_color='white', stopwords=stopwords, min_font_size=10,",
"in nouns: nouns_adjectives.append(x) for y in adj: nouns_adjectives.append(y) comment_words_verbs = ' ' comment_words_nouns_adj",
"plt.figure(figsize=(5, 5), facecolor=None) plt.imshow(wordcloud_nouns_adj) plt.axis(\"off\") plt.tight_layout(pad=0) plt.savefig(nounsAdjWC, title=True) wordclouds = [nounsAdjWC, verbsWC] myJsonDict.update({\"wordclouds\":",
"too small to extract category\"}) else: pass ''' Extract Concepts with NLU '''",
") natural_language_understanding.set_service_url(self.NLU_URL) self.natural_language_understanding = natural_language_understanding except json.decoder.JSONDecodeError: print(\"Natural Language Understanding credentials file is",
"= {\"sentence_id\": tone['sentence_id'], \"text\": tone['text'], \"score\": tone['tones'][0]['score']} sentences_with_joy.append(tempDict) except: continue sentences_with_joy = sorted(",
"'sentiment': i['sentiment']['label'], 'emotion': '' } maximum = i['emotion']['sadness'] keywords_sentiments_emotions_buffer['emotion'] = 'sadness' if i['emotion']['joy']",
"print(\"Natural Language Understanding credentials file is empty, please enter the credentials and try",
"== \"True\": try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(keywords=KeywordsOptions(sentiment=True, emotion=True, limit=10))).get_result() keywords =",
"options = body fileName = body.get('filename') ''' Prepare the text for Analysis''' with",
"in response['syntax']['tokens']: if i['part_of_speech'] == 'VERB': verbs.append(i['text']) nouns = [] for i in",
"small to extract entity\"}) else: pass ''' Extract Sentiments and Emotions with NLU",
"''' Extract Sentiments and Emotions with NLU ''' if options.get('sentiments') == \"True\": try:",
"sorted(response['keywords'], key=itemgetter('relevance'), reverse=True) keywords_sentiments_emotions = [] for i in keywords: keywords_sentiments_emotions_buffer = {",
"text=text, features=Features( syntax=SyntaxOptions( sentences=True, tokens=SyntaxOptionsTokens( lemma=True, part_of_speech=True, )))).get_result() verbs = [] for i",
"response['syntax']['tokens']: if i['part_of_speech'] == 'NOUN': nouns.append(i['text']) adj = [] for i in response['syntax']['tokens']:",
"y in adj: nouns_adjectives.append(y) comment_words_verbs = ' ' comment_words_nouns_adj = ' ' stopwords",
"5 positive sentences ''' if options.get('positiveSentences') == \"True\": tone_analysis = self.tone_analyzer.tone( {'text': text},",
"comment_words_verbs = comment_words_verbs + words + ' ' for val in nouns_adjectives: val",
"= comment_words_verbs + words + ' ' for val in nouns_adjectives: val =",
"tone_analyzer = ToneAnalyzerV3( version='2017-09-21', authenticator=tone_analyzer_authenticator ) tone_analyzer.set_service_url(self.TONE_URL) self.tone_analyzer = tone_analyzer except json.decoder.JSONDecodeError: print(\"Tone",
"= [] for i in keywords: keywords_sentiments_emotions_buffer = { 'keyword': i['text'], 'sentiment': i['sentiment']['label'],",
"for i in response['syntax']['tokens']: if i['part_of_speech'] == 'VERB': verbs.append(i['text']) nouns = [] for",
"= [] for i in response['syntax']['tokens']: if i['part_of_speech'] == 'ADJ': adj.append(i['text']) nouns_adjectives =",
"\"score\": tone['tones'][0]['score']} sentences_with_joy.append(tempDict) except: continue sentences_with_joy = sorted( sentences_with_joy, key=itemgetter('score'), reverse=True) myJsonDict.update( {\"positiveSentences\":",
"val.split() for i in range(len(tokens)): tokens[i] = tokens[i].lower() for words in tokens: comment_words_nouns_adj",
"= i['emotion']['joy'] keywords_sentiments_emotions_buffer['emotion'] = 'joy' elif i['emotion']['fear'] > maximum: maximum = i['emotion']['fear'] keywords_sentiments_emotions_buffer['emotion']",
"ConceptsOptions from ibm_cloud_sdk_core.authenticators import IAMAuthenticator from flask import request, jsonify from operator import",
"again with a bigger document.', \"score\": '100'} myJsonDict.update( {\"positiveSentences\": [tempDict]}) # return sentences_with_joy[:5]",
"plt.tight_layout(pad=0) plt.savefig(verbsWC, title=True) nounsAdjWC = \"static/images/nouns_adjectives\"+todayDate+'.png' plt.switch_backend('Agg') plt.figure(figsize=(5, 5), facecolor=None) plt.imshow(wordcloud_nouns_adj) plt.axis(\"off\") plt.tight_layout(pad=0)",
"to extract sentiments\"}) else: pass ''' Analyse tone to get top 5 positive",
"sentences_with_joy, key=itemgetter('score'), reverse=True) myJsonDict.update( {\"positiveSentences\": sentences_with_joy[:5]}) except: tempDict = {\"sentence_id\": '', \"text\": 'Text",
"response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(concepts=ConceptsOptions(limit=3))).get_result() concepts = sorted(response['concepts'], key=itemgetter('relevance'), reverse=True) myJsonDict.update({\"concepts\": concepts})",
"in verbs: val = str(val) tokens = val.split() for i in range(len(tokens)): tokens[i]",
"for y in adj: nouns_adjectives.append(y) comment_words_verbs = ' ' comment_words_nouns_adj = ' '",
"title=True) nounsAdjWC = \"static/images/nouns_adjectives\"+todayDate+'.png' plt.switch_backend('Agg') plt.figure(figsize=(5, 5), facecolor=None) plt.imshow(wordcloud_nouns_adj) plt.axis(\"off\") plt.tight_layout(pad=0) plt.savefig(nounsAdjWC, title=True)",
"options.get('sentiments') == \"True\": try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(keywords=KeywordsOptions(sentiment=True, emotion=True, limit=10))).get_result() keywords",
"= self.natural_language_understanding.analyze( language='en', text=text, features=Features(concepts=ConceptsOptions(limit=3))).get_result() concepts = sorted(response['concepts'], key=itemgetter('relevance'), reverse=True) myJsonDict.update({\"concepts\": concepts}) except:",
"i['sentiment']['label'], 'emotion': '' } maximum = i['emotion']['sadness'] keywords_sentiments_emotions_buffer['emotion'] = 'sadness' if i['emotion']['joy'] >",
"in keywords: keywords_sentiments_emotions_buffer = { 'keyword': i['text'], 'sentiment': i['sentiment']['label'], 'emotion': '' } maximum",
"'sadness' if i['emotion']['joy'] > maximum: maximum = i['emotion']['joy'] keywords_sentiments_emotions_buffer['emotion'] = 'joy' elif i['emotion']['fear']",
"min_font_size=10, max_font_size=150, random_state=42).generate(comment_words_nouns_adj) todayDate = datetime.today().strftime('%m-%d-%Y-%s') verbsWC = \"static/images/verbs\"+todayDate+'.png' plt.switch_backend('Agg') plt.figure(figsize=(5, 5), facecolor=None)",
"import matplotlib.pyplot as plt from datetime import datetime class WatsonNLUTA(Resource): NLU_API_KEY_ID = \"\"",
"keywords_sentiments_emotions.append( keywords_sentiments_emotions_buffer) myJsonDict.update({\"sentiments\": keywords_sentiments_emotions}) except: myJsonDict.update({\"sentiments\": \"Text too small to extract sentiments\"}) else:",
"\"True\": try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(concepts=ConceptsOptions(limit=3))).get_result() concepts = sorted(response['concepts'], key=itemgetter('relevance'), reverse=True)",
"in response['syntax']['tokens']: if i['part_of_speech'] == 'ADJ': adj.append(i['text']) nouns_adjectives = [] for x in",
"category}) except: myJsonDict.update({\"category\": \"Text too small to extract category\"}) else: pass ''' Extract",
"words + ' ' wordcloud_verbs = WordCloud(width=800, height=800, background_color='white', stopwords=stopwords, min_font_size=10, max_font_size=150, random_state=42).generate(comment_words_verbs)",
"self.NLU_URL = credentials1.get('url') nlu_authenticator = IAMAuthenticator(self.NLU_API_KEY_ID) natural_language_understanding = NaturalLanguageUnderstandingV1( version='2021-08-01', authenticator=nlu_authenticator ) natural_language_understanding.set_service_url(self.NLU_URL)",
"words in tokens: comment_words_verbs = comment_words_verbs + words + ' ' for val",
"as credentialsFile: credentials1 = json.loads(credentialsFile.read()) self.NLU_API_KEY_ID = credentials1.get('apikey') self.NLU_URL = credentials1.get('url') nlu_authenticator =",
"try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(keywords=KeywordsOptions(sentiment=True, emotion=True, limit=10))).get_result() keywords = sorted(response['keywords'], key=itemgetter('relevance'),",
"i['emotion']['anger'] keywords_sentiments_emotions_buffer['emotion'] = 'anger' keywords_sentiments_emotions.append( keywords_sentiments_emotions_buffer) myJsonDict.update({\"sentiments\": keywords_sentiments_emotions}) except: myJsonDict.update({\"sentiments\": \"Text too small",
"== 'NOUN': nouns.append(i['text']) adj = [] for i in response['syntax']['tokens']: if i['part_of_speech'] ==",
")))).get_result() verbs = [] for i in response['syntax']['tokens']: if i['part_of_speech'] == 'VERB': verbs.append(i['text'])",
"5), facecolor=None) plt.imshow(wordcloud_nouns_adj) plt.axis(\"off\") plt.tight_layout(pad=0) plt.savefig(nounsAdjWC, title=True) wordclouds = [nounsAdjWC, verbsWC] myJsonDict.update({\"wordclouds\": wordclouds})",
"[] for i in response['syntax']['tokens']: if i['part_of_speech'] == 'VERB': verbs.append(i['text']) nouns = []",
"except json.decoder.JSONDecodeError: print(\"Natural Language Understanding credentials file is empty, please enter the credentials",
"{} ''' Extract Category with NLU ''' if options.get('category') == \"True\": try: response",
"category\"}) else: pass ''' Extract Concepts with NLU ''' if options.get('concepts') == \"True\":",
"Emotions with NLU ''' if options.get('sentiments') == \"True\": try: response = self.natural_language_understanding.analyze( language='en',",
"'r') as text_file: text = text_file.read() ''' Initialize a return variable ''' myJsonDict",
"= tokens[i].lower() for words in tokens: comment_words_verbs = comment_words_verbs + words + '",
"Cloud ''' try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features( syntax=SyntaxOptions( sentences=True, tokens=SyntaxOptionsTokens( lemma=True,",
"and try again.\") def get(self): pass def post(self): if request.method == 'POST': body",
"['text'] ['score'] else: pass ''' Pre-Processing parts of speech to plot Word Cloud",
"''' if options.get('positiveSentences') == \"True\": tone_analysis = self.tone_analyzer.tone( {'text': text}, content_type='application/json' ).get_result() sentences_with_joy",
"facecolor=None) plt.imshow(wordcloud_verbs) plt.axis(\"off\") plt.tight_layout(pad=0) plt.savefig(verbsWC, title=True) nounsAdjWC = \"static/images/nouns_adjectives\"+todayDate+'.png' plt.switch_backend('Agg') plt.figure(figsize=(5, 5), facecolor=None)",
"tokens=SyntaxOptionsTokens( lemma=True, part_of_speech=True, )))).get_result() verbs = [] for i in response['syntax']['tokens']: if i['part_of_speech']",
"NaturalLanguageUnderstandingV1( version='2021-08-01', authenticator=nlu_authenticator ) natural_language_understanding.set_service_url(self.NLU_URL) self.natural_language_understanding = natural_language_understanding except json.decoder.JSONDecodeError: print(\"Natural Language Understanding",
"= \"\" TONE_API_KEY_ID = \"\" TONE_URL = \"\" def __init__(self): try: with open('naturallanguageunderstanding.json',",
"nounsAdjWC = \"static/images/nouns_adjectives\"+todayDate+'.png' plt.switch_backend('Agg') plt.figure(figsize=(5, 5), facecolor=None) plt.imshow(wordcloud_nouns_adj) plt.axis(\"off\") plt.tight_layout(pad=0) plt.savefig(nounsAdjWC, title=True) wordclouds",
"credentials2 = json.loads(credentialsFile.read()) self.TONE_API_KEY_ID = credentials2.get('apikey') self.TONE_URL = credentials2.get('url') tone_analyzer_authenticator = IAMAuthenticator(self.TONE_API_KEY_ID) tone_analyzer",
"tempDict = {\"sentence_id\": tone['sentence_id'], \"text\": tone['text'], \"score\": tone['tones'][0]['score']} sentences_with_joy.append(tempDict) except: continue sentences_with_joy =",
"i['emotion']['joy'] keywords_sentiments_emotions_buffer['emotion'] = 'joy' elif i['emotion']['fear'] > maximum: maximum = i['emotion']['fear'] keywords_sentiments_emotions_buffer['emotion'] =",
"part_of_speech=True, )))).get_result() verbs = [] for i in response['syntax']['tokens']: if i['part_of_speech'] == 'VERB':",
"= [] for i in response['syntax']['tokens']: if i['part_of_speech'] == 'VERB': verbs.append(i['text']) nouns =",
"WatsonNLUTA(Resource): NLU_API_KEY_ID = \"\" NLU_URL = \"\" TONE_API_KEY_ID = \"\" TONE_URL = \"\"",
"> maximum: maximum = i['emotion']['anger'] keywords_sentiments_emotions_buffer['emotion'] = 'anger' keywords_sentiments_emotions.append( keywords_sentiments_emotions_buffer) myJsonDict.update({\"sentiments\": keywords_sentiments_emotions}) except:",
"= sorted(response['entities'], key=itemgetter('relevance'), reverse=True) myJsonDict.update({\"entity\": entity[0]}) except: myJsonDict.update({\"entity\": \"Text too small to extract",
"json.loads(credentialsFile.read()) self.NLU_API_KEY_ID = credentials1.get('apikey') self.NLU_URL = credentials1.get('url') nlu_authenticator = IAMAuthenticator(self.NLU_API_KEY_ID) natural_language_understanding = NaturalLanguageUnderstandingV1(",
"too small to get positive sentences, please try again with a bigger document.',",
"= {\"sentence_id\": '', \"text\": 'Text file too small to get positive sentences, please",
"EntitiesOptions, KeywordsOptions, \\ SyntaxOptions, SyntaxOptionsTokens, CategoriesOptions, ConceptsOptions from ibm_cloud_sdk_core.authenticators import IAMAuthenticator from flask",
"= tone_analyzer except json.decoder.JSONDecodeError: print(\"Tone Analyzer credentials file is empty, please enter the",
"'VERB': verbs.append(i['text']) nouns = [] for i in response['syntax']['tokens']: if i['part_of_speech'] == 'NOUN':",
"= \"static/images/nouns_adjectives\"+todayDate+'.png' plt.switch_backend('Agg') plt.figure(figsize=(5, 5), facecolor=None) plt.imshow(wordcloud_nouns_adj) plt.axis(\"off\") plt.tight_layout(pad=0) plt.savefig(nounsAdjWC, title=True) wordclouds =",
"def post(self): if request.method == 'POST': body = json.loads(request.get_data()) options = body fileName",
"text}, content_type='application/json' ).get_result() sentences_with_joy = [] # print(json.dumps(tone_analysis, indent=2)) try: for tone in",
"{\"sentence_id\": tone['sentence_id'], \"text\": tone['text'], \"score\": tone['tones'][0]['score']} sentences_with_joy.append(tempDict) except: continue sentences_with_joy = sorted( sentences_with_joy,",
"if options.get('category') == \"True\": try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(categories=CategoriesOptions(limit=1))).get_result() category =",
"'POST': body = json.loads(request.get_data()) options = body fileName = body.get('filename') ''' Prepare the",
"'100'} myJsonDict.update( {\"positiveSentences\": [tempDict]}) # return sentences_with_joy[:5] ['text'] ['score'] else: pass ''' Pre-Processing",
"a return variable ''' myJsonDict = {} ''' Extract Category with NLU '''",
"response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(entities=EntitiesOptions(limit=1))).get_result() entity = sorted(response['entities'], key=itemgetter('relevance'), reverse=True) myJsonDict.update({\"entity\": entity[0]})",
"i['emotion']['disgust'] keywords_sentiments_emotions_buffer['emotion'] = 'disguest' elif i['emotion']['anger'] > maximum: maximum = i['emotion']['anger'] keywords_sentiments_emotions_buffer['emotion'] =",
"natural_language_understanding except json.decoder.JSONDecodeError: print(\"Natural Language Understanding credentials file is empty, please enter the",
"else: pass ''' Extract Sentiments and Emotions with NLU ''' if options.get('sentiments') ==",
"emotion=True, limit=10))).get_result() keywords = sorted(response['keywords'], key=itemgetter('relevance'), reverse=True) keywords_sentiments_emotions = [] for i in",
"credentialsFile: credentials1 = json.loads(credentialsFile.read()) self.NLU_API_KEY_ID = credentials1.get('apikey') self.NLU_URL = credentials1.get('url') nlu_authenticator = IAMAuthenticator(self.NLU_API_KEY_ID)",
"ToneAnalyzerV3( version='2017-09-21', authenticator=tone_analyzer_authenticator ) tone_analyzer.set_service_url(self.TONE_URL) self.tone_analyzer = tone_analyzer except json.decoder.JSONDecodeError: print(\"Tone Analyzer credentials",
"get positive sentences, please try again with a bigger document.', \"score\": '100'} myJsonDict.update(",
"wordcloud_verbs = WordCloud(width=800, height=800, background_color='white', stopwords=stopwords, min_font_size=10, max_font_size=150, random_state=42).generate(comment_words_verbs) wordcloud_nouns_adj = WordCloud(width=800, height=800,",
"height=800, background_color='white', stopwords=stopwords, min_font_size=10, max_font_size=150, random_state=42).generate(comment_words_verbs) wordcloud_nouns_adj = WordCloud(width=800, height=800, background_color='white', colormap=\"Dark2\", stopwords=stopwords,",
"operator import itemgetter from wordcloud import WordCloud, STOPWORDS import matplotlib.pyplot as plt from",
"'disguest' elif i['emotion']['anger'] > maximum: maximum = i['emotion']['anger'] keywords_sentiments_emotions_buffer['emotion'] = 'anger' keywords_sentiments_emotions.append( keywords_sentiments_emotions_buffer)",
"adj.append(i['text']) nouns_adjectives = [] for x in nouns: nouns_adjectives.append(x) for y in adj:",
"credentials and try again.\") def get(self): pass def post(self): if request.method == 'POST':",
"from flask import request, jsonify from operator import itemgetter from wordcloud import WordCloud,",
"category = response['categories'][0] myJsonDict.update({\"category\": category}) except: myJsonDict.update({\"category\": \"Text too small to extract category\"})",
"in tokens: comment_words_verbs = comment_words_verbs + words + ' ' for val in",
"''' if options.get('category') == \"True\": try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(categories=CategoriesOptions(limit=1))).get_result() category",
"plt.switch_backend('Agg') plt.figure(figsize=(5, 5), facecolor=None) plt.imshow(wordcloud_nouns_adj) plt.axis(\"off\") plt.tight_layout(pad=0) plt.savefig(nounsAdjWC, title=True) wordclouds = [nounsAdjWC, verbsWC]",
"open('naturallanguageunderstanding.json', 'r') as credentialsFile: credentials1 = json.loads(credentialsFile.read()) self.NLU_API_KEY_ID = credentials1.get('apikey') self.NLU_URL = credentials1.get('url')",
"reverse=True) keywords_sentiments_emotions = [] for i in keywords: keywords_sentiments_emotions_buffer = { 'keyword': i['text'],",
"= credentials1.get('apikey') self.NLU_URL = credentials1.get('url') nlu_authenticator = IAMAuthenticator(self.NLU_API_KEY_ID) natural_language_understanding = NaturalLanguageUnderstandingV1( version='2021-08-01', authenticator=nlu_authenticator",
"nouns_adjectives.append(x) for y in adj: nouns_adjectives.append(y) comment_words_verbs = ' ' comment_words_nouns_adj = '",
"verbs = [] for i in response['syntax']['tokens']: if i['part_of_speech'] == 'VERB': verbs.append(i['text']) nouns",
"max_font_size=150, random_state=42).generate(comment_words_nouns_adj) todayDate = datetime.today().strftime('%m-%d-%Y-%s') verbsWC = \"static/images/verbs\"+todayDate+'.png' plt.switch_backend('Agg') plt.figure(figsize=(5, 5), facecolor=None) plt.imshow(wordcloud_verbs)",
"import Resource import json from ibm_watson import NaturalLanguageUnderstandingV1 from ibm_watson import ToneAnalyzerV3 from",
"'ADJ': adj.append(i['text']) nouns_adjectives = [] for x in nouns: nouns_adjectives.append(x) for y in",
"= \"\" TONE_URL = \"\" def __init__(self): try: with open('naturallanguageunderstanding.json', 'r') as credentialsFile:",
"x in nouns: nouns_adjectives.append(x) for y in adj: nouns_adjectives.append(y) comment_words_verbs = ' '",
") tone_analyzer.set_service_url(self.TONE_URL) self.tone_analyzer = tone_analyzer except json.decoder.JSONDecodeError: print(\"Tone Analyzer credentials file is empty,",
"maximum: maximum = i['emotion']['joy'] keywords_sentiments_emotions_buffer['emotion'] = 'joy' elif i['emotion']['fear'] > maximum: maximum =",
"again.\") try: with open('toneanalyzer.json', 'r') as credentialsFile: credentials2 = json.loads(credentialsFile.read()) self.TONE_API_KEY_ID = credentials2.get('apikey')",
"NLU_API_KEY_ID = \"\" NLU_URL = \"\" TONE_API_KEY_ID = \"\" TONE_URL = \"\" def",
"credentialsFile: credentials2 = json.loads(credentialsFile.read()) self.TONE_API_KEY_ID = credentials2.get('apikey') self.TONE_URL = credentials2.get('url') tone_analyzer_authenticator = IAMAuthenticator(self.TONE_API_KEY_ID)",
"maximum: maximum = i['emotion']['fear'] keywords_sentiments_emotions_buffer['emotion'] = 'fear' elif i['emotion']['disgust'] > maximum: maximum =",
"natural_language_understanding = NaturalLanguageUnderstandingV1( version='2021-08-01', authenticator=nlu_authenticator ) natural_language_understanding.set_service_url(self.NLU_URL) self.natural_language_understanding = natural_language_understanding except json.decoder.JSONDecodeError: print(\"Natural",
"tone_analyzer except json.decoder.JSONDecodeError: print(\"Tone Analyzer credentials file is empty, please enter the credentials",
"for i in response['syntax']['tokens']: if i['part_of_speech'] == 'ADJ': adj.append(i['text']) nouns_adjectives = [] for",
"max_font_size=150, random_state=42).generate(comment_words_verbs) wordcloud_nouns_adj = WordCloud(width=800, height=800, background_color='white', colormap=\"Dark2\", stopwords=stopwords, min_font_size=10, max_font_size=150, random_state=42).generate(comment_words_nouns_adj) todayDate",
"verbs.append(i['text']) nouns = [] for i in response['syntax']['tokens']: if i['part_of_speech'] == 'NOUN': nouns.append(i['text'])",
"\"\" NLU_URL = \"\" TONE_API_KEY_ID = \"\" TONE_URL = \"\" def __init__(self): try:",
"from wordcloud import WordCloud, STOPWORDS import matplotlib.pyplot as plt from datetime import datetime",
"self.natural_language_understanding.analyze( language='en', text=text, features=Features( syntax=SyntaxOptions( sentences=True, tokens=SyntaxOptionsTokens( lemma=True, part_of_speech=True, )))).get_result() verbs = []",
"i['part_of_speech'] == 'VERB': verbs.append(i['text']) nouns = [] for i in response['syntax']['tokens']: if i['part_of_speech']",
"import request, jsonify from operator import itemgetter from wordcloud import WordCloud, STOPWORDS import",
"\"Joy\": tempDict = {\"sentence_id\": tone['sentence_id'], \"text\": tone['text'], \"score\": tone['tones'][0]['score']} sentences_with_joy.append(tempDict) except: continue sentences_with_joy",
"maximum = i['emotion']['disgust'] keywords_sentiments_emotions_buffer['emotion'] = 'disguest' elif i['emotion']['anger'] > maximum: maximum = i['emotion']['anger']",
"= { 'keyword': i['text'], 'sentiment': i['sentiment']['label'], 'emotion': '' } maximum = i['emotion']['sadness'] keywords_sentiments_emotions_buffer['emotion']",
"stopwords=stopwords, min_font_size=10, max_font_size=150, random_state=42).generate(comment_words_verbs) wordcloud_nouns_adj = WordCloud(width=800, height=800, background_color='white', colormap=\"Dark2\", stopwords=stopwords, min_font_size=10, max_font_size=150,",
"wordclouds}) except: myJsonDict.update({\"wordclouds\": \"Text too small to extract wordclouds\"}) # print(json.dumps(myJsonDict, indent=2)) return",
"def __init__(self): try: with open('naturallanguageunderstanding.json', 'r') as credentialsFile: credentials1 = json.loads(credentialsFile.read()) self.NLU_API_KEY_ID =",
"= json.loads(credentialsFile.read()) self.NLU_API_KEY_ID = credentials1.get('apikey') self.NLU_URL = credentials1.get('url') nlu_authenticator = IAMAuthenticator(self.NLU_API_KEY_ID) natural_language_understanding =",
"to get positive sentences, please try again with a bigger document.', \"score\": '100'}",
"return sentences_with_joy[:5] ['text'] ['score'] else: pass ''' Pre-Processing parts of speech to plot",
"ibm_watson import ToneAnalyzerV3 from ibm_watson.natural_language_understanding_v1 \\ import Features, EntitiesOptions, KeywordsOptions, \\ SyntaxOptions, SyntaxOptionsTokens,",
"> maximum: maximum = i['emotion']['disgust'] keywords_sentiments_emotions_buffer['emotion'] = 'disguest' elif i['emotion']['anger'] > maximum: maximum",
"self.natural_language_understanding.analyze( language='en', text=text, features=Features(concepts=ConceptsOptions(limit=3))).get_result() concepts = sorted(response['concepts'], key=itemgetter('relevance'), reverse=True) myJsonDict.update({\"concepts\": concepts}) except: myJsonDict.update({\"concepts\":",
"response = self.natural_language_understanding.analyze( language='en', text=text, features=Features( syntax=SyntaxOptions( sentences=True, tokens=SyntaxOptionsTokens( lemma=True, part_of_speech=True, )))).get_result() verbs",
"NLU ''' if options.get('concepts') == \"True\": try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(concepts=ConceptsOptions(limit=3))).get_result()",
"= self.natural_language_understanding.analyze( language='en', text=text, features=Features(keywords=KeywordsOptions(sentiment=True, emotion=True, limit=10))).get_result() keywords = sorted(response['keywords'], key=itemgetter('relevance'), reverse=True) keywords_sentiments_emotions",
"sentences_with_joy[:5]}) except: tempDict = {\"sentence_id\": '', \"text\": 'Text file too small to get",
"for x in nouns: nouns_adjectives.append(x) for y in adj: nouns_adjectives.append(y) comment_words_verbs = '",
"= \"static/images/verbs\"+todayDate+'.png' plt.switch_backend('Agg') plt.figure(figsize=(5, 5), facecolor=None) plt.imshow(wordcloud_verbs) plt.axis(\"off\") plt.tight_layout(pad=0) plt.savefig(verbsWC, title=True) nounsAdjWC =",
"pass ''' Extract Sentiments and Emotions with NLU ''' if options.get('sentiments') == \"True\":",
"credentials file is empty, please enter the credentials and try again.\") try: with",
"from flask_restful import Resource import json from ibm_watson import NaturalLanguageUnderstandingV1 from ibm_watson import",
"import json from ibm_watson import NaturalLanguageUnderstandingV1 from ibm_watson import ToneAnalyzerV3 from ibm_watson.natural_language_understanding_v1 \\",
"small to extract category\"}) else: pass ''' Extract Concepts with NLU ''' if",
"== \"True\": tone_analysis = self.tone_analyzer.tone( {'text': text}, content_type='application/json' ).get_result() sentences_with_joy = [] #",
"= comment_words_nouns_adj + words + ' ' wordcloud_verbs = WordCloud(width=800, height=800, background_color='white', stopwords=stopwords,",
"response['syntax']['tokens']: if i['part_of_speech'] == 'VERB': verbs.append(i['text']) nouns = [] for i in response['syntax']['tokens']:",
"[] # print(json.dumps(tone_analysis, indent=2)) try: for tone in tone_analysis['sentences_tone']: try: if tone['tones'][0]['tone_name'] ==",
"nouns: nouns_adjectives.append(x) for y in adj: nouns_adjectives.append(y) comment_words_verbs = ' ' comment_words_nouns_adj =",
"stopwords=stopwords, min_font_size=10, max_font_size=150, random_state=42).generate(comment_words_nouns_adj) todayDate = datetime.today().strftime('%m-%d-%Y-%s') verbsWC = \"static/images/verbs\"+todayDate+'.png' plt.switch_backend('Agg') plt.figure(figsize=(5, 5),",
"as text_file: text = text_file.read() ''' Initialize a return variable ''' myJsonDict =",
"random_state=42).generate(comment_words_nouns_adj) todayDate = datetime.today().strftime('%m-%d-%Y-%s') verbsWC = \"static/images/verbs\"+todayDate+'.png' plt.switch_backend('Agg') plt.figure(figsize=(5, 5), facecolor=None) plt.imshow(wordcloud_verbs) plt.axis(\"off\")",
"if options.get('entity') == \"True\": try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(entities=EntitiesOptions(limit=1))).get_result() entity =",
"in tone_analysis['sentences_tone']: try: if tone['tones'][0]['tone_name'] == \"Joy\": tempDict = {\"sentence_id\": tone['sentence_id'], \"text\": tone['text'],",
"else: pass ''' Extract Concepts with NLU ''' if options.get('concepts') == \"True\": try:",
"nouns_adjectives = [] for x in nouns: nouns_adjectives.append(x) for y in adj: nouns_adjectives.append(y)",
"language='en', text=text, features=Features( syntax=SyntaxOptions( sentences=True, tokens=SyntaxOptionsTokens( lemma=True, part_of_speech=True, )))).get_result() verbs = [] for",
"language='en', text=text, features=Features(keywords=KeywordsOptions(sentiment=True, emotion=True, limit=10))).get_result() keywords = sorted(response['keywords'], key=itemgetter('relevance'), reverse=True) keywords_sentiments_emotions = []",
"parts of speech to plot Word Cloud ''' try: response = self.natural_language_understanding.analyze( language='en',",
"' ' comment_words_nouns_adj = ' ' stopwords = set(STOPWORDS) for val in verbs:",
"print(json.dumps(tone_analysis, indent=2)) try: for tone in tone_analysis['sentences_tone']: try: if tone['tones'][0]['tone_name'] == \"Joy\": tempDict",
"= credentials2.get('apikey') self.TONE_URL = credentials2.get('url') tone_analyzer_authenticator = IAMAuthenticator(self.TONE_API_KEY_ID) tone_analyzer = ToneAnalyzerV3( version='2017-09-21', authenticator=tone_analyzer_authenticator",
"text=text, features=Features(concepts=ConceptsOptions(limit=3))).get_result() concepts = sorted(response['concepts'], key=itemgetter('relevance'), reverse=True) myJsonDict.update({\"concepts\": concepts}) except: myJsonDict.update({\"concepts\": \"Text too",
"key=itemgetter('relevance'), reverse=True) myJsonDict.update({\"entity\": entity[0]}) except: myJsonDict.update({\"entity\": \"Text too small to extract entity\"}) else:",
"[] for i in keywords: keywords_sentiments_emotions_buffer = { 'keyword': i['text'], 'sentiment': i['sentiment']['label'], 'emotion':",
"positive sentences ''' if options.get('positiveSentences') == \"True\": tone_analysis = self.tone_analyzer.tone( {'text': text}, content_type='application/json'",
"plt from datetime import datetime class WatsonNLUTA(Resource): NLU_API_KEY_ID = \"\" NLU_URL = \"\"",
"tokens: comment_words_verbs = comment_words_verbs + words + ' ' for val in nouns_adjectives:",
"colormap=\"Dark2\", stopwords=stopwords, min_font_size=10, max_font_size=150, random_state=42).generate(comment_words_nouns_adj) todayDate = datetime.today().strftime('%m-%d-%Y-%s') verbsWC = \"static/images/verbs\"+todayDate+'.png' plt.switch_backend('Agg') plt.figure(figsize=(5,",
"file is empty, please enter the credentials and try again.\") try: with open('toneanalyzer.json',",
"keywords_sentiments_emotions_buffer['emotion'] = 'sadness' if i['emotion']['joy'] > maximum: maximum = i['emotion']['joy'] keywords_sentiments_emotions_buffer['emotion'] = 'joy'",
"body = json.loads(request.get_data()) options = body fileName = body.get('filename') ''' Prepare the text",
"sentences ''' if options.get('positiveSentences') == \"True\": tone_analysis = self.tone_analyzer.tone( {'text': text}, content_type='application/json' ).get_result()",
"\"Text too small to extract sentiments\"}) else: pass ''' Analyse tone to get",
"keywords_sentiments_emotions}) except: myJsonDict.update({\"sentiments\": \"Text too small to extract sentiments\"}) else: pass ''' Analyse",
"val = str(val) tokens = val.split() for i in range(len(tokens)): tokens[i] = tokens[i].lower()",
"words + ' ' for val in nouns_adjectives: val = str(val) tokens =",
"pass ''' Analyse tone to get top 5 positive sentences ''' if options.get('positiveSentences')",
"\\ SyntaxOptions, SyntaxOptionsTokens, CategoriesOptions, ConceptsOptions from ibm_cloud_sdk_core.authenticators import IAMAuthenticator from flask import request,",
"from ibm_watson import NaturalLanguageUnderstandingV1 from ibm_watson import ToneAnalyzerV3 from ibm_watson.natural_language_understanding_v1 \\ import Features,",
"\"\" def __init__(self): try: with open('naturallanguageunderstanding.json', 'r') as credentialsFile: credentials1 = json.loads(credentialsFile.read()) self.NLU_API_KEY_ID",
"= val.split() for i in range(len(tokens)): tokens[i] = tokens[i].lower() for words in tokens:",
"= IAMAuthenticator(self.TONE_API_KEY_ID) tone_analyzer = ToneAnalyzerV3( version='2017-09-21', authenticator=tone_analyzer_authenticator ) tone_analyzer.set_service_url(self.TONE_URL) self.tone_analyzer = tone_analyzer except",
"try again with a bigger document.', \"score\": '100'} myJsonDict.update( {\"positiveSentences\": [tempDict]}) # return",
"{\"positiveSentences\": [tempDict]}) # return sentences_with_joy[:5] ['text'] ['score'] else: pass ''' Pre-Processing parts of",
"in range(len(tokens)): tokens[i] = tokens[i].lower() for words in tokens: comment_words_verbs = comment_words_verbs +",
"for i in response['syntax']['tokens']: if i['part_of_speech'] == 'NOUN': nouns.append(i['text']) adj = [] for",
"text_file: text = text_file.read() ''' Initialize a return variable ''' myJsonDict = {}",
"to extract category\"}) else: pass ''' Extract Concepts with NLU ''' if options.get('concepts')",
"natural_language_understanding.set_service_url(self.NLU_URL) self.natural_language_understanding = natural_language_understanding except json.decoder.JSONDecodeError: print(\"Natural Language Understanding credentials file is empty,",
"with open('static/transcripts/'+fileName, 'r') as text_file: text = text_file.read() ''' Initialize a return variable",
"self.natural_language_understanding.analyze( language='en', text=text, features=Features(keywords=KeywordsOptions(sentiment=True, emotion=True, limit=10))).get_result() keywords = sorted(response['keywords'], key=itemgetter('relevance'), reverse=True) keywords_sentiments_emotions =",
"with NLU ''' if options.get('concepts') == \"True\": try: response = self.natural_language_understanding.analyze( language='en', text=text,",
"from datetime import datetime class WatsonNLUTA(Resource): NLU_API_KEY_ID = \"\" NLU_URL = \"\" TONE_API_KEY_ID",
"i in keywords: keywords_sentiments_emotions_buffer = { 'keyword': i['text'], 'sentiment': i['sentiment']['label'], 'emotion': '' }",
"maximum = i['emotion']['fear'] keywords_sentiments_emotions_buffer['emotion'] = 'fear' elif i['emotion']['disgust'] > maximum: maximum = i['emotion']['disgust']",
"verbs: val = str(val) tokens = val.split() for i in range(len(tokens)): tokens[i] =",
"try again.\") try: with open('toneanalyzer.json', 'r') as credentialsFile: credentials2 = json.loads(credentialsFile.read()) self.TONE_API_KEY_ID =",
"'Text file too small to get positive sentences, please try again with a",
"''' try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features( syntax=SyntaxOptions( sentences=True, tokens=SyntaxOptionsTokens( lemma=True, part_of_speech=True,",
"= WordCloud(width=800, height=800, background_color='white', colormap=\"Dark2\", stopwords=stopwords, min_font_size=10, max_font_size=150, random_state=42).generate(comment_words_nouns_adj) todayDate = datetime.today().strftime('%m-%d-%Y-%s') verbsWC",
"Resource import json from ibm_watson import NaturalLanguageUnderstandingV1 from ibm_watson import ToneAnalyzerV3 from ibm_watson.natural_language_understanding_v1",
"json.loads(request.get_data()) options = body fileName = body.get('filename') ''' Prepare the text for Analysis'''",
"try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(entities=EntitiesOptions(limit=1))).get_result() entity = sorted(response['entities'], key=itemgetter('relevance'), reverse=True) myJsonDict.update({\"entity\":",
"' stopwords = set(STOPWORDS) for val in verbs: val = str(val) tokens =",
"adj = [] for i in response['syntax']['tokens']: if i['part_of_speech'] == 'ADJ': adj.append(i['text']) nouns_adjectives",
"key=itemgetter('relevance'), reverse=True) myJsonDict.update({\"concepts\": concepts}) except: myJsonDict.update({\"concepts\": \"Text too small to extract concepts\"}) else:",
"flask_restful import Resource import json from ibm_watson import NaturalLanguageUnderstandingV1 from ibm_watson import ToneAnalyzerV3",
"options.get('entity') == \"True\": try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(entities=EntitiesOptions(limit=1))).get_result() entity = sorted(response['entities'],",
"i['part_of_speech'] == 'NOUN': nouns.append(i['text']) adj = [] for i in response['syntax']['tokens']: if i['part_of_speech']",
"ibm_watson.natural_language_understanding_v1 \\ import Features, EntitiesOptions, KeywordsOptions, \\ SyntaxOptions, SyntaxOptionsTokens, CategoriesOptions, ConceptsOptions from ibm_cloud_sdk_core.authenticators",
"myJsonDict.update({\"sentiments\": keywords_sentiments_emotions}) except: myJsonDict.update({\"sentiments\": \"Text too small to extract sentiments\"}) else: pass '''",
"= self.tone_analyzer.tone( {'text': text}, content_type='application/json' ).get_result() sentences_with_joy = [] # print(json.dumps(tone_analysis, indent=2)) try:",
"try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features( syntax=SyntaxOptions( sentences=True, tokens=SyntaxOptionsTokens( lemma=True, part_of_speech=True, )))).get_result()",
"= text_file.read() ''' Initialize a return variable ''' myJsonDict = {} ''' Extract",
"WordCloud(width=800, height=800, background_color='white', stopwords=stopwords, min_font_size=10, max_font_size=150, random_state=42).generate(comment_words_verbs) wordcloud_nouns_adj = WordCloud(width=800, height=800, background_color='white', colormap=\"Dark2\",",
"Extract Concepts with NLU ''' if options.get('concepts') == \"True\": try: response = self.natural_language_understanding.analyze(",
"TONE_API_KEY_ID = \"\" TONE_URL = \"\" def __init__(self): try: with open('naturallanguageunderstanding.json', 'r') as",
"pass def post(self): if request.method == 'POST': body = json.loads(request.get_data()) options = body",
"authenticator=tone_analyzer_authenticator ) tone_analyzer.set_service_url(self.TONE_URL) self.tone_analyzer = tone_analyzer except json.decoder.JSONDecodeError: print(\"Tone Analyzer credentials file is",
"text for Analysis''' with open('static/transcripts/'+fileName, 'r') as text_file: text = text_file.read() ''' Initialize",
"keywords_sentiments_emotions_buffer) myJsonDict.update({\"sentiments\": keywords_sentiments_emotions}) except: myJsonDict.update({\"sentiments\": \"Text too small to extract sentiments\"}) else: pass",
"keywords = sorted(response['keywords'], key=itemgetter('relevance'), reverse=True) keywords_sentiments_emotions = [] for i in keywords: keywords_sentiments_emotions_buffer",
"'fear' elif i['emotion']['disgust'] > maximum: maximum = i['emotion']['disgust'] keywords_sentiments_emotions_buffer['emotion'] = 'disguest' elif i['emotion']['anger']",
"limit=10))).get_result() keywords = sorted(response['keywords'], key=itemgetter('relevance'), reverse=True) keywords_sentiments_emotions = [] for i in keywords:",
"sorted(response['concepts'], key=itemgetter('relevance'), reverse=True) myJsonDict.update({\"concepts\": concepts}) except: myJsonDict.update({\"concepts\": \"Text too small to extract concepts\"})",
"'NOUN': nouns.append(i['text']) adj = [] for i in response['syntax']['tokens']: if i['part_of_speech'] == 'ADJ':",
"with NLU ''' if options.get('category') == \"True\": try: response = self.natural_language_understanding.analyze( language='en', text=text,",
"the text for Analysis''' with open('static/transcripts/'+fileName, 'r') as text_file: text = text_file.read() '''",
"tone_analysis['sentences_tone']: try: if tone['tones'][0]['tone_name'] == \"Joy\": tempDict = {\"sentence_id\": tone['sentence_id'], \"text\": tone['text'], \"score\":",
"'r') as credentialsFile: credentials1 = json.loads(credentialsFile.read()) self.NLU_API_KEY_ID = credentials1.get('apikey') self.NLU_URL = credentials1.get('url') nlu_authenticator",
"sentences_with_joy = [] # print(json.dumps(tone_analysis, indent=2)) try: for tone in tone_analysis['sentences_tone']: try: if",
"' wordcloud_verbs = WordCloud(width=800, height=800, background_color='white', stopwords=stopwords, min_font_size=10, max_font_size=150, random_state=42).generate(comment_words_verbs) wordcloud_nouns_adj = WordCloud(width=800,",
"small to get positive sentences, please try again with a bigger document.', \"score\":",
"language='en', text=text, features=Features(categories=CategoriesOptions(limit=1))).get_result() category = response['categories'][0] myJsonDict.update({\"category\": category}) except: myJsonDict.update({\"category\": \"Text too small",
"open('toneanalyzer.json', 'r') as credentialsFile: credentials2 = json.loads(credentialsFile.read()) self.TONE_API_KEY_ID = credentials2.get('apikey') self.TONE_URL = credentials2.get('url')",
"plt.axis(\"off\") plt.tight_layout(pad=0) plt.savefig(verbsWC, title=True) nounsAdjWC = \"static/images/nouns_adjectives\"+todayDate+'.png' plt.switch_backend('Agg') plt.figure(figsize=(5, 5), facecolor=None) plt.imshow(wordcloud_nouns_adj) plt.axis(\"off\")",
"Understanding credentials file is empty, please enter the credentials and try again.\") try:",
"response['categories'][0] myJsonDict.update({\"category\": category}) except: myJsonDict.update({\"category\": \"Text too small to extract category\"}) else: pass",
"if i['emotion']['joy'] > maximum: maximum = i['emotion']['joy'] keywords_sentiments_emotions_buffer['emotion'] = 'joy' elif i['emotion']['fear'] >",
"Sentiments and Emotions with NLU ''' if options.get('sentiments') == \"True\": try: response =",
"set(STOPWORDS) for val in verbs: val = str(val) tokens = val.split() for i",
"except: continue sentences_with_joy = sorted( sentences_with_joy, key=itemgetter('score'), reverse=True) myJsonDict.update( {\"positiveSentences\": sentences_with_joy[:5]}) except: tempDict",
"= self.natural_language_understanding.analyze( language='en', text=text, features=Features(entities=EntitiesOptions(limit=1))).get_result() entity = sorted(response['entities'], key=itemgetter('relevance'), reverse=True) myJsonDict.update({\"entity\": entity[0]}) except:",
"['score'] else: pass ''' Pre-Processing parts of speech to plot Word Cloud '''",
"return variable ''' myJsonDict = {} ''' Extract Category with NLU ''' if",
"try: with open('toneanalyzer.json', 'r') as credentialsFile: credentials2 = json.loads(credentialsFile.read()) self.TONE_API_KEY_ID = credentials2.get('apikey') self.TONE_URL",
"\"text\": 'Text file too small to get positive sentences, please try again with",
"sentences_with_joy[:5] ['text'] ['score'] else: pass ''' Pre-Processing parts of speech to plot Word",
"extract entity\"}) else: pass ''' Extract Sentiments and Emotions with NLU ''' if",
"in nouns_adjectives: val = str(val) tokens = val.split() for i in range(len(tokens)): tokens[i]",
"content_type='application/json' ).get_result() sentences_with_joy = [] # print(json.dumps(tone_analysis, indent=2)) try: for tone in tone_analysis['sentences_tone']:",
"plt.switch_backend('Agg') plt.figure(figsize=(5, 5), facecolor=None) plt.imshow(wordcloud_verbs) plt.axis(\"off\") plt.tight_layout(pad=0) plt.savefig(verbsWC, title=True) nounsAdjWC = \"static/images/nouns_adjectives\"+todayDate+'.png' plt.switch_backend('Agg')",
"except: myJsonDict.update({\"wordclouds\": \"Text too small to extract wordclouds\"}) # print(json.dumps(myJsonDict, indent=2)) return jsonify(myJsonDict)",
"wordclouds = [nounsAdjWC, verbsWC] myJsonDict.update({\"wordclouds\": wordclouds}) except: myJsonDict.update({\"wordclouds\": \"Text too small to extract",
"random_state=42).generate(comment_words_verbs) wordcloud_nouns_adj = WordCloud(width=800, height=800, background_color='white', colormap=\"Dark2\", stopwords=stopwords, min_font_size=10, max_font_size=150, random_state=42).generate(comment_words_nouns_adj) todayDate =",
"for words in tokens: comment_words_verbs = comment_words_verbs + words + ' ' for",
"\"text\": tone['text'], \"score\": tone['tones'][0]['score']} sentences_with_joy.append(tempDict) except: continue sentences_with_joy = sorted( sentences_with_joy, key=itemgetter('score'), reverse=True)",
"' comment_words_nouns_adj = ' ' stopwords = set(STOPWORDS) for val in verbs: val",
"comment_words_nouns_adj = comment_words_nouns_adj + words + ' ' wordcloud_verbs = WordCloud(width=800, height=800, background_color='white',",
"[] for x in nouns: nouns_adjectives.append(x) for y in adj: nouns_adjectives.append(y) comment_words_verbs =",
"plt.tight_layout(pad=0) plt.savefig(nounsAdjWC, title=True) wordclouds = [nounsAdjWC, verbsWC] myJsonDict.update({\"wordclouds\": wordclouds}) except: myJsonDict.update({\"wordclouds\": \"Text too",
"import datetime class WatsonNLUTA(Resource): NLU_API_KEY_ID = \"\" NLU_URL = \"\" TONE_API_KEY_ID = \"\"",
"= [nounsAdjWC, verbsWC] myJsonDict.update({\"wordclouds\": wordclouds}) except: myJsonDict.update({\"wordclouds\": \"Text too small to extract wordclouds\"})",
"background_color='white', stopwords=stopwords, min_font_size=10, max_font_size=150, random_state=42).generate(comment_words_verbs) wordcloud_nouns_adj = WordCloud(width=800, height=800, background_color='white', colormap=\"Dark2\", stopwords=stopwords, min_font_size=10,",
"self.TONE_API_KEY_ID = credentials2.get('apikey') self.TONE_URL = credentials2.get('url') tone_analyzer_authenticator = IAMAuthenticator(self.TONE_API_KEY_ID) tone_analyzer = ToneAnalyzerV3( version='2017-09-21',",
"''' myJsonDict = {} ''' Extract Category with NLU ''' if options.get('category') ==",
"height=800, background_color='white', colormap=\"Dark2\", stopwords=stopwords, min_font_size=10, max_font_size=150, random_state=42).generate(comment_words_nouns_adj) todayDate = datetime.today().strftime('%m-%d-%Y-%s') verbsWC = \"static/images/verbs\"+todayDate+'.png'",
"credentials and try again.\") try: with open('toneanalyzer.json', 'r') as credentialsFile: credentials2 = json.loads(credentialsFile.read())",
"== \"Joy\": tempDict = {\"sentence_id\": tone['sentence_id'], \"text\": tone['text'], \"score\": tone['tones'][0]['score']} sentences_with_joy.append(tempDict) except: continue",
"SyntaxOptionsTokens, CategoriesOptions, ConceptsOptions from ibm_cloud_sdk_core.authenticators import IAMAuthenticator from flask import request, jsonify from",
"= 'disguest' elif i['emotion']['anger'] > maximum: maximum = i['emotion']['anger'] keywords_sentiments_emotions_buffer['emotion'] = 'anger' keywords_sentiments_emotions.append(",
"myJsonDict.update({\"wordclouds\": wordclouds}) except: myJsonDict.update({\"wordclouds\": \"Text too small to extract wordclouds\"}) # print(json.dumps(myJsonDict, indent=2))",
"except json.decoder.JSONDecodeError: print(\"Tone Analyzer credentials file is empty, please enter the credentials and",
"if i['part_of_speech'] == 'ADJ': adj.append(i['text']) nouns_adjectives = [] for x in nouns: nouns_adjectives.append(x)",
"NLU ''' if options.get('category') == \"True\": try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(categories=CategoriesOptions(limit=1))).get_result()",
"post(self): if request.method == 'POST': body = json.loads(request.get_data()) options = body fileName =",
"' for val in nouns_adjectives: val = str(val) tokens = val.split() for i",
"features=Features(entities=EntitiesOptions(limit=1))).get_result() entity = sorted(response['entities'], key=itemgetter('relevance'), reverse=True) myJsonDict.update({\"entity\": entity[0]}) except: myJsonDict.update({\"entity\": \"Text too small",
"tone_analysis = self.tone_analyzer.tone( {'text': text}, content_type='application/json' ).get_result() sentences_with_joy = [] # print(json.dumps(tone_analysis, indent=2))",
"myJsonDict.update({\"sentiments\": \"Text too small to extract sentiments\"}) else: pass ''' Analyse tone to",
"maximum = i['emotion']['sadness'] keywords_sentiments_emotions_buffer['emotion'] = 'sadness' if i['emotion']['joy'] > maximum: maximum = i['emotion']['joy']",
"plt.figure(figsize=(5, 5), facecolor=None) plt.imshow(wordcloud_verbs) plt.axis(\"off\") plt.tight_layout(pad=0) plt.savefig(verbsWC, title=True) nounsAdjWC = \"static/images/nouns_adjectives\"+todayDate+'.png' plt.switch_backend('Agg') plt.figure(figsize=(5,",
"ibm_watson import NaturalLanguageUnderstandingV1 from ibm_watson import ToneAnalyzerV3 from ibm_watson.natural_language_understanding_v1 \\ import Features, EntitiesOptions,",
"= 'anger' keywords_sentiments_emotions.append( keywords_sentiments_emotions_buffer) myJsonDict.update({\"sentiments\": keywords_sentiments_emotions}) except: myJsonDict.update({\"sentiments\": \"Text too small to extract",
"words in tokens: comment_words_nouns_adj = comment_words_nouns_adj + words + ' ' wordcloud_verbs =",
"> maximum: maximum = i['emotion']['fear'] keywords_sentiments_emotions_buffer['emotion'] = 'fear' elif i['emotion']['disgust'] > maximum: maximum",
"= WordCloud(width=800, height=800, background_color='white', stopwords=stopwords, min_font_size=10, max_font_size=150, random_state=42).generate(comment_words_verbs) wordcloud_nouns_adj = WordCloud(width=800, height=800, background_color='white',",
"print(\"Tone Analyzer credentials file is empty, please enter the credentials and try again.\")",
"self.natural_language_understanding.analyze( language='en', text=text, features=Features(categories=CategoriesOptions(limit=1))).get_result() category = response['categories'][0] myJsonDict.update({\"category\": category}) except: myJsonDict.update({\"category\": \"Text too",
"= i['emotion']['fear'] keywords_sentiments_emotions_buffer['emotion'] = 'fear' elif i['emotion']['disgust'] > maximum: maximum = i['emotion']['disgust'] keywords_sentiments_emotions_buffer['emotion']",
"plt.imshow(wordcloud_verbs) plt.axis(\"off\") plt.tight_layout(pad=0) plt.savefig(verbsWC, title=True) nounsAdjWC = \"static/images/nouns_adjectives\"+todayDate+'.png' plt.switch_backend('Agg') plt.figure(figsize=(5, 5), facecolor=None) plt.imshow(wordcloud_nouns_adj)",
"tokens = val.split() for i in range(len(tokens)): tokens[i] = tokens[i].lower() for words in",
"a bigger document.', \"score\": '100'} myJsonDict.update( {\"positiveSentences\": [tempDict]}) # return sentences_with_joy[:5] ['text'] ['score']",
"with open('toneanalyzer.json', 'r') as credentialsFile: credentials2 = json.loads(credentialsFile.read()) self.TONE_API_KEY_ID = credentials2.get('apikey') self.TONE_URL =",
"with NLU ''' if options.get('entity') == \"True\": try: response = self.natural_language_understanding.analyze( language='en', text=text,",
"import Features, EntitiesOptions, KeywordsOptions, \\ SyntaxOptions, SyntaxOptionsTokens, CategoriesOptions, ConceptsOptions from ibm_cloud_sdk_core.authenticators import IAMAuthenticator",
"options.get('positiveSentences') == \"True\": tone_analysis = self.tone_analyzer.tone( {'text': text}, content_type='application/json' ).get_result() sentences_with_joy = []",
"with NLU ''' if options.get('sentiments') == \"True\": try: response = self.natural_language_understanding.analyze( language='en', text=text,",
"{'text': text}, content_type='application/json' ).get_result() sentences_with_joy = [] # print(json.dumps(tone_analysis, indent=2)) try: for tone",
"[] for i in response['syntax']['tokens']: if i['part_of_speech'] == 'ADJ': adj.append(i['text']) nouns_adjectives = []",
"tokens[i] = tokens[i].lower() for words in tokens: comment_words_nouns_adj = comment_words_nouns_adj + words +",
"file too small to get positive sentences, please try again with a bigger",
"myJsonDict.update( {\"positiveSentences\": [tempDict]}) # return sentences_with_joy[:5] ['text'] ['score'] else: pass ''' Pre-Processing parts",
"itemgetter from wordcloud import WordCloud, STOPWORDS import matplotlib.pyplot as plt from datetime import",
"in tokens: comment_words_nouns_adj = comment_words_nouns_adj + words + ' ' wordcloud_verbs = WordCloud(width=800,",
"def get(self): pass def post(self): if request.method == 'POST': body = json.loads(request.get_data()) options",
"json from ibm_watson import NaturalLanguageUnderstandingV1 from ibm_watson import ToneAnalyzerV3 from ibm_watson.natural_language_understanding_v1 \\ import",
"= [] # print(json.dumps(tone_analysis, indent=2)) try: for tone in tone_analysis['sentences_tone']: try: if tone['tones'][0]['tone_name']",
"= i['emotion']['disgust'] keywords_sentiments_emotions_buffer['emotion'] = 'disguest' elif i['emotion']['anger'] > maximum: maximum = i['emotion']['anger'] keywords_sentiments_emotions_buffer['emotion']",
"for Analysis''' with open('static/transcripts/'+fileName, 'r') as text_file: text = text_file.read() ''' Initialize a",
"\"static/images/nouns_adjectives\"+todayDate+'.png' plt.switch_backend('Agg') plt.figure(figsize=(5, 5), facecolor=None) plt.imshow(wordcloud_nouns_adj) plt.axis(\"off\") plt.tight_layout(pad=0) plt.savefig(nounsAdjWC, title=True) wordclouds = [nounsAdjWC,",
"tempDict = {\"sentence_id\": '', \"text\": 'Text file too small to get positive sentences,",
"try: with open('naturallanguageunderstanding.json', 'r') as credentialsFile: credentials1 = json.loads(credentialsFile.read()) self.NLU_API_KEY_ID = credentials1.get('apikey') self.NLU_URL",
"credentials1 = json.loads(credentialsFile.read()) self.NLU_API_KEY_ID = credentials1.get('apikey') self.NLU_URL = credentials1.get('url') nlu_authenticator = IAMAuthenticator(self.NLU_API_KEY_ID) natural_language_understanding",
"sentences, please try again with a bigger document.', \"score\": '100'} myJsonDict.update( {\"positiveSentences\": [tempDict]})",
"response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(keywords=KeywordsOptions(sentiment=True, emotion=True, limit=10))).get_result() keywords = sorted(response['keywords'], key=itemgetter('relevance'), reverse=True)",
"Concepts with NLU ''' if options.get('concepts') == \"True\": try: response = self.natural_language_understanding.analyze( language='en',",
"body.get('filename') ''' Prepare the text for Analysis''' with open('static/transcripts/'+fileName, 'r') as text_file: text",
"str(val) tokens = val.split() for i in range(len(tokens)): tokens[i] = tokens[i].lower() for words",
"credentials1.get('apikey') self.NLU_URL = credentials1.get('url') nlu_authenticator = IAMAuthenticator(self.NLU_API_KEY_ID) natural_language_understanding = NaturalLanguageUnderstandingV1( version='2021-08-01', authenticator=nlu_authenticator )",
"tone_analyzer_authenticator = IAMAuthenticator(self.TONE_API_KEY_ID) tone_analyzer = ToneAnalyzerV3( version='2017-09-21', authenticator=tone_analyzer_authenticator ) tone_analyzer.set_service_url(self.TONE_URL) self.tone_analyzer = tone_analyzer",
"Analysis''' with open('static/transcripts/'+fileName, 'r') as text_file: text = text_file.read() ''' Initialize a return",
"self.TONE_URL = credentials2.get('url') tone_analyzer_authenticator = IAMAuthenticator(self.TONE_API_KEY_ID) tone_analyzer = ToneAnalyzerV3( version='2017-09-21', authenticator=tone_analyzer_authenticator ) tone_analyzer.set_service_url(self.TONE_URL)",
"CategoriesOptions, ConceptsOptions from ibm_cloud_sdk_core.authenticators import IAMAuthenticator from flask import request, jsonify from operator",
"tokens[i].lower() for words in tokens: comment_words_nouns_adj = comment_words_nouns_adj + words + ' '",
"is empty, please enter the credentials and try again.\") def get(self): pass def",
"tone_analyzer.set_service_url(self.TONE_URL) self.tone_analyzer = tone_analyzer except json.decoder.JSONDecodeError: print(\"Tone Analyzer credentials file is empty, please",
"credentials2.get('url') tone_analyzer_authenticator = IAMAuthenticator(self.TONE_API_KEY_ID) tone_analyzer = ToneAnalyzerV3( version='2017-09-21', authenticator=tone_analyzer_authenticator ) tone_analyzer.set_service_url(self.TONE_URL) self.tone_analyzer =",
"tokens[i].lower() for words in tokens: comment_words_verbs = comment_words_verbs + words + ' '",
"min_font_size=10, max_font_size=150, random_state=42).generate(comment_words_verbs) wordcloud_nouns_adj = WordCloud(width=800, height=800, background_color='white', colormap=\"Dark2\", stopwords=stopwords, min_font_size=10, max_font_size=150, random_state=42).generate(comment_words_nouns_adj)",
"version='2021-08-01', authenticator=nlu_authenticator ) natural_language_understanding.set_service_url(self.NLU_URL) self.natural_language_understanding = natural_language_understanding except json.decoder.JSONDecodeError: print(\"Natural Language Understanding credentials",
"from operator import itemgetter from wordcloud import WordCloud, STOPWORDS import matplotlib.pyplot as plt",
"IAMAuthenticator(self.TONE_API_KEY_ID) tone_analyzer = ToneAnalyzerV3( version='2017-09-21', authenticator=tone_analyzer_authenticator ) tone_analyzer.set_service_url(self.TONE_URL) self.tone_analyzer = tone_analyzer except json.decoder.JSONDecodeError:",
"language='en', text=text, features=Features(entities=EntitiesOptions(limit=1))).get_result() entity = sorted(response['entities'], key=itemgetter('relevance'), reverse=True) myJsonDict.update({\"entity\": entity[0]}) except: myJsonDict.update({\"entity\": \"Text",
"please enter the credentials and try again.\") def get(self): pass def post(self): if",
"if i['part_of_speech'] == 'NOUN': nouns.append(i['text']) adj = [] for i in response['syntax']['tokens']: if",
"features=Features(keywords=KeywordsOptions(sentiment=True, emotion=True, limit=10))).get_result() keywords = sorted(response['keywords'], key=itemgetter('relevance'), reverse=True) keywords_sentiments_emotions = [] for i",
"= ' ' stopwords = set(STOPWORDS) for val in verbs: val = str(val)",
"Analyse tone to get top 5 positive sentences ''' if options.get('positiveSentences') == \"True\":",
"body fileName = body.get('filename') ''' Prepare the text for Analysis''' with open('static/transcripts/'+fileName, 'r')",
"except: myJsonDict.update({\"concepts\": \"Text too small to extract concepts\"}) else: pass ''' Extract Entity",
"self.natural_language_understanding.analyze( language='en', text=text, features=Features(entities=EntitiesOptions(limit=1))).get_result() entity = sorted(response['entities'], key=itemgetter('relevance'), reverse=True) myJsonDict.update({\"entity\": entity[0]}) except: myJsonDict.update({\"entity\":",
"i in response['syntax']['tokens']: if i['part_of_speech'] == 'NOUN': nouns.append(i['text']) adj = [] for i",
"''' Extract Category with NLU ''' if options.get('category') == \"True\": try: response =",
"else: pass ''' Pre-Processing parts of speech to plot Word Cloud ''' try:",
"{ 'keyword': i['text'], 'sentiment': i['sentiment']['label'], 'emotion': '' } maximum = i['emotion']['sadness'] keywords_sentiments_emotions_buffer['emotion'] =",
"of speech to plot Word Cloud ''' try: response = self.natural_language_understanding.analyze( language='en', text=text,",
"plt.imshow(wordcloud_nouns_adj) plt.axis(\"off\") plt.tight_layout(pad=0) plt.savefig(nounsAdjWC, title=True) wordclouds = [nounsAdjWC, verbsWC] myJsonDict.update({\"wordclouds\": wordclouds}) except: myJsonDict.update({\"wordclouds\":",
"''' if options.get('sentiments') == \"True\": try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(keywords=KeywordsOptions(sentiment=True, emotion=True,",
"matplotlib.pyplot as plt from datetime import datetime class WatsonNLUTA(Resource): NLU_API_KEY_ID = \"\" NLU_URL",
"in response['syntax']['tokens']: if i['part_of_speech'] == 'NOUN': nouns.append(i['text']) adj = [] for i in",
"to extract entity\"}) else: pass ''' Extract Sentiments and Emotions with NLU '''",
"= tokens[i].lower() for words in tokens: comment_words_nouns_adj = comment_words_nouns_adj + words + '",
"= response['categories'][0] myJsonDict.update({\"category\": category}) except: myJsonDict.update({\"category\": \"Text too small to extract category\"}) else:",
"get(self): pass def post(self): if request.method == 'POST': body = json.loads(request.get_data()) options =",
"\"True\": try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(entities=EntitiesOptions(limit=1))).get_result() entity = sorted(response['entities'], key=itemgetter('relevance'), reverse=True)",
"indent=2)) try: for tone in tone_analysis['sentences_tone']: try: if tone['tones'][0]['tone_name'] == \"Joy\": tempDict =",
"'anger' keywords_sentiments_emotions.append( keywords_sentiments_emotions_buffer) myJsonDict.update({\"sentiments\": keywords_sentiments_emotions}) except: myJsonDict.update({\"sentiments\": \"Text too small to extract sentiments\"})",
"''' Prepare the text for Analysis''' with open('static/transcripts/'+fileName, 'r') as text_file: text =",
"keywords_sentiments_emotions_buffer = { 'keyword': i['text'], 'sentiment': i['sentiment']['label'], 'emotion': '' } maximum = i['emotion']['sadness']",
"bigger document.', \"score\": '100'} myJsonDict.update( {\"positiveSentences\": [tempDict]}) # return sentences_with_joy[:5] ['text'] ['score'] else:",
"''' Pre-Processing parts of speech to plot Word Cloud ''' try: response =",
"maximum = i['emotion']['anger'] keywords_sentiments_emotions_buffer['emotion'] = 'anger' keywords_sentiments_emotions.append( keywords_sentiments_emotions_buffer) myJsonDict.update({\"sentiments\": keywords_sentiments_emotions}) except: myJsonDict.update({\"sentiments\": \"Text",
"Extract Sentiments and Emotions with NLU ''' if options.get('sentiments') == \"True\": try: response",
"comment_words_nouns_adj = ' ' stopwords = set(STOPWORDS) for val in verbs: val =",
"enter the credentials and try again.\") def get(self): pass def post(self): if request.method",
"to get top 5 positive sentences ''' if options.get('positiveSentences') == \"True\": tone_analysis =",
"to extract concepts\"}) else: pass ''' Extract Entity with NLU ''' if options.get('entity')",
"== \"True\": try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(concepts=ConceptsOptions(limit=3))).get_result() concepts = sorted(response['concepts'], key=itemgetter('relevance'),",
"fileName = body.get('filename') ''' Prepare the text for Analysis''' with open('static/transcripts/'+fileName, 'r') as",
"+ ' ' wordcloud_verbs = WordCloud(width=800, height=800, background_color='white', stopwords=stopwords, min_font_size=10, max_font_size=150, random_state=42).generate(comment_words_verbs) wordcloud_nouns_adj",
"sentences_with_joy = sorted( sentences_with_joy, key=itemgetter('score'), reverse=True) myJsonDict.update( {\"positiveSentences\": sentences_with_joy[:5]}) except: tempDict = {\"sentence_id\":",
"from ibm_watson import ToneAnalyzerV3 from ibm_watson.natural_language_understanding_v1 \\ import Features, EntitiesOptions, KeywordsOptions, \\ SyntaxOptions,",
"{\"positiveSentences\": sentences_with_joy[:5]}) except: tempDict = {\"sentence_id\": '', \"text\": 'Text file too small to",
"__init__(self): try: with open('naturallanguageunderstanding.json', 'r') as credentialsFile: credentials1 = json.loads(credentialsFile.read()) self.NLU_API_KEY_ID = credentials1.get('apikey')",
"IAMAuthenticator(self.NLU_API_KEY_ID) natural_language_understanding = NaturalLanguageUnderstandingV1( version='2021-08-01', authenticator=nlu_authenticator ) natural_language_understanding.set_service_url(self.NLU_URL) self.natural_language_understanding = natural_language_understanding except json.decoder.JSONDecodeError:",
"WordCloud(width=800, height=800, background_color='white', colormap=\"Dark2\", stopwords=stopwords, min_font_size=10, max_font_size=150, random_state=42).generate(comment_words_nouns_adj) todayDate = datetime.today().strftime('%m-%d-%Y-%s') verbsWC =",
"== 'POST': body = json.loads(request.get_data()) options = body fileName = body.get('filename') ''' Prepare",
"= credentials2.get('url') tone_analyzer_authenticator = IAMAuthenticator(self.TONE_API_KEY_ID) tone_analyzer = ToneAnalyzerV3( version='2017-09-21', authenticator=tone_analyzer_authenticator ) tone_analyzer.set_service_url(self.TONE_URL) self.tone_analyzer",
"i['emotion']['joy'] > maximum: maximum = i['emotion']['joy'] keywords_sentiments_emotions_buffer['emotion'] = 'joy' elif i['emotion']['fear'] > maximum:",
"the credentials and try again.\") try: with open('toneanalyzer.json', 'r') as credentialsFile: credentials2 =",
"+ ' ' for val in nouns_adjectives: val = str(val) tokens = val.split()",
"myJsonDict = {} ''' Extract Category with NLU ''' if options.get('category') == \"True\":",
"= credentials1.get('url') nlu_authenticator = IAMAuthenticator(self.NLU_API_KEY_ID) natural_language_understanding = NaturalLanguageUnderstandingV1( version='2021-08-01', authenticator=nlu_authenticator ) natural_language_understanding.set_service_url(self.NLU_URL) self.natural_language_understanding",
"tone to get top 5 positive sentences ''' if options.get('positiveSentences') == \"True\": tone_analysis",
"i in response['syntax']['tokens']: if i['part_of_speech'] == 'VERB': verbs.append(i['text']) nouns = [] for i",
"too small to extract concepts\"}) else: pass ''' Extract Entity with NLU '''",
"\\ import Features, EntitiesOptions, KeywordsOptions, \\ SyntaxOptions, SyntaxOptionsTokens, CategoriesOptions, ConceptsOptions from ibm_cloud_sdk_core.authenticators import",
"SyntaxOptions, SyntaxOptionsTokens, CategoriesOptions, ConceptsOptions from ibm_cloud_sdk_core.authenticators import IAMAuthenticator from flask import request, jsonify",
"= set(STOPWORDS) for val in verbs: val = str(val) tokens = val.split() for",
"please try again with a bigger document.', \"score\": '100'} myJsonDict.update( {\"positiveSentences\": [tempDict]}) #",
"file is empty, please enter the credentials and try again.\") def get(self): pass",
"lemma=True, part_of_speech=True, )))).get_result() verbs = [] for i in response['syntax']['tokens']: if i['part_of_speech'] ==",
"import NaturalLanguageUnderstandingV1 from ibm_watson import ToneAnalyzerV3 from ibm_watson.natural_language_understanding_v1 \\ import Features, EntitiesOptions, KeywordsOptions,",
"[] for i in response['syntax']['tokens']: if i['part_of_speech'] == 'NOUN': nouns.append(i['text']) adj = []",
"else: pass ''' Extract Entity with NLU ''' if options.get('entity') == \"True\": try:",
"= sorted( sentences_with_joy, key=itemgetter('score'), reverse=True) myJsonDict.update( {\"positiveSentences\": sentences_with_joy[:5]}) except: tempDict = {\"sentence_id\": '',",
"Pre-Processing parts of speech to plot Word Cloud ''' try: response = self.natural_language_understanding.analyze(",
"NLU_URL = \"\" TONE_API_KEY_ID = \"\" TONE_URL = \"\" def __init__(self): try: with",
"flask import request, jsonify from operator import itemgetter from wordcloud import WordCloud, STOPWORDS",
"jsonify from operator import itemgetter from wordcloud import WordCloud, STOPWORDS import matplotlib.pyplot as",
"reverse=True) myJsonDict.update({\"entity\": entity[0]}) except: myJsonDict.update({\"entity\": \"Text too small to extract entity\"}) else: pass",
"top 5 positive sentences ''' if options.get('positiveSentences') == \"True\": tone_analysis = self.tone_analyzer.tone( {'text':",
"[tempDict]}) # return sentences_with_joy[:5] ['text'] ['score'] else: pass ''' Pre-Processing parts of speech",
"nlu_authenticator = IAMAuthenticator(self.NLU_API_KEY_ID) natural_language_understanding = NaturalLanguageUnderstandingV1( version='2021-08-01', authenticator=nlu_authenticator ) natural_language_understanding.set_service_url(self.NLU_URL) self.natural_language_understanding = natural_language_understanding",
"} maximum = i['emotion']['sadness'] keywords_sentiments_emotions_buffer['emotion'] = 'sadness' if i['emotion']['joy'] > maximum: maximum =",
"features=Features(concepts=ConceptsOptions(limit=3))).get_result() concepts = sorted(response['concepts'], key=itemgetter('relevance'), reverse=True) myJsonDict.update({\"concepts\": concepts}) except: myJsonDict.update({\"concepts\": \"Text too small",
"{\"sentence_id\": '', \"text\": 'Text file too small to get positive sentences, please try",
"entity[0]}) except: myJsonDict.update({\"entity\": \"Text too small to extract entity\"}) else: pass ''' Extract",
"KeywordsOptions, \\ SyntaxOptions, SyntaxOptionsTokens, CategoriesOptions, ConceptsOptions from ibm_cloud_sdk_core.authenticators import IAMAuthenticator from flask import",
"TONE_URL = \"\" def __init__(self): try: with open('naturallanguageunderstanding.json', 'r') as credentialsFile: credentials1 =",
"wordcloud_nouns_adj = WordCloud(width=800, height=800, background_color='white', colormap=\"Dark2\", stopwords=stopwords, min_font_size=10, max_font_size=150, random_state=42).generate(comment_words_nouns_adj) todayDate = datetime.today().strftime('%m-%d-%Y-%s')",
"# return sentences_with_joy[:5] ['text'] ['score'] else: pass ''' Pre-Processing parts of speech to",
"pass ''' Pre-Processing parts of speech to plot Word Cloud ''' try: response",
"= body fileName = body.get('filename') ''' Prepare the text for Analysis''' with open('static/transcripts/'+fileName,",
"as credentialsFile: credentials2 = json.loads(credentialsFile.read()) self.TONE_API_KEY_ID = credentials2.get('apikey') self.TONE_URL = credentials2.get('url') tone_analyzer_authenticator =",
"again.\") def get(self): pass def post(self): if request.method == 'POST': body = json.loads(request.get_data())",
"Language Understanding credentials file is empty, please enter the credentials and try again.\")",
"datetime.today().strftime('%m-%d-%Y-%s') verbsWC = \"static/images/verbs\"+todayDate+'.png' plt.switch_backend('Agg') plt.figure(figsize=(5, 5), facecolor=None) plt.imshow(wordcloud_verbs) plt.axis(\"off\") plt.tight_layout(pad=0) plt.savefig(verbsWC, title=True)",
"i['emotion']['fear'] keywords_sentiments_emotions_buffer['emotion'] = 'fear' elif i['emotion']['disgust'] > maximum: maximum = i['emotion']['disgust'] keywords_sentiments_emotions_buffer['emotion'] =",
"tokens[i] = tokens[i].lower() for words in tokens: comment_words_verbs = comment_words_verbs + words +",
"background_color='white', colormap=\"Dark2\", stopwords=stopwords, min_font_size=10, max_font_size=150, random_state=42).generate(comment_words_nouns_adj) todayDate = datetime.today().strftime('%m-%d-%Y-%s') verbsWC = \"static/images/verbs\"+todayDate+'.png' plt.switch_backend('Agg')",
"5), facecolor=None) plt.imshow(wordcloud_verbs) plt.axis(\"off\") plt.tight_layout(pad=0) plt.savefig(verbsWC, title=True) nounsAdjWC = \"static/images/nouns_adjectives\"+todayDate+'.png' plt.switch_backend('Agg') plt.figure(figsize=(5, 5),",
"i['emotion']['sadness'] keywords_sentiments_emotions_buffer['emotion'] = 'sadness' if i['emotion']['joy'] > maximum: maximum = i['emotion']['joy'] keywords_sentiments_emotions_buffer['emotion'] =",
"nouns = [] for i in response['syntax']['tokens']: if i['part_of_speech'] == 'NOUN': nouns.append(i['text']) adj",
"adj: nouns_adjectives.append(y) comment_words_verbs = ' ' comment_words_nouns_adj = ' ' stopwords = set(STOPWORDS)",
"keywords_sentiments_emotions_buffer['emotion'] = 'disguest' elif i['emotion']['anger'] > maximum: maximum = i['emotion']['anger'] keywords_sentiments_emotions_buffer['emotion'] = 'anger'",
"plt.savefig(nounsAdjWC, title=True) wordclouds = [nounsAdjWC, verbsWC] myJsonDict.update({\"wordclouds\": wordclouds}) except: myJsonDict.update({\"wordclouds\": \"Text too small",
"'', \"text\": 'Text file too small to get positive sentences, please try again",
"myJsonDict.update({\"concepts\": concepts}) except: myJsonDict.update({\"concepts\": \"Text too small to extract concepts\"}) else: pass '''",
"key=itemgetter('score'), reverse=True) myJsonDict.update( {\"positiveSentences\": sentences_with_joy[:5]}) except: tempDict = {\"sentence_id\": '', \"text\": 'Text file",
"= ToneAnalyzerV3( version='2017-09-21', authenticator=tone_analyzer_authenticator ) tone_analyzer.set_service_url(self.TONE_URL) self.tone_analyzer = tone_analyzer except json.decoder.JSONDecodeError: print(\"Tone Analyzer",
"val in nouns_adjectives: val = str(val) tokens = val.split() for i in range(len(tokens)):",
"tone['tones'][0]['score']} sentences_with_joy.append(tempDict) except: continue sentences_with_joy = sorted( sentences_with_joy, key=itemgetter('score'), reverse=True) myJsonDict.update( {\"positiveSentences\": sentences_with_joy[:5]})",
"verbsWC = \"static/images/verbs\"+todayDate+'.png' plt.switch_backend('Agg') plt.figure(figsize=(5, 5), facecolor=None) plt.imshow(wordcloud_verbs) plt.axis(\"off\") plt.tight_layout(pad=0) plt.savefig(verbsWC, title=True) nounsAdjWC",
"for val in verbs: val = str(val) tokens = val.split() for i in",
"entity\"}) else: pass ''' Extract Sentiments and Emotions with NLU ''' if options.get('sentiments')",
"i in range(len(tokens)): tokens[i] = tokens[i].lower() for words in tokens: comment_words_nouns_adj = comment_words_nouns_adj",
"= 'joy' elif i['emotion']['fear'] > maximum: maximum = i['emotion']['fear'] keywords_sentiments_emotions_buffer['emotion'] = 'fear' elif",
"tokens: comment_words_nouns_adj = comment_words_nouns_adj + words + ' ' wordcloud_verbs = WordCloud(width=800, height=800,",
"= sorted(response['concepts'], key=itemgetter('relevance'), reverse=True) myJsonDict.update({\"concepts\": concepts}) except: myJsonDict.update({\"concepts\": \"Text too small to extract",
"WordCloud, STOPWORDS import matplotlib.pyplot as plt from datetime import datetime class WatsonNLUTA(Resource): NLU_API_KEY_ID",
"request.method == 'POST': body = json.loads(request.get_data()) options = body fileName = body.get('filename') '''",
"empty, please enter the credentials and try again.\") def get(self): pass def post(self):",
"= i['emotion']['sadness'] keywords_sentiments_emotions_buffer['emotion'] = 'sadness' if i['emotion']['joy'] > maximum: maximum = i['emotion']['joy'] keywords_sentiments_emotions_buffer['emotion']",
"= {} ''' Extract Category with NLU ''' if options.get('category') == \"True\": try:",
"myJsonDict.update({\"category\": category}) except: myJsonDict.update({\"category\": \"Text too small to extract category\"}) else: pass '''",
"for i in keywords: keywords_sentiments_emotions_buffer = { 'keyword': i['text'], 'sentiment': i['sentiment']['label'], 'emotion': ''",
"import itemgetter from wordcloud import WordCloud, STOPWORDS import matplotlib.pyplot as plt from datetime",
"authenticator=nlu_authenticator ) natural_language_understanding.set_service_url(self.NLU_URL) self.natural_language_understanding = natural_language_understanding except json.decoder.JSONDecodeError: print(\"Natural Language Understanding credentials file",
"for i in range(len(tokens)): tokens[i] = tokens[i].lower() for words in tokens: comment_words_verbs =",
"\"Text too small to extract entity\"}) else: pass ''' Extract Sentiments and Emotions",
"positive sentences, please try again with a bigger document.', \"score\": '100'} myJsonDict.update( {\"positiveSentences\":",
"text=text, features=Features(entities=EntitiesOptions(limit=1))).get_result() entity = sorted(response['entities'], key=itemgetter('relevance'), reverse=True) myJsonDict.update({\"entity\": entity[0]}) except: myJsonDict.update({\"entity\": \"Text too",
"import ToneAnalyzerV3 from ibm_watson.natural_language_understanding_v1 \\ import Features, EntitiesOptions, KeywordsOptions, \\ SyntaxOptions, SyntaxOptionsTokens, CategoriesOptions,",
"extract concepts\"}) else: pass ''' Extract Entity with NLU ''' if options.get('entity') ==",
"keywords_sentiments_emotions = [] for i in keywords: keywords_sentiments_emotions_buffer = { 'keyword': i['text'], 'sentiment':",
"STOPWORDS import matplotlib.pyplot as plt from datetime import datetime class WatsonNLUTA(Resource): NLU_API_KEY_ID =",
"i['emotion']['anger'] > maximum: maximum = i['emotion']['anger'] keywords_sentiments_emotions_buffer['emotion'] = 'anger' keywords_sentiments_emotions.append( keywords_sentiments_emotions_buffer) myJsonDict.update({\"sentiments\": keywords_sentiments_emotions})",
"open('static/transcripts/'+fileName, 'r') as text_file: text = text_file.read() ''' Initialize a return variable '''",
"import IAMAuthenticator from flask import request, jsonify from operator import itemgetter from wordcloud",
"language='en', text=text, features=Features(concepts=ConceptsOptions(limit=3))).get_result() concepts = sorted(response['concepts'], key=itemgetter('relevance'), reverse=True) myJsonDict.update({\"concepts\": concepts}) except: myJsonDict.update({\"concepts\": \"Text",
"features=Features( syntax=SyntaxOptions( sentences=True, tokens=SyntaxOptionsTokens( lemma=True, part_of_speech=True, )))).get_result() verbs = [] for i in",
"self.natural_language_understanding = natural_language_understanding except json.decoder.JSONDecodeError: print(\"Natural Language Understanding credentials file is empty, please",
"keywords: keywords_sentiments_emotions_buffer = { 'keyword': i['text'], 'sentiment': i['sentiment']['label'], 'emotion': '' } maximum =",
"tone in tone_analysis['sentences_tone']: try: if tone['tones'][0]['tone_name'] == \"Joy\": tempDict = {\"sentence_id\": tone['sentence_id'], \"text\":",
"myJsonDict.update({\"entity\": entity[0]}) except: myJsonDict.update({\"entity\": \"Text too small to extract entity\"}) else: pass '''",
"NLU ''' if options.get('sentiments') == \"True\": try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(keywords=KeywordsOptions(sentiment=True,",
"and try again.\") try: with open('toneanalyzer.json', 'r') as credentialsFile: credentials2 = json.loads(credentialsFile.read()) self.TONE_API_KEY_ID",
"is empty, please enter the credentials and try again.\") try: with open('toneanalyzer.json', 'r')",
"continue sentences_with_joy = sorted( sentences_with_joy, key=itemgetter('score'), reverse=True) myJsonDict.update( {\"positiveSentences\": sentences_with_joy[:5]}) except: tempDict =",
"= \"\" def __init__(self): try: with open('naturallanguageunderstanding.json', 'r') as credentialsFile: credentials1 = json.loads(credentialsFile.read())",
"nouns.append(i['text']) adj = [] for i in response['syntax']['tokens']: if i['part_of_speech'] == 'ADJ': adj.append(i['text'])",
"with open('naturallanguageunderstanding.json', 'r') as credentialsFile: credentials1 = json.loads(credentialsFile.read()) self.NLU_API_KEY_ID = credentials1.get('apikey') self.NLU_URL =",
"reverse=True) myJsonDict.update({\"concepts\": concepts}) except: myJsonDict.update({\"concepts\": \"Text too small to extract concepts\"}) else: pass",
"try again.\") def get(self): pass def post(self): if request.method == 'POST': body =",
"tone['tones'][0]['tone_name'] == \"Joy\": tempDict = {\"sentence_id\": tone['sentence_id'], \"text\": tone['text'], \"score\": tone['tones'][0]['score']} sentences_with_joy.append(tempDict) except:",
"\"True\": tone_analysis = self.tone_analyzer.tone( {'text': text}, content_type='application/json' ).get_result() sentences_with_joy = [] # print(json.dumps(tone_analysis,",
"= [] for x in nouns: nouns_adjectives.append(x) for y in adj: nouns_adjectives.append(y) comment_words_verbs",
"Prepare the text for Analysis''' with open('static/transcripts/'+fileName, 'r') as text_file: text = text_file.read()",
"\"True\": try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(categories=CategoriesOptions(limit=1))).get_result() category = response['categories'][0] myJsonDict.update({\"category\": category})",
"i in range(len(tokens)): tokens[i] = tokens[i].lower() for words in tokens: comment_words_verbs = comment_words_verbs",
"pass ''' Extract Concepts with NLU ''' if options.get('concepts') == \"True\": try: response",
"[nounsAdjWC, verbsWC] myJsonDict.update({\"wordclouds\": wordclouds}) except: myJsonDict.update({\"wordclouds\": \"Text too small to extract wordclouds\"}) #",
"datetime class WatsonNLUTA(Resource): NLU_API_KEY_ID = \"\" NLU_URL = \"\" TONE_API_KEY_ID = \"\" TONE_URL",
"maximum = i['emotion']['joy'] keywords_sentiments_emotions_buffer['emotion'] = 'joy' elif i['emotion']['fear'] > maximum: maximum = i['emotion']['fear']",
"keywords_sentiments_emotions_buffer['emotion'] = 'joy' elif i['emotion']['fear'] > maximum: maximum = i['emotion']['fear'] keywords_sentiments_emotions_buffer['emotion'] = 'fear'",
"reverse=True) myJsonDict.update( {\"positiveSentences\": sentences_with_joy[:5]}) except: tempDict = {\"sentence_id\": '', \"text\": 'Text file too",
"= self.natural_language_understanding.analyze( language='en', text=text, features=Features(categories=CategoriesOptions(limit=1))).get_result() category = response['categories'][0] myJsonDict.update({\"category\": category}) except: myJsonDict.update({\"category\": \"Text",
"Analyzer credentials file is empty, please enter the credentials and try again.\") def",
"== 'VERB': verbs.append(i['text']) nouns = [] for i in response['syntax']['tokens']: if i['part_of_speech'] ==",
"<gh_stars>0 from flask_restful import Resource import json from ibm_watson import NaturalLanguageUnderstandingV1 from ibm_watson",
"options.get('concepts') == \"True\": try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(concepts=ConceptsOptions(limit=3))).get_result() concepts = sorted(response['concepts'],",
"json.decoder.JSONDecodeError: print(\"Tone Analyzer credentials file is empty, please enter the credentials and try",
"= 'sadness' if i['emotion']['joy'] > maximum: maximum = i['emotion']['joy'] keywords_sentiments_emotions_buffer['emotion'] = 'joy' elif",
"' ' for val in nouns_adjectives: val = str(val) tokens = val.split() for",
"= \"\" NLU_URL = \"\" TONE_API_KEY_ID = \"\" TONE_URL = \"\" def __init__(self):",
"concepts = sorted(response['concepts'], key=itemgetter('relevance'), reverse=True) myJsonDict.update({\"concepts\": concepts}) except: myJsonDict.update({\"concepts\": \"Text too small to",
"range(len(tokens)): tokens[i] = tokens[i].lower() for words in tokens: comment_words_nouns_adj = comment_words_nouns_adj + words",
"too small to extract sentiments\"}) else: pass ''' Analyse tone to get top",
"maximum: maximum = i['emotion']['disgust'] keywords_sentiments_emotions_buffer['emotion'] = 'disguest' elif i['emotion']['anger'] > maximum: maximum =",
"syntax=SyntaxOptions( sentences=True, tokens=SyntaxOptionsTokens( lemma=True, part_of_speech=True, )))).get_result() verbs = [] for i in response['syntax']['tokens']:",
"Extract Category with NLU ''' if options.get('category') == \"True\": try: response = self.natural_language_understanding.analyze(",
"for val in nouns_adjectives: val = str(val) tokens = val.split() for i in",
"Entity with NLU ''' if options.get('entity') == \"True\": try: response = self.natural_language_understanding.analyze( language='en',",
"and Emotions with NLU ''' if options.get('sentiments') == \"True\": try: response = self.natural_language_understanding.analyze(",
"response['syntax']['tokens']: if i['part_of_speech'] == 'ADJ': adj.append(i['text']) nouns_adjectives = [] for x in nouns:",
"\"\" TONE_API_KEY_ID = \"\" TONE_URL = \"\" def __init__(self): try: with open('naturallanguageunderstanding.json', 'r')",
"comment_words_verbs + words + ' ' for val in nouns_adjectives: val = str(val)",
"i in response['syntax']['tokens']: if i['part_of_speech'] == 'ADJ': adj.append(i['text']) nouns_adjectives = [] for x",
"if options.get('positiveSentences') == \"True\": tone_analysis = self.tone_analyzer.tone( {'text': text}, content_type='application/json' ).get_result() sentences_with_joy =",
"except: myJsonDict.update({\"entity\": \"Text too small to extract entity\"}) else: pass ''' Extract Sentiments",
"= sorted(response['keywords'], key=itemgetter('relevance'), reverse=True) keywords_sentiments_emotions = [] for i in keywords: keywords_sentiments_emotions_buffer =",
"= [] for i in response['syntax']['tokens']: if i['part_of_speech'] == 'NOUN': nouns.append(i['text']) adj =",
"''' Analyse tone to get top 5 positive sentences ''' if options.get('positiveSentences') ==",
"= NaturalLanguageUnderstandingV1( version='2021-08-01', authenticator=nlu_authenticator ) natural_language_understanding.set_service_url(self.NLU_URL) self.natural_language_understanding = natural_language_understanding except json.decoder.JSONDecodeError: print(\"Natural Language",
"request, jsonify from operator import itemgetter from wordcloud import WordCloud, STOPWORDS import matplotlib.pyplot",
"variable ''' myJsonDict = {} ''' Extract Category with NLU ''' if options.get('category')",
"facecolor=None) plt.imshow(wordcloud_nouns_adj) plt.axis(\"off\") plt.tight_layout(pad=0) plt.savefig(nounsAdjWC, title=True) wordclouds = [nounsAdjWC, verbsWC] myJsonDict.update({\"wordclouds\": wordclouds}) except:",
"plot Word Cloud ''' try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features( syntax=SyntaxOptions( sentences=True,",
"to plot Word Cloud ''' try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features( syntax=SyntaxOptions(",
"= 'fear' elif i['emotion']['disgust'] > maximum: maximum = i['emotion']['disgust'] keywords_sentiments_emotions_buffer['emotion'] = 'disguest' elif",
"\"static/images/verbs\"+todayDate+'.png' plt.switch_backend('Agg') plt.figure(figsize=(5, 5), facecolor=None) plt.imshow(wordcloud_verbs) plt.axis(\"off\") plt.tight_layout(pad=0) plt.savefig(verbsWC, title=True) nounsAdjWC = \"static/images/nouns_adjectives\"+todayDate+'.png'",
"class WatsonNLUTA(Resource): NLU_API_KEY_ID = \"\" NLU_URL = \"\" TONE_API_KEY_ID = \"\" TONE_URL =",
"json.loads(credentialsFile.read()) self.TONE_API_KEY_ID = credentials2.get('apikey') self.TONE_URL = credentials2.get('url') tone_analyzer_authenticator = IAMAuthenticator(self.TONE_API_KEY_ID) tone_analyzer = ToneAnalyzerV3(",
"try: if tone['tones'][0]['tone_name'] == \"Joy\": tempDict = {\"sentence_id\": tone['sentence_id'], \"text\": tone['text'], \"score\": tone['tones'][0]['score']}",
"try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(concepts=ConceptsOptions(limit=3))).get_result() concepts = sorted(response['concepts'], key=itemgetter('relevance'), reverse=True) myJsonDict.update({\"concepts\":",
"if tone['tones'][0]['tone_name'] == \"Joy\": tempDict = {\"sentence_id\": tone['sentence_id'], \"text\": tone['text'], \"score\": tone['tones'][0]['score']} sentences_with_joy.append(tempDict)",
"version='2017-09-21', authenticator=tone_analyzer_authenticator ) tone_analyzer.set_service_url(self.TONE_URL) self.tone_analyzer = tone_analyzer except json.decoder.JSONDecodeError: print(\"Tone Analyzer credentials file",
"Initialize a return variable ''' myJsonDict = {} ''' Extract Category with NLU",
"text = text_file.read() ''' Initialize a return variable ''' myJsonDict = {} '''",
"pass ''' Extract Entity with NLU ''' if options.get('entity') == \"True\": try: response",
"nouns_adjectives: val = str(val) tokens = val.split() for i in range(len(tokens)): tokens[i] =",
"if request.method == 'POST': body = json.loads(request.get_data()) options = body fileName = body.get('filename')",
"Category with NLU ''' if options.get('category') == \"True\": try: response = self.natural_language_understanding.analyze( language='en',",
"sorted(response['entities'], key=itemgetter('relevance'), reverse=True) myJsonDict.update({\"entity\": entity[0]}) except: myJsonDict.update({\"entity\": \"Text too small to extract entity\"})",
"sentences_with_joy.append(tempDict) except: continue sentences_with_joy = sorted( sentences_with_joy, key=itemgetter('score'), reverse=True) myJsonDict.update( {\"positiveSentences\": sentences_with_joy[:5]}) except:",
"for words in tokens: comment_words_nouns_adj = comment_words_nouns_adj + words + ' ' wordcloud_verbs",
"small to extract sentiments\"}) else: pass ''' Analyse tone to get top 5",
"tone['sentence_id'], \"text\": tone['text'], \"score\": tone['tones'][0]['score']} sentences_with_joy.append(tempDict) except: continue sentences_with_joy = sorted( sentences_with_joy, key=itemgetter('score'),",
"= IAMAuthenticator(self.NLU_API_KEY_ID) natural_language_understanding = NaturalLanguageUnderstandingV1( version='2021-08-01', authenticator=nlu_authenticator ) natural_language_understanding.set_service_url(self.NLU_URL) self.natural_language_understanding = natural_language_understanding except",
"= str(val) tokens = val.split() for i in range(len(tokens)): tokens[i] = tokens[i].lower() for",
"NaturalLanguageUnderstandingV1 from ibm_watson import ToneAnalyzerV3 from ibm_watson.natural_language_understanding_v1 \\ import Features, EntitiesOptions, KeywordsOptions, \\",
"import WordCloud, STOPWORDS import matplotlib.pyplot as plt from datetime import datetime class WatsonNLUTA(Resource):",
"get top 5 positive sentences ''' if options.get('positiveSentences') == \"True\": tone_analysis = self.tone_analyzer.tone(",
"= self.natural_language_understanding.analyze( language='en', text=text, features=Features( syntax=SyntaxOptions( sentences=True, tokens=SyntaxOptionsTokens( lemma=True, part_of_speech=True, )))).get_result() verbs =",
"myJsonDict.update({\"concepts\": \"Text too small to extract concepts\"}) else: pass ''' Extract Entity with",
"'r') as credentialsFile: credentials2 = json.loads(credentialsFile.read()) self.TONE_API_KEY_ID = credentials2.get('apikey') self.TONE_URL = credentials2.get('url') tone_analyzer_authenticator",
"== \"True\": try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(categories=CategoriesOptions(limit=1))).get_result() category = response['categories'][0] myJsonDict.update({\"category\":",
"else: pass ''' Analyse tone to get top 5 positive sentences ''' if",
"'keyword': i['text'], 'sentiment': i['sentiment']['label'], 'emotion': '' } maximum = i['emotion']['sadness'] keywords_sentiments_emotions_buffer['emotion'] = 'sadness'",
"in adj: nouns_adjectives.append(y) comment_words_verbs = ' ' comment_words_nouns_adj = ' ' stopwords =",
"as plt from datetime import datetime class WatsonNLUTA(Resource): NLU_API_KEY_ID = \"\" NLU_URL =",
"''' Extract Entity with NLU ''' if options.get('entity') == \"True\": try: response =",
"from ibm_cloud_sdk_core.authenticators import IAMAuthenticator from flask import request, jsonify from operator import itemgetter",
"if options.get('sentiments') == \"True\": try: response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(keywords=KeywordsOptions(sentiment=True, emotion=True, limit=10))).get_result()",
"+ words + ' ' for val in nouns_adjectives: val = str(val) tokens",
"maximum: maximum = i['emotion']['anger'] keywords_sentiments_emotions_buffer['emotion'] = 'anger' keywords_sentiments_emotions.append( keywords_sentiments_emotions_buffer) myJsonDict.update({\"sentiments\": keywords_sentiments_emotions}) except: myJsonDict.update({\"sentiments\":",
"'emotion': '' } maximum = i['emotion']['sadness'] keywords_sentiments_emotions_buffer['emotion'] = 'sadness' if i['emotion']['joy'] > maximum:",
"from ibm_watson.natural_language_understanding_v1 \\ import Features, EntitiesOptions, KeywordsOptions, \\ SyntaxOptions, SyntaxOptionsTokens, CategoriesOptions, ConceptsOptions from",
"credentials1.get('url') nlu_authenticator = IAMAuthenticator(self.NLU_API_KEY_ID) natural_language_understanding = NaturalLanguageUnderstandingV1( version='2021-08-01', authenticator=nlu_authenticator ) natural_language_understanding.set_service_url(self.NLU_URL) self.natural_language_understanding =",
"with a bigger document.', \"score\": '100'} myJsonDict.update( {\"positiveSentences\": [tempDict]}) # return sentences_with_joy[:5] ['text']",
"response = self.natural_language_understanding.analyze( language='en', text=text, features=Features(categories=CategoriesOptions(limit=1))).get_result() category = response['categories'][0] myJsonDict.update({\"category\": category}) except: myJsonDict.update({\"category\":",
"= ' ' comment_words_nouns_adj = ' ' stopwords = set(STOPWORDS) for val in",
"too small to extract entity\"}) else: pass ''' Extract Sentiments and Emotions with",
"please enter the credentials and try again.\") try: with open('toneanalyzer.json', 'r') as credentialsFile:",
"ToneAnalyzerV3 from ibm_watson.natural_language_understanding_v1 \\ import Features, EntitiesOptions, KeywordsOptions, \\ SyntaxOptions, SyntaxOptionsTokens, CategoriesOptions, ConceptsOptions",
"try: for tone in tone_analysis['sentences_tone']: try: if tone['tones'][0]['tone_name'] == \"Joy\": tempDict = {\"sentence_id\":",
"self.tone_analyzer.tone( {'text': text}, content_type='application/json' ).get_result() sentences_with_joy = [] # print(json.dumps(tone_analysis, indent=2)) try: for",
"datetime import datetime class WatsonNLUTA(Resource): NLU_API_KEY_ID = \"\" NLU_URL = \"\" TONE_API_KEY_ID =",
"except: myJsonDict.update({\"category\": \"Text too small to extract category\"}) else: pass ''' Extract Concepts",
"for i in range(len(tokens)): tokens[i] = tokens[i].lower() for words in tokens: comment_words_nouns_adj =",
"+ words + ' ' wordcloud_verbs = WordCloud(width=800, height=800, background_color='white', stopwords=stopwords, min_font_size=10, max_font_size=150,",
"verbsWC] myJsonDict.update({\"wordclouds\": wordclouds}) except: myJsonDict.update({\"wordclouds\": \"Text too small to extract wordclouds\"}) # print(json.dumps(myJsonDict,"
] |
[
"import simplejson as json class TestBasic(TestAPNS): def test_construct_service(self): service = self.create_service() service.start() service.stop()",
"is None) self.assertTrue(service._error_greenlet is None) def test_construct_message(self): msg = self.create_message() encoded = str(msg)",
"as json class TestBasic(TestAPNS): def test_construct_service(self): service = self.create_service() service.start() service.stop() self.assertTrue(service._send_greenlet is",
"m = json.loads(data) self.assertTrue(\"aps\" in m) def test_send_message(self): service = self.create_service() service.start() service.send(self.create_message())",
"applepushnotification import * from unittest import TestCase from applepushnotification.tests import TestAPNS import struct,",
"class TestBasic(TestAPNS): def test_construct_service(self): service = self.create_service() service.start() service.stop() self.assertTrue(service._send_greenlet is None) self.assertTrue(service._error_greenlet",
"e: import simplejson as json class TestBasic(TestAPNS): def test_construct_service(self): service = self.create_service() service.start()",
"from unittest import TestCase from applepushnotification.tests import TestAPNS import struct, time try: import",
"self.assertTrue(service._error_greenlet is None) def test_construct_message(self): msg = self.create_message() encoded = str(msg) command, identifier,",
"self.create_service() service.start() service.stop() self.assertTrue(service._send_greenlet is None) self.assertTrue(service._error_greenlet is None) def test_construct_message(self): msg =",
"is None) def test_construct_message(self): msg = self.create_message() encoded = str(msg) command, identifier, expiry,",
"command, identifier, expiry, tok_length = struct.unpack(\"!bIIH\", encoded[0:11]) self.assertEquals(command, 1) self.assertEquals(identifier, msg.identifier) self.assertTrue(expiry >",
"self.assertEquals(tok_length, 32) data = encoded[45:] m = json.loads(data) self.assertTrue(\"aps\" in m) def test_send_message(self):",
"> time.time()) self.assertEquals(tok_length, 32) data = encoded[45:] m = json.loads(data) self.assertTrue(\"aps\" in m)",
"import json except ImportError, e: import simplejson as json class TestBasic(TestAPNS): def test_construct_service(self):",
"import TestAPNS import struct, time try: import json except ImportError, e: import simplejson",
"simplejson as json class TestBasic(TestAPNS): def test_construct_service(self): service = self.create_service() service.start() service.stop() self.assertTrue(service._send_greenlet",
"= encoded[45:] m = json.loads(data) self.assertTrue(\"aps\" in m) def test_send_message(self): service = self.create_service()",
"from applepushnotification.tests import TestAPNS import struct, time try: import json except ImportError, e:",
"self.assertEquals(command, 1) self.assertEquals(identifier, msg.identifier) self.assertTrue(expiry > time.time()) self.assertEquals(tok_length, 32) data = encoded[45:] m",
"def test_construct_service(self): service = self.create_service() service.start() service.stop() self.assertTrue(service._send_greenlet is None) self.assertTrue(service._error_greenlet is None)",
"self.assertTrue(expiry > time.time()) self.assertEquals(tok_length, 32) data = encoded[45:] m = json.loads(data) self.assertTrue(\"aps\" in",
"* from unittest import TestCase from applepushnotification.tests import TestAPNS import struct, time try:",
"= self.create_service() service.start() service.stop() self.assertTrue(service._send_greenlet is None) self.assertTrue(service._error_greenlet is None) def test_construct_message(self): msg",
"32) data = encoded[45:] m = json.loads(data) self.assertTrue(\"aps\" in m) def test_send_message(self): service",
"try: import json except ImportError, e: import simplejson as json class TestBasic(TestAPNS): def",
"msg.identifier) self.assertTrue(expiry > time.time()) self.assertEquals(tok_length, 32) data = encoded[45:] m = json.loads(data) self.assertTrue(\"aps\"",
"encoded[45:] m = json.loads(data) self.assertTrue(\"aps\" in m) def test_send_message(self): service = self.create_service() service.start()",
"TestCase from applepushnotification.tests import TestAPNS import struct, time try: import json except ImportError,",
"#!/usr/bin/env python from applepushnotification import * from unittest import TestCase from applepushnotification.tests import",
"import TestCase from applepushnotification.tests import TestAPNS import struct, time try: import json except",
"service = self.create_service() service.start() service.stop() self.assertTrue(service._send_greenlet is None) self.assertTrue(service._error_greenlet is None) def test_construct_message(self):",
"self.create_message() encoded = str(msg) command, identifier, expiry, tok_length = struct.unpack(\"!bIIH\", encoded[0:11]) self.assertEquals(command, 1)",
"applepushnotification.tests import TestAPNS import struct, time try: import json except ImportError, e: import",
"= json.loads(data) self.assertTrue(\"aps\" in m) def test_send_message(self): service = self.create_service() service.start() service.send(self.create_message()) self.assertTrue(service.stop())",
"test_construct_service(self): service = self.create_service() service.start() service.stop() self.assertTrue(service._send_greenlet is None) self.assertTrue(service._error_greenlet is None) def",
"struct, time try: import json except ImportError, e: import simplejson as json class",
"encoded = str(msg) command, identifier, expiry, tok_length = struct.unpack(\"!bIIH\", encoded[0:11]) self.assertEquals(command, 1) self.assertEquals(identifier,",
"time try: import json except ImportError, e: import simplejson as json class TestBasic(TestAPNS):",
"test_construct_message(self): msg = self.create_message() encoded = str(msg) command, identifier, expiry, tok_length = struct.unpack(\"!bIIH\",",
"json class TestBasic(TestAPNS): def test_construct_service(self): service = self.create_service() service.start() service.stop() self.assertTrue(service._send_greenlet is None)",
"python from applepushnotification import * from unittest import TestCase from applepushnotification.tests import TestAPNS",
"except ImportError, e: import simplejson as json class TestBasic(TestAPNS): def test_construct_service(self): service =",
"service.start() service.stop() self.assertTrue(service._send_greenlet is None) self.assertTrue(service._error_greenlet is None) def test_construct_message(self): msg = self.create_message()",
"self.assertTrue(service._send_greenlet is None) self.assertTrue(service._error_greenlet is None) def test_construct_message(self): msg = self.create_message() encoded =",
"= str(msg) command, identifier, expiry, tok_length = struct.unpack(\"!bIIH\", encoded[0:11]) self.assertEquals(command, 1) self.assertEquals(identifier, msg.identifier)",
"unittest import TestCase from applepushnotification.tests import TestAPNS import struct, time try: import json",
"= self.create_message() encoded = str(msg) command, identifier, expiry, tok_length = struct.unpack(\"!bIIH\", encoded[0:11]) self.assertEquals(command,",
"None) def test_construct_message(self): msg = self.create_message() encoded = str(msg) command, identifier, expiry, tok_length",
"service.stop() self.assertTrue(service._send_greenlet is None) self.assertTrue(service._error_greenlet is None) def test_construct_message(self): msg = self.create_message() encoded",
"import struct, time try: import json except ImportError, e: import simplejson as json",
"from applepushnotification import * from unittest import TestCase from applepushnotification.tests import TestAPNS import",
"self.assertEquals(identifier, msg.identifier) self.assertTrue(expiry > time.time()) self.assertEquals(tok_length, 32) data = encoded[45:] m = json.loads(data)",
"ImportError, e: import simplejson as json class TestBasic(TestAPNS): def test_construct_service(self): service = self.create_service()",
"expiry, tok_length = struct.unpack(\"!bIIH\", encoded[0:11]) self.assertEquals(command, 1) self.assertEquals(identifier, msg.identifier) self.assertTrue(expiry > time.time()) self.assertEquals(tok_length,",
"msg = self.create_message() encoded = str(msg) command, identifier, expiry, tok_length = struct.unpack(\"!bIIH\", encoded[0:11])",
"data = encoded[45:] m = json.loads(data) self.assertTrue(\"aps\" in m) def test_send_message(self): service =",
"time.time()) self.assertEquals(tok_length, 32) data = encoded[45:] m = json.loads(data) self.assertTrue(\"aps\" in m) def",
"encoded[0:11]) self.assertEquals(command, 1) self.assertEquals(identifier, msg.identifier) self.assertTrue(expiry > time.time()) self.assertEquals(tok_length, 32) data = encoded[45:]",
"str(msg) command, identifier, expiry, tok_length = struct.unpack(\"!bIIH\", encoded[0:11]) self.assertEquals(command, 1) self.assertEquals(identifier, msg.identifier) self.assertTrue(expiry",
"TestAPNS import struct, time try: import json except ImportError, e: import simplejson as",
"struct.unpack(\"!bIIH\", encoded[0:11]) self.assertEquals(command, 1) self.assertEquals(identifier, msg.identifier) self.assertTrue(expiry > time.time()) self.assertEquals(tok_length, 32) data =",
"1) self.assertEquals(identifier, msg.identifier) self.assertTrue(expiry > time.time()) self.assertEquals(tok_length, 32) data = encoded[45:] m =",
"None) self.assertTrue(service._error_greenlet is None) def test_construct_message(self): msg = self.create_message() encoded = str(msg) command,",
"import * from unittest import TestCase from applepushnotification.tests import TestAPNS import struct, time",
"tok_length = struct.unpack(\"!bIIH\", encoded[0:11]) self.assertEquals(command, 1) self.assertEquals(identifier, msg.identifier) self.assertTrue(expiry > time.time()) self.assertEquals(tok_length, 32)",
"= struct.unpack(\"!bIIH\", encoded[0:11]) self.assertEquals(command, 1) self.assertEquals(identifier, msg.identifier) self.assertTrue(expiry > time.time()) self.assertEquals(tok_length, 32) data",
"TestBasic(TestAPNS): def test_construct_service(self): service = self.create_service() service.start() service.stop() self.assertTrue(service._send_greenlet is None) self.assertTrue(service._error_greenlet is",
"identifier, expiry, tok_length = struct.unpack(\"!bIIH\", encoded[0:11]) self.assertEquals(command, 1) self.assertEquals(identifier, msg.identifier) self.assertTrue(expiry > time.time())",
"def test_construct_message(self): msg = self.create_message() encoded = str(msg) command, identifier, expiry, tok_length =",
"json except ImportError, e: import simplejson as json class TestBasic(TestAPNS): def test_construct_service(self): service"
] |
[
"test_select(self): n = 1000 y = pd.Series(np.linspace(0, 100, n)) x = pd.DataFrame({'a': y,",
"100, 100)) b = pd.Series(np.linspace(-4, 4, 100) ** 2) x = pd.DataFrame({'a': y",
"pd.Series(np.random.randint(1, 100, 100)) b = pd.Series(np.linspace(-4, 4, 100)) x = pd.DataFrame({'a': np.cumsum(y), 'b':",
"fpn.load_settings(settings) for k, v in sets.items(): xtn = fpn.transform(x, k) assert len(v) ==",
"y = pd.Series(np.sin(np.linspace(0, 100, 100))) x = pd.DataFrame({'a': np.linspace(0, 100, 100)}) fp =",
"y) assert all([len(i) == 1 for i in sets.values()]), f\"Random Feature Selected: {sets}\"",
"test_diff(self): y = pd.Series(np.random.randint(1, 100, 100)) x = pd.DataFrame({'a': np.cumsum(y)}) fp = FeatureProcesser(mode='regression')",
"v in sets.items(): xtn = fpn.transform(x, k) assert len(v) == len(xtn.keys()), \"Incorrect number",
"spotted\" def test_diff(self): y = pd.Series(np.random.randint(1, 100, 100)) x = pd.DataFrame({'a': np.cumsum(y)}) fp",
"sets = fp.fit_transform(x, y) settings = fp.get_settings() fpn = FeatureProcesser(mode='regression') fpn.load_settings(settings) for k,",
"b / 2}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert set(fp.get_required_features(['a__x__b']))",
"!= 0, \"Difference feature not spotted\" def test_select(self): n = 1000 y =",
"** 2) x = pd.DataFrame({'a': y * b, 'b': b}) fp = FeatureProcesser(mode='regression')",
"x, y = make_regression() x, y = pd.DataFrame(x), pd.Series(y) fp = FeatureProcesser(max_lags=2, mode='regression')",
"= pd.Series(np.linspace(2, 100, 100)) x = pd.DataFrame({'a': np.linspace(-4, 4, 100), 'b': np.linspace(-4, 4,",
"fp = FeatureProcesser(max_lags=2, mode='classification') xt, sets = fp.fit_transform(x, y) def test_co_linearity(self): y =",
"fp.fit_transform(x, y) assert len(fp.coLinearFeatures) != 0, \"Colinear feature not removed\" def test_multiply_features(self): y",
"!= 0, \"Colinear feature not removed\" def test_multiply_features(self): y = pd.Series(np.linspace(2, 100, 100))",
"x = pd.DataFrame({'a': np.linspace(-4, 4, 100), 'b': np.linspace(-4, 4, 100)}) fp = FeatureProcesser(mode='regression')",
"fp.fit_transform(x, y) assert len(fp.laggedFeatures) != 0, \"Lagged feature not spotted\" def test_diff(self): y",
"'c': y / b, 'd': y * b}) fp = FeatureProcesser(mode='regression') xt, sets",
"def test_division(self): y = pd.Series(np.linspace(2, 100, 100)) b = pd.Series(np.linspace(-4, 4, 100) **",
"sklearn.datasets import make_classification from sklearn.datasets import make_regression from Amplo.AutoML import FeatureProcesser class TestFeatureProcessing(unittest.TestCase):",
"spotted\" def test_select(self): n = 1000 y = pd.Series(np.linspace(0, 100, n)) x =",
"= make_regression() x, y = pd.DataFrame(x), pd.Series(y) fp = FeatureProcesser(max_lags=2, mode='regression') xt, sets",
"y) assert len(fp.crossFeatures) != 0, \"Division feature not spotted\" def test_trigonometry(self): y =",
"100, n)) x = pd.DataFrame({'a': y, 'b': np.random.normal(0, 1, n)}) fp = FeatureProcesser(mode='regression')",
"= FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.crossFeatures) != 0, \"Division feature",
"feature not spotted\" def test_select(self): n = 1000 y = pd.Series(np.linspace(0, 100, n))",
"sets.values()]), f\"Random Feature Selected: {sets}\" def test_settings(self): y = pd.Series(np.random.randint(1, 100, 100)) b",
"assert np.allclose(xt[v], xtn), 'Transformed data not consistent for {} set'.format(k) def test_get_required(self): y",
"def test_diff(self): y = pd.Series(np.random.randint(1, 100, 100)) x = pd.DataFrame({'a': np.cumsum(y)}) fp =",
"** 2) x = pd.DataFrame({'a': y / b, 'b': b, 'c': b /",
"FeatureProcesser(max_lags=2, mode='classification') xt, sets = fp.fit_transform(x, y) def test_co_linearity(self): y = pd.Series(np.linspace(2, 100,",
"pd.Series(np.linspace(2, 100, 100)) x = pd.DataFrame({'a': np.linspace(-4, 4, 100), 'b': np.linspace(-4, 4, 100)})",
"FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) settings = fp.get_settings() fpn = FeatureProcesser(mode='regression') fpn.load_settings(settings)",
"feature not spotted\" def test_trigonometry(self): y = pd.Series(np.sin(np.linspace(0, 100, 100))) x = pd.DataFrame({'a':",
"def test_settings(self): y = pd.Series(np.random.randint(1, 100, 100)) b = pd.Series(np.linspace(-4, 4, 100)) x",
"xtn = fpn.transform(x, k) assert len(v) == len(xtn.keys()), \"Incorrect number of keys\" assert",
"as np import pandas as pd from sklearn.datasets import make_classification from sklearn.datasets import",
"2) x = pd.DataFrame({'a': y / b, 'b': b}) fp = FeatureProcesser(mode='regression') xt,",
"b = pd.Series(np.linspace(-4, 4, 100) ** 2) x = pd.DataFrame({'a': y / b,",
"'Keys are not correct' assert np.allclose(xt[v], xtn), 'Transformed data not consistent for {}",
"= FeatureProcesser(mode='regression') fpn.load_settings(settings) for k, v in sets.items(): xtn = fpn.transform(x, k) assert",
"setUpClass(cls): pass def test_regression(self): x, y = make_regression() x, y = pd.DataFrame(x), pd.Series(y)",
"fp.fit_transform(x, y) settings = fp.get_settings() fpn = FeatureProcesser(mode='regression') fpn.load_settings(settings) for k, v in",
"y = pd.Series(np.random.randint(1, 100, 100)) b = pd.Series(np.linspace(-4, 4, 100)) x = pd.DataFrame({'a':",
"= pd.Series(np.sin(np.linspace(0, 100, 100))) x = pd.DataFrame({'a': np.linspace(0, 100, 100)}) fp = FeatureProcesser(mode='regression')",
"xt, sets = fp.fit_transform(x, y) assert len(fp.trigonometricFeatures) != 0, \"Trigonometric feature not spotted\"",
"pd.Series(np.random.randint(0, 100, 100)) x = pd.DataFrame({'a': np.roll(y, -5)}) fp = FeatureProcesser(mode='regression') xt, sets",
"y / b, 'd': y * b}) fp = FeatureProcesser(mode='regression') xt, sets =",
"100) ** 2) x = pd.DataFrame({'a': y / b, 'b': b}) fp =",
"b, 'b': b}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.crossFeatures)",
"= pd.DataFrame(x), pd.Series(y) fp = FeatureProcesser(max_lags=2, mode='classification') xt, sets = fp.fit_transform(x, y) def",
"FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.crossFeatures) != 0, \"Division feature not",
"assert len(fp.trigonometricFeatures) != 0, \"Trigonometric feature not spotted\" def test_lagged(self): y = pd.Series(np.random.randint(0,",
"= FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.coLinearFeatures) != 0, \"Colinear feature",
"b}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.crossFeatures) != 0,",
"100, 100)) x = pd.DataFrame({'a': np.linspace(-4, 4, 100), 'b': np.linspace(-4, 4, 100)}) fp",
"mode='classification') xt, sets = fp.fit_transform(x, y) def test_co_linearity(self): y = pd.Series(np.linspace(2, 100, 100))",
"= fp.fit_transform(x, y) assert len(fp.crossFeatures) != 0, \"Multiplicative feature not spotted\" def test_division(self):",
"= FeatureProcesser(max_lags=2, mode='regression') xt, sets = fp.fit_transform(x, y) def test_classification(self): x, y =",
"FeatureProcesser(max_lags=2, mode='regression') xt, sets = fp.fit_transform(x, y) def test_classification(self): x, y = make_classification()",
"x = pd.DataFrame({'a': np.cumsum(y), 'b': np.roll(y, -5), 'c': y / b, 'd': y",
"xt, sets = fp.fit_transform(x, y) def test_co_linearity(self): y = pd.Series(np.linspace(2, 100, 100)) x",
"len(v) == len(xtn.keys()), \"Incorrect number of keys\" assert all(xt[v].keys() == xtn.keys()), 'Keys are",
"spotted\" def test_division(self): y = pd.Series(np.linspace(2, 100, 100)) b = pd.Series(np.linspace(-4, 4, 100)",
"len(fp.crossFeatures) != 0, \"Division feature not spotted\" def test_trigonometry(self): y = pd.Series(np.sin(np.linspace(0, 100,",
"= fp.fit_transform(x, y) settings = fp.get_settings() fpn = FeatureProcesser(mode='regression') fpn.load_settings(settings) for k, v",
"fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.laggedFeatures) != 0, \"Lagged",
"pandas as pd from sklearn.datasets import make_classification from sklearn.datasets import make_regression from Amplo.AutoML",
"4, 100)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.coLinearFeatures) !=",
"= pd.Series(np.linspace(-4, 4, 100) ** 2) x = pd.DataFrame({'a': y / b, 'b':",
"Selected: {sets}\" def test_settings(self): y = pd.Series(np.random.randint(1, 100, 100)) b = pd.Series(np.linspace(-4, 4,",
"0, \"Colinear feature not removed\" def test_multiply_features(self): y = pd.Series(np.linspace(2, 100, 100)) b",
"!= 0, \"Trigonometric feature not spotted\" def test_lagged(self): y = pd.Series(np.random.randint(0, 100, 100))",
"2}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert set(fp.get_required_features(['a__x__b'])) == set(['b',",
"100)) x = pd.DataFrame({'a': np.cumsum(y)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y)",
"\"Incorrect number of keys\" assert all(xt[v].keys() == xtn.keys()), 'Keys are not correct' assert",
"1, n)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert all([len(i) ==",
"not spotted\" def test_diff(self): y = pd.Series(np.random.randint(1, 100, 100)) x = pd.DataFrame({'a': np.cumsum(y)})",
"fp.fit_transform(x, y) def test_classification(self): x, y = make_classification() x, y = pd.DataFrame(x), pd.Series(y)",
"def setUpClass(cls): pass def test_regression(self): x, y = make_regression() x, y = pd.DataFrame(x),",
"\"Lagged feature not spotted\" def test_diff(self): y = pd.Series(np.random.randint(1, 100, 100)) x =",
"from sklearn.datasets import make_classification from sklearn.datasets import make_regression from Amplo.AutoML import FeatureProcesser class",
"removed\" def test_multiply_features(self): y = pd.Series(np.linspace(2, 100, 100)) b = pd.Series(np.linspace(-4, 4, 100)",
"assert all(xt[v].keys() == xtn.keys()), 'Keys are not correct' assert np.allclose(xt[v], xtn), 'Transformed data",
"def test_get_required(self): y = pd.Series(np.linspace(2, 100, 100)) b = pd.Series(np.linspace(-4, 4, 100) **",
"np import pandas as pd from sklearn.datasets import make_classification from sklearn.datasets import make_regression",
"n = 1000 y = pd.Series(np.linspace(0, 100, n)) x = pd.DataFrame({'a': y, 'b':",
"k, v in sets.items(): xtn = fpn.transform(x, k) assert len(v) == len(xtn.keys()), \"Incorrect",
"100) ** 2) x = pd.DataFrame({'a': y / b, 'b': b, 'c': b",
"xt, sets = fp.fit_transform(x, y) def test_classification(self): x, y = make_classification() x, y",
"= make_classification() x, y = pd.DataFrame(x), pd.Series(y) fp = FeatureProcesser(max_lags=2, mode='classification') xt, sets",
"fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.coLinearFeatures) != 0, \"Colinear",
"y = pd.DataFrame(x), pd.Series(y) fp = FeatureProcesser(max_lags=2, mode='classification') xt, sets = fp.fit_transform(x, y)",
"as pd from sklearn.datasets import make_classification from sklearn.datasets import make_regression from Amplo.AutoML import",
"100)) x = pd.DataFrame({'a': np.linspace(-4, 4, 100), 'b': np.linspace(-4, 4, 100)}) fp =",
"np.cumsum(y), 'b': np.roll(y, -5), 'c': y / b, 'd': y * b}) fp",
"are not correct' assert np.allclose(xt[v], xtn), 'Transformed data not consistent for {} set'.format(k)",
"= pd.DataFrame({'a': np.cumsum(y), 'b': np.roll(y, -5), 'c': y / b, 'd': y *",
"y = pd.Series(np.random.randint(1, 100, 100)) x = pd.DataFrame({'a': np.cumsum(y)}) fp = FeatureProcesser(mode='regression') xt,",
"!= 0, \"Division feature not spotted\" def test_trigonometry(self): y = pd.Series(np.sin(np.linspace(0, 100, 100)))",
"pd.Series(np.linspace(-4, 4, 100) ** 2) x = pd.DataFrame({'a': y / b, 'b': b,",
"test_division(self): y = pd.Series(np.linspace(2, 100, 100)) b = pd.Series(np.linspace(-4, 4, 100) ** 2)",
"= fp.fit_transform(x, y) def test_classification(self): x, y = make_classification() x, y = pd.DataFrame(x),",
"'d': y * b}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) settings",
"def test_lagged(self): y = pd.Series(np.random.randint(0, 100, 100)) x = pd.DataFrame({'a': np.roll(y, -5)}) fp",
"pd.DataFrame({'a': np.linspace(0, 100, 100)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert",
"= pd.DataFrame({'a': np.cumsum(y)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.diffFeatures)",
"test_classification(self): x, y = make_classification() x, y = pd.DataFrame(x), pd.Series(y) fp = FeatureProcesser(max_lags=2,",
"n)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert all([len(i) == 1",
"np.linspace(-4, 4, 100)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.coLinearFeatures)",
"0, \"Multiplicative feature not spotted\" def test_division(self): y = pd.Series(np.linspace(2, 100, 100)) b",
"/ b, 'd': y * b}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x,",
"fp.fit_transform(x, y) assert len(fp.trigonometricFeatures) != 0, \"Trigonometric feature not spotted\" def test_lagged(self): y",
"test_regression(self): x, y = make_regression() x, y = pd.DataFrame(x), pd.Series(y) fp = FeatureProcesser(max_lags=2,",
"4, 100) ** 2) x = pd.DataFrame({'a': y / b, 'b': b}) fp",
"test_co_linearity(self): y = pd.Series(np.linspace(2, 100, 100)) x = pd.DataFrame({'a': np.linspace(-4, 4, 100), 'b':",
"= pd.Series(np.linspace(0, 100, n)) x = pd.DataFrame({'a': y, 'b': np.random.normal(0, 1, n)}) fp",
"100))) x = pd.DataFrame({'a': np.linspace(0, 100, 100)}) fp = FeatureProcesser(mode='regression') xt, sets =",
"xt, sets = fp.fit_transform(x, y) settings = fp.get_settings() fpn = FeatureProcesser(mode='regression') fpn.load_settings(settings) for",
"fpn.transform(x, k) assert len(v) == len(xtn.keys()), \"Incorrect number of keys\" assert all(xt[v].keys() ==",
"y) assert len(fp.coLinearFeatures) != 0, \"Colinear feature not removed\" def test_multiply_features(self): y =",
"from Amplo.AutoML import FeatureProcesser class TestFeatureProcessing(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_regression(self): x,",
"not correct' assert np.allclose(xt[v], xtn), 'Transformed data not consistent for {} set'.format(k) def",
"sets = fp.fit_transform(x, y) assert len(fp.trigonometricFeatures) != 0, \"Trigonometric feature not spotted\" def",
"fp = FeatureProcesser(max_lags=2, mode='regression') xt, sets = fp.fit_transform(x, y) def test_classification(self): x, y",
"y) assert len(fp.diffFeatures) != 0, \"Difference feature not spotted\" def test_select(self): n =",
"FeatureProcesser class TestFeatureProcessing(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_regression(self): x, y = make_regression()",
"y / b, 'b': b, 'c': b / 2}) fp = FeatureProcesser(mode='regression') xt,",
"assert len(v) == len(xtn.keys()), \"Incorrect number of keys\" assert all(xt[v].keys() == xtn.keys()), 'Keys",
"== len(xtn.keys()), \"Incorrect number of keys\" assert all(xt[v].keys() == xtn.keys()), 'Keys are not",
"for i in sets.values()]), f\"Random Feature Selected: {sets}\" def test_settings(self): y = pd.Series(np.random.randint(1,",
"xt, sets = fp.fit_transform(x, y) assert len(fp.coLinearFeatures) != 0, \"Colinear feature not removed\"",
"def test_regression(self): x, y = make_regression() x, y = pd.DataFrame(x), pd.Series(y) fp =",
"FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.diffFeatures) != 0, \"Difference feature not",
"100)) b = pd.Series(np.linspace(-4, 4, 100)) x = pd.DataFrame({'a': np.cumsum(y), 'b': np.roll(y, -5),",
"fp.fit_transform(x, y) assert len(fp.crossFeatures) != 0, \"Multiplicative feature not spotted\" def test_division(self): y",
"y) assert len(fp.crossFeatures) != 0, \"Multiplicative feature not spotted\" def test_division(self): y =",
"x = pd.DataFrame({'a': np.cumsum(y)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert",
"pd.DataFrame(x), pd.Series(y) fp = FeatureProcesser(max_lags=2, mode='regression') xt, sets = fp.fit_transform(x, y) def test_classification(self):",
"assert len(fp.crossFeatures) != 0, \"Multiplicative feature not spotted\" def test_division(self): y = pd.Series(np.linspace(2,",
"pd.Series(np.linspace(2, 100, 100)) b = pd.Series(np.linspace(-4, 4, 100) ** 2) x = pd.DataFrame({'a':",
"\"Difference feature not spotted\" def test_select(self): n = 1000 y = pd.Series(np.linspace(0, 100,",
"set'.format(k) def test_get_required(self): y = pd.Series(np.linspace(2, 100, 100)) b = pd.Series(np.linspace(-4, 4, 100)",
"100, 100)) x = pd.DataFrame({'a': np.cumsum(y)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x,",
"len(fp.laggedFeatures) != 0, \"Lagged feature not spotted\" def test_diff(self): y = pd.Series(np.random.randint(1, 100,",
"pd.Series(y) fp = FeatureProcesser(max_lags=2, mode='classification') xt, sets = fp.fit_transform(x, y) def test_co_linearity(self): y",
"= fp.get_settings() fpn = FeatureProcesser(mode='regression') fpn.load_settings(settings) for k, v in sets.items(): xtn =",
"= pd.Series(np.linspace(-4, 4, 100) ** 2) x = pd.DataFrame({'a': y * b, 'b':",
"\"Colinear feature not removed\" def test_multiply_features(self): y = pd.Series(np.linspace(2, 100, 100)) b =",
"f\"Random Feature Selected: {sets}\" def test_settings(self): y = pd.Series(np.random.randint(1, 100, 100)) b =",
"100)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.trigonometricFeatures) != 0,",
"= fp.fit_transform(x, y) assert len(fp.coLinearFeatures) != 0, \"Colinear feature not removed\" def test_multiply_features(self):",
"= pd.DataFrame({'a': y, 'b': np.random.normal(0, 1, n)}) fp = FeatureProcesser(mode='regression') xt, sets =",
"'b': b}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.crossFeatures) !=",
"pd.Series(y) fp = FeatureProcesser(max_lags=2, mode='regression') xt, sets = fp.fit_transform(x, y) def test_classification(self): x,",
"xt, sets = fp.fit_transform(x, y) assert len(fp.crossFeatures) != 0, \"Division feature not spotted\"",
"= FeatureProcesser(max_lags=2, mode='classification') xt, sets = fp.fit_transform(x, y) def test_co_linearity(self): y = pd.Series(np.linspace(2,",
"= fp.fit_transform(x, y) assert len(fp.trigonometricFeatures) != 0, \"Trigonometric feature not spotted\" def test_lagged(self):",
"y) assert len(fp.trigonometricFeatures) != 0, \"Trigonometric feature not spotted\" def test_lagged(self): y =",
"pd.DataFrame({'a': np.roll(y, -5)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.laggedFeatures)",
"'b': np.roll(y, -5), 'c': y / b, 'd': y * b}) fp =",
"def test_multiply_features(self): y = pd.Series(np.linspace(2, 100, 100)) b = pd.Series(np.linspace(-4, 4, 100) **",
"!= 0, \"Lagged feature not spotted\" def test_diff(self): y = pd.Series(np.random.randint(1, 100, 100))",
"y * b}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) settings =",
"0, \"Lagged feature not spotted\" def test_diff(self): y = pd.Series(np.random.randint(1, 100, 100)) x",
"100, 100)) x = pd.DataFrame({'a': np.roll(y, -5)}) fp = FeatureProcesser(mode='regression') xt, sets =",
"xtn.keys()), 'Keys are not correct' assert np.allclose(xt[v], xtn), 'Transformed data not consistent for",
"fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) settings = fp.get_settings() fpn =",
"assert len(fp.diffFeatures) != 0, \"Difference feature not spotted\" def test_select(self): n = 1000",
"sets = fp.fit_transform(x, y) def test_classification(self): x, y = make_classification() x, y =",
"sets = fp.fit_transform(x, y) assert len(fp.crossFeatures) != 0, \"Multiplicative feature not spotted\" def",
"y * b, 'b': b}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y)",
"sets = fp.fit_transform(x, y) assert len(fp.diffFeatures) != 0, \"Difference feature not spotted\" def",
"y = make_regression() x, y = pd.DataFrame(x), pd.Series(y) fp = FeatureProcesser(max_lags=2, mode='regression') xt,",
"assert len(fp.laggedFeatures) != 0, \"Lagged feature not spotted\" def test_diff(self): y = pd.Series(np.random.randint(1,",
"2) x = pd.DataFrame({'a': y / b, 'b': b, 'c': b / 2})",
"def test_classification(self): x, y = make_classification() x, y = pd.DataFrame(x), pd.Series(y) fp =",
"= FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.crossFeatures) != 0, \"Multiplicative feature",
"FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.crossFeatures) != 0, \"Multiplicative feature not",
"4, 100) ** 2) x = pd.DataFrame({'a': y / b, 'b': b, 'c':",
"y = make_classification() x, y = pd.DataFrame(x), pd.Series(y) fp = FeatureProcesser(max_lags=2, mode='classification') xt,",
"not spotted\" def test_trigonometry(self): y = pd.Series(np.sin(np.linspace(0, 100, 100))) x = pd.DataFrame({'a': np.linspace(0,",
"pd.DataFrame({'a': y / b, 'b': b}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x,",
"x, y = make_classification() x, y = pd.DataFrame(x), pd.Series(y) fp = FeatureProcesser(max_lags=2, mode='classification')",
"feature not removed\" def test_multiply_features(self): y = pd.Series(np.linspace(2, 100, 100)) b = pd.Series(np.linspace(-4,",
"0, \"Trigonometric feature not spotted\" def test_lagged(self): y = pd.Series(np.random.randint(0, 100, 100)) x",
"feature not spotted\" def test_lagged(self): y = pd.Series(np.random.randint(0, 100, 100)) x = pd.DataFrame({'a':",
"make_classification() x, y = pd.DataFrame(x), pd.Series(y) fp = FeatureProcesser(max_lags=2, mode='classification') xt, sets =",
"numpy as np import pandas as pd from sklearn.datasets import make_classification from sklearn.datasets",
"= FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.trigonometricFeatures) != 0, \"Trigonometric feature",
"all(xt[v].keys() == xtn.keys()), 'Keys are not correct' assert np.allclose(xt[v], xtn), 'Transformed data not",
"import make_classification from sklearn.datasets import make_regression from Amplo.AutoML import FeatureProcesser class TestFeatureProcessing(unittest.TestCase): @classmethod",
"= pd.DataFrame({'a': y * b, 'b': b}) fp = FeatureProcesser(mode='regression') xt, sets =",
"= pd.Series(np.linspace(2, 100, 100)) b = pd.Series(np.linspace(-4, 4, 100) ** 2) x =",
"** 2) x = pd.DataFrame({'a': y / b, 'b': b}) fp = FeatureProcesser(mode='regression')",
"np.roll(y, -5)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.laggedFeatures) !=",
"4, 100)) x = pd.DataFrame({'a': np.cumsum(y), 'b': np.roll(y, -5), 'c': y / b,",
"= pd.Series(np.random.randint(1, 100, 100)) x = pd.DataFrame({'a': np.cumsum(y)}) fp = FeatureProcesser(mode='regression') xt, sets",
"y = pd.Series(np.linspace(2, 100, 100)) b = pd.Series(np.linspace(-4, 4, 100) ** 2) x",
"for {} set'.format(k) def test_get_required(self): y = pd.Series(np.linspace(2, 100, 100)) b = pd.Series(np.linspace(-4,",
"xt, sets = fp.fit_transform(x, y) assert all([len(i) == 1 for i in sets.values()]),",
"pd from sklearn.datasets import make_classification from sklearn.datasets import make_regression from Amplo.AutoML import FeatureProcesser",
"spotted\" def test_lagged(self): y = pd.Series(np.random.randint(0, 100, 100)) x = pd.DataFrame({'a': np.roll(y, -5)})",
"= fp.fit_transform(x, y) assert len(fp.diffFeatures) != 0, \"Difference feature not spotted\" def test_select(self):",
"-5)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.laggedFeatures) != 0,",
"FeatureProcesser(mode='regression') fpn.load_settings(settings) for k, v in sets.items(): xtn = fpn.transform(x, k) assert len(v)",
"x = pd.DataFrame({'a': y * b, 'b': b}) fp = FeatureProcesser(mode='regression') xt, sets",
"test_trigonometry(self): y = pd.Series(np.sin(np.linspace(0, 100, 100))) x = pd.DataFrame({'a': np.linspace(0, 100, 100)}) fp",
"x = pd.DataFrame({'a': y, 'b': np.random.normal(0, 1, n)}) fp = FeatureProcesser(mode='regression') xt, sets",
"= pd.Series(np.random.randint(0, 100, 100)) x = pd.DataFrame({'a': np.roll(y, -5)}) fp = FeatureProcesser(mode='regression') xt,",
"fp.fit_transform(x, y) def test_co_linearity(self): y = pd.Series(np.linspace(2, 100, 100)) x = pd.DataFrame({'a': np.linspace(-4,",
"xt, sets = fp.fit_transform(x, y) assert len(fp.crossFeatures) != 0, \"Multiplicative feature not spotted\"",
"100, 100)) b = pd.Series(np.linspace(-4, 4, 100)) x = pd.DataFrame({'a': np.cumsum(y), 'b': np.roll(y,",
"!= 0, \"Multiplicative feature not spotted\" def test_division(self): y = pd.Series(np.linspace(2, 100, 100))",
"pd.Series(np.linspace(-4, 4, 100) ** 2) x = pd.DataFrame({'a': y / b, 'b': b})",
"FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.trigonometricFeatures) != 0, \"Trigonometric feature not",
"make_classification from sklearn.datasets import make_regression from Amplo.AutoML import FeatureProcesser class TestFeatureProcessing(unittest.TestCase): @classmethod def",
"100)) b = pd.Series(np.linspace(-4, 4, 100) ** 2) x = pd.DataFrame({'a': y *",
"np.roll(y, -5), 'c': y / b, 'd': y * b}) fp = FeatureProcesser(mode='regression')",
"fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.trigonometricFeatures) != 0, \"Trigonometric",
"0, \"Division feature not spotted\" def test_trigonometry(self): y = pd.Series(np.sin(np.linspace(0, 100, 100))) x",
"def test_trigonometry(self): y = pd.Series(np.sin(np.linspace(0, 100, 100))) x = pd.DataFrame({'a': np.linspace(0, 100, 100)})",
"sets = fp.fit_transform(x, y) assert len(fp.crossFeatures) != 0, \"Division feature not spotted\" def",
"x = pd.DataFrame({'a': y / b, 'b': b, 'c': b / 2}) fp",
"4, 100) ** 2) x = pd.DataFrame({'a': y * b, 'b': b}) fp",
"make_regression() x, y = pd.DataFrame(x), pd.Series(y) fp = FeatureProcesser(max_lags=2, mode='regression') xt, sets =",
"consistent for {} set'.format(k) def test_get_required(self): y = pd.Series(np.linspace(2, 100, 100)) b =",
"fp.fit_transform(x, y) assert len(fp.diffFeatures) != 0, \"Difference feature not spotted\" def test_select(self): n",
"settings = fp.get_settings() fpn = FeatureProcesser(mode='regression') fpn.load_settings(settings) for k, v in sets.items(): xtn",
"'b': np.linspace(-4, 4, 100)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert",
"def test_select(self): n = 1000 y = pd.Series(np.linspace(0, 100, n)) x = pd.DataFrame({'a':",
"b = pd.Series(np.linspace(-4, 4, 100)) x = pd.DataFrame({'a': np.cumsum(y), 'b': np.roll(y, -5), 'c':",
"k) assert len(v) == len(xtn.keys()), \"Incorrect number of keys\" assert all(xt[v].keys() == xtn.keys()),",
"= FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) settings = fp.get_settings() fpn = FeatureProcesser(mode='regression')",
"2) x = pd.DataFrame({'a': y * b, 'b': b}) fp = FeatureProcesser(mode='regression') xt,",
"= FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert all([len(i) == 1 for i",
"import FeatureProcesser class TestFeatureProcessing(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_regression(self): x, y =",
"pass def test_regression(self): x, y = make_regression() x, y = pd.DataFrame(x), pd.Series(y) fp",
"data not consistent for {} set'.format(k) def test_get_required(self): y = pd.Series(np.linspace(2, 100, 100))",
"b}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) settings = fp.get_settings() fpn",
"100), 'b': np.linspace(-4, 4, 100)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y)",
"x = pd.DataFrame({'a': y / b, 'b': b}) fp = FeatureProcesser(mode='regression') xt, sets",
"fp.fit_transform(x, y) assert len(fp.crossFeatures) != 0, \"Division feature not spotted\" def test_trigonometry(self): y",
"= fp.fit_transform(x, y) assert all([len(i) == 1 for i in sets.values()]), f\"Random Feature",
"y = pd.DataFrame(x), pd.Series(y) fp = FeatureProcesser(max_lags=2, mode='regression') xt, sets = fp.fit_transform(x, y)",
"= pd.DataFrame({'a': np.linspace(-4, 4, 100), 'b': np.linspace(-4, 4, 100)}) fp = FeatureProcesser(mode='regression') xt,",
"from sklearn.datasets import make_regression from Amplo.AutoML import FeatureProcesser class TestFeatureProcessing(unittest.TestCase): @classmethod def setUpClass(cls):",
"100, 100)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.trigonometricFeatures) !=",
"b, 'b': b, 'c': b / 2}) fp = FeatureProcesser(mode='regression') xt, sets =",
"'b': np.random.normal(0, 1, n)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert",
"not removed\" def test_multiply_features(self): y = pd.Series(np.linspace(2, 100, 100)) b = pd.Series(np.linspace(-4, 4,",
"not spotted\" def test_division(self): y = pd.Series(np.linspace(2, 100, 100)) b = pd.Series(np.linspace(-4, 4,",
"= fp.fit_transform(x, y) def test_co_linearity(self): y = pd.Series(np.linspace(2, 100, 100)) x = pd.DataFrame({'a':",
"all([len(i) == 1 for i in sets.values()]), f\"Random Feature Selected: {sets}\" def test_settings(self):",
"== 1 for i in sets.values()]), f\"Random Feature Selected: {sets}\" def test_settings(self): y",
"not spotted\" def test_lagged(self): y = pd.Series(np.random.randint(0, 100, 100)) x = pd.DataFrame({'a': np.roll(y,",
"mode='regression') xt, sets = fp.fit_transform(x, y) def test_classification(self): x, y = make_classification() x,",
"i in sets.values()]), f\"Random Feature Selected: {sets}\" def test_settings(self): y = pd.Series(np.random.randint(1, 100,",
"/ b, 'b': b}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert",
"len(fp.trigonometricFeatures) != 0, \"Trigonometric feature not spotted\" def test_lagged(self): y = pd.Series(np.random.randint(0, 100,",
"number of keys\" assert all(xt[v].keys() == xtn.keys()), 'Keys are not correct' assert np.allclose(xt[v],",
"pd.DataFrame({'a': y, 'b': np.random.normal(0, 1, n)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x,",
"= pd.DataFrame({'a': np.linspace(0, 100, 100)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y)",
"np.cumsum(y)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.diffFeatures) != 0,",
"<reponame>nielsuit227/AutoML import unittest import numpy as np import pandas as pd from sklearn.datasets",
"y, 'b': np.random.normal(0, 1, n)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y)",
"np.allclose(xt[v], xtn), 'Transformed data not consistent for {} set'.format(k) def test_get_required(self): y =",
"\"Trigonometric feature not spotted\" def test_lagged(self): y = pd.Series(np.random.randint(0, 100, 100)) x =",
"= 1000 y = pd.Series(np.linspace(0, 100, n)) x = pd.DataFrame({'a': y, 'b': np.random.normal(0,",
"fp.fit_transform(x, y) assert all([len(i) == 1 for i in sets.values()]), f\"Random Feature Selected:",
"np.linspace(0, 100, 100)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.trigonometricFeatures)",
"y = pd.Series(np.linspace(2, 100, 100)) x = pd.DataFrame({'a': np.linspace(-4, 4, 100), 'b': np.linspace(-4,",
"'c': b / 2}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert",
"unittest import numpy as np import pandas as pd from sklearn.datasets import make_classification",
"= fpn.transform(x, k) assert len(v) == len(xtn.keys()), \"Incorrect number of keys\" assert all(xt[v].keys()",
"len(fp.coLinearFeatures) != 0, \"Colinear feature not removed\" def test_multiply_features(self): y = pd.Series(np.linspace(2, 100,",
"of keys\" assert all(xt[v].keys() == xtn.keys()), 'Keys are not correct' assert np.allclose(xt[v], xtn),",
"len(xtn.keys()), \"Incorrect number of keys\" assert all(xt[v].keys() == xtn.keys()), 'Keys are not correct'",
"y) def test_co_linearity(self): y = pd.Series(np.linspace(2, 100, 100)) x = pd.DataFrame({'a': np.linspace(-4, 4,",
"-5), 'c': y / b, 'd': y * b}) fp = FeatureProcesser(mode='regression') xt,",
"0, \"Difference feature not spotted\" def test_select(self): n = 1000 y = pd.Series(np.linspace(0,",
"pd.DataFrame({'a': np.cumsum(y)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.diffFeatures) !=",
"fp.get_settings() fpn = FeatureProcesser(mode='regression') fpn.load_settings(settings) for k, v in sets.items(): xtn = fpn.transform(x,",
"/ 2}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert set(fp.get_required_features(['a__x__b'])) ==",
"FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.coLinearFeatures) != 0, \"Colinear feature not",
"* b, 'b': b}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert",
"Amplo.AutoML import FeatureProcesser class TestFeatureProcessing(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_regression(self): x, y",
"@classmethod def setUpClass(cls): pass def test_regression(self): x, y = make_regression() x, y =",
"test_lagged(self): y = pd.Series(np.random.randint(0, 100, 100)) x = pd.DataFrame({'a': np.roll(y, -5)}) fp =",
"y = pd.Series(np.random.randint(0, 100, 100)) x = pd.DataFrame({'a': np.roll(y, -5)}) fp = FeatureProcesser(mode='regression')",
"test_multiply_features(self): y = pd.Series(np.linspace(2, 100, 100)) b = pd.Series(np.linspace(-4, 4, 100) ** 2)",
"not spotted\" def test_select(self): n = 1000 y = pd.Series(np.linspace(0, 100, n)) x",
"* b}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) settings = fp.get_settings()",
"4, 100), 'b': np.linspace(-4, 4, 100)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x,",
"import pandas as pd from sklearn.datasets import make_classification from sklearn.datasets import make_regression from",
"def test_co_linearity(self): y = pd.Series(np.linspace(2, 100, 100)) x = pd.DataFrame({'a': np.linspace(-4, 4, 100),",
"pd.DataFrame({'a': np.cumsum(y), 'b': np.roll(y, -5), 'c': y / b, 'd': y * b})",
"np.linspace(-4, 4, 100), 'b': np.linspace(-4, 4, 100)}) fp = FeatureProcesser(mode='regression') xt, sets =",
"len(fp.crossFeatures) != 0, \"Multiplicative feature not spotted\" def test_division(self): y = pd.Series(np.linspace(2, 100,",
"FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert all([len(i) == 1 for i in",
"keys\" assert all(xt[v].keys() == xtn.keys()), 'Keys are not correct' assert np.allclose(xt[v], xtn), 'Transformed",
"len(fp.diffFeatures) != 0, \"Difference feature not spotted\" def test_select(self): n = 1000 y",
"b, 'd': y * b}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y)",
"feature not spotted\" def test_diff(self): y = pd.Series(np.random.randint(1, 100, 100)) x = pd.DataFrame({'a':",
"pd.DataFrame(x), pd.Series(y) fp = FeatureProcesser(max_lags=2, mode='classification') xt, sets = fp.fit_transform(x, y) def test_co_linearity(self):",
"assert all([len(i) == 1 for i in sets.values()]), f\"Random Feature Selected: {sets}\" def",
"in sets.values()]), f\"Random Feature Selected: {sets}\" def test_settings(self): y = pd.Series(np.random.randint(1, 100, 100))",
"pd.Series(np.linspace(-4, 4, 100)) x = pd.DataFrame({'a': np.cumsum(y), 'b': np.roll(y, -5), 'c': y /",
"import numpy as np import pandas as pd from sklearn.datasets import make_classification from",
"xt, sets = fp.fit_transform(x, y) assert len(fp.diffFeatures) != 0, \"Difference feature not spotted\"",
"= fp.fit_transform(x, y) assert len(fp.crossFeatures) != 0, \"Division feature not spotted\" def test_trigonometry(self):",
"y) assert len(fp.laggedFeatures) != 0, \"Lagged feature not spotted\" def test_diff(self): y =",
"\"Multiplicative feature not spotted\" def test_division(self): y = pd.Series(np.linspace(2, 100, 100)) b =",
"import unittest import numpy as np import pandas as pd from sklearn.datasets import",
"test_get_required(self): y = pd.Series(np.linspace(2, 100, 100)) b = pd.Series(np.linspace(-4, 4, 100) ** 2)",
"{} set'.format(k) def test_get_required(self): y = pd.Series(np.linspace(2, 100, 100)) b = pd.Series(np.linspace(-4, 4,",
"for k, v in sets.items(): xtn = fpn.transform(x, k) assert len(v) == len(xtn.keys()),",
"100)) x = pd.DataFrame({'a': np.cumsum(y), 'b': np.roll(y, -5), 'c': y / b, 'd':",
"sets.items(): xtn = fpn.transform(x, k) assert len(v) == len(xtn.keys()), \"Incorrect number of keys\"",
"x, y = pd.DataFrame(x), pd.Series(y) fp = FeatureProcesser(max_lags=2, mode='regression') xt, sets = fp.fit_transform(x,",
"1 for i in sets.values()]), f\"Random Feature Selected: {sets}\" def test_settings(self): y =",
"100)) x = pd.DataFrame({'a': np.roll(y, -5)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x,",
"100)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.coLinearFeatures) != 0,",
"sklearn.datasets import make_regression from Amplo.AutoML import FeatureProcesser class TestFeatureProcessing(unittest.TestCase): @classmethod def setUpClass(cls): pass",
"x = pd.DataFrame({'a': np.linspace(0, 100, 100)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x,",
"sets = fp.fit_transform(x, y) assert len(fp.laggedFeatures) != 0, \"Lagged feature not spotted\" def",
"fpn = FeatureProcesser(mode='regression') fpn.load_settings(settings) for k, v in sets.items(): xtn = fpn.transform(x, k)",
"feature not spotted\" def test_division(self): y = pd.Series(np.linspace(2, 100, 100)) b = pd.Series(np.linspace(-4,",
"100) ** 2) x = pd.DataFrame({'a': y * b, 'b': b}) fp =",
"x, y = pd.DataFrame(x), pd.Series(y) fp = FeatureProcesser(max_lags=2, mode='classification') xt, sets = fp.fit_transform(x,",
"y) def test_classification(self): x, y = make_classification() x, y = pd.DataFrame(x), pd.Series(y) fp",
"100, 100))) x = pd.DataFrame({'a': np.linspace(0, 100, 100)}) fp = FeatureProcesser(mode='regression') xt, sets",
"pd.DataFrame({'a': np.linspace(-4, 4, 100), 'b': np.linspace(-4, 4, 100)}) fp = FeatureProcesser(mode='regression') xt, sets",
"class TestFeatureProcessing(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_regression(self): x, y = make_regression() x,",
"100)) b = pd.Series(np.linspace(-4, 4, 100) ** 2) x = pd.DataFrame({'a': y /",
"xtn), 'Transformed data not consistent for {} set'.format(k) def test_get_required(self): y = pd.Series(np.linspace(2,",
"x = pd.DataFrame({'a': np.roll(y, -5)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y)",
"assert len(fp.crossFeatures) != 0, \"Division feature not spotted\" def test_trigonometry(self): y = pd.Series(np.sin(np.linspace(0,",
"fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.diffFeatures) != 0, \"Difference",
"\"Division feature not spotted\" def test_trigonometry(self): y = pd.Series(np.sin(np.linspace(0, 100, 100))) x =",
"fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert set(fp.get_required_features(['a__x__b'])) == set(['b', 'a'])",
"test_settings(self): y = pd.Series(np.random.randint(1, 100, 100)) b = pd.Series(np.linspace(-4, 4, 100)) x =",
"xt, sets = fp.fit_transform(x, y) assert len(fp.laggedFeatures) != 0, \"Lagged feature not spotted\"",
"FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.laggedFeatures) != 0, \"Lagged feature not",
"y = pd.Series(np.linspace(0, 100, n)) x = pd.DataFrame({'a': y, 'b': np.random.normal(0, 1, n)})",
"pd.Series(np.sin(np.linspace(0, 100, 100))) x = pd.DataFrame({'a': np.linspace(0, 100, 100)}) fp = FeatureProcesser(mode='regression') xt,",
"correct' assert np.allclose(xt[v], xtn), 'Transformed data not consistent for {} set'.format(k) def test_get_required(self):",
"= FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.laggedFeatures) != 0, \"Lagged feature",
"1000 y = pd.Series(np.linspace(0, 100, n)) x = pd.DataFrame({'a': y, 'b': np.random.normal(0, 1,",
"pd.Series(np.linspace(0, 100, n)) x = pd.DataFrame({'a': y, 'b': np.random.normal(0, 1, n)}) fp =",
"TestFeatureProcessing(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_regression(self): x, y = make_regression() x, y",
"fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.crossFeatures) != 0, \"Division",
"= pd.Series(np.random.randint(1, 100, 100)) b = pd.Series(np.linspace(-4, 4, 100)) x = pd.DataFrame({'a': np.cumsum(y),",
"import make_regression from Amplo.AutoML import FeatureProcesser class TestFeatureProcessing(unittest.TestCase): @classmethod def setUpClass(cls): pass def",
"y / b, 'b': b}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y)",
"n)) x = pd.DataFrame({'a': y, 'b': np.random.normal(0, 1, n)}) fp = FeatureProcesser(mode='regression') xt,",
"= FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.diffFeatures) != 0, \"Difference feature",
"{sets}\" def test_settings(self): y = pd.Series(np.random.randint(1, 100, 100)) b = pd.Series(np.linspace(-4, 4, 100))",
"y) settings = fp.get_settings() fpn = FeatureProcesser(mode='regression') fpn.load_settings(settings) for k, v in sets.items():",
"= pd.DataFrame({'a': np.roll(y, -5)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert",
"= pd.DataFrame(x), pd.Series(y) fp = FeatureProcesser(max_lags=2, mode='regression') xt, sets = fp.fit_transform(x, y) def",
"pd.Series(np.linspace(-4, 4, 100) ** 2) x = pd.DataFrame({'a': y * b, 'b': b})",
"== xtn.keys()), 'Keys are not correct' assert np.allclose(xt[v], xtn), 'Transformed data not consistent",
"= pd.Series(np.linspace(-4, 4, 100)) x = pd.DataFrame({'a': np.cumsum(y), 'b': np.roll(y, -5), 'c': y",
"assert len(fp.coLinearFeatures) != 0, \"Colinear feature not removed\" def test_multiply_features(self): y = pd.Series(np.linspace(2,",
"b, 'c': b / 2}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y)",
"sets = fp.fit_transform(x, y) def test_co_linearity(self): y = pd.Series(np.linspace(2, 100, 100)) x =",
"pd.DataFrame({'a': y / b, 'b': b, 'c': b / 2}) fp = FeatureProcesser(mode='regression')",
"pd.DataFrame({'a': y * b, 'b': b}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x,",
"= pd.DataFrame({'a': y / b, 'b': b}) fp = FeatureProcesser(mode='regression') xt, sets =",
"pd.Series(np.random.randint(1, 100, 100)) x = pd.DataFrame({'a': np.cumsum(y)}) fp = FeatureProcesser(mode='regression') xt, sets =",
"Feature Selected: {sets}\" def test_settings(self): y = pd.Series(np.random.randint(1, 100, 100)) b = pd.Series(np.linspace(-4,",
"in sets.items(): xtn = fpn.transform(x, k) assert len(v) == len(xtn.keys()), \"Incorrect number of",
"= pd.DataFrame({'a': y / b, 'b': b, 'c': b / 2}) fp =",
"fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert len(fp.crossFeatures) != 0, \"Multiplicative",
"sets = fp.fit_transform(x, y) assert len(fp.coLinearFeatures) != 0, \"Colinear feature not removed\" def",
"make_regression from Amplo.AutoML import FeatureProcesser class TestFeatureProcessing(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_regression(self):",
"b = pd.Series(np.linspace(-4, 4, 100) ** 2) x = pd.DataFrame({'a': y * b,",
"not consistent for {} set'.format(k) def test_get_required(self): y = pd.Series(np.linspace(2, 100, 100)) b",
"= fp.fit_transform(x, y) assert len(fp.laggedFeatures) != 0, \"Lagged feature not spotted\" def test_diff(self):",
"sets = fp.fit_transform(x, y) assert all([len(i) == 1 for i in sets.values()]), f\"Random",
"fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert all([len(i) == 1 for",
"/ b, 'b': b, 'c': b / 2}) fp = FeatureProcesser(mode='regression') xt, sets",
"'Transformed data not consistent for {} set'.format(k) def test_get_required(self): y = pd.Series(np.linspace(2, 100,",
"spotted\" def test_trigonometry(self): y = pd.Series(np.sin(np.linspace(0, 100, 100))) x = pd.DataFrame({'a': np.linspace(0, 100,",
"'b': b, 'c': b / 2}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x,",
"np.random.normal(0, 1, n)}) fp = FeatureProcesser(mode='regression') xt, sets = fp.fit_transform(x, y) assert all([len(i)"
] |
[
"in a string test = \"\" file = open(testname) for line in file.readlines():",
"store the testdata in a string test = \"\" file = open(testname) for",
"result[item[0].decode('utf-8')] = item[1] csvfile.close() # print result # return a directory {character:code} return",
"= \"\" file = open(testname) for line in file.readlines(): test += line.strip('\\n') test",
"csvfile = open(filename, 'rb') reader = csv.reader(csvfile) result = {} for item in",
"def readfile(filename): csvfile = open(filename, 'rb') reader = csv.reader(csvfile) result = {} for",
"test.decode('utf-8') return test def load_all_pinyin(filename): pinyin = [] pyfile = open(filename) for line",
"reader = csv.reader(csvfile) result = {} for item in reader: result[item[0].decode('utf-8')] = item[1]",
"reader: result[item[0].decode('utf-8')] = item[1] csvfile.close() # print result # return a directory {character:code}",
"item in reader: result[item[0].decode('utf-8')] = item[1] csvfile.close() # print result # return a",
"string test = \"\" file = open(testname) for line in file.readlines(): test +=",
"test = \"\" file = open(testname) for line in file.readlines(): test += line.strip('\\n')",
"+= line.strip('\\n') test = test.decode('utf-8') return test def load_all_pinyin(filename): pinyin = [] pyfile",
"return test def load_all_pinyin(filename): pinyin = [] pyfile = open(filename) for line in",
"line.strip('\\n') test = test.decode('utf-8') return test def load_all_pinyin(filename): pinyin = [] pyfile =",
"for item in reader: result[item[0].decode('utf-8')] = item[1] csvfile.close() # print result # return",
"open(filename, 'rb') reader = csv.reader(csvfile) result = {} for item in reader: result[item[0].decode('utf-8')]",
"file = open(testname) for line in file.readlines(): test += line.strip('\\n') test = test.decode('utf-8')",
"the testdata in a string test = \"\" file = open(testname) for line",
"= {} for item in reader: result[item[0].decode('utf-8')] = item[1] csvfile.close() # print result",
"= open(testname) for line in file.readlines(): test += line.strip('\\n') test = test.decode('utf-8') return",
"= test.decode('utf-8') return test def load_all_pinyin(filename): pinyin = [] pyfile = open(filename) for",
"load_all_pinyin(filename): pinyin = [] pyfile = open(filename) for line in pyfile: pinyin.append(line.strip()) return",
"return result def load_test(testname): # store the testdata in a string test =",
"for line in file.readlines(): test += line.strip('\\n') test = test.decode('utf-8') return test def",
"test = test.decode('utf-8') return test def load_all_pinyin(filename): pinyin = [] pyfile = open(filename)",
"def load_all_pinyin(filename): pinyin = [] pyfile = open(filename) for line in pyfile: pinyin.append(line.strip())",
"csv.reader(csvfile) result = {} for item in reader: result[item[0].decode('utf-8')] = item[1] csvfile.close() #",
"# store the testdata in a string test = \"\" file = open(testname)",
"csv def readfile(filename): csvfile = open(filename, 'rb') reader = csv.reader(csvfile) result = {}",
"pinyin = [] pyfile = open(filename) for line in pyfile: pinyin.append(line.strip()) return pinyin",
"-*- coding:utf-8 -*-# import csv def readfile(filename): csvfile = open(filename, 'rb') reader =",
"# -*- coding:utf-8 -*-# import csv def readfile(filename): csvfile = open(filename, 'rb') reader",
"in file.readlines(): test += line.strip('\\n') test = test.decode('utf-8') return test def load_all_pinyin(filename): pinyin",
"item[1] csvfile.close() # print result # return a directory {character:code} return result def",
"a string test = \"\" file = open(testname) for line in file.readlines(): test",
"file.readlines(): test += line.strip('\\n') test = test.decode('utf-8') return test def load_all_pinyin(filename): pinyin =",
"test += line.strip('\\n') test = test.decode('utf-8') return test def load_all_pinyin(filename): pinyin = []",
"result = {} for item in reader: result[item[0].decode('utf-8')] = item[1] csvfile.close() # print",
"load_test(testname): # store the testdata in a string test = \"\" file =",
"{character:code} return result def load_test(testname): # store the testdata in a string test",
"def load_test(testname): # store the testdata in a string test = \"\" file",
"'rb') reader = csv.reader(csvfile) result = {} for item in reader: result[item[0].decode('utf-8')] =",
"= open(filename, 'rb') reader = csv.reader(csvfile) result = {} for item in reader:",
"csvfile.close() # print result # return a directory {character:code} return result def load_test(testname):",
"result # return a directory {character:code} return result def load_test(testname): # store the",
"readfile(filename): csvfile = open(filename, 'rb') reader = csv.reader(csvfile) result = {} for item",
"return a directory {character:code} return result def load_test(testname): # store the testdata in",
"print result # return a directory {character:code} return result def load_test(testname): # store",
"directory {character:code} return result def load_test(testname): # store the testdata in a string",
"<reponame>YangXuepei/ime-eval # -*- coding:utf-8 -*-# import csv def readfile(filename): csvfile = open(filename, 'rb')",
"a directory {character:code} return result def load_test(testname): # store the testdata in a",
"# return a directory {character:code} return result def load_test(testname): # store the testdata",
"\"\" file = open(testname) for line in file.readlines(): test += line.strip('\\n') test =",
"open(testname) for line in file.readlines(): test += line.strip('\\n') test = test.decode('utf-8') return test",
"test def load_all_pinyin(filename): pinyin = [] pyfile = open(filename) for line in pyfile:",
"# print result # return a directory {character:code} return result def load_test(testname): #",
"testdata in a string test = \"\" file = open(testname) for line in",
"line in file.readlines(): test += line.strip('\\n') test = test.decode('utf-8') return test def load_all_pinyin(filename):",
"result def load_test(testname): # store the testdata in a string test = \"\"",
"import csv def readfile(filename): csvfile = open(filename, 'rb') reader = csv.reader(csvfile) result =",
"= csv.reader(csvfile) result = {} for item in reader: result[item[0].decode('utf-8')] = item[1] csvfile.close()",
"= item[1] csvfile.close() # print result # return a directory {character:code} return result",
"in reader: result[item[0].decode('utf-8')] = item[1] csvfile.close() # print result # return a directory",
"-*-# import csv def readfile(filename): csvfile = open(filename, 'rb') reader = csv.reader(csvfile) result",
"{} for item in reader: result[item[0].decode('utf-8')] = item[1] csvfile.close() # print result #",
"coding:utf-8 -*-# import csv def readfile(filename): csvfile = open(filename, 'rb') reader = csv.reader(csvfile)"
] |
[
"dbc.NavItem(dbc.NavLink( html.Span( \"Linear Regression\", id=\"tooltip-lr\", style={\"cursor\": \"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"linear_regression\")), dbc.NavItem(dbc.NavLink( html.Span( \"Differential",
"i in available_datasets], # only passing in quant value columns value=available_datasets[0]), html.Hr(), html.P(\"Select",
"Multi-Omics Data Dashboard\"), width={\"size\": 6, \"offset\": 3})), html.Hr(), dbc.Row( [dbc.Col( dbc.Nav( [ html.H3(\"TYPE",
"i, 'value': i} for i in available_datasets], # only passing in quant value",
"i} for i in available_datasets], # only passing in quant value columns value=available_datasets[0]),",
"Expression\", id=\"tooltip-de\", style={\"cursor\": \"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"differential_expression\")), dbc.NavItem(dbc.NavLink( html.Span( \"Clustergrammer\", id=\"tooltip-cg\", style={\"cursor\":\"pointer\", \"color\":\"grey\"},",
"html.P(\"Select Biomolecule\", className=\"card-title\", style={\"font-weight\":\"bold\"}), # NOTE: This is dcc object not dbc dcc.Dropdown(",
"{\"toImageButtonOptions\":{'format':'svg', 'filename': 'dash_plot'}, \"displaylogo\": False} first_card = dbc.Card( [ dbc.CardHeader(\"PCA SCORES PLOT\", style={\"background-color\":\"#5bc0de\",",
"index biomolecule_index = df.columns.tolist().index(biomolecule_id) ome_type_list[biomolecule_index] = 'selected_biomolecule' fig = pca_loadings_plot(df, quant_value_range, dataset_id, biomolecule_names_dict,",
"Input('dataset_id', 'value')]) def update_biomolecule_boxplot(biomolecule_id, dataset_id): dataset = dataset_dict[dataset_id] df = df_dict[dataset] biomolecule_names_dict =",
"'Transcripts', 'Combined Biomolecules'] # define dataset dictionaries from app import dataset_dict, df_dict, quant_value_range_dict,",
"df.columns.tolist().index(biomolecule_id) ome_type_list[biomolecule_index] = 'selected_biomolecule' fig = pca_loadings_plot(df, quant_value_range, dataset_id, biomolecule_names_dict, ome_type_list) return fig",
"Input('biomolecule_id', 'value')]) def update_pca_loadings_plot(dataset_id, biomolecule_id): dataset = dataset_dict[dataset_id] df = df_dict[dataset] biomolecule_names_dict =",
"* quant_value_range_dict['proteomics'] ome_type_list.extend(['lipidomics'] * quant_value_range_dict['lipidomics']) ome_type_list.extend(['metabolomics'] * quant_value_range_dict['metabolomics']) ome_type_list.extend(['transcriptomics'] * quant_value_range_dict['transcriptomics']) # get",
"'value'), Input('dataset_id', 'value')]) def update_biomolecule_barplot(biomolecule_id, dataset_id): dataset = dataset_dict[dataset_id] df = df_dict[dataset] biomolecule_names_dict",
"options=[{'label': value, 'value': key} for key, value in sorted_biomolecule_names_dict.items() if key in available_biomolecules]",
"<gh_stars>1-10 import dash import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components",
"dash.dependencies.Output('biomolecule_id', 'options'), [Input('dataset_id', 'value')]) def update_biomolecule_options(dataset_id): dataset = dataset_dict[dataset_id] biomolecule_names_dict = global_names_dict[dataset] df",
"dbc.CardHeader(\"CONTROL PANEL\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody( [html.P(\"Select Dataset\", className=\"card-title\", style={\"font-weight\":\"bold\"}), dcc.Dropdown( id='dataset_id', options=[{'label':",
"align=\"center\")], className=\"mb-3\") ], fluid=True) @app.callback( dash.dependencies.Output('biomolecule_id', 'options'), [Input('dataset_id', 'value')]) def update_biomolecule_options(dataset_id): dataset =",
"for key, value in sorted_biomolecule_names_dict.items() if key in available_biomolecules] #print(options) return options @app.callback(",
"default_biomolecule @app.callback( Output('pca-scores-figure', 'figure'), [Input('dataset_id', 'value')]) def update_pca_scores_plot(dataset_id): dataset = dataset_dict[dataset_id] df =",
"dbc.Row([dbc.Col(third_card, md=7, align=\"center\"), dbc.Col(fourth_card, md=5, align=\"center\")], className=\"mb-3\") ], fluid=True) @app.callback( dash.dependencies.Output('biomolecule_id', 'options'), [Input('dataset_id',",
"dataset_dict[dataset_id] biomolecule_names_dict = global_names_dict[dataset] df = df_dict[dataset] quant_value_range = quant_value_range_dict[dataset] # get list",
"['Proteins', 'Lipids', 'Metabolites', 'Transcripts', 'Combined Biomolecules'] # define dataset dictionaries from app import",
"value columns value=default_biomolecule, className=\"dropdown-item p-0\"), ]) ]) #app.layout = dbc.Container([ layout = dbc.Container([",
"app import lipidomics_df, lipidomics_quant_range print(\"Lipidomics data shape: {}\".format(lipidomics_df.shape)) print(\"Loading proteomics data...\") from app",
"dbc.CardBody(dcc.Graph(id='biomolecule-boxplot', config=plotly_config)) ]) ### control_panel = dbc.Card( [ dbc.CardHeader(\"CONTROL PANEL\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}),",
"style={\"cursor\":\"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"clustergrammer\")), html.Hr(), control_panel ], vertical=\"md\", pills=True ), md=2, className=\"mb-3\"), #dbc.Col(control_panel,",
"quant_value_range_dict['transcriptomics']) # get biomolecule index biomolecule_index = df.columns.tolist().index(biomolecule_id) ome_type_list[biomolecule_index] = 'selected_biomolecule' fig =",
"def update_default_biomolecule(dataset_id): dataset = dataset_dict[dataset_id] biomolecule_names_dict = global_names_dict[dataset] sorted_biomolecule_names_dict = {k: v for",
"\"Differential Expression\", id=\"tooltip-de\", style={\"cursor\": \"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"differential_expression\")), dbc.NavItem(dbc.NavLink( html.Span( \"Clustergrammer\", id=\"tooltip-cg\", style={\"cursor\":\"pointer\",",
"df_dict[dataset] quant_value_range = quant_value_range_dict[dataset] fig = pca_scores_plot(df, quant_value_range) return fig @app.callback( Output('pca-loadings-figure', 'figure'),",
"range print(\"Creating combined omics df...\") df_dict, quant_value_range_dict = get_combined_data(df_dict, quant_value_range_dict) # start with",
"v for k, v in sorted(proteomics_biomolecule_names_dict.items(), key=lambda item: item[1])} #available_biomolecules = proteomics_biomolecule_names_dict.values() #available_biomolecules",
"print(\"Loading lipidomics data...\") from app import lipidomics_df, lipidomics_quant_range print(\"Lipidomics data shape: {}\".format(lipidomics_df.shape)) print(\"Loading",
"metabolomics data...\") from app import metabolomics_df, metabolomics_quant_range print(\"Metabolomics data shape: {}\".format(metabolomics_df.shape)) print(\"Loading lipidomics",
"SCORES PLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='pca-scores-figure', config=plotly_config)) ]) second_card = dbc.Card( [ dbc.CardHeader(\"PCA",
"'figure'), [Input('dataset_id', 'value'), Input('biomolecule_id', 'value')]) def update_pca_loadings_plot(dataset_id, biomolecule_id): dataset = dataset_dict[dataset_id] df =",
"data for pca...\") print() # load metabolomics data matrix print(\"Loading metabolomics data...\") from",
"key, value in sorted_biomolecule_names_dict.items()], # only passing in quant value columns value=default_biomolecule, className=\"dropdown-item",
"Dashboard\"), width={\"size\": 6, \"offset\": 3})), html.Hr(), dbc.Row( [dbc.Col( dbc.Nav( [ html.H3(\"TYPE OF ANALYSIS\",",
"md=7, align=\"center\"), dbc.Col(fourth_card, md=5, align=\"center\")], className=\"mb-3\") ], fluid=True) @app.callback( dash.dependencies.Output('biomolecule_id', 'options'), [Input('dataset_id', 'value')])",
"= {\"toImageButtonOptions\":{'format':'svg', 'filename': 'dash_plot'}, \"displaylogo\": False} first_card = dbc.Card( [ dbc.CardHeader(\"PCA SCORES PLOT\",",
"define dataset dictionaries from app import dataset_dict, df_dict, quant_value_range_dict, global_names_dict from app import",
"dbc.CardHeader(\"PCA LOADINGS PLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='pca-loadings-figure', config=plotly_config)) ]) third_card = dbc.Card( [",
"className=\"mb-3\"), #dbc.Col(control_panel, md=6) dbc.Col(first_card, md=4), dbc.Col(second_card, md=6) ], className=\"mb-3\"), dbc.Row([dbc.Col(third_card, md=7, align=\"center\"), dbc.Col(fourth_card,",
"className=\"mb-3\"), dbc.Row([dbc.Col(third_card, md=7, align=\"center\"), dbc.Col(fourth_card, md=5, align=\"center\")], className=\"mb-3\") ], fluid=True) @app.callback( dash.dependencies.Output('biomolecule_id', 'options'),",
"[Input('dataset_id', 'value')]) def update_biomolecule_options(dataset_id): dataset = dataset_dict[dataset_id] biomolecule_names_dict = global_names_dict[dataset] df = df_dict[dataset]",
"Input('dataset_id', 'value')]) def update_biomolecule_barplot(biomolecule_id, dataset_id): dataset = dataset_dict[dataset_id] df = df_dict[dataset] biomolecule_names_dict =",
"'value')]) def update_biomolecule_boxplot(biomolecule_id, dataset_id): dataset = dataset_dict[dataset_id] df = df_dict[dataset] biomolecule_names_dict = global_names_dict[dataset]",
"quant value range print(\"Creating combined omics df...\") df_dict, quant_value_range_dict = get_combined_data(df_dict, quant_value_range_dict) #",
"#dbc.Col(control_panel, md=6) dbc.Col(first_card, md=4), dbc.Col(second_card, md=6) ], className=\"mb-3\"), dbc.Row([dbc.Col(third_card, md=7, align=\"center\"), dbc.Col(fourth_card, md=5,",
"with proteomics data sorted_biomolecule_names_dict = {k: v for k, v in sorted(proteomics_biomolecule_names_dict.items(), key=lambda",
"return options @app.callback( Output('biomolecule_id', 'value'), [Input('dataset_id', 'value')]) def update_default_biomolecule(dataset_id): dataset = dataset_dict[dataset_id] biomolecule_names_dict",
"key, value in sorted_biomolecule_names_dict.items() if key in available_biomolecules] #print(options) return options @app.callback( Output('biomolecule_id',",
"# label maps to biomolecule name, value to biomolecule_id options=[{'label': value, 'value': key}",
"href=\"pca\", style={\"background-color\":\"grey\"})), dbc.NavItem(dbc.NavLink( html.Span( \"Linear Regression\", id=\"tooltip-lr\", style={\"cursor\": \"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"linear_regression\")), dbc.NavItem(dbc.NavLink(",
"'filename': 'dash_plot'}, \"displaylogo\": False} first_card = dbc.Card( [ dbc.CardHeader(\"PCA SCORES PLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\",",
"Output('pca-scores-figure', 'figure'), [Input('dataset_id', 'value')]) def update_pca_scores_plot(dataset_id): dataset = dataset_dict[dataset_id] df = df_dict[dataset] quant_value_range",
"quant_value_range = quant_value_range_dict[dataset] # build ome type list for coloring if not dataset",
"@app.callback( Output('biomolecule-barplot', 'figure'), [Input('biomolecule_id', 'value'), Input('dataset_id', 'value')]) def update_biomolecule_barplot(biomolecule_id, dataset_id): dataset = dataset_dict[dataset_id]",
"dbc dcc.Dropdown( id='biomolecule_id', # label maps to biomolecule name, value to biomolecule_id options=[{'label':",
"value=available_datasets[0]), html.Hr(), html.P(\"Select Biomolecule\", className=\"card-title\", style={\"font-weight\":\"bold\"}), # NOTE: This is dcc object not",
"df = df_dict[dataset] quant_value_range = quant_value_range_dict[dataset] # get list of columns for dataset",
"'value')]) def update_biomolecule_options(dataset_id): dataset = dataset_dict[dataset_id] biomolecule_names_dict = global_names_dict[dataset] df = df_dict[dataset] quant_value_range",
"# get combined omics df and quant value range print(\"Creating combined omics df...\")",
"'value')]) def update_pca_scores_plot(dataset_id): dataset = dataset_dict[dataset_id] df = df_dict[dataset] quant_value_range = quant_value_range_dict[dataset] fig",
"PLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='pca-loadings-figure', config=plotly_config)) ]) third_card = dbc.Card( [ dbc.CardHeader(\"BIOMOLECULE BARPLOT\",",
"dbc.NavItem(dbc.NavLink( html.Span( \"Clustergrammer\", id=\"tooltip-cg\", style={\"cursor\":\"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"clustergrammer\")), html.Hr(), control_panel ], vertical=\"md\", pills=True",
"biomolecule_names_dict = global_names_dict[dataset] sorted_biomolecule_names_dict = {k: v for k, v in sorted(biomolecule_names_dict.items(), key=lambda",
"Multi-Omics'\"\"\" from app import app print() print(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")) print(\"Loading data for pca...\") print()",
"* quant_value_range_dict['transcriptomics']) # get biomolecule index biomolecule_index = df.columns.tolist().index(biomolecule_id) ome_type_list[biomolecule_index] = 'selected_biomolecule' fig",
"from app import lipidomics_biomolecule_names_dict from app import proteomics_biomolecule_names_dict from app import transcriptomics_biomolecule_names_dict #",
"[Input('dataset_id', 'value')]) def update_default_biomolecule(dataset_id): dataset = dataset_dict[dataset_id] biomolecule_names_dict = global_names_dict[dataset] sorted_biomolecule_names_dict = {k:",
"style={\"cursor\": \"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"linear_regression\")), dbc.NavItem(dbc.NavLink( html.Span( \"Differential Expression\", id=\"tooltip-de\", style={\"cursor\": \"pointer\", \"color\":\"grey\"},",
"dbc.CardBody(dcc.Graph(id='pca-scores-figure', config=plotly_config)) ]) second_card = dbc.Card( [ dbc.CardHeader(\"PCA LOADINGS PLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}),",
"'value')]) def update_biomolecule_barplot(biomolecule_id, dataset_id): dataset = dataset_dict[dataset_id] df = df_dict[dataset] biomolecule_names_dict = global_names_dict[dataset]",
"@app.callback( Output('pca-scores-figure', 'figure'), [Input('dataset_id', 'value')]) def update_pca_scores_plot(dataset_id): dataset = dataset_dict[dataset_id] df = df_dict[dataset]",
"sorted_biomolecule_names_dict = {k: v for k, v in sorted(biomolecule_names_dict.items(), key=lambda item: item[1])} default_biomolecule=list(sorted_biomolecule_names_dict.keys())[0]",
"name, value to biomolecule_id options=[{'label': value, 'value': key} for key, value in sorted_biomolecule_names_dict.items()],",
"dbc.Col(second_card, md=6) ], className=\"mb-3\"), dbc.Row([dbc.Col(third_card, md=7, align=\"center\"), dbc.Col(fourth_card, md=5, align=\"center\")], className=\"mb-3\") ], fluid=True)",
"quant_value_range = quant_value_range_dict[dataset] # get list of columns for dataset available_biomolecules = df.columns[:quant_value_range].sort_values().tolist()",
"coloring if not dataset == 'combined': ome_type_list = [dataset] * quant_value_range else: ome_type_list",
"get_combined_data(df_dict, quant_value_range_dict) # start with proteomics data sorted_biomolecule_names_dict = {k: v for k,",
"in sorted_biomolecule_names_dict.items() if key in available_biomolecules] #print(options) return options @app.callback( Output('biomolecule_id', 'value'), [Input('dataset_id',",
"df_dict, quant_value_range_dict = get_combined_data(df_dict, quant_value_range_dict) # start with proteomics data sorted_biomolecule_names_dict = {k:",
"k, v in sorted(proteomics_biomolecule_names_dict.items(), key=lambda item: item[1])} #available_biomolecules = proteomics_biomolecule_names_dict.values() #available_biomolecules = proteomics_df.columns[:proteomics_quant_range].sort_values().tolist()",
"metabolomics data matrix print(\"Loading metabolomics data...\") from app import metabolomics_df, metabolomics_quant_range print(\"Metabolomics data",
"default_biomolecule=list(sorted_biomolecule_names_dict.keys())[0] return default_biomolecule @app.callback( Output('pca-scores-figure', 'figure'), [Input('dataset_id', 'value')]) def update_pca_scores_plot(dataset_id): dataset = dataset_dict[dataset_id]",
"ome_type_list[biomolecule_index] = 'selected_biomolecule' fig = pca_loadings_plot(df, quant_value_range, dataset_id, biomolecule_names_dict, ome_type_list) return fig @app.callback(",
"df = df_dict[dataset] biomolecule_names_dict = global_names_dict[dataset] biomolecule_name = biomolecule_names_dict[biomolecule_id] fig = biomolecule_bar(df, biomolecule_id,",
"[ dbc.CardHeader(\"BIOMOLECULE BARPLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='biomolecule-barplot', config=plotly_config)) ]) fourth_card = dbc.Card( [",
"= boxplot(df, biomolecule_id, biomolecule_names_dict) return fig print(\"Starting server...\") if __name__ == '__main__': app.run_server(",
"{}\".format(proteomics_df.shape)) print(\"Loading transcriptomics data...\") from app import transcriptomics_df, transcriptomics_quant_range print(\"Transcriptomics data shape: {}\".format(transcriptomics_df.shape))",
"list of columns for dataset available_biomolecules = df.columns[:quant_value_range].sort_values().tolist() sorted_biomolecule_names_dict = {k: v for",
"dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import",
"\"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='pca-scores-figure', config=plotly_config)) ]) second_card = dbc.Card( [ dbc.CardHeader(\"PCA LOADINGS PLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\",",
"= proteomics_df.columns[:proteomics_quant_range].sort_values().tolist() default_biomolecule = list(sorted_biomolecule_names_dict.keys())[0] plotly_config = {\"toImageButtonOptions\":{'format':'svg', 'filename': 'dash_plot'}, \"displaylogo\": False} first_card",
"v in sorted(proteomics_biomolecule_names_dict.items(), key=lambda item: item[1])} #available_biomolecules = proteomics_biomolecule_names_dict.values() #available_biomolecules = proteomics_df.columns[:proteomics_quant_range].sort_values().tolist() default_biomolecule",
"ome_type_list = ['proteomics'] * quant_value_range_dict['proteomics'] ome_type_list.extend(['lipidomics'] * quant_value_range_dict['lipidomics']) ome_type_list.extend(['metabolomics'] * quant_value_range_dict['metabolomics']) ome_type_list.extend(['transcriptomics'] *",
"dataset available_biomolecules = df.columns[:quant_value_range].sort_values().tolist() sorted_biomolecule_names_dict = {k: v for k, v in sorted(biomolecule_names_dict.items(),",
"transcriptomics_df, transcriptomics_quant_range print(\"Transcriptomics data shape: {}\".format(transcriptomics_df.shape)) available_datasets = ['Proteins', 'Lipids', 'Metabolites', 'Transcripts', 'Combined",
"]) ### control_panel = dbc.Card( [ dbc.CardHeader(\"CONTROL PANEL\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody( [html.P(\"Select",
"biomolecule_names_dict = global_names_dict[dataset] df = df_dict[dataset] quant_value_range = quant_value_range_dict[dataset] # get list of",
"'figure'), [Input('dataset_id', 'value')]) def update_pca_scores_plot(dataset_id): dataset = dataset_dict[dataset_id] df = df_dict[dataset] quant_value_range =",
"{k: v for k, v in sorted(biomolecule_names_dict.items(), key=lambda item: item[1])} options=[{'label': value, 'value':",
"biomolecule_index = df.columns.tolist().index(biomolecule_id) ome_type_list[biomolecule_index] = 'selected_biomolecule' fig = pca_loadings_plot(df, quant_value_range, dataset_id, biomolecule_names_dict, ome_type_list)",
"shape: {}\".format(proteomics_df.shape)) print(\"Loading transcriptomics data...\") from app import transcriptomics_df, transcriptomics_quant_range print(\"Transcriptomics data shape:",
"df...\") df_dict, quant_value_range_dict = get_combined_data(df_dict, quant_value_range_dict) # start with proteomics data sorted_biomolecule_names_dict =",
"return default_biomolecule @app.callback( Output('pca-scores-figure', 'figure'), [Input('dataset_id', 'value')]) def update_pca_scores_plot(dataset_id): dataset = dataset_dict[dataset_id] df",
"\"\"\"app = dash.Dash( __name__, external_stylesheets=external_stylesheets) app.title = 'COVID-19 Multi-Omics'\"\"\" from app import app",
"navbar external_stylesheets=[dbc.themes.BOOTSTRAP] \"\"\"app = dash.Dash( __name__, external_stylesheets=external_stylesheets) app.title = 'COVID-19 Multi-Omics'\"\"\" from app",
"maps to biomolecule name, value to biomolecule_id options=[{'label': value, 'value': key} for key,",
"html.Hr(), dbc.Row( [dbc.Col( dbc.Nav( [ html.H3(\"TYPE OF ANALYSIS\", style={\"font-weight\":\"bold\", \"color\":\"black\"}), dbc.NavItem(dbc.NavLink(\"PCA\", active=True, href=\"pca\",",
"= dash.Dash( __name__, external_stylesheets=external_stylesheets) app.title = 'COVID-19 Multi-Omics'\"\"\" from app import app print()",
"dataset_id): dataset = dataset_dict[dataset_id] df = df_dict[dataset] biomolecule_names_dict = global_names_dict[dataset] biomolecule_name = biomolecule_names_dict[biomolecule_id]",
"# build ome type list for coloring if not dataset == 'combined': ome_type_list",
"= pca_scores_plot(df, quant_value_range) return fig @app.callback( Output('pca-loadings-figure', 'figure'), [Input('dataset_id', 'value'), Input('biomolecule_id', 'value')]) def",
"datetime from data import get_omics_data, get_biomolecule_names, get_combined_data from plot import biomolecule_bar, boxplot, pca_scores_plot,",
"width={\"size\": 6, \"offset\": 3})), html.Hr(), dbc.Row( [dbc.Col( dbc.Nav( [ html.H3(\"TYPE OF ANALYSIS\", style={\"font-weight\":\"bold\",",
"external_stylesheets=[dbc.themes.BOOTSTRAP] \"\"\"app = dash.Dash( __name__, external_stylesheets=external_stylesheets) app.title = 'COVID-19 Multi-Omics'\"\"\" from app import",
"boxplot, pca_scores_plot, pca_loadings_plot from nav import navbar external_stylesheets=[dbc.themes.BOOTSTRAP] \"\"\"app = dash.Dash( __name__, external_stylesheets=external_stylesheets)",
"biomolecule_names_dict[biomolecule_id] fig = boxplot(df, biomolecule_id, biomolecule_names_dict) return fig print(\"Starting server...\") if __name__ ==",
"pca...\") print() # load metabolomics data matrix print(\"Loading metabolomics data...\") from app import",
"quant_value_range = quant_value_range_dict[dataset] fig = pca_scores_plot(df, quant_value_range) return fig @app.callback( Output('pca-loadings-figure', 'figure'), [Input('dataset_id',",
"v for k, v in sorted(biomolecule_names_dict.items(), key=lambda item: item[1])} options=[{'label': value, 'value': key}",
"data...\") from app import metabolomics_df, metabolomics_quant_range print(\"Metabolomics data shape: {}\".format(metabolomics_df.shape)) print(\"Loading lipidomics data...\")",
"control_panel ], vertical=\"md\", pills=True ), md=2, className=\"mb-3\"), #dbc.Col(control_panel, md=6) dbc.Col(first_card, md=4), dbc.Col(second_card, md=6)",
"dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from dash.dependencies",
"Regression\", id=\"tooltip-lr\", style={\"cursor\": \"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"linear_regression\")), dbc.NavItem(dbc.NavLink( html.Span( \"Differential Expression\", id=\"tooltip-de\", style={\"cursor\":",
"import proteomics_biomolecule_names_dict from app import transcriptomics_biomolecule_names_dict # get combined omics df and quant",
"= dbc.Card( [ dbc.CardHeader(\"BIOMOLECULE BARPLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='biomolecule-barplot', config=plotly_config)) ]) fourth_card =",
"df_dict[dataset] biomolecule_names_dict = global_names_dict[dataset] biomolecule_name = biomolecule_names_dict[biomolecule_id] fig = boxplot(df, biomolecule_id, biomolecule_names_dict) return",
"\"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"differential_expression\")), dbc.NavItem(dbc.NavLink( html.Span( \"Clustergrammer\", id=\"tooltip-cg\", style={\"cursor\":\"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"clustergrammer\")), html.Hr(),",
"quant_value_range_dict[dataset] fig = pca_scores_plot(df, quant_value_range) return fig @app.callback( Output('pca-loadings-figure', 'figure'), [Input('dataset_id', 'value'), Input('biomolecule_id',",
"get biomolecule index biomolecule_index = df.columns.tolist().index(biomolecule_id) ome_type_list[biomolecule_index] = 'selected_biomolecule' fig = pca_loadings_plot(df, quant_value_range,",
"fig @app.callback( Output('biomolecule-boxplot', 'figure'), [Input('biomolecule_id', 'value'), Input('dataset_id', 'value')]) def update_biomolecule_boxplot(biomolecule_id, dataset_id): dataset =",
"return fig print(\"Starting server...\") if __name__ == '__main__': app.run_server( debug=True, host='0.0.0.0', #port='8080' )",
"dbc.Card( [ dbc.CardHeader(\"BIOMOLECULE BOXPLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='biomolecule-boxplot', config=plotly_config)) ]) ### control_panel =",
"quant_value_range_dict) # start with proteomics data sorted_biomolecule_names_dict = {k: v for k, v",
"print(\"Loading metabolomics data...\") from app import metabolomics_df, metabolomics_quant_range print(\"Metabolomics data shape: {}\".format(metabolomics_df.shape)) print(\"Loading",
"import proteomics_df, proteomics_quant_range print(\"Proteomics data shape: {}\".format(proteomics_df.shape)) print(\"Loading transcriptomics data...\") from app import",
"PLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='pca-scores-figure', config=plotly_config)) ]) second_card = dbc.Card( [ dbc.CardHeader(\"PCA LOADINGS",
"proteomics data sorted_biomolecule_names_dict = {k: v for k, v in sorted(proteomics_biomolecule_names_dict.items(), key=lambda item:",
"options=[{'label': i, 'value': i} for i in available_datasets], # only passing in quant",
"in sorted(biomolecule_names_dict.items(), key=lambda item: item[1])} default_biomolecule=list(sorted_biomolecule_names_dict.keys())[0] return default_biomolecule @app.callback( Output('pca-scores-figure', 'figure'), [Input('dataset_id', 'value')])",
"= global_names_dict[dataset] biomolecule_name = biomolecule_names_dict[biomolecule_id] fig = biomolecule_bar(df, biomolecule_id, biomolecule_names_dict) return fig @app.callback(",
"available_datasets = ['Proteins', 'Lipids', 'Metabolites', 'Transcripts', 'Combined Biomolecules'] # define dataset dictionaries from",
"print(\"Transcriptomics data shape: {}\".format(transcriptomics_df.shape)) available_datasets = ['Proteins', 'Lipids', 'Metabolites', 'Transcripts', 'Combined Biomolecules'] #",
"'COVID-19 Multi-Omics'\"\"\" from app import app print() print(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")) print(\"Loading data for pca...\")",
"\"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='pca-scores-figure', config=plotly_config)) ]) second_card = dbc.Card( [ dbc.CardHeader(\"PCA LOADINGS PLOT\", style={\"background-color\":\"#5bc0de\",",
"dbc.Container([ layout = dbc.Container([ navbar, html.Hr(), dbc.Row(dbc.Col(html.H1(\"COVID-19 Multi-Omics Data Dashboard\"), width={\"size\": 6, \"offset\":",
"]) third_card = dbc.Card( [ dbc.CardHeader(\"BIOMOLECULE BARPLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='biomolecule-barplot', config=plotly_config)) ])",
"value=default_biomolecule, className=\"dropdown-item p-0\"), ]) ]) #app.layout = dbc.Container([ layout = dbc.Container([ navbar, html.Hr(),",
"dash_html_components as html from dash.dependencies import Input, Output import datetime from data import",
"columns for dataset available_biomolecules = df.columns[:quant_value_range].sort_values().tolist() sorted_biomolecule_names_dict = {k: v for k, v",
"global_names_dict[dataset] sorted_biomolecule_names_dict = {k: v for k, v in sorted(biomolecule_names_dict.items(), key=lambda item: item[1])}",
"#app.layout = dbc.Container([ layout = dbc.Container([ navbar, html.Hr(), dbc.Row(dbc.Col(html.H1(\"COVID-19 Multi-Omics Data Dashboard\"), width={\"size\":",
"quant value columns value=default_biomolecule, className=\"dropdown-item p-0\"), ]) ]) #app.layout = dbc.Container([ layout =",
"md=4), dbc.Col(second_card, md=6) ], className=\"mb-3\"), dbc.Row([dbc.Col(third_card, md=7, align=\"center\"), dbc.Col(fourth_card, md=5, align=\"center\")], className=\"mb-3\") ],",
"df_dict[dataset] biomolecule_names_dict = global_names_dict[dataset] biomolecule_name = biomolecule_names_dict[biomolecule_id] fig = biomolecule_bar(df, biomolecule_id, biomolecule_names_dict) return",
"in quant value columns value=default_biomolecule, className=\"dropdown-item p-0\"), ]) ]) #app.layout = dbc.Container([ layout",
"dbc.CardBody(dcc.Graph(id='pca-loadings-figure', config=plotly_config)) ]) third_card = dbc.Card( [ dbc.CardHeader(\"BIOMOLECULE BARPLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='biomolecule-barplot',",
"dataset = dataset_dict[dataset_id] df = df_dict[dataset] quant_value_range = quant_value_range_dict[dataset] fig = pca_scores_plot(df, quant_value_range)",
"= quant_value_range_dict[dataset] # build ome type list for coloring if not dataset ==",
"metabolomics_biomolecule_names_dict from app import lipidomics_biomolecule_names_dict from app import proteomics_biomolecule_names_dict from app import transcriptomics_biomolecule_names_dict",
"Dataset\", className=\"card-title\", style={\"font-weight\":\"bold\"}), dcc.Dropdown( id='dataset_id', options=[{'label': i, 'value': i} for i in available_datasets],",
"v in sorted(biomolecule_names_dict.items(), key=lambda item: item[1])} default_biomolecule=list(sorted_biomolecule_names_dict.keys())[0] return default_biomolecule @app.callback( Output('pca-scores-figure', 'figure'), [Input('dataset_id',",
"app import dataset_dict, df_dict, quant_value_range_dict, global_names_dict from app import metabolomics_biomolecule_names_dict from app import",
"@app.callback( Output('pca-loadings-figure', 'figure'), [Input('dataset_id', 'value'), Input('biomolecule_id', 'value')]) def update_pca_loadings_plot(dataset_id, biomolecule_id): dataset = dataset_dict[dataset_id]",
"[Input('dataset_id', 'value'), Input('biomolecule_id', 'value')]) def update_pca_loadings_plot(dataset_id, biomolecule_id): dataset = dataset_dict[dataset_id] df = df_dict[dataset]",
"quant_value_range_dict['lipidomics']) ome_type_list.extend(['metabolomics'] * quant_value_range_dict['metabolomics']) ome_type_list.extend(['transcriptomics'] * quant_value_range_dict['transcriptomics']) # get biomolecule index biomolecule_index =",
"data shape: {}\".format(metabolomics_df.shape)) print(\"Loading lipidomics data...\") from app import lipidomics_df, lipidomics_quant_range print(\"Lipidomics data",
"item: item[1])} #available_biomolecules = proteomics_biomolecule_names_dict.values() #available_biomolecules = proteomics_df.columns[:proteomics_quant_range].sort_values().tolist() default_biomolecule = list(sorted_biomolecule_names_dict.keys())[0] plotly_config =",
"#available_biomolecules = proteomics_biomolecule_names_dict.values() #available_biomolecules = proteomics_df.columns[:proteomics_quant_range].sort_values().tolist() default_biomolecule = list(sorted_biomolecule_names_dict.keys())[0] plotly_config = {\"toImageButtonOptions\":{'format':'svg', 'filename':",
"dbc.Card( [ dbc.CardHeader(\"PCA SCORES PLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='pca-scores-figure', config=plotly_config)) ]) second_card =",
"proteomics_biomolecule_names_dict.values() #available_biomolecules = proteomics_df.columns[:proteomics_quant_range].sort_values().tolist() default_biomolecule = list(sorted_biomolecule_names_dict.keys())[0] plotly_config = {\"toImageButtonOptions\":{'format':'svg', 'filename': 'dash_plot'}, \"displaylogo\":",
"biomolecule_bar, boxplot, pca_scores_plot, pca_loadings_plot from nav import navbar external_stylesheets=[dbc.themes.BOOTSTRAP] \"\"\"app = dash.Dash( __name__,",
"dbc.Card( [ dbc.CardHeader(\"BIOMOLECULE BARPLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='biomolecule-barplot', config=plotly_config)) ]) fourth_card = dbc.Card(",
"for key, value in sorted_biomolecule_names_dict.items()], # only passing in quant value columns value=default_biomolecule,",
"app import transcriptomics_biomolecule_names_dict # get combined omics df and quant value range print(\"Creating",
"= list(sorted_biomolecule_names_dict.keys())[0] plotly_config = {\"toImageButtonOptions\":{'format':'svg', 'filename': 'dash_plot'}, \"displaylogo\": False} first_card = dbc.Card( [",
"'combined': ome_type_list = [dataset] * quant_value_range else: ome_type_list = ['proteomics'] * quant_value_range_dict['proteomics'] ome_type_list.extend(['lipidomics']",
"# load metabolomics data matrix print(\"Loading metabolomics data...\") from app import metabolomics_df, metabolomics_quant_range",
"dbc.CardBody( [html.P(\"Select Dataset\", className=\"card-title\", style={\"font-weight\":\"bold\"}), dcc.Dropdown( id='dataset_id', options=[{'label': i, 'value': i} for i",
"df = df_dict[dataset] biomolecule_names_dict = global_names_dict[dataset] quant_value_range = quant_value_range_dict[dataset] # build ome type",
"dataset = dataset_dict[dataset_id] biomolecule_names_dict = global_names_dict[dataset] sorted_biomolecule_names_dict = {k: v for k, v",
"id='biomolecule_id', # label maps to biomolecule name, value to biomolecule_id options=[{'label': value, 'value':",
"def update_pca_scores_plot(dataset_id): dataset = dataset_dict[dataset_id] df = df_dict[dataset] quant_value_range = quant_value_range_dict[dataset] fig =",
"import transcriptomics_biomolecule_names_dict # get combined omics df and quant value range print(\"Creating combined",
"dataset = dataset_dict[dataset_id] df = df_dict[dataset] biomolecule_names_dict = global_names_dict[dataset] biomolecule_name = biomolecule_names_dict[biomolecule_id] fig",
"value in sorted_biomolecule_names_dict.items()], # only passing in quant value columns value=default_biomolecule, className=\"dropdown-item p-0\"),",
"html.H3(\"TYPE OF ANALYSIS\", style={\"font-weight\":\"bold\", \"color\":\"black\"}), dbc.NavItem(dbc.NavLink(\"PCA\", active=True, href=\"pca\", style={\"background-color\":\"grey\"})), dbc.NavItem(dbc.NavLink( html.Span( \"Linear Regression\",",
"active=True, href=\"pca\", style={\"background-color\":\"grey\"})), dbc.NavItem(dbc.NavLink( html.Span( \"Linear Regression\", id=\"tooltip-lr\", style={\"cursor\": \"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"linear_regression\")),",
"= df_dict[dataset] quant_value_range = quant_value_range_dict[dataset] # get list of columns for dataset available_biomolecules",
"sorted(proteomics_biomolecule_names_dict.items(), key=lambda item: item[1])} #available_biomolecules = proteomics_biomolecule_names_dict.values() #available_biomolecules = proteomics_df.columns[:proteomics_quant_range].sort_values().tolist() default_biomolecule = list(sorted_biomolecule_names_dict.keys())[0]",
"df_dict[dataset] biomolecule_names_dict = global_names_dict[dataset] quant_value_range = quant_value_range_dict[dataset] # build ome type list for",
"from plot import biomolecule_bar, boxplot, pca_scores_plot, pca_loadings_plot from nav import navbar external_stylesheets=[dbc.themes.BOOTSTRAP] \"\"\"app",
"proteomics_df, proteomics_quant_range print(\"Proteomics data shape: {}\".format(proteomics_df.shape)) print(\"Loading transcriptomics data...\") from app import transcriptomics_df,",
"= df_dict[dataset] biomolecule_names_dict = global_names_dict[dataset] quant_value_range = quant_value_range_dict[dataset] # build ome type list",
"{k: v for k, v in sorted(proteomics_biomolecule_names_dict.items(), key=lambda item: item[1])} #available_biomolecules = proteomics_biomolecule_names_dict.values()",
"from app import proteomics_df, proteomics_quant_range print(\"Proteomics data shape: {}\".format(proteomics_df.shape)) print(\"Loading transcriptomics data...\") from",
"not dataset == 'combined': ome_type_list = [dataset] * quant_value_range else: ome_type_list = ['proteomics']",
"global_names_dict[dataset] biomolecule_name = biomolecule_names_dict[biomolecule_id] fig = boxplot(df, biomolecule_id, biomolecule_names_dict) return fig print(\"Starting server...\")",
"first_card = dbc.Card( [ dbc.CardHeader(\"PCA SCORES PLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='pca-scores-figure', config=plotly_config)) ])",
"dbc.Nav( [ html.H3(\"TYPE OF ANALYSIS\", style={\"font-weight\":\"bold\", \"color\":\"black\"}), dbc.NavItem(dbc.NavLink(\"PCA\", active=True, href=\"pca\", style={\"background-color\":\"grey\"})), dbc.NavItem(dbc.NavLink( html.Span(",
"biomolecule_bar(df, biomolecule_id, biomolecule_names_dict) return fig @app.callback( Output('biomolecule-boxplot', 'figure'), [Input('biomolecule_id', 'value'), Input('dataset_id', 'value')]) def",
"item: item[1])} default_biomolecule=list(sorted_biomolecule_names_dict.keys())[0] return default_biomolecule @app.callback( Output('pca-scores-figure', 'figure'), [Input('dataset_id', 'value')]) def update_pca_scores_plot(dataset_id): dataset",
"['proteomics'] * quant_value_range_dict['proteomics'] ome_type_list.extend(['lipidomics'] * quant_value_range_dict['lipidomics']) ome_type_list.extend(['metabolomics'] * quant_value_range_dict['metabolomics']) ome_type_list.extend(['transcriptomics'] * quant_value_range_dict['transcriptomics']) #",
"data...\") from app import proteomics_df, proteomics_quant_range print(\"Proteomics data shape: {}\".format(proteomics_df.shape)) print(\"Loading transcriptomics data...\")",
"className=\"mb-3\") ], fluid=True) @app.callback( dash.dependencies.Output('biomolecule_id', 'options'), [Input('dataset_id', 'value')]) def update_biomolecule_options(dataset_id): dataset = dataset_dict[dataset_id]",
"quant_value_range) return fig @app.callback( Output('pca-loadings-figure', 'figure'), [Input('dataset_id', 'value'), Input('biomolecule_id', 'value')]) def update_pca_loadings_plot(dataset_id, biomolecule_id):",
"__name__, external_stylesheets=external_stylesheets) app.title = 'COVID-19 Multi-Omics'\"\"\" from app import app print() print(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"))",
"quant_value_range_dict['metabolomics']) ome_type_list.extend(['transcriptomics'] * quant_value_range_dict['transcriptomics']) # get biomolecule index biomolecule_index = df.columns.tolist().index(biomolecule_id) ome_type_list[biomolecule_index] =",
"biomolecule_names_dict, ome_type_list) return fig @app.callback( Output('biomolecule-barplot', 'figure'), [Input('biomolecule_id', 'value'), Input('dataset_id', 'value')]) def update_biomolecule_barplot(biomolecule_id,",
"for dataset available_biomolecules = df.columns[:quant_value_range].sort_values().tolist() sorted_biomolecule_names_dict = {k: v for k, v in",
"to biomolecule name, value to biomolecule_id options=[{'label': value, 'value': key} for key, value",
"'value'), Input('dataset_id', 'value')]) def update_biomolecule_boxplot(biomolecule_id, dataset_id): dataset = dataset_dict[dataset_id] df = df_dict[dataset] biomolecule_names_dict",
"proteomics_df.columns[:proteomics_quant_range].sort_values().tolist() default_biomolecule = list(sorted_biomolecule_names_dict.keys())[0] plotly_config = {\"toImageButtonOptions\":{'format':'svg', 'filename': 'dash_plot'}, \"displaylogo\": False} first_card =",
"nav import navbar external_stylesheets=[dbc.themes.BOOTSTRAP] \"\"\"app = dash.Dash( __name__, external_stylesheets=external_stylesheets) app.title = 'COVID-19 Multi-Omics'\"\"\"",
"[ dbc.CardHeader(\"CONTROL PANEL\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody( [html.P(\"Select Dataset\", className=\"card-title\", style={\"font-weight\":\"bold\"}), dcc.Dropdown( id='dataset_id',",
"dataset_dict[dataset_id] df = df_dict[dataset] biomolecule_names_dict = global_names_dict[dataset] quant_value_range = quant_value_range_dict[dataset] # build ome",
"quant value columns value=available_datasets[0]), html.Hr(), html.P(\"Select Biomolecule\", className=\"card-title\", style={\"font-weight\":\"bold\"}), # NOTE: This is",
"style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='pca-scores-figure', config=plotly_config)) ]) second_card = dbc.Card( [ dbc.CardHeader(\"PCA LOADINGS PLOT\",",
"from dash.dependencies import Input, Output import datetime from data import get_omics_data, get_biomolecule_names, get_combined_data",
"dataset_dict, df_dict, quant_value_range_dict, global_names_dict from app import metabolomics_biomolecule_names_dict from app import lipidomics_biomolecule_names_dict from",
"\"Linear Regression\", id=\"tooltip-lr\", style={\"cursor\": \"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"linear_regression\")), dbc.NavItem(dbc.NavLink( html.Span( \"Differential Expression\", id=\"tooltip-de\",",
"biomolecule_name = biomolecule_names_dict[biomolecule_id] fig = biomolecule_bar(df, biomolecule_id, biomolecule_names_dict) return fig @app.callback( Output('biomolecule-boxplot', 'figure'),",
"get combined omics df and quant value range print(\"Creating combined omics df...\") df_dict,",
"\"color\":\"grey\"}, ),disabled=False, href=\"differential_expression\")), dbc.NavItem(dbc.NavLink( html.Span( \"Clustergrammer\", id=\"tooltip-cg\", style={\"cursor\":\"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"clustergrammer\")), html.Hr(), control_panel",
"options=[{'label': value, 'value': key} for key, value in sorted_biomolecule_names_dict.items()], # only passing in",
"lipidomics data...\") from app import lipidomics_df, lipidomics_quant_range print(\"Lipidomics data shape: {}\".format(lipidomics_df.shape)) print(\"Loading proteomics",
"for i in available_datasets], # only passing in quant value columns value=available_datasets[0]), html.Hr(),",
"default_biomolecule = list(sorted_biomolecule_names_dict.keys())[0] plotly_config = {\"toImageButtonOptions\":{'format':'svg', 'filename': 'dash_plot'}, \"displaylogo\": False} first_card = dbc.Card(",
"= global_names_dict[dataset] sorted_biomolecule_names_dict = {k: v for k, v in sorted(biomolecule_names_dict.items(), key=lambda item:",
"### control_panel = dbc.Card( [ dbc.CardHeader(\"CONTROL PANEL\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody( [html.P(\"Select Dataset\",",
"[ dbc.CardHeader(\"PCA SCORES PLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='pca-scores-figure', config=plotly_config)) ]) second_card = dbc.Card(",
"data shape: {}\".format(transcriptomics_df.shape)) available_datasets = ['Proteins', 'Lipids', 'Metabolites', 'Transcripts', 'Combined Biomolecules'] # define",
"3})), html.Hr(), dbc.Row( [dbc.Col( dbc.Nav( [ html.H3(\"TYPE OF ANALYSIS\", style={\"font-weight\":\"bold\", \"color\":\"black\"}), dbc.NavItem(dbc.NavLink(\"PCA\", active=True,",
"only passing in quant value columns value=default_biomolecule, className=\"dropdown-item p-0\"), ]) ]) #app.layout =",
"ome_type_list = [dataset] * quant_value_range else: ome_type_list = ['proteomics'] * quant_value_range_dict['proteomics'] ome_type_list.extend(['lipidomics'] *",
"= dbc.Container([ navbar, html.Hr(), dbc.Row(dbc.Col(html.H1(\"COVID-19 Multi-Omics Data Dashboard\"), width={\"size\": 6, \"offset\": 3})), html.Hr(),",
"style={\"font-weight\":\"bold\"}), dcc.Dropdown( id='dataset_id', options=[{'label': i, 'value': i} for i in available_datasets], # only",
"dbc.CardHeader(\"BIOMOLECULE BARPLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='biomolecule-barplot', config=plotly_config)) ]) fourth_card = dbc.Card( [ dbc.CardHeader(\"BIOMOLECULE",
"\"displaylogo\": False} first_card = dbc.Card( [ dbc.CardHeader(\"PCA SCORES PLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='pca-scores-figure',",
"data sorted_biomolecule_names_dict = {k: v for k, v in sorted(proteomics_biomolecule_names_dict.items(), key=lambda item: item[1])}",
"md=6) dbc.Col(first_card, md=4), dbc.Col(second_card, md=6) ], className=\"mb-3\"), dbc.Row([dbc.Col(third_card, md=7, align=\"center\"), dbc.Col(fourth_card, md=5, align=\"center\")],",
"# get biomolecule index biomolecule_index = df.columns.tolist().index(biomolecule_id) ome_type_list[biomolecule_index] = 'selected_biomolecule' fig = pca_loadings_plot(df,",
"global_names_dict[dataset] biomolecule_name = biomolecule_names_dict[biomolecule_id] fig = biomolecule_bar(df, biomolecule_id, biomolecule_names_dict) return fig @app.callback( Output('biomolecule-boxplot',",
"= dbc.Card( [ dbc.CardHeader(\"CONTROL PANEL\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody( [html.P(\"Select Dataset\", className=\"card-title\", style={\"font-weight\":\"bold\"}),",
"PANEL\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody( [html.P(\"Select Dataset\", className=\"card-title\", style={\"font-weight\":\"bold\"}), dcc.Dropdown( id='dataset_id', options=[{'label': i,",
"not dbc dcc.Dropdown( id='biomolecule_id', # label maps to biomolecule name, value to biomolecule_id",
"print(\"Lipidomics data shape: {}\".format(lipidomics_df.shape)) print(\"Loading proteomics data...\") from app import proteomics_df, proteomics_quant_range print(\"Proteomics",
"import dash import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as",
"= [dataset] * quant_value_range else: ome_type_list = ['proteomics'] * quant_value_range_dict['proteomics'] ome_type_list.extend(['lipidomics'] * quant_value_range_dict['lipidomics'])",
"return fig @app.callback( Output('biomolecule-barplot', 'figure'), [Input('biomolecule_id', 'value'), Input('dataset_id', 'value')]) def update_biomolecule_barplot(biomolecule_id, dataset_id): dataset",
"shape: {}\".format(lipidomics_df.shape)) print(\"Loading proteomics data...\") from app import proteomics_df, proteomics_quant_range print(\"Proteomics data shape:",
"df = df_dict[dataset] quant_value_range = quant_value_range_dict[dataset] fig = pca_scores_plot(df, quant_value_range) return fig @app.callback(",
"dbc.Row(dbc.Col(html.H1(\"COVID-19 Multi-Omics Data Dashboard\"), width={\"size\": 6, \"offset\": 3})), html.Hr(), dbc.Row( [dbc.Col( dbc.Nav( [",
"'value')]) def update_pca_loadings_plot(dataset_id, biomolecule_id): dataset = dataset_dict[dataset_id] df = df_dict[dataset] biomolecule_names_dict = global_names_dict[dataset]",
"import get_omics_data, get_biomolecule_names, get_combined_data from plot import biomolecule_bar, boxplot, pca_scores_plot, pca_loadings_plot from nav",
"dictionaries from app import dataset_dict, df_dict, quant_value_range_dict, global_names_dict from app import metabolomics_biomolecule_names_dict from",
"= df.columns[:quant_value_range].sort_values().tolist() sorted_biomolecule_names_dict = {k: v for k, v in sorted(biomolecule_names_dict.items(), key=lambda item:",
"from nav import navbar external_stylesheets=[dbc.themes.BOOTSTRAP] \"\"\"app = dash.Dash( __name__, external_stylesheets=external_stylesheets) app.title = 'COVID-19",
"import transcriptomics_df, transcriptomics_quant_range print(\"Transcriptomics data shape: {}\".format(transcriptomics_df.shape)) available_datasets = ['Proteins', 'Lipids', 'Metabolites', 'Transcripts',",
"NOTE: This is dcc object not dbc dcc.Dropdown( id='biomolecule_id', # label maps to",
"for k, v in sorted(biomolecule_names_dict.items(), key=lambda item: item[1])} options=[{'label': value, 'value': key} for",
"biomolecule_names_dict = global_names_dict[dataset] biomolecule_name = biomolecule_names_dict[biomolecule_id] fig = boxplot(df, biomolecule_id, biomolecule_names_dict) return fig",
"= biomolecule_names_dict[biomolecule_id] fig = biomolecule_bar(df, biomolecule_id, biomolecule_names_dict) return fig @app.callback( Output('biomolecule-boxplot', 'figure'), [Input('biomolecule_id',",
"app import proteomics_df, proteomics_quant_range print(\"Proteomics data shape: {}\".format(proteomics_df.shape)) print(\"Loading transcriptomics data...\") from app",
"omics df and quant value range print(\"Creating combined omics df...\") df_dict, quant_value_range_dict =",
"'value': key} for key, value in sorted_biomolecule_names_dict.items() if key in available_biomolecules] #print(options) return",
"passing in quant value columns value=default_biomolecule, className=\"dropdown-item p-0\"), ]) ]) #app.layout = dbc.Container([",
"dataset_dict[dataset_id] df = df_dict[dataset] quant_value_range = quant_value_range_dict[dataset] fig = pca_scores_plot(df, quant_value_range) return fig",
"= dbc.Card( [ dbc.CardHeader(\"PCA LOADINGS PLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='pca-loadings-figure', config=plotly_config)) ]) third_card",
"className=\"card-title\", style={\"font-weight\":\"bold\"}), # NOTE: This is dcc object not dbc dcc.Dropdown( id='biomolecule_id', #",
"LOADINGS PLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='pca-loadings-figure', config=plotly_config)) ]) third_card = dbc.Card( [ dbc.CardHeader(\"BIOMOLECULE",
"app import metabolomics_df, metabolomics_quant_range print(\"Metabolomics data shape: {}\".format(metabolomics_df.shape)) print(\"Loading lipidomics data...\") from app",
"'value': i} for i in available_datasets], # only passing in quant value columns",
"dbc.NavItem(dbc.NavLink(\"PCA\", active=True, href=\"pca\", style={\"background-color\":\"grey\"})), dbc.NavItem(dbc.NavLink( html.Span( \"Linear Regression\", id=\"tooltip-lr\", style={\"cursor\": \"pointer\", \"color\":\"grey\"}, ),disabled=False,",
"Output('biomolecule-boxplot', 'figure'), [Input('biomolecule_id', 'value'), Input('dataset_id', 'value')]) def update_biomolecule_boxplot(biomolecule_id, dataset_id): dataset = dataset_dict[dataset_id] df",
"'Combined Biomolecules'] # define dataset dictionaries from app import dataset_dict, df_dict, quant_value_range_dict, global_names_dict",
"navbar, html.Hr(), dbc.Row(dbc.Col(html.H1(\"COVID-19 Multi-Omics Data Dashboard\"), width={\"size\": 6, \"offset\": 3})), html.Hr(), dbc.Row( [dbc.Col(",
"import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output",
"app import proteomics_biomolecule_names_dict from app import transcriptomics_biomolecule_names_dict # get combined omics df and",
"html.Span( \"Linear Regression\", id=\"tooltip-lr\", style={\"cursor\": \"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"linear_regression\")), dbc.NavItem(dbc.NavLink( html.Span( \"Differential Expression\",",
"get_omics_data, get_biomolecule_names, get_combined_data from plot import biomolecule_bar, boxplot, pca_scores_plot, pca_loadings_plot from nav import",
"Output('biomolecule_id', 'value'), [Input('dataset_id', 'value')]) def update_default_biomolecule(dataset_id): dataset = dataset_dict[dataset_id] biomolecule_names_dict = global_names_dict[dataset] sorted_biomolecule_names_dict",
"proteomics_biomolecule_names_dict from app import transcriptomics_biomolecule_names_dict # get combined omics df and quant value",
"'value')]) def update_default_biomolecule(dataset_id): dataset = dataset_dict[dataset_id] biomolecule_names_dict = global_names_dict[dataset] sorted_biomolecule_names_dict = {k: v",
"import dataset_dict, df_dict, quant_value_range_dict, global_names_dict from app import metabolomics_biomolecule_names_dict from app import lipidomics_biomolecule_names_dict",
"biomolecule index biomolecule_index = df.columns.tolist().index(biomolecule_id) ome_type_list[biomolecule_index] = 'selected_biomolecule' fig = pca_loadings_plot(df, quant_value_range, dataset_id,",
"* quant_value_range_dict['metabolomics']) ome_type_list.extend(['transcriptomics'] * quant_value_range_dict['transcriptomics']) # get biomolecule index biomolecule_index = df.columns.tolist().index(biomolecule_id) ome_type_list[biomolecule_index]",
"# NOTE: This is dcc object not dbc dcc.Dropdown( id='biomolecule_id', # label maps",
"data import get_omics_data, get_biomolecule_names, get_combined_data from plot import biomolecule_bar, boxplot, pca_scores_plot, pca_loadings_plot from",
"'Metabolites', 'Transcripts', 'Combined Biomolecules'] # define dataset dictionaries from app import dataset_dict, df_dict,",
"shape: {}\".format(transcriptomics_df.shape)) available_datasets = ['Proteins', 'Lipids', 'Metabolites', 'Transcripts', 'Combined Biomolecules'] # define dataset",
"print(\"Loading transcriptomics data...\") from app import transcriptomics_df, transcriptomics_quant_range print(\"Transcriptomics data shape: {}\".format(transcriptomics_df.shape)) available_datasets",
"= dbc.Card( [ dbc.CardHeader(\"BIOMOLECULE BOXPLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='biomolecule-boxplot', config=plotly_config)) ]) ### control_panel",
"columns value=default_biomolecule, className=\"dropdown-item p-0\"), ]) ]) #app.layout = dbc.Container([ layout = dbc.Container([ navbar,",
"id=\"tooltip-lr\", style={\"cursor\": \"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"linear_regression\")), dbc.NavItem(dbc.NavLink( html.Span( \"Differential Expression\", id=\"tooltip-de\", style={\"cursor\": \"pointer\",",
"= 'COVID-19 Multi-Omics'\"\"\" from app import app print() print(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")) print(\"Loading data for",
"update_default_biomolecule(dataset_id): dataset = dataset_dict[dataset_id] biomolecule_names_dict = global_names_dict[dataset] sorted_biomolecule_names_dict = {k: v for k,",
"biomolecule_names_dict) return fig print(\"Starting server...\") if __name__ == '__main__': app.run_server( debug=True, host='0.0.0.0', #port='8080'",
"in sorted(proteomics_biomolecule_names_dict.items(), key=lambda item: item[1])} #available_biomolecules = proteomics_biomolecule_names_dict.values() #available_biomolecules = proteomics_df.columns[:proteomics_quant_range].sort_values().tolist() default_biomolecule =",
"import biomolecule_bar, boxplot, pca_scores_plot, pca_loadings_plot from nav import navbar external_stylesheets=[dbc.themes.BOOTSTRAP] \"\"\"app = dash.Dash(",
"app import transcriptomics_df, transcriptomics_quant_range print(\"Transcriptomics data shape: {}\".format(transcriptomics_df.shape)) available_datasets = ['Proteins', 'Lipids', 'Metabolites',",
"import metabolomics_biomolecule_names_dict from app import lipidomics_biomolecule_names_dict from app import proteomics_biomolecule_names_dict from app import",
"config=plotly_config)) ]) ### control_panel = dbc.Card( [ dbc.CardHeader(\"CONTROL PANEL\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(",
"k, v in sorted(biomolecule_names_dict.items(), key=lambda item: item[1])} default_biomolecule=list(sorted_biomolecule_names_dict.keys())[0] return default_biomolecule @app.callback( Output('pca-scores-figure', 'figure'),",
"), md=2, className=\"mb-3\"), #dbc.Col(control_panel, md=6) dbc.Col(first_card, md=4), dbc.Col(second_card, md=6) ], className=\"mb-3\"), dbc.Row([dbc.Col(third_card, md=7,",
"print(\"Metabolomics data shape: {}\".format(metabolomics_df.shape)) print(\"Loading lipidomics data...\") from app import lipidomics_df, lipidomics_quant_range print(\"Lipidomics",
"quant_value_range_dict, global_names_dict from app import metabolomics_biomolecule_names_dict from app import lipidomics_biomolecule_names_dict from app import",
"print() print(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")) print(\"Loading data for pca...\") print() # load metabolomics data matrix",
"\"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='pca-loadings-figure', config=plotly_config)) ]) third_card = dbc.Card( [ dbc.CardHeader(\"BIOMOLECULE BARPLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}),",
"df_dict, quant_value_range_dict, global_names_dict from app import metabolomics_biomolecule_names_dict from app import lipidomics_biomolecule_names_dict from app",
"OF ANALYSIS\", style={\"font-weight\":\"bold\", \"color\":\"black\"}), dbc.NavItem(dbc.NavLink(\"PCA\", active=True, href=\"pca\", style={\"background-color\":\"grey\"})), dbc.NavItem(dbc.NavLink( html.Span( \"Linear Regression\", id=\"tooltip-lr\",",
"= df_dict[dataset] biomolecule_names_dict = global_names_dict[dataset] biomolecule_name = biomolecule_names_dict[biomolecule_id] fig = biomolecule_bar(df, biomolecule_id, biomolecule_names_dict)",
"= biomolecule_bar(df, biomolecule_id, biomolecule_names_dict) return fig @app.callback( Output('biomolecule-boxplot', 'figure'), [Input('biomolecule_id', 'value'), Input('dataset_id', 'value')])",
"dbc.CardHeader(\"PCA SCORES PLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='pca-scores-figure', config=plotly_config)) ]) second_card = dbc.Card( [",
"ome_type_list.extend(['lipidomics'] * quant_value_range_dict['lipidomics']) ome_type_list.extend(['metabolomics'] * quant_value_range_dict['metabolomics']) ome_type_list.extend(['transcriptomics'] * quant_value_range_dict['transcriptomics']) # get biomolecule index",
"app import metabolomics_biomolecule_names_dict from app import lipidomics_biomolecule_names_dict from app import proteomics_biomolecule_names_dict from app",
"dataset = dataset_dict[dataset_id] df = df_dict[dataset] biomolecule_names_dict = global_names_dict[dataset] quant_value_range = quant_value_range_dict[dataset] #",
"quant_value_range else: ome_type_list = ['proteomics'] * quant_value_range_dict['proteomics'] ome_type_list.extend(['lipidomics'] * quant_value_range_dict['lipidomics']) ome_type_list.extend(['metabolomics'] * quant_value_range_dict['metabolomics'])",
"get_biomolecule_names, get_combined_data from plot import biomolecule_bar, boxplot, pca_scores_plot, pca_loadings_plot from nav import navbar",
"html.Span( \"Clustergrammer\", id=\"tooltip-cg\", style={\"cursor\":\"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"clustergrammer\")), html.Hr(), control_panel ], vertical=\"md\", pills=True ),",
"config=plotly_config)) ]) third_card = dbc.Card( [ dbc.CardHeader(\"BIOMOLECULE BARPLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='biomolecule-barplot', config=plotly_config))",
"style={\"font-weight\":\"bold\"}), # NOTE: This is dcc object not dbc dcc.Dropdown( id='biomolecule_id', # label",
"),disabled=False, href=\"linear_regression\")), dbc.NavItem(dbc.NavLink( html.Span( \"Differential Expression\", id=\"tooltip-de\", style={\"cursor\": \"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"differential_expression\")), dbc.NavItem(dbc.NavLink(",
"= df_dict[dataset] quant_value_range = quant_value_range_dict[dataset] fig = pca_scores_plot(df, quant_value_range) return fig @app.callback( Output('pca-loadings-figure',",
"= dbc.Card( [ dbc.CardHeader(\"PCA SCORES PLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='pca-scores-figure', config=plotly_config)) ]) second_card",
"key} for key, value in sorted_biomolecule_names_dict.items() if key in available_biomolecules] #print(options) return options",
"dbc.Card( [ dbc.CardHeader(\"CONTROL PANEL\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody( [html.P(\"Select Dataset\", className=\"card-title\", style={\"font-weight\":\"bold\"}), dcc.Dropdown(",
"\"offset\": 3})), html.Hr(), dbc.Row( [dbc.Col( dbc.Nav( [ html.H3(\"TYPE OF ANALYSIS\", style={\"font-weight\":\"bold\", \"color\":\"black\"}), dbc.NavItem(dbc.NavLink(\"PCA\",",
"df.columns[:quant_value_range].sort_values().tolist() sorted_biomolecule_names_dict = {k: v for k, v in sorted(biomolecule_names_dict.items(), key=lambda item: item[1])}",
"options @app.callback( Output('biomolecule_id', 'value'), [Input('dataset_id', 'value')]) def update_default_biomolecule(dataset_id): dataset = dataset_dict[dataset_id] biomolecule_names_dict =",
"\"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='biomolecule-boxplot', config=plotly_config)) ]) ### control_panel = dbc.Card( [ dbc.CardHeader(\"CONTROL PANEL\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\",",
"pca_loadings_plot(df, quant_value_range, dataset_id, biomolecule_names_dict, ome_type_list) return fig @app.callback( Output('biomolecule-barplot', 'figure'), [Input('biomolecule_id', 'value'), Input('dataset_id',",
"combined omics df...\") df_dict, quant_value_range_dict = get_combined_data(df_dict, quant_value_range_dict) # start with proteomics data",
"as dcc import dash_html_components as html from dash.dependencies import Input, Output import datetime",
"Output import datetime from data import get_omics_data, get_biomolecule_names, get_combined_data from plot import biomolecule_bar,",
"def update_biomolecule_boxplot(biomolecule_id, dataset_id): dataset = dataset_dict[dataset_id] df = df_dict[dataset] biomolecule_names_dict = global_names_dict[dataset] biomolecule_name",
"ome_type_list) return fig @app.callback( Output('biomolecule-barplot', 'figure'), [Input('biomolecule_id', 'value'), Input('dataset_id', 'value')]) def update_biomolecule_barplot(biomolecule_id, dataset_id):",
"= dbc.Container([ layout = dbc.Container([ navbar, html.Hr(), dbc.Row(dbc.Col(html.H1(\"COVID-19 Multi-Omics Data Dashboard\"), width={\"size\": 6,",
"quant_value_range_dict['proteomics'] ome_type_list.extend(['lipidomics'] * quant_value_range_dict['lipidomics']) ome_type_list.extend(['metabolomics'] * quant_value_range_dict['metabolomics']) ome_type_list.extend(['transcriptomics'] * quant_value_range_dict['transcriptomics']) # get biomolecule",
"style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody( [html.P(\"Select Dataset\", className=\"card-title\", style={\"font-weight\":\"bold\"}), dcc.Dropdown( id='dataset_id', options=[{'label': i, 'value':",
"\"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='biomolecule-barplot', config=plotly_config)) ]) fourth_card = dbc.Card( [ dbc.CardHeader(\"BIOMOLECULE BOXPLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}),",
"= dataset_dict[dataset_id] biomolecule_names_dict = global_names_dict[dataset] df = df_dict[dataset] quant_value_range = quant_value_range_dict[dataset] # get",
"= get_combined_data(df_dict, quant_value_range_dict) # start with proteomics data sorted_biomolecule_names_dict = {k: v for",
"\"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='biomolecule-barplot', config=plotly_config)) ]) fourth_card = dbc.Card( [ dbc.CardHeader(\"BIOMOLECULE BOXPLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\",",
"dcc object not dbc dcc.Dropdown( id='biomolecule_id', # label maps to biomolecule name, value",
"html.Span( \"Differential Expression\", id=\"tooltip-de\", style={\"cursor\": \"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"differential_expression\")), dbc.NavItem(dbc.NavLink( html.Span( \"Clustergrammer\", id=\"tooltip-cg\",",
"= quant_value_range_dict[dataset] # get list of columns for dataset available_biomolecules = df.columns[:quant_value_range].sort_values().tolist() sorted_biomolecule_names_dict",
"data...\") from app import lipidomics_df, lipidomics_quant_range print(\"Lipidomics data shape: {}\".format(lipidomics_df.shape)) print(\"Loading proteomics data...\")",
"key in available_biomolecules] #print(options) return options @app.callback( Output('biomolecule_id', 'value'), [Input('dataset_id', 'value')]) def update_default_biomolecule(dataset_id):",
"second_card = dbc.Card( [ dbc.CardHeader(\"PCA LOADINGS PLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='pca-loadings-figure', config=plotly_config)) ])",
"k, v in sorted(biomolecule_names_dict.items(), key=lambda item: item[1])} options=[{'label': value, 'value': key} for key,",
"dataset == 'combined': ome_type_list = [dataset] * quant_value_range else: ome_type_list = ['proteomics'] *",
"* quant_value_range else: ome_type_list = ['proteomics'] * quant_value_range_dict['proteomics'] ome_type_list.extend(['lipidomics'] * quant_value_range_dict['lipidomics']) ome_type_list.extend(['metabolomics'] *",
"sorted(biomolecule_names_dict.items(), key=lambda item: item[1])} default_biomolecule=list(sorted_biomolecule_names_dict.keys())[0] return default_biomolecule @app.callback( Output('pca-scores-figure', 'figure'), [Input('dataset_id', 'value')]) def",
"This is dcc object not dbc dcc.Dropdown( id='biomolecule_id', # label maps to biomolecule",
"* quant_value_range_dict['lipidomics']) ome_type_list.extend(['metabolomics'] * quant_value_range_dict['metabolomics']) ome_type_list.extend(['transcriptomics'] * quant_value_range_dict['transcriptomics']) # get biomolecule index biomolecule_index",
"combined omics df and quant value range print(\"Creating combined omics df...\") df_dict, quant_value_range_dict",
"style={\"cursor\": \"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"differential_expression\")), dbc.NavItem(dbc.NavLink( html.Span( \"Clustergrammer\", id=\"tooltip-cg\", style={\"cursor\":\"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"clustergrammer\")),",
"style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='biomolecule-barplot', config=plotly_config)) ]) fourth_card = dbc.Card( [ dbc.CardHeader(\"BIOMOLECULE BOXPLOT\", style={\"background-color\":\"#5bc0de\",",
"\"color\":\"grey\"}, ),disabled=False, href=\"clustergrammer\")), html.Hr(), control_panel ], vertical=\"md\", pills=True ), md=2, className=\"mb-3\"), #dbc.Col(control_panel, md=6)",
"value, 'value': key} for key, value in sorted_biomolecule_names_dict.items() if key in available_biomolecules] #print(options)",
"start with proteomics data sorted_biomolecule_names_dict = {k: v for k, v in sorted(proteomics_biomolecule_names_dict.items(),",
"item[1])} options=[{'label': value, 'value': key} for key, value in sorted_biomolecule_names_dict.items() if key in",
"print(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")) print(\"Loading data for pca...\") print() # load metabolomics data matrix print(\"Loading",
"\"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='biomolecule-boxplot', config=plotly_config)) ]) ### control_panel = dbc.Card( [ dbc.CardHeader(\"CONTROL PANEL\", style={\"background-color\":\"#5bc0de\",",
"[ dbc.CardHeader(\"PCA LOADINGS PLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='pca-loadings-figure', config=plotly_config)) ]) third_card = dbc.Card(",
"print(\"Proteomics data shape: {}\".format(proteomics_df.shape)) print(\"Loading transcriptomics data...\") from app import transcriptomics_df, transcriptomics_quant_range print(\"Transcriptomics",
"in available_datasets], # only passing in quant value columns value=available_datasets[0]), html.Hr(), html.P(\"Select Biomolecule\",",
"]) ]) #app.layout = dbc.Container([ layout = dbc.Container([ navbar, html.Hr(), dbc.Row(dbc.Col(html.H1(\"COVID-19 Multi-Omics Data",
"in sorted_biomolecule_names_dict.items()], # only passing in quant value columns value=default_biomolecule, className=\"dropdown-item p-0\"), ])",
"import lipidomics_df, lipidomics_quant_range print(\"Lipidomics data shape: {}\".format(lipidomics_df.shape)) print(\"Loading proteomics data...\") from app import",
"metabolomics_df, metabolomics_quant_range print(\"Metabolomics data shape: {}\".format(metabolomics_df.shape)) print(\"Loading lipidomics data...\") from app import lipidomics_df,",
"df and quant value range print(\"Creating combined omics df...\") df_dict, quant_value_range_dict = get_combined_data(df_dict,",
"from app import proteomics_biomolecule_names_dict from app import transcriptomics_biomolecule_names_dict # get combined omics df",
"plotly_config = {\"toImageButtonOptions\":{'format':'svg', 'filename': 'dash_plot'}, \"displaylogo\": False} first_card = dbc.Card( [ dbc.CardHeader(\"PCA SCORES",
"def update_biomolecule_options(dataset_id): dataset = dataset_dict[dataset_id] biomolecule_names_dict = global_names_dict[dataset] df = df_dict[dataset] quant_value_range =",
"available_biomolecules] #print(options) return options @app.callback( Output('biomolecule_id', 'value'), [Input('dataset_id', 'value')]) def update_default_biomolecule(dataset_id): dataset =",
"load metabolomics data matrix print(\"Loading metabolomics data...\") from app import metabolomics_df, metabolomics_quant_range print(\"Metabolomics",
"dataset = dataset_dict[dataset_id] biomolecule_names_dict = global_names_dict[dataset] df = df_dict[dataset] quant_value_range = quant_value_range_dict[dataset] #",
"list(sorted_biomolecule_names_dict.keys())[0] plotly_config = {\"toImageButtonOptions\":{'format':'svg', 'filename': 'dash_plot'}, \"displaylogo\": False} first_card = dbc.Card( [ dbc.CardHeader(\"PCA",
"className=\"dropdown-item p-0\"), ]) ]) #app.layout = dbc.Container([ layout = dbc.Container([ navbar, html.Hr(), dbc.Row(dbc.Col(html.H1(\"COVID-19",
"lipidomics_quant_range print(\"Lipidomics data shape: {}\".format(lipidomics_df.shape)) print(\"Loading proteomics data...\") from app import proteomics_df, proteomics_quant_range",
"id='dataset_id', options=[{'label': i, 'value': i} for i in available_datasets], # only passing in",
"p-0\"), ]) ]) #app.layout = dbc.Container([ layout = dbc.Container([ navbar, html.Hr(), dbc.Row(dbc.Col(html.H1(\"COVID-19 Multi-Omics",
"\"color\":\"black\"}), dbc.NavItem(dbc.NavLink(\"PCA\", active=True, href=\"pca\", style={\"background-color\":\"grey\"})), dbc.NavItem(dbc.NavLink( html.Span( \"Linear Regression\", id=\"tooltip-lr\", style={\"cursor\": \"pointer\", \"color\":\"grey\"},",
"@app.callback( dash.dependencies.Output('biomolecule_id', 'options'), [Input('dataset_id', 'value')]) def update_biomolecule_options(dataset_id): dataset = dataset_dict[dataset_id] biomolecule_names_dict = global_names_dict[dataset]",
"], className=\"mb-3\"), dbc.Row([dbc.Col(third_card, md=7, align=\"center\"), dbc.Col(fourth_card, md=5, align=\"center\")], className=\"mb-3\") ], fluid=True) @app.callback( dash.dependencies.Output('biomolecule_id',",
"html.Hr(), control_panel ], vertical=\"md\", pills=True ), md=2, className=\"mb-3\"), #dbc.Col(control_panel, md=6) dbc.Col(first_card, md=4), dbc.Col(second_card,",
"update_biomolecule_boxplot(biomolecule_id, dataset_id): dataset = dataset_dict[dataset_id] df = df_dict[dataset] biomolecule_names_dict = global_names_dict[dataset] biomolecule_name =",
"pca_loadings_plot from nav import navbar external_stylesheets=[dbc.themes.BOOTSTRAP] \"\"\"app = dash.Dash( __name__, external_stylesheets=external_stylesheets) app.title =",
"= {k: v for k, v in sorted(biomolecule_names_dict.items(), key=lambda item: item[1])} options=[{'label': value,",
"app.title = 'COVID-19 Multi-Omics'\"\"\" from app import app print() print(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")) print(\"Loading data",
"if key in available_biomolecules] #print(options) return options @app.callback( Output('biomolecule_id', 'value'), [Input('dataset_id', 'value')]) def",
"#print(options) return options @app.callback( Output('biomolecule_id', 'value'), [Input('dataset_id', 'value')]) def update_default_biomolecule(dataset_id): dataset = dataset_dict[dataset_id]",
"{}\".format(metabolomics_df.shape)) print(\"Loading lipidomics data...\") from app import lipidomics_df, lipidomics_quant_range print(\"Lipidomics data shape: {}\".format(lipidomics_df.shape))",
"Output('pca-loadings-figure', 'figure'), [Input('dataset_id', 'value'), Input('biomolecule_id', 'value')]) def update_pca_loadings_plot(dataset_id, biomolecule_id): dataset = dataset_dict[dataset_id] df",
"pills=True ), md=2, className=\"mb-3\"), #dbc.Col(control_panel, md=6) dbc.Col(first_card, md=4), dbc.Col(second_card, md=6) ], className=\"mb-3\"), dbc.Row([dbc.Col(third_card,",
"[html.P(\"Select Dataset\", className=\"card-title\", style={\"font-weight\":\"bold\"}), dcc.Dropdown( id='dataset_id', options=[{'label': i, 'value': i} for i in",
"lipidomics_biomolecule_names_dict from app import proteomics_biomolecule_names_dict from app import transcriptomics_biomolecule_names_dict # get combined omics",
"data shape: {}\".format(lipidomics_df.shape)) print(\"Loading proteomics data...\") from app import proteomics_df, proteomics_quant_range print(\"Proteomics data",
"print(\"Loading proteomics data...\") from app import proteomics_df, proteomics_quant_range print(\"Proteomics data shape: {}\".format(proteomics_df.shape)) print(\"Loading",
"import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from",
"from app import transcriptomics_biomolecule_names_dict # get combined omics df and quant value range",
"Input, Output import datetime from data import get_omics_data, get_biomolecule_names, get_combined_data from plot import",
"#available_biomolecules = proteomics_df.columns[:proteomics_quant_range].sort_values().tolist() default_biomolecule = list(sorted_biomolecule_names_dict.keys())[0] plotly_config = {\"toImageButtonOptions\":{'format':'svg', 'filename': 'dash_plot'}, \"displaylogo\": False}",
"biomolecule_id, biomolecule_names_dict) return fig print(\"Starting server...\") if __name__ == '__main__': app.run_server( debug=True, host='0.0.0.0',",
"dataset_dict[dataset_id] df = df_dict[dataset] biomolecule_names_dict = global_names_dict[dataset] biomolecule_name = biomolecule_names_dict[biomolecule_id] fig = boxplot(df,",
"get list of columns for dataset available_biomolecules = df.columns[:quant_value_range].sort_values().tolist() sorted_biomolecule_names_dict = {k: v",
"config=plotly_config)) ]) second_card = dbc.Card( [ dbc.CardHeader(\"PCA LOADINGS PLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='pca-loadings-figure',",
"else: ome_type_list = ['proteomics'] * quant_value_range_dict['proteomics'] ome_type_list.extend(['lipidomics'] * quant_value_range_dict['lipidomics']) ome_type_list.extend(['metabolomics'] * quant_value_range_dict['metabolomics']) ome_type_list.extend(['transcriptomics']",
"= ['proteomics'] * quant_value_range_dict['proteomics'] ome_type_list.extend(['lipidomics'] * quant_value_range_dict['lipidomics']) ome_type_list.extend(['metabolomics'] * quant_value_range_dict['metabolomics']) ome_type_list.extend(['transcriptomics'] * quant_value_range_dict['transcriptomics'])",
"biomolecule_names_dict[biomolecule_id] fig = biomolecule_bar(df, biomolecule_id, biomolecule_names_dict) return fig @app.callback( Output('biomolecule-boxplot', 'figure'), [Input('biomolecule_id', 'value'),",
"),disabled=False, href=\"differential_expression\")), dbc.NavItem(dbc.NavLink( html.Span( \"Clustergrammer\", id=\"tooltip-cg\", style={\"cursor\":\"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"clustergrammer\")), html.Hr(), control_panel ],",
"style={\"background-color\":\"grey\"})), dbc.NavItem(dbc.NavLink( html.Span( \"Linear Regression\", id=\"tooltip-lr\", style={\"cursor\": \"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"linear_regression\")), dbc.NavItem(dbc.NavLink( html.Span(",
"Output('biomolecule-barplot', 'figure'), [Input('biomolecule_id', 'value'), Input('dataset_id', 'value')]) def update_biomolecule_barplot(biomolecule_id, dataset_id): dataset = dataset_dict[dataset_id] df",
"fig = boxplot(df, biomolecule_id, biomolecule_names_dict) return fig print(\"Starting server...\") if __name__ == '__main__':",
"only passing in quant value columns value=available_datasets[0]), html.Hr(), html.P(\"Select Biomolecule\", className=\"card-title\", style={\"font-weight\":\"bold\"}), #",
"False} first_card = dbc.Card( [ dbc.CardHeader(\"PCA SCORES PLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='pca-scores-figure', config=plotly_config))",
"dbc.Col(fourth_card, md=5, align=\"center\")], className=\"mb-3\") ], fluid=True) @app.callback( dash.dependencies.Output('biomolecule_id', 'options'), [Input('dataset_id', 'value')]) def update_biomolecule_options(dataset_id):",
"{}\".format(lipidomics_df.shape)) print(\"Loading proteomics data...\") from app import proteomics_df, proteomics_quant_range print(\"Proteomics data shape: {}\".format(proteomics_df.shape))",
"from app import metabolomics_df, metabolomics_quant_range print(\"Metabolomics data shape: {}\".format(metabolomics_df.shape)) print(\"Loading lipidomics data...\") from",
"\"font-size\":\"large\"}), dbc.CardBody( [html.P(\"Select Dataset\", className=\"card-title\", style={\"font-weight\":\"bold\"}), dcc.Dropdown( id='dataset_id', options=[{'label': i, 'value': i} for",
"import datetime from data import get_omics_data, get_biomolecule_names, get_combined_data from plot import biomolecule_bar, boxplot,",
"= df_dict[dataset] biomolecule_names_dict = global_names_dict[dataset] biomolecule_name = biomolecule_names_dict[biomolecule_id] fig = boxplot(df, biomolecule_id, biomolecule_names_dict)",
"import navbar external_stylesheets=[dbc.themes.BOOTSTRAP] \"\"\"app = dash.Dash( __name__, external_stylesheets=external_stylesheets) app.title = 'COVID-19 Multi-Omics'\"\"\" from",
"]) fourth_card = dbc.Card( [ dbc.CardHeader(\"BIOMOLECULE BOXPLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='biomolecule-boxplot', config=plotly_config)) ])",
"global_names_dict[dataset] quant_value_range = quant_value_range_dict[dataset] # build ome type list for coloring if not",
"from app import dataset_dict, df_dict, quant_value_range_dict, global_names_dict from app import metabolomics_biomolecule_names_dict from app",
"key} for key, value in sorted_biomolecule_names_dict.items()], # only passing in quant value columns",
"'dash_plot'}, \"displaylogo\": False} first_card = dbc.Card( [ dbc.CardHeader(\"PCA SCORES PLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}),",
"fig @app.callback( Output('pca-loadings-figure', 'figure'), [Input('dataset_id', 'value'), Input('biomolecule_id', 'value')]) def update_pca_loadings_plot(dataset_id, biomolecule_id): dataset =",
"value in sorted_biomolecule_names_dict.items() if key in available_biomolecules] #print(options) return options @app.callback( Output('biomolecule_id', 'value'),",
"print() # load metabolomics data matrix print(\"Loading metabolomics data...\") from app import metabolomics_df,",
"dbc.Col(first_card, md=4), dbc.Col(second_card, md=6) ], className=\"mb-3\"), dbc.Row([dbc.Col(third_card, md=7, align=\"center\"), dbc.Col(fourth_card, md=5, align=\"center\")], className=\"mb-3\")",
"to biomolecule_id options=[{'label': value, 'value': key} for key, value in sorted_biomolecule_names_dict.items()], # only",
"for k, v in sorted(proteomics_biomolecule_names_dict.items(), key=lambda item: item[1])} #available_biomolecules = proteomics_biomolecule_names_dict.values() #available_biomolecules =",
"html.Hr(), dbc.Row(dbc.Col(html.H1(\"COVID-19 Multi-Omics Data Dashboard\"), width={\"size\": 6, \"offset\": 3})), html.Hr(), dbc.Row( [dbc.Col( dbc.Nav(",
"item[1])} default_biomolecule=list(sorted_biomolecule_names_dict.keys())[0] return default_biomolecule @app.callback( Output('pca-scores-figure', 'figure'), [Input('dataset_id', 'value')]) def update_pca_scores_plot(dataset_id): dataset =",
"'selected_biomolecule' fig = pca_loadings_plot(df, quant_value_range, dataset_id, biomolecule_names_dict, ome_type_list) return fig @app.callback( Output('biomolecule-barplot', 'figure'),",
"[Input('biomolecule_id', 'value'), Input('dataset_id', 'value')]) def update_biomolecule_barplot(biomolecule_id, dataset_id): dataset = dataset_dict[dataset_id] df = df_dict[dataset]",
"= 'selected_biomolecule' fig = pca_loadings_plot(df, quant_value_range, dataset_id, biomolecule_names_dict, ome_type_list) return fig @app.callback( Output('biomolecule-barplot',",
"label maps to biomolecule name, value to biomolecule_id options=[{'label': value, 'value': key} for",
"sorted_biomolecule_names_dict.items()], # only passing in quant value columns value=default_biomolecule, className=\"dropdown-item p-0\"), ]) ])",
"available_biomolecules = df.columns[:quant_value_range].sort_values().tolist() sorted_biomolecule_names_dict = {k: v for k, v in sorted(biomolecule_names_dict.items(), key=lambda",
"data shape: {}\".format(proteomics_df.shape)) print(\"Loading transcriptomics data...\") from app import transcriptomics_df, transcriptomics_quant_range print(\"Transcriptomics data",
"update_biomolecule_barplot(biomolecule_id, dataset_id): dataset = dataset_dict[dataset_id] df = df_dict[dataset] biomolecule_names_dict = global_names_dict[dataset] biomolecule_name =",
"style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='biomolecule-boxplot', config=plotly_config)) ]) ### control_panel = dbc.Card( [ dbc.CardHeader(\"CONTROL PANEL\",",
"id=\"tooltip-cg\", style={\"cursor\":\"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"clustergrammer\")), html.Hr(), control_panel ], vertical=\"md\", pills=True ), md=2, className=\"mb-3\"),",
"item[1])} #available_biomolecules = proteomics_biomolecule_names_dict.values() #available_biomolecules = proteomics_df.columns[:proteomics_quant_range].sort_values().tolist() default_biomolecule = list(sorted_biomolecule_names_dict.keys())[0] plotly_config = {\"toImageButtonOptions\":{'format':'svg',",
"], fluid=True) @app.callback( dash.dependencies.Output('biomolecule_id', 'options'), [Input('dataset_id', 'value')]) def update_biomolecule_options(dataset_id): dataset = dataset_dict[dataset_id] biomolecule_names_dict",
"for k, v in sorted(biomolecule_names_dict.items(), key=lambda item: item[1])} default_biomolecule=list(sorted_biomolecule_names_dict.keys())[0] return default_biomolecule @app.callback( Output('pca-scores-figure',",
"[ dbc.CardHeader(\"BIOMOLECULE BOXPLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='biomolecule-boxplot', config=plotly_config)) ]) ### control_panel = dbc.Card(",
"html from dash.dependencies import Input, Output import datetime from data import get_omics_data, get_biomolecule_names,",
"global_names_dict from app import metabolomics_biomolecule_names_dict from app import lipidomics_biomolecule_names_dict from app import proteomics_biomolecule_names_dict",
"key=lambda item: item[1])} options=[{'label': value, 'value': key} for key, value in sorted_biomolecule_names_dict.items() if",
"= global_names_dict[dataset] biomolecule_name = biomolecule_names_dict[biomolecule_id] fig = boxplot(df, biomolecule_id, biomolecule_names_dict) return fig print(\"Starting",
"import Input, Output import datetime from data import get_omics_data, get_biomolecule_names, get_combined_data from plot",
"dataset dictionaries from app import dataset_dict, df_dict, quant_value_range_dict, global_names_dict from app import metabolomics_biomolecule_names_dict",
"\"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody( [html.P(\"Select Dataset\", className=\"card-title\", style={\"font-weight\":\"bold\"}), dcc.Dropdown( id='dataset_id', options=[{'label': i, 'value': i}",
"in quant value columns value=available_datasets[0]), html.Hr(), html.P(\"Select Biomolecule\", className=\"card-title\", style={\"font-weight\":\"bold\"}), # NOTE: This",
"ome_type_list.extend(['metabolomics'] * quant_value_range_dict['metabolomics']) ome_type_list.extend(['transcriptomics'] * quant_value_range_dict['transcriptomics']) # get biomolecule index biomolecule_index = df.columns.tolist().index(biomolecule_id)",
"sorted_biomolecule_names_dict = {k: v for k, v in sorted(proteomics_biomolecule_names_dict.items(), key=lambda item: item[1])} #available_biomolecules",
"# define dataset dictionaries from app import dataset_dict, df_dict, quant_value_range_dict, global_names_dict from app",
"value range print(\"Creating combined omics df...\") df_dict, quant_value_range_dict = get_combined_data(df_dict, quant_value_range_dict) # start",
"fourth_card = dbc.Card( [ dbc.CardHeader(\"BIOMOLECULE BOXPLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='biomolecule-boxplot', config=plotly_config)) ]) ###",
"quant_value_range, dataset_id, biomolecule_names_dict, ome_type_list) return fig @app.callback( Output('biomolecule-barplot', 'figure'), [Input('biomolecule_id', 'value'), Input('dataset_id', 'value')])",
"plot import biomolecule_bar, boxplot, pca_scores_plot, pca_loadings_plot from nav import navbar external_stylesheets=[dbc.themes.BOOTSTRAP] \"\"\"app =",
"available_datasets], # only passing in quant value columns value=available_datasets[0]), html.Hr(), html.P(\"Select Biomolecule\", className=\"card-title\",",
"global_names_dict[dataset] df = df_dict[dataset] quant_value_range = quant_value_range_dict[dataset] # get list of columns for",
"from data import get_omics_data, get_biomolecule_names, get_combined_data from plot import biomolecule_bar, boxplot, pca_scores_plot, pca_loadings_plot",
"import metabolomics_df, metabolomics_quant_range print(\"Metabolomics data shape: {}\".format(metabolomics_df.shape)) print(\"Loading lipidomics data...\") from app import",
"className=\"card-title\", style={\"font-weight\":\"bold\"}), dcc.Dropdown( id='dataset_id', options=[{'label': i, 'value': i} for i in available_datasets], #",
"lipidomics_df, lipidomics_quant_range print(\"Lipidomics data shape: {}\".format(lipidomics_df.shape)) print(\"Loading proteomics data...\") from app import proteomics_df,",
"[ html.H3(\"TYPE OF ANALYSIS\", style={\"font-weight\":\"bold\", \"color\":\"black\"}), dbc.NavItem(dbc.NavLink(\"PCA\", active=True, href=\"pca\", style={\"background-color\":\"grey\"})), dbc.NavItem(dbc.NavLink( html.Span( \"Linear",
"dbc.NavItem(dbc.NavLink( html.Span( \"Differential Expression\", id=\"tooltip-de\", style={\"cursor\": \"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"differential_expression\")), dbc.NavItem(dbc.NavLink( html.Span( \"Clustergrammer\",",
"== 'combined': ome_type_list = [dataset] * quant_value_range else: ome_type_list = ['proteomics'] * quant_value_range_dict['proteomics']",
"df_dict[dataset] quant_value_range = quant_value_range_dict[dataset] # get list of columns for dataset available_biomolecules =",
"md=5, align=\"center\")], className=\"mb-3\") ], fluid=True) @app.callback( dash.dependencies.Output('biomolecule_id', 'options'), [Input('dataset_id', 'value')]) def update_biomolecule_options(dataset_id): dataset",
"'figure'), [Input('biomolecule_id', 'value'), Input('dataset_id', 'value')]) def update_biomolecule_barplot(biomolecule_id, dataset_id): dataset = dataset_dict[dataset_id] df =",
"object not dbc dcc.Dropdown( id='biomolecule_id', # label maps to biomolecule name, value to",
"external_stylesheets=external_stylesheets) app.title = 'COVID-19 Multi-Omics'\"\"\" from app import app print() print(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")) print(\"Loading",
"%H:%M:%S\")) print(\"Loading data for pca...\") print() # load metabolomics data matrix print(\"Loading metabolomics",
"dataset_dict[dataset_id] df = df_dict[dataset] biomolecule_names_dict = global_names_dict[dataset] biomolecule_name = biomolecule_names_dict[biomolecule_id] fig = biomolecule_bar(df,",
"for pca...\") print() # load metabolomics data matrix print(\"Loading metabolomics data...\") from app",
"sorted_biomolecule_names_dict.items() if key in available_biomolecules] #print(options) return options @app.callback( Output('biomolecule_id', 'value'), [Input('dataset_id', 'value')])",
"'value'), Input('biomolecule_id', 'value')]) def update_pca_loadings_plot(dataset_id, biomolecule_id): dataset = dataset_dict[dataset_id] df = df_dict[dataset] biomolecule_names_dict",
"print(\"Loading data for pca...\") print() # load metabolomics data matrix print(\"Loading metabolomics data...\")",
"md=6) ], className=\"mb-3\"), dbc.Row([dbc.Col(third_card, md=7, align=\"center\"), dbc.Col(fourth_card, md=5, align=\"center\")], className=\"mb-3\") ], fluid=True) @app.callback(",
"'figure'), [Input('biomolecule_id', 'value'), Input('dataset_id', 'value')]) def update_biomolecule_boxplot(biomolecule_id, dataset_id): dataset = dataset_dict[dataset_id] df =",
"from app import lipidomics_df, lipidomics_quant_range print(\"Lipidomics data shape: {}\".format(lipidomics_df.shape)) print(\"Loading proteomics data...\") from",
"]) #app.layout = dbc.Container([ layout = dbc.Container([ navbar, html.Hr(), dbc.Row(dbc.Col(html.H1(\"COVID-19 Multi-Omics Data Dashboard\"),",
"vertical=\"md\", pills=True ), md=2, className=\"mb-3\"), #dbc.Col(control_panel, md=6) dbc.Col(first_card, md=4), dbc.Col(second_card, md=6) ], className=\"mb-3\"),",
"= proteomics_biomolecule_names_dict.values() #available_biomolecules = proteomics_df.columns[:proteomics_quant_range].sort_values().tolist() default_biomolecule = list(sorted_biomolecule_names_dict.keys())[0] plotly_config = {\"toImageButtonOptions\":{'format':'svg', 'filename': 'dash_plot'},",
"update_pca_loadings_plot(dataset_id, biomolecule_id): dataset = dataset_dict[dataset_id] df = df_dict[dataset] biomolecule_names_dict = global_names_dict[dataset] quant_value_range =",
"import lipidomics_biomolecule_names_dict from app import proteomics_biomolecule_names_dict from app import transcriptomics_biomolecule_names_dict # get combined",
"@app.callback( Output('biomolecule-boxplot', 'figure'), [Input('biomolecule_id', 'value'), Input('dataset_id', 'value')]) def update_biomolecule_boxplot(biomolecule_id, dataset_id): dataset = dataset_dict[dataset_id]",
"href=\"linear_regression\")), dbc.NavItem(dbc.NavLink( html.Span( \"Differential Expression\", id=\"tooltip-de\", style={\"cursor\": \"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"differential_expression\")), dbc.NavItem(dbc.NavLink( html.Span(",
"in sorted(biomolecule_names_dict.items(), key=lambda item: item[1])} options=[{'label': value, 'value': key} for key, value in",
"'value': key} for key, value in sorted_biomolecule_names_dict.items()], # only passing in quant value",
"href=\"clustergrammer\")), html.Hr(), control_panel ], vertical=\"md\", pills=True ), md=2, className=\"mb-3\"), #dbc.Col(control_panel, md=6) dbc.Col(first_card, md=4),",
"md=2, className=\"mb-3\"), #dbc.Col(control_panel, md=6) dbc.Col(first_card, md=4), dbc.Col(second_card, md=6) ], className=\"mb-3\"), dbc.Row([dbc.Col(third_card, md=7, align=\"center\"),",
"item: item[1])} options=[{'label': value, 'value': key} for key, value in sorted_biomolecule_names_dict.items() if key",
"df = df_dict[dataset] biomolecule_names_dict = global_names_dict[dataset] biomolecule_name = biomolecule_names_dict[biomolecule_id] fig = boxplot(df, biomolecule_id,",
"ome_type_list.extend(['transcriptomics'] * quant_value_range_dict['transcriptomics']) # get biomolecule index biomolecule_index = df.columns.tolist().index(biomolecule_id) ome_type_list[biomolecule_index] = 'selected_biomolecule'",
"biomolecule_names_dict = global_names_dict[dataset] biomolecule_name = biomolecule_names_dict[biomolecule_id] fig = biomolecule_bar(df, biomolecule_id, biomolecule_names_dict) return fig",
"pca_scores_plot, pca_loadings_plot from nav import navbar external_stylesheets=[dbc.themes.BOOTSTRAP] \"\"\"app = dash.Dash( __name__, external_stylesheets=external_stylesheets) app.title",
"control_panel = dbc.Card( [ dbc.CardHeader(\"CONTROL PANEL\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody( [html.P(\"Select Dataset\", className=\"card-title\",",
"fig = biomolecule_bar(df, biomolecule_id, biomolecule_names_dict) return fig @app.callback( Output('biomolecule-boxplot', 'figure'), [Input('biomolecule_id', 'value'), Input('dataset_id',",
"@app.callback( Output('biomolecule_id', 'value'), [Input('dataset_id', 'value')]) def update_default_biomolecule(dataset_id): dataset = dataset_dict[dataset_id] biomolecule_names_dict = global_names_dict[dataset]",
"'value'), [Input('dataset_id', 'value')]) def update_default_biomolecule(dataset_id): dataset = dataset_dict[dataset_id] biomolecule_names_dict = global_names_dict[dataset] sorted_biomolecule_names_dict =",
"transcriptomics_biomolecule_names_dict # get combined omics df and quant value range print(\"Creating combined omics",
"\"color\":\"grey\"}, ),disabled=False, href=\"linear_regression\")), dbc.NavItem(dbc.NavLink( html.Span( \"Differential Expression\", id=\"tooltip-de\", style={\"cursor\": \"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"differential_expression\")),",
"def update_biomolecule_barplot(biomolecule_id, dataset_id): dataset = dataset_dict[dataset_id] df = df_dict[dataset] biomolecule_names_dict = global_names_dict[dataset] biomolecule_name",
"\"Clustergrammer\", id=\"tooltip-cg\", style={\"cursor\":\"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"clustergrammer\")), html.Hr(), control_panel ], vertical=\"md\", pills=True ), md=2,",
"data...\") from app import transcriptomics_df, transcriptomics_quant_range print(\"Transcriptomics data shape: {}\".format(transcriptomics_df.shape)) available_datasets = ['Proteins',",
"[Input('dataset_id', 'value')]) def update_pca_scores_plot(dataset_id): dataset = dataset_dict[dataset_id] df = df_dict[dataset] quant_value_range = quant_value_range_dict[dataset]",
"# only passing in quant value columns value=default_biomolecule, className=\"dropdown-item p-0\"), ]) ]) #app.layout",
"id=\"tooltip-de\", style={\"cursor\": \"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"differential_expression\")), dbc.NavItem(dbc.NavLink( html.Span( \"Clustergrammer\", id=\"tooltip-cg\", style={\"cursor\":\"pointer\", \"color\":\"grey\"}, ),disabled=False,",
"# get list of columns for dataset available_biomolecules = df.columns[:quant_value_range].sort_values().tolist() sorted_biomolecule_names_dict = {k:",
"and quant value range print(\"Creating combined omics df...\") df_dict, quant_value_range_dict = get_combined_data(df_dict, quant_value_range_dict)",
"dbc.CardHeader(\"BIOMOLECULE BOXPLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='biomolecule-boxplot', config=plotly_config)) ]) ### control_panel = dbc.Card( [",
"transcriptomics_quant_range print(\"Transcriptomics data shape: {}\".format(transcriptomics_df.shape)) available_datasets = ['Proteins', 'Lipids', 'Metabolites', 'Transcripts', 'Combined Biomolecules']",
"= ['Proteins', 'Lipids', 'Metabolites', 'Transcripts', 'Combined Biomolecules'] # define dataset dictionaries from app",
"# only passing in quant value columns value=available_datasets[0]), html.Hr(), html.P(\"Select Biomolecule\", className=\"card-title\", style={\"font-weight\":\"bold\"}),",
"= dataset_dict[dataset_id] df = df_dict[dataset] quant_value_range = quant_value_range_dict[dataset] fig = pca_scores_plot(df, quant_value_range) return",
"biomolecule name, value to biomolecule_id options=[{'label': value, 'value': key} for key, value in",
"[dataset] * quant_value_range else: ome_type_list = ['proteomics'] * quant_value_range_dict['proteomics'] ome_type_list.extend(['lipidomics'] * quant_value_range_dict['lipidomics']) ome_type_list.extend(['metabolomics']",
"sorted_biomolecule_names_dict = {k: v for k, v in sorted(biomolecule_names_dict.items(), key=lambda item: item[1])} options=[{'label':",
"v in sorted(biomolecule_names_dict.items(), key=lambda item: item[1])} options=[{'label': value, 'value': key} for key, value",
"6, \"offset\": 3})), html.Hr(), dbc.Row( [dbc.Col( dbc.Nav( [ html.H3(\"TYPE OF ANALYSIS\", style={\"font-weight\":\"bold\", \"color\":\"black\"}),",
"= {k: v for k, v in sorted(proteomics_biomolecule_names_dict.items(), key=lambda item: item[1])} #available_biomolecules =",
"config=plotly_config)) ]) fourth_card = dbc.Card( [ dbc.CardHeader(\"BIOMOLECULE BOXPLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='biomolecule-boxplot', config=plotly_config))",
"= {k: v for k, v in sorted(biomolecule_names_dict.items(), key=lambda item: item[1])} default_biomolecule=list(sorted_biomolecule_names_dict.keys())[0] return",
"data matrix print(\"Loading metabolomics data...\") from app import metabolomics_df, metabolomics_quant_range print(\"Metabolomics data shape:",
"list for coloring if not dataset == 'combined': ome_type_list = [dataset] * quant_value_range",
"quant_value_range_dict = get_combined_data(df_dict, quant_value_range_dict) # start with proteomics data sorted_biomolecule_names_dict = {k: v",
"proteomics data...\") from app import proteomics_df, proteomics_quant_range print(\"Proteomics data shape: {}\".format(proteomics_df.shape)) print(\"Loading transcriptomics",
"= dataset_dict[dataset_id] biomolecule_names_dict = global_names_dict[dataset] sorted_biomolecule_names_dict = {k: v for k, v in",
"= quant_value_range_dict[dataset] fig = pca_scores_plot(df, quant_value_range) return fig @app.callback( Output('pca-loadings-figure', 'figure'), [Input('dataset_id', 'value'),",
"import dash_html_components as html from dash.dependencies import Input, Output import datetime from data",
"style={\"font-weight\":\"bold\", \"color\":\"black\"}), dbc.NavItem(dbc.NavLink(\"PCA\", active=True, href=\"pca\", style={\"background-color\":\"grey\"})), dbc.NavItem(dbc.NavLink( html.Span( \"Linear Regression\", id=\"tooltip-lr\", style={\"cursor\": \"pointer\",",
"value to biomolecule_id options=[{'label': value, 'value': key} for key, value in sorted_biomolecule_names_dict.items()], #",
"html.Hr(), html.P(\"Select Biomolecule\", className=\"card-title\", style={\"font-weight\":\"bold\"}), # NOTE: This is dcc object not dbc",
"app import lipidomics_biomolecule_names_dict from app import proteomics_biomolecule_names_dict from app import transcriptomics_biomolecule_names_dict # get",
"BOXPLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='biomolecule-boxplot', config=plotly_config)) ]) ### control_panel = dbc.Card( [ dbc.CardHeader(\"CONTROL",
"= df.columns.tolist().index(biomolecule_id) ome_type_list[biomolecule_index] = 'selected_biomolecule' fig = pca_loadings_plot(df, quant_value_range, dataset_id, biomolecule_names_dict, ome_type_list) return",
"dash.dependencies import Input, Output import datetime from data import get_omics_data, get_biomolecule_names, get_combined_data from",
"fig = pca_loadings_plot(df, quant_value_range, dataset_id, biomolecule_names_dict, ome_type_list) return fig @app.callback( Output('biomolecule-barplot', 'figure'), [Input('biomolecule_id',",
"]) second_card = dbc.Card( [ dbc.CardHeader(\"PCA LOADINGS PLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='pca-loadings-figure', config=plotly_config))",
"BARPLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='biomolecule-barplot', config=plotly_config)) ]) fourth_card = dbc.Card( [ dbc.CardHeader(\"BIOMOLECULE BOXPLOT\",",
"is dcc object not dbc dcc.Dropdown( id='biomolecule_id', # label maps to biomolecule name,",
"align=\"center\"), dbc.Col(fourth_card, md=5, align=\"center\")], className=\"mb-3\") ], fluid=True) @app.callback( dash.dependencies.Output('biomolecule_id', 'options'), [Input('dataset_id', 'value')]) def",
"= dataset_dict[dataset_id] df = df_dict[dataset] biomolecule_names_dict = global_names_dict[dataset] quant_value_range = quant_value_range_dict[dataset] # build",
"sorted(biomolecule_names_dict.items(), key=lambda item: item[1])} options=[{'label': value, 'value': key} for key, value in sorted_biomolecule_names_dict.items()",
"third_card = dbc.Card( [ dbc.CardHeader(\"BIOMOLECULE BARPLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='biomolecule-barplot', config=plotly_config)) ]) fourth_card",
"get_combined_data from plot import biomolecule_bar, boxplot, pca_scores_plot, pca_loadings_plot from nav import navbar external_stylesheets=[dbc.themes.BOOTSTRAP]",
"def update_pca_loadings_plot(dataset_id, biomolecule_id): dataset = dataset_dict[dataset_id] df = df_dict[dataset] biomolecule_names_dict = global_names_dict[dataset] quant_value_range",
"value, 'value': key} for key, value in sorted_biomolecule_names_dict.items()], # only passing in quant",
"pca_scores_plot(df, quant_value_range) return fig @app.callback( Output('pca-loadings-figure', 'figure'), [Input('dataset_id', 'value'), Input('biomolecule_id', 'value')]) def update_pca_loadings_plot(dataset_id,",
"in available_biomolecules] #print(options) return options @app.callback( Output('biomolecule_id', 'value'), [Input('dataset_id', 'value')]) def update_default_biomolecule(dataset_id): dataset",
"= global_names_dict[dataset] quant_value_range = quant_value_range_dict[dataset] # build ome type list for coloring if",
"\"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"linear_regression\")), dbc.NavItem(dbc.NavLink( html.Span( \"Differential Expression\", id=\"tooltip-de\", style={\"cursor\": \"pointer\", \"color\":\"grey\"}, ),disabled=False,",
"quant_value_range_dict[dataset] # build ome type list for coloring if not dataset == 'combined':",
"build ome type list for coloring if not dataset == 'combined': ome_type_list =",
"dbc.Container([ navbar, html.Hr(), dbc.Row(dbc.Col(html.H1(\"COVID-19 Multi-Omics Data Dashboard\"), width={\"size\": 6, \"offset\": 3})), html.Hr(), dbc.Row(",
"dash import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html",
"import app print() print(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")) print(\"Loading data for pca...\") print() # load metabolomics",
"boxplot(df, biomolecule_id, biomolecule_names_dict) return fig print(\"Starting server...\") if __name__ == '__main__': app.run_server( debug=True,",
"= global_names_dict[dataset] df = df_dict[dataset] quant_value_range = quant_value_range_dict[dataset] # get list of columns",
"= pca_loadings_plot(df, quant_value_range, dataset_id, biomolecule_names_dict, ome_type_list) return fig @app.callback( Output('biomolecule-barplot', 'figure'), [Input('biomolecule_id', 'value'),",
"columns value=available_datasets[0]), html.Hr(), html.P(\"Select Biomolecule\", className=\"card-title\", style={\"font-weight\":\"bold\"}), # NOTE: This is dcc object",
"metabolomics_quant_range print(\"Metabolomics data shape: {}\".format(metabolomics_df.shape)) print(\"Loading lipidomics data...\") from app import lipidomics_df, lipidomics_quant_range",
"{}\".format(transcriptomics_df.shape)) available_datasets = ['Proteins', 'Lipids', 'Metabolites', 'Transcripts', 'Combined Biomolecules'] # define dataset dictionaries",
"key=lambda item: item[1])} #available_biomolecules = proteomics_biomolecule_names_dict.values() #available_biomolecules = proteomics_df.columns[:proteomics_quant_range].sort_values().tolist() default_biomolecule = list(sorted_biomolecule_names_dict.keys())[0] plotly_config",
"Biomolecule\", className=\"card-title\", style={\"font-weight\":\"bold\"}), # NOTE: This is dcc object not dbc dcc.Dropdown( id='biomolecule_id',",
"v for k, v in sorted(biomolecule_names_dict.items(), key=lambda item: item[1])} default_biomolecule=list(sorted_biomolecule_names_dict.keys())[0] return default_biomolecule @app.callback(",
"print(\"Creating combined omics df...\") df_dict, quant_value_range_dict = get_combined_data(df_dict, quant_value_range_dict) # start with proteomics",
"'options'), [Input('dataset_id', 'value')]) def update_biomolecule_options(dataset_id): dataset = dataset_dict[dataset_id] biomolecule_names_dict = global_names_dict[dataset] df =",
"matrix print(\"Loading metabolomics data...\") from app import metabolomics_df, metabolomics_quant_range print(\"Metabolomics data shape: {}\".format(metabolomics_df.shape))",
"fig @app.callback( Output('biomolecule-barplot', 'figure'), [Input('biomolecule_id', 'value'), Input('dataset_id', 'value')]) def update_biomolecule_barplot(biomolecule_id, dataset_id): dataset =",
"biomolecule_names_dict) return fig @app.callback( Output('biomolecule-boxplot', 'figure'), [Input('biomolecule_id', 'value'), Input('dataset_id', 'value')]) def update_biomolecule_boxplot(biomolecule_id, dataset_id):",
"= biomolecule_names_dict[biomolecule_id] fig = boxplot(df, biomolecule_id, biomolecule_names_dict) return fig print(\"Starting server...\") if __name__",
"app import app print() print(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")) print(\"Loading data for pca...\") print() # load",
"app print() print(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")) print(\"Loading data for pca...\") print() # load metabolomics data",
"of columns for dataset available_biomolecules = df.columns[:quant_value_range].sort_values().tolist() sorted_biomolecule_names_dict = {k: v for k,",
"[Input('biomolecule_id', 'value'), Input('dataset_id', 'value')]) def update_biomolecule_boxplot(biomolecule_id, dataset_id): dataset = dataset_dict[dataset_id] df = df_dict[dataset]",
"transcriptomics data...\") from app import transcriptomics_df, transcriptomics_quant_range print(\"Transcriptomics data shape: {}\".format(transcriptomics_df.shape)) available_datasets =",
"= dataset_dict[dataset_id] df = df_dict[dataset] biomolecule_names_dict = global_names_dict[dataset] biomolecule_name = biomolecule_names_dict[biomolecule_id] fig =",
"type list for coloring if not dataset == 'combined': ome_type_list = [dataset] *",
"proteomics_quant_range print(\"Proteomics data shape: {}\".format(proteomics_df.shape)) print(\"Loading transcriptomics data...\") from app import transcriptomics_df, transcriptomics_quant_range",
"passing in quant value columns value=available_datasets[0]), html.Hr(), html.P(\"Select Biomolecule\", className=\"card-title\", style={\"font-weight\":\"bold\"}), # NOTE:",
"dash.Dash( __name__, external_stylesheets=external_stylesheets) app.title = 'COVID-19 Multi-Omics'\"\"\" from app import app print() print(datetime.datetime.now().strftime(\"%Y-%m-%d",
"),disabled=False, href=\"clustergrammer\")), html.Hr(), control_panel ], vertical=\"md\", pills=True ), md=2, className=\"mb-3\"), #dbc.Col(control_panel, md=6) dbc.Col(first_card,",
"if not dataset == 'combined': ome_type_list = [dataset] * quant_value_range else: ome_type_list =",
"[dbc.Col( dbc.Nav( [ html.H3(\"TYPE OF ANALYSIS\", style={\"font-weight\":\"bold\", \"color\":\"black\"}), dbc.NavItem(dbc.NavLink(\"PCA\", active=True, href=\"pca\", style={\"background-color\":\"grey\"})), dbc.NavItem(dbc.NavLink(",
"biomolecule_id): dataset = dataset_dict[dataset_id] df = df_dict[dataset] biomolecule_names_dict = global_names_dict[dataset] quant_value_range = quant_value_range_dict[dataset]",
"value columns value=available_datasets[0]), html.Hr(), html.P(\"Select Biomolecule\", className=\"card-title\", style={\"font-weight\":\"bold\"}), # NOTE: This is dcc",
"dataset_id, biomolecule_names_dict, ome_type_list) return fig @app.callback( Output('biomolecule-barplot', 'figure'), [Input('biomolecule_id', 'value'), Input('dataset_id', 'value')]) def",
"biomolecule_id, biomolecule_names_dict) return fig @app.callback( Output('biomolecule-boxplot', 'figure'), [Input('biomolecule_id', 'value'), Input('dataset_id', 'value')]) def update_biomolecule_boxplot(biomolecule_id,",
"key=lambda item: item[1])} default_biomolecule=list(sorted_biomolecule_names_dict.keys())[0] return default_biomolecule @app.callback( Output('pca-scores-figure', 'figure'), [Input('dataset_id', 'value')]) def update_pca_scores_plot(dataset_id):",
"{k: v for k, v in sorted(biomolecule_names_dict.items(), key=lambda item: item[1])} default_biomolecule=list(sorted_biomolecule_names_dict.keys())[0] return default_biomolecule",
"Data Dashboard\"), width={\"size\": 6, \"offset\": 3})), html.Hr(), dbc.Row( [dbc.Col( dbc.Nav( [ html.H3(\"TYPE OF",
"], vertical=\"md\", pills=True ), md=2, className=\"mb-3\"), #dbc.Col(control_panel, md=6) dbc.Col(first_card, md=4), dbc.Col(second_card, md=6) ],",
"return fig @app.callback( Output('biomolecule-boxplot', 'figure'), [Input('biomolecule_id', 'value'), Input('dataset_id', 'value')]) def update_biomolecule_boxplot(biomolecule_id, dataset_id): dataset",
"dbc import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input,",
"biomolecule_id options=[{'label': value, 'value': key} for key, value in sorted_biomolecule_names_dict.items()], # only passing",
"shape: {}\".format(metabolomics_df.shape)) print(\"Loading lipidomics data...\") from app import lipidomics_df, lipidomics_quant_range print(\"Lipidomics data shape:",
"omics df...\") df_dict, quant_value_range_dict = get_combined_data(df_dict, quant_value_range_dict) # start with proteomics data sorted_biomolecule_names_dict",
"dbc.Row( [dbc.Col( dbc.Nav( [ html.H3(\"TYPE OF ANALYSIS\", style={\"font-weight\":\"bold\", \"color\":\"black\"}), dbc.NavItem(dbc.NavLink(\"PCA\", active=True, href=\"pca\", style={\"background-color\":\"grey\"})),",
"from app import app print() print(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")) print(\"Loading data for pca...\") print() #",
"biomolecule_names_dict = global_names_dict[dataset] quant_value_range = quant_value_range_dict[dataset] # build ome type list for coloring",
"for coloring if not dataset == 'combined': ome_type_list = [dataset] * quant_value_range else:",
"dbc.CardBody(dcc.Graph(id='biomolecule-barplot', config=plotly_config)) ]) fourth_card = dbc.Card( [ dbc.CardHeader(\"BIOMOLECULE BOXPLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='biomolecule-boxplot',",
"dcc import dash_html_components as html from dash.dependencies import Input, Output import datetime from",
"dbc.Card( [ dbc.CardHeader(\"PCA LOADINGS PLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='pca-loadings-figure', config=plotly_config)) ]) third_card =",
"from app import metabolomics_biomolecule_names_dict from app import lipidomics_biomolecule_names_dict from app import proteomics_biomolecule_names_dict from",
"layout = dbc.Container([ navbar, html.Hr(), dbc.Row(dbc.Col(html.H1(\"COVID-19 Multi-Omics Data Dashboard\"), width={\"size\": 6, \"offset\": 3})),",
"from app import transcriptomics_df, transcriptomics_quant_range print(\"Transcriptomics data shape: {}\".format(transcriptomics_df.shape)) available_datasets = ['Proteins', 'Lipids',",
"fluid=True) @app.callback( dash.dependencies.Output('biomolecule_id', 'options'), [Input('dataset_id', 'value')]) def update_biomolecule_options(dataset_id): dataset = dataset_dict[dataset_id] biomolecule_names_dict =",
"as html from dash.dependencies import Input, Output import datetime from data import get_omics_data,",
"'Lipids', 'Metabolites', 'Transcripts', 'Combined Biomolecules'] # define dataset dictionaries from app import dataset_dict,",
"dcc.Dropdown( id='biomolecule_id', # label maps to biomolecule name, value to biomolecule_id options=[{'label': value,",
"dataset_dict[dataset_id] biomolecule_names_dict = global_names_dict[dataset] sorted_biomolecule_names_dict = {k: v for k, v in sorted(biomolecule_names_dict.items(),",
"quant_value_range_dict[dataset] # get list of columns for dataset available_biomolecules = df.columns[:quant_value_range].sort_values().tolist() sorted_biomolecule_names_dict =",
"update_pca_scores_plot(dataset_id): dataset = dataset_dict[dataset_id] df = df_dict[dataset] quant_value_range = quant_value_range_dict[dataset] fig = pca_scores_plot(df,",
"style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='pca-loadings-figure', config=plotly_config)) ]) third_card = dbc.Card( [ dbc.CardHeader(\"BIOMOLECULE BARPLOT\", style={\"background-color\":\"#5bc0de\",",
"return fig @app.callback( Output('pca-loadings-figure', 'figure'), [Input('dataset_id', 'value'), Input('biomolecule_id', 'value')]) def update_pca_loadings_plot(dataset_id, biomolecule_id): dataset",
"href=\"differential_expression\")), dbc.NavItem(dbc.NavLink( html.Span( \"Clustergrammer\", id=\"tooltip-cg\", style={\"cursor\":\"pointer\", \"color\":\"grey\"}, ),disabled=False, href=\"clustergrammer\")), html.Hr(), control_panel ], vertical=\"md\",",
"dcc.Dropdown( id='dataset_id', options=[{'label': i, 'value': i} for i in available_datasets], # only passing",
"biomolecule_name = biomolecule_names_dict[biomolecule_id] fig = boxplot(df, biomolecule_id, biomolecule_names_dict) return fig print(\"Starting server...\") if",
"as dbc import dash_core_components as dcc import dash_html_components as html from dash.dependencies import",
"ANALYSIS\", style={\"font-weight\":\"bold\", \"color\":\"black\"}), dbc.NavItem(dbc.NavLink(\"PCA\", active=True, href=\"pca\", style={\"background-color\":\"grey\"})), dbc.NavItem(dbc.NavLink( html.Span( \"Linear Regression\", id=\"tooltip-lr\", style={\"cursor\":",
"update_biomolecule_options(dataset_id): dataset = dataset_dict[dataset_id] biomolecule_names_dict = global_names_dict[dataset] df = df_dict[dataset] quant_value_range = quant_value_range_dict[dataset]",
"fig = pca_scores_plot(df, quant_value_range) return fig @app.callback( Output('pca-loadings-figure', 'figure'), [Input('dataset_id', 'value'), Input('biomolecule_id', 'value')])",
"\"font-weight\":\"bold\", \"font-size\":\"large\"}), dbc.CardBody(dcc.Graph(id='pca-loadings-figure', config=plotly_config)) ]) third_card = dbc.Card( [ dbc.CardHeader(\"BIOMOLECULE BARPLOT\", style={\"background-color\":\"#5bc0de\", \"font-weight\":\"bold\",",
"Biomolecules'] # define dataset dictionaries from app import dataset_dict, df_dict, quant_value_range_dict, global_names_dict from",
"# start with proteomics data sorted_biomolecule_names_dict = {k: v for k, v in",
"ome type list for coloring if not dataset == 'combined': ome_type_list = [dataset]"
] |
[
"options={ }, bases=(models.Model,), ), migrations.CreateModel( name='Week', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('date',",
"-*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import",
"django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [",
"-*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations",
"models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('requested_by', models.ManyToManyField(related_name=b'requested_availability_updates', to=settings.AUTH_USER_MODEL)), ('user', models.ForeignKey(related_name=b'update_requests', to=settings.AUTH_USER_MODEL)), ], options={ },",
"('user', models.ForeignKey(related_name=b'availability_weeks', to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ('date',), }, bases=(models.Model,), ), migrations.AlterUniqueTogether( name='week', unique_together=set([('user',",
"Migration(migrations.Migration): dependencies = [ ('projects', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='UpdateRequest',",
"('user', models.ForeignKey(related_name=b'update_requests', to=settings.AUTH_USER_MODEL)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='Week', fields=[ ('id', models.AutoField(verbose_name='ID',",
"unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies",
"migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('projects', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL),",
"bases=(models.Model,), ), migrations.CreateModel( name='Week', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('date', models.DateField()), ('allocation',",
"name='Week', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('date', models.DateField()), ('allocation', models.IntegerField(default=0)), ('proposed', models.ManyToManyField(related_name=b'availability_weeks',",
"('allocation', models.IntegerField(default=0)), ('proposed', models.ManyToManyField(related_name=b'availability_weeks', to='projects.ProposedResource')), ('user', models.ForeignKey(related_name=b'availability_weeks', to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ('date',), },",
"dependencies = [ ('projects', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='UpdateRequest', fields=[",
"coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from",
"[ migrations.CreateModel( name='UpdateRequest', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('requested_by', models.ManyToManyField(related_name=b'requested_availability_updates', to=settings.AUTH_USER_MODEL)), ('user',",
"name='UpdateRequest', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('requested_by', models.ManyToManyField(related_name=b'requested_availability_updates', to=settings.AUTH_USER_MODEL)), ('user', models.ForeignKey(related_name=b'update_requests', to=settings.AUTH_USER_MODEL)),",
"('date', models.DateField()), ('allocation', models.IntegerField(default=0)), ('proposed', models.ManyToManyField(related_name=b'availability_weeks', to='projects.ProposedResource')), ('user', models.ForeignKey(related_name=b'availability_weeks', to=settings.AUTH_USER_MODEL)), ], options={ 'ordering':",
"models.ManyToManyField(related_name=b'availability_weeks', to='projects.ProposedResource')), ('user', models.ForeignKey(related_name=b'availability_weeks', to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ('date',), }, bases=(models.Model,), ), migrations.AlterUniqueTogether(",
"models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('date', models.DateField()), ('allocation', models.IntegerField(default=0)), ('proposed', models.ManyToManyField(related_name=b'availability_weeks', to='projects.ProposedResource')), ('user', models.ForeignKey(related_name=b'availability_weeks',",
"to='projects.ProposedResource')), ('user', models.ForeignKey(related_name=b'availability_weeks', to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ('date',), }, bases=(models.Model,), ), migrations.AlterUniqueTogether( name='week',",
"import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('projects',",
"('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('requested_by', models.ManyToManyField(related_name=b'requested_availability_updates', to=settings.AUTH_USER_MODEL)), ('user', models.ForeignKey(related_name=b'update_requests', to=settings.AUTH_USER_MODEL)), ], options={",
"operations = [ migrations.CreateModel( name='UpdateRequest', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('requested_by', models.ManyToManyField(related_name=b'requested_availability_updates',",
"= [ migrations.CreateModel( name='UpdateRequest', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('requested_by', models.ManyToManyField(related_name=b'requested_availability_updates', to=settings.AUTH_USER_MODEL)),",
"auto_created=True, primary_key=True)), ('date', models.DateField()), ('allocation', models.IntegerField(default=0)), ('proposed', models.ManyToManyField(related_name=b'availability_weeks', to='projects.ProposedResource')), ('user', models.ForeignKey(related_name=b'availability_weeks', to=settings.AUTH_USER_MODEL)), ],",
"fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('date', models.DateField()), ('allocation', models.IntegerField(default=0)), ('proposed', models.ManyToManyField(related_name=b'availability_weeks', to='projects.ProposedResource')),",
"models.ForeignKey(related_name=b'update_requests', to=settings.AUTH_USER_MODEL)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='Week', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False,",
"], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='Week', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),",
"] operations = [ migrations.CreateModel( name='UpdateRequest', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('requested_by',",
"to=settings.AUTH_USER_MODEL)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='Week', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True,",
"import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration):",
"], options={ 'ordering': ('date',), }, bases=(models.Model,), ), migrations.AlterUniqueTogether( name='week', unique_together=set([('user', 'date')]), ), ]",
"('requested_by', models.ManyToManyField(related_name=b'requested_availability_updates', to=settings.AUTH_USER_MODEL)), ('user', models.ForeignKey(related_name=b'update_requests', to=settings.AUTH_USER_MODEL)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='Week',",
"migrations.CreateModel( name='Week', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('date', models.DateField()), ('allocation', models.IntegerField(default=0)), ('proposed',",
"models.IntegerField(default=0)), ('proposed', models.ManyToManyField(related_name=b'availability_weeks', to='projects.ProposedResource')), ('user', models.ForeignKey(related_name=b'availability_weeks', to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ('date',), }, bases=(models.Model,),",
"from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('projects', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ]",
"class Migration(migrations.Migration): dependencies = [ ('projects', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel(",
"models.ManyToManyField(related_name=b'requested_availability_updates', to=settings.AUTH_USER_MODEL)), ('user', models.ForeignKey(related_name=b'update_requests', to=settings.AUTH_USER_MODEL)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='Week', fields=[",
"to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ('date',), }, bases=(models.Model,), ), migrations.AlterUniqueTogether( name='week', unique_together=set([('user', 'date')]), ),",
"}, bases=(models.Model,), ), migrations.CreateModel( name='Week', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('date', models.DateField()),",
"('proposed', models.ManyToManyField(related_name=b'availability_weeks', to='projects.ProposedResource')), ('user', models.ForeignKey(related_name=b'availability_weeks', to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ('date',), }, bases=(models.Model,), ),",
"[ ('projects', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='UpdateRequest', fields=[ ('id', models.AutoField(verbose_name='ID',",
"import settings class Migration(migrations.Migration): dependencies = [ ('projects', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations =",
"('projects', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='UpdateRequest', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False,",
"from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings",
"models.DateField()), ('allocation', models.IntegerField(default=0)), ('proposed', models.ManyToManyField(related_name=b'availability_weeks', to='projects.ProposedResource')), ('user', models.ForeignKey(related_name=b'availability_weeks', to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ('date',),",
"django.conf import settings class Migration(migrations.Migration): dependencies = [ ('projects', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations",
"utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf",
"settings class Migration(migrations.Migration): dependencies = [ ('projects', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [",
"fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('requested_by', models.ManyToManyField(related_name=b'requested_availability_updates', to=settings.AUTH_USER_MODEL)), ('user', models.ForeignKey(related_name=b'update_requests', to=settings.AUTH_USER_MODEL)), ],",
"'0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='UpdateRequest', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True,",
"serialize=False, auto_created=True, primary_key=True)), ('requested_by', models.ManyToManyField(related_name=b'requested_availability_updates', to=settings.AUTH_USER_MODEL)), ('user', models.ForeignKey(related_name=b'update_requests', to=settings.AUTH_USER_MODEL)), ], options={ }, bases=(models.Model,),",
"= [ ('projects', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='UpdateRequest', fields=[ ('id',",
"__future__ import unicode_literals from django.db import models, migrations from django.conf import settings class",
"migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='UpdateRequest', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),",
"from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies =",
"models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('projects', '0001_initial'),",
"auto_created=True, primary_key=True)), ('requested_by', models.ManyToManyField(related_name=b'requested_availability_updates', to=settings.AUTH_USER_MODEL)), ('user', models.ForeignKey(related_name=b'update_requests', to=settings.AUTH_USER_MODEL)), ], options={ }, bases=(models.Model,), ),",
"primary_key=True)), ('requested_by', models.ManyToManyField(related_name=b'requested_availability_updates', to=settings.AUTH_USER_MODEL)), ('user', models.ForeignKey(related_name=b'update_requests', to=settings.AUTH_USER_MODEL)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel(",
"to=settings.AUTH_USER_MODEL)), ('user', models.ForeignKey(related_name=b'update_requests', to=settings.AUTH_USER_MODEL)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='Week', fields=[ ('id',",
"), migrations.CreateModel( name='Week', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('date', models.DateField()), ('allocation', models.IntegerField(default=0)),",
"models.ForeignKey(related_name=b'availability_weeks', to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ('date',), }, bases=(models.Model,), ), migrations.AlterUniqueTogether( name='week', unique_together=set([('user', 'date')]),",
"primary_key=True)), ('date', models.DateField()), ('allocation', models.IntegerField(default=0)), ('proposed', models.ManyToManyField(related_name=b'availability_weeks', to='projects.ProposedResource')), ('user', models.ForeignKey(related_name=b'availability_weeks', to=settings.AUTH_USER_MODEL)), ], options={",
"('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('date', models.DateField()), ('allocation', models.IntegerField(default=0)), ('proposed', models.ManyToManyField(related_name=b'availability_weeks', to='projects.ProposedResource')), ('user',",
"# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models,",
"migrations.CreateModel( name='UpdateRequest', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('requested_by', models.ManyToManyField(related_name=b'requested_availability_updates', to=settings.AUTH_USER_MODEL)), ('user', models.ForeignKey(related_name=b'update_requests',",
"serialize=False, auto_created=True, primary_key=True)), ('date', models.DateField()), ('allocation', models.IntegerField(default=0)), ('proposed', models.ManyToManyField(related_name=b'availability_weeks', to='projects.ProposedResource')), ('user', models.ForeignKey(related_name=b'availability_weeks', to=settings.AUTH_USER_MODEL)),"
] |
[
"= False for child in self.children(): child.invalidate(pipeline) pipeline.delete(self.name) if is_root_call: pipeline.execute() def invalidate_on(self,",
"is_root_call = True else: is_root_call = False for child in self.children(): child.invalidate(pipeline) pipeline.delete(self.name)",
"if raw_value is not None: return self._serializer.loads(raw_value) else: raise KeyError(item) def __setitem__(self, key,",
"\"\"\" @wraps(f) def wrapper(*args, **kwargs): key = self._serializer.dumps((args, kwargs)) try: ret = self[key]",
"pylint: disable=W0212 if self._region_cache._raise_on_timeout: # raise the redis timeout error instead of a",
"False if self._region_cache.is_disconnected(): raise KeyError(item) # pylint: disable=W0212 if self._region_cache._raise_on_timeout: # raise the",
"Callable or scalar. The value to return. Will be stored in the cache",
"name, timeout=None, update_resets_timeout=True, serializer=pickle): self._region_cache = region_cache self.name = name self._region_cache.conn.hset(name, '__cache_region_created_at__', datetime.utcnow().isoformat())",
"scalar. :param item: The key to get :param alt: Callable or scalar. The",
"handler timed out. Flush it manually\".format(self=self)) for sig in signals: if isinstance(sig, str):",
"alt def __getitem__(self, item): timed_out = False if self._region_cache.is_disconnected(): raise KeyError(item) # pylint:",
"invalidate_on(self, *signals): \"\"\" Bind this cache region to blinker signals. When any of",
"\"\"\" Get the value, or if the value is not in the cache,",
"ret = f(*args, **kwargs) self[key] = ret return ret return wrapper def get_or_compute(self,",
"else: raise KeyError(item) def __setitem__(self, key, value): raw_value = self._serializer.dumps(value) if not self._region_cache.is_disconnected():",
"= region_cache self._serializer = serializer self._pipe = None self._children_key = self.name + \"::child_caches\"",
"logging.getLogger('region_cache').exception( \"Invalidation of {self.name} in signal handler timed out. Flush it manually\".format(self=self)) for",
"subregions of this subregion. :param timeout: The timeout in seconds for this region.",
"triggered, invalidate the cache. :param signals: blinker signal objects or string names for",
"_logger.warning(\"Cannot reach cache. Using alternative\") if callable(alt): return alt() else: return alt def",
"raise KeyError(item) if raw_value is not None: return self._serializer.loads(raw_value) else: raise KeyError(item) def",
"(len(self) == 1 and key in self))) if self._pipe: self._pipe.hdel(self.name, key) else: self._region_cache.conn.hdel(self.name,",
"\"\"\" Decorator that uses a serialized form of the input args as a",
"the subregion. If dots are included, then the dotted regions are treated as",
"= True if timed_out: # pylint: disable=W0212 if self._region_cache._reconnect_on_timeout: self._region_cache.invalidate_connections() raise KeyError(item) if",
"= None self._region_cache = region_cache self._serializer = serializer self._pipe = None self._children_key =",
"def __eq__(self, other): return other.name == self.name def children(self): return (self._region_cache.region(name.decode('utf-8')) for name",
"= value return value except redis.TimeoutError: _logger.warning(\"Cannot reach cache. Using alternative\") if callable(alt):",
"region. When this region is invalidated, the subregion will be too. :param name:",
"get :param alt: Callable or scalar. The value to return. Will be stored",
"else: return alt def __getitem__(self, item): timed_out = False if self._region_cache.is_disconnected(): raise KeyError(item)",
"make for proper nesting of cache structures. \"\"\" def __init__(self, region_cache, name, timeout=None,",
"blinker.signal(sig) sig.connect(handler, weak=False) def cached(self, f): \"\"\" Decorator that uses a serialized form",
"{self.name} because we are disconnected.\") def __iter__(self): for k in self._region_cache.read_conn.hkeys(self.name): if not",
"self._region_cache.read_conn.hget(self.name, item) except redis.TimeoutError: raw_value = None timed_out = True if timed_out: #",
"self._timeout) def __delitem__(self, key): if not self._region_cache.is_disconnected(): should_reset_timeout = (not self._pipe and self._timeout",
"None else self._update_resets_timeout), serializer=serializer or self._serializer ) def invalidate(self, pipeline=None): \"\"\" Delete this",
"this region. When this region is invalidated, the subregion will be too. :param",
"sig.connect(handler, weak=False) def cached(self, f): \"\"\" Decorator that uses a serialized form of",
"raw_value = self._region_cache.read_conn.hget(self.name, item) except redis.TimeoutError: raw_value = None timed_out = True if",
"or len(self) == 0)) self._pipe.execute() if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) retval = True else:",
"internally. :return: None \"\"\" _logger.debug(\"Invalidating region %s\", self.name) if pipeline is None: pipeline",
"When this region is invalidated, the subregion will be too. :param name: The",
"alternative\") if callable(alt): return alt() else: return alt def __getitem__(self, item): timed_out =",
"define loads and dumps(). Defaults to the parent region's setting :return: Region \"\"\"",
"if is_root_call: pipeline.execute() def invalidate_on(self, *signals): \"\"\" Bind this cache region to blinker",
"self._timeout, update_resets_timeout=( update_resets_timeout if self._update_resets_timeout is not None else self._update_resets_timeout), serializer=serializer or self._serializer",
"self.name = name self._region_cache.conn.hset(name, '__cache_region_created_at__', datetime.utcnow().isoformat()) self._timeout = None self._region_cache = region_cache self._serializer",
"subregions. :param pipeline: Used internally. :return: None \"\"\" _logger.debug(\"Invalidating region %s\", self.name) if",
"self._region_cache.conn.hdel(self.name, key) if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) else: raise redis.TimeoutError(f\"Cannot delete item {key} from",
"__init__(self, region_cache, name, timeout=None, update_resets_timeout=True, serializer=pickle): self._region_cache = region_cache self.name = name self._region_cache.conn.hset(name,",
"return other.name == self.name def children(self): return (self._region_cache.region(name.decode('utf-8')) for name in self._region_cache.read_conn.smembers(self._children_key)) def",
"Subsequent calls to the method with the same arguments will return the cached",
"or if the value is not in the cache, compute it from `alt`.",
"def invalidate_on(self, *signals): \"\"\" Bind this cache region to blinker signals. When any",
"Defaults to the parent region's setting. :param serializer: The serializer to use. Must",
"get_or_compute(self, item, alt): \"\"\" Get the value, or if the value is not",
"else: self._pipe.reset() retval = False self._pipe = None return retval def __eq__(self, other):",
"\"::child_caches\" self._update_resets_timeout = update_resets_timeout if timeout: self._timeout = timeout self._region_cache.conn.expire(name, timeout) if '.'",
"= name self._region_cache.conn.hset(name, '__cache_region_created_at__', datetime.utcnow().isoformat()) self._timeout = None self._region_cache = region_cache self._serializer =",
"**kwargs): key = self._serializer.dumps((args, kwargs)) try: ret = self[key] except KeyError: ret =",
"self._pipe.execute() if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) retval = True else: self._pipe.reset() retval = False",
"datetime import datetime from functools import wraps import blinker import logging from logging",
"key and caches the result of calling the method. Subsequent calls to the",
"redis.TimeoutError: logging.getLogger('region_cache').exception( \"Invalidation of {self.name} in signal handler timed out. Flush it manually\".format(self=self))",
"self[item] except KeyError: value = alt() if callable(alt) else alt self[item] = value",
"len(self))) if self._pipe: self._pipe.hset(self.name, key, raw_value) else: self._region_cache.conn.hset(self.name, key, raw_value) if should_reset_timeout: self._region_cache.conn.expire(self.name,",
"__delitem__(self, key): if not self._region_cache.is_disconnected(): should_reset_timeout = (not self._pipe and self._timeout and (self._update_resets_timeout",
"**kwargs): try: self.invalidate() except redis.TimeoutError: logging.getLogger('region_cache').exception( \"Invalidation of {self.name} in signal handler timed",
"Get a sub-region from this region. When this region is invalidated, the subregion",
"if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) retval = True else: self._pipe.reset() retval = False self._pipe",
"timeout error instead of a key error raw_value = self._region_cache.read_conn.hget(self.name, item) else: try:",
"these directly. Instead use the RegionCache.region() function. This will make for proper nesting",
"The key to get :param alt: Callable or scalar. The value to return.",
"self._pipe.hset(self.name, key, raw_value) else: self._region_cache.conn.hset(self.name, key, raw_value) if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) def __delitem__(self,",
"The serializer to use. Must define loads and dumps(). Defaults to the parent",
"(self._update_resets_timeout or not len(self))) if self._pipe: self._pipe.hset(self.name, key, raw_value) else: self._region_cache.conn.hset(self.name, key, raw_value)",
"wraps import blinker import logging from logging import getLogger _logger = getLogger('region_cache') class",
"name, timeout=timeout or self._timeout, update_resets_timeout=( update_resets_timeout if self._update_resets_timeout is not None else self._update_resets_timeout),",
"sig in signals: if isinstance(sig, str): sig = blinker.signal(sig) sig.connect(handler, weak=False) def cached(self,",
"def wrapper(*args, **kwargs): key = self._serializer.dumps((args, kwargs)) try: ret = self[key] except KeyError:",
"setting :return: Region \"\"\" return self._region_cache.region( name=self.name + '.' + name, timeout=timeout or",
"region_cache self._serializer = serializer self._pipe = None self._children_key = self.name + \"::child_caches\" self._update_resets_timeout",
"it should_reset_timeout = (self._timeout and (self._update_resets_timeout or len(self) == 0)) self._pipe.execute() if should_reset_timeout:",
"\"\"\" _logger.debug(\"Invalidating region %s\", self.name) if pipeline is None: pipeline = self._region_cache.conn.pipeline() is_root_call",
"dots are included, then the dotted regions are treated as subregions of this",
"exc_tb): if exc_type is None: # if we started with nothing in the",
"and self._timeout and (self._update_resets_timeout or (len(self) == 1 and key in self))) if",
"delete item {key} from {self.name} because we are disconnected.\") def __iter__(self): for k",
":return: None \"\"\" def handler(sender, **kwargs): try: self.invalidate() except redis.TimeoutError: logging.getLogger('region_cache').exception( \"Invalidation of",
"names for named signals. :return: None \"\"\" def handler(sender, **kwargs): try: self.invalidate() except",
"children(self): return (self._region_cache.region(name.decode('utf-8')) for name in self._region_cache.read_conn.smembers(self._children_key)) def add_child(self, child): self._region_cache.conn.sadd(self._children_key, child.name) def",
"and self._timeout and (self._update_resets_timeout or not len(self))) if self._pipe: self._pipe.hset(self.name, key, raw_value) else:",
"self._region_cache.conn.expire(name, timeout) if '.' in name: parent = name.rsplit('.', 1)[0] parent = self._region_cache.region(parent)",
"pipeline.execute() def invalidate_on(self, *signals): \"\"\" Bind this cache region to blinker signals. When",
"self def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is None: # if we",
"= getLogger('region_cache') class Region(MutableMapping): \"\"\" A bound cache region. Do not instantiate these",
"ret return wrapper def get_or_compute(self, item, alt): \"\"\" Get the value, or if",
"isinstance(sig, str): sig = blinker.signal(sig) sig.connect(handler, weak=False) def cached(self, f): \"\"\" Decorator that",
"except redis.TimeoutError: logging.getLogger('region_cache').exception( \"Invalidation of {self.name} in signal handler timed out. Flush it",
"treated as subregions of this subregion. :param timeout: The timeout in seconds for",
"wrapper def get_or_compute(self, item, alt): \"\"\" Get the value, or if the value",
"+ '.' + name, timeout=timeout or self._timeout, update_resets_timeout=( update_resets_timeout if self._update_resets_timeout is not",
"= region_cache self.name = name self._region_cache.conn.hset(name, '__cache_region_created_at__', datetime.utcnow().isoformat()) self._timeout = None self._region_cache =",
"updating the region resets the timeout. Defaults to the parent region's setting. :param",
"the value, or if the value is not in the cache, compute it",
":param item: The key to get :param alt: Callable or scalar. The value",
"self._pipe.reset() retval = False self._pipe = None return retval def __eq__(self, other): return",
"update_resets_timeout=( update_resets_timeout if self._update_resets_timeout is not None else self._update_resets_timeout), serializer=serializer or self._serializer )",
"import datetime from functools import wraps import blinker import logging from logging import",
"this cache region to blinker signals. When any of the signals have been",
"The value in the cache. \"\"\" try: return self[item] except KeyError: value =",
"pickle import redis from collections.abc import MutableMapping from datetime import datetime from functools",
"redis from collections.abc import MutableMapping from datetime import datetime from functools import wraps",
"import blinker import logging from logging import getLogger _logger = getLogger('region_cache') class Region(MutableMapping):",
"the parent region's timeout :param update_resets_timeout: Whether updating the region resets the timeout.",
"self._pipe.hdel(self.name, key) else: self._region_cache.conn.hdel(self.name, key) if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) else: raise redis.TimeoutError(f\"Cannot delete",
"the cache, reset it should_reset_timeout = (self._timeout and (self._update_resets_timeout or len(self) == 0))",
"cache region. Do not instantiate these directly. Instead use the RegionCache.region() function. This",
"item, alt): \"\"\" Get the value, or if the value is not in",
"k def __len__(self): return self._region_cache.conn.hlen(self.name) def __enter__(self): if not self._pipe: self._pipe = self._region_cache.conn.pipeline()",
"name: The name of the subregion. If dots are included, then the dotted",
"timeout) if '.' in name: parent = name.rsplit('.', 1)[0] parent = self._region_cache.region(parent) parent.add_child(self)",
"started with nothing in the cache, reset it should_reset_timeout = (self._timeout and (self._update_resets_timeout",
"objects or string names for named signals. :return: None \"\"\" def handler(sender, **kwargs):",
"disable=W0212 if self._region_cache._raise_on_timeout: # raise the redis timeout error instead of a key",
"timeout=timeout or self._timeout, update_resets_timeout=( update_resets_timeout if self._update_resets_timeout is not None else self._update_resets_timeout), serializer=serializer",
"for named signals. :return: None \"\"\" def handler(sender, **kwargs): try: self.invalidate() except redis.TimeoutError:",
"\"\"\" Get a sub-region from this region. When this region is invalidated, the",
"timeout: The timeout in seconds for this region. Defaults to the parent region's",
"then the dotted regions are treated as subregions of this subregion. :param timeout:",
"_logger.debug(\"Invalidating region %s\", self.name) if pipeline is None: pipeline = self._region_cache.conn.pipeline() is_root_call =",
"if timeout: self._timeout = timeout self._region_cache.conn.expire(name, timeout) if '.' in name: parent =",
"self._timeout = timeout self._region_cache.conn.expire(name, timeout) if '.' in name: parent = name.rsplit('.', 1)[0]",
"update_resets_timeout if self._update_resets_timeout is not None else self._update_resets_timeout), serializer=serializer or self._serializer ) def",
"cache data and all its subregions. :param pipeline: Used internally. :return: None \"\"\"",
"or not len(self))) if self._pipe: self._pipe.hset(self.name, key, raw_value) else: self._region_cache.conn.hset(self.name, key, raw_value) if",
"reach cache. Using alternative\") if callable(alt): return alt() else: return alt def __getitem__(self,",
"A bound cache region. Do not instantiate these directly. Instead use the RegionCache.region()",
"result. \"\"\" @wraps(f) def wrapper(*args, **kwargs): key = self._serializer.dumps((args, kwargs)) try: ret =",
"self._timeout) else: raise redis.TimeoutError(f\"Cannot delete item {key} from {self.name} because we are disconnected.\")",
"this region is invalidated, the subregion will be too. :param name: The name",
"to the parent region's setting :return: Region \"\"\" return self._region_cache.region( name=self.name + '.'",
"try: ret = self[key] except KeyError: ret = f(*args, **kwargs) self[key] = ret",
"ret = self[key] except KeyError: ret = f(*args, **kwargs) self[key] = ret return",
"True else: is_root_call = False for child in self.children(): child.invalidate(pipeline) pipeline.delete(self.name) if is_root_call:",
"as a key and caches the result of calling the method. Subsequent calls",
"return self._region_cache.conn.hlen(self.name) def __enter__(self): if not self._pipe: self._pipe = self._region_cache.conn.pipeline() return self def",
"pipeline is None: pipeline = self._region_cache.conn.pipeline() is_root_call = True else: is_root_call = False",
"def __enter__(self): if not self._pipe: self._pipe = self._region_cache.conn.pipeline() return self def __exit__(self, exc_type,",
"or scalar. The value to return. Will be stored in the cache on",
"or self._serializer ) def invalidate(self, pipeline=None): \"\"\" Delete this region's cache data and",
"raw_value = self._serializer.dumps(value) if not self._region_cache.is_disconnected(): should_reset_timeout = (not self._pipe and self._timeout and",
"__setitem__(self, key, value): raw_value = self._serializer.dumps(value) if not self._region_cache.is_disconnected(): should_reset_timeout = (not self._pipe",
"the cache. \"\"\" try: return self[item] except KeyError: value = alt() if callable(alt)",
"as subregions of this subregion. :param timeout: The timeout in seconds for this",
"def __init__(self, region_cache, name, timeout=None, update_resets_timeout=True, serializer=pickle): self._region_cache = region_cache self.name = name",
"of the signals have been triggered, invalidate the cache. :param signals: blinker signal",
"included, then the dotted regions are treated as subregions of this subregion. :param",
"disconnected.\") def __iter__(self): for k in self._region_cache.read_conn.hkeys(self.name): if not k.decode('utf-8').startswith('__'): yield k def",
"def children(self): return (self._region_cache.region(name.decode('utf-8')) for name in self._region_cache.read_conn.smembers(self._children_key)) def add_child(self, child): self._region_cache.conn.sadd(self._children_key, child.name)",
"signal handler timed out. Flush it manually\".format(self=self)) for sig in signals: if isinstance(sig,",
"region's cache data and all its subregions. :param pipeline: Used internally. :return: None",
"manually\".format(self=self)) for sig in signals: if isinstance(sig, str): sig = blinker.signal(sig) sig.connect(handler, weak=False)",
"except KeyError: value = alt() if callable(alt) else alt self[item] = value return",
"len(self) == 0)) self._pipe.execute() if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) retval = True else: self._pipe.reset()",
"= self[key] except KeyError: ret = f(*args, **kwargs) self[key] = ret return ret",
"of this subregion. :param timeout: The timeout in seconds for this region. Defaults",
"not len(self))) if self._pipe: self._pipe.hset(self.name, key, raw_value) else: self._region_cache.conn.hset(self.name, key, raw_value) if should_reset_timeout:",
"not self._pipe: self._pipe = self._region_cache.conn.pipeline() return self def __exit__(self, exc_type, exc_val, exc_tb): if",
"cache. \"\"\" try: return self[item] except KeyError: value = alt() if callable(alt) else",
"else alt self[item] = value return value except redis.TimeoutError: _logger.warning(\"Cannot reach cache. Using",
"(self._timeout and (self._update_resets_timeout or len(self) == 0)) self._pipe.execute() if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) retval",
"Will be stored in the cache on computation. :return: The value in the",
"parent region's setting :return: Region \"\"\" return self._region_cache.region( name=self.name + '.' + name,",
"timeout=None, update_resets_timeout=None, serializer=None): \"\"\" Get a sub-region from this region. When this region",
"alt() if callable(alt) else alt self[item] = value return value except redis.TimeoutError: _logger.warning(\"Cannot",
"timeout: self._timeout = timeout self._region_cache.conn.expire(name, timeout) if '.' in name: parent = name.rsplit('.',",
"will return the cached result. \"\"\" @wraps(f) def wrapper(*args, **kwargs): key = self._serializer.dumps((args,",
"self._update_resets_timeout), serializer=serializer or self._serializer ) def invalidate(self, pipeline=None): \"\"\" Delete this region's cache",
"wrapper(*args, **kwargs): key = self._serializer.dumps((args, kwargs)) try: ret = self[key] except KeyError: ret",
"The name of the subregion. If dots are included, then the dotted regions",
"try: raw_value = self._region_cache.read_conn.hget(self.name, item) except redis.TimeoutError: raw_value = None timed_out = True",
":param signals: blinker signal objects or string names for named signals. :return: None",
"pipeline = self._region_cache.conn.pipeline() is_root_call = True else: is_root_call = False for child in",
"= True else: is_root_call = False for child in self.children(): child.invalidate(pipeline) pipeline.delete(self.name) if",
"parent.add_child(self) def __repr__(self): return \"Region({})\".format(self.name) def region(self, name=None, timeout=None, update_resets_timeout=None, serializer=None): \"\"\" Get",
"return \"Region({})\".format(self.name) def region(self, name=None, timeout=None, update_resets_timeout=None, serializer=None): \"\"\" Get a sub-region from",
"self._pipe and self._timeout and (self._update_resets_timeout or not len(self))) if self._pipe: self._pipe.hset(self.name, key, raw_value)",
"seconds for this region. Defaults to the parent region's timeout :param update_resets_timeout: Whether",
"disable=W0212 if self._region_cache._reconnect_on_timeout: self._region_cache.invalidate_connections() raise KeyError(item) if raw_value is not None: return self._serializer.loads(raw_value)",
"= None timed_out = True if timed_out: # pylint: disable=W0212 if self._region_cache._reconnect_on_timeout: self._region_cache.invalidate_connections()",
"def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is None: # if we started",
"and dumps(). Defaults to the parent region's setting :return: Region \"\"\" return self._region_cache.region(",
"from functools import wraps import blinker import logging from logging import getLogger _logger",
"True else: self._pipe.reset() retval = False self._pipe = None return retval def __eq__(self,",
"from collections.abc import MutableMapping from datetime import datetime from functools import wraps import",
"if self._pipe: self._pipe.hset(self.name, key, raw_value) else: self._region_cache.conn.hset(self.name, key, raw_value) if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout)",
"== 0)) self._pipe.execute() if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) retval = True else: self._pipe.reset() retval",
"update_resets_timeout=None, serializer=None): \"\"\" Get a sub-region from this region. When this region is",
"\"\"\" Bind this cache region to blinker signals. When any of the signals",
"\"\"\" try: return self[item] except KeyError: value = alt() if callable(alt) else alt",
"None: pipeline = self._region_cache.conn.pipeline() is_root_call = True else: is_root_call = False for child",
"The value to return. Will be stored in the cache on computation. :return:",
"the method. Subsequent calls to the method with the same arguments will return",
"value return value except redis.TimeoutError: _logger.warning(\"Cannot reach cache. Using alternative\") if callable(alt): return",
"name=None, timeout=None, update_resets_timeout=None, serializer=None): \"\"\" Get a sub-region from this region. When this",
"compute it from `alt`. Alt can be a callable or a scalar. :param",
"serializer self._pipe = None self._children_key = self.name + \"::child_caches\" self._update_resets_timeout = update_resets_timeout if",
"k in self._region_cache.read_conn.hkeys(self.name): if not k.decode('utf-8').startswith('__'): yield k def __len__(self): return self._region_cache.conn.hlen(self.name) def",
"of cache structures. \"\"\" def __init__(self, region_cache, name, timeout=None, update_resets_timeout=True, serializer=pickle): self._region_cache =",
"self._region_cache.is_disconnected(): should_reset_timeout = (not self._pipe and self._timeout and (self._update_resets_timeout or (len(self) == 1",
"a serialized form of the input args as a key and caches the",
"\"Region({})\".format(self.name) def region(self, name=None, timeout=None, update_resets_timeout=None, serializer=None): \"\"\" Get a sub-region from this",
"raw_value = self._region_cache.read_conn.hget(self.name, item) else: try: raw_value = self._region_cache.read_conn.hget(self.name, item) except redis.TimeoutError: raw_value",
"_logger = getLogger('region_cache') class Region(MutableMapping): \"\"\" A bound cache region. Do not instantiate",
"from `alt`. Alt can be a callable or a scalar. :param item: The",
"should_reset_timeout = (not self._pipe and self._timeout and (self._update_resets_timeout or (len(self) == 1 and",
"instead of a key error raw_value = self._region_cache.read_conn.hget(self.name, item) else: try: raw_value =",
"of calling the method. Subsequent calls to the method with the same arguments",
"this region. Defaults to the parent region's timeout :param update_resets_timeout: Whether updating the",
"self.name + \"::child_caches\" self._update_resets_timeout = update_resets_timeout if timeout: self._timeout = timeout self._region_cache.conn.expire(name, timeout)",
"self))) if self._pipe: self._pipe.hdel(self.name, key) else: self._region_cache.conn.hdel(self.name, key) if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) else:",
"function. This will make for proper nesting of cache structures. \"\"\" def __init__(self,",
"region to blinker signals. When any of the signals have been triggered, invalidate",
"weak=False) def cached(self, f): \"\"\" Decorator that uses a serialized form of the",
"should_reset_timeout = (not self._pipe and self._timeout and (self._update_resets_timeout or not len(self))) if self._pipe:",
"= update_resets_timeout if timeout: self._timeout = timeout self._region_cache.conn.expire(name, timeout) if '.' in name:",
"return self[item] except KeyError: value = alt() if callable(alt) else alt self[item] =",
"False self._pipe = None return retval def __eq__(self, other): return other.name == self.name",
"to the parent region's timeout :param update_resets_timeout: Whether updating the region resets the",
"dumps(). Defaults to the parent region's setting :return: Region \"\"\" return self._region_cache.region( name=self.name",
"This will make for proper nesting of cache structures. \"\"\" def __init__(self, region_cache,",
"else: self._region_cache.conn.hdel(self.name, key) if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) else: raise redis.TimeoutError(f\"Cannot delete item {key}",
"key in self))) if self._pipe: self._pipe.hdel(self.name, key) else: self._region_cache.conn.hdel(self.name, key) if should_reset_timeout: self._region_cache.conn.expire(self.name,",
"from datetime import datetime from functools import wraps import blinker import logging from",
"parent = self._region_cache.region(parent) parent.add_child(self) def __repr__(self): return \"Region({})\".format(self.name) def region(self, name=None, timeout=None, update_resets_timeout=None,",
"value except redis.TimeoutError: _logger.warning(\"Cannot reach cache. Using alternative\") if callable(alt): return alt() else:",
"cache. Using alternative\") if callable(alt): return alt() else: return alt def __getitem__(self, item):",
"\"\"\" Delete this region's cache data and all its subregions. :param pipeline: Used",
":param alt: Callable or scalar. The value to return. Will be stored in",
"this region's cache data and all its subregions. :param pipeline: Used internally. :return:",
"should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) retval = True else: self._pipe.reset() retval = False self._pipe =",
"subregion. If dots are included, then the dotted regions are treated as subregions",
"computation. :return: The value in the cache. \"\"\" try: return self[item] except KeyError:",
"import wraps import blinker import logging from logging import getLogger _logger = getLogger('region_cache')",
"if not k.decode('utf-8').startswith('__'): yield k def __len__(self): return self._region_cache.conn.hlen(self.name) def __enter__(self): if not",
"import pickle import redis from collections.abc import MutableMapping from datetime import datetime from",
"self._region_cache.conn.expire(self.name, self._timeout) else: raise redis.TimeoutError(f\"Cannot delete item {key} from {self.name} because we are",
"return self._serializer.loads(raw_value) else: raise KeyError(item) def __setitem__(self, key, value): raw_value = self._serializer.dumps(value) if",
"Whether updating the region resets the timeout. Defaults to the parent region's setting.",
"self._serializer = serializer self._pipe = None self._children_key = self.name + \"::child_caches\" self._update_resets_timeout =",
"in self.children(): child.invalidate(pipeline) pipeline.delete(self.name) if is_root_call: pipeline.execute() def invalidate_on(self, *signals): \"\"\" Bind this",
"should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) def __delitem__(self, key): if not self._region_cache.is_disconnected(): should_reset_timeout = (not self._pipe",
"= self._serializer.dumps(value) if not self._region_cache.is_disconnected(): should_reset_timeout = (not self._pipe and self._timeout and (self._update_resets_timeout",
"self._region_cache.region( name=self.name + '.' + name, timeout=timeout or self._timeout, update_resets_timeout=( update_resets_timeout if self._update_resets_timeout",
"region. Defaults to the parent region's timeout :param update_resets_timeout: Whether updating the region",
"in the cache, reset it should_reset_timeout = (self._timeout and (self._update_resets_timeout or len(self) ==",
"timeout. Defaults to the parent region's setting. :param serializer: The serializer to use.",
"callable(alt): return alt() else: return alt def __getitem__(self, item): timed_out = False if",
"all its subregions. :param pipeline: Used internally. :return: None \"\"\" _logger.debug(\"Invalidating region %s\",",
"None: return self._serializer.loads(raw_value) else: raise KeyError(item) def __setitem__(self, key, value): raw_value = self._serializer.dumps(value)",
"self._region_cache.conn.hset(self.name, key, raw_value) if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) def __delitem__(self, key): if not self._region_cache.is_disconnected():",
"not k.decode('utf-8').startswith('__'): yield k def __len__(self): return self._region_cache.conn.hlen(self.name) def __enter__(self): if not self._pipe:",
"proper nesting of cache structures. \"\"\" def __init__(self, region_cache, name, timeout=None, update_resets_timeout=True, serializer=pickle):",
"region is invalidated, the subregion will be too. :param name: The name of",
"not instantiate these directly. Instead use the RegionCache.region() function. This will make for",
"calls to the method with the same arguments will return the cached result.",
"@wraps(f) def wrapper(*args, **kwargs): key = self._serializer.dumps((args, kwargs)) try: ret = self[key] except",
"collections.abc import MutableMapping from datetime import datetime from functools import wraps import blinker",
"sub-region from this region. When this region is invalidated, the subregion will be",
"in the cache. \"\"\" try: return self[item] except KeyError: value = alt() if",
"signal objects or string names for named signals. :return: None \"\"\" def handler(sender,",
"redis.TimeoutError: _logger.warning(\"Cannot reach cache. Using alternative\") if callable(alt): return alt() else: return alt",
"== 1 and key in self))) if self._pipe: self._pipe.hdel(self.name, key) else: self._region_cache.conn.hdel(self.name, key)",
"exc_val, exc_tb): if exc_type is None: # if we started with nothing in",
"handler(sender, **kwargs): try: self.invalidate() except redis.TimeoutError: logging.getLogger('region_cache').exception( \"Invalidation of {self.name} in signal handler",
"name: parent = name.rsplit('.', 1)[0] parent = self._region_cache.region(parent) parent.add_child(self) def __repr__(self): return \"Region({})\".format(self.name)",
"KeyError(item) def __setitem__(self, key, value): raw_value = self._serializer.dumps(value) if not self._region_cache.is_disconnected(): should_reset_timeout =",
"self._pipe: self._pipe.hdel(self.name, key) else: self._region_cache.conn.hdel(self.name, key) if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) else: raise redis.TimeoutError(f\"Cannot",
"KeyError: ret = f(*args, **kwargs) self[key] = ret return ret return wrapper def",
"__len__(self): return self._region_cache.conn.hlen(self.name) def __enter__(self): if not self._pipe: self._pipe = self._region_cache.conn.pipeline() return self",
"method with the same arguments will return the cached result. \"\"\" @wraps(f) def",
"reset it should_reset_timeout = (self._timeout and (self._update_resets_timeout or len(self) == 0)) self._pipe.execute() if",
"self.children(): child.invalidate(pipeline) pipeline.delete(self.name) if is_root_call: pipeline.execute() def invalidate_on(self, *signals): \"\"\" Bind this cache",
"\"\"\" def __init__(self, region_cache, name, timeout=None, update_resets_timeout=True, serializer=pickle): self._region_cache = region_cache self.name =",
"def region(self, name=None, timeout=None, update_resets_timeout=None, serializer=None): \"\"\" Get a sub-region from this region.",
"def cached(self, f): \"\"\" Decorator that uses a serialized form of the input",
"self._serializer.dumps(value) if not self._region_cache.is_disconnected(): should_reset_timeout = (not self._pipe and self._timeout and (self._update_resets_timeout or",
"signals have been triggered, invalidate the cache. :param signals: blinker signal objects or",
"return retval def __eq__(self, other): return other.name == self.name def children(self): return (self._region_cache.region(name.decode('utf-8'))",
"= self._region_cache.region(parent) parent.add_child(self) def __repr__(self): return \"Region({})\".format(self.name) def region(self, name=None, timeout=None, update_resets_timeout=None, serializer=None):",
"the signals have been triggered, invalidate the cache. :param signals: blinker signal objects",
"region's setting :return: Region \"\"\" return self._region_cache.region( name=self.name + '.' + name, timeout=timeout",
") def invalidate(self, pipeline=None): \"\"\" Delete this region's cache data and all its",
"KeyError: value = alt() if callable(alt) else alt self[item] = value return value",
"a scalar. :param item: The key to get :param alt: Callable or scalar.",
"loads and dumps(). Defaults to the parent region's setting :return: Region \"\"\" return",
"from {self.name} because we are disconnected.\") def __iter__(self): for k in self._region_cache.read_conn.hkeys(self.name): if",
"raise KeyError(item) # pylint: disable=W0212 if self._region_cache._raise_on_timeout: # raise the redis timeout error",
"# pylint: disable=W0212 if self._region_cache._raise_on_timeout: # raise the redis timeout error instead of",
"in seconds for this region. Defaults to the parent region's timeout :param update_resets_timeout:",
"out. Flush it manually\".format(self=self)) for sig in signals: if isinstance(sig, str): sig =",
"timed_out = True if timed_out: # pylint: disable=W0212 if self._region_cache._reconnect_on_timeout: self._region_cache.invalidate_connections() raise KeyError(item)",
"alt self[item] = value return value except redis.TimeoutError: _logger.warning(\"Cannot reach cache. Using alternative\")",
"None: # if we started with nothing in the cache, reset it should_reset_timeout",
"serializer to use. Must define loads and dumps(). Defaults to the parent region's",
"{key} from {self.name} because we are disconnected.\") def __iter__(self): for k in self._region_cache.read_conn.hkeys(self.name):",
"key = self._serializer.dumps((args, kwargs)) try: ret = self[key] except KeyError: ret = f(*args,",
"item) else: try: raw_value = self._region_cache.read_conn.hget(self.name, item) except redis.TimeoutError: raw_value = None timed_out",
"= self._region_cache.conn.pipeline() is_root_call = True else: is_root_call = False for child in self.children():",
"the same arguments will return the cached result. \"\"\" @wraps(f) def wrapper(*args, **kwargs):",
"else: is_root_call = False for child in self.children(): child.invalidate(pipeline) pipeline.delete(self.name) if is_root_call: pipeline.execute()",
"None timed_out = True if timed_out: # pylint: disable=W0212 if self._region_cache._reconnect_on_timeout: self._region_cache.invalidate_connections() raise",
"with nothing in the cache, reset it should_reset_timeout = (self._timeout and (self._update_resets_timeout or",
"+ \"::child_caches\" self._update_resets_timeout = update_resets_timeout if timeout: self._timeout = timeout self._region_cache.conn.expire(name, timeout) if",
"= True else: self._pipe.reset() retval = False self._pipe = None return retval def",
"Get the value, or if the value is not in the cache, compute",
"'.' in name: parent = name.rsplit('.', 1)[0] parent = self._region_cache.region(parent) parent.add_child(self) def __repr__(self):",
"serialized form of the input args as a key and caches the result",
"= None self._children_key = self.name + \"::child_caches\" self._update_resets_timeout = update_resets_timeout if timeout: self._timeout",
"regions are treated as subregions of this subregion. :param timeout: The timeout in",
"except redis.TimeoutError: raw_value = None timed_out = True if timed_out: # pylint: disable=W0212",
"self._pipe = None return retval def __eq__(self, other): return other.name == self.name def",
"invalidate(self, pipeline=None): \"\"\" Delete this region's cache data and all its subregions. :param",
"signals. When any of the signals have been triggered, invalidate the cache. :param",
"__iter__(self): for k in self._region_cache.read_conn.hkeys(self.name): if not k.decode('utf-8').startswith('__'): yield k def __len__(self): return",
"for proper nesting of cache structures. \"\"\" def __init__(self, region_cache, name, timeout=None, update_resets_timeout=True,",
":param pipeline: Used internally. :return: None \"\"\" _logger.debug(\"Invalidating region %s\", self.name) if pipeline",
"to return. Will be stored in the cache on computation. :return: The value",
"f(*args, **kwargs) self[key] = ret return ret return wrapper def get_or_compute(self, item, alt):",
"`alt`. Alt can be a callable or a scalar. :param item: The key",
"retval def __eq__(self, other): return other.name == self.name def children(self): return (self._region_cache.region(name.decode('utf-8')) for",
"if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) else: raise redis.TimeoutError(f\"Cannot delete item {key} from {self.name} because",
"and (self._update_resets_timeout or (len(self) == 1 and key in self))) if self._pipe: self._pipe.hdel(self.name,",
"if pipeline is None: pipeline = self._region_cache.conn.pipeline() is_root_call = True else: is_root_call =",
"name of the subregion. If dots are included, then the dotted regions are",
"None \"\"\" _logger.debug(\"Invalidating region %s\", self.name) if pipeline is None: pipeline = self._region_cache.conn.pipeline()",
"because we are disconnected.\") def __iter__(self): for k in self._region_cache.read_conn.hkeys(self.name): if not k.decode('utf-8').startswith('__'):",
"= self._serializer.dumps((args, kwargs)) try: ret = self[key] except KeyError: ret = f(*args, **kwargs)",
"cache region to blinker signals. When any of the signals have been triggered,",
"error raw_value = self._region_cache.read_conn.hget(self.name, item) else: try: raw_value = self._region_cache.read_conn.hget(self.name, item) except redis.TimeoutError:",
"self._pipe: self._pipe.hset(self.name, key, raw_value) else: self._region_cache.conn.hset(self.name, key, raw_value) if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) def",
"self._pipe: self._pipe = self._region_cache.conn.pipeline() return self def __exit__(self, exc_type, exc_val, exc_tb): if exc_type",
"= self._region_cache.conn.pipeline() return self def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is None:",
"subregion will be too. :param name: The name of the subregion. If dots",
"nesting of cache structures. \"\"\" def __init__(self, region_cache, name, timeout=None, update_resets_timeout=True, serializer=pickle): self._region_cache",
"the value is not in the cache, compute it from `alt`. Alt can",
"and caches the result of calling the method. Subsequent calls to the method",
"the region resets the timeout. Defaults to the parent region's setting. :param serializer:",
"the parent region's setting. :param serializer: The serializer to use. Must define loads",
"sig = blinker.signal(sig) sig.connect(handler, weak=False) def cached(self, f): \"\"\" Decorator that uses a",
"alt): \"\"\" Get the value, or if the value is not in the",
"self[item] = value return value except redis.TimeoutError: _logger.warning(\"Cannot reach cache. Using alternative\") if",
"timed_out: # pylint: disable=W0212 if self._region_cache._reconnect_on_timeout: self._region_cache.invalidate_connections() raise KeyError(item) if raw_value is not",
"= (self._timeout and (self._update_resets_timeout or len(self) == 0)) self._pipe.execute() if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout)",
"use the RegionCache.region() function. This will make for proper nesting of cache structures.",
"\"\"\" A bound cache region. Do not instantiate these directly. Instead use the",
"with the same arguments will return the cached result. \"\"\" @wraps(f) def wrapper(*args,",
"def handler(sender, **kwargs): try: self.invalidate() except redis.TimeoutError: logging.getLogger('region_cache').exception( \"Invalidation of {self.name} in signal",
"method. Subsequent calls to the method with the same arguments will return the",
"= self._region_cache.read_conn.hget(self.name, item) except redis.TimeoutError: raw_value = None timed_out = True if timed_out:",
"else: raise redis.TimeoutError(f\"Cannot delete item {key} from {self.name} because we are disconnected.\") def",
"self._pipe and self._timeout and (self._update_resets_timeout or (len(self) == 1 and key in self)))",
"cached(self, f): \"\"\" Decorator that uses a serialized form of the input args",
"self.invalidate() except redis.TimeoutError: logging.getLogger('region_cache').exception( \"Invalidation of {self.name} in signal handler timed out. Flush",
"timeout in seconds for this region. Defaults to the parent region's timeout :param",
"The timeout in seconds for this region. Defaults to the parent region's timeout",
"def __repr__(self): return \"Region({})\".format(self.name) def region(self, name=None, timeout=None, update_resets_timeout=None, serializer=None): \"\"\" Get a",
"the input args as a key and caches the result of calling the",
"be stored in the cache on computation. :return: The value in the cache.",
"the subregion will be too. :param name: The name of the subregion. If",
"error instead of a key error raw_value = self._region_cache.read_conn.hget(self.name, item) else: try: raw_value",
"try: return self[item] except KeyError: value = alt() if callable(alt) else alt self[item]",
"the redis timeout error instead of a key error raw_value = self._region_cache.read_conn.hget(self.name, item)",
"is_root_call: pipeline.execute() def invalidate_on(self, *signals): \"\"\" Bind this cache region to blinker signals.",
"0)) self._pipe.execute() if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) retval = True else: self._pipe.reset() retval =",
"is not in the cache, compute it from `alt`. Alt can be a",
"serializer: The serializer to use. Must define loads and dumps(). Defaults to the",
"RegionCache.region() function. This will make for proper nesting of cache structures. \"\"\" def",
"__eq__(self, other): return other.name == self.name def children(self): return (self._region_cache.region(name.decode('utf-8')) for name in",
"for child in self.children(): child.invalidate(pipeline) pipeline.delete(self.name) if is_root_call: pipeline.execute() def invalidate_on(self, *signals): \"\"\"",
"import redis from collections.abc import MutableMapping from datetime import datetime from functools import",
"caches the result of calling the method. Subsequent calls to the method with",
"Defaults to the parent region's timeout :param update_resets_timeout: Whether updating the region resets",
":return: The value in the cache. \"\"\" try: return self[item] except KeyError: value",
"raw_value is not None: return self._serializer.loads(raw_value) else: raise KeyError(item) def __setitem__(self, key, value):",
"not None: return self._serializer.loads(raw_value) else: raise KeyError(item) def __setitem__(self, key, value): raw_value =",
"to use. Must define loads and dumps(). Defaults to the parent region's setting",
"class Region(MutableMapping): \"\"\" A bound cache region. Do not instantiate these directly. Instead",
"item: The key to get :param alt: Callable or scalar. The value to",
"value in the cache. \"\"\" try: return self[item] except KeyError: value = alt()",
"key, raw_value) else: self._region_cache.conn.hset(self.name, key, raw_value) if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) def __delitem__(self, key):",
"'__cache_region_created_at__', datetime.utcnow().isoformat()) self._timeout = None self._region_cache = region_cache self._serializer = serializer self._pipe =",
"invalidated, the subregion will be too. :param name: The name of the subregion.",
"parent region's timeout :param update_resets_timeout: Whether updating the region resets the timeout. Defaults",
"if the value is not in the cache, compute it from `alt`. Alt",
"# raise the redis timeout error instead of a key error raw_value =",
"of the subregion. If dots are included, then the dotted regions are treated",
"Alt can be a callable or a scalar. :param item: The key to",
"region_cache self.name = name self._region_cache.conn.hset(name, '__cache_region_created_at__', datetime.utcnow().isoformat()) self._timeout = None self._region_cache = region_cache",
"kwargs)) try: ret = self[key] except KeyError: ret = f(*args, **kwargs) self[key] =",
"in signal handler timed out. Flush it manually\".format(self=self)) for sig in signals: if",
"item): timed_out = False if self._region_cache.is_disconnected(): raise KeyError(item) # pylint: disable=W0212 if self._region_cache._raise_on_timeout:",
"# pylint: disable=W0212 if self._region_cache._reconnect_on_timeout: self._region_cache.invalidate_connections() raise KeyError(item) if raw_value is not None:",
"return (self._region_cache.region(name.decode('utf-8')) for name in self._region_cache.read_conn.smembers(self._children_key)) def add_child(self, child): self._region_cache.conn.sadd(self._children_key, child.name) def reset_timeout(self):",
"cache, reset it should_reset_timeout = (self._timeout and (self._update_resets_timeout or len(self) == 0)) self._pipe.execute()",
"= (not self._pipe and self._timeout and (self._update_resets_timeout or not len(self))) if self._pipe: self._pipe.hset(self.name,",
"# if we started with nothing in the cache, reset it should_reset_timeout =",
"Must define loads and dumps(). Defaults to the parent region's setting :return: Region",
"str): sig = blinker.signal(sig) sig.connect(handler, weak=False) def cached(self, f): \"\"\" Decorator that uses",
"cache. :param signals: blinker signal objects or string names for named signals. :return:",
"it manually\".format(self=self)) for sig in signals: if isinstance(sig, str): sig = blinker.signal(sig) sig.connect(handler,",
"the RegionCache.region() function. This will make for proper nesting of cache structures. \"\"\"",
"= name.rsplit('.', 1)[0] parent = self._region_cache.region(parent) parent.add_child(self) def __repr__(self): return \"Region({})\".format(self.name) def region(self,",
"of the input args as a key and caches the result of calling",
"and (self._update_resets_timeout or not len(self))) if self._pipe: self._pipe.hset(self.name, key, raw_value) else: self._region_cache.conn.hset(self.name, key,",
"if not self._pipe: self._pipe = self._region_cache.conn.pipeline() return self def __exit__(self, exc_type, exc_val, exc_tb):",
"if exc_type is None: # if we started with nothing in the cache,",
"if self._region_cache.is_disconnected(): raise KeyError(item) # pylint: disable=W0212 if self._region_cache._raise_on_timeout: # raise the redis",
"(self._update_resets_timeout or (len(self) == 1 and key in self))) if self._pipe: self._pipe.hdel(self.name, key)",
"= None return retval def __eq__(self, other): return other.name == self.name def children(self):",
"self._region_cache.conn.expire(self.name, self._timeout) retval = True else: self._pipe.reset() retval = False self._pipe = None",
"we are disconnected.\") def __iter__(self): for k in self._region_cache.read_conn.hkeys(self.name): if not k.decode('utf-8').startswith('__'): yield",
"from logging import getLogger _logger = getLogger('region_cache') class Region(MutableMapping): \"\"\" A bound cache",
"blinker import logging from logging import getLogger _logger = getLogger('region_cache') class Region(MutableMapping): \"\"\"",
"raw_value) if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) def __delitem__(self, key): if not self._region_cache.is_disconnected(): should_reset_timeout =",
"should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) else: raise redis.TimeoutError(f\"Cannot delete item {key} from {self.name} because we",
"the cache, compute it from `alt`. Alt can be a callable or a",
"self._update_resets_timeout = update_resets_timeout if timeout: self._timeout = timeout self._region_cache.conn.expire(name, timeout) if '.' in",
"redis.TimeoutError(f\"Cannot delete item {key} from {self.name} because we are disconnected.\") def __iter__(self): for",
"uses a serialized form of the input args as a key and caches",
"too. :param name: The name of the subregion. If dots are included, then",
"self._region_cache = region_cache self.name = name self._region_cache.conn.hset(name, '__cache_region_created_at__', datetime.utcnow().isoformat()) self._timeout = None self._region_cache",
"%s\", self.name) if pipeline is None: pipeline = self._region_cache.conn.pipeline() is_root_call = True else:",
"= alt() if callable(alt) else alt self[item] = value return value except redis.TimeoutError:",
"is invalidated, the subregion will be too. :param name: The name of the",
"other): return other.name == self.name def children(self): return (self._region_cache.region(name.decode('utf-8')) for name in self._region_cache.read_conn.smembers(self._children_key))",
"nothing in the cache, reset it should_reset_timeout = (self._timeout and (self._update_resets_timeout or len(self)",
"to the parent region's setting. :param serializer: The serializer to use. Must define",
"= False if self._region_cache.is_disconnected(): raise KeyError(item) # pylint: disable=W0212 if self._region_cache._raise_on_timeout: # raise",
"not None else self._update_resets_timeout), serializer=serializer or self._serializer ) def invalidate(self, pipeline=None): \"\"\" Delete",
"**kwargs) self[key] = ret return ret return wrapper def get_or_compute(self, item, alt): \"\"\"",
"cache on computation. :return: The value in the cache. \"\"\" try: return self[item]",
"getLogger _logger = getLogger('region_cache') class Region(MutableMapping): \"\"\" A bound cache region. Do not",
"logging from logging import getLogger _logger = getLogger('region_cache') class Region(MutableMapping): \"\"\" A bound",
"that uses a serialized form of the input args as a key and",
"of {self.name} in signal handler timed out. Flush it manually\".format(self=self)) for sig in",
"self._region_cache.conn.hset(name, '__cache_region_created_at__', datetime.utcnow().isoformat()) self._timeout = None self._region_cache = region_cache self._serializer = serializer self._pipe",
"def invalidate(self, pipeline=None): \"\"\" Delete this region's cache data and all its subregions.",
"structures. \"\"\" def __init__(self, region_cache, name, timeout=None, update_resets_timeout=True, serializer=pickle): self._region_cache = region_cache self.name",
"callable(alt) else alt self[item] = value return value except redis.TimeoutError: _logger.warning(\"Cannot reach cache.",
"is_root_call = False for child in self.children(): child.invalidate(pipeline) pipeline.delete(self.name) if is_root_call: pipeline.execute() def",
"item) except redis.TimeoutError: raw_value = None timed_out = True if timed_out: # pylint:",
"parent region's setting. :param serializer: The serializer to use. Must define loads and",
"invalidate the cache. :param signals: blinker signal objects or string names for named",
"key, raw_value) if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) def __delitem__(self, key): if not self._region_cache.is_disconnected(): should_reset_timeout",
"else: try: raw_value = self._region_cache.read_conn.hget(self.name, item) except redis.TimeoutError: raw_value = None timed_out =",
"key to get :param alt: Callable or scalar. The value to return. Will",
"self._timeout) retval = True else: self._pipe.reset() retval = False self._pipe = None return",
"region %s\", self.name) if pipeline is None: pipeline = self._region_cache.conn.pipeline() is_root_call = True",
"if self._pipe: self._pipe.hdel(self.name, key) else: self._region_cache.conn.hdel(self.name, key) if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) else: raise",
"Region \"\"\" return self._region_cache.region( name=self.name + '.' + name, timeout=timeout or self._timeout, update_resets_timeout=(",
"None \"\"\" def handler(sender, **kwargs): try: self.invalidate() except redis.TimeoutError: logging.getLogger('region_cache').exception( \"Invalidation of {self.name}",
"signals: if isinstance(sig, str): sig = blinker.signal(sig) sig.connect(handler, weak=False) def cached(self, f): \"\"\"",
"def get_or_compute(self, item, alt): \"\"\" Get the value, or if the value is",
"retval = False self._pipe = None return retval def __eq__(self, other): return other.name",
"this subregion. :param timeout: The timeout in seconds for this region. Defaults to",
"import getLogger _logger = getLogger('region_cache') class Region(MutableMapping): \"\"\" A bound cache region. Do",
"def __getitem__(self, item): timed_out = False if self._region_cache.is_disconnected(): raise KeyError(item) # pylint: disable=W0212",
"key) else: self._region_cache.conn.hdel(self.name, key) if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) else: raise redis.TimeoutError(f\"Cannot delete item",
"blinker signals. When any of the signals have been triggered, invalidate the cache.",
"retval = True else: self._pipe.reset() retval = False self._pipe = None return retval",
"parent = name.rsplit('.', 1)[0] parent = self._region_cache.region(parent) parent.add_child(self) def __repr__(self): return \"Region({})\".format(self.name) def",
"are disconnected.\") def __iter__(self): for k in self._region_cache.read_conn.hkeys(self.name): if not k.decode('utf-8').startswith('__'): yield k",
"= (not self._pipe and self._timeout and (self._update_resets_timeout or (len(self) == 1 and key",
"If dots are included, then the dotted regions are treated as subregions of",
"or (len(self) == 1 and key in self))) if self._pipe: self._pipe.hdel(self.name, key) else:",
":param timeout: The timeout in seconds for this region. Defaults to the parent",
"signals: blinker signal objects or string names for named signals. :return: None \"\"\"",
"'.' + name, timeout=timeout or self._timeout, update_resets_timeout=( update_resets_timeout if self._update_resets_timeout is not None",
"is not None else self._update_resets_timeout), serializer=serializer or self._serializer ) def invalidate(self, pipeline=None): \"\"\"",
"for this region. Defaults to the parent region's timeout :param update_resets_timeout: Whether updating",
"stored in the cache on computation. :return: The value in the cache. \"\"\"",
"= serializer self._pipe = None self._children_key = self.name + \"::child_caches\" self._update_resets_timeout = update_resets_timeout",
"its subregions. :param pipeline: Used internally. :return: None \"\"\" _logger.debug(\"Invalidating region %s\", self.name)",
"Used internally. :return: None \"\"\" _logger.debug(\"Invalidating region %s\", self.name) if pipeline is None:",
"will make for proper nesting of cache structures. \"\"\" def __init__(self, region_cache, name,",
"self._children_key = self.name + \"::child_caches\" self._update_resets_timeout = update_resets_timeout if timeout: self._timeout = timeout",
"serializer=None): \"\"\" Get a sub-region from this region. When this region is invalidated,",
"Decorator that uses a serialized form of the input args as a key",
"except redis.TimeoutError: _logger.warning(\"Cannot reach cache. Using alternative\") if callable(alt): return alt() else: return",
"will be too. :param name: The name of the subregion. If dots are",
"self.name def children(self): return (self._region_cache.region(name.decode('utf-8')) for name in self._region_cache.read_conn.smembers(self._children_key)) def add_child(self, child): self._region_cache.conn.sadd(self._children_key,",
"in signals: if isinstance(sig, str): sig = blinker.signal(sig) sig.connect(handler, weak=False) def cached(self, f):",
"else: self._region_cache.conn.hset(self.name, key, raw_value) if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) def __delitem__(self, key): if not",
"in the cache on computation. :return: The value in the cache. \"\"\" try:",
"= self.name + \"::child_caches\" self._update_resets_timeout = update_resets_timeout if timeout: self._timeout = timeout self._region_cache.conn.expire(name,",
"if self._update_resets_timeout is not None else self._update_resets_timeout), serializer=serializer or self._serializer ) def invalidate(self,",
"cache structures. \"\"\" def __init__(self, region_cache, name, timeout=None, update_resets_timeout=True, serializer=pickle): self._region_cache = region_cache",
"__exit__(self, exc_type, exc_val, exc_tb): if exc_type is None: # if we started with",
"self._timeout and (self._update_resets_timeout or not len(self))) if self._pipe: self._pipe.hset(self.name, key, raw_value) else: self._region_cache.conn.hset(self.name,",
"self._serializer.dumps((args, kwargs)) try: ret = self[key] except KeyError: ret = f(*args, **kwargs) self[key]",
"a key error raw_value = self._region_cache.read_conn.hget(self.name, item) else: try: raw_value = self._region_cache.read_conn.hget(self.name, item)",
"serializer=pickle): self._region_cache = region_cache self.name = name self._region_cache.conn.hset(name, '__cache_region_created_at__', datetime.utcnow().isoformat()) self._timeout = None",
"if not self._region_cache.is_disconnected(): should_reset_timeout = (not self._pipe and self._timeout and (self._update_resets_timeout or (len(self)",
"key, value): raw_value = self._serializer.dumps(value) if not self._region_cache.is_disconnected(): should_reset_timeout = (not self._pipe and",
"raw_value = None timed_out = True if timed_out: # pylint: disable=W0212 if self._region_cache._reconnect_on_timeout:",
"self._region_cache._reconnect_on_timeout: self._region_cache.invalidate_connections() raise KeyError(item) if raw_value is not None: return self._serializer.loads(raw_value) else: raise",
"redis timeout error instead of a key error raw_value = self._region_cache.read_conn.hget(self.name, item) else:",
"timeout self._region_cache.conn.expire(name, timeout) if '.' in name: parent = name.rsplit('.', 1)[0] parent =",
"to get :param alt: Callable or scalar. The value to return. Will be",
"Instead use the RegionCache.region() function. This will make for proper nesting of cache",
"redis.TimeoutError: raw_value = None timed_out = True if timed_out: # pylint: disable=W0212 if",
":param serializer: The serializer to use. Must define loads and dumps(). Defaults to",
"if callable(alt): return alt() else: return alt def __getitem__(self, item): timed_out = False",
"exc_type, exc_val, exc_tb): if exc_type is None: # if we started with nothing",
"True if timed_out: # pylint: disable=W0212 if self._region_cache._reconnect_on_timeout: self._region_cache.invalidate_connections() raise KeyError(item) if raw_value",
"data and all its subregions. :param pipeline: Used internally. :return: None \"\"\" _logger.debug(\"Invalidating",
"self._region_cache.is_disconnected(): should_reset_timeout = (not self._pipe and self._timeout and (self._update_resets_timeout or not len(self))) if",
"self._timeout and (self._update_resets_timeout or (len(self) == 1 and key in self))) if self._pipe:",
"in self._region_cache.read_conn.hkeys(self.name): if not k.decode('utf-8').startswith('__'): yield k def __len__(self): return self._region_cache.conn.hlen(self.name) def __enter__(self):",
"name=self.name + '.' + name, timeout=timeout or self._timeout, update_resets_timeout=( update_resets_timeout if self._update_resets_timeout is",
"string names for named signals. :return: None \"\"\" def handler(sender, **kwargs): try: self.invalidate()",
"signals. :return: None \"\"\" def handler(sender, **kwargs): try: self.invalidate() except redis.TimeoutError: logging.getLogger('region_cache').exception( \"Invalidation",
"instantiate these directly. Instead use the RegionCache.region() function. This will make for proper",
"key) if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) else: raise redis.TimeoutError(f\"Cannot delete item {key} from {self.name}",
"item {key} from {self.name} because we are disconnected.\") def __iter__(self): for k in",
"return wrapper def get_or_compute(self, item, alt): \"\"\" Get the value, or if the",
"we started with nothing in the cache, reset it should_reset_timeout = (self._timeout and",
"(self._region_cache.region(name.decode('utf-8')) for name in self._region_cache.read_conn.smembers(self._children_key)) def add_child(self, child): self._region_cache.conn.sadd(self._children_key, child.name) def reset_timeout(self): self._region_cache.conn.expire(self.name,",
"region resets the timeout. Defaults to the parent region's setting. :param serializer: The",
"= ret return ret return wrapper def get_or_compute(self, item, alt): \"\"\" Get the",
"timed_out = False if self._region_cache.is_disconnected(): raise KeyError(item) # pylint: disable=W0212 if self._region_cache._raise_on_timeout: #",
"alt: Callable or scalar. The value to return. Will be stored in the",
"if timed_out: # pylint: disable=W0212 if self._region_cache._reconnect_on_timeout: self._region_cache.invalidate_connections() raise KeyError(item) if raw_value is",
"and (self._update_resets_timeout or len(self) == 0)) self._pipe.execute() if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) retval =",
"if we started with nothing in the cache, reset it should_reset_timeout = (self._timeout",
"self._timeout = None self._region_cache = region_cache self._serializer = serializer self._pipe = None self._children_key",
"raw_value) else: self._region_cache.conn.hset(self.name, key, raw_value) if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) def __delitem__(self, key): if",
"+ name, timeout=timeout or self._timeout, update_resets_timeout=( update_resets_timeout if self._update_resets_timeout is not None else",
"self._region_cache._raise_on_timeout: # raise the redis timeout error instead of a key error raw_value",
"a callable or a scalar. :param item: The key to get :param alt:",
"Region(MutableMapping): \"\"\" A bound cache region. Do not instantiate these directly. Instead use",
"pipeline: Used internally. :return: None \"\"\" _logger.debug(\"Invalidating region %s\", self.name) if pipeline is",
"functools import wraps import blinker import logging from logging import getLogger _logger =",
"self._pipe = self._region_cache.conn.pipeline() return self def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is",
"in self))) if self._pipe: self._pipe.hdel(self.name, key) else: self._region_cache.conn.hdel(self.name, key) if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout)",
"form of the input args as a key and caches the result of",
"region's timeout :param update_resets_timeout: Whether updating the region resets the timeout. Defaults to",
"None return retval def __eq__(self, other): return other.name == self.name def children(self): return",
"not self._region_cache.is_disconnected(): should_reset_timeout = (not self._pipe and self._timeout and (self._update_resets_timeout or (len(self) ==",
"self.name) if pipeline is None: pipeline = self._region_cache.conn.pipeline() is_root_call = True else: is_root_call",
":param update_resets_timeout: Whether updating the region resets the timeout. Defaults to the parent",
"= blinker.signal(sig) sig.connect(handler, weak=False) def cached(self, f): \"\"\" Decorator that uses a serialized",
"Delete this region's cache data and all its subregions. :param pipeline: Used internally.",
"cache, compute it from `alt`. Alt can be a callable or a scalar.",
"and key in self))) if self._pipe: self._pipe.hdel(self.name, key) else: self._region_cache.conn.hdel(self.name, key) if should_reset_timeout:",
"the cache. :param signals: blinker signal objects or string names for named signals.",
"self._serializer ) def invalidate(self, pipeline=None): \"\"\" Delete this region's cache data and all",
"blinker signal objects or string names for named signals. :return: None \"\"\" def",
"pipeline.delete(self.name) if is_root_call: pipeline.execute() def invalidate_on(self, *signals): \"\"\" Bind this cache region to",
"a key and caches the result of calling the method. Subsequent calls to",
"False for child in self.children(): child.invalidate(pipeline) pipeline.delete(self.name) if is_root_call: pipeline.execute() def invalidate_on(self, *signals):",
"self._region_cache.conn.expire(self.name, self._timeout) def __delitem__(self, key): if not self._region_cache.is_disconnected(): should_reset_timeout = (not self._pipe and",
"is None: pipeline = self._region_cache.conn.pipeline() is_root_call = True else: is_root_call = False for",
"the cached result. \"\"\" @wraps(f) def wrapper(*args, **kwargs): key = self._serializer.dumps((args, kwargs)) try:",
"self._region_cache = region_cache self._serializer = serializer self._pipe = None self._children_key = self.name +",
"it from `alt`. Alt can be a callable or a scalar. :param item:",
"KeyError(item) if raw_value is not None: return self._serializer.loads(raw_value) else: raise KeyError(item) def __setitem__(self,",
"result of calling the method. Subsequent calls to the method with the same",
"update_resets_timeout: Whether updating the region resets the timeout. Defaults to the parent region's",
"__repr__(self): return \"Region({})\".format(self.name) def region(self, name=None, timeout=None, update_resets_timeout=None, serializer=None): \"\"\" Get a sub-region",
"or self._timeout, update_resets_timeout=( update_resets_timeout if self._update_resets_timeout is not None else self._update_resets_timeout), serializer=serializer or",
"child in self.children(): child.invalidate(pipeline) pipeline.delete(self.name) if is_root_call: pipeline.execute() def invalidate_on(self, *signals): \"\"\" Bind",
"logging import getLogger _logger = getLogger('region_cache') class Region(MutableMapping): \"\"\" A bound cache region.",
"input args as a key and caches the result of calling the method.",
"the result of calling the method. Subsequent calls to the method with the",
"the parent region's setting :return: Region \"\"\" return self._region_cache.region( name=self.name + '.' +",
"def __iter__(self): for k in self._region_cache.read_conn.hkeys(self.name): if not k.decode('utf-8').startswith('__'): yield k def __len__(self):",
"1)[0] parent = self._region_cache.region(parent) parent.add_child(self) def __repr__(self): return \"Region({})\".format(self.name) def region(self, name=None, timeout=None,",
"if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) def __delitem__(self, key): if not self._region_cache.is_disconnected(): should_reset_timeout = (not",
"self._region_cache.conn.pipeline() return self def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is None: #",
"if self._region_cache._reconnect_on_timeout: self._region_cache.invalidate_connections() raise KeyError(item) if raw_value is not None: return self._serializer.loads(raw_value) else:",
"if callable(alt) else alt self[item] = value return value except redis.TimeoutError: _logger.warning(\"Cannot reach",
"any of the signals have been triggered, invalidate the cache. :param signals: blinker",
"named signals. :return: None \"\"\" def handler(sender, **kwargs): try: self.invalidate() except redis.TimeoutError: logging.getLogger('region_cache').exception(",
"a sub-region from this region. When this region is invalidated, the subregion will",
"key): if not self._region_cache.is_disconnected(): should_reset_timeout = (not self._pipe and self._timeout and (self._update_resets_timeout or",
"return self def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is None: # if",
"Defaults to the parent region's setting :return: Region \"\"\" return self._region_cache.region( name=self.name +",
"import MutableMapping from datetime import datetime from functools import wraps import blinker import",
"k.decode('utf-8').startswith('__'): yield k def __len__(self): return self._region_cache.conn.hlen(self.name) def __enter__(self): if not self._pipe: self._pipe",
"dotted regions are treated as subregions of this subregion. :param timeout: The timeout",
"= self._region_cache.read_conn.hget(self.name, item) else: try: raw_value = self._region_cache.read_conn.hget(self.name, item) except redis.TimeoutError: raw_value =",
"(not self._pipe and self._timeout and (self._update_resets_timeout or not len(self))) if self._pipe: self._pipe.hset(self.name, key,",
"Flush it manually\".format(self=self)) for sig in signals: if isinstance(sig, str): sig = blinker.signal(sig)",
"update_resets_timeout=True, serializer=pickle): self._region_cache = region_cache self.name = name self._region_cache.conn.hset(name, '__cache_region_created_at__', datetime.utcnow().isoformat()) self._timeout =",
"None self._children_key = self.name + \"::child_caches\" self._update_resets_timeout = update_resets_timeout if timeout: self._timeout =",
"ret return ret return wrapper def get_or_compute(self, item, alt): \"\"\" Get the value,",
"region_cache, name, timeout=None, update_resets_timeout=True, serializer=pickle): self._region_cache = region_cache self.name = name self._region_cache.conn.hset(name, '__cache_region_created_at__',",
"return value except redis.TimeoutError: _logger.warning(\"Cannot reach cache. Using alternative\") if callable(alt): return alt()",
"or a scalar. :param item: The key to get :param alt: Callable or",
"region's setting. :param serializer: The serializer to use. Must define loads and dumps().",
"key error raw_value = self._region_cache.read_conn.hget(self.name, item) else: try: raw_value = self._region_cache.read_conn.hget(self.name, item) except",
"Bind this cache region to blinker signals. When any of the signals have",
"region. Do not instantiate these directly. Instead use the RegionCache.region() function. This will",
"import logging from logging import getLogger _logger = getLogger('region_cache') class Region(MutableMapping): \"\"\" A",
"for name in self._region_cache.read_conn.smembers(self._children_key)) def add_child(self, child): self._region_cache.conn.sadd(self._children_key, child.name) def reset_timeout(self): self._region_cache.conn.expire(self.name, self._timeout)",
":return: Region \"\"\" return self._region_cache.region( name=self.name + '.' + name, timeout=timeout or self._timeout,",
"the method with the same arguments will return the cached result. \"\"\" @wraps(f)",
"subregion. :param timeout: The timeout in seconds for this region. Defaults to the",
"from this region. When this region is invalidated, the subregion will be too.",
"Using alternative\") if callable(alt): return alt() else: return alt def __getitem__(self, item): timed_out",
"if self._region_cache._raise_on_timeout: # raise the redis timeout error instead of a key error",
"is not None: return self._serializer.loads(raw_value) else: raise KeyError(item) def __setitem__(self, key, value): raw_value",
"datetime from functools import wraps import blinker import logging from logging import getLogger",
":param name: The name of the subregion. If dots are included, then the",
"self._pipe = None self._children_key = self.name + \"::child_caches\" self._update_resets_timeout = update_resets_timeout if timeout:",
"datetime.utcnow().isoformat()) self._timeout = None self._region_cache = region_cache self._serializer = serializer self._pipe = None",
"When any of the signals have been triggered, invalidate the cache. :param signals:",
"update_resets_timeout if timeout: self._timeout = timeout self._region_cache.conn.expire(name, timeout) if '.' in name: parent",
"= timeout self._region_cache.conn.expire(name, timeout) if '.' in name: parent = name.rsplit('.', 1)[0] parent",
"KeyError(item) # pylint: disable=W0212 if self._region_cache._raise_on_timeout: # raise the redis timeout error instead",
"cached result. \"\"\" @wraps(f) def wrapper(*args, **kwargs): key = self._serializer.dumps((args, kwargs)) try: ret",
"Do not instantiate these directly. Instead use the RegionCache.region() function. This will make",
"bound cache region. Do not instantiate these directly. Instead use the RegionCache.region() function.",
"\"\"\" return self._region_cache.region( name=self.name + '.' + name, timeout=timeout or self._timeout, update_resets_timeout=( update_resets_timeout",
"return self._region_cache.region( name=self.name + '.' + name, timeout=timeout or self._timeout, update_resets_timeout=( update_resets_timeout if",
"return. Will be stored in the cache on computation. :return: The value in",
"1 and key in self))) if self._pipe: self._pipe.hdel(self.name, key) else: self._region_cache.conn.hdel(self.name, key) if",
"value = alt() if callable(alt) else alt self[item] = value return value except",
"value): raw_value = self._serializer.dumps(value) if not self._region_cache.is_disconnected(): should_reset_timeout = (not self._pipe and self._timeout",
"args as a key and caches the result of calling the method. Subsequent",
"serializer=serializer or self._serializer ) def invalidate(self, pipeline=None): \"\"\" Delete this region's cache data",
"for sig in signals: if isinstance(sig, str): sig = blinker.signal(sig) sig.connect(handler, weak=False) def",
"__getitem__(self, item): timed_out = False if self._region_cache.is_disconnected(): raise KeyError(item) # pylint: disable=W0212 if",
"in name: parent = name.rsplit('.', 1)[0] parent = self._region_cache.region(parent) parent.add_child(self) def __repr__(self): return",
"else self._update_resets_timeout), serializer=serializer or self._serializer ) def invalidate(self, pipeline=None): \"\"\" Delete this region's",
"same arguments will return the cached result. \"\"\" @wraps(f) def wrapper(*args, **kwargs): key",
"not in the cache, compute it from `alt`. Alt can be a callable",
"self._serializer.loads(raw_value) else: raise KeyError(item) def __setitem__(self, key, value): raw_value = self._serializer.dumps(value) if not",
"MutableMapping from datetime import datetime from functools import wraps import blinker import logging",
"= f(*args, **kwargs) self[key] = ret return ret return wrapper def get_or_compute(self, item,",
"and all its subregions. :param pipeline: Used internally. :return: None \"\"\" _logger.debug(\"Invalidating region",
"the cache on computation. :return: The value in the cache. \"\"\" try: return",
"the dotted regions are treated as subregions of this subregion. :param timeout: The",
"raise KeyError(item) def __setitem__(self, key, value): raw_value = self._serializer.dumps(value) if not self._region_cache.is_disconnected(): should_reset_timeout",
"scalar. The value to return. Will be stored in the cache on computation.",
"return the cached result. \"\"\" @wraps(f) def wrapper(*args, **kwargs): key = self._serializer.dumps((args, kwargs))",
"self[key] = ret return ret return wrapper def get_or_compute(self, item, alt): \"\"\" Get",
"self._region_cache.read_conn.hget(self.name, item) else: try: raw_value = self._region_cache.read_conn.hget(self.name, item) except redis.TimeoutError: raw_value = None",
"are treated as subregions of this subregion. :param timeout: The timeout in seconds",
"f): \"\"\" Decorator that uses a serialized form of the input args as",
"region(self, name=None, timeout=None, update_resets_timeout=None, serializer=None): \"\"\" Get a sub-region from this region. When",
"setting. :param serializer: The serializer to use. Must define loads and dumps(). Defaults",
"self[key] except KeyError: ret = f(*args, **kwargs) self[key] = ret return ret return",
"use. Must define loads and dumps(). Defaults to the parent region's setting :return:",
"(not self._pipe and self._timeout and (self._update_resets_timeout or (len(self) == 1 and key in",
"return ret return wrapper def get_or_compute(self, item, alt): \"\"\" Get the value, or",
"*signals): \"\"\" Bind this cache region to blinker signals. When any of the",
"the timeout. Defaults to the parent region's setting. :param serializer: The serializer to",
"self._region_cache.conn.hlen(self.name) def __enter__(self): if not self._pipe: self._pipe = self._region_cache.conn.pipeline() return self def __exit__(self,",
"to blinker signals. When any of the signals have been triggered, invalidate the",
"alt() else: return alt def __getitem__(self, item): timed_out = False if self._region_cache.is_disconnected(): raise",
"can be a callable or a scalar. :param item: The key to get",
"return alt def __getitem__(self, item): timed_out = False if self._region_cache.is_disconnected(): raise KeyError(item) #",
"self._region_cache.conn.pipeline() is_root_call = True else: is_root_call = False for child in self.children(): child.invalidate(pipeline)",
"exc_type is None: # if we started with nothing in the cache, reset",
"== self.name def children(self): return (self._region_cache.region(name.decode('utf-8')) for name in self._region_cache.read_conn.smembers(self._children_key)) def add_child(self, child):",
"if isinstance(sig, str): sig = blinker.signal(sig) sig.connect(handler, weak=False) def cached(self, f): \"\"\" Decorator",
"have been triggered, invalidate the cache. :param signals: blinker signal objects or string",
"timeout=None, update_resets_timeout=True, serializer=pickle): self._region_cache = region_cache self.name = name self._region_cache.conn.hset(name, '__cache_region_created_at__', datetime.utcnow().isoformat()) self._timeout",
"raise redis.TimeoutError(f\"Cannot delete item {key} from {self.name} because we are disconnected.\") def __iter__(self):",
"or string names for named signals. :return: None \"\"\" def handler(sender, **kwargs): try:",
"of a key error raw_value = self._region_cache.read_conn.hget(self.name, item) else: try: raw_value = self._region_cache.read_conn.hget(self.name,",
"not self._region_cache.is_disconnected(): should_reset_timeout = (not self._pipe and self._timeout and (self._update_resets_timeout or not len(self)))",
"pipeline=None): \"\"\" Delete this region's cache data and all its subregions. :param pipeline:",
"pylint: disable=W0212 if self._region_cache._reconnect_on_timeout: self._region_cache.invalidate_connections() raise KeyError(item) if raw_value is not None: return",
"\"Invalidation of {self.name} in signal handler timed out. Flush it manually\".format(self=self)) for sig",
"raise the redis timeout error instead of a key error raw_value = self._region_cache.read_conn.hget(self.name,",
"in the cache, compute it from `alt`. Alt can be a callable or",
"def __len__(self): return self._region_cache.conn.hlen(self.name) def __enter__(self): if not self._pipe: self._pipe = self._region_cache.conn.pipeline() return",
"= False self._pipe = None return retval def __eq__(self, other): return other.name ==",
"(self._update_resets_timeout or len(self) == 0)) self._pipe.execute() if should_reset_timeout: self._region_cache.conn.expire(self.name, self._timeout) retval = True",
":return: None \"\"\" _logger.debug(\"Invalidating region %s\", self.name) if pipeline is None: pipeline =",
"arguments will return the cached result. \"\"\" @wraps(f) def wrapper(*args, **kwargs): key =",
"resets the timeout. Defaults to the parent region's setting. :param serializer: The serializer",
"value is not in the cache, compute it from `alt`. Alt can be",
"if not self._region_cache.is_disconnected(): should_reset_timeout = (not self._pipe and self._timeout and (self._update_resets_timeout or not",
"try: self.invalidate() except redis.TimeoutError: logging.getLogger('region_cache').exception( \"Invalidation of {self.name} in signal handler timed out.",
"{self.name} in signal handler timed out. Flush it manually\".format(self=self)) for sig in signals:",
"value, or if the value is not in the cache, compute it from",
"except KeyError: ret = f(*args, **kwargs) self[key] = ret return ret return wrapper",
"getLogger('region_cache') class Region(MutableMapping): \"\"\" A bound cache region. Do not instantiate these directly.",
"other.name == self.name def children(self): return (self._region_cache.region(name.decode('utf-8')) for name in self._region_cache.read_conn.smembers(self._children_key)) def add_child(self,",
"value to return. Will be stored in the cache on computation. :return: The",
"timeout :param update_resets_timeout: Whether updating the region resets the timeout. Defaults to the",
"return alt() else: return alt def __getitem__(self, item): timed_out = False if self._region_cache.is_disconnected():",
"self._region_cache.invalidate_connections() raise KeyError(item) if raw_value is not None: return self._serializer.loads(raw_value) else: raise KeyError(item)",
"def __setitem__(self, key, value): raw_value = self._serializer.dumps(value) if not self._region_cache.is_disconnected(): should_reset_timeout = (not",
"are included, then the dotted regions are treated as subregions of this subregion.",
"self._region_cache.read_conn.hkeys(self.name): if not k.decode('utf-8').startswith('__'): yield k def __len__(self): return self._region_cache.conn.hlen(self.name) def __enter__(self): if",
"__enter__(self): if not self._pipe: self._pipe = self._region_cache.conn.pipeline() return self def __exit__(self, exc_type, exc_val,",
"<reponame>jheard-tw/region_cache import pickle import redis from collections.abc import MutableMapping from datetime import datetime",
"should_reset_timeout = (self._timeout and (self._update_resets_timeout or len(self) == 0)) self._pipe.execute() if should_reset_timeout: self._region_cache.conn.expire(self.name,",
"been triggered, invalidate the cache. :param signals: blinker signal objects or string names",
"def __delitem__(self, key): if not self._region_cache.is_disconnected(): should_reset_timeout = (not self._pipe and self._timeout and",
"\"\"\" def handler(sender, **kwargs): try: self.invalidate() except redis.TimeoutError: logging.getLogger('region_cache').exception( \"Invalidation of {self.name} in",
"to the method with the same arguments will return the cached result. \"\"\"",
"name.rsplit('.', 1)[0] parent = self._region_cache.region(parent) parent.add_child(self) def __repr__(self): return \"Region({})\".format(self.name) def region(self, name=None,",
"be too. :param name: The name of the subregion. If dots are included,",
"self._region_cache.region(parent) parent.add_child(self) def __repr__(self): return \"Region({})\".format(self.name) def region(self, name=None, timeout=None, update_resets_timeout=None, serializer=None): \"\"\"",
"is None: # if we started with nothing in the cache, reset it",
"timed out. Flush it manually\".format(self=self)) for sig in signals: if isinstance(sig, str): sig",
"be a callable or a scalar. :param item: The key to get :param",
"if '.' in name: parent = name.rsplit('.', 1)[0] parent = self._region_cache.region(parent) parent.add_child(self) def",
"for k in self._region_cache.read_conn.hkeys(self.name): if not k.decode('utf-8').startswith('__'): yield k def __len__(self): return self._region_cache.conn.hlen(self.name)",
"directly. Instead use the RegionCache.region() function. This will make for proper nesting of",
"calling the method. Subsequent calls to the method with the same arguments will",
"child.invalidate(pipeline) pipeline.delete(self.name) if is_root_call: pipeline.execute() def invalidate_on(self, *signals): \"\"\" Bind this cache region",
"self._region_cache.is_disconnected(): raise KeyError(item) # pylint: disable=W0212 if self._region_cache._raise_on_timeout: # raise the redis timeout",
"None self._region_cache = region_cache self._serializer = serializer self._pipe = None self._children_key = self.name",
"callable or a scalar. :param item: The key to get :param alt: Callable",
"on computation. :return: The value in the cache. \"\"\" try: return self[item] except",
"name self._region_cache.conn.hset(name, '__cache_region_created_at__', datetime.utcnow().isoformat()) self._timeout = None self._region_cache = region_cache self._serializer = serializer",
"self._update_resets_timeout is not None else self._update_resets_timeout), serializer=serializer or self._serializer ) def invalidate(self, pipeline=None):",
"yield k def __len__(self): return self._region_cache.conn.hlen(self.name) def __enter__(self): if not self._pipe: self._pipe ="
] |
[
"resultful import ( unsafe, success, failure, unwrap_failure, Result, NoResult, ) from .conftest import",
"== f\"resultful.Failure({error!r})\" @given(error=st_exceptions()) def test_unsafe(error: BaseException) -> None: with pytest.raises(BaseException) as exception: unsafe(failure(error))",
"None: assert failure(error) == failure(error) @given(error=st_exceptions()) def test_inequality_with_success(error: BaseException) -> None: assert failure(error)",
"test_inequality_with_success(error: BaseException) -> None: assert failure(error) != success(error) @given(error=st_exceptions()) def test_unwrap_failure_from_failure(error: BaseException) ->",
"@given(error=st_exceptions()) def test_error_wrapped_in_failure(error: BaseException) -> None: result = failure(failure(error)) assert not result assert",
"@given(error=st_exceptions()) def test_result_if_condition(error: BaseException) -> None: def compute() -> Result[int, BaseException]: return failure(error)",
"unwrap_failure, Result, NoResult, ) from .conftest import ( st_exceptions, unreachable, ) @given(error=st_exceptions()) def",
"failure(failure(error)) assert not result assert result.error is error @given(value=st.integers()) def test_error_wrapped_in_success(value: int) ->",
"error @given(error=st_exceptions()) def test_error_wrapped_in_failure(error: BaseException) -> None: result = failure(failure(error)) assert not result",
"test_error_wrapped_in_success(value: int) -> None: result = failure(success(value)) assert result is NoResult @given(error=st_exceptions()) def",
"test_result_if_condition_walrus_operator(error: BaseException) -> None: def compute() -> Result[int, BaseException]: return failure(error) if not",
"compute() if not result: assert result.error is error else: unreachable() if result.is_failure: assert",
"@given(value=st.integers()) def test_error_wrapped_in_success(value: int) -> None: result = failure(success(value)) assert result is NoResult",
"assert result.error is error else: unreachable() if (result := compute()).is_failure: assert result.error is",
"unreachable() if (result := compute()).is_failure: assert result.error is error else: unreachable() if (result",
"result: assert result.error is error else: unreachable() if result.is_failure: assert result.error is error",
"Result[int, BaseException]: return failure(error) if not (result := compute()): assert result.error is error",
"result.error is error else: unreachable() if result.is_failure: assert result.error is error else: unreachable()",
"st_exceptions, unreachable, ) @given(error=st_exceptions()) def test_special_methods(error: BaseException) -> None: result = failure(error) assert",
"import ( unsafe, success, failure, unwrap_failure, Result, NoResult, ) from .conftest import (",
"def test_result_if_condition(error: BaseException) -> None: def compute() -> Result[int, BaseException]: return failure(error) result",
"error @given(error=st_exceptions()) def test_equality(error: BaseException) -> None: assert failure(error) == failure(error) @given(error=st_exceptions()) def",
"failure, unwrap_failure, Result, NoResult, ) from .conftest import ( st_exceptions, unreachable, ) @given(error=st_exceptions())",
"= compute() if not result: assert result.error is error else: unreachable() if result.is_failure:",
"def test_error(error: BaseException) -> None: result = failure(error) assert not result assert result.error",
"@given(error=st_exceptions()) def test_result_if_condition_walrus_operator(error: BaseException) -> None: def compute() -> Result[int, BaseException]: return failure(error)",
"<gh_stars>0 import pytest from hypothesis import ( given, strategies as st, ) from",
"as exception: unsafe(failure(error)) assert exception.value is error @given(error=st_exceptions()) def test_equality(error: BaseException) -> None:",
"@given(error=st_exceptions()) def test_unwrap_failure_from_failure(error: BaseException) -> None: result = unwrap_failure(failure(error)) assert result is error",
"-> None: assert failure(error) != success(error) @given(error=st_exceptions()) def test_unwrap_failure_from_failure(error: BaseException) -> None: result",
"else: assert result.error is error @given(error=st_exceptions()) def test_result_if_condition_walrus_operator(error: BaseException) -> None: def compute()",
"pytest.raises(BaseException) as exception: unsafe(failure(error)) assert exception.value is error @given(error=st_exceptions()) def test_equality(error: BaseException) ->",
"import ( given, strategies as st, ) from resultful import ( unsafe, success,",
"BaseException) -> None: result = unwrap_failure(failure(error)) assert result is error @given(value=st.integers()) def test_unwrap_failure_from_success(value:",
"if result.is_success: unreachable() else: assert result.error is error @given(error=st_exceptions()) def test_result_if_condition_walrus_operator(error: BaseException) ->",
"@given(error=st_exceptions()) def test_unsafe(error: BaseException) -> None: with pytest.raises(BaseException) as exception: unsafe(failure(error)) assert exception.value",
"BaseException) -> None: def compute() -> Result[int, BaseException]: return failure(error) result = compute()",
"None: assert failure(error) != success(error) @given(error=st_exceptions()) def test_unwrap_failure_from_failure(error: BaseException) -> None: result =",
"is NoResult @given(error=st_exceptions()) def test_result_if_condition(error: BaseException) -> None: def compute() -> Result[int, BaseException]:",
"failure(error) == failure(error) @given(error=st_exceptions()) def test_inequality_with_success(error: BaseException) -> None: assert failure(error) != success(error)",
"def test_inequality_with_success(error: BaseException) -> None: assert failure(error) != success(error) @given(error=st_exceptions()) def test_unwrap_failure_from_failure(error: BaseException)",
"assert result.error is error else: unreachable() if result.is_failure: assert result.error is error else:",
"compute() -> Result[int, BaseException]: return failure(error) result = compute() if not result: assert",
"test_unwrap_failure_from_success(value: int) -> None: result = unwrap_failure(success(value)) assert result is NoResult @given(error=st_exceptions()) def",
"error @given(error=st_exceptions()) def test_result_if_condition_walrus_operator(error: BaseException) -> None: def compute() -> Result[int, BaseException]: return",
"Result, NoResult, ) from .conftest import ( st_exceptions, unreachable, ) @given(error=st_exceptions()) def test_special_methods(error:",
"BaseException) -> None: result = failure(failure(error)) assert not result assert result.error is error",
"def test_error_wrapped_in_failure(error: BaseException) -> None: result = failure(failure(error)) assert not result assert result.error",
"-> Result[int, BaseException]: return failure(error) if not (result := compute()): assert result.error is",
"repr(result) == f\"resultful.Failure({error!r})\" @given(error=st_exceptions()) def test_unsafe(error: BaseException) -> None: with pytest.raises(BaseException) as exception:",
"return failure(error) if not (result := compute()): assert result.error is error else: unreachable()",
"NoResult, ) from .conftest import ( st_exceptions, unreachable, ) @given(error=st_exceptions()) def test_special_methods(error: BaseException)",
"BaseException) -> None: result = failure(error) assert bool(result) is False assert repr(result) ==",
"result is NoResult @given(error=st_exceptions()) def test_error(error: BaseException) -> None: result = failure(error) assert",
"-> None: result = failure(error) assert bool(result) is False assert repr(result) == f\"resultful.Failure({error!r})\"",
"is False assert repr(result) == f\"resultful.Failure({error!r})\" @given(error=st_exceptions()) def test_unsafe(error: BaseException) -> None: with",
"None: result = failure(error) assert not result assert result.error is error @given(error=st_exceptions()) def",
"error else: unreachable() if (result := compute()).is_success: unreachable() else: assert result.error is error",
"is error @given(value=st.integers()) def test_unwrap_failure_from_success(value: int) -> None: result = unwrap_failure(success(value)) assert result",
"def test_unwrap_failure_from_success(value: int) -> None: result = unwrap_failure(success(value)) assert result is NoResult @given(error=st_exceptions())",
"else: unreachable() if (result := compute()).is_failure: assert result.error is error else: unreachable() if",
"compute()): assert result.error is error else: unreachable() if (result := compute()).is_failure: assert result.error",
"None: def compute() -> Result[int, BaseException]: return failure(error) if not (result := compute()):",
"None: def compute() -> Result[int, BaseException]: return failure(error) result = compute() if not",
"assert bool(result) is False assert repr(result) == f\"resultful.Failure({error!r})\" @given(error=st_exceptions()) def test_unsafe(error: BaseException) ->",
"result = failure(failure(error)) assert not result assert result.error is error @given(value=st.integers()) def test_error_wrapped_in_success(value:",
"unsafe, success, failure, unwrap_failure, Result, NoResult, ) from .conftest import ( st_exceptions, unreachable,",
"def test_error_wrapped_in_success(value: int) -> None: result = failure(success(value)) assert result is NoResult @given(error=st_exceptions())",
"assert result.error is error @given(error=st_exceptions()) def test_error_wrapped_in_failure(error: BaseException) -> None: result = failure(failure(error))",
"if result.is_failure: assert result.error is error else: unreachable() if result.is_success: unreachable() else: assert",
"None: result = failure(success(value)) assert result is NoResult @given(error=st_exceptions()) def test_result_if_condition(error: BaseException) ->",
"assert repr(result) == f\"resultful.Failure({error!r})\" @given(error=st_exceptions()) def test_unsafe(error: BaseException) -> None: with pytest.raises(BaseException) as",
"-> None: def compute() -> Result[int, BaseException]: return failure(error) if not (result :=",
"BaseException) -> None: def compute() -> Result[int, BaseException]: return failure(error) if not (result",
"result.error is error else: unreachable() if (result := compute()).is_success: unreachable() else: assert result.error",
"import pytest from hypothesis import ( given, strategies as st, ) from resultful",
"import ( st_exceptions, unreachable, ) @given(error=st_exceptions()) def test_special_methods(error: BaseException) -> None: result =",
"not result assert result.error is error @given(value=st.integers()) def test_error_wrapped_in_success(value: int) -> None: result",
"from resultful import ( unsafe, success, failure, unwrap_failure, Result, NoResult, ) from .conftest",
"= failure(success(value)) assert result is NoResult @given(error=st_exceptions()) def test_result_if_condition(error: BaseException) -> None: def",
"-> None: with pytest.raises(BaseException) as exception: unsafe(failure(error)) assert exception.value is error @given(error=st_exceptions()) def",
"-> None: result = unwrap_failure(failure(error)) assert result is error @given(value=st.integers()) def test_unwrap_failure_from_success(value: int)",
"unreachable() if result.is_success: unreachable() else: assert result.error is error @given(error=st_exceptions()) def test_result_if_condition_walrus_operator(error: BaseException)",
"given, strategies as st, ) from resultful import ( unsafe, success, failure, unwrap_failure,",
"bool(result) is False assert repr(result) == f\"resultful.Failure({error!r})\" @given(error=st_exceptions()) def test_unsafe(error: BaseException) -> None:",
"assert not result assert result.error is error @given(error=st_exceptions()) def test_error_wrapped_in_failure(error: BaseException) -> None:",
"failure(error) @given(error=st_exceptions()) def test_inequality_with_success(error: BaseException) -> None: assert failure(error) != success(error) @given(error=st_exceptions()) def",
"not result: assert result.error is error else: unreachable() if result.is_failure: assert result.error is",
"is error else: unreachable() if (result := compute()).is_success: unreachable() else: assert result.error is",
"error else: unreachable() if result.is_failure: assert result.error is error else: unreachable() if result.is_success:",
"is error @given(error=st_exceptions()) def test_error_wrapped_in_failure(error: BaseException) -> None: result = failure(failure(error)) assert not",
"BaseException) -> None: with pytest.raises(BaseException) as exception: unsafe(failure(error)) assert exception.value is error @given(error=st_exceptions())",
"is NoResult @given(error=st_exceptions()) def test_error(error: BaseException) -> None: result = failure(error) assert not",
"result is error @given(value=st.integers()) def test_unwrap_failure_from_success(value: int) -> None: result = unwrap_failure(success(value)) assert",
"as st, ) from resultful import ( unsafe, success, failure, unwrap_failure, Result, NoResult,",
"(result := compute()).is_failure: assert result.error is error else: unreachable() if (result := compute()).is_success:",
"NoResult @given(error=st_exceptions()) def test_error(error: BaseException) -> None: result = failure(error) assert not result",
") @given(error=st_exceptions()) def test_special_methods(error: BaseException) -> None: result = failure(error) assert bool(result) is",
"exception.value is error @given(error=st_exceptions()) def test_equality(error: BaseException) -> None: assert failure(error) == failure(error)",
"def test_equality(error: BaseException) -> None: assert failure(error) == failure(error) @given(error=st_exceptions()) def test_inequality_with_success(error: BaseException)",
"@given(error=st_exceptions()) def test_special_methods(error: BaseException) -> None: result = failure(error) assert bool(result) is False",
"result = failure(error) assert bool(result) is False assert repr(result) == f\"resultful.Failure({error!r})\" @given(error=st_exceptions()) def",
"@given(error=st_exceptions()) def test_inequality_with_success(error: BaseException) -> None: assert failure(error) != success(error) @given(error=st_exceptions()) def test_unwrap_failure_from_failure(error:",
"result = failure(success(value)) assert result is NoResult @given(error=st_exceptions()) def test_result_if_condition(error: BaseException) -> None:",
"BaseException]: return failure(error) if not (result := compute()): assert result.error is error else:",
"result.error is error else: unreachable() if (result := compute()).is_failure: assert result.error is error",
"else: unreachable() if result.is_success: unreachable() else: assert result.error is error @given(error=st_exceptions()) def test_result_if_condition_walrus_operator(error:",
"test_result_if_condition(error: BaseException) -> None: def compute() -> Result[int, BaseException]: return failure(error) result =",
"BaseException) -> None: assert failure(error) == failure(error) @given(error=st_exceptions()) def test_inequality_with_success(error: BaseException) -> None:",
"@given(error=st_exceptions()) def test_error(error: BaseException) -> None: result = failure(error) assert not result assert",
"f\"resultful.Failure({error!r})\" @given(error=st_exceptions()) def test_unsafe(error: BaseException) -> None: with pytest.raises(BaseException) as exception: unsafe(failure(error)) assert",
"is error else: unreachable() if result.is_success: unreachable() else: assert result.error is error @given(error=st_exceptions())",
"= failure(error) assert not result assert result.error is error @given(error=st_exceptions()) def test_error_wrapped_in_failure(error: BaseException)",
"= unwrap_failure(success(value)) assert result is NoResult @given(error=st_exceptions()) def test_error(error: BaseException) -> None: result",
"= failure(failure(error)) assert not result assert result.error is error @given(value=st.integers()) def test_error_wrapped_in_success(value: int)",
"int) -> None: result = unwrap_failure(success(value)) assert result is NoResult @given(error=st_exceptions()) def test_error(error:",
"compute()).is_failure: assert result.error is error else: unreachable() if (result := compute()).is_success: unreachable() else:",
"test_equality(error: BaseException) -> None: assert failure(error) == failure(error) @given(error=st_exceptions()) def test_inequality_with_success(error: BaseException) ->",
"-> None: result = failure(failure(error)) assert not result assert result.error is error @given(value=st.integers())",
"error else: unreachable() if result.is_success: unreachable() else: assert result.error is error @given(error=st_exceptions()) def",
"hypothesis import ( given, strategies as st, ) from resultful import ( unsafe,",
"compute() -> Result[int, BaseException]: return failure(error) if not (result := compute()): assert result.error",
"BaseException]: return failure(error) result = compute() if not result: assert result.error is error",
"assert failure(error) == failure(error) @given(error=st_exceptions()) def test_inequality_with_success(error: BaseException) -> None: assert failure(error) !=",
") from .conftest import ( st_exceptions, unreachable, ) @given(error=st_exceptions()) def test_special_methods(error: BaseException) ->",
"failure(success(value)) assert result is NoResult @given(error=st_exceptions()) def test_result_if_condition(error: BaseException) -> None: def compute()",
"failure(error) assert bool(result) is False assert repr(result) == f\"resultful.Failure({error!r})\" @given(error=st_exceptions()) def test_unsafe(error: BaseException)",
"unreachable() else: assert result.error is error @given(error=st_exceptions()) def test_result_if_condition_walrus_operator(error: BaseException) -> None: def",
"-> None: result = failure(success(value)) assert result is NoResult @given(error=st_exceptions()) def test_result_if_condition(error: BaseException)",
"else: unreachable() if result.is_failure: assert result.error is error else: unreachable() if result.is_success: unreachable()",
"!= success(error) @given(error=st_exceptions()) def test_unwrap_failure_from_failure(error: BaseException) -> None: result = unwrap_failure(failure(error)) assert result",
"result = compute() if not result: assert result.error is error else: unreachable() if",
"@given(error=st_exceptions()) def test_equality(error: BaseException) -> None: assert failure(error) == failure(error) @given(error=st_exceptions()) def test_inequality_with_success(error:",
"def test_special_methods(error: BaseException) -> None: result = failure(error) assert bool(result) is False assert",
"is error else: unreachable() if (result := compute()).is_failure: assert result.error is error else:",
"NoResult @given(error=st_exceptions()) def test_result_if_condition(error: BaseException) -> None: def compute() -> Result[int, BaseException]: return",
"-> None: assert failure(error) == failure(error) @given(error=st_exceptions()) def test_inequality_with_success(error: BaseException) -> None: assert",
"-> None: result = failure(error) assert not result assert result.error is error @given(error=st_exceptions())",
"( unsafe, success, failure, unwrap_failure, Result, NoResult, ) from .conftest import ( st_exceptions,",
"test_error(error: BaseException) -> None: result = failure(error) assert not result assert result.error is",
"if (result := compute()).is_failure: assert result.error is error else: unreachable() if (result :=",
"result assert result.error is error @given(value=st.integers()) def test_error_wrapped_in_success(value: int) -> None: result =",
"None: with pytest.raises(BaseException) as exception: unsafe(failure(error)) assert exception.value is error @given(error=st_exceptions()) def test_equality(error:",
"def compute() -> Result[int, BaseException]: return failure(error) result = compute() if not result:",
"-> Result[int, BaseException]: return failure(error) result = compute() if not result: assert result.error",
"assert exception.value is error @given(error=st_exceptions()) def test_equality(error: BaseException) -> None: assert failure(error) ==",
"def test_unwrap_failure_from_failure(error: BaseException) -> None: result = unwrap_failure(failure(error)) assert result is error @given(value=st.integers())",
"None: result = unwrap_failure(failure(error)) assert result is error @given(value=st.integers()) def test_unwrap_failure_from_success(value: int) ->",
"int) -> None: result = failure(success(value)) assert result is NoResult @given(error=st_exceptions()) def test_result_if_condition(error:",
"if not (result := compute()): assert result.error is error else: unreachable() if (result",
"error else: unreachable() if (result := compute()).is_failure: assert result.error is error else: unreachable()",
":= compute()).is_failure: assert result.error is error else: unreachable() if (result := compute()).is_success: unreachable()",
"assert not result assert result.error is error @given(value=st.integers()) def test_error_wrapped_in_success(value: int) -> None:",
"error @given(value=st.integers()) def test_error_wrapped_in_success(value: int) -> None: result = failure(success(value)) assert result is",
"success, failure, unwrap_failure, Result, NoResult, ) from .conftest import ( st_exceptions, unreachable, )",
"unwrap_failure(success(value)) assert result is NoResult @given(error=st_exceptions()) def test_error(error: BaseException) -> None: result =",
"unwrap_failure(failure(error)) assert result is error @given(value=st.integers()) def test_unwrap_failure_from_success(value: int) -> None: result =",
"result.is_success: unreachable() else: assert result.error is error @given(error=st_exceptions()) def test_result_if_condition_walrus_operator(error: BaseException) -> None:",
"unreachable, ) @given(error=st_exceptions()) def test_special_methods(error: BaseException) -> None: result = failure(error) assert bool(result)",
"BaseException) -> None: assert failure(error) != success(error) @given(error=st_exceptions()) def test_unwrap_failure_from_failure(error: BaseException) -> None:",
"def compute() -> Result[int, BaseException]: return failure(error) if not (result := compute()): assert",
".conftest import ( st_exceptions, unreachable, ) @given(error=st_exceptions()) def test_special_methods(error: BaseException) -> None: result",
"is error @given(value=st.integers()) def test_error_wrapped_in_success(value: int) -> None: result = failure(success(value)) assert result",
"test_special_methods(error: BaseException) -> None: result = failure(error) assert bool(result) is False assert repr(result)",
"assert result is error @given(value=st.integers()) def test_unwrap_failure_from_success(value: int) -> None: result = unwrap_failure(success(value))",
"None: result = failure(failure(error)) assert not result assert result.error is error @given(value=st.integers()) def",
"is error else: unreachable() if result.is_failure: assert result.error is error else: unreachable() if",
"@given(value=st.integers()) def test_unwrap_failure_from_success(value: int) -> None: result = unwrap_failure(success(value)) assert result is NoResult",
"assert result.error is error else: unreachable() if result.is_success: unreachable() else: assert result.error is",
"def test_result_if_condition_walrus_operator(error: BaseException) -> None: def compute() -> Result[int, BaseException]: return failure(error) if",
"st, ) from resultful import ( unsafe, success, failure, unwrap_failure, Result, NoResult, )",
"= failure(error) assert bool(result) is False assert repr(result) == f\"resultful.Failure({error!r})\" @given(error=st_exceptions()) def test_unsafe(error:",
"strategies as st, ) from resultful import ( unsafe, success, failure, unwrap_failure, Result,",
"def test_unsafe(error: BaseException) -> None: with pytest.raises(BaseException) as exception: unsafe(failure(error)) assert exception.value is",
"failure(error) != success(error) @given(error=st_exceptions()) def test_unwrap_failure_from_failure(error: BaseException) -> None: result = unwrap_failure(failure(error)) assert",
"Result[int, BaseException]: return failure(error) result = compute() if not result: assert result.error is",
"failure(error) assert not result assert result.error is error @given(error=st_exceptions()) def test_error_wrapped_in_failure(error: BaseException) ->",
"BaseException) -> None: result = failure(error) assert not result assert result.error is error",
"exception: unsafe(failure(error)) assert exception.value is error @given(error=st_exceptions()) def test_equality(error: BaseException) -> None: assert",
"from .conftest import ( st_exceptions, unreachable, ) @given(error=st_exceptions()) def test_special_methods(error: BaseException) -> None:",
"( st_exceptions, unreachable, ) @given(error=st_exceptions()) def test_special_methods(error: BaseException) -> None: result = failure(error)",
"success(error) @given(error=st_exceptions()) def test_unwrap_failure_from_failure(error: BaseException) -> None: result = unwrap_failure(failure(error)) assert result is",
"not result assert result.error is error @given(error=st_exceptions()) def test_error_wrapped_in_failure(error: BaseException) -> None: result",
"assert result.error is error @given(error=st_exceptions()) def test_result_if_condition_walrus_operator(error: BaseException) -> None: def compute() ->",
":= compute()): assert result.error is error else: unreachable() if (result := compute()).is_failure: assert",
"assert result.error is error @given(value=st.integers()) def test_error_wrapped_in_success(value: int) -> None: result = failure(success(value))",
"( given, strategies as st, ) from resultful import ( unsafe, success, failure,",
"assert failure(error) != success(error) @given(error=st_exceptions()) def test_unwrap_failure_from_failure(error: BaseException) -> None: result = unwrap_failure(failure(error))",
"result.error is error @given(error=st_exceptions()) def test_result_if_condition_walrus_operator(error: BaseException) -> None: def compute() -> Result[int,",
"failure(error) result = compute() if not result: assert result.error is error else: unreachable()",
") from resultful import ( unsafe, success, failure, unwrap_failure, Result, NoResult, ) from",
"-> None: def compute() -> Result[int, BaseException]: return failure(error) result = compute() if",
"result.is_failure: assert result.error is error else: unreachable() if result.is_success: unreachable() else: assert result.error",
"assert result.error is error else: unreachable() if (result := compute()).is_success: unreachable() else: assert",
"assert result is NoResult @given(error=st_exceptions()) def test_result_if_condition(error: BaseException) -> None: def compute() ->",
"result.error is error @given(value=st.integers()) def test_error_wrapped_in_success(value: int) -> None: result = failure(success(value)) assert",
"from hypothesis import ( given, strategies as st, ) from resultful import (",
"unreachable() if result.is_failure: assert result.error is error else: unreachable() if result.is_success: unreachable() else:",
"result is NoResult @given(error=st_exceptions()) def test_result_if_condition(error: BaseException) -> None: def compute() -> Result[int,",
"error @given(value=st.integers()) def test_unwrap_failure_from_success(value: int) -> None: result = unwrap_failure(success(value)) assert result is",
"-> None: result = unwrap_failure(success(value)) assert result is NoResult @given(error=st_exceptions()) def test_error(error: BaseException)",
"result.error is error @given(error=st_exceptions()) def test_error_wrapped_in_failure(error: BaseException) -> None: result = failure(failure(error)) assert",
"(result := compute()): assert result.error is error else: unreachable() if (result := compute()).is_failure:",
"unsafe(failure(error)) assert exception.value is error @given(error=st_exceptions()) def test_equality(error: BaseException) -> None: assert failure(error)",
"False assert repr(result) == f\"resultful.Failure({error!r})\" @given(error=st_exceptions()) def test_unsafe(error: BaseException) -> None: with pytest.raises(BaseException)",
"= unwrap_failure(failure(error)) assert result is error @given(value=st.integers()) def test_unwrap_failure_from_success(value: int) -> None: result",
"None: result = unwrap_failure(success(value)) assert result is NoResult @given(error=st_exceptions()) def test_error(error: BaseException) ->",
"return failure(error) result = compute() if not result: assert result.error is error else:",
"is error @given(error=st_exceptions()) def test_equality(error: BaseException) -> None: assert failure(error) == failure(error) @given(error=st_exceptions())",
"result = unwrap_failure(success(value)) assert result is NoResult @given(error=st_exceptions()) def test_error(error: BaseException) -> None:",
"result assert result.error is error @given(error=st_exceptions()) def test_error_wrapped_in_failure(error: BaseException) -> None: result =",
"result.error is error else: unreachable() if result.is_success: unreachable() else: assert result.error is error",
"pytest from hypothesis import ( given, strategies as st, ) from resultful import",
"None: result = failure(error) assert bool(result) is False assert repr(result) == f\"resultful.Failure({error!r})\" @given(error=st_exceptions())",
"failure(error) if not (result := compute()): assert result.error is error else: unreachable() if",
"== failure(error) @given(error=st_exceptions()) def test_inequality_with_success(error: BaseException) -> None: assert failure(error) != success(error) @given(error=st_exceptions())",
"is error @given(error=st_exceptions()) def test_result_if_condition_walrus_operator(error: BaseException) -> None: def compute() -> Result[int, BaseException]:",
"test_error_wrapped_in_failure(error: BaseException) -> None: result = failure(failure(error)) assert not result assert result.error is",
"result = unwrap_failure(failure(error)) assert result is error @given(value=st.integers()) def test_unwrap_failure_from_success(value: int) -> None:",
"not (result := compute()): assert result.error is error else: unreachable() if (result :=",
"result = failure(error) assert not result assert result.error is error @given(error=st_exceptions()) def test_error_wrapped_in_failure(error:",
"if not result: assert result.error is error else: unreachable() if result.is_failure: assert result.error",
"test_unwrap_failure_from_failure(error: BaseException) -> None: result = unwrap_failure(failure(error)) assert result is error @given(value=st.integers()) def",
"test_unsafe(error: BaseException) -> None: with pytest.raises(BaseException) as exception: unsafe(failure(error)) assert exception.value is error",
"assert result is NoResult @given(error=st_exceptions()) def test_error(error: BaseException) -> None: result = failure(error)",
"with pytest.raises(BaseException) as exception: unsafe(failure(error)) assert exception.value is error @given(error=st_exceptions()) def test_equality(error: BaseException)"
] |
[
"label = 1 if label >2 else 0 train_X.append(sentence) train_y.append(label) test_X = []",
">2 else 0 train_X.append(sentence) train_y.append(label) test_X = [] test_y = [] for e",
"= 1 if label >2 else 0 test_X.append(sentence) test_y.append(label) return (train_X,train_y), (test_X, test_y)",
"import pytreebank import pickle import numpy as np dataset = pytreebank.load_sst() def get_sst(cate='5'):",
"label, sentence = e.to_labeled_lines()[0] if cate == '2' and label == 2: continue",
"'2' and label == 2: continue if cate == '2': label = 1",
"label >2 else 0 test_X.append(sentence) test_y.append(label) return (train_X,train_y), (test_X, test_y) if __name__ ==",
"dataset = pytreebank.load_sst() def get_sst(cate='5'): train_X = [] train_y = [] for e",
"if label >2 else 0 train_X.append(sentence) train_y.append(label) test_X = [] test_y = []",
"pytreebank import pickle import numpy as np dataset = pytreebank.load_sst() def get_sst(cate='5'): train_X",
"if cate == '2' and label == 2: continue if cate == '2':",
"0 train_X.append(sentence) train_y.append(label) test_X = [] test_y = [] for e in dataset['test']:",
"== '2': label = 1 if label >2 else 0 test_X.append(sentence) test_y.append(label) return",
"cate == '2': label = 1 if label >2 else 0 train_X.append(sentence) train_y.append(label)",
"np dataset = pytreebank.load_sst() def get_sst(cate='5'): train_X = [] train_y = [] for",
"train_y.append(label) test_X = [] test_y = [] for e in dataset['test']: label, sentence",
"if cate == '2': label = 1 if label >2 else 0 test_X.append(sentence)",
"cate == '2': label = 1 if label >2 else 0 test_X.append(sentence) test_y.append(label)",
"else 0 train_X.append(sentence) train_y.append(label) test_X = [] test_y = [] for e in",
"def get_sst(cate='5'): train_X = [] train_y = [] for e in dataset['train']: label,",
"train_X = [] train_y = [] for e in dataset['train']: label, sentence =",
"as np dataset = pytreebank.load_sst() def get_sst(cate='5'): train_X = [] train_y = []",
"in dataset['test']: label, sentence = e.to_labeled_lines()[0] if cate == '2' and label ==",
"if label >2 else 0 test_X.append(sentence) test_y.append(label) return (train_X,train_y), (test_X, test_y) if __name__",
"= e.to_labeled_lines()[0] if cate == '2' and label == 2: continue if cate",
"get_sst(cate='5'): train_X = [] train_y = [] for e in dataset['train']: label, sentence",
"= [] for e in dataset['train']: label, sentence = e.to_labeled_lines()[0] if cate ==",
"= [] train_y = [] for e in dataset['train']: label, sentence = e.to_labeled_lines()[0]",
"[] for e in dataset['test']: label, sentence = e.to_labeled_lines()[0] if cate == '2'",
">2 else 0 test_X.append(sentence) test_y.append(label) return (train_X,train_y), (test_X, test_y) if __name__ == '__main__':",
"for e in dataset['train']: label, sentence = e.to_labeled_lines()[0] if cate == '2' and",
"numpy as np dataset = pytreebank.load_sst() def get_sst(cate='5'): train_X = [] train_y =",
"dataset['train']: label, sentence = e.to_labeled_lines()[0] if cate == '2' and label == 2:",
"== '2' and label == 2: continue if cate == '2': label =",
"if cate == '2': label = 1 if label >2 else 0 train_X.append(sentence)",
"== '2': label = 1 if label >2 else 0 train_X.append(sentence) train_y.append(label) test_X",
"[] for e in dataset['train']: label, sentence = e.to_labeled_lines()[0] if cate == '2'",
"[] train_y = [] for e in dataset['train']: label, sentence = e.to_labeled_lines()[0] if",
"sentence = e.to_labeled_lines()[0] if cate == '2' and label == 2: continue if",
"2: continue if cate == '2': label = 1 if label >2 else",
"1 if label >2 else 0 train_X.append(sentence) train_y.append(label) test_X = [] test_y =",
"test_X = [] test_y = [] for e in dataset['test']: label, sentence =",
"and label == 2: continue if cate == '2': label = 1 if",
"train_y = [] for e in dataset['train']: label, sentence = e.to_labeled_lines()[0] if cate",
"continue if cate == '2': label = 1 if label >2 else 0",
"= [] for e in dataset['test']: label, sentence = e.to_labeled_lines()[0] if cate ==",
"'2': label = 1 if label >2 else 0 test_X.append(sentence) test_y.append(label) return (train_X,train_y),",
"test_y = [] for e in dataset['test']: label, sentence = e.to_labeled_lines()[0] if cate",
"pytreebank.load_sst() def get_sst(cate='5'): train_X = [] train_y = [] for e in dataset['train']:",
"pickle import numpy as np dataset = pytreebank.load_sst() def get_sst(cate='5'): train_X = []",
"[] test_y = [] for e in dataset['test']: label, sentence = e.to_labeled_lines()[0] if",
"cate == '2' and label == 2: continue if cate == '2': label",
"train_X.append(sentence) train_y.append(label) test_X = [] test_y = [] for e in dataset['test']: label,",
"import numpy as np dataset = pytreebank.load_sst() def get_sst(cate='5'): train_X = [] train_y",
"in dataset['train']: label, sentence = e.to_labeled_lines()[0] if cate == '2' and label ==",
"= [] test_y = [] for e in dataset['test']: label, sentence = e.to_labeled_lines()[0]",
"== 2: continue if cate == '2': label = 1 if label >2",
"for e in dataset['test']: label, sentence = e.to_labeled_lines()[0] if cate == '2' and",
"e in dataset['test']: label, sentence = e.to_labeled_lines()[0] if cate == '2' and label",
"1 if label >2 else 0 test_X.append(sentence) test_y.append(label) return (train_X,train_y), (test_X, test_y) if",
"dataset['test']: label, sentence = e.to_labeled_lines()[0] if cate == '2' and label == 2:",
"import pickle import numpy as np dataset = pytreebank.load_sst() def get_sst(cate='5'): train_X =",
"e in dataset['train']: label, sentence = e.to_labeled_lines()[0] if cate == '2' and label",
"e.to_labeled_lines()[0] if cate == '2' and label == 2: continue if cate ==",
"'2': label = 1 if label >2 else 0 train_X.append(sentence) train_y.append(label) test_X =",
"= 1 if label >2 else 0 train_X.append(sentence) train_y.append(label) test_X = [] test_y",
"label = 1 if label >2 else 0 test_X.append(sentence) test_y.append(label) return (train_X,train_y), (test_X,",
"<filename>data.py import pytreebank import pickle import numpy as np dataset = pytreebank.load_sst() def",
"else 0 test_X.append(sentence) test_y.append(label) return (train_X,train_y), (test_X, test_y) if __name__ == '__main__': pass",
"label >2 else 0 train_X.append(sentence) train_y.append(label) test_X = [] test_y = [] for",
"= pytreebank.load_sst() def get_sst(cate='5'): train_X = [] train_y = [] for e in",
"label == 2: continue if cate == '2': label = 1 if label"
] |
[
"default=3, metavar='', help='number of input channels') parser.add_argument('--nfilters', type=int, default=64, metavar='', help='number of filters",
"for uniform noise') parser.add_argument('--resolution-high', type=int, default=32, metavar='', help='image resolution height') parser.add_argument('--resolution-wide', type=int, default=32,",
"on gpu') parser.add_argument('--ngpu', type=int, default=1, metavar='', help='number of gpus to use') parser.add_argument('--batch-size', type=int,",
"metavar='', help='label train filename for filelist and folderlist') parser.add_argument('--loader-input', type=str, default=None, metavar='', help='input",
"type=int, default=1, metavar='', help='number of gpus to use') parser.add_argument('--batch-size', type=int, default=64, metavar='', help='batch",
"parser.add_argument('--tau', type=float, default=None, metavar='', help='Tau') # ======================== Training Settings ======================================= parser.add_argument('--cuda', type=bool, default=True,",
"dataset to split') parser.add_argument('--split_train', type=float, default=None, metavar='', help='percentage of train dataset to split')",
"import datetime import argparse result_path = \"results/\" result_path = os.path.join(result_path, datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S/')) parser =",
"# ======================== Data Setings ============================================ parser.add_argument('--dataset-test', type=str, default='CIFAR10', metavar='', help='name of training dataset')",
"loader') # ======================== Network Model Setings =================================== parser.add_argument('--nblocks', type=int, default=10, metavar='', help='number of",
"parser.add_argument('--avgpool', type=int, default=1, metavar='', help='set to 7 for imagenet and 1 for cifar10')",
"metavar='', help='Beta 1 parameter for Adam') parser.add_argument('--adam-beta2', type=float, default=0.999, metavar='', help='Beta 2 parameter",
"help='port for visualizing training at http://localhost:port') # ======================== Hyperparameter Setings ================================== parser.add_argument('--optim-method', type=str,",
"metavar='', help='image resolution height') parser.add_argument('--resolution-wide', type=int, default=32, metavar='', help='image resolution width') parser.add_argument('--ndim', type=int,",
"split') parser.add_argument('--split_train', type=float, default=None, metavar='', help='percentage of train dataset to split') parser.add_argument('--dataroot', type=str,",
"default=result_path +'Save', metavar='', help='save the trained models here') parser.add_argument('--logs', type=str, default=result_path +'Logs', metavar='',",
"help='number of gpus to use') parser.add_argument('--batch-size', type=int, default=64, metavar='', help='batch size for training')",
"and folderlist') parser.add_argument('--input-filename-train', type=str, default=None, metavar='', help='input train filename for filelist and folderlist')",
"metavar='', help='learning rate decay') parser.add_argument('--momentum', type=float, default=0.9, metavar='', help='momentum') parser.add_argument('--weight-decay', type=float, default=1e-4, metavar='',",
"+'Save', metavar='', help='save the trained models here') parser.add_argument('--logs', type=str, default=result_path +'Logs', metavar='', help='save",
"loading') parser.add_argument('--manual-seed', type=int, default=1, metavar='', help='manual seed for randomness') parser.add_argument('--port', type=int, default=8097, metavar='',",
"metavar='', help='name of training dataset') parser.add_argument('--split_test', type=float, default=None, metavar='', help='percentage of test dataset",
"import argparse result_path = \"results/\" result_path = os.path.join(result_path, datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S/')) parser = argparse.ArgumentParser(description='Your project",
"help='weight decay') parser.add_argument('--adam-beta1', type=float, default=0.9, metavar='', help='Beta 1 parameter for Adam') parser.add_argument('--adam-beta2', type=float,",
"Setings ============================================ parser.add_argument('--dataset-test', type=str, default='CIFAR10', metavar='', help='name of training dataset') parser.add_argument('--dataset-train', type=str, default='CIFAR10',",
"to 7 for imagenet and 1 for cifar10') parser.add_argument('--level', type=float, default=0.1, metavar='', help='noise",
"Training Settings ======================================= parser.add_argument('--cuda', type=bool, default=True, metavar='', help='run on gpu') parser.add_argument('--ngpu', type=int, default=1,",
"dataset') parser.add_argument('--split_test', type=float, default=None, metavar='', help='percentage of test dataset to split') parser.add_argument('--split_train', type=float,",
"default=0.9, metavar='', help='Beta 1 parameter for Adam') parser.add_argument('--adam-beta2', type=float, default=0.999, metavar='', help='Beta 2",
"parser.add_argument('--split_test', type=float, default=None, metavar='', help='percentage of test dataset to split') parser.add_argument('--split_train', type=float, default=None,",
"type=str, default='CIFAR10', metavar='', help='name of training dataset') parser.add_argument('--split_test', type=float, default=None, metavar='', help='percentage of",
"type=int, default=20, metavar='', help='number of threads for data loading') parser.add_argument('--manual-seed', type=int, default=1, metavar='',",
"type=float, default=0.9, metavar='', help='Beta 1 parameter for Adam') parser.add_argument('--adam-beta2', type=float, default=0.999, metavar='', help='Beta",
"metavar='', help='label test filename for filelist and folderlist') parser.add_argument('--input-filename-train', type=str, default=None, metavar='', help='input",
"======================== Data Setings ============================================ parser.add_argument('--dataset-test', type=str, default='CIFAR10', metavar='', help='name of training dataset') parser.add_argument('--dataset-train',",
"type=str, default=None, metavar='', help='input test filename for filelist and folderlist') parser.add_argument('--label-filename-test', type=str, default=None,",
"folderlist') parser.add_argument('--loader-input', type=str, default=None, metavar='', help='input loader') parser.add_argument('--loader-label', type=str, default=None, metavar='', help='label loader')",
"default=6, metavar='', help='number of layers') parser.add_argument('--nchannels', type=int, default=3, metavar='', help='number of input channels')",
"help='Tau') # ======================== Training Settings ======================================= parser.add_argument('--cuda', type=bool, default=True, metavar='', help='run on gpu')",
"type=float, default=0.9, metavar='', help='momentum') parser.add_argument('--weight-decay', type=float, default=1e-4, metavar='', help='weight decay') parser.add_argument('--adam-beta1', type=float, default=0.9,",
"type=int, default=64, metavar='', help='number of filters in each layer') parser.add_argument('--avgpool', type=int, default=1, metavar='',",
"default=None, metavar='', help='number of feature dimensions') parser.add_argument('--nunits', type=int, default=None, metavar='', help='number of units",
"type=str, default=None, metavar='', help='full path of models to resume training') parser.add_argument('--nclasses', type=int, default=10,",
"iterations at test time') parser.add_argument('--epoch-number', type=int, default=None, metavar='', help='epoch number') parser.add_argument('--nthreads', type=int, default=20,",
"imagenet and 1 for cifar10') parser.add_argument('--level', type=float, default=0.1, metavar='', help='noise level for uniform",
"default=None, metavar='', help='percentage of test dataset to split') parser.add_argument('--split_train', type=float, default=None, metavar='', help='percentage",
"help='noise level for uniform noise') parser.add_argument('--resolution-high', type=int, default=32, metavar='', help='image resolution height') parser.add_argument('--resolution-wide',",
"to train') parser.add_argument('--niters', type=int, default=None, metavar='', help='number of iterations at test time') parser.add_argument('--epoch-number',",
"of feature dimensions') parser.add_argument('--nunits', type=int, default=None, metavar='', help='number of units in hidden layers')",
"parser.add_argument('--momentum', type=float, default=0.9, metavar='', help='momentum') parser.add_argument('--weight-decay', type=float, default=1e-4, metavar='', help='weight decay') parser.add_argument('--adam-beta1', type=float,",
"help='percentage of test dataset to split') parser.add_argument('--split_train', type=float, default=None, metavar='', help='percentage of train",
"gpu') parser.add_argument('--ngpu', type=int, default=1, metavar='', help='number of gpus to use') parser.add_argument('--batch-size', type=int, default=64,",
"metavar='', help='full path of models to resume training') parser.add_argument('--nclasses', type=int, default=10, metavar='', help='number",
"units in hidden layers') parser.add_argument('--dropout', type=float, default=None, metavar='', help='dropout parameter') parser.add_argument('--net-type', type=str, default='noiseresnet18',",
"metavar='', help='percentage of train dataset to split') parser.add_argument('--dataroot', type=str, default='../../data', metavar='', help='path to",
"type=int, default=None, metavar='', help='number of feature dimensions') parser.add_argument('--nunits', type=int, default=None, metavar='', help='number of",
"metavar='', help='label loader') # ======================== Network Model Setings =================================== parser.add_argument('--nblocks', type=int, default=10, metavar='',",
"here') parser.add_argument('--logs', type=str, default=result_path +'Logs', metavar='', help='save the training log files here') parser.add_argument('--resume',",
"parser.add_argument('--ndim', type=int, default=None, metavar='', help='number of feature dimensions') parser.add_argument('--nunits', type=int, default=None, metavar='', help='number",
"======================== Network Model Setings =================================== parser.add_argument('--nblocks', type=int, default=10, metavar='', help='number of blocks in",
"help='input loader') parser.add_argument('--loader-label', type=str, default=None, metavar='', help='label loader') # ======================== Network Model Setings",
"default=None, metavar='', help='percentage of train dataset to split') parser.add_argument('--dataroot', type=str, default='../../data', metavar='', help='path",
"parser.add_argument('--port', type=int, default=8097, metavar='', help='port for visualizing training at http://localhost:port') # ======================== Hyperparameter",
"parser.add_argument('--nfilters', type=int, default=64, metavar='', help='number of filters in each layer') parser.add_argument('--avgpool', type=int, default=1,",
"result_path = \"results/\" result_path = os.path.join(result_path, datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S/')) parser = argparse.ArgumentParser(description='Your project title goes",
"filename for filelist and folderlist') parser.add_argument('--label-filename-test', type=str, default=None, metavar='', help='label test filename for",
"metavar='', help='noise level for uniform noise') parser.add_argument('--resolution-high', type=int, default=32, metavar='', help='image resolution height')",
"======================== Training Settings ======================================= parser.add_argument('--cuda', type=bool, default=True, metavar='', help='run on gpu') parser.add_argument('--ngpu', type=int,",
"metavar='', help='number of gpus to use') parser.add_argument('--batch-size', type=int, default=64, metavar='', help='batch size for",
"rate') parser.add_argument('--learning-rate-decay', type=float, default=None, metavar='', help='learning rate decay') parser.add_argument('--momentum', type=float, default=0.9, metavar='', help='momentum')",
"type=int, default=64, metavar='', help='batch size for training') parser.add_argument('--nepochs', type=int, default=500, metavar='', help='number of",
"layers') parser.add_argument('--dropout', type=float, default=None, metavar='', help='dropout parameter') parser.add_argument('--net-type', type=str, default='noiseresnet18', metavar='', help='type of",
"============================================ parser.add_argument('--dataset-test', type=str, default='CIFAR10', metavar='', help='name of training dataset') parser.add_argument('--dataset-train', type=str, default='CIFAR10', metavar='',",
"train dataset to split') parser.add_argument('--dataroot', type=str, default='../../data', metavar='', help='path to the data') parser.add_argument('--save',",
"type=str, default=None, metavar='', help='input loader') parser.add_argument('--loader-label', type=str, default=None, metavar='', help='label loader') # ========================",
"import os import datetime import argparse result_path = \"results/\" result_path = os.path.join(result_path, datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S/'))",
"type=str, default=None, metavar='', help='label test filename for filelist and folderlist') parser.add_argument('--input-filename-train', type=str, default=None,",
"to split') parser.add_argument('--split_train', type=float, default=None, metavar='', help='percentage of train dataset to split') parser.add_argument('--dataroot',",
"metavar='', help='number of iterations at test time') parser.add_argument('--epoch-number', type=int, default=None, metavar='', help='epoch number')",
"train filename for filelist and folderlist') parser.add_argument('--loader-input', type=str, default=None, metavar='', help='input loader') parser.add_argument('--loader-label',",
"type=str, default=None, metavar='', help='label loader') # ======================== Network Model Setings =================================== parser.add_argument('--nblocks', type=int,",
"parser.add_argument('--nchannels', type=int, default=3, metavar='', help='number of input channels') parser.add_argument('--nfilters', type=int, default=64, metavar='', help='number",
"gpus to use') parser.add_argument('--batch-size', type=int, default=64, metavar='', help='batch size for training') parser.add_argument('--nepochs', type=int,",
"test dataset to split') parser.add_argument('--split_train', type=float, default=None, metavar='', help='percentage of train dataset to",
"parser.add_argument('--loader-label', type=str, default=None, metavar='', help='label loader') # ======================== Network Model Setings =================================== parser.add_argument('--nblocks',",
"metavar='', help='length scale') parser.add_argument('--tau', type=float, default=None, metavar='', help='Tau') # ======================== Training Settings =======================================",
"for visualizing training at http://localhost:port') # ======================== Hyperparameter Setings ================================== parser.add_argument('--optim-method', type=str, default='Adam',",
"data loading') parser.add_argument('--manual-seed', type=int, default=1, metavar='', help='manual seed for randomness') parser.add_argument('--port', type=int, default=8097,",
"time') parser.add_argument('--epoch-number', type=int, default=None, metavar='', help='epoch number') parser.add_argument('--nthreads', type=int, default=20, metavar='', help='number of",
"channels') parser.add_argument('--nfilters', type=int, default=64, metavar='', help='number of filters in each layer') parser.add_argument('--avgpool', type=int,",
"Setings =================================== parser.add_argument('--nblocks', type=int, default=10, metavar='', help='number of blocks in each layer') parser.add_argument('--nlayers',",
"metavar='', help='number of layers') parser.add_argument('--nchannels', type=int, default=3, metavar='', help='number of input channels') parser.add_argument('--nfilters',",
"metavar='', help='Tau') # ======================== Training Settings ======================================= parser.add_argument('--cuda', type=bool, default=True, metavar='', help='run on",
"layer') parser.add_argument('--nlayers', type=int, default=6, metavar='', help='number of layers') parser.add_argument('--nchannels', type=int, default=3, metavar='', help='number",
"loader') parser.add_argument('--loader-label', type=str, default=None, metavar='', help='label loader') # ======================== Network Model Setings ===================================",
"type=int, default=10, metavar='', help='number of blocks in each layer') parser.add_argument('--nlayers', type=int, default=6, metavar='',",
"parser.add_argument('--niters', type=int, default=None, metavar='', help='number of iterations at test time') parser.add_argument('--epoch-number', type=int, default=None,",
"help='batch size for training') parser.add_argument('--nepochs', type=int, default=500, metavar='', help='number of epochs to train')",
"======================== Hyperparameter Setings ================================== parser.add_argument('--optim-method', type=str, default='Adam', metavar='', help='the optimization routine ') parser.add_argument('--learning-rate',",
"default='noiseresnet18', metavar='', help='type of network') parser.add_argument('--length-scale', type=float, default=None, metavar='', help='length scale') parser.add_argument('--tau', type=float,",
"default=None, metavar='', help='full path of models to resume training') parser.add_argument('--nclasses', type=int, default=10, metavar='',",
"default=64, metavar='', help='number of filters in each layer') parser.add_argument('--avgpool', type=int, default=1, metavar='', help='set",
"folderlist') parser.add_argument('--label-filename-train', type=str, default=None, metavar='', help='label train filename for filelist and folderlist') parser.add_argument('--loader-input',",
"+'Logs', metavar='', help='save the training log files here') parser.add_argument('--resume', type=str, default=None, metavar='', help='full",
"help='dropout parameter') parser.add_argument('--net-type', type=str, default='noiseresnet18', metavar='', help='type of network') parser.add_argument('--length-scale', type=float, default=None, metavar='',",
"number') parser.add_argument('--nthreads', type=int, default=20, metavar='', help='number of threads for data loading') parser.add_argument('--manual-seed', type=int,",
"resolution height') parser.add_argument('--resolution-wide', type=int, default=32, metavar='', help='image resolution width') parser.add_argument('--ndim', type=int, default=None, metavar='',",
"argparse.ArgumentParser(description='Your project title goes here') # ======================== Data Setings ============================================ parser.add_argument('--dataset-test', type=str, default='CIFAR10',",
"filename for filelist and folderlist') parser.add_argument('--label-filename-train', type=str, default=None, metavar='', help='label train filename for",
"type=float, default=1e-3, metavar='', help='learning rate') parser.add_argument('--learning-rate-decay', type=float, default=None, metavar='', help='learning rate decay') parser.add_argument('--momentum',",
"for filelist and folderlist') parser.add_argument('--input-filename-train', type=str, default=None, metavar='', help='input train filename for filelist",
"help='name of training dataset') parser.add_argument('--dataset-train', type=str, default='CIFAR10', metavar='', help='name of training dataset') parser.add_argument('--split_test',",
"and folderlist') parser.add_argument('--label-filename-test', type=str, default=None, metavar='', help='label test filename for filelist and folderlist')",
"and folderlist') parser.add_argument('--label-filename-train', type=str, default=None, metavar='', help='label train filename for filelist and folderlist')",
"help='run on gpu') parser.add_argument('--ngpu', type=int, default=1, metavar='', help='number of gpus to use') parser.add_argument('--batch-size',",
"datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S/')) parser = argparse.ArgumentParser(description='Your project title goes here') # ======================== Data Setings ============================================",
"metavar='', help='number of epochs to train') parser.add_argument('--niters', type=int, default=None, metavar='', help='number of iterations",
"to use') parser.add_argument('--batch-size', type=int, default=64, metavar='', help='batch size for training') parser.add_argument('--nepochs', type=int, default=500,",
"parser.add_argument('--learning-rate', type=float, default=1e-3, metavar='', help='learning rate') parser.add_argument('--learning-rate-decay', type=float, default=None, metavar='', help='learning rate decay')",
"and 1 for cifar10') parser.add_argument('--level', type=float, default=0.1, metavar='', help='noise level for uniform noise')",
"help='image resolution height') parser.add_argument('--resolution-wide', type=int, default=32, metavar='', help='image resolution width') parser.add_argument('--ndim', type=int, default=None,",
"classes for classification') parser.add_argument('--input-filename-test', type=str, default=None, metavar='', help='input test filename for filelist and",
"in each layer') parser.add_argument('--avgpool', type=int, default=1, metavar='', help='set to 7 for imagenet and",
"blocks in each layer') parser.add_argument('--nlayers', type=int, default=6, metavar='', help='number of layers') parser.add_argument('--nchannels', type=int,",
"optimization routine ') parser.add_argument('--learning-rate', type=float, default=1e-3, metavar='', help='learning rate') parser.add_argument('--learning-rate-decay', type=float, default=None, metavar='',",
"type=float, default=None, metavar='', help='Tau') # ======================== Training Settings ======================================= parser.add_argument('--cuda', type=bool, default=True, metavar='',",
"metavar='', help='batch size for training') parser.add_argument('--nepochs', type=int, default=500, metavar='', help='number of epochs to",
"help='number of blocks in each layer') parser.add_argument('--nlayers', type=int, default=6, metavar='', help='number of layers')",
"metavar='', help='dropout parameter') parser.add_argument('--net-type', type=str, default='noiseresnet18', metavar='', help='type of network') parser.add_argument('--length-scale', type=float, default=None,",
"epochs to train') parser.add_argument('--niters', type=int, default=None, metavar='', help='number of iterations at test time')",
"training dataset') parser.add_argument('--split_test', type=float, default=None, metavar='', help='percentage of test dataset to split') parser.add_argument('--split_train',",
"test filename for filelist and folderlist') parser.add_argument('--label-filename-test', type=str, default=None, metavar='', help='label test filename",
"training') parser.add_argument('--nclasses', type=int, default=10, metavar='', help='number of classes for classification') parser.add_argument('--input-filename-test', type=str, default=None,",
"for filelist and folderlist') parser.add_argument('--label-filename-train', type=str, default=None, metavar='', help='label train filename for filelist",
"default=32, metavar='', help='image resolution width') parser.add_argument('--ndim', type=int, default=None, metavar='', help='number of feature dimensions')",
"metavar='', help='number of threads for data loading') parser.add_argument('--manual-seed', type=int, default=1, metavar='', help='manual seed",
"of epochs to train') parser.add_argument('--niters', type=int, default=None, metavar='', help='number of iterations at test",
"each layer') parser.add_argument('--avgpool', type=int, default=1, metavar='', help='set to 7 for imagenet and 1",
"parser.add_argument('--batch-size', type=int, default=64, metavar='', help='batch size for training') parser.add_argument('--nepochs', type=int, default=500, metavar='', help='number",
"resume training') parser.add_argument('--nclasses', type=int, default=10, metavar='', help='number of classes for classification') parser.add_argument('--input-filename-test', type=str,",
"type=float, default=None, metavar='', help='percentage of test dataset to split') parser.add_argument('--split_train', type=float, default=None, metavar='',",
"of threads for data loading') parser.add_argument('--manual-seed', type=int, default=1, metavar='', help='manual seed for randomness')",
"metavar='', help='momentum') parser.add_argument('--weight-decay', type=float, default=1e-4, metavar='', help='weight decay') parser.add_argument('--adam-beta1', type=float, default=0.9, metavar='', help='Beta",
"help='full path of models to resume training') parser.add_argument('--nclasses', type=int, default=10, metavar='', help='number of",
"metavar='', help='epoch number') parser.add_argument('--nthreads', type=int, default=20, metavar='', help='number of threads for data loading')",
"filename for filelist and folderlist') parser.add_argument('--loader-input', type=str, default=None, metavar='', help='input loader') parser.add_argument('--loader-label', type=str,",
"training dataset') parser.add_argument('--dataset-train', type=str, default='CIFAR10', metavar='', help='name of training dataset') parser.add_argument('--split_test', type=float, default=None,",
"trained models here') parser.add_argument('--logs', type=str, default=result_path +'Logs', metavar='', help='save the training log files",
"hidden layers') parser.add_argument('--dropout', type=float, default=None, metavar='', help='dropout parameter') parser.add_argument('--net-type', type=str, default='noiseresnet18', metavar='', help='type",
"type=str, default=result_path +'Save', metavar='', help='save the trained models here') parser.add_argument('--logs', type=str, default=result_path +'Logs',",
"project title goes here') # ======================== Data Setings ============================================ parser.add_argument('--dataset-test', type=str, default='CIFAR10', metavar='',",
"parser.add_argument('--resolution-high', type=int, default=32, metavar='', help='image resolution height') parser.add_argument('--resolution-wide', type=int, default=32, metavar='', help='image resolution",
"') parser.add_argument('--learning-rate', type=float, default=1e-3, metavar='', help='learning rate') parser.add_argument('--learning-rate-decay', type=float, default=None, metavar='', help='learning rate",
"metavar='', help='save the training log files here') parser.add_argument('--resume', type=str, default=None, metavar='', help='full path",
"default=0.1, metavar='', help='noise level for uniform noise') parser.add_argument('--resolution-high', type=int, default=32, metavar='', help='image resolution",
"folderlist') parser.add_argument('--label-filename-test', type=str, default=None, metavar='', help='label test filename for filelist and folderlist') parser.add_argument('--input-filename-train',",
"type=str, default=None, metavar='', help='input train filename for filelist and folderlist') parser.add_argument('--label-filename-train', type=str, default=None,",
"parser.add_argument('--epoch-number', type=int, default=None, metavar='', help='epoch number') parser.add_argument('--nthreads', type=int, default=20, metavar='', help='number of threads",
"parser.add_argument('--dataroot', type=str, default='../../data', metavar='', help='path to the data') parser.add_argument('--save', type=str, default=result_path +'Save', metavar='',",
"parser.add_argument('--learning-rate-decay', type=float, default=None, metavar='', help='learning rate decay') parser.add_argument('--momentum', type=float, default=0.9, metavar='', help='momentum') parser.add_argument('--weight-decay',",
"help='path to the data') parser.add_argument('--save', type=str, default=result_path +'Save', metavar='', help='save the trained models",
"parser.add_argument('--input-filename-test', type=str, default=None, metavar='', help='input test filename for filelist and folderlist') parser.add_argument('--label-filename-test', type=str,",
"help='label test filename for filelist and folderlist') parser.add_argument('--input-filename-train', type=str, default=None, metavar='', help='input train",
"Model Setings =================================== parser.add_argument('--nblocks', type=int, default=10, metavar='', help='number of blocks in each layer')",
"parser.add_argument('--dataset-test', type=str, default='CIFAR10', metavar='', help='name of training dataset') parser.add_argument('--dataset-train', type=str, default='CIFAR10', metavar='', help='name",
"network') parser.add_argument('--length-scale', type=float, default=None, metavar='', help='length scale') parser.add_argument('--tau', type=float, default=None, metavar='', help='Tau') #",
"metavar='', help='input test filename for filelist and folderlist') parser.add_argument('--label-filename-test', type=str, default=None, metavar='', help='label",
"type=str, default='Adam', metavar='', help='the optimization routine ') parser.add_argument('--learning-rate', type=float, default=1e-3, metavar='', help='learning rate')",
"# ======================== Training Settings ======================================= parser.add_argument('--cuda', type=bool, default=True, metavar='', help='run on gpu') parser.add_argument('--ngpu',",
"parser.add_argument('--adam-beta1', type=float, default=0.9, metavar='', help='Beta 1 parameter for Adam') parser.add_argument('--adam-beta2', type=float, default=0.999, metavar='',",
"metavar='', help='number of input channels') parser.add_argument('--nfilters', type=int, default=64, metavar='', help='number of filters in",
"of training dataset') parser.add_argument('--split_test', type=float, default=None, metavar='', help='percentage of test dataset to split')",
"at http://localhost:port') # ======================== Hyperparameter Setings ================================== parser.add_argument('--optim-method', type=str, default='Adam', metavar='', help='the optimization",
"help='length scale') parser.add_argument('--tau', type=float, default=None, metavar='', help='Tau') # ======================== Training Settings ======================================= parser.add_argument('--cuda',",
"help='number of filters in each layer') parser.add_argument('--avgpool', type=int, default=1, metavar='', help='set to 7",
"size for training') parser.add_argument('--nepochs', type=int, default=500, metavar='', help='number of epochs to train') parser.add_argument('--niters',",
"of test dataset to split') parser.add_argument('--split_train', type=float, default=None, metavar='', help='percentage of train dataset",
"parser.add_argument('--split_train', type=float, default=None, metavar='', help='percentage of train dataset to split') parser.add_argument('--dataroot', type=str, default='../../data',",
"models here') parser.add_argument('--logs', type=str, default=result_path +'Logs', metavar='', help='save the training log files here')",
"default=None, metavar='', help='length scale') parser.add_argument('--tau', type=float, default=None, metavar='', help='Tau') # ======================== Training Settings",
"default='Adam', metavar='', help='the optimization routine ') parser.add_argument('--learning-rate', type=float, default=1e-3, metavar='', help='learning rate') parser.add_argument('--learning-rate-decay',",
"type=int, default=8097, metavar='', help='port for visualizing training at http://localhost:port') # ======================== Hyperparameter Setings",
"metavar='', help='type of network') parser.add_argument('--length-scale', type=float, default=None, metavar='', help='length scale') parser.add_argument('--tau', type=float, default=None,",
"type=str, default='noiseresnet18', metavar='', help='type of network') parser.add_argument('--length-scale', type=float, default=None, metavar='', help='length scale') parser.add_argument('--tau',",
"help='number of epochs to train') parser.add_argument('--niters', type=int, default=None, metavar='', help='number of iterations at",
"os import datetime import argparse result_path = \"results/\" result_path = os.path.join(result_path, datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S/')) parser",
"default=1e-4, metavar='', help='weight decay') parser.add_argument('--adam-beta1', type=float, default=0.9, metavar='', help='Beta 1 parameter for Adam')",
"goes here') # ======================== Data Setings ============================================ parser.add_argument('--dataset-test', type=str, default='CIFAR10', metavar='', help='name of",
"data') parser.add_argument('--save', type=str, default=result_path +'Save', metavar='', help='save the trained models here') parser.add_argument('--logs', type=str,",
"type=int, default=3, metavar='', help='number of input channels') parser.add_argument('--nfilters', type=int, default=64, metavar='', help='number of",
"default=64, metavar='', help='batch size for training') parser.add_argument('--nepochs', type=int, default=500, metavar='', help='number of epochs",
"of gpus to use') parser.add_argument('--batch-size', type=int, default=64, metavar='', help='batch size for training') parser.add_argument('--nepochs',",
"of iterations at test time') parser.add_argument('--epoch-number', type=int, default=None, metavar='', help='epoch number') parser.add_argument('--nthreads', type=int,",
"parser.add_argument('--nblocks', type=int, default=10, metavar='', help='number of blocks in each layer') parser.add_argument('--nlayers', type=int, default=6,",
"parser.add_argument('--dataset-train', type=str, default='CIFAR10', metavar='', help='name of training dataset') parser.add_argument('--split_test', type=float, default=None, metavar='', help='percentage",
"default='CIFAR10', metavar='', help='name of training dataset') parser.add_argument('--split_test', type=float, default=None, metavar='', help='percentage of test",
"path of models to resume training') parser.add_argument('--nclasses', type=int, default=10, metavar='', help='number of classes",
"Setings ================================== parser.add_argument('--optim-method', type=str, default='Adam', metavar='', help='the optimization routine ') parser.add_argument('--learning-rate', type=float, default=1e-3,",
"parser.add_argument('--level', type=float, default=0.1, metavar='', help='noise level for uniform noise') parser.add_argument('--resolution-high', type=int, default=32, metavar='',",
"default='CIFAR10', metavar='', help='name of training dataset') parser.add_argument('--dataset-train', type=str, default='CIFAR10', metavar='', help='name of training",
"to split') parser.add_argument('--dataroot', type=str, default='../../data', metavar='', help='path to the data') parser.add_argument('--save', type=str, default=result_path",
"parser.add_argument('--label-filename-test', type=str, default=None, metavar='', help='label test filename for filelist and folderlist') parser.add_argument('--input-filename-train', type=str,",
"layer') parser.add_argument('--avgpool', type=int, default=1, metavar='', help='set to 7 for imagenet and 1 for",
"of network') parser.add_argument('--length-scale', type=float, default=None, metavar='', help='length scale') parser.add_argument('--tau', type=float, default=None, metavar='', help='Tau')",
"help='manual seed for randomness') parser.add_argument('--port', type=int, default=8097, metavar='', help='port for visualizing training at",
"metavar='', help='number of blocks in each layer') parser.add_argument('--nlayers', type=int, default=6, metavar='', help='number of",
"filename for filelist and folderlist') parser.add_argument('--input-filename-train', type=str, default=None, metavar='', help='input train filename for",
"parser.add_argument('--input-filename-train', type=str, default=None, metavar='', help='input train filename for filelist and folderlist') parser.add_argument('--label-filename-train', type=str,",
"of filters in each layer') parser.add_argument('--avgpool', type=int, default=1, metavar='', help='set to 7 for",
"default=1e-3, metavar='', help='learning rate') parser.add_argument('--learning-rate-decay', type=float, default=None, metavar='', help='learning rate decay') parser.add_argument('--momentum', type=float,",
"os.path.join(result_path, datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S/')) parser = argparse.ArgumentParser(description='Your project title goes here') # ======================== Data Setings",
"for classification') parser.add_argument('--input-filename-test', type=str, default=None, metavar='', help='input test filename for filelist and folderlist')",
"and folderlist') parser.add_argument('--loader-input', type=str, default=None, metavar='', help='input loader') parser.add_argument('--loader-label', type=str, default=None, metavar='', help='label",
"\"results/\" result_path = os.path.join(result_path, datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S/')) parser = argparse.ArgumentParser(description='Your project title goes here') #",
"config.py import os import datetime import argparse result_path = \"results/\" result_path = os.path.join(result_path,",
"randomness') parser.add_argument('--port', type=int, default=8097, metavar='', help='port for visualizing training at http://localhost:port') # ========================",
"type=str, default=None, metavar='', help='label train filename for filelist and folderlist') parser.add_argument('--loader-input', type=str, default=None,",
"default=8097, metavar='', help='port for visualizing training at http://localhost:port') # ======================== Hyperparameter Setings ==================================",
"parser.add_argument('--nepochs', type=int, default=500, metavar='', help='number of epochs to train') parser.add_argument('--niters', type=int, default=None, metavar='',",
"in hidden layers') parser.add_argument('--dropout', type=float, default=None, metavar='', help='dropout parameter') parser.add_argument('--net-type', type=str, default='noiseresnet18', metavar='',",
"uniform noise') parser.add_argument('--resolution-high', type=int, default=32, metavar='', help='image resolution height') parser.add_argument('--resolution-wide', type=int, default=32, metavar='',",
"type=int, default=500, metavar='', help='number of epochs to train') parser.add_argument('--niters', type=int, default=None, metavar='', help='number",
"rate decay') parser.add_argument('--momentum', type=float, default=0.9, metavar='', help='momentum') parser.add_argument('--weight-decay', type=float, default=1e-4, metavar='', help='weight decay')",
"parser.add_argument('--length-scale', type=float, default=None, metavar='', help='length scale') parser.add_argument('--tau', type=float, default=None, metavar='', help='Tau') # ========================",
"width') parser.add_argument('--ndim', type=int, default=None, metavar='', help='number of feature dimensions') parser.add_argument('--nunits', type=int, default=None, metavar='',",
"routine ') parser.add_argument('--learning-rate', type=float, default=1e-3, metavar='', help='learning rate') parser.add_argument('--learning-rate-decay', type=float, default=None, metavar='', help='learning",
"filelist and folderlist') parser.add_argument('--label-filename-test', type=str, default=None, metavar='', help='label test filename for filelist and",
"split') parser.add_argument('--dataroot', type=str, default='../../data', metavar='', help='path to the data') parser.add_argument('--save', type=str, default=result_path +'Save',",
"dataset to split') parser.add_argument('--dataroot', type=str, default='../../data', metavar='', help='path to the data') parser.add_argument('--save', type=str,",
"type=int, default=1, metavar='', help='manual seed for randomness') parser.add_argument('--port', type=int, default=8097, metavar='', help='port for",
"help='input test filename for filelist and folderlist') parser.add_argument('--label-filename-test', type=str, default=None, metavar='', help='label test",
"of classes for classification') parser.add_argument('--input-filename-test', type=str, default=None, metavar='', help='input test filename for filelist",
"of train dataset to split') parser.add_argument('--dataroot', type=str, default='../../data', metavar='', help='path to the data')",
"for filelist and folderlist') parser.add_argument('--loader-input', type=str, default=None, metavar='', help='input loader') parser.add_argument('--loader-label', type=str, default=None,",
"dimensions') parser.add_argument('--nunits', type=int, default=None, metavar='', help='number of units in hidden layers') parser.add_argument('--dropout', type=float,",
"= \"results/\" result_path = os.path.join(result_path, datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S/')) parser = argparse.ArgumentParser(description='Your project title goes here')",
"each layer') parser.add_argument('--nlayers', type=int, default=6, metavar='', help='number of layers') parser.add_argument('--nchannels', type=int, default=3, metavar='',",
"default=10, metavar='', help='number of blocks in each layer') parser.add_argument('--nlayers', type=int, default=6, metavar='', help='number",
"parser.add_argument('--net-type', type=str, default='noiseresnet18', metavar='', help='type of network') parser.add_argument('--length-scale', type=float, default=None, metavar='', help='length scale')",
"default=1, metavar='', help='manual seed for randomness') parser.add_argument('--port', type=int, default=8097, metavar='', help='port for visualizing",
"here') # ======================== Data Setings ============================================ parser.add_argument('--dataset-test', type=str, default='CIFAR10', metavar='', help='name of training",
"help='label train filename for filelist and folderlist') parser.add_argument('--loader-input', type=str, default=None, metavar='', help='input loader')",
"seed for randomness') parser.add_argument('--port', type=int, default=8097, metavar='', help='port for visualizing training at http://localhost:port')",
"to resume training') parser.add_argument('--nclasses', type=int, default=10, metavar='', help='number of classes for classification') parser.add_argument('--input-filename-test',",
"training at http://localhost:port') # ======================== Hyperparameter Setings ================================== parser.add_argument('--optim-method', type=str, default='Adam', metavar='', help='the",
"for imagenet and 1 for cifar10') parser.add_argument('--level', type=float, default=0.1, metavar='', help='noise level for",
"help='Beta 1 parameter for Adam') parser.add_argument('--adam-beta2', type=float, default=0.999, metavar='', help='Beta 2 parameter for",
"training') parser.add_argument('--nepochs', type=int, default=500, metavar='', help='number of epochs to train') parser.add_argument('--niters', type=int, default=None,",
"default=1, metavar='', help='set to 7 for imagenet and 1 for cifar10') parser.add_argument('--level', type=float,",
"# ======================== Hyperparameter Setings ================================== parser.add_argument('--optim-method', type=str, default='Adam', metavar='', help='the optimization routine ')",
"default=None, metavar='', help='number of iterations at test time') parser.add_argument('--epoch-number', type=int, default=None, metavar='', help='epoch",
"Settings ======================================= parser.add_argument('--cuda', type=bool, default=True, metavar='', help='run on gpu') parser.add_argument('--ngpu', type=int, default=1, metavar='',",
"for data loading') parser.add_argument('--manual-seed', type=int, default=1, metavar='', help='manual seed for randomness') parser.add_argument('--port', type=int,",
"metavar='', help='port for visualizing training at http://localhost:port') # ======================== Hyperparameter Setings ================================== parser.add_argument('--optim-method',",
"the trained models here') parser.add_argument('--logs', type=str, default=result_path +'Logs', metavar='', help='save the training log",
"help='momentum') parser.add_argument('--weight-decay', type=float, default=1e-4, metavar='', help='weight decay') parser.add_argument('--adam-beta1', type=float, default=0.9, metavar='', help='Beta 1",
"parser.add_argument('--optim-method', type=str, default='Adam', metavar='', help='the optimization routine ') parser.add_argument('--learning-rate', type=float, default=1e-3, metavar='', help='learning",
"cifar10') parser.add_argument('--level', type=float, default=0.1, metavar='', help='noise level for uniform noise') parser.add_argument('--resolution-high', type=int, default=32,",
"help='number of iterations at test time') parser.add_argument('--epoch-number', type=int, default=None, metavar='', help='epoch number') parser.add_argument('--nthreads',",
"at test time') parser.add_argument('--epoch-number', type=int, default=None, metavar='', help='epoch number') parser.add_argument('--nthreads', type=int, default=20, metavar='',",
"parser.add_argument('--logs', type=str, default=result_path +'Logs', metavar='', help='save the training log files here') parser.add_argument('--resume', type=str,",
"test time') parser.add_argument('--epoch-number', type=int, default=None, metavar='', help='epoch number') parser.add_argument('--nthreads', type=int, default=20, metavar='', help='number",
"threads for data loading') parser.add_argument('--manual-seed', type=int, default=1, metavar='', help='manual seed for randomness') parser.add_argument('--port',",
"parser = argparse.ArgumentParser(description='Your project title goes here') # ======================== Data Setings ============================================ parser.add_argument('--dataset-test',",
"help='label loader') # ======================== Network Model Setings =================================== parser.add_argument('--nblocks', type=int, default=10, metavar='', help='number",
"argparse result_path = \"results/\" result_path = os.path.join(result_path, datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S/')) parser = argparse.ArgumentParser(description='Your project title",
"metavar='', help='number of feature dimensions') parser.add_argument('--nunits', type=int, default=None, metavar='', help='number of units in",
"for cifar10') parser.add_argument('--level', type=float, default=0.1, metavar='', help='noise level for uniform noise') parser.add_argument('--resolution-high', type=int,",
"metavar='', help='name of training dataset') parser.add_argument('--dataset-train', type=str, default='CIFAR10', metavar='', help='name of training dataset')",
"======================================= parser.add_argument('--cuda', type=bool, default=True, metavar='', help='run on gpu') parser.add_argument('--ngpu', type=int, default=1, metavar='', help='number",
"default=True, metavar='', help='run on gpu') parser.add_argument('--ngpu', type=int, default=1, metavar='', help='number of gpus to",
"for Adam') parser.add_argument('--adam-beta2', type=float, default=0.999, metavar='', help='Beta 2 parameter for Adam') args =",
"default=None, metavar='', help='dropout parameter') parser.add_argument('--net-type', type=str, default='noiseresnet18', metavar='', help='type of network') parser.add_argument('--length-scale', type=float,",
"parser.add_argument('--cuda', type=bool, default=True, metavar='', help='run on gpu') parser.add_argument('--ngpu', type=int, default=1, metavar='', help='number of",
"parser.add_argument('--resolution-wide', type=int, default=32, metavar='', help='image resolution width') parser.add_argument('--ndim', type=int, default=None, metavar='', help='number of",
"test filename for filelist and folderlist') parser.add_argument('--input-filename-train', type=str, default=None, metavar='', help='input train filename",
"default=None, metavar='', help='label train filename for filelist and folderlist') parser.add_argument('--loader-input', type=str, default=None, metavar='',",
"default='../../data', metavar='', help='path to the data') parser.add_argument('--save', type=str, default=result_path +'Save', metavar='', help='save the",
"use') parser.add_argument('--batch-size', type=int, default=64, metavar='', help='batch size for training') parser.add_argument('--nepochs', type=int, default=500, metavar='',",
"=================================== parser.add_argument('--nblocks', type=int, default=10, metavar='', help='number of blocks in each layer') parser.add_argument('--nlayers', type=int,",
"type=int, default=32, metavar='', help='image resolution width') parser.add_argument('--ndim', type=int, default=None, metavar='', help='number of feature",
"help='number of layers') parser.add_argument('--nchannels', type=int, default=3, metavar='', help='number of input channels') parser.add_argument('--nfilters', type=int,",
"files here') parser.add_argument('--resume', type=str, default=None, metavar='', help='full path of models to resume training')",
"parser.add_argument('--loader-input', type=str, default=None, metavar='', help='input loader') parser.add_argument('--loader-label', type=str, default=None, metavar='', help='label loader') #",
"help='number of classes for classification') parser.add_argument('--input-filename-test', type=str, default=None, metavar='', help='input test filename for",
"type=str, default='../../data', metavar='', help='path to the data') parser.add_argument('--save', type=str, default=result_path +'Save', metavar='', help='save",
"feature dimensions') parser.add_argument('--nunits', type=int, default=None, metavar='', help='number of units in hidden layers') parser.add_argument('--dropout',",
"help='number of threads for data loading') parser.add_argument('--manual-seed', type=int, default=1, metavar='', help='manual seed for",
"default=32, metavar='', help='image resolution height') parser.add_argument('--resolution-wide', type=int, default=32, metavar='', help='image resolution width') parser.add_argument('--ndim',",
"type=int, default=None, metavar='', help='epoch number') parser.add_argument('--nthreads', type=int, default=20, metavar='', help='number of threads for",
"type=str, default=result_path +'Logs', metavar='', help='save the training log files here') parser.add_argument('--resume', type=str, default=None,",
"type=str, default='CIFAR10', metavar='', help='name of training dataset') parser.add_argument('--dataset-train', type=str, default='CIFAR10', metavar='', help='name of",
"parser.add_argument('--manual-seed', type=int, default=1, metavar='', help='manual seed for randomness') parser.add_argument('--port', type=int, default=8097, metavar='', help='port",
"7 for imagenet and 1 for cifar10') parser.add_argument('--level', type=float, default=0.1, metavar='', help='noise level",
"metavar='', help='save the trained models here') parser.add_argument('--logs', type=str, default=result_path +'Logs', metavar='', help='save the",
"default=None, metavar='', help='input test filename for filelist and folderlist') parser.add_argument('--label-filename-test', type=str, default=None, metavar='',",
"decay') parser.add_argument('--adam-beta1', type=float, default=0.9, metavar='', help='Beta 1 parameter for Adam') parser.add_argument('--adam-beta2', type=float, default=0.999,",
"type=float, default=None, metavar='', help='percentage of train dataset to split') parser.add_argument('--dataroot', type=str, default='../../data', metavar='',",
"1 for cifar10') parser.add_argument('--level', type=float, default=0.1, metavar='', help='noise level for uniform noise') parser.add_argument('--resolution-high',",
"default=None, metavar='', help='learning rate decay') parser.add_argument('--momentum', type=float, default=0.9, metavar='', help='momentum') parser.add_argument('--weight-decay', type=float, default=1e-4,",
"height') parser.add_argument('--resolution-wide', type=int, default=32, metavar='', help='image resolution width') parser.add_argument('--ndim', type=int, default=None, metavar='', help='number",
"parser.add_argument('--nunits', type=int, default=None, metavar='', help='number of units in hidden layers') parser.add_argument('--dropout', type=float, default=None,",
"metavar='', help='manual seed for randomness') parser.add_argument('--port', type=int, default=8097, metavar='', help='port for visualizing training",
"default=20, metavar='', help='number of threads for data loading') parser.add_argument('--manual-seed', type=int, default=1, metavar='', help='manual",
"decay') parser.add_argument('--momentum', type=float, default=0.9, metavar='', help='momentum') parser.add_argument('--weight-decay', type=float, default=1e-4, metavar='', help='weight decay') parser.add_argument('--adam-beta1',",
"filters in each layer') parser.add_argument('--avgpool', type=int, default=1, metavar='', help='set to 7 for imagenet",
"type=int, default=None, metavar='', help='number of units in hidden layers') parser.add_argument('--dropout', type=float, default=None, metavar='',",
"parameter') parser.add_argument('--net-type', type=str, default='noiseresnet18', metavar='', help='type of network') parser.add_argument('--length-scale', type=float, default=None, metavar='', help='length",
"metavar='', help='input loader') parser.add_argument('--loader-label', type=str, default=None, metavar='', help='label loader') # ======================== Network Model",
"help='number of input channels') parser.add_argument('--nfilters', type=int, default=64, metavar='', help='number of filters in each",
"of units in hidden layers') parser.add_argument('--dropout', type=float, default=None, metavar='', help='dropout parameter') parser.add_argument('--net-type', type=str,",
"metavar='', help='image resolution width') parser.add_argument('--ndim', type=int, default=None, metavar='', help='number of feature dimensions') parser.add_argument('--nunits',",
"default=None, metavar='', help='Tau') # ======================== Training Settings ======================================= parser.add_argument('--cuda', type=bool, default=True, metavar='', help='run",
"scale') parser.add_argument('--tau', type=float, default=None, metavar='', help='Tau') # ======================== Training Settings ======================================= parser.add_argument('--cuda', type=bool,",
"help='learning rate decay') parser.add_argument('--momentum', type=float, default=0.9, metavar='', help='momentum') parser.add_argument('--weight-decay', type=float, default=1e-4, metavar='', help='weight",
"the training log files here') parser.add_argument('--resume', type=str, default=None, metavar='', help='full path of models",
"filelist and folderlist') parser.add_argument('--input-filename-train', type=str, default=None, metavar='', help='input train filename for filelist and",
"type=float, default=1e-4, metavar='', help='weight decay') parser.add_argument('--adam-beta1', type=float, default=0.9, metavar='', help='Beta 1 parameter for",
"classification') parser.add_argument('--input-filename-test', type=str, default=None, metavar='', help='input test filename for filelist and folderlist') parser.add_argument('--label-filename-test',",
"here') parser.add_argument('--resume', type=str, default=None, metavar='', help='full path of models to resume training') parser.add_argument('--nclasses',",
"filelist and folderlist') parser.add_argument('--loader-input', type=str, default=None, metavar='', help='input loader') parser.add_argument('--loader-label', type=str, default=None, metavar='',",
"parameter for Adam') parser.add_argument('--adam-beta2', type=float, default=0.999, metavar='', help='Beta 2 parameter for Adam') args",
"default=None, metavar='', help='input train filename for filelist and folderlist') parser.add_argument('--label-filename-train', type=str, default=None, metavar='',",
"train') parser.add_argument('--niters', type=int, default=None, metavar='', help='number of iterations at test time') parser.add_argument('--epoch-number', type=int,",
"parser.add_argument('--nclasses', type=int, default=10, metavar='', help='number of classes for classification') parser.add_argument('--input-filename-test', type=str, default=None, metavar='',",
"filelist and folderlist') parser.add_argument('--label-filename-train', type=str, default=None, metavar='', help='label train filename for filelist and",
"parser.add_argument('--label-filename-train', type=str, default=None, metavar='', help='label train filename for filelist and folderlist') parser.add_argument('--loader-input', type=str,",
"parser.add_argument('--dropout', type=float, default=None, metavar='', help='dropout parameter') parser.add_argument('--net-type', type=str, default='noiseresnet18', metavar='', help='type of network')",
"default=0.9, metavar='', help='momentum') parser.add_argument('--weight-decay', type=float, default=1e-4, metavar='', help='weight decay') parser.add_argument('--adam-beta1', type=float, default=0.9, metavar='',",
"training log files here') parser.add_argument('--resume', type=str, default=None, metavar='', help='full path of models to",
"metavar='', help='run on gpu') parser.add_argument('--ngpu', type=int, default=1, metavar='', help='number of gpus to use')",
"title goes here') # ======================== Data Setings ============================================ parser.add_argument('--dataset-test', type=str, default='CIFAR10', metavar='', help='name",
"datetime import argparse result_path = \"results/\" result_path = os.path.join(result_path, datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S/')) parser = argparse.ArgumentParser(description='Your",
"type=int, default=10, metavar='', help='number of classes for classification') parser.add_argument('--input-filename-test', type=str, default=None, metavar='', help='input",
"noise') parser.add_argument('--resolution-high', type=int, default=32, metavar='', help='image resolution height') parser.add_argument('--resolution-wide', type=int, default=32, metavar='', help='image",
"type=float, default=0.1, metavar='', help='noise level for uniform noise') parser.add_argument('--resolution-high', type=int, default=32, metavar='', help='image",
"# ======================== Network Model Setings =================================== parser.add_argument('--nblocks', type=int, default=10, metavar='', help='number of blocks",
"default=500, metavar='', help='number of epochs to train') parser.add_argument('--niters', type=int, default=None, metavar='', help='number of",
"metavar='', help='the optimization routine ') parser.add_argument('--learning-rate', type=float, default=1e-3, metavar='', help='learning rate') parser.add_argument('--learning-rate-decay', type=float,",
"metavar='', help='weight decay') parser.add_argument('--adam-beta1', type=float, default=0.9, metavar='', help='Beta 1 parameter for Adam') parser.add_argument('--adam-beta2',",
"of input channels') parser.add_argument('--nfilters', type=int, default=64, metavar='', help='number of filters in each layer')",
"default=1, metavar='', help='number of gpus to use') parser.add_argument('--batch-size', type=int, default=64, metavar='', help='batch size",
"of layers') parser.add_argument('--nchannels', type=int, default=3, metavar='', help='number of input channels') parser.add_argument('--nfilters', type=int, default=64,",
"type=int, default=1, metavar='', help='set to 7 for imagenet and 1 for cifar10') parser.add_argument('--level',",
"http://localhost:port') # ======================== Hyperparameter Setings ================================== parser.add_argument('--optim-method', type=str, default='Adam', metavar='', help='the optimization routine",
"help='number of feature dimensions') parser.add_argument('--nunits', type=int, default=None, metavar='', help='number of units in hidden",
"help='save the training log files here') parser.add_argument('--resume', type=str, default=None, metavar='', help='full path of",
"1 parameter for Adam') parser.add_argument('--adam-beta2', type=float, default=0.999, metavar='', help='Beta 2 parameter for Adam')",
"type=bool, default=True, metavar='', help='run on gpu') parser.add_argument('--ngpu', type=int, default=1, metavar='', help='number of gpus",
"parser.add_argument('--resume', type=str, default=None, metavar='', help='full path of models to resume training') parser.add_argument('--nclasses', type=int,",
"parser.add_argument('--nthreads', type=int, default=20, metavar='', help='number of threads for data loading') parser.add_argument('--manual-seed', type=int, default=1,",
"of models to resume training') parser.add_argument('--nclasses', type=int, default=10, metavar='', help='number of classes for",
"default=None, metavar='', help='number of units in hidden layers') parser.add_argument('--dropout', type=float, default=None, metavar='', help='dropout",
"of training dataset') parser.add_argument('--dataset-train', type=str, default='CIFAR10', metavar='', help='name of training dataset') parser.add_argument('--split_test', type=float,",
"help='name of training dataset') parser.add_argument('--split_test', type=float, default=None, metavar='', help='percentage of test dataset to",
"input channels') parser.add_argument('--nfilters', type=int, default=64, metavar='', help='number of filters in each layer') parser.add_argument('--avgpool',",
"parser.add_argument('--ngpu', type=int, default=1, metavar='', help='number of gpus to use') parser.add_argument('--batch-size', type=int, default=64, metavar='',",
"resolution width') parser.add_argument('--ndim', type=int, default=None, metavar='', help='number of feature dimensions') parser.add_argument('--nunits', type=int, default=None,",
"metavar='', help='path to the data') parser.add_argument('--save', type=str, default=result_path +'Save', metavar='', help='save the trained",
"metavar='', help='set to 7 for imagenet and 1 for cifar10') parser.add_argument('--level', type=float, default=0.1,",
"default=result_path +'Logs', metavar='', help='save the training log files here') parser.add_argument('--resume', type=str, default=None, metavar='',",
"to the data') parser.add_argument('--save', type=str, default=result_path +'Save', metavar='', help='save the trained models here')",
"help='image resolution width') parser.add_argument('--ndim', type=int, default=None, metavar='', help='number of feature dimensions') parser.add_argument('--nunits', type=int,",
"for randomness') parser.add_argument('--port', type=int, default=8097, metavar='', help='port for visualizing training at http://localhost:port') #",
"help='number of units in hidden layers') parser.add_argument('--dropout', type=float, default=None, metavar='', help='dropout parameter') parser.add_argument('--net-type',",
"the data') parser.add_argument('--save', type=str, default=result_path +'Save', metavar='', help='save the trained models here') parser.add_argument('--logs',",
"type=float, default=None, metavar='', help='dropout parameter') parser.add_argument('--net-type', type=str, default='noiseresnet18', metavar='', help='type of network') parser.add_argument('--length-scale',",
"help='type of network') parser.add_argument('--length-scale', type=float, default=None, metavar='', help='length scale') parser.add_argument('--tau', type=float, default=None, metavar='',",
"default=None, metavar='', help='label loader') # ======================== Network Model Setings =================================== parser.add_argument('--nblocks', type=int, default=10,",
"help='set to 7 for imagenet and 1 for cifar10') parser.add_argument('--level', type=float, default=0.1, metavar='',",
"help='input train filename for filelist and folderlist') parser.add_argument('--label-filename-train', type=str, default=None, metavar='', help='label train",
"of blocks in each layer') parser.add_argument('--nlayers', type=int, default=6, metavar='', help='number of layers') parser.add_argument('--nchannels',",
"result_path = os.path.join(result_path, datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S/')) parser = argparse.ArgumentParser(description='Your project title goes here') # ========================",
"default=10, metavar='', help='number of classes for classification') parser.add_argument('--input-filename-test', type=str, default=None, metavar='', help='input test",
"Network Model Setings =================================== parser.add_argument('--nblocks', type=int, default=10, metavar='', help='number of blocks in each",
"metavar='', help='percentage of test dataset to split') parser.add_argument('--split_train', type=float, default=None, metavar='', help='percentage of",
"help='epoch number') parser.add_argument('--nthreads', type=int, default=20, metavar='', help='number of threads for data loading') parser.add_argument('--manual-seed',",
"folderlist') parser.add_argument('--input-filename-train', type=str, default=None, metavar='', help='input train filename for filelist and folderlist') parser.add_argument('--label-filename-train',",
"parser.add_argument('--weight-decay', type=float, default=1e-4, metavar='', help='weight decay') parser.add_argument('--adam-beta1', type=float, default=0.9, metavar='', help='Beta 1 parameter",
"train filename for filelist and folderlist') parser.add_argument('--label-filename-train', type=str, default=None, metavar='', help='label train filename",
"help='percentage of train dataset to split') parser.add_argument('--dataroot', type=str, default='../../data', metavar='', help='path to the",
"help='the optimization routine ') parser.add_argument('--learning-rate', type=float, default=1e-3, metavar='', help='learning rate') parser.add_argument('--learning-rate-decay', type=float, default=None,",
"type=int, default=6, metavar='', help='number of layers') parser.add_argument('--nchannels', type=int, default=3, metavar='', help='number of input",
"parser.add_argument('--nlayers', type=int, default=6, metavar='', help='number of layers') parser.add_argument('--nchannels', type=int, default=3, metavar='', help='number of",
"for training') parser.add_argument('--nepochs', type=int, default=500, metavar='', help='number of epochs to train') parser.add_argument('--niters', type=int,",
"visualizing training at http://localhost:port') # ======================== Hyperparameter Setings ================================== parser.add_argument('--optim-method', type=str, default='Adam', metavar='',",
"= os.path.join(result_path, datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S/')) parser = argparse.ArgumentParser(description='Your project title goes here') # ======================== Data",
"metavar='', help='number of filters in each layer') parser.add_argument('--avgpool', type=int, default=1, metavar='', help='set to",
"type=float, default=None, metavar='', help='length scale') parser.add_argument('--tau', type=float, default=None, metavar='', help='Tau') # ======================== Training",
"================================== parser.add_argument('--optim-method', type=str, default='Adam', metavar='', help='the optimization routine ') parser.add_argument('--learning-rate', type=float, default=1e-3, metavar='',",
"Hyperparameter Setings ================================== parser.add_argument('--optim-method', type=str, default='Adam', metavar='', help='the optimization routine ') parser.add_argument('--learning-rate', type=float,",
"= argparse.ArgumentParser(description='Your project title goes here') # ======================== Data Setings ============================================ parser.add_argument('--dataset-test', type=str,",
"# config.py import os import datetime import argparse result_path = \"results/\" result_path =",
"models to resume training') parser.add_argument('--nclasses', type=int, default=10, metavar='', help='number of classes for classification')",
"metavar='', help='learning rate') parser.add_argument('--learning-rate-decay', type=float, default=None, metavar='', help='learning rate decay') parser.add_argument('--momentum', type=float, default=0.9,",
"metavar='', help='input train filename for filelist and folderlist') parser.add_argument('--label-filename-train', type=str, default=None, metavar='', help='label",
"metavar='', help='number of classes for classification') parser.add_argument('--input-filename-test', type=str, default=None, metavar='', help='input test filename",
"layers') parser.add_argument('--nchannels', type=int, default=3, metavar='', help='number of input channels') parser.add_argument('--nfilters', type=int, default=64, metavar='',",
"help='learning rate') parser.add_argument('--learning-rate-decay', type=float, default=None, metavar='', help='learning rate decay') parser.add_argument('--momentum', type=float, default=0.9, metavar='',",
"default=None, metavar='', help='epoch number') parser.add_argument('--nthreads', type=int, default=20, metavar='', help='number of threads for data",
"in each layer') parser.add_argument('--nlayers', type=int, default=6, metavar='', help='number of layers') parser.add_argument('--nchannels', type=int, default=3,",
"Adam') parser.add_argument('--adam-beta2', type=float, default=0.999, metavar='', help='Beta 2 parameter for Adam') args = parser.parse_args()",
"help='save the trained models here') parser.add_argument('--logs', type=str, default=result_path +'Logs', metavar='', help='save the training",
"type=int, default=None, metavar='', help='number of iterations at test time') parser.add_argument('--epoch-number', type=int, default=None, metavar='',",
"level for uniform noise') parser.add_argument('--resolution-high', type=int, default=32, metavar='', help='image resolution height') parser.add_argument('--resolution-wide', type=int,",
"default=None, metavar='', help='input loader') parser.add_argument('--loader-label', type=str, default=None, metavar='', help='label loader') # ======================== Network",
"dataset') parser.add_argument('--dataset-train', type=str, default='CIFAR10', metavar='', help='name of training dataset') parser.add_argument('--split_test', type=float, default=None, metavar='',",
"type=int, default=32, metavar='', help='image resolution height') parser.add_argument('--resolution-wide', type=int, default=32, metavar='', help='image resolution width')",
"metavar='', help='number of units in hidden layers') parser.add_argument('--dropout', type=float, default=None, metavar='', help='dropout parameter')",
"for filelist and folderlist') parser.add_argument('--label-filename-test', type=str, default=None, metavar='', help='label test filename for filelist",
"default=None, metavar='', help='label test filename for filelist and folderlist') parser.add_argument('--input-filename-train', type=str, default=None, metavar='',",
"log files here') parser.add_argument('--resume', type=str, default=None, metavar='', help='full path of models to resume",
"parser.add_argument('--save', type=str, default=result_path +'Save', metavar='', help='save the trained models here') parser.add_argument('--logs', type=str, default=result_path",
"type=float, default=None, metavar='', help='learning rate decay') parser.add_argument('--momentum', type=float, default=0.9, metavar='', help='momentum') parser.add_argument('--weight-decay', type=float,",
"Data Setings ============================================ parser.add_argument('--dataset-test', type=str, default='CIFAR10', metavar='', help='name of training dataset') parser.add_argument('--dataset-train', type=str,"
] |
[] |
[
"for c in range(0, 3): print('|', end='') for i in range(0, 3): print(f'{matriz[c][i]:^5}',",
"print() print('-'*30) print(f'A soma dos valores pares é: {par}') print(f'A soma dos valores",
"in range(0, 3): print(f'{matriz[c][i]:^5}', end='|') print() print('-'*30) print(f'A soma dos valores pares é:",
"range(0, 3): print(f'{matriz[c][i]:^5}', end='|') print() print('-'*30) print(f'A soma dos valores pares é: {par}')",
"3): for i in range(0, 3): matriz[c].append(int(input(f'Digite um valor para a posição [{c}/{i}]:",
"[{c}/{i}]: '))) if matriz[c][i] % 2 == 0: par += matriz[c][i] somatre =",
"soma dos valores pares é: {par}') print(f'A soma dos valores da terceira coluna",
"i in range(0, 3): matriz[c].append(int(input(f'Digite um valor para a posição [{c}/{i}]: '))) if",
"3): print('|', end='') for i in range(0, 3): print(f'{matriz[c][i]:^5}', end='|') print() print('-'*30) print(f'A",
"= 0 somatre = 0 for c in range(0, 3): for i in",
"[], []] par = 0 somatre = 0 for c in range(0, 3):",
"2 == 0: par += matriz[c][i] somatre = somatre + matriz[c][2] print('=+'*28) for",
"0: par += matriz[c][i] somatre = somatre + matriz[c][2] print('=+'*28) for c in",
"dos valores pares é: {par}') print(f'A soma dos valores da terceira coluna é:",
"valores da terceira coluna é: {somatre}') print(f'O maior valor da segunda linha é:",
"print('|', end='') for i in range(0, 3): print(f'{matriz[c][i]:^5}', end='|') print() print('-'*30) print(f'A soma",
"[[], [], []] par = 0 somatre = 0 for c in range(0,",
"== 0: par += matriz[c][i] somatre = somatre + matriz[c][2] print('=+'*28) for c",
"par += matriz[c][i] somatre = somatre + matriz[c][2] print('=+'*28) for c in range(0,",
"end='|') print() print('-'*30) print(f'A soma dos valores pares é: {par}') print(f'A soma dos",
"0 somatre = 0 for c in range(0, 3): for i in range(0,",
"print(f'A soma dos valores da terceira coluna é: {somatre}') print(f'O maior valor da",
"= somatre + matriz[c][2] print('=+'*28) for c in range(0, 3): print('|', end='') for",
"par = 0 somatre = 0 for c in range(0, 3): for i",
"range(0, 3): matriz[c].append(int(input(f'Digite um valor para a posição [{c}/{i}]: '))) if matriz[c][i] %",
"3): matriz[c].append(int(input(f'Digite um valor para a posição [{c}/{i}]: '))) if matriz[c][i] % 2",
"matriz[c][i] % 2 == 0: par += matriz[c][i] somatre = somatre + matriz[c][2]",
"range(0, 3): print('|', end='') for i in range(0, 3): print(f'{matriz[c][i]:^5}', end='|') print() print('-'*30)",
"= [[], [], []] par = 0 somatre = 0 for c in",
"matriz[c].append(int(input(f'Digite um valor para a posição [{c}/{i}]: '))) if matriz[c][i] % 2 ==",
"matriz[c][i] somatre = somatre + matriz[c][2] print('=+'*28) for c in range(0, 3): print('|',",
"print('=+'*28) for c in range(0, 3): print('|', end='') for i in range(0, 3):",
"end='') for i in range(0, 3): print(f'{matriz[c][i]:^5}', end='|') print() print('-'*30) print(f'A soma dos",
"para a posição [{c}/{i}]: '))) if matriz[c][i] % 2 == 0: par +=",
"'))) if matriz[c][i] % 2 == 0: par += matriz[c][i] somatre = somatre",
"+= matriz[c][i] somatre = somatre + matriz[c][2] print('=+'*28) for c in range(0, 3):",
"print('-'*30) print(f'A soma dos valores pares é: {par}') print(f'A soma dos valores da",
"= 0 for c in range(0, 3): for i in range(0, 3): matriz[c].append(int(input(f'Digite",
"a posição [{c}/{i}]: '))) if matriz[c][i] % 2 == 0: par += matriz[c][i]",
"um valor para a posição [{c}/{i}]: '))) if matriz[c][i] % 2 == 0:",
"somatre + matriz[c][2] print('=+'*28) for c in range(0, 3): print('|', end='') for i",
"i in range(0, 3): print(f'{matriz[c][i]:^5}', end='|') print() print('-'*30) print(f'A soma dos valores pares",
"in range(0, 3): for i in range(0, 3): matriz[c].append(int(input(f'Digite um valor para a",
"print(f'{matriz[c][i]:^5}', end='|') print() print('-'*30) print(f'A soma dos valores pares é: {par}') print(f'A soma",
"+ matriz[c][2] print('=+'*28) for c in range(0, 3): print('|', end='') for i in",
"[]] par = 0 somatre = 0 for c in range(0, 3): for",
"print(f'A soma dos valores pares é: {par}') print(f'A soma dos valores da terceira",
"3): print(f'{matriz[c][i]:^5}', end='|') print() print('-'*30) print(f'A soma dos valores pares é: {par}') print(f'A",
"for i in range(0, 3): matriz[c].append(int(input(f'Digite um valor para a posição [{c}/{i}]: ')))",
"0 for c in range(0, 3): for i in range(0, 3): matriz[c].append(int(input(f'Digite um",
"c in range(0, 3): for i in range(0, 3): matriz[c].append(int(input(f'Digite um valor para",
"posição [{c}/{i}]: '))) if matriz[c][i] % 2 == 0: par += matriz[c][i] somatre",
"dos valores da terceira coluna é: {somatre}') print(f'O maior valor da segunda linha",
"matriz[c][2] print('=+'*28) for c in range(0, 3): print('|', end='') for i in range(0,",
"% 2 == 0: par += matriz[c][i] somatre = somatre + matriz[c][2] print('=+'*28)",
"valores pares é: {par}') print(f'A soma dos valores da terceira coluna é: {somatre}')",
"c in range(0, 3): print('|', end='') for i in range(0, 3): print(f'{matriz[c][i]:^5}', end='|')",
"{par}') print(f'A soma dos valores da terceira coluna é: {somatre}') print(f'O maior valor",
"for c in range(0, 3): for i in range(0, 3): matriz[c].append(int(input(f'Digite um valor",
"for i in range(0, 3): print(f'{matriz[c][i]:^5}', end='|') print() print('-'*30) print(f'A soma dos valores",
"in range(0, 3): matriz[c].append(int(input(f'Digite um valor para a posição [{c}/{i}]: '))) if matriz[c][i]",
"valor para a posição [{c}/{i}]: '))) if matriz[c][i] % 2 == 0: par",
"if matriz[c][i] % 2 == 0: par += matriz[c][i] somatre = somatre +",
"somatre = somatre + matriz[c][2] print('=+'*28) for c in range(0, 3): print('|', end='')",
"soma dos valores da terceira coluna é: {somatre}') print(f'O maior valor da segunda",
"somatre = 0 for c in range(0, 3): for i in range(0, 3):",
"in range(0, 3): print('|', end='') for i in range(0, 3): print(f'{matriz[c][i]:^5}', end='|') print()",
"pares é: {par}') print(f'A soma dos valores da terceira coluna é: {somatre}') print(f'O",
"da terceira coluna é: {somatre}') print(f'O maior valor da segunda linha é: {max(matriz[1])}')",
"matriz = [[], [], []] par = 0 somatre = 0 for c",
"é: {par}') print(f'A soma dos valores da terceira coluna é: {somatre}') print(f'O maior",
"range(0, 3): for i in range(0, 3): matriz[c].append(int(input(f'Digite um valor para a posição"
] |
[
"utf-8 -*- ''' dict ''' d1 = {'a':1, 'b':2, 'c':3} print(d1) print(d1.keys()) print(d1.values())",
"{'a':1, 'b':2, 'c':3} print(d1) print(d1.keys()) print(d1.values()) print(str(d1)) print(len(d1)) print(d1['a']) d1['a'] = 10 print(d1['a'])",
"print(d1.values()) print(str(d1)) print(len(d1)) print(d1['a']) d1['a'] = 10 print(d1['a']) del d1['a'] print(d1) d1.clear() print(d1)",
"python # -*- coding: utf-8 -*- ''' dict ''' d1 = {'a':1, 'b':2,",
"'c':3} print(d1) print(d1.keys()) print(d1.values()) print(str(d1)) print(len(d1)) print(d1['a']) d1['a'] = 10 print(d1['a']) del d1['a']",
"dict ''' d1 = {'a':1, 'b':2, 'c':3} print(d1) print(d1.keys()) print(d1.values()) print(str(d1)) print(len(d1)) print(d1['a'])",
"<reponame>tanyong-cq/pythonlearning #!/usr/bin/env python # -*- coding: utf-8 -*- ''' dict ''' d1 =",
"print(d1) print(d1.keys()) print(d1.values()) print(str(d1)) print(len(d1)) print(d1['a']) d1['a'] = 10 print(d1['a']) del d1['a'] print(d1)",
"#!/usr/bin/env python # -*- coding: utf-8 -*- ''' dict ''' d1 = {'a':1,",
"= {'a':1, 'b':2, 'c':3} print(d1) print(d1.keys()) print(d1.values()) print(str(d1)) print(len(d1)) print(d1['a']) d1['a'] = 10",
"print(str(d1)) print(len(d1)) print(d1['a']) d1['a'] = 10 print(d1['a']) del d1['a'] print(d1) d1.clear() print(d1) print(d1.get('a'))",
"'b':2, 'c':3} print(d1) print(d1.keys()) print(d1.values()) print(str(d1)) print(len(d1)) print(d1['a']) d1['a'] = 10 print(d1['a']) del",
"''' dict ''' d1 = {'a':1, 'b':2, 'c':3} print(d1) print(d1.keys()) print(d1.values()) print(str(d1)) print(len(d1))",
"-*- coding: utf-8 -*- ''' dict ''' d1 = {'a':1, 'b':2, 'c':3} print(d1)",
"# -*- coding: utf-8 -*- ''' dict ''' d1 = {'a':1, 'b':2, 'c':3}",
"print(d1.keys()) print(d1.values()) print(str(d1)) print(len(d1)) print(d1['a']) d1['a'] = 10 print(d1['a']) del d1['a'] print(d1) d1.clear()",
"''' d1 = {'a':1, 'b':2, 'c':3} print(d1) print(d1.keys()) print(d1.values()) print(str(d1)) print(len(d1)) print(d1['a']) d1['a']",
"coding: utf-8 -*- ''' dict ''' d1 = {'a':1, 'b':2, 'c':3} print(d1) print(d1.keys())",
"d1 = {'a':1, 'b':2, 'c':3} print(d1) print(d1.keys()) print(d1.values()) print(str(d1)) print(len(d1)) print(d1['a']) d1['a'] =",
"-*- ''' dict ''' d1 = {'a':1, 'b':2, 'c':3} print(d1) print(d1.keys()) print(d1.values()) print(str(d1))"
] |
[
"contactPoint = ModelType(ContactPoint) class ProcuringEntity(Organization): \"\"\"An organization.\"\"\" class Options: roles = RolesFromCsv('ProcuringEntity.csv', relative_to=__file__)",
"as BaseOrganization from openprocurement.tender.cfaselectionua.models.submodels.contactpoint import ContactPoint from schematics.types import StringType from schematics.types.compound import",
"from openprocurement.api.models import ListType class Organization(BaseOrganization): \"\"\"An organization.\"\"\" contactPoint = ModelType(ContactPoint) class ProcuringEntity(Organization):",
"organization.\"\"\" contactPoint = ModelType(ContactPoint) class ProcuringEntity(Organization): \"\"\"An organization.\"\"\" class Options: roles = RolesFromCsv('ProcuringEntity.csv',",
"ProcuringEntity(Organization): \"\"\"An organization.\"\"\" class Options: roles = RolesFromCsv('ProcuringEntity.csv', relative_to=__file__) kind = StringType(choices=['general', 'special',",
"ModelType(ContactPoint) class ProcuringEntity(Organization): \"\"\"An organization.\"\"\" class Options: roles = RolesFromCsv('ProcuringEntity.csv', relative_to=__file__) kind =",
"ListType class Organization(BaseOrganization): \"\"\"An organization.\"\"\" contactPoint = ModelType(ContactPoint) class ProcuringEntity(Organization): \"\"\"An organization.\"\"\" class",
"from schematics.types.compound import ModelType from openprocurement.api.roles import RolesFromCsv from openprocurement.api.models import ListType class",
"\"\"\"An organization.\"\"\" class Options: roles = RolesFromCsv('ProcuringEntity.csv', relative_to=__file__) kind = StringType(choices=['general', 'special', 'defense',",
"\"\"\"An organization.\"\"\" contactPoint = ModelType(ContactPoint) class ProcuringEntity(Organization): \"\"\"An organization.\"\"\" class Options: roles =",
"class Organization(BaseOrganization): \"\"\"An organization.\"\"\" contactPoint = ModelType(ContactPoint) class ProcuringEntity(Organization): \"\"\"An organization.\"\"\" class Options:",
"import ListType class Organization(BaseOrganization): \"\"\"An organization.\"\"\" contactPoint = ModelType(ContactPoint) class ProcuringEntity(Organization): \"\"\"An organization.\"\"\"",
"roles = RolesFromCsv('ProcuringEntity.csv', relative_to=__file__) kind = StringType(choices=['general', 'special', 'defense', 'other']) additionalContactPoints = ListType(",
"class ProcuringEntity(Organization): \"\"\"An organization.\"\"\" class Options: roles = RolesFromCsv('ProcuringEntity.csv', relative_to=__file__) kind = StringType(choices=['general',",
"openprocurement.api.roles import RolesFromCsv from openprocurement.api.models import ListType class Organization(BaseOrganization): \"\"\"An organization.\"\"\" contactPoint =",
"import Organization as BaseOrganization from openprocurement.tender.cfaselectionua.models.submodels.contactpoint import ContactPoint from schematics.types import StringType from",
"kind = StringType(choices=['general', 'special', 'defense', 'other']) additionalContactPoints = ListType( ModelType(ContactPoint, required=True), required=False )",
"import StringType from schematics.types.compound import ModelType from openprocurement.api.roles import RolesFromCsv from openprocurement.api.models import",
"from openprocurement.api.roles import RolesFromCsv from openprocurement.api.models import ListType class Organization(BaseOrganization): \"\"\"An organization.\"\"\" contactPoint",
"= RolesFromCsv('ProcuringEntity.csv', relative_to=__file__) kind = StringType(choices=['general', 'special', 'defense', 'other']) additionalContactPoints = ListType( ModelType(ContactPoint,",
"Organization(BaseOrganization): \"\"\"An organization.\"\"\" contactPoint = ModelType(ContactPoint) class ProcuringEntity(Organization): \"\"\"An organization.\"\"\" class Options: roles",
"schematics.types.compound import ModelType from openprocurement.api.roles import RolesFromCsv from openprocurement.api.models import ListType class Organization(BaseOrganization):",
"RolesFromCsv from openprocurement.api.models import ListType class Organization(BaseOrganization): \"\"\"An organization.\"\"\" contactPoint = ModelType(ContactPoint) class",
"openprocurement.tender.cfaselectionua.models.submodels.contactpoint import ContactPoint from schematics.types import StringType from schematics.types.compound import ModelType from openprocurement.api.roles",
"openprocurement.api.models import ListType class Organization(BaseOrganization): \"\"\"An organization.\"\"\" contactPoint = ModelType(ContactPoint) class ProcuringEntity(Organization): \"\"\"An",
"import ModelType from openprocurement.api.roles import RolesFromCsv from openprocurement.api.models import ListType class Organization(BaseOrganization): \"\"\"An",
"class Options: roles = RolesFromCsv('ProcuringEntity.csv', relative_to=__file__) kind = StringType(choices=['general', 'special', 'defense', 'other']) additionalContactPoints",
"schematics.types import StringType from schematics.types.compound import ModelType from openprocurement.api.roles import RolesFromCsv from openprocurement.api.models",
"Options: roles = RolesFromCsv('ProcuringEntity.csv', relative_to=__file__) kind = StringType(choices=['general', 'special', 'defense', 'other']) additionalContactPoints =",
"from schematics.types import StringType from schematics.types.compound import ModelType from openprocurement.api.roles import RolesFromCsv from",
"organization.\"\"\" class Options: roles = RolesFromCsv('ProcuringEntity.csv', relative_to=__file__) kind = StringType(choices=['general', 'special', 'defense', 'other'])",
"RolesFromCsv('ProcuringEntity.csv', relative_to=__file__) kind = StringType(choices=['general', 'special', 'defense', 'other']) additionalContactPoints = ListType( ModelType(ContactPoint, required=True),",
"import RolesFromCsv from openprocurement.api.models import ListType class Organization(BaseOrganization): \"\"\"An organization.\"\"\" contactPoint = ModelType(ContactPoint)",
"from openprocurement.tender.cfaselectionua.models.submodels.contactpoint import ContactPoint from schematics.types import StringType from schematics.types.compound import ModelType from",
"relative_to=__file__) kind = StringType(choices=['general', 'special', 'defense', 'other']) additionalContactPoints = ListType( ModelType(ContactPoint, required=True), required=False",
"StringType from schematics.types.compound import ModelType from openprocurement.api.roles import RolesFromCsv from openprocurement.api.models import ListType",
"BaseOrganization from openprocurement.tender.cfaselectionua.models.submodels.contactpoint import ContactPoint from schematics.types import StringType from schematics.types.compound import ModelType",
"= ModelType(ContactPoint) class ProcuringEntity(Organization): \"\"\"An organization.\"\"\" class Options: roles = RolesFromCsv('ProcuringEntity.csv', relative_to=__file__) kind",
"Organization as BaseOrganization from openprocurement.tender.cfaselectionua.models.submodels.contactpoint import ContactPoint from schematics.types import StringType from schematics.types.compound",
"from openprocurement.api.models import Organization as BaseOrganization from openprocurement.tender.cfaselectionua.models.submodels.contactpoint import ContactPoint from schematics.types import",
"openprocurement.api.models import Organization as BaseOrganization from openprocurement.tender.cfaselectionua.models.submodels.contactpoint import ContactPoint from schematics.types import StringType",
"ModelType from openprocurement.api.roles import RolesFromCsv from openprocurement.api.models import ListType class Organization(BaseOrganization): \"\"\"An organization.\"\"\"",
"ContactPoint from schematics.types import StringType from schematics.types.compound import ModelType from openprocurement.api.roles import RolesFromCsv",
"import ContactPoint from schematics.types import StringType from schematics.types.compound import ModelType from openprocurement.api.roles import"
] |
[
"allocationPool = kwargs['allocationPool'] except KeyError, AttributeError: allocationPool = False try: routeTarget = kwargs['routeTarget']",
"domain=self.domain, tenantName=self.tenantName) def createNetwork(self, **kwargs): _requiredArgs = ['cidr', 'name'] try: cidr = kwargs['cidr']",
"= vnc_api.FloatingIpPool(name = fipPoolName, parent_obj = networkObj) fipPool.uuid = fipPoolId self.vnc.floating_ip_pool_create(fipPool) self.tenantObj.add_floating_ip_pool(fipPool) self.vnc.project_update(self.tenantObj)",
"self.log.error(\"Function: createNetwork Message: cidr is not in correct format : {0}\".format(e)) return False",
"uuid class vncNetwork(hybridLogger): def __init__(self, vnc, domain, tenantName ,logLevel='INFO'): self.log = super(vncNetwork, self).log(level=logLevel,",
"newNetworkId = self.vnc.virtual_network_create(networkObj) self.log.info(\"Virtual Network: {0} created \".format(networkName)) except Exception as e: self.log.error(\"Function:",
"if fipPoolName: routerExternal = True else: routerExternal = False try: networkObj = vnc_api.VirtualNetwork(name=networkName,",
"in allocationPoolList: try: allocationPoolStart, allocationPoolStop = allocationPool.split('-') allocType = vnc_api.AllocationPoolType() allocType.set_start(allocationPoolStart) allocType.set_end(allocationPoolStop) allocTypeList.append(allocType)",
"{0} already exists\".format(networkName)) return networkObj subnet = vnc_api.SubnetType(prefix, prefixLen) if not allocTypeList: ipamSubnet",
"except KeyError, AttributeError: allocationPool = False try: routeTarget = kwargs['routeTarget'] except KeyError, AttributeError:",
"as e: self.log.error(\"Function: createNetwork Message: Error While Creating network : {0}\".format(e)) return False",
"False if fipPoolName: routerExternal = True else: routerExternal = False try: networkObj =",
"networkObj, tenantObj): newFqName = networkObj.get_fq_name() vnList = self.vnc.virtual_networks_list(parent_id=tenantObj.uuid) if not vnList: return False",
"try: networkObj = vnc_api.VirtualNetwork(name=networkName, parent_obj=self.tenantObj, router_external=routerExternal) networkExists = self._checkIfNetworkExists(networkObj, self.tenantObj) if networkExists: self.log.warn(\"Network:",
"= vnc_api.RouteTargetList(['target:' + routeTarget]) networkObj.set_route_target_list(routeTargets) return self.vnc.virtual_network_update(networkObj) except Exception as e: raise ContrailError(vncApi='vnc_api.RouteTargetList',",
"self._checkIfNetworkExists(networkObj, self.tenantObj) if networkExists: self.log.warn(\"Network: {0} already exists\".format(networkName)) return networkObj subnet = vnc_api.SubnetType(prefix,",
"{0} created \".format(networkName)) except Exception as e: self.log.error(\"Function: createNetwork Message: Error While Creating",
"name=vncNetwork.__name__) self.vnc = vnc self.tenantName = tenantName self.domain = domain self.tenantObj = readTenant(self.vnc,",
"False else: for elem in vnList['virtual-networks']: if(elem['fq_name'] == newFqName): return True else: continue",
"= self._addRouteTarget(networkObj, routeTarget) except Exception as e: self.log.error(\"Function: createNetwork Message: Error While adding",
"vnc_api.IpamSubnetType(subnet = subnet) else: ipamSubnet = vnc_api.IpamSubnetType(subnet = subnet, allocation_pools=allocTypeList) networkObj.add_network_ipam(vnc_api.NetworkIpam(),vnc_api.VnSubnetsType([ipamSubnet])) newNetworkId =",
"not vnList: return False else: for elem in vnList['virtual-networks']: if(elem['fq_name'] == newFqName): return",
"routerExternal = True else: routerExternal = False try: networkObj = vnc_api.VirtualNetwork(name=networkName, parent_obj=self.tenantObj, router_external=routerExternal)",
"_checkIfNetworkExists(self, networkObj, tenantObj): newFqName = networkObj.get_fq_name() vnList = self.vnc.virtual_networks_list(parent_id=tenantObj.uuid) if not vnList: return",
"parent_obj = networkObj) fipPool.uuid = fipPoolId self.vnc.floating_ip_pool_create(fipPool) self.tenantObj.add_floating_ip_pool(fipPool) self.vnc.project_update(self.tenantObj) return fipPool def _checkIfNetworkExists(self,",
"self._addRouteTarget(networkObj, routeTarget) except Exception as e: self.log.error(\"Function: createNetwork Message: Error While adding route",
"= fipPoolId self.vnc.floating_ip_pool_create(fipPool) self.tenantObj.add_floating_ip_pool(fipPool) self.vnc.project_update(self.tenantObj) return fipPool def _checkIfNetworkExists(self, networkObj, tenantObj): newFqName =",
"= False if fipPoolName: routerExternal = True else: routerExternal = False try: networkObj",
"routeTarget = False allocTypeList = [] if allocationPool: if type(allocationPool) == list: allocationPoolList",
"createNetwork Message: Error While adding route target to the network: {0}\".format(e)) return False",
"fipPoolName, parent_obj = networkObj) fipPool.uuid = fipPoolId self.vnc.floating_ip_pool_create(fipPool) self.tenantObj.add_floating_ip_pool(fipPool) self.vnc.project_update(self.tenantObj) return fipPool def",
"False try: fipPoolName = kwargs['fipPoolName'] except KeyError, AttributeError: fipPoolName = False if fipPoolName:",
"fipPoolName: routerExternal = True else: routerExternal = False try: networkObj = vnc_api.VirtualNetwork(name=networkName, parent_obj=self.tenantObj,",
"<gh_stars>0 from vnc_api import vnc_api from contrail.util import (readTenant, readNetwork) from hybridLogger import",
"{0}\".format(e)) return False prefixLen = int(prefixLen) try: allocationPool = kwargs['allocationPool'] except KeyError, AttributeError:",
"= tenantName self.domain = domain self.tenantObj = readTenant(self.vnc, domain=self.domain, tenantName=self.tenantName) def createNetwork(self, **kwargs):",
"try: allocationPoolStart, allocationPoolStop = allocationPool.split('-') allocType = vnc_api.AllocationPoolType() allocType.set_start(allocationPoolStart) allocType.set_end(allocationPoolStop) allocTypeList.append(allocType) except Exception",
"if networkExists: self.log.warn(\"Network: {0} already exists\".format(networkName)) return networkObj subnet = vnc_api.SubnetType(prefix, prefixLen) if",
"else: continue return False def _addRouteTarget(self, networkObj, routeTarget): try: routeTargets = vnc_api.RouteTargetList(['target:' +",
"domain, tenantName ,logLevel='INFO'): self.log = super(vncNetwork, self).log(level=logLevel, name=vncNetwork.__name__) self.vnc = vnc self.tenantName =",
"elem in vnList['virtual-networks']: if(elem['fq_name'] == newFqName): return True else: continue return False def",
"= True else: routerExternal = False try: networkObj = vnc_api.VirtualNetwork(name=networkName, parent_obj=self.tenantObj, router_external=routerExternal) networkExists",
"= False try: routeTarget = kwargs['routeTarget'] except KeyError, AttributeError: routeTarget = False allocTypeList",
"except Exception as e: self.log.error(\"Function: createNetwork Message: cidr is not in correct format",
"return fipPool def _checkIfNetworkExists(self, networkObj, tenantObj): newFqName = networkObj.get_fq_name() vnList = self.vnc.virtual_networks_list(parent_id=tenantObj.uuid) if",
"= self.vnc.virtual_networks_list(parent_id=tenantObj.uuid) if not vnList: return False else: for elem in vnList['virtual-networks']: if(elem['fq_name']",
"AttributeError: allocationPool = False try: routeTarget = kwargs['routeTarget'] except KeyError, AttributeError: routeTarget =",
"try: fipPoolName = kwargs['fipPoolName'] except KeyError, AttributeError: fipPoolName = False if fipPoolName: routerExternal",
"for allocationPool in allocationPoolList: try: allocationPoolStart, allocationPoolStop = allocationPool.split('-') allocType = vnc_api.AllocationPoolType() allocType.set_start(allocationPoolStart)",
"= domain self.tenantObj = readTenant(self.vnc, domain=self.domain, tenantName=self.tenantName) def createNetwork(self, **kwargs): _requiredArgs = ['cidr',",
"else: routerExternal = False try: networkObj = vnc_api.VirtualNetwork(name=networkName, parent_obj=self.tenantObj, router_external=routerExternal) networkExists = self._checkIfNetworkExists(networkObj,",
"= subnet) else: ipamSubnet = vnc_api.IpamSubnetType(subnet = subnet, allocation_pools=allocTypeList) networkObj.add_network_ipam(vnc_api.NetworkIpam(),vnc_api.VnSubnetsType([ipamSubnet])) newNetworkId = self.vnc.virtual_network_create(networkObj)",
"* import uuid class vncNetwork(hybridLogger): def __init__(self, vnc, domain, tenantName ,logLevel='INFO'): self.log =",
"correct format : {0}\".format(e)) return False prefixLen = int(prefixLen) try: allocationPool = kwargs['allocationPool']",
"continue return False def _addRouteTarget(self, networkObj, routeTarget): try: routeTargets = vnc_api.RouteTargetList(['target:' + routeTarget])",
"**kwargs): _requiredArgs = ['cidr', 'name'] try: cidr = kwargs['cidr'] networkName = kwargs['name'] prefix,",
"[] if allocationPool: if type(allocationPool) == list: allocationPoolList = allocationPool else: allocationPoolList =",
"to the network: {0}\".format(e)) return False if fipPoolName: fipObj = self.returnFipObj(fipPoolName, networkObj) else:",
"= kwargs['cidr'] networkName = kwargs['name'] prefix, prefixLen = cidr.split('/') except KeyError: raise ArguementError(_requiredArgs,",
"as e: self.log.error(\"Function: createNetwork Message: cidr is not in correct format : {0}\".format(e))",
"None return networkObj, fipObj def returnFipObj(self, fipPoolName, networkObj): fipPoolId = str(uuid.uuid4()) fipPool =",
"= vnc_api.SubnetType(prefix, prefixLen) if not allocTypeList: ipamSubnet = vnc_api.IpamSubnetType(subnet = subnet) else: ipamSubnet",
"str(uuid.uuid4()) fipPool = vnc_api.FloatingIpPool(name = fipPoolName, parent_obj = networkObj) fipPool.uuid = fipPoolId self.vnc.floating_ip_pool_create(fipPool)",
"return networkObj, fipObj def returnFipObj(self, fipPoolName, networkObj): fipPoolId = str(uuid.uuid4()) fipPool = vnc_api.FloatingIpPool(name",
"allocationPoolStart, allocationPoolStop = allocationPool.split('-') allocType = vnc_api.AllocationPoolType() allocType.set_start(allocationPoolStart) allocType.set_end(allocationPoolStop) allocTypeList.append(allocType) except Exception as",
"else: fipObj = None return networkObj, fipObj def returnFipObj(self, fipPoolName, networkObj): fipPoolId =",
"allocTypeList: ipamSubnet = vnc_api.IpamSubnetType(subnet = subnet) else: ipamSubnet = vnc_api.IpamSubnetType(subnet = subnet, allocation_pools=allocTypeList)",
"While adding route target to the network: {0}\".format(e)) return False if fipPoolName: fipObj",
"vncNetwork.createNetwork.__name__) except Exception as e: self.log.error(\"Function: createNetwork Message: cidr is not in correct",
"cidr = kwargs['cidr'] networkName = kwargs['name'] prefix, prefixLen = cidr.split('/') except KeyError: raise",
"While Creating network : {0}\".format(e)) return False if routeTarget: try: updateNetwork = self._addRouteTarget(networkObj,",
"_requiredArgs = ['cidr', 'name'] try: cidr = kwargs['cidr'] networkName = kwargs['name'] prefix, prefixLen",
"type(allocationPool) == list: allocationPoolList = allocationPool else: allocationPoolList = [allocationPool] for allocationPool in",
"not allocTypeList: ipamSubnet = vnc_api.IpamSubnetType(subnet = subnet) else: ipamSubnet = vnc_api.IpamSubnetType(subnet = subnet,",
"= vnc self.tenantName = tenantName self.domain = domain self.tenantObj = readTenant(self.vnc, domain=self.domain, tenantName=self.tenantName)",
"kwargs['name'] prefix, prefixLen = cidr.split('/') except KeyError: raise ArguementError(_requiredArgs, vncNetwork.createNetwork.__name__) except Exception as",
"except Exception as e: self.log.error(\"Function: createNetwork Message: Error While adding route target to",
"vnc_api.AllocationPoolType() allocType.set_start(allocationPoolStart) allocType.set_end(allocationPoolStop) allocTypeList.append(allocType) except Exception as e: self.log.error(\"Function: createNetwork Message: allocationPool error",
"= None return networkObj, fipObj def returnFipObj(self, fipPoolName, networkObj): fipPoolId = str(uuid.uuid4()) fipPool",
"created \".format(networkName)) except Exception as e: self.log.error(\"Function: createNetwork Message: Error While Creating network",
"def _addRouteTarget(self, networkObj, routeTarget): try: routeTargets = vnc_api.RouteTargetList(['target:' + routeTarget]) networkObj.set_route_target_list(routeTargets) return self.vnc.virtual_network_update(networkObj)",
"from hybridLogger import hybridLogger from exception import * import uuid class vncNetwork(hybridLogger): def",
"tenantName self.domain = domain self.tenantObj = readTenant(self.vnc, domain=self.domain, tenantName=self.tenantName) def createNetwork(self, **kwargs): _requiredArgs",
"e: self.log.error(\"Function: createNetwork Message: Error While adding route target to the network: {0}\".format(e))",
"== newFqName): return True else: continue return False def _addRouteTarget(self, networkObj, routeTarget): try:",
"import uuid class vncNetwork(hybridLogger): def __init__(self, vnc, domain, tenantName ,logLevel='INFO'): self.log = super(vncNetwork,",
"return False prefixLen = int(prefixLen) try: allocationPool = kwargs['allocationPool'] except KeyError, AttributeError: allocationPool",
"= kwargs['name'] prefix, prefixLen = cidr.split('/') except KeyError: raise ArguementError(_requiredArgs, vncNetwork.createNetwork.__name__) except Exception",
"raise ArguementError(_requiredArgs, vncNetwork.createNetwork.__name__) except Exception as e: self.log.error(\"Function: createNetwork Message: cidr is not",
"Message: cidr is not in correct format : {0}\".format(e)) return False prefixLen =",
"= kwargs['allocationPool'] except KeyError, AttributeError: allocationPool = False try: routeTarget = kwargs['routeTarget'] except",
"else: ipamSubnet = vnc_api.IpamSubnetType(subnet = subnet, allocation_pools=allocTypeList) networkObj.add_network_ipam(vnc_api.NetworkIpam(),vnc_api.VnSubnetsType([ipamSubnet])) newNetworkId = self.vnc.virtual_network_create(networkObj) self.log.info(\"Virtual Network:",
"allocTypeList = [] if allocationPool: if type(allocationPool) == list: allocationPoolList = allocationPool else:",
"super(vncNetwork, self).log(level=logLevel, name=vncNetwork.__name__) self.vnc = vnc self.tenantName = tenantName self.domain = domain self.tenantObj",
"allocationPool error : {0}\".format(e)) return False try: fipPoolName = kwargs['fipPoolName'] except KeyError, AttributeError:",
"updateNetwork = self._addRouteTarget(networkObj, routeTarget) except Exception as e: self.log.error(\"Function: createNetwork Message: Error While",
"networkObj) else: fipObj = None return networkObj, fipObj def returnFipObj(self, fipPoolName, networkObj): fipPoolId",
"except Exception as e: self.log.error(\"Function: createNetwork Message: Error While Creating network : {0}\".format(e))",
"except KeyError, AttributeError: routeTarget = False allocTypeList = [] if allocationPool: if type(allocationPool)",
"fipPoolName = kwargs['fipPoolName'] except KeyError, AttributeError: fipPoolName = False if fipPoolName: routerExternal =",
"prefixLen) if not allocTypeList: ipamSubnet = vnc_api.IpamSubnetType(subnet = subnet) else: ipamSubnet = vnc_api.IpamSubnetType(subnet",
"if(elem['fq_name'] == newFqName): return True else: continue return False def _addRouteTarget(self, networkObj, routeTarget):",
"fipObj = None return networkObj, fipObj def returnFipObj(self, fipPoolName, networkObj): fipPoolId = str(uuid.uuid4())",
"self.vnc = vnc self.tenantName = tenantName self.domain = domain self.tenantObj = readTenant(self.vnc, domain=self.domain,",
"= [allocationPool] for allocationPool in allocationPoolList: try: allocationPoolStart, allocationPoolStop = allocationPool.split('-') allocType =",
"from vnc_api import vnc_api from contrail.util import (readTenant, readNetwork) from hybridLogger import hybridLogger",
"fipPool = vnc_api.FloatingIpPool(name = fipPoolName, parent_obj = networkObj) fipPool.uuid = fipPoolId self.vnc.floating_ip_pool_create(fipPool) self.tenantObj.add_floating_ip_pool(fipPool)",
"vnc_api.RouteTargetList(['target:' + routeTarget]) networkObj.set_route_target_list(routeTargets) return self.vnc.virtual_network_update(networkObj) except Exception as e: raise ContrailError(vncApi='vnc_api.RouteTargetList', error=e)",
"KeyError: raise ArguementError(_requiredArgs, vncNetwork.createNetwork.__name__) except Exception as e: self.log.error(\"Function: createNetwork Message: cidr is",
"fipPoolId self.vnc.floating_ip_pool_create(fipPool) self.tenantObj.add_floating_ip_pool(fipPool) self.vnc.project_update(self.tenantObj) return fipPool def _checkIfNetworkExists(self, networkObj, tenantObj): newFqName = networkObj.get_fq_name()",
"returnFipObj(self, fipPoolName, networkObj): fipPoolId = str(uuid.uuid4()) fipPool = vnc_api.FloatingIpPool(name = fipPoolName, parent_obj =",
"self.vnc.floating_ip_pool_create(fipPool) self.tenantObj.add_floating_ip_pool(fipPool) self.vnc.project_update(self.tenantObj) return fipPool def _checkIfNetworkExists(self, networkObj, tenantObj): newFqName = networkObj.get_fq_name() vnList",
"fipPool def _checkIfNetworkExists(self, networkObj, tenantObj): newFqName = networkObj.get_fq_name() vnList = self.vnc.virtual_networks_list(parent_id=tenantObj.uuid) if not",
"vncNetwork(hybridLogger): def __init__(self, vnc, domain, tenantName ,logLevel='INFO'): self.log = super(vncNetwork, self).log(level=logLevel, name=vncNetwork.__name__) self.vnc",
"return True else: continue return False def _addRouteTarget(self, networkObj, routeTarget): try: routeTargets =",
"else: allocationPoolList = [allocationPool] for allocationPool in allocationPoolList: try: allocationPoolStart, allocationPoolStop = allocationPool.split('-')",
"network : {0}\".format(e)) return False if routeTarget: try: updateNetwork = self._addRouteTarget(networkObj, routeTarget) except",
"False def _addRouteTarget(self, networkObj, routeTarget): try: routeTargets = vnc_api.RouteTargetList(['target:' + routeTarget]) networkObj.set_route_target_list(routeTargets) return",
"self.vnc.virtual_network_create(networkObj) self.log.info(\"Virtual Network: {0} created \".format(networkName)) except Exception as e: self.log.error(\"Function: createNetwork Message:",
"AttributeError: routeTarget = False allocTypeList = [] if allocationPool: if type(allocationPool) == list:",
"in correct format : {0}\".format(e)) return False prefixLen = int(prefixLen) try: allocationPool =",
"if not allocTypeList: ipamSubnet = vnc_api.IpamSubnetType(subnet = subnet) else: ipamSubnet = vnc_api.IpamSubnetType(subnet =",
"False try: networkObj = vnc_api.VirtualNetwork(name=networkName, parent_obj=self.tenantObj, router_external=routerExternal) networkExists = self._checkIfNetworkExists(networkObj, self.tenantObj) if networkExists:",
"createNetwork Message: cidr is not in correct format : {0}\".format(e)) return False prefixLen",
"vnc_api.FloatingIpPool(name = fipPoolName, parent_obj = networkObj) fipPool.uuid = fipPoolId self.vnc.floating_ip_pool_create(fipPool) self.tenantObj.add_floating_ip_pool(fipPool) self.vnc.project_update(self.tenantObj) return",
"router_external=routerExternal) networkExists = self._checkIfNetworkExists(networkObj, self.tenantObj) if networkExists: self.log.warn(\"Network: {0} already exists\".format(networkName)) return networkObj",
"fipObj = self.returnFipObj(fipPoolName, networkObj) else: fipObj = None return networkObj, fipObj def returnFipObj(self,",
"False allocTypeList = [] if allocationPool: if type(allocationPool) == list: allocationPoolList = allocationPool",
"return False if routeTarget: try: updateNetwork = self._addRouteTarget(networkObj, routeTarget) except Exception as e:",
"try: routeTarget = kwargs['routeTarget'] except KeyError, AttributeError: routeTarget = False allocTypeList = []",
"fipPool.uuid = fipPoolId self.vnc.floating_ip_pool_create(fipPool) self.tenantObj.add_floating_ip_pool(fipPool) self.vnc.project_update(self.tenantObj) return fipPool def _checkIfNetworkExists(self, networkObj, tenantObj): newFqName",
"False try: routeTarget = kwargs['routeTarget'] except KeyError, AttributeError: routeTarget = False allocTypeList =",
"class vncNetwork(hybridLogger): def __init__(self, vnc, domain, tenantName ,logLevel='INFO'): self.log = super(vncNetwork, self).log(level=logLevel, name=vncNetwork.__name__)",
"networkObj subnet = vnc_api.SubnetType(prefix, prefixLen) if not allocTypeList: ipamSubnet = vnc_api.IpamSubnetType(subnet = subnet)",
"= vnc_api.IpamSubnetType(subnet = subnet) else: ipamSubnet = vnc_api.IpamSubnetType(subnet = subnet, allocation_pools=allocTypeList) networkObj.add_network_ipam(vnc_api.NetworkIpam(),vnc_api.VnSubnetsType([ipamSubnet])) newNetworkId",
"self.log.warn(\"Network: {0} already exists\".format(networkName)) return networkObj subnet = vnc_api.SubnetType(prefix, prefixLen) if not allocTypeList:",
"allocType.set_start(allocationPoolStart) allocType.set_end(allocationPoolStop) allocTypeList.append(allocType) except Exception as e: self.log.error(\"Function: createNetwork Message: allocationPool error :",
"allocTypeList.append(allocType) except Exception as e: self.log.error(\"Function: createNetwork Message: allocationPool error : {0}\".format(e)) return",
"subnet = vnc_api.SubnetType(prefix, prefixLen) if not allocTypeList: ipamSubnet = vnc_api.IpamSubnetType(subnet = subnet) else:",
"int(prefixLen) try: allocationPool = kwargs['allocationPool'] except KeyError, AttributeError: allocationPool = False try: routeTarget",
"self.vnc.project_update(self.tenantObj) return fipPool def _checkIfNetworkExists(self, networkObj, tenantObj): newFqName = networkObj.get_fq_name() vnList = self.vnc.virtual_networks_list(parent_id=tenantObj.uuid)",
"prefixLen = int(prefixLen) try: allocationPool = kwargs['allocationPool'] except KeyError, AttributeError: allocationPool = False",
"if not vnList: return False else: for elem in vnList['virtual-networks']: if(elem['fq_name'] == newFqName):",
"allocType = vnc_api.AllocationPoolType() allocType.set_start(allocationPoolStart) allocType.set_end(allocationPoolStop) allocTypeList.append(allocType) except Exception as e: self.log.error(\"Function: createNetwork Message:",
"allocationPoolStop = allocationPool.split('-') allocType = vnc_api.AllocationPoolType() allocType.set_start(allocationPoolStart) allocType.set_end(allocationPoolStop) allocTypeList.append(allocType) except Exception as e:",
"if type(allocationPool) == list: allocationPoolList = allocationPool else: allocationPoolList = [allocationPool] for allocationPool",
"else: for elem in vnList['virtual-networks']: if(elem['fq_name'] == newFqName): return True else: continue return",
"[allocationPool] for allocationPool in allocationPoolList: try: allocationPoolStart, allocationPoolStop = allocationPool.split('-') allocType = vnc_api.AllocationPoolType()",
",logLevel='INFO'): self.log = super(vncNetwork, self).log(level=logLevel, name=vncNetwork.__name__) self.vnc = vnc self.tenantName = tenantName self.domain",
"tenantName=self.tenantName) def createNetwork(self, **kwargs): _requiredArgs = ['cidr', 'name'] try: cidr = kwargs['cidr'] networkName",
"= allocationPool else: allocationPoolList = [allocationPool] for allocationPool in allocationPoolList: try: allocationPoolStart, allocationPoolStop",
"= self.returnFipObj(fipPoolName, networkObj) else: fipObj = None return networkObj, fipObj def returnFipObj(self, fipPoolName,",
"cidr is not in correct format : {0}\".format(e)) return False prefixLen = int(prefixLen)",
"try: allocationPool = kwargs['allocationPool'] except KeyError, AttributeError: allocationPool = False try: routeTarget =",
"return False else: for elem in vnList['virtual-networks']: if(elem['fq_name'] == newFqName): return True else:",
"exists\".format(networkName)) return networkObj subnet = vnc_api.SubnetType(prefix, prefixLen) if not allocTypeList: ipamSubnet = vnc_api.IpamSubnetType(subnet",
"Message: Error While Creating network : {0}\".format(e)) return False if routeTarget: try: updateNetwork",
"target to the network: {0}\".format(e)) return False if fipPoolName: fipObj = self.returnFipObj(fipPoolName, networkObj)",
"network: {0}\".format(e)) return False if fipPoolName: fipObj = self.returnFipObj(fipPoolName, networkObj) else: fipObj =",
"ArguementError(_requiredArgs, vncNetwork.createNetwork.__name__) except Exception as e: self.log.error(\"Function: createNetwork Message: cidr is not in",
"self.tenantName = tenantName self.domain = domain self.tenantObj = readTenant(self.vnc, domain=self.domain, tenantName=self.tenantName) def createNetwork(self,",
"'name'] try: cidr = kwargs['cidr'] networkName = kwargs['name'] prefix, prefixLen = cidr.split('/') except",
"allocationPoolList: try: allocationPoolStart, allocationPoolStop = allocationPool.split('-') allocType = vnc_api.AllocationPoolType() allocType.set_start(allocationPoolStart) allocType.set_end(allocationPoolStop) allocTypeList.append(allocType) except",
"import (readTenant, readNetwork) from hybridLogger import hybridLogger from exception import * import uuid",
"try: cidr = kwargs['cidr'] networkName = kwargs['name'] prefix, prefixLen = cidr.split('/') except KeyError:",
"exception import * import uuid class vncNetwork(hybridLogger): def __init__(self, vnc, domain, tenantName ,logLevel='INFO'):",
"self.tenantObj = readTenant(self.vnc, domain=self.domain, tenantName=self.tenantName) def createNetwork(self, **kwargs): _requiredArgs = ['cidr', 'name'] try:",
"self.log.error(\"Function: createNetwork Message: Error While Creating network : {0}\".format(e)) return False if routeTarget:",
"try: routeTargets = vnc_api.RouteTargetList(['target:' + routeTarget]) networkObj.set_route_target_list(routeTargets) return self.vnc.virtual_network_update(networkObj) except Exception as e:",
"self.log.info(\"Virtual Network: {0} created \".format(networkName)) except Exception as e: self.log.error(\"Function: createNetwork Message: Error",
"ipamSubnet = vnc_api.IpamSubnetType(subnet = subnet, allocation_pools=allocTypeList) networkObj.add_network_ipam(vnc_api.NetworkIpam(),vnc_api.VnSubnetsType([ipamSubnet])) newNetworkId = self.vnc.virtual_network_create(networkObj) self.log.info(\"Virtual Network: {0}",
"contrail.util import (readTenant, readNetwork) from hybridLogger import hybridLogger from exception import * import",
"{0}\".format(e)) return False if routeTarget: try: updateNetwork = self._addRouteTarget(networkObj, routeTarget) except Exception as",
"Creating network : {0}\".format(e)) return False if routeTarget: try: updateNetwork = self._addRouteTarget(networkObj, routeTarget)",
"self.log.error(\"Function: createNetwork Message: allocationPool error : {0}\".format(e)) return False try: fipPoolName = kwargs['fipPoolName']",
": {0}\".format(e)) return False prefixLen = int(prefixLen) try: allocationPool = kwargs['allocationPool'] except KeyError,",
"fipObj def returnFipObj(self, fipPoolName, networkObj): fipPoolId = str(uuid.uuid4()) fipPool = vnc_api.FloatingIpPool(name = fipPoolName,",
"kwargs['fipPoolName'] except KeyError, AttributeError: fipPoolName = False if fipPoolName: routerExternal = True else:",
"self.tenantObj.add_floating_ip_pool(fipPool) self.vnc.project_update(self.tenantObj) return fipPool def _checkIfNetworkExists(self, networkObj, tenantObj): newFqName = networkObj.get_fq_name() vnList =",
"self.vnc.virtual_networks_list(parent_id=tenantObj.uuid) if not vnList: return False else: for elem in vnList['virtual-networks']: if(elem['fq_name'] ==",
"def _checkIfNetworkExists(self, networkObj, tenantObj): newFqName = networkObj.get_fq_name() vnList = self.vnc.virtual_networks_list(parent_id=tenantObj.uuid) if not vnList:",
"the network: {0}\".format(e)) return False if fipPoolName: fipObj = self.returnFipObj(fipPoolName, networkObj) else: fipObj",
"try: updateNetwork = self._addRouteTarget(networkObj, routeTarget) except Exception as e: self.log.error(\"Function: createNetwork Message: Error",
"= self.vnc.virtual_network_create(networkObj) self.log.info(\"Virtual Network: {0} created \".format(networkName)) except Exception as e: self.log.error(\"Function: createNetwork",
"= str(uuid.uuid4()) fipPool = vnc_api.FloatingIpPool(name = fipPoolName, parent_obj = networkObj) fipPool.uuid = fipPoolId",
"domain self.tenantObj = readTenant(self.vnc, domain=self.domain, tenantName=self.tenantName) def createNetwork(self, **kwargs): _requiredArgs = ['cidr', 'name']",
"allocationPool = False try: routeTarget = kwargs['routeTarget'] except KeyError, AttributeError: routeTarget = False",
"routerExternal = False try: networkObj = vnc_api.VirtualNetwork(name=networkName, parent_obj=self.tenantObj, router_external=routerExternal) networkExists = self._checkIfNetworkExists(networkObj, self.tenantObj)",
"KeyError, AttributeError: allocationPool = False try: routeTarget = kwargs['routeTarget'] except KeyError, AttributeError: routeTarget",
"vnc_api.VirtualNetwork(name=networkName, parent_obj=self.tenantObj, router_external=routerExternal) networkExists = self._checkIfNetworkExists(networkObj, self.tenantObj) if networkExists: self.log.warn(\"Network: {0} already exists\".format(networkName))",
"Exception as e: self.log.error(\"Function: createNetwork Message: Error While Creating network : {0}\".format(e)) return",
"False if fipPoolName: fipObj = self.returnFipObj(fipPoolName, networkObj) else: fipObj = None return networkObj,",
"vnc_api.SubnetType(prefix, prefixLen) if not allocTypeList: ipamSubnet = vnc_api.IpamSubnetType(subnet = subnet) else: ipamSubnet =",
"def __init__(self, vnc, domain, tenantName ,logLevel='INFO'): self.log = super(vncNetwork, self).log(level=logLevel, name=vncNetwork.__name__) self.vnc =",
"allocationPoolList = allocationPool else: allocationPoolList = [allocationPool] for allocationPool in allocationPoolList: try: allocationPoolStart,",
"networkObj): fipPoolId = str(uuid.uuid4()) fipPool = vnc_api.FloatingIpPool(name = fipPoolName, parent_obj = networkObj) fipPool.uuid",
"= vnc_api.VirtualNetwork(name=networkName, parent_obj=self.tenantObj, router_external=routerExternal) networkExists = self._checkIfNetworkExists(networkObj, self.tenantObj) if networkExists: self.log.warn(\"Network: {0} already",
"routeTarget): try: routeTargets = vnc_api.RouteTargetList(['target:' + routeTarget]) networkObj.set_route_target_list(routeTargets) return self.vnc.virtual_network_update(networkObj) except Exception as",
"Exception as e: self.log.error(\"Function: createNetwork Message: cidr is not in correct format :",
"allocationPoolList = [allocationPool] for allocationPool in allocationPoolList: try: allocationPoolStart, allocationPoolStop = allocationPool.split('-') allocType",
"networkObj.get_fq_name() vnList = self.vnc.virtual_networks_list(parent_id=tenantObj.uuid) if not vnList: return False else: for elem in",
"except Exception as e: self.log.error(\"Function: createNetwork Message: allocationPool error : {0}\".format(e)) return False",
"newFqName = networkObj.get_fq_name() vnList = self.vnc.virtual_networks_list(parent_id=tenantObj.uuid) if not vnList: return False else: for",
"kwargs['routeTarget'] except KeyError, AttributeError: routeTarget = False allocTypeList = [] if allocationPool: if",
"= False allocTypeList = [] if allocationPool: if type(allocationPool) == list: allocationPoolList =",
"vnc, domain, tenantName ,logLevel='INFO'): self.log = super(vncNetwork, self).log(level=logLevel, name=vncNetwork.__name__) self.vnc = vnc self.tenantName",
"{0}\".format(e)) return False try: fipPoolName = kwargs['fipPoolName'] except KeyError, AttributeError: fipPoolName = False",
"self.tenantObj) if networkExists: self.log.warn(\"Network: {0} already exists\".format(networkName)) return networkObj subnet = vnc_api.SubnetType(prefix, prefixLen)",
"createNetwork Message: allocationPool error : {0}\".format(e)) return False try: fipPoolName = kwargs['fipPoolName'] except",
"not in correct format : {0}\".format(e)) return False prefixLen = int(prefixLen) try: allocationPool",
": {0}\".format(e)) return False if routeTarget: try: updateNetwork = self._addRouteTarget(networkObj, routeTarget) except Exception",
"kwargs['cidr'] networkName = kwargs['name'] prefix, prefixLen = cidr.split('/') except KeyError: raise ArguementError(_requiredArgs, vncNetwork.createNetwork.__name__)",
"readTenant(self.vnc, domain=self.domain, tenantName=self.tenantName) def createNetwork(self, **kwargs): _requiredArgs = ['cidr', 'name'] try: cidr =",
"prefix, prefixLen = cidr.split('/') except KeyError: raise ArguementError(_requiredArgs, vncNetwork.createNetwork.__name__) except Exception as e:",
"True else: routerExternal = False try: networkObj = vnc_api.VirtualNetwork(name=networkName, parent_obj=self.tenantObj, router_external=routerExternal) networkExists =",
"['cidr', 'name'] try: cidr = kwargs['cidr'] networkName = kwargs['name'] prefix, prefixLen = cidr.split('/')",
"vnc_api from contrail.util import (readTenant, readNetwork) from hybridLogger import hybridLogger from exception import",
"if allocationPool: if type(allocationPool) == list: allocationPoolList = allocationPool else: allocationPoolList = [allocationPool]",
"return networkObj subnet = vnc_api.SubnetType(prefix, prefixLen) if not allocTypeList: ipamSubnet = vnc_api.IpamSubnetType(subnet =",
"= fipPoolName, parent_obj = networkObj) fipPool.uuid = fipPoolId self.vnc.floating_ip_pool_create(fipPool) self.tenantObj.add_floating_ip_pool(fipPool) self.vnc.project_update(self.tenantObj) return fipPool",
"routeTarget = kwargs['routeTarget'] except KeyError, AttributeError: routeTarget = False allocTypeList = [] if",
"= [] if allocationPool: if type(allocationPool) == list: allocationPoolList = allocationPool else: allocationPoolList",
"fipPoolName: fipObj = self.returnFipObj(fipPoolName, networkObj) else: fipObj = None return networkObj, fipObj def",
"self.returnFipObj(fipPoolName, networkObj) else: fipObj = None return networkObj, fipObj def returnFipObj(self, fipPoolName, networkObj):",
"format : {0}\".format(e)) return False prefixLen = int(prefixLen) try: allocationPool = kwargs['allocationPool'] except",
"KeyError, AttributeError: routeTarget = False allocTypeList = [] if allocationPool: if type(allocationPool) ==",
"= subnet, allocation_pools=allocTypeList) networkObj.add_network_ipam(vnc_api.NetworkIpam(),vnc_api.VnSubnetsType([ipamSubnet])) newNetworkId = self.vnc.virtual_network_create(networkObj) self.log.info(\"Virtual Network: {0} created \".format(networkName)) except",
"allocationPool in allocationPoolList: try: allocationPoolStart, allocationPoolStop = allocationPool.split('-') allocType = vnc_api.AllocationPoolType() allocType.set_start(allocationPoolStart) allocType.set_end(allocationPoolStop)",
"fipPoolName, networkObj): fipPoolId = str(uuid.uuid4()) fipPool = vnc_api.FloatingIpPool(name = fipPoolName, parent_obj = networkObj)",
"vnList = self.vnc.virtual_networks_list(parent_id=tenantObj.uuid) if not vnList: return False else: for elem in vnList['virtual-networks']:",
"networkExists: self.log.warn(\"Network: {0} already exists\".format(networkName)) return networkObj subnet = vnc_api.SubnetType(prefix, prefixLen) if not",
"= self._checkIfNetworkExists(networkObj, self.tenantObj) if networkExists: self.log.warn(\"Network: {0} already exists\".format(networkName)) return networkObj subnet =",
"networkObj, fipObj def returnFipObj(self, fipPoolName, networkObj): fipPoolId = str(uuid.uuid4()) fipPool = vnc_api.FloatingIpPool(name =",
"False prefixLen = int(prefixLen) try: allocationPool = kwargs['allocationPool'] except KeyError, AttributeError: allocationPool =",
"Exception as e: self.log.error(\"Function: createNetwork Message: allocationPool error : {0}\".format(e)) return False try:",
"parent_obj=self.tenantObj, router_external=routerExternal) networkExists = self._checkIfNetworkExists(networkObj, self.tenantObj) if networkExists: self.log.warn(\"Network: {0} already exists\".format(networkName)) return",
"vnList: return False else: for elem in vnList['virtual-networks']: if(elem['fq_name'] == newFqName): return True",
"allocType.set_end(allocationPoolStop) allocTypeList.append(allocType) except Exception as e: self.log.error(\"Function: createNetwork Message: allocationPool error : {0}\".format(e))",
"(readTenant, readNetwork) from hybridLogger import hybridLogger from exception import * import uuid class",
"import * import uuid class vncNetwork(hybridLogger): def __init__(self, vnc, domain, tenantName ,logLevel='INFO'): self.log",
"adding route target to the network: {0}\".format(e)) return False if fipPoolName: fipObj =",
"def createNetwork(self, **kwargs): _requiredArgs = ['cidr', 'name'] try: cidr = kwargs['cidr'] networkName =",
"if fipPoolName: fipObj = self.returnFipObj(fipPoolName, networkObj) else: fipObj = None return networkObj, fipObj",
"networkObj) fipPool.uuid = fipPoolId self.vnc.floating_ip_pool_create(fipPool) self.tenantObj.add_floating_ip_pool(fipPool) self.vnc.project_update(self.tenantObj) return fipPool def _checkIfNetworkExists(self, networkObj, tenantObj):",
"allocationPool: if type(allocationPool) == list: allocationPoolList = allocationPool else: allocationPoolList = [allocationPool] for",
"allocationPool else: allocationPoolList = [allocationPool] for allocationPool in allocationPoolList: try: allocationPoolStart, allocationPoolStop =",
"createNetwork Message: Error While Creating network : {0}\".format(e)) return False if routeTarget: try:",
"readNetwork) from hybridLogger import hybridLogger from exception import * import uuid class vncNetwork(hybridLogger):",
"import vnc_api from contrail.util import (readTenant, readNetwork) from hybridLogger import hybridLogger from exception",
"KeyError, AttributeError: fipPoolName = False if fipPoolName: routerExternal = True else: routerExternal =",
"= vnc_api.IpamSubnetType(subnet = subnet, allocation_pools=allocTypeList) networkObj.add_network_ipam(vnc_api.NetworkIpam(),vnc_api.VnSubnetsType([ipamSubnet])) newNetworkId = self.vnc.virtual_network_create(networkObj) self.log.info(\"Virtual Network: {0} created",
"networkObj.add_network_ipam(vnc_api.NetworkIpam(),vnc_api.VnSubnetsType([ipamSubnet])) newNetworkId = self.vnc.virtual_network_create(networkObj) self.log.info(\"Virtual Network: {0} created \".format(networkName)) except Exception as e:",
"= networkObj) fipPool.uuid = fipPoolId self.vnc.floating_ip_pool_create(fipPool) self.tenantObj.add_floating_ip_pool(fipPool) self.vnc.project_update(self.tenantObj) return fipPool def _checkIfNetworkExists(self, networkObj,",
"subnet) else: ipamSubnet = vnc_api.IpamSubnetType(subnet = subnet, allocation_pools=allocTypeList) networkObj.add_network_ipam(vnc_api.NetworkIpam(),vnc_api.VnSubnetsType([ipamSubnet])) newNetworkId = self.vnc.virtual_network_create(networkObj) self.log.info(\"Virtual",
"\".format(networkName)) except Exception as e: self.log.error(\"Function: createNetwork Message: Error While Creating network :",
"__init__(self, vnc, domain, tenantName ,logLevel='INFO'): self.log = super(vncNetwork, self).log(level=logLevel, name=vncNetwork.__name__) self.vnc = vnc",
"Exception as e: self.log.error(\"Function: createNetwork Message: Error While adding route target to the",
"return False if fipPoolName: fipObj = self.returnFipObj(fipPoolName, networkObj) else: fipObj = None return",
"= readTenant(self.vnc, domain=self.domain, tenantName=self.tenantName) def createNetwork(self, **kwargs): _requiredArgs = ['cidr', 'name'] try: cidr",
"as e: self.log.error(\"Function: createNetwork Message: allocationPool error : {0}\".format(e)) return False try: fipPoolName",
"= kwargs['fipPoolName'] except KeyError, AttributeError: fipPoolName = False if fipPoolName: routerExternal = True",
"newFqName): return True else: continue return False def _addRouteTarget(self, networkObj, routeTarget): try: routeTargets",
"= networkObj.get_fq_name() vnList = self.vnc.virtual_networks_list(parent_id=tenantObj.uuid) if not vnList: return False else: for elem",
"cidr.split('/') except KeyError: raise ArguementError(_requiredArgs, vncNetwork.createNetwork.__name__) except Exception as e: self.log.error(\"Function: createNetwork Message:",
"= int(prefixLen) try: allocationPool = kwargs['allocationPool'] except KeyError, AttributeError: allocationPool = False try:",
"fipPoolName = False if fipPoolName: routerExternal = True else: routerExternal = False try:",
"tenantName ,logLevel='INFO'): self.log = super(vncNetwork, self).log(level=logLevel, name=vncNetwork.__name__) self.vnc = vnc self.tenantName = tenantName",
"= vnc_api.AllocationPoolType() allocType.set_start(allocationPoolStart) allocType.set_end(allocationPoolStop) allocTypeList.append(allocType) except Exception as e: self.log.error(\"Function: createNetwork Message: allocationPool",
"fipPoolId = str(uuid.uuid4()) fipPool = vnc_api.FloatingIpPool(name = fipPoolName, parent_obj = networkObj) fipPool.uuid =",
"networkObj, routeTarget): try: routeTargets = vnc_api.RouteTargetList(['target:' + routeTarget]) networkObj.set_route_target_list(routeTargets) return self.vnc.virtual_network_update(networkObj) except Exception",
"tenantObj): newFqName = networkObj.get_fq_name() vnList = self.vnc.virtual_networks_list(parent_id=tenantObj.uuid) if not vnList: return False else:",
"ipamSubnet = vnc_api.IpamSubnetType(subnet = subnet) else: ipamSubnet = vnc_api.IpamSubnetType(subnet = subnet, allocation_pools=allocTypeList) networkObj.add_network_ipam(vnc_api.NetworkIpam(),vnc_api.VnSubnetsType([ipamSubnet]))",
": {0}\".format(e)) return False try: fipPoolName = kwargs['fipPoolName'] except KeyError, AttributeError: fipPoolName =",
"allocation_pools=allocTypeList) networkObj.add_network_ipam(vnc_api.NetworkIpam(),vnc_api.VnSubnetsType([ipamSubnet])) newNetworkId = self.vnc.virtual_network_create(networkObj) self.log.info(\"Virtual Network: {0} created \".format(networkName)) except Exception as",
"e: self.log.error(\"Function: createNetwork Message: allocationPool error : {0}\".format(e)) return False try: fipPoolName =",
"routeTarget: try: updateNetwork = self._addRouteTarget(networkObj, routeTarget) except Exception as e: self.log.error(\"Function: createNetwork Message:",
"prefixLen = cidr.split('/') except KeyError: raise ArguementError(_requiredArgs, vncNetwork.createNetwork.__name__) except Exception as e: self.log.error(\"Function:",
"Message: allocationPool error : {0}\".format(e)) return False try: fipPoolName = kwargs['fipPoolName'] except KeyError,",
"allocationPool.split('-') allocType = vnc_api.AllocationPoolType() allocType.set_start(allocationPoolStart) allocType.set_end(allocationPoolStop) allocTypeList.append(allocType) except Exception as e: self.log.error(\"Function: createNetwork",
"= kwargs['routeTarget'] except KeyError, AttributeError: routeTarget = False allocTypeList = [] if allocationPool:",
"= allocationPool.split('-') allocType = vnc_api.AllocationPoolType() allocType.set_start(allocationPoolStart) allocType.set_end(allocationPoolStop) allocTypeList.append(allocType) except Exception as e: self.log.error(\"Function:",
"except KeyError, AttributeError: fipPoolName = False if fipPoolName: routerExternal = True else: routerExternal",
"_addRouteTarget(self, networkObj, routeTarget): try: routeTargets = vnc_api.RouteTargetList(['target:' + routeTarget]) networkObj.set_route_target_list(routeTargets) return self.vnc.virtual_network_update(networkObj) except",
"except KeyError: raise ArguementError(_requiredArgs, vncNetwork.createNetwork.__name__) except Exception as e: self.log.error(\"Function: createNetwork Message: cidr",
"in vnList['virtual-networks']: if(elem['fq_name'] == newFqName): return True else: continue return False def _addRouteTarget(self,",
"networkObj = vnc_api.VirtualNetwork(name=networkName, parent_obj=self.tenantObj, router_external=routerExternal) networkExists = self._checkIfNetworkExists(networkObj, self.tenantObj) if networkExists: self.log.warn(\"Network: {0}",
"= super(vncNetwork, self).log(level=logLevel, name=vncNetwork.__name__) self.vnc = vnc self.tenantName = tenantName self.domain = domain",
"vnc_api.IpamSubnetType(subnet = subnet, allocation_pools=allocTypeList) networkObj.add_network_ipam(vnc_api.NetworkIpam(),vnc_api.VnSubnetsType([ipamSubnet])) newNetworkId = self.vnc.virtual_network_create(networkObj) self.log.info(\"Virtual Network: {0} created \".format(networkName))",
"vnList['virtual-networks']: if(elem['fq_name'] == newFqName): return True else: continue return False def _addRouteTarget(self, networkObj,",
"def returnFipObj(self, fipPoolName, networkObj): fipPoolId = str(uuid.uuid4()) fipPool = vnc_api.FloatingIpPool(name = fipPoolName, parent_obj",
"== list: allocationPoolList = allocationPool else: allocationPoolList = [allocationPool] for allocationPool in allocationPoolList:",
"networkName = kwargs['name'] prefix, prefixLen = cidr.split('/') except KeyError: raise ArguementError(_requiredArgs, vncNetwork.createNetwork.__name__) except",
"e: self.log.error(\"Function: createNetwork Message: Error While Creating network : {0}\".format(e)) return False if",
"self.log = super(vncNetwork, self).log(level=logLevel, name=vncNetwork.__name__) self.vnc = vnc self.tenantName = tenantName self.domain =",
"from contrail.util import (readTenant, readNetwork) from hybridLogger import hybridLogger from exception import *",
"error : {0}\".format(e)) return False try: fipPoolName = kwargs['fipPoolName'] except KeyError, AttributeError: fipPoolName",
"routeTargets = vnc_api.RouteTargetList(['target:' + routeTarget]) networkObj.set_route_target_list(routeTargets) return self.vnc.virtual_network_update(networkObj) except Exception as e: raise",
"= ['cidr', 'name'] try: cidr = kwargs['cidr'] networkName = kwargs['name'] prefix, prefixLen =",
"False if routeTarget: try: updateNetwork = self._addRouteTarget(networkObj, routeTarget) except Exception as e: self.log.error(\"Function:",
"return False try: fipPoolName = kwargs['fipPoolName'] except KeyError, AttributeError: fipPoolName = False if",
"self).log(level=logLevel, name=vncNetwork.__name__) self.vnc = vnc self.tenantName = tenantName self.domain = domain self.tenantObj =",
"networkExists = self._checkIfNetworkExists(networkObj, self.tenantObj) if networkExists: self.log.warn(\"Network: {0} already exists\".format(networkName)) return networkObj subnet",
"already exists\".format(networkName)) return networkObj subnet = vnc_api.SubnetType(prefix, prefixLen) if not allocTypeList: ipamSubnet =",
"e: self.log.error(\"Function: createNetwork Message: cidr is not in correct format : {0}\".format(e)) return",
"Error While adding route target to the network: {0}\".format(e)) return False if fipPoolName:",
"hybridLogger import hybridLogger from exception import * import uuid class vncNetwork(hybridLogger): def __init__(self,",
"kwargs['allocationPool'] except KeyError, AttributeError: allocationPool = False try: routeTarget = kwargs['routeTarget'] except KeyError,",
"{0}\".format(e)) return False if fipPoolName: fipObj = self.returnFipObj(fipPoolName, networkObj) else: fipObj = None",
"createNetwork(self, **kwargs): _requiredArgs = ['cidr', 'name'] try: cidr = kwargs['cidr'] networkName = kwargs['name']",
"route target to the network: {0}\".format(e)) return False if fipPoolName: fipObj = self.returnFipObj(fipPoolName,",
"Network: {0} created \".format(networkName)) except Exception as e: self.log.error(\"Function: createNetwork Message: Error While",
"import hybridLogger from exception import * import uuid class vncNetwork(hybridLogger): def __init__(self, vnc,",
"routeTarget) except Exception as e: self.log.error(\"Function: createNetwork Message: Error While adding route target",
"vnc_api import vnc_api from contrail.util import (readTenant, readNetwork) from hybridLogger import hybridLogger from",
"Error While Creating network : {0}\".format(e)) return False if routeTarget: try: updateNetwork =",
"for elem in vnList['virtual-networks']: if(elem['fq_name'] == newFqName): return True else: continue return False",
"from exception import * import uuid class vncNetwork(hybridLogger): def __init__(self, vnc, domain, tenantName",
"= cidr.split('/') except KeyError: raise ArguementError(_requiredArgs, vncNetwork.createNetwork.__name__) except Exception as e: self.log.error(\"Function: createNetwork",
"Message: Error While adding route target to the network: {0}\".format(e)) return False if",
"as e: self.log.error(\"Function: createNetwork Message: Error While adding route target to the network:",
"subnet, allocation_pools=allocTypeList) networkObj.add_network_ipam(vnc_api.NetworkIpam(),vnc_api.VnSubnetsType([ipamSubnet])) newNetworkId = self.vnc.virtual_network_create(networkObj) self.log.info(\"Virtual Network: {0} created \".format(networkName)) except Exception",
"self.domain = domain self.tenantObj = readTenant(self.vnc, domain=self.domain, tenantName=self.tenantName) def createNetwork(self, **kwargs): _requiredArgs =",
"self.log.error(\"Function: createNetwork Message: Error While adding route target to the network: {0}\".format(e)) return",
"True else: continue return False def _addRouteTarget(self, networkObj, routeTarget): try: routeTargets = vnc_api.RouteTargetList(['target:'",
"list: allocationPoolList = allocationPool else: allocationPoolList = [allocationPool] for allocationPool in allocationPoolList: try:",
"vnc self.tenantName = tenantName self.domain = domain self.tenantObj = readTenant(self.vnc, domain=self.domain, tenantName=self.tenantName) def",
"= False try: networkObj = vnc_api.VirtualNetwork(name=networkName, parent_obj=self.tenantObj, router_external=routerExternal) networkExists = self._checkIfNetworkExists(networkObj, self.tenantObj) if",
"is not in correct format : {0}\".format(e)) return False prefixLen = int(prefixLen) try:",
"hybridLogger from exception import * import uuid class vncNetwork(hybridLogger): def __init__(self, vnc, domain,",
"if routeTarget: try: updateNetwork = self._addRouteTarget(networkObj, routeTarget) except Exception as e: self.log.error(\"Function: createNetwork",
"return False def _addRouteTarget(self, networkObj, routeTarget): try: routeTargets = vnc_api.RouteTargetList(['target:' + routeTarget]) networkObj.set_route_target_list(routeTargets)",
"AttributeError: fipPoolName = False if fipPoolName: routerExternal = True else: routerExternal = False"
] |
[
"repository diff Show changes between commits, commit and working tree, etc merge Join",
"everyday) add Add file contents to the index mv Move or rename a",
"help everyday) add Add file contents to the index mv Move or rename",
"'clear') os.system('python refresh.py') exit() elif(command.count('cat ')): command = command.replace(\"cat \", \"\") cat =",
"index examine the history and state (see also: git help revisions) bisect Use",
"with associated objects 'git help -a' and 'git help -g' list available subcommands",
"file cd browse directories ls listing files clear clean terminal ''' while True:",
"current HEAD to the specified state rm Remove files from the working tree",
"= input(f'{desktop}:# ') if command == 'ls': #listing files os.chdir(location) print(location) location =",
"command = command.replace(\"cd \", \"\") os.chdir(command) location = os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}')",
"Move or rename a file, a directory, or a symlink reset Reset current",
"history and state (see also: git help revisions) bisect Use binary search to",
"commit logs show Show various types of objects status Show the working tree",
"= ''' These are common Git commands used in various situations: start a",
"Add file contents to the index mv Move or rename a file, a",
"list available subcommands and some concept guides. See 'git help <command>' or 'git",
"#browsing the files location = str(command).replace(\"cd\", \"\").replace(\" \",\"\") if(command.count(\"..\")): os.chdir('../') location = os.getcwd()",
"'ls': #listing files os.chdir(location) print(location) location = os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') for",
"'': pass elif command == 'help' or command == 'commands': print(command_list) elif(command.count('wget ')):",
"clean terminal ''' while True: command = input(f'{desktop}:# ') if command == 'ls':",
"objects status Show the working tree status grow, mark and tweak your common",
"changes to the repository diff Show changes between commits, commit and working tree,",
"missing URL git help -g' list available subcommands cat list content in file",
"revisions) bisect Use binary search to find the commit that introduced a bug",
"(see also: git help workflows) fetch Download objects and refs from another repository",
"''' command_list = ''' List of Commands wget missing URL git help -g'",
"clone Clone a repository into a new directory init Create an empty Git",
"'t': os.system(command) elif command == '': pass elif command == 'help' or command",
"cat = open(f'{command}', 'r') content = cat.readlines() #listing content of file print('\\n') for",
"os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') else: command = command.replace(\"cd \", \"\") os.chdir(command) location",
"') if command == 'ls': #listing files os.chdir(location) print(location) location = os.getcwd() desktop",
"the working tree and from the index examine the history and state (see",
"commit that introduced a bug grep Print lines matching a pattern log Show",
"history branch List, create, or delete branches checkout Switch branches or restore working",
"help_git = ''' These are common Git commands used in various situations: start",
"os.system(command) elif command == '': pass elif command == 'help' or command ==",
"also: git help everyday) add Add file contents to the index mv Move",
"an existing one work on the current change (see also: git help everyday)",
"command = input(f'{desktop}:# ') if command == 'ls': #listing files os.chdir(location) print(location) location",
"and some concept guides. See 'git help <command>' or 'git help <concept>' to",
"f'{data}') else: command = command.replace(\"cd \", \"\") os.chdir(command) location = os.getcwd() desktop =",
"working tree status grow, mark and tweak your common history branch List, create,",
"in file cd browse directories ls listing files clear clean terminal ''' while",
"'i' and command[2] == 't': os.system(command) elif command == '': pass elif command",
"terminal os.system('cls' if os.name == 'nt' else 'clear') os.system('python refresh.py') exit() elif(command.count('cat ')):",
"os.system('cls' if os.name == 'nt' else 'clear') os.system('python refresh.py') exit() elif(command.count('cat ')): command",
"Download objects and refs from another repository pull Fetch from and integrate with",
"branch push Update remote refs along with associated objects 'git help -a' and",
"= open(f'{command}', 'r') content = cat.readlines() #listing content of file print('\\n') for line",
"= os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') else: command = command.replace(\"cd \", \"\") os.chdir(command)",
"to the index mv Move or rename a file, a directory, or a",
"verify a tag object signed with GPG collaborate (see also: git help workflows)",
"os.system('python refresh.py') exit() elif(command.count('cat ')): command = command.replace(\"cat \", \"\") cat = open(f'{command}',",
"git help -g' list available subcommands cat list content in file cd browse",
"push Update remote refs along with associated objects 'git help -a' and 'git",
"branches or restore working tree files commit Record changes to the repository diff",
"tree and from the index examine the history and state (see also: git",
"tutorial) clone Clone a repository into a new directory init Create an empty",
"rm Remove files from the working tree and from the index examine the",
"list content in file cd browse directories ls listing files clear clean terminal",
"else 'clear') os.system('python refresh.py') exit() elif(command.count('cat ')): command = command.replace(\"cat \", \"\") cat",
"os import glob files = open('dados.dll') data = files.read() files.close #desktop of user",
"cd browse directories ls listing files clear clean terminal ''' while True: command",
"are common Git commands used in various situations: start a working area (see",
"os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') for file in glob.glob(\"*\"): print(file) elif(command[0] == 'c' and command[1] ==",
"Record changes to the repository diff Show changes between commits, commit and working",
"= os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') for file in glob.glob(\"*\"): print(file) elif(command[0] ==",
"to read about a specific subcommand or concept. ''' command_list = ''' List",
"cat.readlines() #listing content of file print('\\n') for line in content: print(line) cat.close() print('\\n')",
"= os.path.expanduser('~\\\\Desktop') desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') os.chdir(location) help_git = ''' These are common",
"'git help -g' list available subcommands and some concept guides. See 'git help",
"of file print('\\n') for line in content: print(line) cat.close() print('\\n') elif command[0] ==",
"and working tree, etc merge Join two or more development histories together rebase",
"the history and state (see also: git help revisions) bisect Use binary search",
"command == 'help' or command == 'commands': print(command_list) elif(command.count('wget ')): print(os.getcwd()) elif(command ==",
"files.close #desktop of user user_info = os.path.expanduser('~') location_default = os.path.expanduser('~\\\\Desktop') location = os.path.expanduser('~\\\\Desktop')",
"or verify a tag object signed with GPG collaborate (see also: git help",
"command == '': pass elif command == 'help' or command == 'commands': print(command_list)",
"a bug grep Print lines matching a pattern log Show commit logs show",
"if os.name == 'nt' else 'clear') elif command == 'refresh': #restart of terminal",
"git help everyday) add Add file contents to the index mv Move or",
"refs from another repository pull Fetch from and integrate with another repository or",
"to the repository diff Show changes between commits, commit and working tree, etc",
"concept. ''' command_list = ''' List of Commands wget missing URL git help",
"True: command = input(f'{desktop}:# ') if command == 'ls': #listing files os.chdir(location) print(location)",
"help -g' list available subcommands cat list content in file cd browse directories",
"existing one work on the current change (see also: git help everyday) add",
"into a new directory init Create an empty Git repository or reinitialize an",
"Show various types of objects status Show the working tree status grow, mark",
"Git commands used in various situations: start a working area (see also: git",
"lines matching a pattern log Show commit logs show Show various types of",
"index mv Move or rename a file, a directory, or a symlink reset",
"Remove files from the working tree and from the index examine the history",
"'g' and command[1] == 'i' and command[2] == 't': os.system(command) elif command ==",
"change (see also: git help everyday) add Add file contents to the index",
"etc merge Join two or more development histories together rebase Reapply commits on",
"(see also: git help revisions) bisect Use binary search to find the commit",
"collaborate (see also: git help workflows) fetch Download objects and refs from another",
"command[2] == 't': os.system(command) elif command == '': pass elif command == 'help'",
"-g' list available subcommands cat list content in file cd browse directories ls",
"command[1] == 'd'): #browsing the files location = str(command).replace(\"cd\", \"\").replace(\" \",\"\") if(command.count(\"..\")): os.chdir('../')",
"help revisions) bisect Use binary search to find the commit that introduced a",
"glob.glob(\"*\"): print(file) elif(command[0] == 'c' and command[1] == 'd'): #browsing the files location",
"create, or delete branches checkout Switch branches or restore working tree files commit",
"if command == 'ls': #listing files os.chdir(location) print(location) location = os.getcwd() desktop =",
"os.name == 'nt' else 'clear') os.system('python refresh.py') exit() elif(command.count('cat ')): command = command.replace(\"cat",
"file, a directory, or a symlink reset Reset current HEAD to the specified",
"ls listing files clear clean terminal ''' while True: command = input(f'{desktop}:# ')",
"the index examine the history and state (see also: git help revisions) bisect",
"os.chdir(location) print(location) location = os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') for file in glob.glob(\"*\"):",
"along with associated objects 'git help -a' and 'git help -g' list available",
"<command>' or 'git help <concept>' to read about a specific subcommand or concept.",
"git help workflows) fetch Download objects and refs from another repository pull Fetch",
"your common history branch List, create, or delete branches checkout Switch branches or",
"Git repository or reinitialize an existing one work on the current change (see",
"bisect Use binary search to find the commit that introduced a bug grep",
"various situations: start a working area (see also: git help tutorial) clone Clone",
"bug grep Print lines matching a pattern log Show commit logs show Show",
"working tree files commit Record changes to the repository diff Show changes between",
"Print lines matching a pattern log Show commit logs show Show various types",
"git help tutorial) clone Clone a repository into a new directory init Create",
"commits, commit and working tree, etc merge Join two or more development histories",
"== 'd'): #browsing the files location = str(command).replace(\"cd\", \"\").replace(\" \",\"\") if(command.count(\"..\")): os.chdir('../') location",
"refresh.py') exit() elif(command.count('cat ')): command = command.replace(\"cat \", \"\") cat = open(f'{command}', 'r')",
"development histories together rebase Reapply commits on top of another base tip tag",
"a symlink reset Reset current HEAD to the specified state rm Remove files",
"delete or verify a tag object signed with GPG collaborate (see also: git",
"pass elif command == 'help' or command == 'commands': print(command_list) elif(command.count('wget ')): print(os.getcwd())",
"the current change (see also: git help everyday) add Add file contents to",
"examine the history and state (see also: git help revisions) bisect Use binary",
"symlink reset Reset current HEAD to the specified state rm Remove files from",
"tree status grow, mark and tweak your common history branch List, create, or",
"cat list content in file cd browse directories ls listing files clear clean",
"tag object signed with GPG collaborate (see also: git help workflows) fetch Download",
"in glob.glob(\"*\"): print(file) elif(command[0] == 'c' and command[1] == 'd'): #browsing the files",
"URL git help -g' list available subcommands cat list content in file cd",
"= cat.readlines() #listing content of file print('\\n') for line in content: print(line) cat.close()",
"working tree, etc merge Join two or more development histories together rebase Reapply",
"data = files.read() files.close #desktop of user user_info = os.path.expanduser('~') location_default = os.path.expanduser('~\\\\Desktop')",
"mark and tweak your common history branch List, create, or delete branches checkout",
"one work on the current change (see also: git help everyday) add Add",
"import os import glob files = open('dados.dll') data = files.read() files.close #desktop of",
"to the specified state rm Remove files from the working tree and from",
"local branch push Update remote refs along with associated objects 'git help -a'",
"Use binary search to find the commit that introduced a bug grep Print",
"= ''' List of Commands wget missing URL git help -g' list available",
"various types of objects status Show the working tree status grow, mark and",
"of Commands wget missing URL git help -g' list available subcommands cat list",
"common Git commands used in various situations: start a working area (see also:",
"= files.read() files.close #desktop of user user_info = os.path.expanduser('~') location_default = os.path.expanduser('~\\\\Desktop') location",
"and 'git help -g' list available subcommands and some concept guides. See 'git",
"to find the commit that introduced a bug grep Print lines matching a",
"Join two or more development histories together rebase Reapply commits on top of",
"Fetch from and integrate with another repository or a local branch push Update",
"in terminal os.system('cls' if os.name == 'nt' else 'clear') elif command == 'refresh':",
"pull Fetch from and integrate with another repository or a local branch push",
"\"\").replace(\" \",\"\") if(command.count(\"..\")): os.chdir('../') location = os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') else: command",
"if(command.count(\"..\")): os.chdir('../') location = os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') else: command = command.replace(\"cd",
"'clear': #clean in terminal os.system('cls' if os.name == 'nt' else 'clear') elif command",
"else: command = command.replace(\"cd \", \"\") os.chdir(command) location = os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}',",
"cat.close() print('\\n') elif command[0] == 'g' and command[1] == 'i' and command[2] ==",
"list available subcommands cat list content in file cd browse directories ls listing",
"elif command == 'refresh': #restart of terminal os.system('cls' if os.name == 'nt' else",
"command == 'ls': #listing files os.chdir(location) print(location) location = os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}',",
"or concept. ''' command_list = ''' List of Commands wget missing URL git",
"command.replace(\"cd \", \"\") os.chdir(command) location = os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') elif command",
"rename a file, a directory, or a symlink reset Reset current HEAD to",
"listing files clear clean terminal ''' while True: command = input(f'{desktop}:# ') if",
"tree, etc merge Join two or more development histories together rebase Reapply commits",
"= open('dados.dll') data = files.read() files.close #desktop of user user_info = os.path.expanduser('~') location_default",
"print(file) elif(command[0] == 'c' and command[1] == 'd'): #browsing the files location =",
"mv Move or rename a file, a directory, or a symlink reset Reset",
"str(command).replace(\"cd\", \"\").replace(\" \",\"\") if(command.count(\"..\")): os.chdir('../') location = os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') else:",
"pattern log Show commit logs show Show various types of objects status Show",
"and command[2] == 't': os.system(command) elif command == '': pass elif command ==",
"os.name == 'nt' else 'clear') elif command == 'refresh': #restart of terminal os.system('cls'",
"reset Reset current HEAD to the specified state rm Remove files from the",
"another base tip tag Create, list, delete or verify a tag object signed",
"== '': pass elif command == 'help' or command == 'commands': print(command_list) elif(command.count('wget",
"repository pull Fetch from and integrate with another repository or a local branch",
"== 'nt' else 'clear') elif command == 'refresh': #restart of terminal os.system('cls' if",
"of user user_info = os.path.expanduser('~') location_default = os.path.expanduser('~\\\\Desktop') location = os.path.expanduser('~\\\\Desktop') desktop =",
"wget missing URL git help -g' list available subcommands cat list content in",
"subcommand or concept. ''' command_list = ''' List of Commands wget missing URL",
"files = open('dados.dll') data = files.read() files.close #desktop of user user_info = os.path.expanduser('~')",
"Switch branches or restore working tree files commit Record changes to the repository",
"#listing files os.chdir(location) print(location) location = os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') for file",
"specified state rm Remove files from the working tree and from the index",
"os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') elif command == 'clear': #clean in terminal os.system('cls'",
"git help revisions) bisect Use binary search to find the commit that introduced",
"checkout Switch branches or restore working tree files commit Record changes to the",
"== 'clear': #clean in terminal os.system('cls' if os.name == 'nt' else 'clear') elif",
"os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') for file in glob.glob(\"*\"): print(file) elif(command[0] == 'c'",
"#clean in terminal os.system('cls' if os.name == 'nt' else 'clear') elif command ==",
"location = os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') else: command = command.replace(\"cd \", \"\")",
"command_list = ''' List of Commands wget missing URL git help -g' list",
"or rename a file, a directory, or a symlink reset Reset current HEAD",
"os.path.expanduser('~\\\\Desktop') desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') os.chdir(location) help_git = ''' These are common Git",
"GPG collaborate (see also: git help workflows) fetch Download objects and refs from",
"repository or a local branch push Update remote refs along with associated objects",
"== 't': os.system(command) elif command == '': pass elif command == 'help' or",
"Reapply commits on top of another base tip tag Create, list, delete or",
"from another repository pull Fetch from and integrate with another repository or a",
"file print('\\n') for line in content: print(line) cat.close() print('\\n') elif command[0] == 'g'",
"guides. See 'git help <command>' or 'git help <concept>' to read about a",
"grep Print lines matching a pattern log Show commit logs show Show various",
"(see also: git help tutorial) clone Clone a repository into a new directory",
"command[0] == 'g' and command[1] == 'i' and command[2] == 't': os.system(command) elif",
"Commands wget missing URL git help -g' list available subcommands cat list content",
"open('dados.dll') data = files.read() files.close #desktop of user user_info = os.path.expanduser('~') location_default =",
"'clear') elif command == 'refresh': #restart of terminal os.system('cls' if os.name == 'nt'",
"command[1] == 'i' and command[2] == 't': os.system(command) elif command == '': pass",
"tip tag Create, list, delete or verify a tag object signed with GPG",
"<concept>' to read about a specific subcommand or concept. ''' command_list = '''",
"fetch Download objects and refs from another repository pull Fetch from and integrate",
"tag Create, list, delete or verify a tag object signed with GPG collaborate",
"or reinitialize an existing one work on the current change (see also: git",
"log Show commit logs show Show various types of objects status Show the",
"signed with GPG collaborate (see also: git help workflows) fetch Download objects and",
"= os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') for file in glob.glob(\"*\"): print(file) elif(command[0] == 'c' and command[1]",
"a specific subcommand or concept. ''' command_list = ''' List of Commands wget",
"or restore working tree files commit Record changes to the repository diff Show",
"files.read() files.close #desktop of user user_info = os.path.expanduser('~') location_default = os.path.expanduser('~\\\\Desktop') location =",
"else 'clear') elif command == 'refresh': #restart of terminal os.system('cls' if os.name ==",
"concept guides. See 'git help <command>' or 'git help <concept>' to read about",
"browse directories ls listing files clear clean terminal ''' while True: command =",
"tree files commit Record changes to the repository diff Show changes between commits,",
"elif command == 'help' or command == 'commands': print(command_list) elif(command.count('wget ')): print(os.getcwd()) elif(command",
"')): command = command.replace(\"cat \", \"\") cat = open(f'{command}', 'r') content = cat.readlines()",
"help tutorial) clone Clone a repository into a new directory init Create an",
"location = str(command).replace(\"cd\", \"\").replace(\" \",\"\") if(command.count(\"..\")): os.chdir('../') location = os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}',",
"of objects status Show the working tree status grow, mark and tweak your",
"\",\"\") if(command.count(\"..\")): os.chdir('../') location = os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') else: command =",
"HEAD to the specified state rm Remove files from the working tree and",
"a local branch push Update remote refs along with associated objects 'git help",
"os.chdir(command) location = os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') elif command == 'clear': #clean",
"desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') else: command = command.replace(\"cd \", \"\") os.chdir(command) location =",
"help <command>' or 'git help <concept>' to read about a specific subcommand or",
"state (see also: git help revisions) bisect Use binary search to find the",
"logs show Show various types of objects status Show the working tree status",
"subcommands and some concept guides. See 'git help <command>' or 'git help <concept>'",
"#restart of terminal os.system('cls' if os.name == 'nt' else 'clear') os.system('python refresh.py') exit()",
"together rebase Reapply commits on top of another base tip tag Create, list,",
"\"\") os.chdir(command) location = os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') elif command == 'clear':",
"and from the index examine the history and state (see also: git help",
"working area (see also: git help tutorial) clone Clone a repository into a",
"base tip tag Create, list, delete or verify a tag object signed with",
"and tweak your common history branch List, create, or delete branches checkout Switch",
"''' List of Commands wget missing URL git help -g' list available subcommands",
"file contents to the index mv Move or rename a file, a directory,",
"on the current change (see also: git help everyday) add Add file contents",
"of another base tip tag Create, list, delete or verify a tag object",
"desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') for file in glob.glob(\"*\"): print(file) elif(command[0] == 'c' and",
"f'{data}') os.chdir(location) help_git = ''' These are common Git commands used in various",
"List of Commands wget missing URL git help -g' list available subcommands cat",
"commands used in various situations: start a working area (see also: git help",
"or delete branches checkout Switch branches or restore working tree files commit Record",
"on top of another base tip tag Create, list, delete or verify a",
"command = command.replace(\"cat \", \"\") cat = open(f'{command}', 'r') content = cat.readlines() #listing",
"command.replace(\"cat \", \"\") cat = open(f'{command}', 'r') content = cat.readlines() #listing content of",
"with another repository or a local branch push Update remote refs along with",
"-a' and 'git help -g' list available subcommands and some concept guides. See",
"terminal os.system('cls' if os.name == 'nt' else 'clear') elif command == 'refresh': #restart",
"help workflows) fetch Download objects and refs from another repository pull Fetch from",
"another repository or a local branch push Update remote refs along with associated",
"= str(command).replace(\"cd\", \"\").replace(\" \",\"\") if(command.count(\"..\")): os.chdir('../') location = os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}')",
"empty Git repository or reinitialize an existing one work on the current change",
"location = os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') for file in glob.glob(\"*\"): print(file) elif(command[0]",
"files os.chdir(location) print(location) location = os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') for file in",
"Show commit logs show Show various types of objects status Show the working",
"user user_info = os.path.expanduser('~') location_default = os.path.expanduser('~\\\\Desktop') location = os.path.expanduser('~\\\\Desktop') desktop = os.path.expanduser(f'{location}').replace(f'{user_info}',",
"matching a pattern log Show commit logs show Show various types of objects",
"current change (see also: git help everyday) add Add file contents to the",
"\"\") cat = open(f'{command}', 'r') content = cat.readlines() #listing content of file print('\\n')",
"a repository into a new directory init Create an empty Git repository or",
"remote refs along with associated objects 'git help -a' and 'git help -g'",
"Clone a repository into a new directory init Create an empty Git repository",
"introduced a bug grep Print lines matching a pattern log Show commit logs",
"files from the working tree and from the index examine the history and",
"objects 'git help -a' and 'git help -g' list available subcommands and some",
"more development histories together rebase Reapply commits on top of another base tip",
"= command.replace(\"cd \", \"\") os.chdir(command) location = os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') elif",
"= os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') else: command = command.replace(\"cd \", \"\") os.chdir(command) location = os.getcwd()",
"integrate with another repository or a local branch push Update remote refs along",
"or 'git help <concept>' to read about a specific subcommand or concept. '''",
"directories ls listing files clear clean terminal ''' while True: command = input(f'{desktop}:#",
"branches checkout Switch branches or restore working tree files commit Record changes to",
"the files location = str(command).replace(\"cd\", \"\").replace(\" \",\"\") if(command.count(\"..\")): os.chdir('../') location = os.getcwd() desktop",
"a file, a directory, or a symlink reset Reset current HEAD to the",
"binary search to find the commit that introduced a bug grep Print lines",
"f'{data}') elif command == 'clear': #clean in terminal os.system('cls' if os.name == 'nt'",
"specific subcommand or concept. ''' command_list = ''' List of Commands wget missing",
"os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') os.chdir(location) help_git = ''' These are common Git commands used in",
"content in file cd browse directories ls listing files clear clean terminal '''",
"'c' and command[1] == 'd'): #browsing the files location = str(command).replace(\"cd\", \"\").replace(\" \",\"\")",
"in content: print(line) cat.close() print('\\n') elif command[0] == 'g' and command[1] == 'i'",
"in various situations: start a working area (see also: git help tutorial) clone",
"''' while True: command = input(f'{desktop}:# ') if command == 'ls': #listing files",
"files commit Record changes to the repository diff Show changes between commits, commit",
"#listing content of file print('\\n') for line in content: print(line) cat.close() print('\\n') elif",
"work on the current change (see also: git help everyday) add Add file",
"commits on top of another base tip tag Create, list, delete or verify",
"diff Show changes between commits, commit and working tree, etc merge Join two",
"= os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') elif command == 'clear': #clean in terminal",
"available subcommands cat list content in file cd browse directories ls listing files",
"os.chdir('../') location = os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') else: command = command.replace(\"cd \",",
"init Create an empty Git repository or reinitialize an existing one work on",
"input(f'{desktop}:# ') if command == 'ls': #listing files os.chdir(location) print(location) location = os.getcwd()",
"about a specific subcommand or concept. ''' command_list = ''' List of Commands",
"area (see also: git help tutorial) clone Clone a repository into a new",
"a tag object signed with GPG collaborate (see also: git help workflows) fetch",
"= os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') os.chdir(location) help_git = ''' These are common Git commands used",
"== 'help' or command == 'commands': print(command_list) elif(command.count('wget ')): print(os.getcwd()) elif(command == 'pwd'):",
"= os.path.expanduser('~') location_default = os.path.expanduser('~\\\\Desktop') location = os.path.expanduser('~\\\\Desktop') desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') os.chdir(location)",
"os.path.expanduser('~') location_default = os.path.expanduser('~\\\\Desktop') location = os.path.expanduser('~\\\\Desktop') desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') os.chdir(location) help_git",
"Create an empty Git repository or reinitialize an existing one work on the",
"== 'nt' else 'clear') os.system('python refresh.py') exit() elif(command.count('cat ')): command = command.replace(\"cat \",",
"and state (see also: git help revisions) bisect Use binary search to find",
"associated objects 'git help -a' and 'git help -g' list available subcommands and",
"== 'ls': #listing files os.chdir(location) print(location) location = os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}')",
"elif(command.count('cat ')): command = command.replace(\"cat \", \"\") cat = open(f'{command}', 'r') content =",
"subcommands cat list content in file cd browse directories ls listing files clear",
"working tree and from the index examine the history and state (see also:",
"files location = str(command).replace(\"cd\", \"\").replace(\" \",\"\") if(command.count(\"..\")): os.chdir('../') location = os.getcwd() desktop =",
"content: print(line) cat.close() print('\\n') elif command[0] == 'g' and command[1] == 'i' and",
"clear clean terminal ''' while True: command = input(f'{desktop}:# ') if command ==",
"tweak your common history branch List, create, or delete branches checkout Switch branches",
"os.system('cls' if os.name == 'nt' else 'clear') elif command == 'refresh': #restart of",
"and command[1] == 'd'): #browsing the files location = str(command).replace(\"cd\", \"\").replace(\" \",\"\") if(command.count(\"..\")):",
"\", \"\") cat = open(f'{command}', 'r') content = cat.readlines() #listing content of file",
"'help' or command == 'commands': print(command_list) elif(command.count('wget ')): print(os.getcwd()) elif(command == 'pwd'): print(location)",
"commit and working tree, etc merge Join two or more development histories together",
"content = cat.readlines() #listing content of file print('\\n') for line in content: print(line)",
"branch List, create, or delete branches checkout Switch branches or restore working tree",
"histories together rebase Reapply commits on top of another base tip tag Create,",
"location = os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') elif command == 'clear': #clean in",
"== 'c' and command[1] == 'd'): #browsing the files location = str(command).replace(\"cd\", \"\").replace(\"",
"objects and refs from another repository pull Fetch from and integrate with another",
"'refresh': #restart of terminal os.system('cls' if os.name == 'nt' else 'clear') os.system('python refresh.py')",
"open(f'{command}', 'r') content = cat.readlines() #listing content of file print('\\n') for line in",
"''' These are common Git commands used in various situations: start a working",
"repository into a new directory init Create an empty Git repository or reinitialize",
"or a symlink reset Reset current HEAD to the specified state rm Remove",
"object signed with GPG collaborate (see also: git help workflows) fetch Download objects",
"status Show the working tree status grow, mark and tweak your common history",
"or a local branch push Update remote refs along with associated objects 'git",
"new directory init Create an empty Git repository or reinitialize an existing one",
"a new directory init Create an empty Git repository or reinitialize an existing",
"Reset current HEAD to the specified state rm Remove files from the working",
"grow, mark and tweak your common history branch List, create, or delete branches",
"directory init Create an empty Git repository or reinitialize an existing one work",
"Show the working tree status grow, mark and tweak your common history branch",
"'nt' else 'clear') os.system('python refresh.py') exit() elif(command.count('cat ')): command = command.replace(\"cat \", \"\")",
"start a working area (see also: git help tutorial) clone Clone a repository",
"help -g' list available subcommands and some concept guides. See 'git help <command>'",
"the specified state rm Remove files from the working tree and from the",
"Show changes between commits, commit and working tree, etc merge Join two or",
"elif command[0] == 'g' and command[1] == 'i' and command[2] == 't': os.system(command)",
"reinitialize an existing one work on the current change (see also: git help",
"os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') elif command == 'clear': #clean in terminal os.system('cls' if os.name ==",
"some concept guides. See 'git help <command>' or 'git help <concept>' to read",
"file in glob.glob(\"*\"): print(file) elif(command[0] == 'c' and command[1] == 'd'): #browsing the",
"'git help <command>' or 'git help <concept>' to read about a specific subcommand",
"read about a specific subcommand or concept. ''' command_list = ''' List of",
"that introduced a bug grep Print lines matching a pattern log Show commit",
"== 'i' and command[2] == 't': os.system(command) elif command == '': pass elif",
"line in content: print(line) cat.close() print('\\n') elif command[0] == 'g' and command[1] ==",
"#desktop of user user_info = os.path.expanduser('~') location_default = os.path.expanduser('~\\\\Desktop') location = os.path.expanduser('~\\\\Desktop') desktop",
"and integrate with another repository or a local branch push Update remote refs",
"repository or reinitialize an existing one work on the current change (see also:",
"commit Record changes to the repository diff Show changes between commits, commit and",
"or more development histories together rebase Reapply commits on top of another base",
"workflows) fetch Download objects and refs from another repository pull Fetch from and",
"refs along with associated objects 'git help -a' and 'git help -g' list",
"os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') else: command = command.replace(\"cd \", \"\") os.chdir(command) location = os.getcwd() desktop",
"content of file print('\\n') for line in content: print(line) cat.close() print('\\n') elif command[0]",
"print(location) location = os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') for file in glob.glob(\"*\"): print(file)",
"directory, or a symlink reset Reset current HEAD to the specified state rm",
"restore working tree files commit Record changes to the repository diff Show changes",
"print('\\n') for line in content: print(line) cat.close() print('\\n') elif command[0] == 'g' and",
"search to find the commit that introduced a bug grep Print lines matching",
"also: git help tutorial) clone Clone a repository into a new directory init",
"a pattern log Show commit logs show Show various types of objects status",
"= os.path.expanduser('~\\\\Desktop') location = os.path.expanduser('~\\\\Desktop') desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') os.chdir(location) help_git = '''",
"== 'refresh': #restart of terminal os.system('cls' if os.name == 'nt' else 'clear') os.system('python",
"files clear clean terminal ''' while True: command = input(f'{desktop}:# ') if command",
"These are common Git commands used in various situations: start a working area",
"os.chdir(location) help_git = ''' These are common Git commands used in various situations:",
"command == 'clear': #clean in terminal os.system('cls' if os.name == 'nt' else 'clear')",
"f'{data}') for file in glob.glob(\"*\"): print(file) elif(command[0] == 'c' and command[1] == 'd'):",
"os.path.expanduser('~\\\\Desktop') location = os.path.expanduser('~\\\\Desktop') desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') os.chdir(location) help_git = ''' These",
"exit() elif(command.count('cat ')): command = command.replace(\"cat \", \"\") cat = open(f'{command}', 'r') content",
"the index mv Move or rename a file, a directory, or a symlink",
"a working area (see also: git help tutorial) clone Clone a repository into",
"\", \"\") os.chdir(command) location = os.getcwd() desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') elif command ==",
"for line in content: print(line) cat.close() print('\\n') elif command[0] == 'g' and command[1]",
"location_default = os.path.expanduser('~\\\\Desktop') location = os.path.expanduser('~\\\\Desktop') desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') os.chdir(location) help_git =",
"from the index examine the history and state (see also: git help revisions)",
"list, delete or verify a tag object signed with GPG collaborate (see also:",
"Create, list, delete or verify a tag object signed with GPG collaborate (see",
"used in various situations: start a working area (see also: git help tutorial)",
"an empty Git repository or reinitialize an existing one work on the current",
"changes between commits, commit and working tree, etc merge Join two or more",
"the repository diff Show changes between commits, commit and working tree, etc merge",
"status grow, mark and tweak your common history branch List, create, or delete",
"-g' list available subcommands and some concept guides. See 'git help <command>' or",
"for file in glob.glob(\"*\"): print(file) elif(command[0] == 'c' and command[1] == 'd'): #browsing",
"show Show various types of objects status Show the working tree status grow,",
"See 'git help <command>' or 'git help <concept>' to read about a specific",
"of terminal os.system('cls' if os.name == 'nt' else 'clear') os.system('python refresh.py') exit() elif(command.count('cat",
"types of objects status Show the working tree status grow, mark and tweak",
"a directory, or a symlink reset Reset current HEAD to the specified state",
"another repository pull Fetch from and integrate with another repository or a local",
"with GPG collaborate (see also: git help workflows) fetch Download objects and refs",
"'git help -a' and 'git help -g' list available subcommands and some concept",
"command == 'refresh': #restart of terminal os.system('cls' if os.name == 'nt' else 'clear')",
"from the working tree and from the index examine the history and state",
"state rm Remove files from the working tree and from the index examine",
"and refs from another repository pull Fetch from and integrate with another repository",
"rebase Reapply commits on top of another base tip tag Create, list, delete",
"common history branch List, create, or delete branches checkout Switch branches or restore",
"available subcommands and some concept guides. See 'git help <command>' or 'git help",
"print('\\n') elif command[0] == 'g' and command[1] == 'i' and command[2] == 't':",
"'git help <concept>' to read about a specific subcommand or concept. ''' command_list",
"situations: start a working area (see also: git help tutorial) clone Clone a",
"also: git help revisions) bisect Use binary search to find the commit that",
"List, create, or delete branches checkout Switch branches or restore working tree files",
"'nt' else 'clear') elif command == 'refresh': #restart of terminal os.system('cls' if os.name",
"add Add file contents to the index mv Move or rename a file,",
"desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') os.chdir(location) help_git = ''' These are common Git commands",
"two or more development histories together rebase Reapply commits on top of another",
"'r') content = cat.readlines() #listing content of file print('\\n') for line in content:",
"between commits, commit and working tree, etc merge Join two or more development",
"merge Join two or more development histories together rebase Reapply commits on top",
"= command.replace(\"cat \", \"\") cat = open(f'{command}', 'r') content = cat.readlines() #listing content",
"and command[1] == 'i' and command[2] == 't': os.system(command) elif command == '':",
"if os.name == 'nt' else 'clear') os.system('python refresh.py') exit() elif(command.count('cat ')): command =",
"(see also: git help everyday) add Add file contents to the index mv",
"delete branches checkout Switch branches or restore working tree files commit Record changes",
"import glob files = open('dados.dll') data = files.read() files.close #desktop of user user_info",
"user_info = os.path.expanduser('~') location_default = os.path.expanduser('~\\\\Desktop') location = os.path.expanduser('~\\\\Desktop') desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}')",
"also: git help workflows) fetch Download objects and refs from another repository pull",
"elif(command[0] == 'c' and command[1] == 'd'): #browsing the files location = str(command).replace(\"cd\",",
"the commit that introduced a bug grep Print lines matching a pattern log",
"'d'): #browsing the files location = str(command).replace(\"cd\", \"\").replace(\" \",\"\") if(command.count(\"..\")): os.chdir('../') location =",
"location = os.path.expanduser('~\\\\Desktop') desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') os.chdir(location) help_git = ''' These are",
"= os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') elif command == 'clear': #clean in terminal os.system('cls' if os.name",
"elif command == '': pass elif command == 'help' or command == 'commands':",
"the working tree status grow, mark and tweak your common history branch List,",
"Update remote refs along with associated objects 'git help -a' and 'git help",
"top of another base tip tag Create, list, delete or verify a tag",
"help <concept>' to read about a specific subcommand or concept. ''' command_list =",
"terminal ''' while True: command = input(f'{desktop}:# ') if command == 'ls': #listing",
"contents to the index mv Move or rename a file, a directory, or",
"elif command == 'clear': #clean in terminal os.system('cls' if os.name == 'nt' else",
"from and integrate with another repository or a local branch push Update remote",
"== 'g' and command[1] == 'i' and command[2] == 't': os.system(command) elif command",
"help -a' and 'git help -g' list available subcommands and some concept guides.",
"find the commit that introduced a bug grep Print lines matching a pattern",
"print(line) cat.close() print('\\n') elif command[0] == 'g' and command[1] == 'i' and command[2]",
"desktop = os.path.expanduser(f'{location}').replace(f'{user_info}', f'{data}') elif command == 'clear': #clean in terminal os.system('cls' if",
"glob files = open('dados.dll') data = files.read() files.close #desktop of user user_info =",
"while True: command = input(f'{desktop}:# ') if command == 'ls': #listing files os.chdir(location)"
] |
[
"from pactor.node_parent import AstNode from pactor.node_stack_helper import pop_value, pop class WhenNode(AstNode): def run(self,",
"pactor.node_stack_helper import pop_value, pop class WhenNode(AstNode): def run(self, vm: VM): quote = pop(vm)",
"pop class WhenNode(AstNode): def run(self, vm: VM): quote = pop(vm) is_true = pop_value(vm)",
"AstNode from pactor.node_stack_helper import pop_value, pop class WhenNode(AstNode): def run(self, vm: VM): quote",
"VM): quote_false = pop(vm) quote_true = pop(vm) is_true = pop_value(vm) if is_true: vm.run_ast(quote_true.ast)",
"class WhenNode(AstNode): def run(self, vm: VM): quote = pop(vm) is_true = pop_value(vm) if",
"def __repr__(self): return 'if' class TimesNode(AstNode): def run(self, vm: VM): quote = pop(vm)",
"= pop(vm) count = pop_value(vm) for _ in range(0, count): vm.run_ast(quote.ast) def __repr__(self):",
"vm: VM): quote = pop(vm) count = pop_value(vm) for _ in range(0, count):",
"vm: VM): quote = pop(vm) is_true = pop_value(vm) if is_true: vm.run_ast(quote.ast) def __repr__(self):",
"pop(vm) quote_true = pop(vm) is_true = pop_value(vm) if is_true: vm.run_ast(quote_true.ast) else: vm.run_ast(quote_false.ast) def",
"pop_value, pop class WhenNode(AstNode): def run(self, vm: VM): quote = pop(vm) is_true =",
"class TimesNode(AstNode): def run(self, vm: VM): quote = pop(vm) count = pop_value(vm) for",
"quote = pop(vm) is_true = pop_value(vm) if is_true: vm.run_ast(quote.ast) def __repr__(self): return 'when'",
"pactor.vm import VM from pactor.node_parent import AstNode from pactor.node_stack_helper import pop_value, pop class",
"__repr__(self): return 'if' class TimesNode(AstNode): def run(self, vm: VM): quote = pop(vm) count",
"__repr__(self): return 'when' class IfNode(AstNode): def run(self, vm: VM): quote_false = pop(vm) quote_true",
"if is_true: vm.run_ast(quote_true.ast) else: vm.run_ast(quote_false.ast) def __repr__(self): return 'if' class TimesNode(AstNode): def run(self,",
"class IfNode(AstNode): def run(self, vm: VM): quote_false = pop(vm) quote_true = pop(vm) is_true",
"pop(vm) is_true = pop_value(vm) if is_true: vm.run_ast(quote.ast) def __repr__(self): return 'when' class IfNode(AstNode):",
"def run(self, vm: VM): quote = pop(vm) is_true = pop_value(vm) if is_true: vm.run_ast(quote.ast)",
"= pop_value(vm) if is_true: vm.run_ast(quote.ast) def __repr__(self): return 'when' class IfNode(AstNode): def run(self,",
"count = pop_value(vm) for _ in range(0, count): vm.run_ast(quote.ast) def __repr__(self): return 'times'",
"TimesNode(AstNode): def run(self, vm: VM): quote = pop(vm) count = pop_value(vm) for _",
"is_true: vm.run_ast(quote.ast) def __repr__(self): return 'when' class IfNode(AstNode): def run(self, vm: VM): quote_false",
"quote_false = pop(vm) quote_true = pop(vm) is_true = pop_value(vm) if is_true: vm.run_ast(quote_true.ast) else:",
"def __repr__(self): return 'when' class IfNode(AstNode): def run(self, vm: VM): quote_false = pop(vm)",
"is_true: vm.run_ast(quote_true.ast) else: vm.run_ast(quote_false.ast) def __repr__(self): return 'if' class TimesNode(AstNode): def run(self, vm:",
"pop_value(vm) if is_true: vm.run_ast(quote.ast) def __repr__(self): return 'when' class IfNode(AstNode): def run(self, vm:",
"import pop_value, pop class WhenNode(AstNode): def run(self, vm: VM): quote = pop(vm) is_true",
"import VM from pactor.node_parent import AstNode from pactor.node_stack_helper import pop_value, pop class WhenNode(AstNode):",
"if is_true: vm.run_ast(quote.ast) def __repr__(self): return 'when' class IfNode(AstNode): def run(self, vm: VM):",
"is_true = pop_value(vm) if is_true: vm.run_ast(quote_true.ast) else: vm.run_ast(quote_false.ast) def __repr__(self): return 'if' class",
"def run(self, vm: VM): quote = pop(vm) count = pop_value(vm) for _ in",
"= pop(vm) quote_true = pop(vm) is_true = pop_value(vm) if is_true: vm.run_ast(quote_true.ast) else: vm.run_ast(quote_false.ast)",
"'when' class IfNode(AstNode): def run(self, vm: VM): quote_false = pop(vm) quote_true = pop(vm)",
"return 'when' class IfNode(AstNode): def run(self, vm: VM): quote_false = pop(vm) quote_true =",
"= pop(vm) is_true = pop_value(vm) if is_true: vm.run_ast(quote.ast) def __repr__(self): return 'when' class",
"quote_true = pop(vm) is_true = pop_value(vm) if is_true: vm.run_ast(quote_true.ast) else: vm.run_ast(quote_false.ast) def __repr__(self):",
"pop_value(vm) if is_true: vm.run_ast(quote_true.ast) else: vm.run_ast(quote_false.ast) def __repr__(self): return 'if' class TimesNode(AstNode): def",
"VM): quote = pop(vm) is_true = pop_value(vm) if is_true: vm.run_ast(quote.ast) def __repr__(self): return",
"run(self, vm: VM): quote = pop(vm) count = pop_value(vm) for _ in range(0,",
"= pop_value(vm) if is_true: vm.run_ast(quote_true.ast) else: vm.run_ast(quote_false.ast) def __repr__(self): return 'if' class TimesNode(AstNode):",
"def run(self, vm: VM): quote_false = pop(vm) quote_true = pop(vm) is_true = pop_value(vm)",
"WhenNode(AstNode): def run(self, vm: VM): quote = pop(vm) is_true = pop_value(vm) if is_true:",
"IfNode(AstNode): def run(self, vm: VM): quote_false = pop(vm) quote_true = pop(vm) is_true =",
"return 'if' class TimesNode(AstNode): def run(self, vm: VM): quote = pop(vm) count =",
"import AstNode from pactor.node_stack_helper import pop_value, pop class WhenNode(AstNode): def run(self, vm: VM):",
"= pop(vm) is_true = pop_value(vm) if is_true: vm.run_ast(quote_true.ast) else: vm.run_ast(quote_false.ast) def __repr__(self): return",
"run(self, vm: VM): quote_false = pop(vm) quote_true = pop(vm) is_true = pop_value(vm) if",
"vm.run_ast(quote_true.ast) else: vm.run_ast(quote_false.ast) def __repr__(self): return 'if' class TimesNode(AstNode): def run(self, vm: VM):",
"run(self, vm: VM): quote = pop(vm) is_true = pop_value(vm) if is_true: vm.run_ast(quote.ast) def",
"vm.run_ast(quote_false.ast) def __repr__(self): return 'if' class TimesNode(AstNode): def run(self, vm: VM): quote =",
"VM): quote = pop(vm) count = pop_value(vm) for _ in range(0, count): vm.run_ast(quote.ast)",
"pop(vm) count = pop_value(vm) for _ in range(0, count): vm.run_ast(quote.ast) def __repr__(self): return",
"from pactor.node_stack_helper import pop_value, pop class WhenNode(AstNode): def run(self, vm: VM): quote =",
"'if' class TimesNode(AstNode): def run(self, vm: VM): quote = pop(vm) count = pop_value(vm)",
"pop(vm) is_true = pop_value(vm) if is_true: vm.run_ast(quote_true.ast) else: vm.run_ast(quote_false.ast) def __repr__(self): return 'if'",
"else: vm.run_ast(quote_false.ast) def __repr__(self): return 'if' class TimesNode(AstNode): def run(self, vm: VM): quote",
"vm.run_ast(quote.ast) def __repr__(self): return 'when' class IfNode(AstNode): def run(self, vm: VM): quote_false =",
"is_true = pop_value(vm) if is_true: vm.run_ast(quote.ast) def __repr__(self): return 'when' class IfNode(AstNode): def",
"from pactor.vm import VM from pactor.node_parent import AstNode from pactor.node_stack_helper import pop_value, pop",
"pactor.node_parent import AstNode from pactor.node_stack_helper import pop_value, pop class WhenNode(AstNode): def run(self, vm:",
"vm: VM): quote_false = pop(vm) quote_true = pop(vm) is_true = pop_value(vm) if is_true:",
"<reponame>kstrempel/pactor from pactor.vm import VM from pactor.node_parent import AstNode from pactor.node_stack_helper import pop_value,",
"quote = pop(vm) count = pop_value(vm) for _ in range(0, count): vm.run_ast(quote.ast) def",
"VM from pactor.node_parent import AstNode from pactor.node_stack_helper import pop_value, pop class WhenNode(AstNode): def"
] |
[
"in self.weaponSets: for weapon in weaponSet: weapon.cleanup() self.weaponSets = [] self.weaponNPs = {}",
"in self.weaponSets[weaponSet]: if not weapon.active: weapon.triggerPressed(self) def ceaseFiringSet(self, weaponSet): if weaponSet < len(self.weaponSets):",
"self.walking = False self.size = size if colliderName is not None: colliderNode =",
"knockback, flinchValue, overcharge = False): previousHealth = self.health self.health += dHealth if incomingImpulse",
"from panda3d.core import NodePath, PandaNode from panda3d.core import Quat from Section2SpaceflightDocking.CommonValues import *",
"self.maxSize = maxSize self.sizeRange = self.maxSize - self.minSize self.duration = duration self.timer =",
"if weaponSet < len(self.weaponSets): for weapon in self.weaponSets[weaponSet]: if weapon.active: weapon.triggerReleased(self) def update(self,",
"if speed > self.terminalVelocity: self.velocity.normalize() self.velocity *= self.terminalVelocity speed = self.terminalVelocity if Common.useFriction:",
"self.health self.health += dHealth if incomingImpulse is not None and knockback > 0.1:",
"modelName, modelAnims, maxHealth, maxSpeed, colliderName, weaponIntoMask, size): self.root = Common.framework.showBase.render.attachNewNode(PandaNode(\"obj\")) self.colliderName = colliderName",
"frictionVal *= 0.8 if frictionVal > speed: self.velocity.set(0, 0, 0) else: frictionVec =",
"overcharge = False): previousHealth = self.health self.health += dHealth if incomingImpulse is not",
"= minSize self.maxSize = maxSize self.sizeRange = self.maxSize - self.minSize self.duration = duration",
"panda3d.core import PointLight from panda3d.core import NodePath, PandaNode from panda3d.core import Quat from",
"self.terminalVelocity = 50 self.flinchCounter = 0 self.velocity = Vec3(0, 0, 0) self.acceleration =",
"speed > self.terminalVelocity: self.velocity.normalize() self.velocity *= self.terminalVelocity speed = self.terminalVelocity if Common.useFriction: if",
"pass def addWeapon(self, weapon, setIndex, sourceNP): while len(self.weaponSets) <= setIndex: self.weaponSets.append([]) self.weaponSets[setIndex].append(weapon) self.weaponNPs[weapon]",
"self.model = model self.model.setTwoSided(True) self.model.setTransparency(True) self.model.setBillboardPointEye() self.minSize = minSize self.maxSize = maxSize self.sizeRange",
"self.weaponNPs = {} class Blast(): def __init__(self, model, minSize, maxSize, duration): self.model =",
"is not None: colliderNode = CollisionNode(colliderName) colliderNode.addSolid(CollisionSphere(0, 0, 0, size)) self.colliderNP = self.root.attachNewNode(colliderNode)",
"if not self.inControl: frictionVal *= 0.8 if frictionVal > speed: self.velocity.set(0, 0, 0)",
"self.actor = None if self.root is not None: self.root.removeNode() self.root = None class",
"if colliderName is not None: colliderNode = CollisionNode(colliderName) colliderNode.addSolid(CollisionSphere(0, 0, 0, size)) self.colliderNP",
"self.acceleration = 300.0 self.inControl = True self.outOfControlTimer = 0 self.walking = False self.size",
"ArmedObject(): def __init__(self): self.weaponSets = [] self.weaponNPs = {} self.lockedTarget = None def",
"is not None: self.root.setPos(pos) self.maxHealth = maxHealth self.health = maxHealth self.healthRechargeRate = 2.0",
"self.root.attachNewNode(PandaNode(\"stand-in\")) self.deathSound = None def physicalImpact(self, surfaceNormal): proj = self.velocity.project(surfaceNormal) self.velocity -= proj*2",
"angle = math.copysign(min(abs(angle), turnRate*dt), angle) quat.setFromAxisAngle(angle, axis) newQuat = selfQuat*quat self.root.setQuat(Common.framework.showBase.render, newQuat) def",
"0) else: frictionVec = -self.velocity frictionVec.normalize() frictionVec *= frictionVal self.velocity += frictionVec if",
"weapon.active: weapon.triggerPressed(self) def ceaseFiringSet(self, weaponSet): if weaponSet < len(self.weaponSets): for weapon in self.weaponSets[weaponSet]:",
"= False if dHealth < 0: self.healthRechargeSuppressionTimer = self.healthRechargeSuppressionDuration if self.health < 0:",
"*= self.maxSpeed speed = self.maxSpeed else: if speed > self.terminalVelocity: self.velocity.normalize() self.velocity *=",
"CollisionSphere, CollisionCapsule, CollisionNode, CollisionRay, CollisionSegment, CollisionHandlerQueue from direct.gui.OnscreenText import OnscreenText from direct.gui.OnscreenImage import",
"import PointLight from panda3d.core import NodePath, PandaNode from panda3d.core import Quat from Section2SpaceflightDocking.CommonValues",
"self.health = 0 if flinchValue > 0: self.flinchCounter -= flinchValue if dHealth >",
"{} self.lockedTarget = None def weaponFired(self, weapon): pass def weaponReset(self, weapon): pass def",
"0 if flinchValue > 0: self.flinchCounter -= flinchValue if dHealth > 0 and",
"self.inControl = True self.outOfControlTimer = 0 self.walking = False self.size = size if",
"return angle def cleanup(self): if self.colliderNP is not None and not self.colliderNP.isEmpty(): self.colliderNP.clearPythonTag(TAG_OWNER)",
"import TextNode from panda3d.core import AudioSound from panda3d.core import PointLight from panda3d.core import",
"if not weapon.active: weapon.triggerPressed(self) def ceaseFiringSet(self, weaponSet): if weaponSet < len(self.weaponSets): for weapon",
"target = target.root.getPos(Common.framework.showBase.render) diff = target - self.root.getPos(Common.framework.showBase.render) selfQuat = self.root.getQuat(Common.framework.showBase.render) selfForward =",
"self.weaponSets.append([]) self.weaponSets[setIndex].append(weapon) self.weaponNPs[weapon] = sourceNP def startFiringSet(self, weaponSet): if weaponSet < len(self.weaponSets): for",
"else: self.alterHealth(self.healthRechargeRate*dt, None, 0, 0) def alterHealth(self, dHealth, incomingImpulse, knockback, flinchValue, overcharge =",
"GameObject(): def __init__(self, pos, modelName, modelAnims, maxHealth, maxSpeed, colliderName, weaponIntoMask, size): self.root =",
"maxHealth self.health = maxHealth self.healthRechargeRate = 2.0 self.healthRechargeSuppressionTimer = 0 self.healthRechargeSuppressionDuration = 0.5",
"= 10.0 class GameObject(): def __init__(self, pos, modelName, modelAnims, maxHealth, maxSpeed, colliderName, weaponIntoMask,",
"= maxHealth self.healthRechargeRate = 2.0 self.healthRechargeSuppressionTimer = 0 self.healthRechargeSuppressionDuration = 0.5 self.maxSpeed =",
"vec.y) vec.normalize() angle = forward2D.signedAngleDeg(vec) return angle def cleanup(self): if self.colliderNP is not",
"= NodePath(PandaNode(\"actor\")) elif modelAnims is None: self.actor = Common.framework.showBase.loader.loadModel(modelName) else: self.actor = Actor(modelName,",
"is not None and not self.colliderNP.isEmpty(): self.colliderNP.clearPythonTag(TAG_OWNER) self.colliderNP.removeNode() self.colliderNP = None if self.actor",
"self.weaponSets[weaponSet]: if weapon.active: weapon.triggerReleased(self) def update(self, dt): for weaponSet in self.weaponSets: for weapon",
"= self.health self.health += dHealth if incomingImpulse is not None and knockback >",
"= model self.model.setTwoSided(True) self.model.setTransparency(True) self.model.setBillboardPointEye() self.minSize = minSize self.maxSize = maxSize self.sizeRange =",
"= 2.0 self.healthRechargeSuppressionTimer = 0 self.healthRechargeSuppressionDuration = 0.5 self.maxSpeed = maxSpeed self.terminalVelocity =",
"if self.walking and speed > self.maxSpeed: self.velocity.normalize() self.velocity *= self.maxSpeed speed = self.maxSpeed",
"previousHealth = self.health self.health += dHealth if incomingImpulse is not None and knockback",
"None: colliderNode = CollisionNode(colliderName) colliderNode.addSolid(CollisionSphere(0, 0, 0, size)) self.colliderNP = self.root.attachNewNode(colliderNode) self.colliderNP.setPythonTag(TAG_OWNER, self)",
"0 perc = 1.0 - (self.timer / self.duration) self.model.setScale(self.minSize + self.sizeRange*perc) self.model.setAlphaScale(math.sin(perc*3.142)) def",
"if modelName is None: self.actor = NodePath(PandaNode(\"actor\")) elif modelAnims is None: self.actor =",
"def update(self, dt, fluid = False): speed = self.velocity.length() if self.inControl: if self.walking",
"math.copysign(min(abs(angle), turnRate*dt), angle) quat.setFromAxisAngle(angle, axis) newQuat = selfQuat*quat self.root.setQuat(Common.framework.showBase.render, newQuat) def getAngleWithVec(self, vec):",
"self.weaponSets[weaponSet]: if not weapon.active: weapon.triggerPressed(self) def ceaseFiringSet(self, weaponSet): if weaponSet < len(self.weaponSets): for",
"ceaseFiringSet(self, weaponSet): if weaponSet < len(self.weaponSets): for weapon in self.weaponSets[weaponSet]: if weapon.active: weapon.triggerReleased(self)",
"= Common.framework.showBase.loader.loadModel(modelName) else: self.actor = Actor(modelName, modelAnims) self.actor.reparentTo(self.root) if pos is not None:",
"self.actor is not None: if isinstance(self.actor, Actor): self.actor.cleanup() self.actor.removeNode() self.actor = None if",
"self.deathSound = None def physicalImpact(self, surfaceNormal): proj = self.velocity.project(surfaceNormal) self.velocity -= proj*2 def",
"Section2SpaceflightDocking.CommonValues import * from Section2SpaceflightDocking.Common import Common import math, random FRICTION = 10.0",
"True else: self.outOfControlTimer -= dt if self.outOfControlTimer <= 0: self.inControl = True if",
"-= dt if self.outOfControlTimer <= 0: self.inControl = True if fluid: self.root.setFluidPos(self.root.getPos() +",
"self.maxHealth if previousHealth > 0 and self.health <= 0 and self.deathSound is not",
"maxSize self.sizeRange = self.maxSize - self.minSize self.duration = duration self.timer = duration def",
"+ self.sizeRange*perc) self.model.setAlphaScale(math.sin(perc*3.142)) def cleanup(self): if self.model is not None: self.model.removeNode() self.model =",
"CollisionNode, CollisionRay, CollisionSegment, CollisionHandlerQueue from direct.gui.OnscreenText import OnscreenText from direct.gui.OnscreenImage import OnscreenImage from",
"Actor): self.actor.cleanup() self.actor.removeNode() self.actor = None if self.root is not None: self.root.removeNode() self.root",
"False): speed = self.velocity.length() if self.inControl: if self.walking and speed > self.maxSpeed: self.velocity.normalize()",
"= False self.size = size if colliderName is not None: colliderNode = CollisionNode(colliderName)",
"self.terminalVelocity: self.velocity.normalize() self.velocity *= self.terminalVelocity speed = self.terminalVelocity if Common.useFriction: if not self.walking:",
"and self.health > self.maxHealth and not overcharge: self.health = self.maxHealth if previousHealth >",
"colliderName self.modelName = modelName if modelName is None: self.actor = NodePath(PandaNode(\"actor\")) elif modelAnims",
"not weapon.active: weapon.triggerPressed(self) def ceaseFiringSet(self, weaponSet): if weaponSet < len(self.weaponSets): for weapon in",
"> self.maxHealth and not overcharge: self.health = self.maxHealth if previousHealth > 0 and",
"size if colliderName is not None: colliderNode = CollisionNode(colliderName) colliderNode.addSolid(CollisionSphere(0, 0, 0, size))",
"sourceNP def startFiringSet(self, weaponSet): if weaponSet < len(self.weaponSets): for weapon in self.weaponSets[weaponSet]: if",
"NodePath): target = target.getPos(Common.framework.showBase.render) elif isinstance(target, GameObject): target = target.root.getPos(Common.framework.showBase.render) diff = target",
"__init__(self, pos, modelName, modelAnims, maxHealth, maxSpeed, colliderName, weaponIntoMask, size): self.root = Common.framework.showBase.render.attachNewNode(PandaNode(\"obj\")) self.colliderName",
"< 0.1: return angle = selfForward.signedAngleDeg(diff.normalized(), axis) quat = Quat() angle = math.copysign(min(abs(angle),",
"dHealth < 0: self.healthRechargeSuppressionTimer = self.healthRechargeSuppressionDuration if self.health < 0: self.health = 0",
"CollisionNode(colliderName) colliderNode.addSolid(CollisionSphere(0, 0, 0, size)) self.colliderNP = self.root.attachNewNode(colliderNode) self.colliderNP.setPythonTag(TAG_OWNER, self) colliderNode.setFromCollideMask(0) colliderNode.setIntoCollideMask(weaponIntoMask) #self.colliderNP.show()",
"= None def weaponFired(self, weapon): pass def weaponReset(self, weapon): pass def addWeapon(self, weapon,",
"from Section2SpaceflightDocking.CommonValues import * from Section2SpaceflightDocking.Common import Common import math, random FRICTION =",
"not self.inControl: frictionVal *= 0.8 if frictionVal > speed: self.velocity.set(0, 0, 0) else:",
"= True self.outOfControlTimer = 0 self.walking = False self.size = size if colliderName",
"weaponSet in self.weaponSets: for weapon in weaponSet: weapon.cleanup() self.weaponSets = [] self.weaponNPs =",
"not None: self.root.removeNode() self.root = None class ArmedObject(): def __init__(self): self.weaponSets = []",
"0 and self.health <= 0 and self.deathSound is not None: self.deathSound.play() def turnTowards(self,",
"startFiringSet(self, weaponSet): if weaponSet < len(self.weaponSets): for weapon in self.weaponSets[weaponSet]: if not weapon.active:",
"not None and not self.colliderNP.isEmpty(): self.colliderNP.clearPythonTag(TAG_OWNER) self.colliderNP.removeNode() self.colliderNP = None if self.actor is",
"panda3d.core import AudioSound from panda3d.core import PointLight from panda3d.core import NodePath, PandaNode from",
"self.root = Common.framework.showBase.render.attachNewNode(PandaNode(\"obj\")) self.colliderName = colliderName self.modelName = modelName if modelName is None:",
"None if self.actor is not None: if isinstance(self.actor, Actor): self.actor.cleanup() self.actor.removeNode() self.actor =",
"0.1: self.velocity += incomingImpulse*knockback self.inControl = False self.outOfControlTimer = knockback*0.1 self.walking = False",
"not None and knockback > 0.1: self.velocity += incomingImpulse*knockback self.inControl = False self.outOfControlTimer",
"dHealth, incomingImpulse, knockback, flinchValue, overcharge = False): previousHealth = self.health self.health += dHealth",
"self.timer < 0: self.timer = 0 perc = 1.0 - (self.timer / self.duration)",
"0 self.walking = False self.size = size if colliderName is not None: colliderNode",
"self.alterHealth(self.healthRechargeRate*dt, None, 0, 0) def alterHealth(self, dHealth, incomingImpulse, knockback, flinchValue, overcharge = False):",
"update(self, dt): for weaponSet in self.weaponSets: for weapon in weaponSet: weapon.update(dt, self) def",
"import math, random FRICTION = 10.0 class GameObject(): def __init__(self, pos, modelName, modelAnims,",
"from direct.actor.Actor import Actor from panda3d.core import CollisionSphere, CollisionCapsule, CollisionNode, CollisionRay, CollisionSegment, CollisionHandlerQueue",
"< len(self.weaponSets): for weapon in self.weaponSets[weaponSet]: if not weapon.active: weapon.triggerPressed(self) def ceaseFiringSet(self, weaponSet):",
"import NodePath, PandaNode from panda3d.core import Quat from Section2SpaceflightDocking.CommonValues import * from Section2SpaceflightDocking.Common",
"maxSpeed, colliderName, weaponIntoMask, size): self.root = Common.framework.showBase.render.attachNewNode(PandaNode(\"obj\")) self.colliderName = colliderName self.modelName = modelName",
"= sourceNP def startFiringSet(self, weaponSet): if weaponSet < len(self.weaponSets): for weapon in self.weaponSets[weaponSet]:",
"if self.actor is not None: if isinstance(self.actor, Actor): self.actor.cleanup() self.actor.removeNode() self.actor = None",
"> 0.1: self.velocity += incomingImpulse*knockback self.inControl = False self.outOfControlTimer = knockback*0.1 self.walking =",
"axis) quat = Quat() angle = math.copysign(min(abs(angle), turnRate*dt), angle) quat.setFromAxisAngle(angle, axis) newQuat =",
"< 0.1: self.inControl = True else: self.outOfControlTimer -= dt if self.outOfControlTimer <= 0:",
"self.velocity*dt) else: self.root.setPos(self.root.getPos() + self.velocity*dt) if self.healthRechargeSuppressionTimer > 0: self.healthRechargeSuppressionTimer -= dt else:",
"None if self.root is not None: self.root.removeNode() self.root = None class ArmedObject(): def",
"frictionVal > speed: self.velocity.set(0, 0, 0) else: frictionVec = -self.velocity frictionVec.normalize() frictionVec *=",
"self.health <= 0 and self.deathSound is not None: self.deathSound.play() def turnTowards(self, target, turnRate,",
"cleanup(self): for weaponSet in self.weaponSets: for weapon in weaponSet: weapon.cleanup() self.weaponSets = []",
"self.weaponSets = [] self.weaponNPs = {} self.lockedTarget = None def weaponFired(self, weapon): pass",
"FRICTION = 10.0 class GameObject(): def __init__(self, pos, modelName, modelAnims, maxHealth, maxSpeed, colliderName,",
"vec.normalize() angle = forward2D.signedAngleDeg(vec) return angle def cleanup(self): if self.colliderNP is not None",
"+= dHealth if incomingImpulse is not None and knockback > 0.1: self.velocity +=",
"> 0: self.flinchCounter -= flinchValue if dHealth > 0 and self.health > self.maxHealth",
"{} class Blast(): def __init__(self, model, minSize, maxSize, duration): self.model = model self.model.setTwoSided(True)",
"self.inControl = True if fluid: self.root.setFluidPos(self.root.getPos() + self.velocity*dt) else: self.root.setPos(self.root.getPos() + self.velocity*dt) if",
"self.healthRechargeSuppressionDuration = 0.5 self.maxSpeed = maxSpeed self.terminalVelocity = 50 self.flinchCounter = 0 self.velocity",
"quat = Quat() angle = math.copysign(min(abs(angle), turnRate*dt), angle) quat.setFromAxisAngle(angle, axis) newQuat = selfQuat*quat",
"= math.copysign(min(abs(angle), turnRate*dt), angle) quat.setFromAxisAngle(angle, axis) newQuat = selfQuat*quat self.root.setQuat(Common.framework.showBase.render, newQuat) def getAngleWithVec(self,",
"self.minSize = minSize self.maxSize = maxSize self.sizeRange = self.maxSize - self.minSize self.duration =",
"= -self.velocity frictionVec.normalize() frictionVec *= frictionVal self.velocity += frictionVec if not self.inControl: if",
"= maxSize self.sizeRange = self.maxSize - self.minSize self.duration = duration self.timer = duration",
"self.timer = 0 perc = 1.0 - (self.timer / self.duration) self.model.setScale(self.minSize + self.sizeRange*perc)",
"/ self.duration) self.model.setScale(self.minSize + self.sizeRange*perc) self.model.setAlphaScale(math.sin(perc*3.142)) def cleanup(self): if self.model is not None:",
"= self.root.attachNewNode(colliderNode) self.colliderNP.setPythonTag(TAG_OWNER, self) colliderNode.setFromCollideMask(0) colliderNode.setIntoCollideMask(weaponIntoMask) #self.colliderNP.show() else: self.colliderNP = self.root.attachNewNode(PandaNode(\"stand-in\")) self.deathSound =",
"forward = self.actor.getQuat(Common.framework.showBase.render).getForward() forward2D = Vec2(forward.x, forward.y) vec = Vec2(vec.x, vec.y) vec.normalize() angle",
"speed/self.maxSpeed frictionVal = FRICTION*dt/(max(1, perc*perc)) if not self.inControl: frictionVal *= 0.8 if frictionVal",
"self.root = None class ArmedObject(): def __init__(self): self.weaponSets = [] self.weaponNPs = {}",
"weapon in self.weaponSets[weaponSet]: if weapon.active: weapon.triggerReleased(self) def update(self, dt): for weaponSet in self.weaponSets:",
"0 self.velocity = Vec3(0, 0, 0) self.acceleration = 300.0 self.inControl = True self.outOfControlTimer",
"modelName is None: self.actor = NodePath(PandaNode(\"actor\")) elif modelAnims is None: self.actor = Common.framework.showBase.loader.loadModel(modelName)",
"self.timer -= dt if self.timer < 0: self.timer = 0 perc = 1.0",
"pos, modelName, modelAnims, maxHealth, maxSpeed, colliderName, weaponIntoMask, size): self.root = Common.framework.showBase.render.attachNewNode(PandaNode(\"obj\")) self.colliderName =",
"0) self.acceleration = 300.0 self.inControl = True self.outOfControlTimer = 0 self.walking = False",
"speed = self.terminalVelocity if Common.useFriction: if not self.walking: perc = speed/self.maxSpeed frictionVal =",
"cleanup(self): if self.colliderNP is not None and not self.colliderNP.isEmpty(): self.colliderNP.clearPythonTag(TAG_OWNER) self.colliderNP.removeNode() self.colliderNP =",
"GameObject): target = target.root.getPos(Common.framework.showBase.render) diff = target - self.root.getPos(Common.framework.showBase.render) selfQuat = self.root.getQuat(Common.framework.showBase.render) selfForward",
"> 0 and self.health > self.maxHealth and not overcharge: self.health = self.maxHealth if",
"0) def alterHealth(self, dHealth, incomingImpulse, knockback, flinchValue, overcharge = False): previousHealth = self.health",
"def weaponFired(self, weapon): pass def weaponReset(self, weapon): pass def addWeapon(self, weapon, setIndex, sourceNP):",
"newQuat = selfQuat*quat self.root.setQuat(Common.framework.showBase.render, newQuat) def getAngleWithVec(self, vec): forward = self.actor.getQuat(Common.framework.showBase.render).getForward() forward2D =",
"def getAngleWithVec(self, vec): forward = self.actor.getQuat(Common.framework.showBase.render).getForward() forward2D = Vec2(forward.x, forward.y) vec = Vec2(vec.x,",
"= self.terminalVelocity if Common.useFriction: if not self.walking: perc = speed/self.maxSpeed frictionVal = FRICTION*dt/(max(1,",
"self.sizeRange*perc) self.model.setAlphaScale(math.sin(perc*3.142)) def cleanup(self): if self.model is not None: self.model.removeNode() self.model = None",
"else: self.outOfControlTimer -= dt if self.outOfControlTimer <= 0: self.inControl = True if fluid:",
"else: self.colliderNP = self.root.attachNewNode(PandaNode(\"stand-in\")) self.deathSound = None def physicalImpact(self, surfaceNormal): proj = self.velocity.project(surfaceNormal)",
"else: if speed > self.terminalVelocity: self.velocity.normalize() self.velocity *= self.terminalVelocity speed = self.terminalVelocity if",
"incomingImpulse is not None and knockback > 0.1: self.velocity += incomingImpulse*knockback self.inControl =",
"from panda3d.core import AudioSound from panda3d.core import PointLight from panda3d.core import NodePath, PandaNode",
"and not self.colliderNP.isEmpty(): self.colliderNP.clearPythonTag(TAG_OWNER) self.colliderNP.removeNode() self.colliderNP = None if self.actor is not None:",
"weaponSet < len(self.weaponSets): for weapon in self.weaponSets[weaponSet]: if weapon.active: weapon.triggerReleased(self) def update(self, dt):",
"= {} self.lockedTarget = None def weaponFired(self, weapon): pass def weaponReset(self, weapon): pass",
"random FRICTION = 10.0 class GameObject(): def __init__(self, pos, modelName, modelAnims, maxHealth, maxSpeed,",
"and self.health <= 0 and self.deathSound is not None: self.deathSound.play() def turnTowards(self, target,",
"diff = target - self.root.getPos(Common.framework.showBase.render) selfQuat = self.root.getQuat(Common.framework.showBase.render) selfForward = selfQuat.getForward() axis =",
"> speed: self.velocity.set(0, 0, 0) else: frictionVec = -self.velocity frictionVec.normalize() frictionVec *= frictionVal",
"self.terminalVelocity speed = self.terminalVelocity if Common.useFriction: if not self.walking: perc = speed/self.maxSpeed frictionVal",
"Vec4, Vec3, Vec2, Plane, Point3, BitMask32 from direct.actor.Actor import Actor from panda3d.core import",
"<gh_stars>0 from panda3d.core import Vec4, Vec3, Vec2, Plane, Point3, BitMask32 from direct.actor.Actor import",
"weapon, setIndex, sourceNP): while len(self.weaponSets) <= setIndex: self.weaponSets.append([]) self.weaponSets[setIndex].append(weapon) self.weaponNPs[weapon] = sourceNP def",
"= colliderName self.modelName = modelName if modelName is None: self.actor = NodePath(PandaNode(\"actor\")) elif",
"self.velocity.normalize() self.velocity *= self.terminalVelocity speed = self.terminalVelocity if Common.useFriction: if not self.walking: perc",
"0, size)) self.colliderNP = self.root.attachNewNode(colliderNode) self.colliderNP.setPythonTag(TAG_OWNER, self) colliderNode.setFromCollideMask(0) colliderNode.setIntoCollideMask(weaponIntoMask) #self.colliderNP.show() else: self.colliderNP =",
"speed: self.velocity.set(0, 0, 0) else: frictionVec = -self.velocity frictionVec.normalize() frictionVec *= frictionVal self.velocity",
"incomingImpulse*knockback self.inControl = False self.outOfControlTimer = knockback*0.1 self.walking = False if dHealth <",
"weapon.triggerReleased(self) def update(self, dt): for weaponSet in self.weaponSets: for weapon in weaponSet: weapon.update(dt,",
"self.colliderNP.setPythonTag(TAG_OWNER, self) colliderNode.setFromCollideMask(0) colliderNode.setIntoCollideMask(weaponIntoMask) #self.colliderNP.show() else: self.colliderNP = self.root.attachNewNode(PandaNode(\"stand-in\")) self.deathSound = None def",
"self.deathSound.play() def turnTowards(self, target, turnRate, dt): if isinstance(target, NodePath): target = target.getPos(Common.framework.showBase.render) elif",
"0 and self.deathSound is not None: self.deathSound.play() def turnTowards(self, target, turnRate, dt): if",
"pos is not None: self.root.setPos(pos) self.maxHealth = maxHealth self.health = maxHealth self.healthRechargeRate =",
"self.velocity -= proj*2 def update(self, dt, fluid = False): speed = self.velocity.length() if",
"modelName if modelName is None: self.actor = NodePath(PandaNode(\"actor\")) elif modelAnims is None: self.actor",
"if isinstance(self.actor, Actor): self.actor.cleanup() self.actor.removeNode() self.actor = None if self.root is not None:",
"if self.health < 0: self.health = 0 if flinchValue > 0: self.flinchCounter -=",
"self.weaponSets: for weapon in weaponSet: weapon.cleanup() self.weaponSets = [] self.weaponNPs = {} class",
"overcharge: self.health = self.maxHealth if previousHealth > 0 and self.health <= 0 and",
"-= dt if self.timer < 0: self.timer = 0 perc = 1.0 -",
"maxHealth self.healthRechargeRate = 2.0 self.healthRechargeSuppressionTimer = 0 self.healthRechargeSuppressionDuration = 0.5 self.maxSpeed = maxSpeed",
"*= 0.8 if frictionVal > speed: self.velocity.set(0, 0, 0) else: frictionVec = -self.velocity",
"turnRate, dt): if isinstance(target, NodePath): target = target.getPos(Common.framework.showBase.render) elif isinstance(target, GameObject): target =",
"dt): self.timer -= dt if self.timer < 0: self.timer = 0 perc =",
"direct.actor.Actor import Actor from panda3d.core import CollisionSphere, CollisionCapsule, CollisionNode, CollisionRay, CollisionSegment, CollisionHandlerQueue from",
"OnscreenText from direct.gui.OnscreenImage import OnscreenImage from panda3d.core import TextNode from panda3d.core import AudioSound",
"colliderName is not None: colliderNode = CollisionNode(colliderName) colliderNode.addSolid(CollisionSphere(0, 0, 0, size)) self.colliderNP =",
"isinstance(target, GameObject): target = target.root.getPos(Common.framework.showBase.render) diff = target - self.root.getPos(Common.framework.showBase.render) selfQuat = self.root.getQuat(Common.framework.showBase.render)",
"panda3d.core import CollisionSphere, CollisionCapsule, CollisionNode, CollisionRay, CollisionSegment, CollisionHandlerQueue from direct.gui.OnscreenText import OnscreenText from",
"selfQuat*quat self.root.setQuat(Common.framework.showBase.render, newQuat) def getAngleWithVec(self, vec): forward = self.actor.getQuat(Common.framework.showBase.render).getForward() forward2D = Vec2(forward.x, forward.y)",
"self.healthRechargeSuppressionDuration if self.health < 0: self.health = 0 if flinchValue > 0: self.flinchCounter",
"PointLight from panda3d.core import NodePath, PandaNode from panda3d.core import Quat from Section2SpaceflightDocking.CommonValues import",
"self.health = self.maxHealth if previousHealth > 0 and self.health <= 0 and self.deathSound",
"target.getPos(Common.framework.showBase.render) elif isinstance(target, GameObject): target = target.root.getPos(Common.framework.showBase.render) diff = target - self.root.getPos(Common.framework.showBase.render) selfQuat",
"alterHealth(self, dHealth, incomingImpulse, knockback, flinchValue, overcharge = False): previousHealth = self.health self.health +=",
"None def weaponFired(self, weapon): pass def weaponReset(self, weapon): pass def addWeapon(self, weapon, setIndex,",
"self.maxSpeed speed = self.maxSpeed else: if speed > self.terminalVelocity: self.velocity.normalize() self.velocity *= self.terminalVelocity",
"Common.framework.showBase.loader.loadModel(modelName) else: self.actor = Actor(modelName, modelAnims) self.actor.reparentTo(self.root) if pos is not None: self.root.setPos(pos)",
"proj = self.velocity.project(surfaceNormal) self.velocity -= proj*2 def update(self, dt, fluid = False): speed",
"= forward2D.signedAngleDeg(vec) return angle def cleanup(self): if self.colliderNP is not None and not",
"surfaceNormal): proj = self.velocity.project(surfaceNormal) self.velocity -= proj*2 def update(self, dt, fluid = False):",
"colliderName, weaponIntoMask, size): self.root = Common.framework.showBase.render.attachNewNode(PandaNode(\"obj\")) self.colliderName = colliderName self.modelName = modelName if",
"import Common import math, random FRICTION = 10.0 class GameObject(): def __init__(self, pos,",
"def cleanup(self): if self.colliderNP is not None and not self.colliderNP.isEmpty(): self.colliderNP.clearPythonTag(TAG_OWNER) self.colliderNP.removeNode() self.colliderNP",
"None and knockback > 0.1: self.velocity += incomingImpulse*knockback self.inControl = False self.outOfControlTimer =",
"self.root.setQuat(Common.framework.showBase.render, newQuat) def getAngleWithVec(self, vec): forward = self.actor.getQuat(Common.framework.showBase.render).getForward() forward2D = Vec2(forward.x, forward.y) vec",
"None: self.deathSound.play() def turnTowards(self, target, turnRate, dt): if isinstance(target, NodePath): target = target.getPos(Common.framework.showBase.render)",
"if frictionVal > speed: self.velocity.set(0, 0, 0) else: frictionVec = -self.velocity frictionVec.normalize() frictionVec",
"is not None: self.deathSound.play() def turnTowards(self, target, turnRate, dt): if isinstance(target, NodePath): target",
"+ self.velocity*dt) else: self.root.setPos(self.root.getPos() + self.velocity*dt) if self.healthRechargeSuppressionTimer > 0: self.healthRechargeSuppressionTimer -= dt",
"= FRICTION*dt/(max(1, perc*perc)) if not self.inControl: frictionVal *= 0.8 if frictionVal > speed:",
"- self.root.getPos(Common.framework.showBase.render) selfQuat = self.root.getQuat(Common.framework.showBase.render) selfForward = selfQuat.getForward() axis = selfForward.cross(diff.normalized()) axis.normalize() if",
"self.velocity.project(surfaceNormal) self.velocity -= proj*2 def update(self, dt, fluid = False): speed = self.velocity.length()",
"= {} class Blast(): def __init__(self, model, minSize, maxSize, duration): self.model = model",
"dt if self.outOfControlTimer <= 0: self.inControl = True if fluid: self.root.setFluidPos(self.root.getPos() + self.velocity*dt)",
"50 self.flinchCounter = 0 self.velocity = Vec3(0, 0, 0) self.acceleration = 300.0 self.inControl",
"if fluid: self.root.setFluidPos(self.root.getPos() + self.velocity*dt) else: self.root.setPos(self.root.getPos() + self.velocity*dt) if self.healthRechargeSuppressionTimer > 0:",
"= duration self.timer = duration def update(self, dt): self.timer -= dt if self.timer",
"self.sizeRange = self.maxSize - self.minSize self.duration = duration self.timer = duration def update(self,",
"and self.deathSound is not None: self.deathSound.play() def turnTowards(self, target, turnRate, dt): if isinstance(target,",
"False self.size = size if colliderName is not None: colliderNode = CollisionNode(colliderName) colliderNode.addSolid(CollisionSphere(0,",
"= 0 self.velocity = Vec3(0, 0, 0) self.acceleration = 300.0 self.inControl = True",
"self.actor = Actor(modelName, modelAnims) self.actor.reparentTo(self.root) if pos is not None: self.root.setPos(pos) self.maxHealth =",
"is None: self.actor = NodePath(PandaNode(\"actor\")) elif modelAnims is None: self.actor = Common.framework.showBase.loader.loadModel(modelName) else:",
"target = target.getPos(Common.framework.showBase.render) elif isinstance(target, GameObject): target = target.root.getPos(Common.framework.showBase.render) diff = target -",
"self) def attackPerformed(self, weapon): pass def cleanup(self): for weaponSet in self.weaponSets: for weapon",
"self.root.setFluidPos(self.root.getPos() + self.velocity*dt) else: self.root.setPos(self.root.getPos() + self.velocity*dt) if self.healthRechargeSuppressionTimer > 0: self.healthRechargeSuppressionTimer -=",
"= selfQuat*quat self.root.setQuat(Common.framework.showBase.render, newQuat) def getAngleWithVec(self, vec): forward = self.actor.getQuat(Common.framework.showBase.render).getForward() forward2D = Vec2(forward.x,",
"< 0: self.health = 0 if flinchValue > 0: self.flinchCounter -= flinchValue if",
"not self.colliderNP.isEmpty(): self.colliderNP.clearPythonTag(TAG_OWNER) self.colliderNP.removeNode() self.colliderNP = None if self.actor is not None: if",
"> self.terminalVelocity: self.velocity.normalize() self.velocity *= self.terminalVelocity speed = self.terminalVelocity if Common.useFriction: if not",
"self.weaponNPs = {} self.lockedTarget = None def weaponFired(self, weapon): pass def weaponReset(self, weapon):",
"weaponSet in self.weaponSets: for weapon in weaponSet: weapon.update(dt, self) def attackPerformed(self, weapon): pass",
"if self.root is not None: self.root.removeNode() self.root = None class ArmedObject(): def __init__(self):",
"self.actor.cleanup() self.actor.removeNode() self.actor = None if self.root is not None: self.root.removeNode() self.root =",
"self.walking and speed > self.maxSpeed: self.velocity.normalize() self.velocity *= self.maxSpeed speed = self.maxSpeed else:",
"pass def weaponReset(self, weapon): pass def addWeapon(self, weapon, setIndex, sourceNP): while len(self.weaponSets) <=",
"attackPerformed(self, weapon): pass def cleanup(self): for weaponSet in self.weaponSets: for weapon in weaponSet:",
"-self.velocity frictionVec.normalize() frictionVec *= frictionVal self.velocity += frictionVec if not self.inControl: if speed",
"0: self.health = 0 if flinchValue > 0: self.flinchCounter -= flinchValue if dHealth",
"def physicalImpact(self, surfaceNormal): proj = self.velocity.project(surfaceNormal) self.velocity -= proj*2 def update(self, dt, fluid",
"isinstance(target, NodePath): target = target.getPos(Common.framework.showBase.render) elif isinstance(target, GameObject): target = target.root.getPos(Common.framework.showBase.render) diff =",
"weapon): pass def addWeapon(self, weapon, setIndex, sourceNP): while len(self.weaponSets) <= setIndex: self.weaponSets.append([]) self.weaponSets[setIndex].append(weapon)",
"for weapon in self.weaponSets[weaponSet]: if not weapon.active: weapon.triggerPressed(self) def ceaseFiringSet(self, weaponSet): if weaponSet",
"CollisionHandlerQueue from direct.gui.OnscreenText import OnscreenText from direct.gui.OnscreenImage import OnscreenImage from panda3d.core import TextNode",
"PandaNode from panda3d.core import Quat from Section2SpaceflightDocking.CommonValues import * from Section2SpaceflightDocking.Common import Common",
"update(self, dt): self.timer -= dt if self.timer < 0: self.timer = 0 perc",
"None and not self.colliderNP.isEmpty(): self.colliderNP.clearPythonTag(TAG_OWNER) self.colliderNP.removeNode() self.colliderNP = None if self.actor is not",
"self.model.setBillboardPointEye() self.minSize = minSize self.maxSize = maxSize self.sizeRange = self.maxSize - self.minSize self.duration",
"< 0: self.timer = 0 perc = 1.0 - (self.timer / self.duration) self.model.setScale(self.minSize",
"and knockback > 0.1: self.velocity += incomingImpulse*knockback self.inControl = False self.outOfControlTimer = knockback*0.1",
"= self.actor.getQuat(Common.framework.showBase.render).getForward() forward2D = Vec2(forward.x, forward.y) vec = Vec2(vec.x, vec.y) vec.normalize() angle =",
"= None class ArmedObject(): def __init__(self): self.weaponSets = [] self.weaponNPs = {} self.lockedTarget",
"modelAnims, maxHealth, maxSpeed, colliderName, weaponIntoMask, size): self.root = Common.framework.showBase.render.attachNewNode(PandaNode(\"obj\")) self.colliderName = colliderName self.modelName",
"angle) quat.setFromAxisAngle(angle, axis) newQuat = selfQuat*quat self.root.setQuat(Common.framework.showBase.render, newQuat) def getAngleWithVec(self, vec): forward =",
"= self.healthRechargeSuppressionDuration if self.health < 0: self.health = 0 if flinchValue > 0:",
"if self.outOfControlTimer <= 0: self.inControl = True if fluid: self.root.setFluidPos(self.root.getPos() + self.velocity*dt) else:",
"weapon.active: weapon.triggerReleased(self) def update(self, dt): for weaponSet in self.weaponSets: for weapon in weaponSet:",
"0: self.flinchCounter -= flinchValue if dHealth > 0 and self.health > self.maxHealth and",
"= True if fluid: self.root.setFluidPos(self.root.getPos() + self.velocity*dt) else: self.root.setPos(self.root.getPos() + self.velocity*dt) if self.healthRechargeSuppressionTimer",
"direct.gui.OnscreenImage import OnscreenImage from panda3d.core import TextNode from panda3d.core import AudioSound from panda3d.core",
"self.inControl = False self.outOfControlTimer = knockback*0.1 self.walking = False if dHealth < 0:",
"direct.gui.OnscreenText import OnscreenText from direct.gui.OnscreenImage import OnscreenImage from panda3d.core import TextNode from panda3d.core",
"self.outOfControlTimer = knockback*0.1 self.walking = False if dHealth < 0: self.healthRechargeSuppressionTimer = self.healthRechargeSuppressionDuration",
"self.inControl: frictionVal *= 0.8 if frictionVal > speed: self.velocity.set(0, 0, 0) else: frictionVec",
"= 0 perc = 1.0 - (self.timer / self.duration) self.model.setScale(self.minSize + self.sizeRange*perc) self.model.setAlphaScale(math.sin(perc*3.142))",
"if not self.walking: perc = speed/self.maxSpeed frictionVal = FRICTION*dt/(max(1, perc*perc)) if not self.inControl:",
"*= frictionVal self.velocity += frictionVec if not self.inControl: if speed < 0.1: self.inControl",
"def __init__(self, pos, modelName, modelAnims, maxHealth, maxSpeed, colliderName, weaponIntoMask, size): self.root = Common.framework.showBase.render.attachNewNode(PandaNode(\"obj\"))",
"FRICTION*dt/(max(1, perc*perc)) if not self.inControl: frictionVal *= 0.8 if frictionVal > speed: self.velocity.set(0,",
"self.health = maxHealth self.healthRechargeRate = 2.0 self.healthRechargeSuppressionTimer = 0 self.healthRechargeSuppressionDuration = 0.5 self.maxSpeed",
"if previousHealth > 0 and self.health <= 0 and self.deathSound is not None:",
"from direct.gui.OnscreenText import OnscreenText from direct.gui.OnscreenImage import OnscreenImage from panda3d.core import TextNode from",
"self.colliderNP.removeNode() self.colliderNP = None if self.actor is not None: if isinstance(self.actor, Actor): self.actor.cleanup()",
"if self.inControl: if self.walking and speed > self.maxSpeed: self.velocity.normalize() self.velocity *= self.maxSpeed speed",
"* from Section2SpaceflightDocking.Common import Common import math, random FRICTION = 10.0 class GameObject():",
"perc*perc)) if not self.inControl: frictionVal *= 0.8 if frictionVal > speed: self.velocity.set(0, 0,",
"dt if self.timer < 0: self.timer = 0 perc = 1.0 - (self.timer",
"if weapon.active: weapon.triggerReleased(self) def update(self, dt): for weaponSet in self.weaponSets: for weapon in",
"= target - self.root.getPos(Common.framework.showBase.render) selfQuat = self.root.getQuat(Common.framework.showBase.render) selfForward = selfQuat.getForward() axis = selfForward.cross(diff.normalized())",
"= Common.framework.showBase.render.attachNewNode(PandaNode(\"obj\")) self.colliderName = colliderName self.modelName = modelName if modelName is None: self.actor",
"#self.colliderNP.show() else: self.colliderNP = self.root.attachNewNode(PandaNode(\"stand-in\")) self.deathSound = None def physicalImpact(self, surfaceNormal): proj =",
"colliderNode.setIntoCollideMask(weaponIntoMask) #self.colliderNP.show() else: self.colliderNP = self.root.attachNewNode(PandaNode(\"stand-in\")) self.deathSound = None def physicalImpact(self, surfaceNormal): proj",
"= self.maxHealth if previousHealth > 0 and self.health <= 0 and self.deathSound is",
"Quat() angle = math.copysign(min(abs(angle), turnRate*dt), angle) quat.setFromAxisAngle(angle, axis) newQuat = selfQuat*quat self.root.setQuat(Common.framework.showBase.render, newQuat)",
"= Vec3(0, 0, 0) self.acceleration = 300.0 self.inControl = True self.outOfControlTimer = 0",
"+= frictionVec if not self.inControl: if speed < 0.1: self.inControl = True else:",
"from Section2SpaceflightDocking.Common import Common import math, random FRICTION = 10.0 class GameObject(): def",
"dHealth > 0 and self.health > self.maxHealth and not overcharge: self.health = self.maxHealth",
"self.actor.getQuat(Common.framework.showBase.render).getForward() forward2D = Vec2(forward.x, forward.y) vec = Vec2(vec.x, vec.y) vec.normalize() angle = forward2D.signedAngleDeg(vec)",
"weapon.cleanup() self.weaponSets = [] self.weaponNPs = {} class Blast(): def __init__(self, model, minSize,",
"__init__(self): self.weaponSets = [] self.weaponNPs = {} self.lockedTarget = None def weaponFired(self, weapon):",
"= size if colliderName is not None: colliderNode = CollisionNode(colliderName) colliderNode.addSolid(CollisionSphere(0, 0, 0,",
"0: self.healthRechargeSuppressionTimer = self.healthRechargeSuppressionDuration if self.health < 0: self.health = 0 if flinchValue",
"len(self.weaponSets) <= setIndex: self.weaponSets.append([]) self.weaponSets[setIndex].append(weapon) self.weaponNPs[weapon] = sourceNP def startFiringSet(self, weaponSet): if weaponSet",
"not None: self.root.setPos(pos) self.maxHealth = maxHealth self.health = maxHealth self.healthRechargeRate = 2.0 self.healthRechargeSuppressionTimer",
"self.model.setTransparency(True) self.model.setBillboardPointEye() self.minSize = minSize self.maxSize = maxSize self.sizeRange = self.maxSize - self.minSize",
"if not self.inControl: if speed < 0.1: self.inControl = True else: self.outOfControlTimer -=",
"forward2D.signedAngleDeg(vec) return angle def cleanup(self): if self.colliderNP is not None and not self.colliderNP.isEmpty():",
"is not None: if isinstance(self.actor, Actor): self.actor.cleanup() self.actor.removeNode() self.actor = None if self.root",
"import * from Section2SpaceflightDocking.Common import Common import math, random FRICTION = 10.0 class",
"in weaponSet: weapon.update(dt, self) def attackPerformed(self, weapon): pass def cleanup(self): for weaponSet in",
"self.weaponSets = [] self.weaponNPs = {} class Blast(): def __init__(self, model, minSize, maxSize,",
"in weaponSet: weapon.cleanup() self.weaponSets = [] self.weaponNPs = {} class Blast(): def __init__(self,",
"elif isinstance(target, GameObject): target = target.root.getPos(Common.framework.showBase.render) diff = target - self.root.getPos(Common.framework.showBase.render) selfQuat =",
"self.root is not None: self.root.removeNode() self.root = None class ArmedObject(): def __init__(self): self.weaponSets",
"self.colliderNP.clearPythonTag(TAG_OWNER) self.colliderNP.removeNode() self.colliderNP = None if self.actor is not None: if isinstance(self.actor, Actor):",
"speed = self.maxSpeed else: if speed > self.terminalVelocity: self.velocity.normalize() self.velocity *= self.terminalVelocity speed",
"for weaponSet in self.weaponSets: for weapon in weaponSet: weapon.update(dt, self) def attackPerformed(self, weapon):",
"0.5 self.maxSpeed = maxSpeed self.terminalVelocity = 50 self.flinchCounter = 0 self.velocity = Vec3(0,",
"Common.framework.showBase.render.attachNewNode(PandaNode(\"obj\")) self.colliderName = colliderName self.modelName = modelName if modelName is None: self.actor =",
"CollisionCapsule, CollisionNode, CollisionRay, CollisionSegment, CollisionHandlerQueue from direct.gui.OnscreenText import OnscreenText from direct.gui.OnscreenImage import OnscreenImage",
"Actor(modelName, modelAnims) self.actor.reparentTo(self.root) if pos is not None: self.root.setPos(pos) self.maxHealth = maxHealth self.health",
"= None def physicalImpact(self, surfaceNormal): proj = self.velocity.project(surfaceNormal) self.velocity -= proj*2 def update(self,",
"+ self.velocity*dt) if self.healthRechargeSuppressionTimer > 0: self.healthRechargeSuppressionTimer -= dt else: self.alterHealth(self.healthRechargeRate*dt, None, 0,",
"from panda3d.core import CollisionSphere, CollisionCapsule, CollisionNode, CollisionRay, CollisionSegment, CollisionHandlerQueue from direct.gui.OnscreenText import OnscreenText",
"and not overcharge: self.health = self.maxHealth if previousHealth > 0 and self.health <=",
"(self.timer / self.duration) self.model.setScale(self.minSize + self.sizeRange*perc) self.model.setAlphaScale(math.sin(perc*3.142)) def cleanup(self): if self.model is not",
"= Quat() angle = math.copysign(min(abs(angle), turnRate*dt), angle) quat.setFromAxisAngle(angle, axis) newQuat = selfQuat*quat self.root.setQuat(Common.framework.showBase.render,",
"= 50 self.flinchCounter = 0 self.velocity = Vec3(0, 0, 0) self.acceleration = 300.0",
"self.colliderNP = self.root.attachNewNode(colliderNode) self.colliderNP.setPythonTag(TAG_OWNER, self) colliderNode.setFromCollideMask(0) colliderNode.setIntoCollideMask(weaponIntoMask) #self.colliderNP.show() else: self.colliderNP = self.root.attachNewNode(PandaNode(\"stand-in\")) self.deathSound",
"= 300.0 self.inControl = True self.outOfControlTimer = 0 self.walking = False self.size =",
"self.maxSize - self.minSize self.duration = duration self.timer = duration def update(self, dt): self.timer",
"Common import math, random FRICTION = 10.0 class GameObject(): def __init__(self, pos, modelName,",
"if incomingImpulse is not None and knockback > 0.1: self.velocity += incomingImpulse*knockback self.inControl",
"True if fluid: self.root.setFluidPos(self.root.getPos() + self.velocity*dt) else: self.root.setPos(self.root.getPos() + self.velocity*dt) if self.healthRechargeSuppressionTimer >",
"+= incomingImpulse*knockback self.inControl = False self.outOfControlTimer = knockback*0.1 self.walking = False if dHealth",
"from direct.gui.OnscreenImage import OnscreenImage from panda3d.core import TextNode from panda3d.core import AudioSound from",
"2.0 self.healthRechargeSuppressionTimer = 0 self.healthRechargeSuppressionDuration = 0.5 self.maxSpeed = maxSpeed self.terminalVelocity = 50",
"import Actor from panda3d.core import CollisionSphere, CollisionCapsule, CollisionNode, CollisionRay, CollisionSegment, CollisionHandlerQueue from direct.gui.OnscreenText",
"flinchValue if dHealth > 0 and self.health > self.maxHealth and not overcharge: self.health",
"weaponFired(self, weapon): pass def weaponReset(self, weapon): pass def addWeapon(self, weapon, setIndex, sourceNP): while",
"axis.normalize() if axis.lengthSquared() < 0.1: return angle = selfForward.signedAngleDeg(diff.normalized(), axis) quat = Quat()",
"modelAnims is None: self.actor = Common.framework.showBase.loader.loadModel(modelName) else: self.actor = Actor(modelName, modelAnims) self.actor.reparentTo(self.root) if",
"weaponSet): if weaponSet < len(self.weaponSets): for weapon in self.weaponSets[weaponSet]: if weapon.active: weapon.triggerReleased(self) def",
"self.inControl: if self.walking and speed > self.maxSpeed: self.velocity.normalize() self.velocity *= self.maxSpeed speed =",
"self.walking = False if dHealth < 0: self.healthRechargeSuppressionTimer = self.healthRechargeSuppressionDuration if self.health <",
"panda3d.core import Quat from Section2SpaceflightDocking.CommonValues import * from Section2SpaceflightDocking.Common import Common import math,",
"dt): if isinstance(target, NodePath): target = target.getPos(Common.framework.showBase.render) elif isinstance(target, GameObject): target = target.root.getPos(Common.framework.showBase.render)",
"= 0 if flinchValue > 0: self.flinchCounter -= flinchValue if dHealth > 0",
"addWeapon(self, weapon, setIndex, sourceNP): while len(self.weaponSets) <= setIndex: self.weaponSets.append([]) self.weaponSets[setIndex].append(weapon) self.weaponNPs[weapon] = sourceNP",
"if axis.lengthSquared() < 0.1: return angle = selfForward.signedAngleDeg(diff.normalized(), axis) quat = Quat() angle",
"in self.weaponSets: for weapon in weaponSet: weapon.update(dt, self) def attackPerformed(self, weapon): pass def",
"def alterHealth(self, dHealth, incomingImpulse, knockback, flinchValue, overcharge = False): previousHealth = self.health self.health",
"self.colliderNP = self.root.attachNewNode(PandaNode(\"stand-in\")) self.deathSound = None def physicalImpact(self, surfaceNormal): proj = self.velocity.project(surfaceNormal) self.velocity",
"not self.inControl: if speed < 0.1: self.inControl = True else: self.outOfControlTimer -= dt",
"self.velocity *= self.terminalVelocity speed = self.terminalVelocity if Common.useFriction: if not self.walking: perc =",
"self.colliderNP.isEmpty(): self.colliderNP.clearPythonTag(TAG_OWNER) self.colliderNP.removeNode() self.colliderNP = None if self.actor is not None: if isinstance(self.actor,",
"OnscreenImage from panda3d.core import TextNode from panda3d.core import AudioSound from panda3d.core import PointLight",
"def startFiringSet(self, weaponSet): if weaponSet < len(self.weaponSets): for weapon in self.weaponSets[weaponSet]: if not",
"False self.outOfControlTimer = knockback*0.1 self.walking = False if dHealth < 0: self.healthRechargeSuppressionTimer =",
"if self.healthRechargeSuppressionTimer > 0: self.healthRechargeSuppressionTimer -= dt else: self.alterHealth(self.healthRechargeRate*dt, None, 0, 0) def",
"self.duration = duration self.timer = duration def update(self, dt): self.timer -= dt if",
"= target.root.getPos(Common.framework.showBase.render) diff = target - self.root.getPos(Common.framework.showBase.render) selfQuat = self.root.getQuat(Common.framework.showBase.render) selfForward = selfQuat.getForward()",
"< len(self.weaponSets): for weapon in self.weaponSets[weaponSet]: if weapon.active: weapon.triggerReleased(self) def update(self, dt): for",
"import OnscreenText from direct.gui.OnscreenImage import OnscreenImage from panda3d.core import TextNode from panda3d.core import",
"True self.outOfControlTimer = 0 self.walking = False self.size = size if colliderName is",
"= self.maxSpeed else: if speed > self.terminalVelocity: self.velocity.normalize() self.velocity *= self.terminalVelocity speed =",
"forward2D = Vec2(forward.x, forward.y) vec = Vec2(vec.x, vec.y) vec.normalize() angle = forward2D.signedAngleDeg(vec) return",
"maxSpeed self.terminalVelocity = 50 self.flinchCounter = 0 self.velocity = Vec3(0, 0, 0) self.acceleration",
"perc = speed/self.maxSpeed frictionVal = FRICTION*dt/(max(1, perc*perc)) if not self.inControl: frictionVal *= 0.8",
"fluid: self.root.setFluidPos(self.root.getPos() + self.velocity*dt) else: self.root.setPos(self.root.getPos() + self.velocity*dt) if self.healthRechargeSuppressionTimer > 0: self.healthRechargeSuppressionTimer",
"pass def cleanup(self): for weaponSet in self.weaponSets: for weapon in weaponSet: weapon.cleanup() self.weaponSets",
"10.0 class GameObject(): def __init__(self, pos, modelName, modelAnims, maxHealth, maxSpeed, colliderName, weaponIntoMask, size):",
"0: self.inControl = True if fluid: self.root.setFluidPos(self.root.getPos() + self.velocity*dt) else: self.root.setPos(self.root.getPos() + self.velocity*dt)",
"self.outOfControlTimer -= dt if self.outOfControlTimer <= 0: self.inControl = True if fluid: self.root.setFluidPos(self.root.getPos()",
"self.healthRechargeSuppressionTimer = 0 self.healthRechargeSuppressionDuration = 0.5 self.maxSpeed = maxSpeed self.terminalVelocity = 50 self.flinchCounter",
"= self.root.attachNewNode(PandaNode(\"stand-in\")) self.deathSound = None def physicalImpact(self, surfaceNormal): proj = self.velocity.project(surfaceNormal) self.velocity -=",
"incomingImpulse, knockback, flinchValue, overcharge = False): previousHealth = self.health self.health += dHealth if",
"if pos is not None: self.root.setPos(pos) self.maxHealth = maxHealth self.health = maxHealth self.healthRechargeRate",
"<= setIndex: self.weaponSets.append([]) self.weaponSets[setIndex].append(weapon) self.weaponNPs[weapon] = sourceNP def startFiringSet(self, weaponSet): if weaponSet <",
"NodePath(PandaNode(\"actor\")) elif modelAnims is None: self.actor = Common.framework.showBase.loader.loadModel(modelName) else: self.actor = Actor(modelName, modelAnims)",
"None: self.actor = Common.framework.showBase.loader.loadModel(modelName) else: self.actor = Actor(modelName, modelAnims) self.actor.reparentTo(self.root) if pos is",
"= target.getPos(Common.framework.showBase.render) elif isinstance(target, GameObject): target = target.root.getPos(Common.framework.showBase.render) diff = target - self.root.getPos(Common.framework.showBase.render)",
"import CollisionSphere, CollisionCapsule, CollisionNode, CollisionRay, CollisionSegment, CollisionHandlerQueue from direct.gui.OnscreenText import OnscreenText from direct.gui.OnscreenImage",
"duration): self.model = model self.model.setTwoSided(True) self.model.setTransparency(True) self.model.setBillboardPointEye() self.minSize = minSize self.maxSize = maxSize",
"speed = self.velocity.length() if self.inControl: if self.walking and speed > self.maxSpeed: self.velocity.normalize() self.velocity",
"> self.maxSpeed: self.velocity.normalize() self.velocity *= self.maxSpeed speed = self.maxSpeed else: if speed >",
"0: self.timer = 0 perc = 1.0 - (self.timer / self.duration) self.model.setScale(self.minSize +",
"self.actor = Common.framework.showBase.loader.loadModel(modelName) else: self.actor = Actor(modelName, modelAnims) self.actor.reparentTo(self.root) if pos is not",
"dHealth if incomingImpulse is not None and knockback > 0.1: self.velocity += incomingImpulse*knockback",
"-= dt else: self.alterHealth(self.healthRechargeRate*dt, None, 0, 0) def alterHealth(self, dHealth, incomingImpulse, knockback, flinchValue,",
"forward.y) vec = Vec2(vec.x, vec.y) vec.normalize() angle = forward2D.signedAngleDeg(vec) return angle def cleanup(self):",
"selfQuat = self.root.getQuat(Common.framework.showBase.render) selfForward = selfQuat.getForward() axis = selfForward.cross(diff.normalized()) axis.normalize() if axis.lengthSquared() <",
"self.duration) self.model.setScale(self.minSize + self.sizeRange*perc) self.model.setAlphaScale(math.sin(perc*3.142)) def cleanup(self): if self.model is not None: self.model.removeNode()",
"CollisionRay, CollisionSegment, CollisionHandlerQueue from direct.gui.OnscreenText import OnscreenText from direct.gui.OnscreenImage import OnscreenImage from panda3d.core",
"Vec2(vec.x, vec.y) vec.normalize() angle = forward2D.signedAngleDeg(vec) return angle def cleanup(self): if self.colliderNP is",
"weaponIntoMask, size): self.root = Common.framework.showBase.render.attachNewNode(PandaNode(\"obj\")) self.colliderName = colliderName self.modelName = modelName if modelName",
"not None: if isinstance(self.actor, Actor): self.actor.cleanup() self.actor.removeNode() self.actor = None if self.root is",
"False if dHealth < 0: self.healthRechargeSuppressionTimer = self.healthRechargeSuppressionDuration if self.health < 0: self.health",
"selfForward.signedAngleDeg(diff.normalized(), axis) quat = Quat() angle = math.copysign(min(abs(angle), turnRate*dt), angle) quat.setFromAxisAngle(angle, axis) newQuat",
"= Actor(modelName, modelAnims) self.actor.reparentTo(self.root) if pos is not None: self.root.setPos(pos) self.maxHealth = maxHealth",
"math, random FRICTION = 10.0 class GameObject(): def __init__(self, pos, modelName, modelAnims, maxHealth,",
"__init__(self, model, minSize, maxSize, duration): self.model = model self.model.setTwoSided(True) self.model.setTransparency(True) self.model.setBillboardPointEye() self.minSize =",
"if dHealth > 0 and self.health > self.maxHealth and not overcharge: self.health =",
"0, 0, size)) self.colliderNP = self.root.attachNewNode(colliderNode) self.colliderNP.setPythonTag(TAG_OWNER, self) colliderNode.setFromCollideMask(0) colliderNode.setIntoCollideMask(weaponIntoMask) #self.colliderNP.show() else: self.colliderNP",
"self.weaponNPs[weapon] = sourceNP def startFiringSet(self, weaponSet): if weaponSet < len(self.weaponSets): for weapon in",
"self.maxHealth = maxHealth self.health = maxHealth self.healthRechargeRate = 2.0 self.healthRechargeSuppressionTimer = 0 self.healthRechargeSuppressionDuration",
"def turnTowards(self, target, turnRate, dt): if isinstance(target, NodePath): target = target.getPos(Common.framework.showBase.render) elif isinstance(target,",
"target - self.root.getPos(Common.framework.showBase.render) selfQuat = self.root.getQuat(Common.framework.showBase.render) selfForward = selfQuat.getForward() axis = selfForward.cross(diff.normalized()) axis.normalize()",
"model, minSize, maxSize, duration): self.model = model self.model.setTwoSided(True) self.model.setTransparency(True) self.model.setBillboardPointEye() self.minSize = minSize",
"Vec3, Vec2, Plane, Point3, BitMask32 from direct.actor.Actor import Actor from panda3d.core import CollisionSphere,",
"Plane, Point3, BitMask32 from direct.actor.Actor import Actor from panda3d.core import CollisionSphere, CollisionCapsule, CollisionNode,",
"if dHealth < 0: self.healthRechargeSuppressionTimer = self.healthRechargeSuppressionDuration if self.health < 0: self.health =",
"if weaponSet < len(self.weaponSets): for weapon in self.weaponSets[weaponSet]: if not weapon.active: weapon.triggerPressed(self) def",
"self.timer = duration def update(self, dt): self.timer -= dt if self.timer < 0:",
"Vec2, Plane, Point3, BitMask32 from direct.actor.Actor import Actor from panda3d.core import CollisionSphere, CollisionCapsule,",
"self.healthRechargeSuppressionTimer = self.healthRechargeSuppressionDuration if self.health < 0: self.health = 0 if flinchValue >",
"def cleanup(self): for weaponSet in self.weaponSets: for weapon in weaponSet: weapon.cleanup() self.weaponSets =",
"selfQuat.getForward() axis = selfForward.cross(diff.normalized()) axis.normalize() if axis.lengthSquared() < 0.1: return angle = selfForward.signedAngleDeg(diff.normalized(),",
"self.maxSpeed = maxSpeed self.terminalVelocity = 50 self.flinchCounter = 0 self.velocity = Vec3(0, 0,",
"self.terminalVelocity if Common.useFriction: if not self.walking: perc = speed/self.maxSpeed frictionVal = FRICTION*dt/(max(1, perc*perc))",
"self.root.getQuat(Common.framework.showBase.render) selfForward = selfQuat.getForward() axis = selfForward.cross(diff.normalized()) axis.normalize() if axis.lengthSquared() < 0.1: return",
"NodePath, PandaNode from panda3d.core import Quat from Section2SpaceflightDocking.CommonValues import * from Section2SpaceflightDocking.Common import",
"def update(self, dt): self.timer -= dt if self.timer < 0: self.timer = 0",
"self) colliderNode.setFromCollideMask(0) colliderNode.setIntoCollideMask(weaponIntoMask) #self.colliderNP.show() else: self.colliderNP = self.root.attachNewNode(PandaNode(\"stand-in\")) self.deathSound = None def physicalImpact(self,",
"def weaponReset(self, weapon): pass def addWeapon(self, weapon, setIndex, sourceNP): while len(self.weaponSets) <= setIndex:",
"self.outOfControlTimer = 0 self.walking = False self.size = size if colliderName is not",
"= 0.5 self.maxSpeed = maxSpeed self.terminalVelocity = 50 self.flinchCounter = 0 self.velocity =",
"TextNode from panda3d.core import AudioSound from panda3d.core import PointLight from panda3d.core import NodePath,",
"and speed > self.maxSpeed: self.velocity.normalize() self.velocity *= self.maxSpeed speed = self.maxSpeed else: if",
"self.flinchCounter -= flinchValue if dHealth > 0 and self.health > self.maxHealth and not",
"target.root.getPos(Common.framework.showBase.render) diff = target - self.root.getPos(Common.framework.showBase.render) selfQuat = self.root.getQuat(Common.framework.showBase.render) selfForward = selfQuat.getForward() axis",
"self.size = size if colliderName is not None: colliderNode = CollisionNode(colliderName) colliderNode.addSolid(CollisionSphere(0, 0,",
"*= self.terminalVelocity speed = self.terminalVelocity if Common.useFriction: if not self.walking: perc = speed/self.maxSpeed",
"self.velocity.normalize() self.velocity *= self.maxSpeed speed = self.maxSpeed else: if speed > self.terminalVelocity: self.velocity.normalize()",
"self.colliderName = colliderName self.modelName = modelName if modelName is None: self.actor = NodePath(PandaNode(\"actor\"))",
"None class ArmedObject(): def __init__(self): self.weaponSets = [] self.weaponNPs = {} self.lockedTarget =",
"size)) self.colliderNP = self.root.attachNewNode(colliderNode) self.colliderNP.setPythonTag(TAG_OWNER, self) colliderNode.setFromCollideMask(0) colliderNode.setIntoCollideMask(weaponIntoMask) #self.colliderNP.show() else: self.colliderNP = self.root.attachNewNode(PandaNode(\"stand-in\"))",
"colliderNode = CollisionNode(colliderName) colliderNode.addSolid(CollisionSphere(0, 0, 0, size)) self.colliderNP = self.root.attachNewNode(colliderNode) self.colliderNP.setPythonTag(TAG_OWNER, self) colliderNode.setFromCollideMask(0)",
"= 0 self.walking = False self.size = size if colliderName is not None:",
"self.healthRechargeSuppressionTimer -= dt else: self.alterHealth(self.healthRechargeRate*dt, None, 0, 0) def alterHealth(self, dHealth, incomingImpulse, knockback,",
"minSize self.maxSize = maxSize self.sizeRange = self.maxSize - self.minSize self.duration = duration self.timer",
"[] self.weaponNPs = {} self.lockedTarget = None def weaponFired(self, weapon): pass def weaponReset(self,",
"= 1.0 - (self.timer / self.duration) self.model.setScale(self.minSize + self.sizeRange*perc) self.model.setAlphaScale(math.sin(perc*3.142)) def cleanup(self): if",
"self.inControl: if speed < 0.1: self.inControl = True else: self.outOfControlTimer -= dt if",
"= maxHealth self.health = maxHealth self.healthRechargeRate = 2.0 self.healthRechargeSuppressionTimer = 0 self.healthRechargeSuppressionDuration =",
"frictionVec if not self.inControl: if speed < 0.1: self.inControl = True else: self.outOfControlTimer",
"dt): for weaponSet in self.weaponSets: for weapon in weaponSet: weapon.update(dt, self) def attackPerformed(self,",
"frictionVec.normalize() frictionVec *= frictionVal self.velocity += frictionVec if not self.inControl: if speed <",
"minSize, maxSize, duration): self.model = model self.model.setTwoSided(True) self.model.setTransparency(True) self.model.setBillboardPointEye() self.minSize = minSize self.maxSize",
"def attackPerformed(self, weapon): pass def cleanup(self): for weaponSet in self.weaponSets: for weapon in",
"not None: self.deathSound.play() def turnTowards(self, target, turnRate, dt): if isinstance(target, NodePath): target =",
"len(self.weaponSets): for weapon in self.weaponSets[weaponSet]: if weapon.active: weapon.triggerReleased(self) def update(self, dt): for weaponSet",
"physicalImpact(self, surfaceNormal): proj = self.velocity.project(surfaceNormal) self.velocity -= proj*2 def update(self, dt, fluid =",
"setIndex, sourceNP): while len(self.weaponSets) <= setIndex: self.weaponSets.append([]) self.weaponSets[setIndex].append(weapon) self.weaponNPs[weapon] = sourceNP def startFiringSet(self,",
"sourceNP): while len(self.weaponSets) <= setIndex: self.weaponSets.append([]) self.weaponSets[setIndex].append(weapon) self.weaponNPs[weapon] = sourceNP def startFiringSet(self, weaponSet):",
"setIndex: self.weaponSets.append([]) self.weaponSets[setIndex].append(weapon) self.weaponNPs[weapon] = sourceNP def startFiringSet(self, weaponSet): if weaponSet < len(self.weaponSets):",
"if Common.useFriction: if not self.walking: perc = speed/self.maxSpeed frictionVal = FRICTION*dt/(max(1, perc*perc)) if",
"else: self.actor = Actor(modelName, modelAnims) self.actor.reparentTo(self.root) if pos is not None: self.root.setPos(pos) self.maxHealth",
"= self.velocity.length() if self.inControl: if self.walking and speed > self.maxSpeed: self.velocity.normalize() self.velocity *=",
"None: self.root.removeNode() self.root = None class ArmedObject(): def __init__(self): self.weaponSets = [] self.weaponNPs",
"weaponSet: weapon.cleanup() self.weaponSets = [] self.weaponNPs = {} class Blast(): def __init__(self, model,",
"not self.walking: perc = speed/self.maxSpeed frictionVal = FRICTION*dt/(max(1, perc*perc)) if not self.inControl: frictionVal",
"self.velocity *= self.maxSpeed speed = self.maxSpeed else: if speed > self.terminalVelocity: self.velocity.normalize() self.velocity",
"0 and self.health > self.maxHealth and not overcharge: self.health = self.maxHealth if previousHealth",
"if flinchValue > 0: self.flinchCounter -= flinchValue if dHealth > 0 and self.health",
"in self.weaponSets[weaponSet]: if weapon.active: weapon.triggerReleased(self) def update(self, dt): for weaponSet in self.weaponSets: for",
"self.velocity*dt) if self.healthRechargeSuppressionTimer > 0: self.healthRechargeSuppressionTimer -= dt else: self.alterHealth(self.healthRechargeRate*dt, None, 0, 0)",
"= selfForward.cross(diff.normalized()) axis.normalize() if axis.lengthSquared() < 0.1: return angle = selfForward.signedAngleDeg(diff.normalized(), axis) quat",
"knockback > 0.1: self.velocity += incomingImpulse*knockback self.inControl = False self.outOfControlTimer = knockback*0.1 self.walking",
"class ArmedObject(): def __init__(self): self.weaponSets = [] self.weaponNPs = {} self.lockedTarget = None",
"= duration def update(self, dt): self.timer -= dt if self.timer < 0: self.timer",
"is None: self.actor = Common.framework.showBase.loader.loadModel(modelName) else: self.actor = Actor(modelName, modelAnims) self.actor.reparentTo(self.root) if pos",
"self.weaponSets[setIndex].append(weapon) self.weaponNPs[weapon] = sourceNP def startFiringSet(self, weaponSet): if weaponSet < len(self.weaponSets): for weapon",
"def update(self, dt): for weaponSet in self.weaponSets: for weapon in weaponSet: weapon.update(dt, self)",
"self.health > self.maxHealth and not overcharge: self.health = self.maxHealth if previousHealth > 0",
"from panda3d.core import TextNode from panda3d.core import AudioSound from panda3d.core import PointLight from",
"update(self, dt, fluid = False): speed = self.velocity.length() if self.inControl: if self.walking and",
"speed < 0.1: self.inControl = True else: self.outOfControlTimer -= dt if self.outOfControlTimer <=",
"colliderNode.addSolid(CollisionSphere(0, 0, 0, size)) self.colliderNP = self.root.attachNewNode(colliderNode) self.colliderNP.setPythonTag(TAG_OWNER, self) colliderNode.setFromCollideMask(0) colliderNode.setIntoCollideMask(weaponIntoMask) #self.colliderNP.show() else:",
"= CollisionNode(colliderName) colliderNode.addSolid(CollisionSphere(0, 0, 0, size)) self.colliderNP = self.root.attachNewNode(colliderNode) self.colliderNP.setPythonTag(TAG_OWNER, self) colliderNode.setFromCollideMask(0) colliderNode.setIntoCollideMask(weaponIntoMask)",
"None, 0, 0) def alterHealth(self, dHealth, incomingImpulse, knockback, flinchValue, overcharge = False): previousHealth",
"from panda3d.core import Vec4, Vec3, Vec2, Plane, Point3, BitMask32 from direct.actor.Actor import Actor",
"self.velocity += frictionVec if not self.inControl: if speed < 0.1: self.inControl = True",
"is not None: self.root.removeNode() self.root = None class ArmedObject(): def __init__(self): self.weaponSets =",
"self.velocity.length() if self.inControl: if self.walking and speed > self.maxSpeed: self.velocity.normalize() self.velocity *= self.maxSpeed",
"for weaponSet in self.weaponSets: for weapon in weaponSet: weapon.cleanup() self.weaponSets = [] self.weaponNPs",
"class Blast(): def __init__(self, model, minSize, maxSize, duration): self.model = model self.model.setTwoSided(True) self.model.setTransparency(True)",
"= True else: self.outOfControlTimer -= dt if self.outOfControlTimer <= 0: self.inControl = True",
"None: self.actor = NodePath(PandaNode(\"actor\")) elif modelAnims is None: self.actor = Common.framework.showBase.loader.loadModel(modelName) else: self.actor",
"axis.lengthSquared() < 0.1: return angle = selfForward.signedAngleDeg(diff.normalized(), axis) quat = Quat() angle =",
"= Vec2(forward.x, forward.y) vec = Vec2(vec.x, vec.y) vec.normalize() angle = forward2D.signedAngleDeg(vec) return angle",
"self.root.setPos(pos) self.maxHealth = maxHealth self.health = maxHealth self.healthRechargeRate = 2.0 self.healthRechargeSuppressionTimer = 0",
"is not None and knockback > 0.1: self.velocity += incomingImpulse*knockback self.inControl = False",
"target, turnRate, dt): if isinstance(target, NodePath): target = target.getPos(Common.framework.showBase.render) elif isinstance(target, GameObject): target",
"= False): previousHealth = self.health self.health += dHealth if incomingImpulse is not None",
"turnRate*dt), angle) quat.setFromAxisAngle(angle, axis) newQuat = selfQuat*quat self.root.setQuat(Common.framework.showBase.render, newQuat) def getAngleWithVec(self, vec): forward",
"frictionVec *= frictionVal self.velocity += frictionVec if not self.inControl: if speed < 0.1:",
"self.inControl = True else: self.outOfControlTimer -= dt if self.outOfControlTimer <= 0: self.inControl =",
"self.modelName = modelName if modelName is None: self.actor = NodePath(PandaNode(\"actor\")) elif modelAnims is",
"self.velocity.set(0, 0, 0) else: frictionVec = -self.velocity frictionVec.normalize() frictionVec *= frictionVal self.velocity +=",
"BitMask32 from direct.actor.Actor import Actor from panda3d.core import CollisionSphere, CollisionCapsule, CollisionNode, CollisionRay, CollisionSegment,",
"proj*2 def update(self, dt, fluid = False): speed = self.velocity.length() if self.inControl: if",
"0, 0) def alterHealth(self, dHealth, incomingImpulse, knockback, flinchValue, overcharge = False): previousHealth =",
"self.minSize self.duration = duration self.timer = duration def update(self, dt): self.timer -= dt",
"self.root.setPos(self.root.getPos() + self.velocity*dt) if self.healthRechargeSuppressionTimer > 0: self.healthRechargeSuppressionTimer -= dt else: self.alterHealth(self.healthRechargeRate*dt, None,",
"not overcharge: self.health = self.maxHealth if previousHealth > 0 and self.health <= 0",
"= False): speed = self.velocity.length() if self.inControl: if self.walking and speed > self.maxSpeed:",
"for weapon in self.weaponSets[weaponSet]: if weapon.active: weapon.triggerReleased(self) def update(self, dt): for weaponSet in",
"0.8 if frictionVal > speed: self.velocity.set(0, 0, 0) else: frictionVec = -self.velocity frictionVec.normalize()",
"axis) newQuat = selfQuat*quat self.root.setQuat(Common.framework.showBase.render, newQuat) def getAngleWithVec(self, vec): forward = self.actor.getQuat(Common.framework.showBase.render).getForward() forward2D",
"perc = 1.0 - (self.timer / self.duration) self.model.setScale(self.minSize + self.sizeRange*perc) self.model.setAlphaScale(math.sin(perc*3.142)) def cleanup(self):",
"weapon): pass def cleanup(self): for weaponSet in self.weaponSets: for weapon in weaponSet: weapon.cleanup()",
"colliderNode.setFromCollideMask(0) colliderNode.setIntoCollideMask(weaponIntoMask) #self.colliderNP.show() else: self.colliderNP = self.root.attachNewNode(PandaNode(\"stand-in\")) self.deathSound = None def physicalImpact(self, surfaceNormal):",
"dt, fluid = False): speed = self.velocity.length() if self.inControl: if self.walking and speed",
"self.model.setTwoSided(True) self.model.setTransparency(True) self.model.setBillboardPointEye() self.minSize = minSize self.maxSize = maxSize self.sizeRange = self.maxSize -",
"frictionVec = -self.velocity frictionVec.normalize() frictionVec *= frictionVal self.velocity += frictionVec if not self.inControl:",
"1.0 - (self.timer / self.duration) self.model.setScale(self.minSize + self.sizeRange*perc) self.model.setAlphaScale(math.sin(perc*3.142)) def cleanup(self): if self.model",
"weapon.triggerPressed(self) def ceaseFiringSet(self, weaponSet): if weaponSet < len(self.weaponSets): for weapon in self.weaponSets[weaponSet]: if",
"AudioSound from panda3d.core import PointLight from panda3d.core import NodePath, PandaNode from panda3d.core import",
"self.actor = NodePath(PandaNode(\"actor\")) elif modelAnims is None: self.actor = Common.framework.showBase.loader.loadModel(modelName) else: self.actor =",
"= modelName if modelName is None: self.actor = NodePath(PandaNode(\"actor\")) elif modelAnims is None:",
"newQuat) def getAngleWithVec(self, vec): forward = self.actor.getQuat(Common.framework.showBase.render).getForward() forward2D = Vec2(forward.x, forward.y) vec =",
"300.0 self.inControl = True self.outOfControlTimer = 0 self.walking = False self.size = size",
"from panda3d.core import PointLight from panda3d.core import NodePath, PandaNode from panda3d.core import Quat",
"Vec3(0, 0, 0) self.acceleration = 300.0 self.inControl = True self.outOfControlTimer = 0 self.walking",
"self.actor.reparentTo(self.root) if pos is not None: self.root.setPos(pos) self.maxHealth = maxHealth self.health = maxHealth",
"frictionVal self.velocity += frictionVec if not self.inControl: if speed < 0.1: self.inControl =",
"self.root.attachNewNode(colliderNode) self.colliderNP.setPythonTag(TAG_OWNER, self) colliderNode.setFromCollideMask(0) colliderNode.setIntoCollideMask(weaponIntoMask) #self.colliderNP.show() else: self.colliderNP = self.root.attachNewNode(PandaNode(\"stand-in\")) self.deathSound = None",
"weaponSet): if weaponSet < len(self.weaponSets): for weapon in self.weaponSets[weaponSet]: if not weapon.active: weapon.triggerPressed(self)",
"def ceaseFiringSet(self, weaponSet): if weaponSet < len(self.weaponSets): for weapon in self.weaponSets[weaponSet]: if weapon.active:",
"Point3, BitMask32 from direct.actor.Actor import Actor from panda3d.core import CollisionSphere, CollisionCapsule, CollisionNode, CollisionRay,",
"= maxSpeed self.terminalVelocity = 50 self.flinchCounter = 0 self.velocity = Vec3(0, 0, 0)",
"self.maxSpeed else: if speed > self.terminalVelocity: self.velocity.normalize() self.velocity *= self.terminalVelocity speed = self.terminalVelocity",
"duration self.timer = duration def update(self, dt): self.timer -= dt if self.timer <",
"vec = Vec2(vec.x, vec.y) vec.normalize() angle = forward2D.signedAngleDeg(vec) return angle def cleanup(self): if",
"Actor from panda3d.core import CollisionSphere, CollisionCapsule, CollisionNode, CollisionRay, CollisionSegment, CollisionHandlerQueue from direct.gui.OnscreenText import",
"= knockback*0.1 self.walking = False if dHealth < 0: self.healthRechargeSuppressionTimer = self.healthRechargeSuppressionDuration if",
"weaponReset(self, weapon): pass def addWeapon(self, weapon, setIndex, sourceNP): while len(self.weaponSets) <= setIndex: self.weaponSets.append([])",
"size): self.root = Common.framework.showBase.render.attachNewNode(PandaNode(\"obj\")) self.colliderName = colliderName self.modelName = modelName if modelName is",
"= None if self.actor is not None: if isinstance(self.actor, Actor): self.actor.cleanup() self.actor.removeNode() self.actor",
"weaponSet < len(self.weaponSets): for weapon in self.weaponSets[weaponSet]: if not weapon.active: weapon.triggerPressed(self) def ceaseFiringSet(self,",
"self.maxSpeed: self.velocity.normalize() self.velocity *= self.maxSpeed speed = self.maxSpeed else: if speed > self.terminalVelocity:",
"-= proj*2 def update(self, dt, fluid = False): speed = self.velocity.length() if self.inControl:",
"weapon in self.weaponSets[weaponSet]: if not weapon.active: weapon.triggerPressed(self) def ceaseFiringSet(self, weaponSet): if weaponSet <",
"weapon in weaponSet: weapon.update(dt, self) def attackPerformed(self, weapon): pass def cleanup(self): for weaponSet",
"model self.model.setTwoSided(True) self.model.setTransparency(True) self.model.setBillboardPointEye() self.minSize = minSize self.maxSize = maxSize self.sizeRange = self.maxSize",
"panda3d.core import NodePath, PandaNode from panda3d.core import Quat from Section2SpaceflightDocking.CommonValues import * from",
"Common.useFriction: if not self.walking: perc = speed/self.maxSpeed frictionVal = FRICTION*dt/(max(1, perc*perc)) if not",
"0 self.healthRechargeSuppressionDuration = 0.5 self.maxSpeed = maxSpeed self.terminalVelocity = 50 self.flinchCounter = 0",
"isinstance(self.actor, Actor): self.actor.cleanup() self.actor.removeNode() self.actor = None if self.root is not None: self.root.removeNode()",
"elif modelAnims is None: self.actor = Common.framework.showBase.loader.loadModel(modelName) else: self.actor = Actor(modelName, modelAnims) self.actor.reparentTo(self.root)",
"= Vec2(vec.x, vec.y) vec.normalize() angle = forward2D.signedAngleDeg(vec) return angle def cleanup(self): if self.colliderNP",
"panda3d.core import Vec4, Vec3, Vec2, Plane, Point3, BitMask32 from direct.actor.Actor import Actor from",
"def addWeapon(self, weapon, setIndex, sourceNP): while len(self.weaponSets) <= setIndex: self.weaponSets.append([]) self.weaponSets[setIndex].append(weapon) self.weaponNPs[weapon] =",
"self.root.removeNode() self.root = None class ArmedObject(): def __init__(self): self.weaponSets = [] self.weaponNPs =",
"= None if self.root is not None: self.root.removeNode() self.root = None class ArmedObject():",
"if isinstance(target, NodePath): target = target.getPos(Common.framework.showBase.render) elif isinstance(target, GameObject): target = target.root.getPos(Common.framework.showBase.render) diff",
"= self.velocity.project(surfaceNormal) self.velocity -= proj*2 def update(self, dt, fluid = False): speed =",
"= [] self.weaponNPs = {} class Blast(): def __init__(self, model, minSize, maxSize, duration):",
"getAngleWithVec(self, vec): forward = self.actor.getQuat(Common.framework.showBase.render).getForward() forward2D = Vec2(forward.x, forward.y) vec = Vec2(vec.x, vec.y)",
"= selfQuat.getForward() axis = selfForward.cross(diff.normalized()) axis.normalize() if axis.lengthSquared() < 0.1: return angle =",
"flinchValue, overcharge = False): previousHealth = self.health self.health += dHealth if incomingImpulse is",
"< 0: self.healthRechargeSuppressionTimer = self.healthRechargeSuppressionDuration if self.health < 0: self.health = 0 if",
"for weapon in weaponSet: weapon.update(dt, self) def attackPerformed(self, weapon): pass def cleanup(self): for",
"= self.maxSize - self.minSize self.duration = duration self.timer = duration def update(self, dt):",
"knockback*0.1 self.walking = False if dHealth < 0: self.healthRechargeSuppressionTimer = self.healthRechargeSuppressionDuration if self.health",
"self.velocity = Vec3(0, 0, 0) self.acceleration = 300.0 self.inControl = True self.outOfControlTimer =",
"weapon): pass def weaponReset(self, weapon): pass def addWeapon(self, weapon, setIndex, sourceNP): while len(self.weaponSets)",
"flinchValue > 0: self.flinchCounter -= flinchValue if dHealth > 0 and self.health >",
"<= 0: self.inControl = True if fluid: self.root.setFluidPos(self.root.getPos() + self.velocity*dt) else: self.root.setPos(self.root.getPos() +",
"from panda3d.core import Quat from Section2SpaceflightDocking.CommonValues import * from Section2SpaceflightDocking.Common import Common import",
"import AudioSound from panda3d.core import PointLight from panda3d.core import NodePath, PandaNode from panda3d.core",
"Vec2(forward.x, forward.y) vec = Vec2(vec.x, vec.y) vec.normalize() angle = forward2D.signedAngleDeg(vec) return angle def",
"else: frictionVec = -self.velocity frictionVec.normalize() frictionVec *= frictionVal self.velocity += frictionVec if not",
"self.colliderNP is not None and not self.colliderNP.isEmpty(): self.colliderNP.clearPythonTag(TAG_OWNER) self.colliderNP.removeNode() self.colliderNP = None if",
"self.maxHealth and not overcharge: self.health = self.maxHealth if previousHealth > 0 and self.health",
"0, 0) self.acceleration = 300.0 self.inControl = True self.outOfControlTimer = 0 self.walking =",
"def __init__(self, model, minSize, maxSize, duration): self.model = model self.model.setTwoSided(True) self.model.setTransparency(True) self.model.setBillboardPointEye() self.minSize",
"if self.timer < 0: self.timer = 0 perc = 1.0 - (self.timer /",
"if speed < 0.1: self.inControl = True else: self.outOfControlTimer -= dt if self.outOfControlTimer",
"[] self.weaponNPs = {} class Blast(): def __init__(self, model, minSize, maxSize, duration): self.model",
"<= 0 and self.deathSound is not None: self.deathSound.play() def turnTowards(self, target, turnRate, dt):",
"self.healthRechargeSuppressionTimer > 0: self.healthRechargeSuppressionTimer -= dt else: self.alterHealth(self.healthRechargeRate*dt, None, 0, 0) def alterHealth(self,",
"False): previousHealth = self.health self.health += dHealth if incomingImpulse is not None and",
"speed > self.maxSpeed: self.velocity.normalize() self.velocity *= self.maxSpeed speed = self.maxSpeed else: if speed",
"self.health < 0: self.health = 0 if flinchValue > 0: self.flinchCounter -= flinchValue",
"quat.setFromAxisAngle(angle, axis) newQuat = selfQuat*quat self.root.setQuat(Common.framework.showBase.render, newQuat) def getAngleWithVec(self, vec): forward = self.actor.getQuat(Common.framework.showBase.render).getForward()",
"frictionVal = FRICTION*dt/(max(1, perc*perc)) if not self.inControl: frictionVal *= 0.8 if frictionVal >",
"- (self.timer / self.duration) self.model.setScale(self.minSize + self.sizeRange*perc) self.model.setAlphaScale(math.sin(perc*3.142)) def cleanup(self): if self.model is",
"selfForward = selfQuat.getForward() axis = selfForward.cross(diff.normalized()) axis.normalize() if axis.lengthSquared() < 0.1: return angle",
"not None: colliderNode = CollisionNode(colliderName) colliderNode.addSolid(CollisionSphere(0, 0, 0, size)) self.colliderNP = self.root.attachNewNode(colliderNode) self.colliderNP.setPythonTag(TAG_OWNER,",
"= selfForward.signedAngleDeg(diff.normalized(), axis) quat = Quat() angle = math.copysign(min(abs(angle), turnRate*dt), angle) quat.setFromAxisAngle(angle, axis)",
"def __init__(self): self.weaponSets = [] self.weaponNPs = {} self.lockedTarget = None def weaponFired(self,",
"len(self.weaponSets): for weapon in self.weaponSets[weaponSet]: if not weapon.active: weapon.triggerPressed(self) def ceaseFiringSet(self, weaponSet): if",
"dt else: self.alterHealth(self.healthRechargeRate*dt, None, 0, 0) def alterHealth(self, dHealth, incomingImpulse, knockback, flinchValue, overcharge",
"if self.colliderNP is not None and not self.colliderNP.isEmpty(): self.colliderNP.clearPythonTag(TAG_OWNER) self.colliderNP.removeNode() self.colliderNP = None",
"duration def update(self, dt): self.timer -= dt if self.timer < 0: self.timer =",
"None def physicalImpact(self, surfaceNormal): proj = self.velocity.project(surfaceNormal) self.velocity -= proj*2 def update(self, dt,",
"self.outOfControlTimer <= 0: self.inControl = True if fluid: self.root.setFluidPos(self.root.getPos() + self.velocity*dt) else: self.root.setPos(self.root.getPos()",
"import OnscreenImage from panda3d.core import TextNode from panda3d.core import AudioSound from panda3d.core import",
"Quat from Section2SpaceflightDocking.CommonValues import * from Section2SpaceflightDocking.Common import Common import math, random FRICTION",
"= speed/self.maxSpeed frictionVal = FRICTION*dt/(max(1, perc*perc)) if not self.inControl: frictionVal *= 0.8 if",
"else: self.root.setPos(self.root.getPos() + self.velocity*dt) if self.healthRechargeSuppressionTimer > 0: self.healthRechargeSuppressionTimer -= dt else: self.alterHealth(self.healthRechargeRate*dt,",
"0, 0) else: frictionVec = -self.velocity frictionVec.normalize() frictionVec *= frictionVal self.velocity += frictionVec",
"vec): forward = self.actor.getQuat(Common.framework.showBase.render).getForward() forward2D = Vec2(forward.x, forward.y) vec = Vec2(vec.x, vec.y) vec.normalize()",
"while len(self.weaponSets) <= setIndex: self.weaponSets.append([]) self.weaponSets[setIndex].append(weapon) self.weaponNPs[weapon] = sourceNP def startFiringSet(self, weaponSet): if",
"self.flinchCounter = 0 self.velocity = Vec3(0, 0, 0) self.acceleration = 300.0 self.inControl =",
"self.weaponSets: for weapon in weaponSet: weapon.update(dt, self) def attackPerformed(self, weapon): pass def cleanup(self):",
"import Quat from Section2SpaceflightDocking.CommonValues import * from Section2SpaceflightDocking.Common import Common import math, random",
"None: self.root.setPos(pos) self.maxHealth = maxHealth self.health = maxHealth self.healthRechargeRate = 2.0 self.healthRechargeSuppressionTimer =",
"weapon.update(dt, self) def attackPerformed(self, weapon): pass def cleanup(self): for weaponSet in self.weaponSets: for",
"Section2SpaceflightDocking.Common import Common import math, random FRICTION = 10.0 class GameObject(): def __init__(self,",
"None: if isinstance(self.actor, Actor): self.actor.cleanup() self.actor.removeNode() self.actor = None if self.root is not",
"panda3d.core import TextNode from panda3d.core import AudioSound from panda3d.core import PointLight from panda3d.core",
"fluid = False): speed = self.velocity.length() if self.inControl: if self.walking and speed >",
"weaponSet: weapon.update(dt, self) def attackPerformed(self, weapon): pass def cleanup(self): for weaponSet in self.weaponSets:",
"= [] self.weaponNPs = {} self.lockedTarget = None def weaponFired(self, weapon): pass def",
"> 0 and self.health <= 0 and self.deathSound is not None: self.deathSound.play() def",
"CollisionSegment, CollisionHandlerQueue from direct.gui.OnscreenText import OnscreenText from direct.gui.OnscreenImage import OnscreenImage from panda3d.core import",
"class GameObject(): def __init__(self, pos, modelName, modelAnims, maxHealth, maxSpeed, colliderName, weaponIntoMask, size): self.root",
"modelAnims) self.actor.reparentTo(self.root) if pos is not None: self.root.setPos(pos) self.maxHealth = maxHealth self.health =",
"return angle = selfForward.signedAngleDeg(diff.normalized(), axis) quat = Quat() angle = math.copysign(min(abs(angle), turnRate*dt), angle)",
"self.velocity += incomingImpulse*knockback self.inControl = False self.outOfControlTimer = knockback*0.1 self.walking = False if",
"> 0: self.healthRechargeSuppressionTimer -= dt else: self.alterHealth(self.healthRechargeRate*dt, None, 0, 0) def alterHealth(self, dHealth,",
"self.model.setScale(self.minSize + self.sizeRange*perc) self.model.setAlphaScale(math.sin(perc*3.142)) def cleanup(self): if self.model is not None: self.model.removeNode() self.model",
"self.lockedTarget = None def weaponFired(self, weapon): pass def weaponReset(self, weapon): pass def addWeapon(self,",
"angle def cleanup(self): if self.colliderNP is not None and not self.colliderNP.isEmpty(): self.colliderNP.clearPythonTag(TAG_OWNER) self.colliderNP.removeNode()",
"self.colliderNP = None if self.actor is not None: if isinstance(self.actor, Actor): self.actor.cleanup() self.actor.removeNode()",
"Blast(): def __init__(self, model, minSize, maxSize, duration): self.model = model self.model.setTwoSided(True) self.model.setTransparency(True) self.model.setBillboardPointEye()",
"angle = selfForward.signedAngleDeg(diff.normalized(), axis) quat = Quat() angle = math.copysign(min(abs(angle), turnRate*dt), angle) quat.setFromAxisAngle(angle,",
"maxHealth, maxSpeed, colliderName, weaponIntoMask, size): self.root = Common.framework.showBase.render.attachNewNode(PandaNode(\"obj\")) self.colliderName = colliderName self.modelName =",
"0.1: self.inControl = True else: self.outOfControlTimer -= dt if self.outOfControlTimer <= 0: self.inControl",
"0: self.healthRechargeSuppressionTimer -= dt else: self.alterHealth(self.healthRechargeRate*dt, None, 0, 0) def alterHealth(self, dHealth, incomingImpulse,",
"= self.root.getQuat(Common.framework.showBase.render) selfForward = selfQuat.getForward() axis = selfForward.cross(diff.normalized()) axis.normalize() if axis.lengthSquared() < 0.1:",
"axis = selfForward.cross(diff.normalized()) axis.normalize() if axis.lengthSquared() < 0.1: return angle = selfForward.signedAngleDeg(diff.normalized(), axis)",
"selfForward.cross(diff.normalized()) axis.normalize() if axis.lengthSquared() < 0.1: return angle = selfForward.signedAngleDeg(diff.normalized(), axis) quat =",
"self.health += dHealth if incomingImpulse is not None and knockback > 0.1: self.velocity",
"- self.minSize self.duration = duration self.timer = duration def update(self, dt): self.timer -=",
"previousHealth > 0 and self.health <= 0 and self.deathSound is not None: self.deathSound.play()",
"self.deathSound is not None: self.deathSound.play() def turnTowards(self, target, turnRate, dt): if isinstance(target, NodePath):",
"0.1: return angle = selfForward.signedAngleDeg(diff.normalized(), axis) quat = Quat() angle = math.copysign(min(abs(angle), turnRate*dt),",
"self.healthRechargeRate = 2.0 self.healthRechargeSuppressionTimer = 0 self.healthRechargeSuppressionDuration = 0.5 self.maxSpeed = maxSpeed self.terminalVelocity",
"weapon in weaponSet: weapon.cleanup() self.weaponSets = [] self.weaponNPs = {} class Blast(): def",
"= 0 self.healthRechargeSuppressionDuration = 0.5 self.maxSpeed = maxSpeed self.terminalVelocity = 50 self.flinchCounter =",
"maxSize, duration): self.model = model self.model.setTwoSided(True) self.model.setTransparency(True) self.model.setBillboardPointEye() self.minSize = minSize self.maxSize =",
"self.actor.removeNode() self.actor = None if self.root is not None: self.root.removeNode() self.root = None",
"self.walking: perc = speed/self.maxSpeed frictionVal = FRICTION*dt/(max(1, perc*perc)) if not self.inControl: frictionVal *=",
"import Vec4, Vec3, Vec2, Plane, Point3, BitMask32 from direct.actor.Actor import Actor from panda3d.core",
"= False self.outOfControlTimer = knockback*0.1 self.walking = False if dHealth < 0: self.healthRechargeSuppressionTimer",
"-= flinchValue if dHealth > 0 and self.health > self.maxHealth and not overcharge:",
"turnTowards(self, target, turnRate, dt): if isinstance(target, NodePath): target = target.getPos(Common.framework.showBase.render) elif isinstance(target, GameObject):",
"angle = forward2D.signedAngleDeg(vec) return angle def cleanup(self): if self.colliderNP is not None and",
"for weapon in weaponSet: weapon.cleanup() self.weaponSets = [] self.weaponNPs = {} class Blast():",
"self.root.getPos(Common.framework.showBase.render) selfQuat = self.root.getQuat(Common.framework.showBase.render) selfForward = selfQuat.getForward() axis = selfForward.cross(diff.normalized()) axis.normalize() if axis.lengthSquared()"
] |
[
"start_amqp(self): \"\"\"Starts all needed threads: scheduler, controller and AMQP transport IOLOOP. \"\"\" retry_timeout",
"KeyboardInterrupt: self.stop_synapse() except KeyboardInterrupt: self.stop_synapse() except SystemExit: pass except ResourceException as err: self.logger.error(str(err))",
"try: transports[self.transport]() except (AttributeError, KeyError), err: self.logger.error(\"Transport unknown. [%s]\" % err) self.stop_synapse() sys.exit()",
"Start the scheduler self.sched.start() self.amqpsynapse = AmqpSynapse(config.rabbitmq, publish_queue=self.publish_queue, tasks_queue=self.tasks_queue) while not self.force_close: try:",
"import sys import time import signal import socket from Queue import Queue from",
"class Dispatcher(object): \"\"\"This module dispatches commands incoming from the command line to specific",
"from synapse.amqp import AmqpSynapse, AmqpAdmin, AmqpError from synapse.config import config from synapse.controller import",
"%d sec\" % retry_timeout) time.sleep(retry_timeout) except KeyboardInterrupt: self.stop_synapse() raise SystemExit except AmqpError as",
"unknown. [%s]\" % err) self.stop_synapse() sys.exit() def start_amqp(self): \"\"\"Starts all needed threads: scheduler,",
"self.resourcefile = None # These queues will be shared between the controller and",
"transport self.force_close = False # Handle signals #signal.signal(signal.SIGINT, self.stop) signal.signal(signal.SIGTERM, self.stop) # Threads",
"It is also responsible for starting threads and catching signals like SIGINT and",
"{ 'amqp': self.start_amqp, 'http': self.start_resourcefile, 'file': self.start_resourcefile, } try: transports[self.transport]() except (AttributeError, KeyError),",
"and SIGTERM signals. \"\"\" self.logger.debug(\"Stopping due to signal #%d\" % signum) self.stop_synapse() def",
"SystemExit: pass except ResourceException as err: self.logger.error(str(err)) def start_resourcefile(self): \"\"\"This method handles the",
"import Queue from synapse.scheduler import SynSched from synapse.amqp import AmqpSynapse, AmqpAdmin, AmqpError from",
"Start the controller self.controller.start() # Start the scheduler self.sched.start() self.amqpsynapse = AmqpSynapse(config.rabbitmq, publish_queue=self.publish_queue,",
"KeyboardInterrupt: self.stop_synapse() raise SystemExit except AmqpError as err: break except KeyboardInterrupt: self.stop_synapse() raise",
"queues will be shared between the controller and the # transport and are",
"time.sleep(retry_timeout) except KeyboardInterrupt: self.stop_synapse() raise SystemExit except AmqpError as err: break except KeyboardInterrupt:",
"SIGTERM signals. \"\"\" self.logger.debug(\"Stopping due to signal #%d\" % signum) self.stop_synapse() def stop_synapse(self):",
"transport' % self.transport.capitalize()) transports = { 'amqp': self.start_amqp, 'http': self.start_resourcefile, 'file': self.start_resourcefile, }",
"signals. \"\"\" self.logger.debug(\"Stopping due to signal #%d\" % signum) self.stop_synapse() def stop_synapse(self): \"\"\"Closes",
"to quit if self.controller: if self.controller.isAlive(): self.controller.close() self.controller.join() self.logger.debug(\"Controller thread stopped\") # Shutdown",
"} try: transports[self.transport]() except (AttributeError, KeyError), err: self.logger.error(\"Transport unknown. [%s]\" % err) self.stop_synapse()",
"start_resourcefile(self): \"\"\"This method handles the --uri file and --uri http commands. \"\"\" from",
"self.logger.error(str(err)) def start_resourcefile(self): \"\"\"This method handles the --uri file and --uri http commands.",
"and wait for it to quit if self.controller: if self.controller.isAlive(): self.controller.close() self.controller.join() self.logger.debug(\"Controller",
"self.stop_synapse() except SystemExit: pass except ResourceException as err: self.logger.error(str(err)) def start_resourcefile(self): \"\"\"This method",
"self.sched.join() self.logger.debug(\"Scheduler stopped\") self.force_close = True self.logger.info(\"Successfully stopped.\") def dispatch(self): \"\"\"This method actually",
"AMQP transport IOLOOP. \"\"\" retry_timeout = config.rabbitmq['retry_timeout'] try: self.amqpadmin = AmqpAdmin(config.rabbitmq) while not",
"tasks and responses self.publish_queue = Queue() self.tasks_queue = Queue() def stop(self, signum, frame):",
"and catching signals like SIGINT and SIGTERM. \"\"\" def __init__(self, transport): self.transport =",
"and --uri http commands. \"\"\" from synapse.resourcefile import ResourceFile try: self.resourcefile = ResourceFile(self.transport)",
"while not self.force_close: try: self.amqpadmin.connect() break except (socket.timeout, IOError) as err: self.logger.error(err) try:",
"SynSched() self.controller = Controller(scheduler=self.sched, tasks_queue=self.tasks_queue, publish_queue=self.publish_queue) # Start the controller self.controller.start() # Start",
"\"\"\"This method actually dispatches to specific transport methods according to command line parameters.",
"\"\"\"Closes all threads and exits properly. \"\"\" if self.resourcefile: self.resourcefile.done = True #",
"line parameters. \"\"\" self.logger.info('Starting on %s transport' % self.transport.capitalize()) transports = { 'amqp':",
"methods according to command line parameters. \"\"\" self.logger.info('Starting on %s transport' % self.transport.capitalize())",
"\"\"\" retry_timeout = config.rabbitmq['retry_timeout'] try: self.amqpadmin = AmqpAdmin(config.rabbitmq) while not self.force_close: try: self.amqpadmin.connect()",
"time import signal import socket from Queue import Queue from synapse.scheduler import SynSched",
"True # Close the controller and wait for it to quit if self.controller:",
"import logger from synapse.synapse_exceptions import ResourceException @logger class Dispatcher(object): \"\"\"This module dispatches commands",
"SystemExit except AmqpError as err: break except KeyboardInterrupt: self.stop_synapse() raise SystemExit self.sched =",
"self.logger.debug(\"Controller thread stopped\") # Shutdown the scheduler/monitor if self.sched: if self.sched.isAlive(): self.sched.shutdown() self.sched.join()",
"'amqp': self.start_amqp, 'http': self.start_resourcefile, 'file': self.start_resourcefile, } try: transports[self.transport]() except (AttributeError, KeyError), err:",
"Queue() def stop(self, signum, frame): \"\"\"This method handles SIGINT and SIGTERM signals. \"\"\"",
"def start_resourcefile(self): \"\"\"This method handles the --uri file and --uri http commands. \"\"\"",
"tasks_queue=self.tasks_queue) while not self.force_close: try: self.amqpsynapse.connect() except (AmqpError, IOError) as err: self.logger.error(err) try:",
"self.logger.debug(\"Scheduler stopped\") self.force_close = True self.logger.info(\"Successfully stopped.\") def dispatch(self): \"\"\"This method actually dispatches",
"def dispatch(self): \"\"\"This method actually dispatches to specific transport methods according to command",
"#%d\" % signum) self.stop_synapse() def stop_synapse(self): \"\"\"Closes all threads and exits properly. \"\"\"",
"self.controller.join() self.logger.debug(\"Controller thread stopped\") # Shutdown the scheduler/monitor if self.sched: if self.sched.isAlive(): self.sched.shutdown()",
"properly. \"\"\" if self.resourcefile: self.resourcefile.done = True # Close the controller and wait",
"between the controller and the # transport and are used for incoming tasks",
"except KeyboardInterrupt: self.stop_synapse() raise SystemExit self.sched = SynSched() self.controller = Controller(scheduler=self.sched, tasks_queue=self.tasks_queue, publish_queue=self.publish_queue)",
"= True self.logger.info(\"Successfully stopped.\") def dispatch(self): \"\"\"This method actually dispatches to specific transport",
"from Queue import Queue from synapse.scheduler import SynSched from synapse.amqp import AmqpSynapse, AmqpAdmin,",
"the --uri file and --uri http commands. \"\"\" from synapse.resourcefile import ResourceFile try:",
"self.logger.info('Starting on %s transport' % self.transport.capitalize()) transports = { 'amqp': self.start_amqp, 'http': self.start_resourcefile,",
"transport methods according to command line parameters. \"\"\" self.logger.info('Starting on %s transport' %",
"logger from synapse.synapse_exceptions import ResourceException @logger class Dispatcher(object): \"\"\"This module dispatches commands incoming",
"try: self.amqpadmin = AmqpAdmin(config.rabbitmq) while not self.force_close: try: self.amqpadmin.connect() break except (socket.timeout, IOError)",
"exits properly. \"\"\" if self.resourcefile: self.resourcefile.done = True # Close the controller and",
"if self.controller.isAlive(): self.controller.close() self.controller.join() self.logger.debug(\"Controller thread stopped\") # Shutdown the scheduler/monitor if self.sched:",
"and the # transport and are used for incoming tasks and responses self.publish_queue",
"try: self.logger.debug(\"Sleeping %d sec\" % retry_timeout) time.sleep(retry_timeout) except KeyboardInterrupt: self.stop_synapse() except KeyboardInterrupt: self.stop_synapse()",
"socket from Queue import Queue from synapse.scheduler import SynSched from synapse.amqp import AmqpSynapse,",
"be shared between the controller and the # transport and are used for",
"and responses self.publish_queue = Queue() self.tasks_queue = Queue() def stop(self, signum, frame): \"\"\"This",
"from synapse.config import config from synapse.controller import Controller from synapse.logger import logger from",
"True self.logger.info(\"Successfully stopped.\") def dispatch(self): \"\"\"This method actually dispatches to specific transport methods",
"KeyboardInterrupt: self.stop_synapse() except SystemExit: pass except ResourceException as err: self.logger.error(str(err)) def start_resourcefile(self): \"\"\"This",
"self.logger.debug(\"Sleeping %d sec\" % retry_timeout) time.sleep(retry_timeout) except KeyboardInterrupt: self.stop_synapse() raise SystemExit except AmqpError",
"= None # These queues will be shared between the controller and the",
"% retry_timeout) time.sleep(retry_timeout) except KeyboardInterrupt: self.stop_synapse() raise SystemExit except AmqpError as err: break",
"= None self.resourcefile = None # These queues will be shared between the",
"except ResourceException as err: self.logger.error(str(err)) def start_resourcefile(self): \"\"\"This method handles the --uri file",
"= AmqpSynapse(config.rabbitmq, publish_queue=self.publish_queue, tasks_queue=self.tasks_queue) while not self.force_close: try: self.amqpsynapse.connect() except (AmqpError, IOError) as",
"err: self.logger.error(err) try: self.logger.debug(\"Sleeping %d sec\" % retry_timeout) time.sleep(retry_timeout) except KeyboardInterrupt: self.stop_synapse() except",
"AmqpSynapse, AmqpAdmin, AmqpError from synapse.config import config from synapse.controller import Controller from synapse.logger",
"self.controller = None self.sched = None self.resourcefile = None # These queues will",
"Close the controller and wait for it to quit if self.controller: if self.controller.isAlive():",
"incoming from the command line to specific transports. It is also responsible for",
"ResourceException as err: self.logger.error(str(err)) def start_resourcefile(self): \"\"\"This method handles the --uri file and",
"scheduler, controller and AMQP transport IOLOOP. \"\"\" retry_timeout = config.rabbitmq['retry_timeout'] try: self.amqpadmin =",
"catching signals like SIGINT and SIGTERM. \"\"\" def __init__(self, transport): self.transport = transport",
"is also responsible for starting threads and catching signals like SIGINT and SIGTERM.",
"# Close the controller and wait for it to quit if self.controller: if",
"transport): self.transport = transport self.force_close = False # Handle signals #signal.signal(signal.SIGINT, self.stop) signal.signal(signal.SIGTERM,",
"self.sched = SynSched() self.controller = Controller(scheduler=self.sched, tasks_queue=self.tasks_queue, publish_queue=self.publish_queue) # Start the controller self.controller.start()",
"the # transport and are used for incoming tasks and responses self.publish_queue =",
"= False # Handle signals #signal.signal(signal.SIGINT, self.stop) signal.signal(signal.SIGTERM, self.stop) # Threads instances variables",
"Threads instances variables self.controller = None self.sched = None self.resourcefile = None #",
"handles SIGINT and SIGTERM signals. \"\"\" self.logger.debug(\"Stopping due to signal #%d\" % signum)",
"retry_timeout) time.sleep(retry_timeout) except KeyboardInterrupt: self.stop_synapse() raise SystemExit except AmqpError as err: break except",
"self.stop_synapse() raise SystemExit except AmqpError as err: break except KeyboardInterrupt: self.stop_synapse() raise SystemExit",
"self.force_close = False # Handle signals #signal.signal(signal.SIGINT, self.stop) signal.signal(signal.SIGTERM, self.stop) # Threads instances",
"synapse.synapse_exceptions import ResourceException @logger class Dispatcher(object): \"\"\"This module dispatches commands incoming from the",
"self.sched.start() self.amqpsynapse = AmqpSynapse(config.rabbitmq, publish_queue=self.publish_queue, tasks_queue=self.tasks_queue) while not self.force_close: try: self.amqpsynapse.connect() except (AmqpError,",
"self.force_close = True self.logger.info(\"Successfully stopped.\") def dispatch(self): \"\"\"This method actually dispatches to specific",
"are used for incoming tasks and responses self.publish_queue = Queue() self.tasks_queue = Queue()",
"try: self.logger.debug(\"Sleeping %d sec\" % retry_timeout) time.sleep(retry_timeout) except KeyboardInterrupt: self.stop_synapse() raise SystemExit except",
"import ResourceException @logger class Dispatcher(object): \"\"\"This module dispatches commands incoming from the command",
"'http': self.start_resourcefile, 'file': self.start_resourcefile, } try: transports[self.transport]() except (AttributeError, KeyError), err: self.logger.error(\"Transport unknown.",
"self.transport = transport self.force_close = False # Handle signals #signal.signal(signal.SIGINT, self.stop) signal.signal(signal.SIGTERM, self.stop)",
"publish_queue=self.publish_queue, tasks_queue=self.tasks_queue) while not self.force_close: try: self.amqpsynapse.connect() except (AmqpError, IOError) as err: self.logger.error(err)",
"method handles the --uri file and --uri http commands. \"\"\" from synapse.resourcefile import",
"scheduler self.sched.start() self.amqpsynapse = AmqpSynapse(config.rabbitmq, publish_queue=self.publish_queue, tasks_queue=self.tasks_queue) while not self.force_close: try: self.amqpsynapse.connect() except",
"self.tasks_queue = Queue() def stop(self, signum, frame): \"\"\"This method handles SIGINT and SIGTERM",
"signal.signal(signal.SIGTERM, self.stop) # Threads instances variables self.controller = None self.sched = None self.resourcefile",
"ResourceException @logger class Dispatcher(object): \"\"\"This module dispatches commands incoming from the command line",
"= AmqpAdmin(config.rabbitmq) while not self.force_close: try: self.amqpadmin.connect() break except (socket.timeout, IOError) as err:",
"signals like SIGINT and SIGTERM. \"\"\" def __init__(self, transport): self.transport = transport self.force_close",
"self.transport.capitalize()) transports = { 'amqp': self.start_amqp, 'http': self.start_resourcefile, 'file': self.start_resourcefile, } try: transports[self.transport]()",
"= Queue() self.tasks_queue = Queue() def stop(self, signum, frame): \"\"\"This method handles SIGINT",
"wait for it to quit if self.controller: if self.controller.isAlive(): self.controller.close() self.controller.join() self.logger.debug(\"Controller thread",
"responses self.publish_queue = Queue() self.tasks_queue = Queue() def stop(self, signum, frame): \"\"\"This method",
"AmqpError as err: break except KeyboardInterrupt: self.stop_synapse() raise SystemExit self.sched = SynSched() self.controller",
"synapse.logger import logger from synapse.synapse_exceptions import ResourceException @logger class Dispatcher(object): \"\"\"This module dispatches",
"and exits properly. \"\"\" if self.resourcefile: self.resourcefile.done = True # Close the controller",
"tasks_queue=self.tasks_queue, publish_queue=self.publish_queue) # Start the controller self.controller.start() # Start the scheduler self.sched.start() self.amqpsynapse",
"(socket.timeout, IOError) as err: self.logger.error(err) try: self.logger.debug(\"Sleeping %d sec\" % retry_timeout) time.sleep(retry_timeout) except",
"AmqpAdmin, AmqpError from synapse.config import config from synapse.controller import Controller from synapse.logger import",
"\"\"\"This method handles SIGINT and SIGTERM signals. \"\"\" self.logger.debug(\"Stopping due to signal #%d\"",
"controller self.controller.start() # Start the scheduler self.sched.start() self.amqpsynapse = AmqpSynapse(config.rabbitmq, publish_queue=self.publish_queue, tasks_queue=self.tasks_queue) while",
"file and --uri http commands. \"\"\" from synapse.resourcefile import ResourceFile try: self.resourcefile =",
"command line parameters. \"\"\" self.logger.info('Starting on %s transport' % self.transport.capitalize()) transports = {",
"def __init__(self, transport): self.transport = transport self.force_close = False # Handle signals #signal.signal(signal.SIGINT,",
"as err: self.logger.error(err) try: self.logger.debug(\"Sleeping %d sec\" % retry_timeout) time.sleep(retry_timeout) except KeyboardInterrupt: self.stop_synapse()",
"method handles SIGINT and SIGTERM signals. \"\"\" self.logger.debug(\"Stopping due to signal #%d\" %",
"self.start_amqp, 'http': self.start_resourcefile, 'file': self.start_resourcefile, } try: transports[self.transport]() except (AttributeError, KeyError), err: self.logger.error(\"Transport",
"break except KeyboardInterrupt: self.stop_synapse() raise SystemExit self.sched = SynSched() self.controller = Controller(scheduler=self.sched, tasks_queue=self.tasks_queue,",
"self.logger.debug(\"Sleeping %d sec\" % retry_timeout) time.sleep(retry_timeout) except KeyboardInterrupt: self.stop_synapse() except KeyboardInterrupt: self.stop_synapse() except",
"to specific transports. It is also responsible for starting threads and catching signals",
"raise SystemExit self.sched = SynSched() self.controller = Controller(scheduler=self.sched, tasks_queue=self.tasks_queue, publish_queue=self.publish_queue) # Start the",
"self.amqpadmin = AmqpAdmin(config.rabbitmq) while not self.force_close: try: self.amqpadmin.connect() break except (socket.timeout, IOError) as",
"config.rabbitmq['retry_timeout'] try: self.amqpadmin = AmqpAdmin(config.rabbitmq) while not self.force_close: try: self.amqpadmin.connect() break except (socket.timeout,",
"except SystemExit: pass except ResourceException as err: self.logger.error(str(err)) def start_resourcefile(self): \"\"\"This method handles",
"err) self.stop_synapse() sys.exit() def start_amqp(self): \"\"\"Starts all needed threads: scheduler, controller and AMQP",
"controller and AMQP transport IOLOOP. \"\"\" retry_timeout = config.rabbitmq['retry_timeout'] try: self.amqpadmin = AmqpAdmin(config.rabbitmq)",
"sec\" % retry_timeout) time.sleep(retry_timeout) except KeyboardInterrupt: self.stop_synapse() raise SystemExit except AmqpError as err:",
"publish_queue=self.publish_queue) # Start the controller self.controller.start() # Start the scheduler self.sched.start() self.amqpsynapse =",
"self.amqpsynapse = AmqpSynapse(config.rabbitmq, publish_queue=self.publish_queue, tasks_queue=self.tasks_queue) while not self.force_close: try: self.amqpsynapse.connect() except (AmqpError, IOError)",
"--uri http commands. \"\"\" from synapse.resourcefile import ResourceFile try: self.resourcefile = ResourceFile(self.transport) self.resourcefile.fetch()",
"self.stop_synapse() except KeyboardInterrupt: self.stop_synapse() except SystemExit: pass except ResourceException as err: self.logger.error(str(err)) def",
"if self.controller: if self.controller.isAlive(): self.controller.close() self.controller.join() self.logger.debug(\"Controller thread stopped\") # Shutdown the scheduler/monitor",
"needed threads: scheduler, controller and AMQP transport IOLOOP. \"\"\" retry_timeout = config.rabbitmq['retry_timeout'] try:",
"except (AttributeError, KeyError), err: self.logger.error(\"Transport unknown. [%s]\" % err) self.stop_synapse() sys.exit() def start_amqp(self):",
"AmqpAdmin(config.rabbitmq) while not self.force_close: try: self.amqpadmin.connect() break except (socket.timeout, IOError) as err: self.logger.error(err)",
"stopped\") # Shutdown the scheduler/monitor if self.sched: if self.sched.isAlive(): self.sched.shutdown() self.sched.join() self.logger.debug(\"Scheduler stopped\")",
"instances variables self.controller = None self.sched = None self.resourcefile = None # These",
"Controller(scheduler=self.sched, tasks_queue=self.tasks_queue, publish_queue=self.publish_queue) # Start the controller self.controller.start() # Start the scheduler self.sched.start()",
"def start_amqp(self): \"\"\"Starts all needed threads: scheduler, controller and AMQP transport IOLOOP. \"\"\"",
"SIGTERM. \"\"\" def __init__(self, transport): self.transport = transport self.force_close = False # Handle",
"commands incoming from the command line to specific transports. It is also responsible",
"Dispatcher(object): \"\"\"This module dispatches commands incoming from the command line to specific transports.",
"due to signal #%d\" % signum) self.stop_synapse() def stop_synapse(self): \"\"\"Closes all threads and",
"self.sched.shutdown() self.sched.join() self.logger.debug(\"Scheduler stopped\") self.force_close = True self.logger.info(\"Successfully stopped.\") def dispatch(self): \"\"\"This method",
"signals #signal.signal(signal.SIGINT, self.stop) signal.signal(signal.SIGTERM, self.stop) # Threads instances variables self.controller = None self.sched",
"Shutdown the scheduler/monitor if self.sched: if self.sched.isAlive(): self.sched.shutdown() self.sched.join() self.logger.debug(\"Scheduler stopped\") self.force_close =",
"% self.transport.capitalize()) transports = { 'amqp': self.start_amqp, 'http': self.start_resourcefile, 'file': self.start_resourcefile, } try:",
"to specific transport methods according to command line parameters. \"\"\" self.logger.info('Starting on %s",
"AmqpError from synapse.config import config from synapse.controller import Controller from synapse.logger import logger",
"dispatches commands incoming from the command line to specific transports. It is also",
"self.logger.debug(\"Stopping due to signal #%d\" % signum) self.stop_synapse() def stop_synapse(self): \"\"\"Closes all threads",
"responsible for starting threads and catching signals like SIGINT and SIGTERM. \"\"\" def",
"incoming tasks and responses self.publish_queue = Queue() self.tasks_queue = Queue() def stop(self, signum,",
"dispatches to specific transport methods according to command line parameters. \"\"\" self.logger.info('Starting on",
"variables self.controller = None self.sched = None self.resourcefile = None # These queues",
"scheduler/monitor if self.sched: if self.sched.isAlive(): self.sched.shutdown() self.sched.join() self.logger.debug(\"Scheduler stopped\") self.force_close = True self.logger.info(\"Successfully",
"and are used for incoming tasks and responses self.publish_queue = Queue() self.tasks_queue =",
"SynSched from synapse.amqp import AmqpSynapse, AmqpAdmin, AmqpError from synapse.config import config from synapse.controller",
"SIGINT and SIGTERM signals. \"\"\" self.logger.debug(\"Stopping due to signal #%d\" % signum) self.stop_synapse()",
"--uri file and --uri http commands. \"\"\" from synapse.resourcefile import ResourceFile try: self.resourcefile",
"KeyError), err: self.logger.error(\"Transport unknown. [%s]\" % err) self.stop_synapse() sys.exit() def start_amqp(self): \"\"\"Starts all",
"from synapse.controller import Controller from synapse.logger import logger from synapse.synapse_exceptions import ResourceException @logger",
"(AmqpError, IOError) as err: self.logger.error(err) try: self.logger.debug(\"Sleeping %d sec\" % retry_timeout) time.sleep(retry_timeout) except",
"also responsible for starting threads and catching signals like SIGINT and SIGTERM. \"\"\"",
"transport IOLOOP. \"\"\" retry_timeout = config.rabbitmq['retry_timeout'] try: self.amqpadmin = AmqpAdmin(config.rabbitmq) while not self.force_close:",
"sys import time import signal import socket from Queue import Queue from synapse.scheduler",
"if self.sched: if self.sched.isAlive(): self.sched.shutdown() self.sched.join() self.logger.debug(\"Scheduler stopped\") self.force_close = True self.logger.info(\"Successfully stopped.\")",
"= transport self.force_close = False # Handle signals #signal.signal(signal.SIGINT, self.stop) signal.signal(signal.SIGTERM, self.stop) #",
"from synapse.logger import logger from synapse.synapse_exceptions import ResourceException @logger class Dispatcher(object): \"\"\"This module",
"synapse.controller import Controller from synapse.logger import logger from synapse.synapse_exceptions import ResourceException @logger class",
"= Queue() def stop(self, signum, frame): \"\"\"This method handles SIGINT and SIGTERM signals.",
"config from synapse.controller import Controller from synapse.logger import logger from synapse.synapse_exceptions import ResourceException",
"'file': self.start_resourcefile, } try: transports[self.transport]() except (AttributeError, KeyError), err: self.logger.error(\"Transport unknown. [%s]\" %",
"http commands. \"\"\" from synapse.resourcefile import ResourceFile try: self.resourcefile = ResourceFile(self.transport) self.resourcefile.fetch() except",
"except KeyboardInterrupt: self.stop_synapse() except KeyboardInterrupt: self.stop_synapse() except SystemExit: pass except ResourceException as err:",
"self.stop_synapse() sys.exit() def start_amqp(self): \"\"\"Starts all needed threads: scheduler, controller and AMQP transport",
"for it to quit if self.controller: if self.controller.isAlive(): self.controller.close() self.controller.join() self.logger.debug(\"Controller thread stopped\")",
"specific transports. It is also responsible for starting threads and catching signals like",
"try: self.amqpadmin.connect() break except (socket.timeout, IOError) as err: self.logger.error(err) try: self.logger.debug(\"Sleeping %d sec\"",
"the controller self.controller.start() # Start the scheduler self.sched.start() self.amqpsynapse = AmqpSynapse(config.rabbitmq, publish_queue=self.publish_queue, tasks_queue=self.tasks_queue)",
"all needed threads: scheduler, controller and AMQP transport IOLOOP. \"\"\" retry_timeout = config.rabbitmq['retry_timeout']",
"stop_synapse(self): \"\"\"Closes all threads and exits properly. \"\"\" if self.resourcefile: self.resourcefile.done = True",
"commands. \"\"\" from synapse.resourcefile import ResourceFile try: self.resourcefile = ResourceFile(self.transport) self.resourcefile.fetch() except KeyboardInterrupt:",
"synapse.scheduler import SynSched from synapse.amqp import AmqpSynapse, AmqpAdmin, AmqpError from synapse.config import config",
"err: break except KeyboardInterrupt: self.stop_synapse() raise SystemExit self.sched = SynSched() self.controller = Controller(scheduler=self.sched,",
"and AMQP transport IOLOOP. \"\"\" retry_timeout = config.rabbitmq['retry_timeout'] try: self.amqpadmin = AmqpAdmin(config.rabbitmq) while",
"for starting threads and catching signals like SIGINT and SIGTERM. \"\"\" def __init__(self,",
"parameters. \"\"\" self.logger.info('Starting on %s transport' % self.transport.capitalize()) transports = { 'amqp': self.start_amqp,",
"= Controller(scheduler=self.sched, tasks_queue=self.tasks_queue, publish_queue=self.publish_queue) # Start the controller self.controller.start() # Start the scheduler",
"self.controller = Controller(scheduler=self.sched, tasks_queue=self.tasks_queue, publish_queue=self.publish_queue) # Start the controller self.controller.start() # Start the",
"except (AmqpError, IOError) as err: self.logger.error(err) try: self.logger.debug(\"Sleeping %d sec\" % retry_timeout) time.sleep(retry_timeout)",
"self.amqpadmin.connect() break except (socket.timeout, IOError) as err: self.logger.error(err) try: self.logger.debug(\"Sleeping %d sec\" %",
"% retry_timeout) time.sleep(retry_timeout) except KeyboardInterrupt: self.stop_synapse() except KeyboardInterrupt: self.stop_synapse() except SystemExit: pass except",
"\"\"\" self.logger.info('Starting on %s transport' % self.transport.capitalize()) transports = { 'amqp': self.start_amqp, 'http':",
"retry_timeout) time.sleep(retry_timeout) except KeyboardInterrupt: self.stop_synapse() except KeyboardInterrupt: self.stop_synapse() except SystemExit: pass except ResourceException",
"#signal.signal(signal.SIGINT, self.stop) signal.signal(signal.SIGTERM, self.stop) # Threads instances variables self.controller = None self.sched =",
"on %s transport' % self.transport.capitalize()) transports = { 'amqp': self.start_amqp, 'http': self.start_resourcefile, 'file':",
"except KeyboardInterrupt: self.stop_synapse() raise SystemExit except AmqpError as err: break except KeyboardInterrupt: self.stop_synapse()",
"self.resourcefile.done = True # Close the controller and wait for it to quit",
"\"\"\"Starts all needed threads: scheduler, controller and AMQP transport IOLOOP. \"\"\" retry_timeout =",
"These queues will be shared between the controller and the # transport and",
"# These queues will be shared between the controller and the # transport",
"import time import signal import socket from Queue import Queue from synapse.scheduler import",
"stopped.\") def dispatch(self): \"\"\"This method actually dispatches to specific transport methods according to",
"def stop_synapse(self): \"\"\"Closes all threads and exits properly. \"\"\" if self.resourcefile: self.resourcefile.done =",
"frame): \"\"\"This method handles SIGINT and SIGTERM signals. \"\"\" self.logger.debug(\"Stopping due to signal",
"self.force_close: try: self.amqpadmin.connect() break except (socket.timeout, IOError) as err: self.logger.error(err) try: self.logger.debug(\"Sleeping %d",
"stopped\") self.force_close = True self.logger.info(\"Successfully stopped.\") def dispatch(self): \"\"\"This method actually dispatches to",
"%d sec\" % retry_timeout) time.sleep(retry_timeout) except KeyboardInterrupt: self.stop_synapse() except KeyboardInterrupt: self.stop_synapse() except SystemExit:",
"self.logger.error(err) try: self.logger.debug(\"Sleeping %d sec\" % retry_timeout) time.sleep(retry_timeout) except KeyboardInterrupt: self.stop_synapse() except KeyboardInterrupt:",
"self.logger.error(\"Transport unknown. [%s]\" % err) self.stop_synapse() sys.exit() def start_amqp(self): \"\"\"Starts all needed threads:",
"KeyboardInterrupt: self.stop_synapse() raise SystemExit self.sched = SynSched() self.controller = Controller(scheduler=self.sched, tasks_queue=self.tasks_queue, publish_queue=self.publish_queue) #",
"sys.exit() def start_amqp(self): \"\"\"Starts all needed threads: scheduler, controller and AMQP transport IOLOOP.",
"None # These queues will be shared between the controller and the #",
"controller and the # transport and are used for incoming tasks and responses",
"the command line to specific transports. It is also responsible for starting threads",
"# Shutdown the scheduler/monitor if self.sched: if self.sched.isAlive(): self.sched.shutdown() self.sched.join() self.logger.debug(\"Scheduler stopped\") self.force_close",
"import signal import socket from Queue import Queue from synapse.scheduler import SynSched from",
"self.sched.isAlive(): self.sched.shutdown() self.sched.join() self.logger.debug(\"Scheduler stopped\") self.force_close = True self.logger.info(\"Successfully stopped.\") def dispatch(self): \"\"\"This",
"self.controller: if self.controller.isAlive(): self.controller.close() self.controller.join() self.logger.debug(\"Controller thread stopped\") # Shutdown the scheduler/monitor if",
"= None self.sched = None self.resourcefile = None # These queues will be",
"method actually dispatches to specific transport methods according to command line parameters. \"\"\"",
"not self.force_close: try: self.amqpadmin.connect() break except (socket.timeout, IOError) as err: self.logger.error(err) try: self.logger.debug(\"Sleeping",
"import config from synapse.controller import Controller from synapse.logger import logger from synapse.synapse_exceptions import",
"self.controller.start() # Start the scheduler self.sched.start() self.amqpsynapse = AmqpSynapse(config.rabbitmq, publish_queue=self.publish_queue, tasks_queue=self.tasks_queue) while not",
"synapse.config import config from synapse.controller import Controller from synapse.logger import logger from synapse.synapse_exceptions",
"self.logger.info(\"Successfully stopped.\") def dispatch(self): \"\"\"This method actually dispatches to specific transport methods according",
"specific transport methods according to command line parameters. \"\"\" self.logger.info('Starting on %s transport'",
"try: self.amqpsynapse.connect() except (AmqpError, IOError) as err: self.logger.error(err) try: self.logger.debug(\"Sleeping %d sec\" %",
"to command line parameters. \"\"\" self.logger.info('Starting on %s transport' % self.transport.capitalize()) transports =",
"self.publish_queue = Queue() self.tasks_queue = Queue() def stop(self, signum, frame): \"\"\"This method handles",
"the controller and the # transport and are used for incoming tasks and",
"# Start the controller self.controller.start() # Start the scheduler self.sched.start() self.amqpsynapse = AmqpSynapse(config.rabbitmq,",
"import socket from Queue import Queue from synapse.scheduler import SynSched from synapse.amqp import",
"Queue() self.tasks_queue = Queue() def stop(self, signum, frame): \"\"\"This method handles SIGINT and",
"self.logger.error(err) try: self.logger.debug(\"Sleeping %d sec\" % retry_timeout) time.sleep(retry_timeout) except KeyboardInterrupt: self.stop_synapse() raise SystemExit",
"actually dispatches to specific transport methods according to command line parameters. \"\"\" self.logger.info('Starting",
"SystemExit self.sched = SynSched() self.controller = Controller(scheduler=self.sched, tasks_queue=self.tasks_queue, publish_queue=self.publish_queue) # Start the controller",
"AmqpSynapse(config.rabbitmq, publish_queue=self.publish_queue, tasks_queue=self.tasks_queue) while not self.force_close: try: self.amqpsynapse.connect() except (AmqpError, IOError) as err:",
"threads: scheduler, controller and AMQP transport IOLOOP. \"\"\" retry_timeout = config.rabbitmq['retry_timeout'] try: self.amqpadmin",
"= SynSched() self.controller = Controller(scheduler=self.sched, tasks_queue=self.tasks_queue, publish_queue=self.publish_queue) # Start the controller self.controller.start() #",
"and SIGTERM. \"\"\" def __init__(self, transport): self.transport = transport self.force_close = False #",
"\"\"\" self.logger.debug(\"Stopping due to signal #%d\" % signum) self.stop_synapse() def stop_synapse(self): \"\"\"Closes all",
"except KeyboardInterrupt: self.stop_synapse() except SystemExit: pass except ResourceException as err: self.logger.error(str(err)) def start_resourcefile(self):",
"pass except ResourceException as err: self.logger.error(str(err)) def start_resourcefile(self): \"\"\"This method handles the --uri",
"from the command line to specific transports. It is also responsible for starting",
"False # Handle signals #signal.signal(signal.SIGINT, self.stop) signal.signal(signal.SIGTERM, self.stop) # Threads instances variables self.controller",
"except (socket.timeout, IOError) as err: self.logger.error(err) try: self.logger.debug(\"Sleeping %d sec\" % retry_timeout) time.sleep(retry_timeout)",
"\"\"\"This method handles the --uri file and --uri http commands. \"\"\" from synapse.resourcefile",
"IOLOOP. \"\"\" retry_timeout = config.rabbitmq['retry_timeout'] try: self.amqpadmin = AmqpAdmin(config.rabbitmq) while not self.force_close: try:",
"% err) self.stop_synapse() sys.exit() def start_amqp(self): \"\"\"Starts all needed threads: scheduler, controller and",
"self.stop) signal.signal(signal.SIGTERM, self.stop) # Threads instances variables self.controller = None self.sched = None",
"shared between the controller and the # transport and are used for incoming",
"as err: self.logger.error(str(err)) def start_resourcefile(self): \"\"\"This method handles the --uri file and --uri",
"# Start the scheduler self.sched.start() self.amqpsynapse = AmqpSynapse(config.rabbitmq, publish_queue=self.publish_queue, tasks_queue=self.tasks_queue) while not self.force_close:",
"not self.force_close: try: self.amqpsynapse.connect() except (AmqpError, IOError) as err: self.logger.error(err) try: self.logger.debug(\"Sleeping %d",
"\"\"\" if self.resourcefile: self.resourcefile.done = True # Close the controller and wait for",
"self.start_resourcefile, 'file': self.start_resourcefile, } try: transports[self.transport]() except (AttributeError, KeyError), err: self.logger.error(\"Transport unknown. [%s]\"",
"while not self.force_close: try: self.amqpsynapse.connect() except (AmqpError, IOError) as err: self.logger.error(err) try: self.logger.debug(\"Sleeping",
"def stop(self, signum, frame): \"\"\"This method handles SIGINT and SIGTERM signals. \"\"\" self.logger.debug(\"Stopping",
"None self.sched = None self.resourcefile = None # These queues will be shared",
"IOError) as err: self.logger.error(err) try: self.logger.debug(\"Sleeping %d sec\" % retry_timeout) time.sleep(retry_timeout) except KeyboardInterrupt:",
"according to command line parameters. \"\"\" self.logger.info('Starting on %s transport' % self.transport.capitalize()) transports",
"threads and exits properly. \"\"\" if self.resourcefile: self.resourcefile.done = True # Close the",
"thread stopped\") # Shutdown the scheduler/monitor if self.sched: if self.sched.isAlive(): self.sched.shutdown() self.sched.join() self.logger.debug(\"Scheduler",
"err: self.logger.error(err) try: self.logger.debug(\"Sleeping %d sec\" % retry_timeout) time.sleep(retry_timeout) except KeyboardInterrupt: self.stop_synapse() raise",
"self.start_resourcefile, } try: transports[self.transport]() except (AttributeError, KeyError), err: self.logger.error(\"Transport unknown. [%s]\" % err)",
"used for incoming tasks and responses self.publish_queue = Queue() self.tasks_queue = Queue() def",
"Queue import Queue from synapse.scheduler import SynSched from synapse.amqp import AmqpSynapse, AmqpAdmin, AmqpError",
"self.sched = None self.resourcefile = None # These queues will be shared between",
"self.sched: if self.sched.isAlive(): self.sched.shutdown() self.sched.join() self.logger.debug(\"Scheduler stopped\") self.force_close = True self.logger.info(\"Successfully stopped.\") def",
"will be shared between the controller and the # transport and are used",
"SIGINT and SIGTERM. \"\"\" def __init__(self, transport): self.transport = transport self.force_close = False",
"\"\"\" from synapse.resourcefile import ResourceFile try: self.resourcefile = ResourceFile(self.transport) self.resourcefile.fetch() except KeyboardInterrupt: self.stop_synapse()",
"self.controller.close() self.controller.join() self.logger.debug(\"Controller thread stopped\") # Shutdown the scheduler/monitor if self.sched: if self.sched.isAlive():",
"retry_timeout = config.rabbitmq['retry_timeout'] try: self.amqpadmin = AmqpAdmin(config.rabbitmq) while not self.force_close: try: self.amqpadmin.connect() break",
"if self.sched.isAlive(): self.sched.shutdown() self.sched.join() self.logger.debug(\"Scheduler stopped\") self.force_close = True self.logger.info(\"Successfully stopped.\") def dispatch(self):",
"import Controller from synapse.logger import logger from synapse.synapse_exceptions import ResourceException @logger class Dispatcher(object):",
"time.sleep(retry_timeout) except KeyboardInterrupt: self.stop_synapse() except KeyboardInterrupt: self.stop_synapse() except SystemExit: pass except ResourceException as",
"the scheduler/monitor if self.sched: if self.sched.isAlive(): self.sched.shutdown() self.sched.join() self.logger.debug(\"Scheduler stopped\") self.force_close = True",
"it to quit if self.controller: if self.controller.isAlive(): self.controller.close() self.controller.join() self.logger.debug(\"Controller thread stopped\") #",
"= { 'amqp': self.start_amqp, 'http': self.start_resourcefile, 'file': self.start_resourcefile, } try: transports[self.transport]() except (AttributeError,",
"err: self.logger.error(\"Transport unknown. [%s]\" % err) self.stop_synapse() sys.exit() def start_amqp(self): \"\"\"Starts all needed",
"import SynSched from synapse.amqp import AmqpSynapse, AmqpAdmin, AmqpError from synapse.config import config from",
"for incoming tasks and responses self.publish_queue = Queue() self.tasks_queue = Queue() def stop(self,",
"quit if self.controller: if self.controller.isAlive(): self.controller.close() self.controller.join() self.logger.debug(\"Controller thread stopped\") # Shutdown the",
"self.stop) # Threads instances variables self.controller = None self.sched = None self.resourcefile =",
"line to specific transports. It is also responsible for starting threads and catching",
"handles the --uri file and --uri http commands. \"\"\" from synapse.resourcefile import ResourceFile",
"(AttributeError, KeyError), err: self.logger.error(\"Transport unknown. [%s]\" % err) self.stop_synapse() sys.exit() def start_amqp(self): \"\"\"Starts",
"threads and catching signals like SIGINT and SIGTERM. \"\"\" def __init__(self, transport): self.transport",
"% signum) self.stop_synapse() def stop_synapse(self): \"\"\"Closes all threads and exits properly. \"\"\" if",
"the controller and wait for it to quit if self.controller: if self.controller.isAlive(): self.controller.close()",
"like SIGINT and SIGTERM. \"\"\" def __init__(self, transport): self.transport = transport self.force_close =",
"= True # Close the controller and wait for it to quit if",
"sec\" % retry_timeout) time.sleep(retry_timeout) except KeyboardInterrupt: self.stop_synapse() except KeyboardInterrupt: self.stop_synapse() except SystemExit: pass",
"Handle signals #signal.signal(signal.SIGINT, self.stop) signal.signal(signal.SIGTERM, self.stop) # Threads instances variables self.controller = None",
"break except (socket.timeout, IOError) as err: self.logger.error(err) try: self.logger.debug(\"Sleeping %d sec\" % retry_timeout)",
"import AmqpSynapse, AmqpAdmin, AmqpError from synapse.config import config from synapse.controller import Controller from",
"transports = { 'amqp': self.start_amqp, 'http': self.start_resourcefile, 'file': self.start_resourcefile, } try: transports[self.transport]() except",
"# transport and are used for incoming tasks and responses self.publish_queue = Queue()",
"signal #%d\" % signum) self.stop_synapse() def stop_synapse(self): \"\"\"Closes all threads and exits properly.",
"to signal #%d\" % signum) self.stop_synapse() def stop_synapse(self): \"\"\"Closes all threads and exits",
"except AmqpError as err: break except KeyboardInterrupt: self.stop_synapse() raise SystemExit self.sched = SynSched()",
"the scheduler self.sched.start() self.amqpsynapse = AmqpSynapse(config.rabbitmq, publish_queue=self.publish_queue, tasks_queue=self.tasks_queue) while not self.force_close: try: self.amqpsynapse.connect()",
"\"\"\"This module dispatches commands incoming from the command line to specific transports. It",
"signum) self.stop_synapse() def stop_synapse(self): \"\"\"Closes all threads and exits properly. \"\"\" if self.resourcefile:",
"signal import socket from Queue import Queue from synapse.scheduler import SynSched from synapse.amqp",
"None self.resourcefile = None # These queues will be shared between the controller",
"\"\"\" def __init__(self, transport): self.transport = transport self.force_close = False # Handle signals",
"from synapse.scheduler import SynSched from synapse.amqp import AmqpSynapse, AmqpAdmin, AmqpError from synapse.config import",
"[%s]\" % err) self.stop_synapse() sys.exit() def start_amqp(self): \"\"\"Starts all needed threads: scheduler, controller",
"stop(self, signum, frame): \"\"\"This method handles SIGINT and SIGTERM signals. \"\"\" self.logger.debug(\"Stopping due",
"= config.rabbitmq['retry_timeout'] try: self.amqpadmin = AmqpAdmin(config.rabbitmq) while not self.force_close: try: self.amqpadmin.connect() break except",
"command line to specific transports. It is also responsible for starting threads and",
"Queue from synapse.scheduler import SynSched from synapse.amqp import AmqpSynapse, AmqpAdmin, AmqpError from synapse.config",
"signum, frame): \"\"\"This method handles SIGINT and SIGTERM signals. \"\"\" self.logger.debug(\"Stopping due to",
"# Threads instances variables self.controller = None self.sched = None self.resourcefile = None",
"self.resourcefile: self.resourcefile.done = True # Close the controller and wait for it to",
"dispatch(self): \"\"\"This method actually dispatches to specific transport methods according to command line",
"# Handle signals #signal.signal(signal.SIGINT, self.stop) signal.signal(signal.SIGTERM, self.stop) # Threads instances variables self.controller =",
"controller and wait for it to quit if self.controller: if self.controller.isAlive(): self.controller.close() self.controller.join()",
"__init__(self, transport): self.transport = transport self.force_close = False # Handle signals #signal.signal(signal.SIGINT, self.stop)",
"if self.resourcefile: self.resourcefile.done = True # Close the controller and wait for it",
"as err: break except KeyboardInterrupt: self.stop_synapse() raise SystemExit self.sched = SynSched() self.controller =",
"transports[self.transport]() except (AttributeError, KeyError), err: self.logger.error(\"Transport unknown. [%s]\" % err) self.stop_synapse() sys.exit() def",
"module dispatches commands incoming from the command line to specific transports. It is",
"err: self.logger.error(str(err)) def start_resourcefile(self): \"\"\"This method handles the --uri file and --uri http",
"%s transport' % self.transport.capitalize()) transports = { 'amqp': self.start_amqp, 'http': self.start_resourcefile, 'file': self.start_resourcefile,",
"@logger class Dispatcher(object): \"\"\"This module dispatches commands incoming from the command line to",
"self.stop_synapse() def stop_synapse(self): \"\"\"Closes all threads and exits properly. \"\"\" if self.resourcefile: self.resourcefile.done",
"starting threads and catching signals like SIGINT and SIGTERM. \"\"\" def __init__(self, transport):",
"from synapse.synapse_exceptions import ResourceException @logger class Dispatcher(object): \"\"\"This module dispatches commands incoming from",
"all threads and exits properly. \"\"\" if self.resourcefile: self.resourcefile.done = True # Close",
"self.controller.isAlive(): self.controller.close() self.controller.join() self.logger.debug(\"Controller thread stopped\") # Shutdown the scheduler/monitor if self.sched: if",
"self.force_close: try: self.amqpsynapse.connect() except (AmqpError, IOError) as err: self.logger.error(err) try: self.logger.debug(\"Sleeping %d sec\"",
"synapse.amqp import AmqpSynapse, AmqpAdmin, AmqpError from synapse.config import config from synapse.controller import Controller",
"transports. It is also responsible for starting threads and catching signals like SIGINT",
"self.amqpsynapse.connect() except (AmqpError, IOError) as err: self.logger.error(err) try: self.logger.debug(\"Sleeping %d sec\" % retry_timeout)",
"raise SystemExit except AmqpError as err: break except KeyboardInterrupt: self.stop_synapse() raise SystemExit self.sched",
"Controller from synapse.logger import logger from synapse.synapse_exceptions import ResourceException @logger class Dispatcher(object): \"\"\"This",
"self.stop_synapse() raise SystemExit self.sched = SynSched() self.controller = Controller(scheduler=self.sched, tasks_queue=self.tasks_queue, publish_queue=self.publish_queue) # Start",
"transport and are used for incoming tasks and responses self.publish_queue = Queue() self.tasks_queue"
] |
[
"%% sns.pairplot(df.loc[df.DeviceId != 3, :], hue=\"DeviceId\", vars=[\"AccMgn_mean\", \"AccMgn_median\"], markers='.') # %% test =",
"# %% print('RandomForestClassifier + SMOTE') accuracies = [] precisions = [] recalls =",
"= True) df = df.loc[(df.DeviceId != 4) & (df.DeviceId != 7), :].reset_index(drop =",
"[1, 2, 3], 'estimator__bootstrap': [True, False] } grid = RandomizedSearchCV(estimator = selector, \\",
"= SMOTETomek().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier estimator =",
"X_device = X.loc[y == device_id, :] X_non_device = X.loc[y != device_id, :] from",
"# %% print('GaussianNB') accuracies = [] precisions = [] recalls = [] fscores",
"pd.DataFrame = pickle.load(open(unlock_data_path, 'rb')) # full_df = full_df.loc[full_df.DeviceId != '1439cbc3ad71ac06'].reset_index(drop = True) #",
"train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.feature_selection import RFE from sklearn.ensemble import",
"RandomOverSampler') accuracies = [] precisions = [] recalls = [] fscores = []",
"import RFE from imblearn.ensemble import BalancedRandomForestClassifier estimator = BalancedRandomForestClassifier(n_estimators = 10, random_state =",
"[2, 3, 4, 5], 'estimator__min_samples_leaf': [1, 2, 3], 'estimator__bootstrap': [True, False] } grid",
"!= '3', :] sns.swarmplot(data = test, x=\"DeviceId\", y=\"RotMgn_median\") # %% test = full_df.loc[:,",
"+ [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(108, 144)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(144, 180)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:,",
"12369) from sklearn.decomposition import PCA pca = PCA(n_components=20).fit(X_train) X_train = pca.transform(X_train) X_test =",
"\"AccMgn_median\"], markers='.') # %% test = df.loc[df.DeviceId != '3', :] sns.swarmplot(data = test,",
"full_df.loc[full_df.DeviceId != 3].reset_index(drop = True) ## Old database # unlock_data_path = storage_service.download_file(last_run.unlock_data_uri) #",
"RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10, random_state = 12369) selector = SelectFromModel(estimator, max_features",
"{round(accuracy, 2)}, precision: {round(precision, 2)}, recall: {round(recall, 2)}') # print(f'{device_id} - Class acc:",
"acc: {round(np.mean(estimator.predict(X_non_device) == -1), 2)}') print(f'Accuracy: {round(np.mean(accuracies), 2)}, precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls),",
"= StandardScaler().fit_transform(X) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X_std, y_device,",
"72)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(72, 108)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(108, 144)) + [216]].groupby('DeviceId').agg([np.mean]))",
"classification_report(y_test, estimator.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score']) print(f'Accuracy: {round(np.mean(accuracies), 2)}, precision: {round(np.mean(precisions), 2)},",
"RandomUnderSampler') accuracies = [] precisions = [] recalls = [] fscores = []",
"as pd import numpy as np import matplotlib.pyplot as plt import seaborn as",
"imblearn.ensemble import BalancedRandomForestClassifier estimator = BalancedRandomForestClassifier(n_estimators = 10, random_state = 12369) selector =",
"2)}, precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('GaussianNB')",
"import RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10, random_state = 12369) selector = RFECV(estimator,",
"= 0.05) selector.fit(X_oversampled, y_oversampled) from sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test, selector.predict(X_test))) report",
"'sqrt', \\ max_depth = 20) selector = RFE(estimator, n_features_to_select = 20, step =",
"train_test_split X_train, X_test, y_train, y_test = train_test_split(X_device, y_device, test_size=0.2) from sklearn.ensemble import IsolationForest",
"full_df = full_df.loc[full_df.DeviceId != 3].reset_index(drop = True) ## Old database # unlock_data_path =",
"= 12369) from sklearn.feature_selection import SelectKBest, f_classif selector = SelectKBest(score_func = f_classif, k=20).fit(X_train,",
"X_test, y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from imblearn.over_sampling import",
"False] } grid = RandomizedSearchCV(estimator = selector, \\ param_distributions = param_grid, \\ n_iter",
"estimator.fit(X_train) tp = np.mean(estimator.predict(X_test) == 1) fn = np.mean(estimator.predict(X_test) == -1) tn =",
"RFE from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10, random_state = 12369)",
"X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state = 12369) from yellowbrick.model_selection import",
"+ SMOTETomek') accuracies = [] precisions = [] recalls = [] fscores =",
"print('RandomForestClassifier - global model') from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test =",
"2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + RFECV') from",
"+ fn) fscore = 2 * recall * precision / (recall + precision)",
"SelectKBest(score_func = mutual_info_classif, k=20).fit(X_train, y_train) X_train = selector.transform(X_train) X_test = selector.transform(X_test) from sklearn.ensemble",
"X_train, X_test, y_train, y_test = train_test_split(X_device, y_device, test_size=0.2) from sklearn.svm import OneClassSVM estimator",
"np.max])) display(full_df.iloc[:, list(range(72, 108)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(108, 144)) + [216]].groupby('DeviceId').agg([np.min, np.max]))",
"X_train, X_test, y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.ensemble",
"precision = tp / (tp + fp) recall = tp / (tp +",
"train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.neighbors import KNeighborsClassifier estimator = KNeighborsClassifier()",
"# %% print('RandomForestClassifier + SelectKBest (f_classif)') accuracies = [] precisions = [] recalls",
"fscore: {round(np.mean(fscores), 2)}') # %% print('BalancedRandomForestClassifier') accuracies = [] precisions = [] recalls",
"= RFECV(estimator, cv = 5, scoring='f1_weighted', step = 0.05) selector.fit(X_train, y_train) selector.show() from",
"%% sns.boxplot(df.DeviceId, df.AccMgn_median) # %% sns.boxplot(df.DeviceId, df.GyrMgn_amax) # %% sns.pairplot(df.loc[df.DeviceId != 3, :],",
"2)}, precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('KNeighborsClassifier')",
"selector = SelectKBest(score_func = mutual_info_classif, k=20).fit(X_train, y_train) X_train = selector.transform(X_train) X_test = selector.transform(X_test)",
"+ SelectKBest (f_classif)') accuracies = [] precisions = [] recalls = [] fscores",
"%% print('RandomForestClassifier + RFECV') from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test =",
"train_test_split(X, y, test_size=0.2, random_state = 12369) from yellowbrick.model_selection import RFECV from sklearn.ensemble import",
"12369) from imblearn.combine import SMOTEENN X_oversampled, y_oversampled = SMOTEENN().fit_resample(X_train, y_train) from sklearn.feature_selection import",
"fp) recall = tp / (tp + fn) fscore = 2 * recall",
"# %% print('BalancedRandomForestClassifier') accuracies = [] precisions = [] recalls = [] fscores",
"12369) selector = SelectFromModel(estimator, max_features = 20) selector.fit(X_train, y_train) from sklearn.metrics import classification_report",
"= RandomUnderSampler().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier estimator =",
"recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('Hyperparameter tuning') for device_id in",
"+ precision) accuracies.append(accuracy if not np.isnan(accuracy) else 0) precisions.append(precision if not np.isnan(precision) else",
"SMOTEENN') accuracies = [] precisions = [] recalls = [] fscores = []",
"fscore: {round(np.mean(fscores), 2)}') # %% print('LOF') accuracies = [] precisions = [] recalls",
"print('RandomForestClassifier + SMOTETomek + parameters') accuracies = [] precisions = [] recalls =",
"== 1), 2)}, non-class acc: {round(np.mean(estimator.predict(X_non_device) == -1), 2)}') print(f'Accuracy: {round(np.mean(accuracies), 2)}, precision:",
"list(range(36)) + list(range(72, 108)) + list(range(108, 144)) + list(range(180, 216)) + [216]].reset_index(drop =",
"2)}, recall: {round(recall, 2)}') # print(f'{device_id} - Class acc: {round(np.mean(estimator.predict(X_device) == 1), 2)},",
"2)}, precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier')",
"'1439cbc3ad71ac06'].reset_index(drop = True) # %% df = full_df.iloc[:, list(range(36)) + list(range(72, 108)) +",
"[None], 'estimator__min_samples_split': [2, 3, 4, 5], 'estimator__min_samples_leaf': [1, 2, 3], 'estimator__bootstrap': [True, False]",
"['auto', 'sqrt', 'log2'], 'estimator__max_depth': [int(x) for x in np.linspace(2, 20, num = 2)]",
"RFE20') accuracies = [] precisions = [] recalls = [] fscores = []",
"# param_grid = { # 'estimator__n_estimators': [10, 50, 100, 200, 500], # 'estimator__max_features':",
"{round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + RandomOverSampler')",
"0) from sklearn.preprocessing import StandardScaler X_std = StandardScaler().fit_transform(X) from sklearn.model_selection import train_test_split X_train,",
"y_train) from sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test))) report = classification_report(y_test, estimator.predict(X_test), output_dict=True) accuracies.append(report['accuracy'])",
"SelectFromModel from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10, random_state = 12369)",
"sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test))) report = classification_report(y_test, estimator.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall'])",
"1) fn = np.mean(estimator.predict(X_test) == -1) tn = np.mean(estimator.predict(X_non_device) == 1) fp =",
"1), 2)}, non-class acc: {round(np.mean(estimator.predict(X_non_device) == -1), 2)}') print(f'Accuracy: {round(np.mean(accuracies), 2)}, precision: {round(np.mean(precisions),",
"2)}') # print(f'{device_id} - Class acc: {round(np.mean(estimator.predict(X_test) == 1), 2)}, non-class acc: {round(np.mean(estimator.predict(X_non_device)",
"= selector.transform(X_train) X_test = selector.transform(X_test) from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators =",
"recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SelectFromModel') accuracies =",
"selector = RFECV(estimator, cv = 5, scoring='f1_weighted', step = 0.05) selector.fit(X_train, y_train) selector.show()",
"sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(random_state = 12369, \\",
"== device_id, :] X_non_device = X.loc[y != device_id, :] from sklearn.model_selection import train_test_split",
"5, scoring='f1_weighted', step = 0.05) selector.fit(X_train, y_train) selector.show() from sklearn.metrics import classification_report print(classification_report(y_test,",
"estimator = RandomForestClassifier(n_estimators = 10, random_state = 12369) selector = RFE(estimator, n_features_to_select =",
"# %% print('IsolationForest') accuracies = [] precisions = [] recalls = [] fscores",
"cv = 3, \\ verbose = 2, \\ random_state = 42, \\ n_jobs",
"sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(random_state = 12369) estimator.fit(X_train, y_train) from sklearn.metrics import",
"X_oversampled, y_oversampled = RandomOverSampler().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier",
"= 12369) from imblearn.combine import SMOTEENN X_oversampled, y_oversampled = SMOTEENN().fit_resample(X_train, y_train) from sklearn.feature_selection",
"{round(precision, 2)}, recall: {round(recall, 2)}') # print(f'{device_id} - Class acc: {round(np.mean(estimator.predict(X_device) == 1),",
"np.isnan(recall) else 0) fscores.append(fscore if not np.isnan(fscore) else 0) print(f'{device_id} - accuracy: {round(accuracy,",
"LinearSVC estimator = LinearSVC(random_state = 12369) estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(classification_report(y_test,",
"= f_classif, k=20).fit(X_train, y_train) X_train = selector.transform(X_train) X_test = selector.transform(X_test) from sklearn.ensemble import",
":], hue=\"DeviceId\", vars=[\"AccMgn_mean\", \"AccMgn_median\"], markers='.') # %% test = df.loc[df.DeviceId != '3', :]",
"= SelectKBest(score_func = mutual_info_classif, k=20).fit(X_train, y_train) X_train = selector.transform(X_train) X_test = selector.transform(X_test) from",
"display(full_df.iloc[:, list(range(72, 108)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(108, 144)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:,",
"PCA(n_components=20).fit(X_train) X_train = pca.transform(X_train) X_test = pca.transform(X_test) from sklearn.ensemble import RandomForestClassifier estimator =",
"[216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(36, 72)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(72, 108)) + [216]].groupby('DeviceId').agg([np.min,",
"20) selector = RFE(estimator, n_features_to_select = 20, step = 0.05) selector.fit(X_oversampled, y_oversampled) from",
"import classification_report print(classification_report(y_test, estimator.predict(X_test))) report = classification_report(y_test, estimator.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score'])",
"print(f'Accuracy: {round(np.mean(accuracies), 2)}, precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') #",
"import train_test_split X_train, X_test, y_train, y_test = train_test_split(X_device, y_device, test_size=0.2) from sklearn.svm import",
"10, random_state = 12369) selector = SelectFromModel(estimator, max_features = 20) selector.fit(X_train, y_train) from",
"X_train, X_test, y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from imblearn.under_sampling",
"from imblearn.ensemble import BalancedRandomForestClassifier estimator = BalancedRandomForestClassifier(n_estimators = 10, random_state = 12369) selector",
"= IsolationForest(n_estimators = 10) estimator.fit(X_train) tp = np.mean(estimator.predict(X_test) == 1) fn = np.mean(estimator.predict(X_test)",
"y_device, test_size=0.2, random_state = 12369) from imblearn.under_sampling import RandomUnderSampler X_oversampled, y_oversampled = RandomUnderSampler().fit_resample(X_train,",
"random_state = 12369) from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier estimator =",
"2, \\ random_state = 42, \\ n_jobs = -1) grid.fit(X_oversampled, y_oversampled) print(grid.best_params_) #",
"{device_id}:') print(classification_report(y_test, estimator.predict(X_test))) report = classification_report(y_test, estimator.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score']) print(f'Accuracy:",
"2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + RandomUnderSampler') accuracies = [] precisions",
"(tp + tn) / (tp + tn + fn + fp) precision =",
"profile_service = Services.profile_service() storage_service = Services.storage_service() last_run = profile_service.get_last_profile_creation_run() ## New database full_df:",
"+ [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(144, 180)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(180, 216)) + [216]].groupby('DeviceId').agg([np.mean])) #",
"database full_df: pd.DataFrame = pickle.load(last_run.unlock_data.open('rb')) # full_df = full_df.loc[full_df.DeviceId != 3].reset_index(drop = True)",
"= RFE(estimator, n_features_to_select = 20, step = 0.05) selector.fit(X_train, y_train) from sklearn.metrics import",
"print(classification_report(y_test, selector.predict(X_test))) report = classification_report(y_test, selector.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score']) print(f'Accuracy: {round(np.mean(accuracies),",
"= 12369) from sklearn.feature_selection import SelectKBest, mutual_info_classif selector = SelectKBest(score_func = mutual_info_classif, k=20).fit(X_train,",
"2)}') # %% print('RandomForestClassifier + PCA') accuracies = [] precisions = [] recalls",
"fscore: {round(np.mean(fscores), 2)}') # %% print('IsolationForest') accuracies = [] precisions = [] recalls",
"X_train, X_test, y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from imblearn.combine",
"'MAKDataHub.settings' import django django.setup() # %% import math import pickle import pandas as",
"y, test_size=0.2, random_state = 12369) from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(random_state =",
"180)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(180, 216)) + [216]].groupby('DeviceId').agg([np.mean])) # %% sns.boxplot(df.DeviceId, df.AccMgn_mean) #",
"= train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.naive_bayes import GaussianNB estimator =",
"0.05) # from sklearn.model_selection import GridSearchCV # param_grid = { # 'estimator__n_estimators': [10,",
"* precision / (recall + precision) accuracies.append(accuracy if not np.isnan(accuracy) else 0) precisions.append(precision",
"+ list(range(180, 216)) + [216]].reset_index(drop = True) df = df.loc[(df.DeviceId != 4) &",
"{round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier - global model') from sklearn.model_selection",
"True) X, y = df.iloc[:, 0:-1], df.iloc[:, -1] #%% full_df.shape # %% display(full_df.iloc[:,",
"recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score']) print(f'Accuracy: {round(np.mean(accuracies), 2)}, precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores),",
"from sklearn.metrics import classification_report print(classification_report(y_test, selector.predict(X_test))) # %% print('RandomForestClassifier + RFE20') accuracies =",
"recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SelectKBest (f_classif)') accuracies",
"2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('LinearSVC') accuracies = [] precisions = []",
"recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('LOF') accuracies = [] precisions",
"+ list(range(108, 144)) + list(range(180, 216)) + [216]].reset_index(drop = True) df = df.loc[(df.DeviceId",
"'auto') estimator.fit(X_train) tp = np.mean(estimator.predict(X_test) == 1) fn = np.mean(estimator.predict(X_test) == -1) tn",
"test_size=0.2, random_state = 12369) from sklearn.decomposition import PCA pca = PCA(n_components=20).fit(X_train) X_train =",
"+ SMOTEENN') accuracies = [] precisions = [] recalls = [] fscores =",
"recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('IsolationForest') accuracies = [] precisions",
"%% print('RandomForestClassifier + SMOTETomek') accuracies = [] precisions = [] recalls = []",
"- Class acc: {round(np.mean(estimator.predict(X_test) == 1), 2)}, non-class acc: {round(np.mean(estimator.predict(X_non_device) == -1), 2)}')",
"+ [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(36, 72)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(72, 108)) +",
"100, 200, 500], # 'estimator__max_features': ['auto', 'sqrt', 'log2'], # 'estimator__max_depth': [4, 5, 6,",
"%% print('RandomForestClassifier + RandomOverSampler') accuracies = [] precisions = [] recalls = []",
"y_train) from sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test, selector.estimator_.predict(X_test))) report = classification_report(y_test, selector.estimator_.predict(X_test),",
"{round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('GaussianNB') accuracies = [] precisions =",
"{round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SMOTETomek')",
"train_test_split(X, y, test_size=0.2, random_state = 12369) from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(random_state",
"RandomForestClassifier(n_estimators = 10, random_state = 12369) selector = SelectFromModel(estimator, max_features = 20) selector.fit(X_train,",
"fn + fp) precision = tp / (tp + fp) recall = tp",
"from sklearn.feature_selection import SelectKBest, mutual_info_classif selector = SelectKBest(score_func = mutual_info_classif, k=20).fit(X_train, y_train) X_train",
"X_test, y_train, y_test = train_test_split(X_device, y_device, test_size=0.2) from sklearn.ensemble import IsolationForest estimator =",
"imblearn.over_sampling import SMOTE X_oversampled, y_oversampled = SMOTE().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from",
"= test, x=\"DeviceId\", y=\"RotMgn_median\") # %% test = full_df.loc[:, :] sns.boxplot(data = test,",
"y_device = np.where(y == device_id, 1, 0) from sklearn.model_selection import train_test_split X_train, X_test,",
"20, step = 0.05) # from sklearn.model_selection import GridSearchCV # param_grid = {",
"LocalOutlierFactor estimator = LocalOutlierFactor(n_neighbors = 10, novelty = True, contamination = 'auto') estimator.fit(X_train)",
"test_size=0.2, random_state = 12369) from yellowbrick.model_selection import RFECV from sklearn.ensemble import RandomForestClassifier estimator",
"import IsolationForest estimator = IsolationForest(n_estimators = 10) estimator.fit(X_train) tp = np.mean(estimator.predict(X_test) == 1)",
"imblearn.under_sampling import RandomUnderSampler X_oversampled, y_oversampled = RandomUnderSampler().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from",
"verbose = 2, \\ random_state = 42, \\ n_jobs = -1) grid.fit(X_oversampled, y_oversampled)",
"'log2'], 'estimator__max_depth': [int(x) for x in np.linspace(2, 20, num = 2)] + [None],",
"# %% display(full_df.iloc[:, list(range(36)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(36, 72)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(72,",
"tn = np.mean(estimator.predict(X_non_device) == 1) fp = np.mean(estimator.predict(X_non_device) == 1) accuracy = (tp",
"# %% print('Hyperparameter tuning') for device_id in y.unique(): y_device = np.where(y == device_id,",
"2)}') # %% print('LOF') accuracies = [] precisions = [] recalls = []",
"500], # 'estimator__max_features': ['auto', 'sqrt', 'log2'], # 'estimator__max_depth': [4, 5, 6, 7, 8],",
"test_size=0.2, random_state = 12369) from sklearn.feature_selection import RFE from imblearn.ensemble import BalancedRandomForestClassifier estimator",
"random_state = 12369) selector = SelectFromModel(estimator, max_features = 20) selector.fit(X_train, y_train) from sklearn.metrics",
"y_device, test_size=0.2, random_state = 12369) from imblearn.combine import SMOTETomek X_oversampled, y_oversampled = SMOTETomek().fit_resample(X_train,",
"display(full_df.iloc[:, list(range(144, 180)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(180, 216)) + [216]].groupby('DeviceId').agg([np.mean])) # %% sns.boxplot(df.DeviceId,",
"2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SMOTE') accuracies",
"X_train, X_test, y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.svm",
"RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10, random_state = 12369) selector = RFECV(estimator, cv",
"= BalancedRandomForestClassifier(n_estimators = 10, random_state = 12369) selector = RFE(estimator, n_features_to_select = 20,",
"\\ param_distributions = param_grid, \\ n_iter = 100, \\ cv = 3, \\",
"test_size=0.2, random_state = 12369) from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier estimator",
"list(range(180, 216)) + [216]].groupby('DeviceId').agg([np.min, np.max])) # %% display(full_df.iloc[:, list(range(36)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(36,",
"y_train) X_train = selector.transform(X_train) X_test = selector.transform(X_test) from sklearn.ensemble import RandomForestClassifier estimator =",
"print('RandomForestClassifier + RFE20') accuracies = [] precisions = [] recalls = [] fscores",
"X_train, X_test, y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.decomposition",
"y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.decomposition import PCA pca",
"2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('GaussianNB') accuracies = [] precisions = []",
"= 12369) from sklearn.feature_selection import RFE from imblearn.ensemble import BalancedRandomForestClassifier estimator = BalancedRandomForestClassifier(n_estimators",
"x=\"DeviceId\", y=\"GrvMgn_amax\") # %% print('OneClassSVM') accuracies = [] precisions = [] recalls =",
"-1), 2)}') print(f'Accuracy: {round(np.mean(accuracies), 2)}, precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores),",
"+ [216]].groupby('DeviceId').agg([np.min, np.max])) # %% display(full_df.iloc[:, list(range(36)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(36, 72)) +",
"y_test = train_test_split(X_device, y_device, test_size=0.2) from sklearn.ensemble import IsolationForest estimator = IsolationForest(n_estimators =",
"{round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier - global model') from sklearn.model_selection import train_test_split X_train,",
"y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from imblearn.combine import SMOTETomek X_oversampled,",
"50, 100, 200, 500], # 'estimator__max_features': ['auto', 'sqrt', 'log2'], # 'estimator__max_depth': [4, 5,",
"= 10, random_state = 12369) selector = SelectFromModel(estimator, max_features = 20) selector.fit(X_train, y_train)",
"recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier - global model') from",
"y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.ensemble import RandomForestClassifier",
"precisions = [] recalls = [] fscores = [] for device_id in y.unique():",
"1) fp = np.mean(estimator.predict(X_non_device) == 1) accuracy = (tp + tn) / (tp",
"test_size=0.2, random_state = 12369) from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(random_state = 12369)",
"y_train) from sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test, estimator.predict(X_test))) report = classification_report(y_test, estimator.predict(X_test),",
"100], 'estimator__max_features': ['auto', 'sqrt', 'log2'], 'estimator__max_depth': [int(x) for x in np.linspace(2, 20, num",
"+ [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(72, 108)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(108, 144)) +",
"2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SelectKBest (f_classif)') accuracies = []",
"= train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.feature_selection import SelectKBest, f_classif selector",
"{round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier') accuracies = [] precisions = [] recalls =",
"fscore: {round(np.mean(fscores), 2)}') # %% print('GaussianNB') accuracies = [] precisions = [] recalls",
"selector.fit(X_train, y_train) from sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test, selector.estimator_.predict(X_test))) report = classification_report(y_test,",
"12369) from imblearn.over_sampling import SMOTE X_oversampled, y_oversampled = SMOTE().fit_resample(X_train, y_train) from sklearn.feature_selection import",
"report = classification_report(y_test, selector.estimator_.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score']) print(f'Accuracy: {round(np.mean(accuracies), 2)}, precision:",
"vars=[\"AccMgn_mean\", \"AccMgn_median\"], markers='.') # %% test = df.loc[df.DeviceId != '3', :] sns.swarmplot(data =",
"import LinearSVC estimator = LinearSVC(random_state = 12369) estimator.fit(X_train, y_train) from sklearn.metrics import classification_report",
"as sns from MAKDataHub.services import Services profile_service = Services.profile_service() storage_service = Services.storage_service() last_run",
"recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('GaussianNB') accuracies = [] precisions",
"= full_df.loc[full_df.DeviceId != '1439cbc3ad71ac06'].reset_index(drop = True) # %% df = full_df.iloc[:, list(range(36)) +",
"precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('GaussianNB') accuracies",
"as np import matplotlib.pyplot as plt import seaborn as sns from MAKDataHub.services import",
"2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('KNeighborsClassifier') accuracies = [] precisions = []",
"RFE from imblearn.ensemble import BalancedRandomForestClassifier estimator = BalancedRandomForestClassifier(n_estimators = 10, random_state = 12369)",
"RFE(estimator, n_features_to_select = 20, step = 0.05) selector.fit(X_train, y_train) from sklearn.metrics import classification_report",
"for device_id in y.unique(): y_device = np.where(y == device_id, 1, 0) from sklearn.preprocessing",
"2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + RandomOverSampler') accuracies = [] precisions",
"test_size=0.2, random_state = 12369) from imblearn.under_sampling import RandomUnderSampler X_oversampled, y_oversampled = RandomUnderSampler().fit_resample(X_train, y_train)",
"\\ random_state = 42, \\ n_jobs = -1) grid.fit(X_oversampled, y_oversampled) print(grid.best_params_) # %%",
"y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.feature_selection import SelectKBest, mutual_info_classif",
"{round(recall, 2)}') # print(f'{device_id} - Class acc: {round(np.mean(estimator.predict(X_test) == 1), 2)}, non-class acc:",
"= np.where(y == device_id, 1, 0) from sklearn.model_selection import train_test_split X_train, X_test, y_train,",
"2, 3], 'estimator__bootstrap': [True, False] } grid = RandomizedSearchCV(estimator = selector, \\ param_distributions",
"SMOTETomek + parameters') accuracies = [] precisions = [] recalls = [] fscores",
"= pca.transform(X_test) from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10, random_state =",
"= RandomForestClassifier(n_estimators = 10, random_state = 12369) estimator.fit(X_train, y_train) from sklearn.metrics import classification_report",
"X_train = pca.transform(X_train) X_test = pca.transform(X_test) from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators",
"RFE(estimator, n_features_to_select = 20, step = 0.05) # from sklearn.model_selection import GridSearchCV #",
":].reset_index(drop = True) X, y = df.iloc[:, 0:-1], df.iloc[:, -1] #%% full_df.shape #",
"tuning') for device_id in y.unique(): y_device = np.where(y == device_id, 1, 0) from",
"# %% sns.boxplot(df.DeviceId, df.AccMgn_mean) # %% sns.boxplot(df.DeviceId, df.AccMgn_median) # %% sns.boxplot(df.DeviceId, df.GyrMgn_amax) #",
"+ [216]].groupby('DeviceId').agg([np.mean])) # %% sns.boxplot(df.DeviceId, df.AccMgn_mean) # %% sns.boxplot(df.DeviceId, df.AccMgn_median) # %% sns.boxplot(df.DeviceId,",
"print(f'Device {device_id}:') print(classification_report(y_test, selector.predict(X_test))) report = classification_report(y_test, selector.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score'])",
"{round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + RFECV') from sklearn.model_selection import",
"from imblearn.under_sampling import RandomUnderSampler X_oversampled, y_oversampled = RandomUnderSampler().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE",
"report = classification_report(y_test, estimator.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score']) print(f'Accuracy: {round(np.mean(accuracies), 2)}, precision:",
"\\ cv = 3, \\ verbose = 2, \\ random_state = 42, \\",
"= LocalOutlierFactor(n_neighbors = 10, novelty = True, contamination = 'auto') estimator.fit(X_train) tp =",
"= SelectKBest(score_func = f_classif, k=20).fit(X_train, y_train) X_train = selector.transform(X_train) X_test = selector.transform(X_test) from",
"sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test, selector.estimator_.predict(X_test))) report = classification_report(y_test, selector.estimator_.predict(X_test), output_dict=True) accuracies.append(report['accuracy'])",
"## Old database # unlock_data_path = storage_service.download_file(last_run.unlock_data_uri) # full_df: pd.DataFrame = pickle.load(open(unlock_data_path, 'rb'))",
"+ SMOTETomek + parameters') accuracies = [] precisions = [] recalls = []",
"KNeighborsClassifier estimator = KNeighborsClassifier() estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test))) report",
"from sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test))) report = classification_report(y_test, estimator.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision'])",
"print('RandomForestClassifier + SelectKBest (f_classif)') accuracies = [] precisions = [] recalls = []",
"else 0) fscores.append(fscore if not np.isnan(fscore) else 0) print(f'{device_id} - accuracy: {round(accuracy, 2)},",
"import RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10, random_state = 12369) selector = SelectFromModel(estimator,",
"import seaborn as sns from MAKDataHub.services import Services profile_service = Services.profile_service() storage_service =",
"os.chdir(\"../../..\") os.environ['DJANGO_SETTINGS_MODULE'] = 'MAKDataHub.settings' import django django.setup() # %% import math import pickle",
"X_train, X_test, y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.neighbors",
"from sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test, estimator.predict(X_test))) report = classification_report(y_test, estimator.predict(X_test), output_dict=True)",
"2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SMOTETomek') accuracies = [] precisions",
"= 12369) estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test))) report = classification_report(y_test,",
"y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from imblearn.over_sampling import RandomOverSampler X_oversampled,",
"= 10) estimator.fit(X_train) tp = np.mean(estimator.predict(X_test) == 1) fn = np.mean(estimator.predict(X_test) == -1)",
"# %% print('LOF') accuracies = [] precisions = [] recalls = [] fscores",
"precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('LinearSVC') accuracies",
"X_test, y_train, y_test = train_test_split(X_std, y_device, test_size=0.2, random_state = 12369) from sklearn.ensemble import",
"tp / (tp + fp) recall = tp / (tp + fn) fscore",
"classification_report print(f'Device {device_id}:') print(classification_report(y_test, selector.predict(X_test))) report = classification_report(y_test, selector.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall'])",
"import LocalOutlierFactor estimator = LocalOutlierFactor(n_neighbors = 10, novelty = True, contamination = 'auto')",
"random_state = 12369) from yellowbrick.model_selection import RFECV from sklearn.ensemble import RandomForestClassifier estimator =",
"y_device, test_size=0.2, random_state = 12369) from sklearn.feature_selection import RFE from imblearn.ensemble import BalancedRandomForestClassifier",
"np.isnan(accuracy) else 0) precisions.append(precision if not np.isnan(precision) else 0) recalls.append(recall if not np.isnan(recall)",
"SMOTEENN X_oversampled, y_oversampled = SMOTEENN().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble import",
"[216]].groupby('DeviceId').agg([np.min, np.max])) # %% display(full_df.iloc[:, list(range(36)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(36, 72)) + [216]].groupby('DeviceId').agg([np.mean]))",
"random_state = 12369) from imblearn.over_sampling import SMOTE X_oversampled, y_oversampled = SMOTE().fit_resample(X_train, y_train) from",
"2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('LOF') accuracies = []",
"2)}') # %% print('IsolationForest') accuracies = [] precisions = [] recalls = []",
"'log2'], # 'estimator__max_depth': [4, 5, 6, 7, 8], # 'estimator__criterion': ['gini', 'entropy'] #",
"'estimator__bootstrap': [True, False] } grid = RandomizedSearchCV(estimator = selector, \\ param_distributions = param_grid,",
"= full_df.loc[:, :] sns.boxplot(data = test, x=\"DeviceId\", y=\"GrvMgn_amax\") # %% print('OneClassSVM') accuracies =",
"list(range(36)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(36, 72)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(72, 108))",
"recalls = [] fscores = [] for device_id in y.unique(): y_device = y[y",
"+ SelectKBest (mutual_info_classif)') accuracies = [] precisions = [] recalls = [] fscores",
"print('RandomForestClassifier + SMOTE') accuracies = [] precisions = [] recalls = [] fscores",
"random_state = 12369) from imblearn.under_sampling import RandomUnderSampler X_oversampled, y_oversampled = RandomUnderSampler().fit_resample(X_train, y_train) from",
"test_size=0.2) from sklearn.svm import OneClassSVM estimator = OneClassSVM(random_state = 12369) estimator.fit_predict(X_train) tp =",
"(recall + precision) accuracies.append(accuracy if not np.isnan(accuracy) else 0) precisions.append(precision if not np.isnan(precision)",
"{round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('Hyperparameter tuning') for",
"10, random_state = 12369) estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test,",
"df.loc[df.DeviceId != '3', :] sns.swarmplot(data = test, x=\"DeviceId\", y=\"RotMgn_median\") # %% test =",
"sns.swarmplot(data = test, x=\"DeviceId\", y=\"RotMgn_median\") # %% test = full_df.loc[:, :] sns.boxplot(data =",
"{round(np.mean(estimator.predict(X_non_device) == -1), 2)}') print(f'Accuracy: {round(np.mean(accuracies), 2)}, precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)},",
"2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier - global model') from sklearn.model_selection import",
"= train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.feature_selection import RFE from imblearn.ensemble",
"display(full_df.iloc[:, list(range(180, 216)) + [216]].groupby('DeviceId').agg([np.mean])) # %% sns.boxplot(df.DeviceId, df.AccMgn_mean) # %% sns.boxplot(df.DeviceId, df.AccMgn_median)",
"from sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test))) # %% print('RandomForestClassifier - standardized') accuracies =",
"max_features = 20) selector.fit(X_train, y_train) from sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test, selector.estimator_.predict(X_test)))",
"12369) from imblearn.over_sampling import RandomOverSampler X_oversampled, y_oversampled = RandomOverSampler().fit_resample(X_train, y_train) from sklearn.feature_selection import",
"from imblearn.over_sampling import RandomOverSampler X_oversampled, y_oversampled = RandomOverSampler().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE",
"import RandomForestClassifier estimator = RandomForestClassifier(random_state = 12369) estimator.fit(X_train, y_train) from sklearn.metrics import classification_report",
"param_distributions = param_grid, \\ n_iter = 100, \\ cv = 3, \\ verbose",
"216)) + [216]].reset_index(drop = True) df = df.loc[(df.DeviceId != 4) & (df.DeviceId !=",
"sns from MAKDataHub.services import Services profile_service = Services.profile_service() storage_service = Services.storage_service() last_run =",
"= 12369) from sklearn.svm import LinearSVC estimator = LinearSVC(random_state = 12369) estimator.fit(X_train, y_train)",
"np.mean(estimator.predict(X_test) == -1) tn = np.mean(estimator.predict(X_non_device) == 1) fp = np.mean(estimator.predict(X_non_device) == 1)",
"= train_test_split(X_device, y_device, test_size=0.2) from sklearn.ensemble import IsolationForest estimator = IsolationForest(n_estimators = 10)",
"fscores = [] for device_id in y.unique(): y_device = y[y == device_id] X_device",
"sklearn.neighbors import KNeighborsClassifier estimator = KNeighborsClassifier() estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(classification_report(y_test,",
"import SMOTETomek X_oversampled, y_oversampled = SMOTETomek().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble",
"{round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SelectKBest (f_classif)') accuracies = [] precisions =",
"random_state = 12369) from sklearn.naive_bayes import GaussianNB estimator = GaussianNB() estimator.fit(X_train, y_train) from",
"= 2, \\ random_state = 42, \\ n_jobs = -1) grid.fit(X_oversampled, y_oversampled) print(grid.best_params_)",
"if not np.isnan(precision) else 0) recalls.append(recall if not np.isnan(recall) else 0) fscores.append(fscore if",
"True, contamination = 'auto') estimator.fit(X_train) tp = np.mean(estimator.predict(X_test) == 1) fn = np.mean(estimator.predict(X_test)",
"= train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.svm import LinearSVC estimator =",
"2)}, precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier",
"= 20) selector = RFE(estimator, n_features_to_select = 20, step = 0.05) # from",
"%% print('RandomForestClassifier + SelectFromModel') accuracies = [] precisions = [] recalls = []",
"RandomForestClassifier(random_state = 12369, \\ n_estimators = 50, min_samples_leaf = 1, \\ min_samples_split =",
"/ (tp + fn) fscore = 2 * recall * precision / (recall",
"from sklearn.model_selection import GridSearchCV # param_grid = { # 'estimator__n_estimators': [10, 50, 100,",
"import classification_report print(f'Device {device_id}:') print(classification_report(y_test, selector.predict(X_test))) report = classification_report(y_test, selector.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision'])",
"## New database full_df: pd.DataFrame = pickle.load(last_run.unlock_data.open('rb')) # full_df = full_df.loc[full_df.DeviceId != 3].reset_index(drop",
"2)}') # %% print('RandomForestClassifier + RFECV') from sklearn.model_selection import train_test_split X_train, X_test, y_train,",
"import RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10, random_state = 12369) selector = RFE(estimator,",
"2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + PCA') accuracies = [] precisions",
"# %% print('RandomForestClassifier + RandomUnderSampler') accuracies = [] precisions = [] recalls =",
"estimator = RandomForestClassifier(n_estimators = 10, random_state = 12369) estimator.fit(X_train, y_train) from sklearn.metrics import",
"12369) from sklearn.feature_selection import SelectFromModel from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators =",
"'estimator__min_samples_split': [2, 3, 4, 5], 'estimator__min_samples_leaf': [1, 2, 3], 'estimator__bootstrap': [True, False] }",
"train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.feature_selection import SelectKBest, mutual_info_classif selector =",
"y_test = train_test_split(X_device, y_device, test_size=0.2) from sklearn.svm import OneClassSVM estimator = OneClassSVM(random_state =",
"= RandomForestClassifier(random_state = 12369) estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test))) #",
"else 0) precisions.append(precision if not np.isnan(precision) else 0) recalls.append(recall if not np.isnan(recall) else",
"df.AccMgn_mean) # %% sns.boxplot(df.DeviceId, df.AccMgn_median) # %% sns.boxplot(df.DeviceId, df.GyrMgn_amax) # %% sns.pairplot(df.loc[df.DeviceId !=",
"+ RFE20') accuracies = [] precisions = [] recalls = [] fscores =",
"import Services profile_service = Services.profile_service() storage_service = Services.storage_service() last_run = profile_service.get_last_profile_creation_run() ## New",
"- standardized') accuracies = [] precisions = [] recalls = [] fscores =",
"fscores.append(report['1']['f1-score']) print(f'Accuracy: {round(np.mean(accuracies), 2)}, precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}')",
"os import sys # os.chdir(\"../../..\") os.environ['DJANGO_SETTINGS_MODULE'] = 'MAKDataHub.settings' import django django.setup() # %%",
"df = df.loc[(df.DeviceId != 4) & (df.DeviceId != 7), :].reset_index(drop = True) X,",
"classification_report print(classification_report(y_test, estimator.predict(X_test))) # %% print('RandomForestClassifier - standardized') accuracies = [] precisions =",
"+ parameters') accuracies = [] precisions = [] recalls = [] fscores =",
"2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SMOTETomek') accuracies",
"4) & (df.DeviceId != 7), :].reset_index(drop = True) X, y = df.iloc[:, 0:-1],",
"df.AccMgn_median) # %% sns.boxplot(df.DeviceId, df.GyrMgn_amax) # %% sns.pairplot(df.loc[df.DeviceId != 3, :], hue=\"DeviceId\", vars=[\"AccMgn_mean\",",
"[int(x) for x in np.linspace(2, 20, num = 2)] + [None], 'estimator__min_samples_split': [2,",
"1, 0) from sklearn.preprocessing import StandardScaler X_std = StandardScaler().fit_transform(X) from sklearn.model_selection import train_test_split",
"non-class acc: {round(np.mean(estimator.predict(X_non_device) == -1), 2)}') print(f'Accuracy: {round(np.mean(accuracies), 2)}, precision: {round(np.mean(precisions), 2)}, recall:",
"display(full_df.iloc[:, list(range(180, 216)) + [216]].groupby('DeviceId').agg([np.min, np.max])) # %% display(full_df.iloc[:, list(range(36)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:,",
"sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10, random_state",
"# %% test = df.loc[df.DeviceId != '3', :] sns.swarmplot(data = test, x=\"DeviceId\", y=\"RotMgn_median\")",
"144)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(144, 180)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(180, 216)) + [216]].groupby('DeviceId').agg([np.mean]))",
"OneClassSVM estimator = OneClassSVM(random_state = 12369) estimator.fit_predict(X_train) tp = np.mean(estimator.predict(X_test) == 1) fn",
"'estimator__max_features': ['auto', 'sqrt', 'log2'], # 'estimator__max_depth': [4, 5, 6, 7, 8], # 'estimator__criterion':",
"recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + RandomUnderSampler') accuracies =",
"= True) X, y = df.iloc[:, 0:-1], df.iloc[:, -1] #%% full_df.shape # %%",
"'estimator__max_features': ['auto', 'sqrt', 'log2'], 'estimator__max_depth': [int(x) for x in np.linspace(2, 20, num =",
"database # unlock_data_path = storage_service.download_file(last_run.unlock_data_uri) # full_df: pd.DataFrame = pickle.load(open(unlock_data_path, 'rb')) # full_df",
"X_oversampled, y_oversampled = SMOTETomek().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier",
"2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier') accuracies = [] precisions = []",
"RandomForestClassifier(random_state = 12369) estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test))) # %%",
"50, min_samples_leaf = 1, \\ min_samples_split = 2, \\ bootstrap = False, \\",
"sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X_device, y_device, test_size=0.2) from sklearn.svm",
"estimator.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score']) print(f'Accuracy: {round(np.mean(accuracies), 2)}, precision: {round(np.mean(precisions), 2)}, recall:",
":] sns.boxplot(data = test, x=\"DeviceId\", y=\"GrvMgn_amax\") # %% print('OneClassSVM') accuracies = [] precisions",
"yellowbrick.model_selection import RFECV from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10, random_state",
"test_size=0.2, random_state = 12369) from imblearn.over_sampling import RandomOverSampler X_oversampled, y_oversampled = RandomOverSampler().fit_resample(X_train, y_train)",
"+ RFECV') from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y,",
"!= 7), :].reset_index(drop = True) X, y = df.iloc[:, 0:-1], df.iloc[:, -1] #%%",
"X_test, y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.naive_bayes import",
"= RandomForestClassifier(random_state = 12369) estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test))) report",
"= 12369) selector = RFECV(estimator, cv = 5, scoring='f1_weighted', step = 0.05) selector.fit(X_train,",
"KNeighborsClassifier() estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test))) report = classification_report(y_test, estimator.predict(X_test),",
"Class acc: {round(np.mean(estimator.predict(X_device) == 1), 2)}, non-class acc: {round(np.mean(estimator.predict(X_non_device) == -1), 2)}') print(f'Accuracy:",
"= mutual_info_classif, k=20).fit(X_train, y_train) X_train = selector.transform(X_train) X_test = selector.transform(X_test) from sklearn.ensemble import",
"2)}') # %% print('RandomForestClassifier + SMOTETomek') accuracies = [] precisions = [] recalls",
"2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + RFECV') from sklearn.model_selection import train_test_split",
"True) ## Old database # unlock_data_path = storage_service.download_file(last_run.unlock_data_uri) # full_df: pd.DataFrame = pickle.load(open(unlock_data_path,",
"fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SelectKBest (mutual_info_classif)') accuracies = [] precisions",
"2)}') # %% print('LinearSVC') accuracies = [] precisions = [] recalls = []",
"selector = SelectFromModel(estimator, max_features = 20) selector.fit(X_train, y_train) from sklearn.metrics import classification_report print(f'Device",
"X_test, y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.decomposition import",
"SMOTE X_oversampled, y_oversampled = SMOTE().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble import",
"device_id, :] X_non_device = X.loc[y != device_id, :] from sklearn.model_selection import train_test_split X_train,",
"Class acc: {round(np.mean(estimator.predict(X_test) == 1), 2)}, non-class acc: {round(np.mean(estimator.predict(X_non_device) == -1), 2)}') print(f'Accuracy:",
"12369) from yellowbrick.model_selection import RFECV from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators =",
"50, 100], 'estimator__max_features': ['auto', 'sqrt', 'log2'], 'estimator__max_depth': [int(x) for x in np.linspace(2, 20,",
"selector.estimator_.predict(X_test))) report = classification_report(y_test, selector.estimator_.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score']) print(f'Accuracy: {round(np.mean(accuracies), 2)},",
"in np.linspace(2, 20, num = 2)] + [None], 'estimator__min_samples_split': [2, 3, 4, 5],",
"sklearn.feature_selection import SelectFromModel from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10, random_state",
"cv = 5, scoring='f1_weighted', step = 0.05) selector.fit(X_train, y_train) selector.show() from sklearn.metrics import",
"= 12369) from imblearn.over_sampling import RandomOverSampler X_oversampled, y_oversampled = RandomOverSampler().fit_resample(X_train, y_train) from sklearn.feature_selection",
"min_samples_split = 2, \\ bootstrap = False, \\ max_features = 'sqrt', \\ max_depth",
"step = 0.05) selector.fit(X_train, y_train) from sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test, selector.predict(X_test)))",
"sns.boxplot(data = test, x=\"DeviceId\", y=\"GrvMgn_amax\") # %% print('OneClassSVM') accuracies = [] precisions =",
"selector.predict(X_test))) report = classification_report(y_test, selector.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score']) print(f'Accuracy: {round(np.mean(accuracies), 2)},",
"2)}') # %% print('RandomForestClassifier') accuracies = [] precisions = [] recalls = []",
"= RandomForestClassifier(n_estimators = 10, random_state = 12369) selector = SelectFromModel(estimator, max_features = 20)",
"= RandomForestClassifier(n_estimators = 10, random_state = 12369) selector = RFECV(estimator, cv = 5,",
"sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test, estimator.predict(X_test))) report = classification_report(y_test, estimator.predict(X_test), output_dict=True) accuracies.append(report['accuracy'])",
"from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10, random_state = 12369) selector",
"precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('BalancedRandomForestClassifier') accuracies",
"X_test, y_train, y_test = train_test_split(X_device, y_device, test_size=0.2) from sklearn.neighbors import LocalOutlierFactor estimator =",
"import SMOTE X_oversampled, y_oversampled = SMOTE().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble",
"= 12369) estimator.fit_predict(X_train) tp = np.mean(estimator.predict(X_test) == 1) fn = np.mean(estimator.predict(X_test) == -1)",
"2)}') # %% print('GaussianNB') accuracies = [] precisions = [] recalls = []",
"2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier - global model')",
"%% df = full_df.iloc[:, list(range(36)) + list(range(72, 108)) + list(range(108, 144)) + list(range(180,",
"selector, \\ param_distributions = param_grid, \\ n_iter = 100, \\ cv = 3,",
"sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state =",
"%% print('RandomForestClassifier + SelectKBest (mutual_info_classif)') accuracies = [] precisions = [] recalls =",
"(tp + fp) recall = tp / (tp + fn) fscore = 2",
"pd.DataFrame = pickle.load(last_run.unlock_data.open('rb')) # full_df = full_df.loc[full_df.DeviceId != 3].reset_index(drop = True) ## Old",
"in y.unique(): y_device = y[y == device_id] X_device = X.loc[y == device_id, :]",
"} from sklearn.model_selection import RandomizedSearchCV param_grid = { 'estimator__n_estimators': [10, 20, 50, 100],",
"RandomForestClassifier(n_estimators = 10, random_state = 12369) estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(f'Device",
"= 'MAKDataHub.settings' import django django.setup() # %% import math import pickle import pandas",
"random_state = 12369) estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test, estimator.predict(X_test)))",
"12369) from sklearn.svm import LinearSVC estimator = LinearSVC(random_state = 12369) estimator.fit(X_train, y_train) from",
"LinearSVC(random_state = 12369) estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test))) report =",
"y.unique(): y_device = y[y == device_id] X_device = X.loc[y == device_id, :] X_non_device",
"2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SelectFromModel') accuracies",
"list(range(72, 108)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(108, 144)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(144, 180)) +",
"{round(np.mean(fscores), 2)}') # %% print('LOF') accuracies = [] precisions = [] recalls =",
"test_size=0.2) from sklearn.ensemble import IsolationForest estimator = IsolationForest(n_estimators = 10) estimator.fit(X_train) tp =",
"'estimator__min_samples_leaf': [1, 2, 3], 'estimator__bootstrap': [True, False] } grid = RandomizedSearchCV(estimator = selector,",
"True) df = df.loc[(df.DeviceId != 4) & (df.DeviceId != 7), :].reset_index(drop = True)",
"= pickle.load(last_run.unlock_data.open('rb')) # full_df = full_df.loc[full_df.DeviceId != 3].reset_index(drop = True) ## Old database",
"+ SelectFromModel') accuracies = [] precisions = [] recalls = [] fscores =",
"(mutual_info_classif)') accuracies = [] precisions = [] recalls = [] fscores = []",
"param_grid = { 'estimator__n_estimators': [10, 20, 50, 100], 'estimator__max_features': ['auto', 'sqrt', 'log2'], 'estimator__max_depth':",
"full_df.loc[full_df.DeviceId != '1439cbc3ad71ac06'].reset_index(drop = True) # %% df = full_df.iloc[:, list(range(36)) + list(range(72,",
"django.setup() # %% import math import pickle import pandas as pd import numpy",
"df.iloc[:, -1] #%% full_df.shape # %% display(full_df.iloc[:, list(range(36)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(36,",
"fscore: {round(np.mean(fscores), 2)}') # %% print('KNeighborsClassifier') accuracies = [] precisions = [] recalls",
"import math import pickle import pandas as pd import numpy as np import",
"OneClassSVM(random_state = 12369) estimator.fit_predict(X_train) tp = np.mean(estimator.predict(X_test) == 1) fn = np.mean(estimator.predict(X_test) ==",
"2)}') # %% print('RandomForestClassifier + SMOTEENN') accuracies = [] precisions = [] recalls",
"= OneClassSVM(random_state = 12369) estimator.fit_predict(X_train) tp = np.mean(estimator.predict(X_test) == 1) fn = np.mean(estimator.predict(X_test)",
"fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier - global model') from sklearn.model_selection import train_test_split",
"\\ min_samples_split = 2, \\ bootstrap = False, \\ max_features = 'sqrt', \\",
"y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from imblearn.combine import SMOTEENN",
"SelectKBest(score_func = f_classif, k=20).fit(X_train, y_train) X_train = selector.transform(X_train) X_test = selector.transform(X_test) from sklearn.ensemble",
"df = full_df.iloc[:, list(range(36)) + list(range(72, 108)) + list(range(108, 144)) + list(range(180, 216))",
"[216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(144, 180)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(180, 216)) + [216]].groupby('DeviceId').agg([np.mean])) # %%",
"precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('KNeighborsClassifier') accuracies",
"[216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(72, 108)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(108, 144)) + [216]].groupby('DeviceId').agg([np.min,",
"recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('LinearSVC') accuracies = [] precisions",
"random_state = 12369) from sklearn.feature_selection import RFE from imblearn.ensemble import BalancedRandomForestClassifier estimator =",
"'estimator__max_depth': [int(x) for x in np.linspace(2, 20, num = 2)] + [None], 'estimator__min_samples_split':",
"= train_test_split(X, y_device, test_size=0.2, random_state = 12369) from imblearn.combine import SMOTETomek X_oversampled, y_oversampled",
"{round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + PCA') accuracies = [] precisions = []",
"+ tn + fn + fp) precision = tp / (tp + fp)",
"selector.fit(X_oversampled, y_oversampled) from sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test, selector.predict(X_test))) report = classification_report(y_test,",
"y_device, test_size=0.2, random_state = 12369) from sklearn.decomposition import PCA pca = PCA(n_components=20).fit(X_train) X_train",
"fscores = [] for device_id in y.unique(): y_device = np.where(y == device_id, 1,",
"= { 'estimator__n_estimators': [10, 20, 50, 100], 'estimator__max_features': ['auto', 'sqrt', 'log2'], 'estimator__max_depth': [int(x)",
"& (df.DeviceId != 7), :].reset_index(drop = True) X, y = df.iloc[:, 0:-1], df.iloc[:,",
"['auto', 'sqrt', 'log2'], # 'estimator__max_depth': [4, 5, 6, 7, 8], # 'estimator__criterion': ['gini',",
"import pandas as pd import numpy as np import matplotlib.pyplot as plt import",
"in y.unique(): y_device = np.where(y == device_id, 1, 0) from sklearn.preprocessing import StandardScaler",
"5], 'estimator__min_samples_leaf': [1, 2, 3], 'estimator__bootstrap': [True, False] } grid = RandomizedSearchCV(estimator =",
"StandardScaler X_std = StandardScaler().fit_transform(X) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test =",
"'sqrt', 'log2'], # 'estimator__max_depth': [4, 5, 6, 7, 8], # 'estimator__criterion': ['gini', 'entropy']",
"display(full_df.iloc[:, list(range(108, 144)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(144, 180)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(180, 216))",
"= True, contamination = 'auto') estimator.fit(X_train) tp = np.mean(estimator.predict(X_test) == 1) fn =",
"import classification_report print(classification_report(y_test, estimator.predict(X_test))) # %% print('RandomForestClassifier - standardized') accuracies = [] precisions",
"import train_test_split X_train, X_test, y_train, y_test = train_test_split(X_device, y_device, test_size=0.2) from sklearn.ensemble import",
"y_device = y[y == device_id] X_device = X.loc[y == device_id, :] X_non_device =",
"y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from imblearn.combine import SMOTEENN X_oversampled,",
"{round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + RFECV') from sklearn.model_selection import train_test_split X_train, X_test,",
"classification_report print(f'Device {device_id}:') print(classification_report(y_test, selector.estimator_.predict(X_test))) report = classification_report(y_test, selector.estimator_.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall'])",
"y_test = train_test_split(X, y, test_size=0.2, random_state = 12369) from yellowbrick.model_selection import RFECV from",
"# %% sns.boxplot(df.DeviceId, df.GyrMgn_amax) # %% sns.pairplot(df.loc[df.DeviceId != 3, :], hue=\"DeviceId\", vars=[\"AccMgn_mean\", \"AccMgn_median\"],",
"= classification_report(y_test, selector.estimator_.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score']) print(f'Accuracy: {round(np.mean(accuracies), 2)}, precision: {round(np.mean(precisions),",
"{round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + PCA') accuracies = []",
"tn + fn + fp) precision = tp / (tp + fp) recall",
"import PCA pca = PCA(n_components=20).fit(X_train) X_train = pca.transform(X_train) X_test = pca.transform(X_test) from sklearn.ensemble",
"estimator.fit_predict(X_train) tp = np.mean(estimator.predict(X_test) == 1) fn = np.mean(estimator.predict(X_test) == -1) tn =",
"step = 0.05) selector.fit(X_train, y_train) selector.show() from sklearn.metrics import classification_report print(classification_report(y_test, selector.predict(X_test))) #",
"2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('Hyperparameter tuning') for device_id in y.unique(): y_device",
"n_features_to_select = 20, step = 0.05) # from sklearn.model_selection import GridSearchCV # param_grid",
"(tp + tn + fn + fp) precision = tp / (tp +",
"2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SMOTEENN') accuracies",
"2)}, precision: {round(precision, 2)}, recall: {round(recall, 2)}') # print(f'{device_id} - Class acc: {round(np.mean(estimator.predict(X_device)",
"fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SelectKBest (f_classif)') accuracies = [] precisions",
"3], 'estimator__bootstrap': [True, False] } grid = RandomizedSearchCV(estimator = selector, \\ param_distributions =",
"sklearn.feature_selection import SelectKBest, mutual_info_classif selector = SelectKBest(score_func = mutual_info_classif, k=20).fit(X_train, y_train) X_train =",
"BalancedRandomForestClassifier estimator = BalancedRandomForestClassifier(n_estimators = 10, random_state = 12369) selector = RFE(estimator, n_features_to_select",
"42, \\ n_jobs = -1) grid.fit(X_oversampled, y_oversampled) print(grid.best_params_) # %% print('RandomForestClassifier + SMOTETomek",
"y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.feature_selection import SelectFromModel",
"list(range(108, 144)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(144, 180)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(180,",
"{round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SMOTE') accuracies = [] precisions = []",
"recall: {round(recall, 2)}') # print(f'{device_id} - Class acc: {round(np.mean(estimator.predict(X_test) == 1), 2)}, non-class",
"list(range(72, 108)) + list(range(108, 144)) + list(range(180, 216)) + [216]].reset_index(drop = True) df",
"sns.boxplot(df.DeviceId, df.GyrMgn_amax) # %% sns.pairplot(df.loc[df.DeviceId != 3, :], hue=\"DeviceId\", vars=[\"AccMgn_mean\", \"AccMgn_median\"], markers='.') #",
"imblearn.combine import SMOTETomek X_oversampled, y_oversampled = SMOTETomek().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from",
"list(range(72, 108)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(108, 144)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(144,",
"estimator = KNeighborsClassifier() estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test))) report =",
"not np.isnan(fscore) else 0) print(f'{device_id} - accuracy: {round(accuracy, 2)}, precision: {round(precision, 2)}, recall:",
"sklearn.model_selection import RandomizedSearchCV param_grid = { 'estimator__n_estimators': [10, 20, 50, 100], 'estimator__max_features': ['auto',",
"classification_report print(classification_report(y_test, estimator.predict(X_test))) report = classification_report(y_test, estimator.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score']) print(f'Accuracy:",
"selector.predict(X_test))) # %% print('RandomForestClassifier + RFE20') accuracies = [] precisions = [] recalls",
"display(full_df.iloc[:, list(range(144, 180)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(180, 216)) + [216]].groupby('DeviceId').agg([np.min, np.max])) #",
"= np.mean(estimator.predict(X_test) == -1) tn = np.mean(estimator.predict(X_non_device) == 1) fp = np.mean(estimator.predict(X_non_device) ==",
"{round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SelectKBest",
"fp) precision = tp / (tp + fp) recall = tp / (tp",
"RandomForestClassifier(n_estimators = 10, random_state = 12369) selector = RFECV(estimator, cv = 5, scoring='f1_weighted',",
"200, 500], # 'estimator__max_features': ['auto', 'sqrt', 'log2'], # 'estimator__max_depth': [4, 5, 6, 7,",
"\\ n_jobs = -1) grid.fit(X_oversampled, y_oversampled) print(grid.best_params_) # %% print('RandomForestClassifier + SMOTETomek +",
"= 12369) selector = RFE(estimator, n_features_to_select = 20, step = 0.05) selector.fit(X_oversampled, y_oversampled)",
"print(f'Device {device_id}:') print(classification_report(y_test, selector.estimator_.predict(X_test))) report = classification_report(y_test, selector.estimator_.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score'])",
"train_test_split(X, y_device, test_size=0.2, random_state = 12369) from imblearn.combine import SMOTETomek X_oversampled, y_oversampled =",
"print(f'Device {device_id}:') print(classification_report(y_test, estimator.predict(X_test))) report = classification_report(y_test, estimator.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score'])",
"precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier') accuracies",
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state = 12369) from yellowbrick.model_selection",
"12369) from imblearn.combine import SMOTETomek X_oversampled, y_oversampled = SMOTETomek().fit_resample(X_train, y_train) from sklearn.feature_selection import",
"# from sklearn.model_selection import GridSearchCV # param_grid = { # 'estimator__n_estimators': [10, 50,",
"{round(recall, 2)}') # print(f'{device_id} - Class acc: {round(np.mean(estimator.predict(X_device) == 1), 2)}, non-class acc:",
"last_run = profile_service.get_last_profile_creation_run() ## New database full_df: pd.DataFrame = pickle.load(last_run.unlock_data.open('rb')) # full_df =",
"StandardScaler().fit_transform(X) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X_std, y_device, test_size=0.2,",
"global model') from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y,",
"+ [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(180, 216)) + [216]].groupby('DeviceId').agg([np.min, np.max])) # %% display(full_df.iloc[:, list(range(36))",
"'3', :] sns.swarmplot(data = test, x=\"DeviceId\", y=\"RotMgn_median\") # %% test = full_df.loc[:, :]",
"estimator = OneClassSVM(random_state = 12369) estimator.fit_predict(X_train) tp = np.mean(estimator.predict(X_test) == 1) fn =",
"import SelectFromModel from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10, random_state =",
"k=20).fit(X_train, y_train) X_train = selector.transform(X_train) X_test = selector.transform(X_test) from sklearn.ensemble import RandomForestClassifier estimator",
"pca = PCA(n_components=20).fit(X_train) X_train = pca.transform(X_train) X_test = pca.transform(X_test) from sklearn.ensemble import RandomForestClassifier",
"0) fscores.append(fscore if not np.isnan(fscore) else 0) print(f'{device_id} - accuracy: {round(accuracy, 2)}, precision:",
"/ (tp + fp) recall = tp / (tp + fn) fscore =",
"sklearn.naive_bayes import GaussianNB estimator = GaussianNB() estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(classification_report(y_test,",
"\\ verbose = 2, \\ random_state = 42, \\ n_jobs = -1) grid.fit(X_oversampled,",
"0.05) selector.fit(X_oversampled, y_oversampled) from sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test, selector.predict(X_test))) report =",
"3, \\ verbose = 2, \\ random_state = 42, \\ n_jobs = -1)",
"# %% import math import pickle import pandas as pd import numpy as",
"list(range(108, 144)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(144, 180)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(180, 216)) +",
"fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + RFECV') from sklearn.model_selection import train_test_split X_train,",
"} grid = RandomizedSearchCV(estimator = selector, \\ param_distributions = param_grid, \\ n_iter =",
"108)) + list(range(108, 144)) + list(range(180, 216)) + [216]].reset_index(drop = True) df =",
"standardized') accuracies = [] precisions = [] recalls = [] fscores = []",
"2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('BalancedRandomForestClassifier') accuracies = []",
"precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('LOF') accuracies",
"y_oversampled = SMOTE().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier estimator",
"from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state",
"recall = tp / (tp + fn) fscore = 2 * recall *",
"selector = RFE(estimator, n_features_to_select = 20, step = 0.05) selector.fit(X_oversampled, y_oversampled) from sklearn.metrics",
"max_features = 'sqrt', \\ max_depth = 20) selector = RFE(estimator, n_features_to_select = 20,",
"max_depth = 20) selector = RFE(estimator, n_features_to_select = 20, step = 0.05) #",
"{round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SMOTEENN') accuracies = []",
"# %% print('OneClassSVM') accuracies = [] precisions = [] recalls = [] fscores",
"2)}') # %% print('KNeighborsClassifier') accuracies = [] precisions = [] recalls = []",
"param_grid, \\ n_iter = 100, \\ cv = 3, \\ verbose = 2,",
"from sklearn.model_selection import RandomizedSearchCV param_grid = { 'estimator__n_estimators': [10, 20, 50, 100], 'estimator__max_features':",
"recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + RFECV') from sklearn.model_selection",
"for x in np.linspace(2, 20, num = 2)] + [None], 'estimator__min_samples_split': [2, 3,",
"else 0) print(f'{device_id} - accuracy: {round(accuracy, 2)}, precision: {round(precision, 2)}, recall: {round(recall, 2)}')",
"{round(np.mean(estimator.predict(X_device) == 1), 2)}, non-class acc: {round(np.mean(estimator.predict(X_non_device) == -1), 2)}') print(f'Accuracy: {round(np.mean(accuracies), 2)},",
"216)) + [216]].groupby('DeviceId').agg([np.mean])) # %% sns.boxplot(df.DeviceId, df.AccMgn_mean) # %% sns.boxplot(df.DeviceId, df.AccMgn_median) # %%",
"{round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('LOF') accuracies =",
"print('RandomForestClassifier + PCA') accuracies = [] precisions = [] recalls = [] fscores",
"2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('Hyperparameter tuning') for device_id",
"20) selector.fit(X_train, y_train) from sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test, selector.estimator_.predict(X_test))) report =",
"{round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier - global",
"RandomizedSearchCV param_grid = { 'estimator__n_estimators': [10, 20, 50, 100], 'estimator__max_features': ['auto', 'sqrt', 'log2'],",
"estimator = LinearSVC(random_state = 12369) estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test)))",
"3, :], hue=\"DeviceId\", vars=[\"AccMgn_mean\", \"AccMgn_median\"], markers='.') # %% test = df.loc[df.DeviceId != '3',",
"20, 50, 100], 'estimator__max_features': ['auto', 'sqrt', 'log2'], 'estimator__max_depth': [int(x) for x in np.linspace(2,",
"= 0.05) selector.fit(X_train, y_train) selector.show() from sklearn.metrics import classification_report print(classification_report(y_test, selector.predict(X_test))) # %%",
"= 12369) from imblearn.combine import SMOTETomek X_oversampled, y_oversampled = SMOTETomek().fit_resample(X_train, y_train) from sklearn.feature_selection",
"= 42, \\ n_jobs = -1) grid.fit(X_oversampled, y_oversampled) print(grid.best_params_) # %% print('RandomForestClassifier +",
"if not np.isnan(fscore) else 0) print(f'{device_id} - accuracy: {round(accuracy, 2)}, precision: {round(precision, 2)},",
"= classification_report(y_test, selector.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score']) print(f'Accuracy: {round(np.mean(accuracies), 2)}, precision: {round(np.mean(precisions),",
"test = full_df.loc[:, :] sns.boxplot(data = test, x=\"DeviceId\", y=\"GrvMgn_amax\") # %% print('OneClassSVM') accuracies",
"%% sns.boxplot(df.DeviceId, df.GyrMgn_amax) # %% sns.pairplot(df.loc[df.DeviceId != 3, :], hue=\"DeviceId\", vars=[\"AccMgn_mean\", \"AccMgn_median\"], markers='.')",
"from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X_device, y_device, test_size=0.2) from",
"from sklearn.neighbors import LocalOutlierFactor estimator = LocalOutlierFactor(n_neighbors = 10, novelty = True, contamination",
"X_train, X_test, y_train, y_test = train_test_split(X_std, y_device, test_size=0.2, random_state = 12369) from sklearn.ensemble",
"%% import math import pickle import pandas as pd import numpy as np",
"- accuracy: {round(accuracy, 2)}, precision: {round(precision, 2)}, recall: {round(recall, 2)}') # print(f'{device_id} -",
"2)}, precision: {round(precision, 2)}, recall: {round(recall, 2)}') # print(f'{device_id} - Class acc: {round(np.mean(estimator.predict(X_test)",
"= train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.feature_selection import SelectFromModel from sklearn.ensemble",
"%% print('Hyperparameter tuning') for device_id in y.unique(): y_device = np.where(y == device_id, 1,",
"X_test, y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from imblearn.under_sampling import",
"20, num = 2)] + [None], 'estimator__min_samples_split': [2, 3, 4, 5], 'estimator__min_samples_leaf': [1,",
"grid = RandomizedSearchCV(estimator = selector, \\ param_distributions = param_grid, \\ n_iter = 100,",
"if not np.isnan(recall) else 0) fscores.append(fscore if not np.isnan(fscore) else 0) print(f'{device_id} -",
"y_device, test_size=0.2, random_state = 12369) from sklearn.feature_selection import SelectKBest, mutual_info_classif selector = SelectKBest(score_func",
"x=\"DeviceId\", y=\"RotMgn_median\") # %% test = full_df.loc[:, :] sns.boxplot(data = test, x=\"DeviceId\", y=\"GrvMgn_amax\")",
"+ [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(36, 72)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(72, 108)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:,",
"# %% print('RandomForestClassifier - global model') from sklearn.model_selection import train_test_split X_train, X_test, y_train,",
"display(full_df.iloc[:, list(range(72, 108)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(108, 144)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(144, 180))",
"fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SelectFromModel') accuracies = [] precisions =",
"n_features_to_select = 20, step = 0.05) selector.fit(X_oversampled, y_oversampled) from sklearn.metrics import classification_report print(f'Device",
"= 10, random_state = 12369) selector = RFE(estimator, n_features_to_select = 20, step =",
"= df.loc[df.DeviceId != '3', :] sns.swarmplot(data = test, x=\"DeviceId\", y=\"RotMgn_median\") # %% test",
"y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.feature_selection import RFE from",
"= 2)] + [None], 'estimator__min_samples_split': [2, 3, 4, 5], 'estimator__min_samples_leaf': [1, 2, 3],",
"RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10, random_state = 12369) selector = RFE(estimator, n_features_to_select",
"from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10, random_state = 12369) estimator.fit(X_train,",
"X_test, y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from imblearn.combine import",
"X, y = df.iloc[:, 0:-1], df.iloc[:, -1] #%% full_df.shape # %% display(full_df.iloc[:, list(range(36))",
"# %% print('RandomForestClassifier + SMOTETomek') accuracies = [] precisions = [] recalls =",
"display(full_df.iloc[:, list(range(36)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(36, 72)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(72, 108)) +",
"{round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('IsolationForest') accuracies =",
"[4, 5, 6, 7, 8], # 'estimator__criterion': ['gini', 'entropy'] # } from sklearn.model_selection",
"= 12369) from sklearn.feature_selection import SelectFromModel from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators",
"= [] precisions = [] recalls = [] fscores = [] for device_id",
"'rb')) # full_df = full_df.loc[full_df.DeviceId != '1439cbc3ad71ac06'].reset_index(drop = True) # %% df =",
"random_state = 12369) from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(random_state = 12369) estimator.fit(X_train,",
"y_oversampled = RandomOverSampler().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier estimator",
"10, random_state = 12369) selector = RFE(estimator, n_features_to_select = 20, step = 0.05)",
"n_features_to_select = 20, step = 0.05) selector.fit(X_train, y_train) from sklearn.metrics import classification_report print(f'Device",
"list(range(36, 72)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(72, 108)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(108, 144)) +",
"y[y == device_id] X_device = X.loc[y == device_id, :] X_non_device = X.loc[y !=",
"= 12369) from sklearn.decomposition import PCA pca = PCA(n_components=20).fit(X_train) X_train = pca.transform(X_train) X_test",
"= train_test_split(X, y_device, test_size=0.2, random_state = 12369) from imblearn.over_sampling import RandomOverSampler X_oversampled, y_oversampled",
"recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + RandomOverSampler') accuracies =",
"recalls.append(recall if not np.isnan(recall) else 0) fscores.append(fscore if not np.isnan(fscore) else 0) print(f'{device_id}",
"12369) selector = RFE(estimator, n_features_to_select = 20, step = 0.05) selector.fit(X_oversampled, y_oversampled) from",
"unlock_data_path = storage_service.download_file(last_run.unlock_data_uri) # full_df: pd.DataFrame = pickle.load(open(unlock_data_path, 'rb')) # full_df = full_df.loc[full_df.DeviceId",
"RFECV from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10, random_state = 12369)",
"selector.fit(X_train, y_train) from sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test, selector.predict(X_test))) report = classification_report(y_test,",
"y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.feature_selection import RFE",
"output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score']) print(f'Accuracy: {round(np.mean(accuracies), 2)}, precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls),",
"X_oversampled, y_oversampled = SMOTEENN().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier",
"import train_test_split X_train, X_test, y_train, y_test = train_test_split(X_std, y_device, test_size=0.2, random_state = 12369)",
"SMOTETomek().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators",
"#%% full_df.shape # %% display(full_df.iloc[:, list(range(36)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(36, 72)) +",
"== 1) fp = np.mean(estimator.predict(X_non_device) == 1) accuracy = (tp + tn) /",
"[] precisions = [] recalls = [] fscores = [] for device_id in",
"= pca.transform(X_train) X_test = pca.transform(X_test) from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators =",
"= tp / (tp + fn) fscore = 2 * recall * precision",
"{round(np.mean(fscores), 2)}') # %% print('IsolationForest') accuracies = [] precisions = [] recalls =",
"import SMOTEENN X_oversampled, y_oversampled = SMOTEENN().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble",
"= [] for device_id in y.unique(): y_device = np.where(y == device_id, 1, 0)",
"# %% test = full_df.loc[:, :] sns.boxplot(data = test, x=\"DeviceId\", y=\"GrvMgn_amax\") # %%",
"%% test = full_df.loc[:, :] sns.boxplot(data = test, x=\"DeviceId\", y=\"GrvMgn_amax\") # %% print('OneClassSVM')",
"= train_test_split(X_device, y_device, test_size=0.2) from sklearn.svm import OneClassSVM estimator = OneClassSVM(random_state = 12369)",
"precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier -",
"recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SelectKBest (mutual_info_classif)') accuracies",
"2)}, recall: {round(recall, 2)}') # print(f'{device_id} - Class acc: {round(np.mean(estimator.predict(X_test) == 1), 2)},",
"test_size=0.2, random_state = 12369) from imblearn.combine import SMOTEENN X_oversampled, y_oversampled = SMOTEENN().fit_resample(X_train, y_train)",
"= train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.ensemble import RandomForestClassifier estimator =",
"from sklearn.feature_selection import SelectKBest, f_classif selector = SelectKBest(score_func = f_classif, k=20).fit(X_train, y_train) X_train",
"y_train, y_test = train_test_split(X_device, y_device, test_size=0.2) from sklearn.ensemble import IsolationForest estimator = IsolationForest(n_estimators",
"scoring='f1_weighted', step = 0.05) selector.fit(X_train, y_train) selector.show() from sklearn.metrics import classification_report print(classification_report(y_test, selector.predict(X_test)))",
"[216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(72, 108)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(108, 144)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(144,",
"y_oversampled) print(grid.best_params_) # %% print('RandomForestClassifier + SMOTETomek + parameters') accuracies = [] precisions",
"print('RandomForestClassifier + SelectFromModel') accuracies = [] precisions = [] recalls = [] fscores",
"from MAKDataHub.services import Services profile_service = Services.profile_service() storage_service = Services.storage_service() last_run = profile_service.get_last_profile_creation_run()",
"- Class acc: {round(np.mean(estimator.predict(X_device) == 1), 2)}, non-class acc: {round(np.mean(estimator.predict(X_non_device) == -1), 2)}')",
"# %% print('RandomForestClassifier + SelectFromModel') accuracies = [] precisions = [] recalls =",
"MAKDataHub.services import Services profile_service = Services.profile_service() storage_service = Services.storage_service() last_run = profile_service.get_last_profile_creation_run() ##",
"{round(np.mean(fscores), 2)}') # %% print('KNeighborsClassifier') accuracies = [] precisions = [] recalls =",
"import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369)",
"{round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('LinearSVC') accuracies =",
"import GaussianNB estimator = GaussianNB() estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test)))",
"2)] + [None], 'estimator__min_samples_split': [2, 3, 4, 5], 'estimator__min_samples_leaf': [1, 2, 3], 'estimator__bootstrap':",
"= [] fscores = [] for device_id in y.unique(): y_device = np.where(y ==",
"print('RandomForestClassifier + RandomUnderSampler') accuracies = [] precisions = [] recalls = [] fscores",
"{ # 'estimator__n_estimators': [10, 50, 100, 200, 500], # 'estimator__max_features': ['auto', 'sqrt', 'log2'],",
"{device_id}:') print(classification_report(y_test, selector.predict(X_test))) report = classification_report(y_test, selector.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score']) print(f'Accuracy:",
"GaussianNB estimator = GaussianNB() estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test))) report",
"print(f'{device_id} - Class acc: {round(np.mean(estimator.predict(X_test) == 1), 2)}, non-class acc: {round(np.mean(estimator.predict(X_non_device) == -1),",
"'estimator__criterion': ['gini', 'entropy'] # } from sklearn.model_selection import RandomizedSearchCV param_grid = { 'estimator__n_estimators':",
"2)}') # %% print('RandomForestClassifier + RandomOverSampler') accuracies = [] precisions = [] recalls",
"precision: {round(precision, 2)}, recall: {round(recall, 2)}') # print(f'{device_id} - Class acc: {round(np.mean(estimator.predict(X_device) ==",
"= test, x=\"DeviceId\", y=\"GrvMgn_amax\") # %% print('OneClassSVM') accuracies = [] precisions = []",
"train_test_split(X, y_device, test_size=0.2, random_state = 12369) from imblearn.combine import SMOTEENN X_oversampled, y_oversampled =",
"y_oversampled = SMOTETomek().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier estimator",
"np.max])) # %% display(full_df.iloc[:, list(range(36)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(36, 72)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:,",
"2)}, precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('LinearSVC')",
"= Services.storage_service() last_run = profile_service.get_last_profile_creation_run() ## New database full_df: pd.DataFrame = pickle.load(last_run.unlock_data.open('rb')) #",
"= { # 'estimator__n_estimators': [10, 50, 100, 200, 500], # 'estimator__max_features': ['auto', 'sqrt',",
"12369) from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators =",
"df.GyrMgn_amax) # %% sns.pairplot(df.loc[df.DeviceId != 3, :], hue=\"DeviceId\", vars=[\"AccMgn_mean\", \"AccMgn_median\"], markers='.') # %%",
"print('GaussianNB') accuracies = [] precisions = [] recalls = [] fscores = []",
"# 'estimator__max_features': ['auto', 'sqrt', 'log2'], # 'estimator__max_depth': [4, 5, 6, 7, 8], #",
"[] for device_id in y.unique(): y_device = np.where(y == device_id, 1, 0) from",
"estimator = RandomForestClassifier(random_state = 12369) estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test)))",
"train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from",
"recall * precision / (recall + precision) accuracies.append(accuracy if not np.isnan(accuracy) else 0)",
"1, \\ min_samples_split = 2, \\ bootstrap = False, \\ max_features = 'sqrt',",
"full_df: pd.DataFrame = pickle.load(last_run.unlock_data.open('rb')) # full_df = full_df.loc[full_df.DeviceId != 3].reset_index(drop = True) ##",
"for device_id in y.unique(): y_device = y[y == device_id] X_device = X.loc[y ==",
"y_train) from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(random_state =",
"%% print('RandomForestClassifier - standardized') accuracies = [] precisions = [] recalls = []",
"2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SelectKBest (mutual_info_classif)') accuracies = []",
"# %% print('RandomForestClassifier - standardized') accuracies = [] precisions = [] recalls =",
"y=\"RotMgn_median\") # %% test = full_df.loc[:, :] sns.boxplot(data = test, x=\"DeviceId\", y=\"GrvMgn_amax\") #",
"= full_df.loc[full_df.DeviceId != 3].reset_index(drop = True) ## Old database # unlock_data_path = storage_service.download_file(last_run.unlock_data_uri)",
"selector = RFE(estimator, n_features_to_select = 20, step = 0.05) # from sklearn.model_selection import",
"(f_classif)') accuracies = [] precisions = [] recalls = [] fscores = []",
"fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SMOTE') accuracies = [] precisions =",
"# %% df = full_df.iloc[:, list(range(36)) + list(range(72, 108)) + list(range(108, 144)) +",
"2)}') # %% print('RandomForestClassifier + RandomUnderSampler') accuracies = [] precisions = [] recalls",
"test_size=0.2, random_state = 12369) from sklearn.feature_selection import SelectKBest, f_classif selector = SelectKBest(score_func =",
"estimator = BalancedRandomForestClassifier(n_estimators = 10, random_state = 12369) selector = RFE(estimator, n_features_to_select =",
"train_test_split(X_device, y_device, test_size=0.2) from sklearn.svm import OneClassSVM estimator = OneClassSVM(random_state = 12369) estimator.fit_predict(X_train)",
"= 0.05) # from sklearn.model_selection import GridSearchCV # param_grid = { # 'estimator__n_estimators':",
"0.05) selector.fit(X_train, y_train) from sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test, selector.predict(X_test))) report =",
"y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.neighbors import KNeighborsClassifier",
"X_std = StandardScaler().fit_transform(X) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X_std,",
"sklearn.metrics import classification_report print(classification_report(y_test, selector.predict(X_test))) # %% print('RandomForestClassifier + RFE20') accuracies = []",
"Services.profile_service() storage_service = Services.storage_service() last_run = profile_service.get_last_profile_creation_run() ## New database full_df: pd.DataFrame =",
"%% print('LinearSVC') accuracies = [] precisions = [] recalls = [] fscores =",
"12369) estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test))) report = classification_report(y_test, estimator.predict(X_test),",
"= 2, \\ bootstrap = False, \\ max_features = 'sqrt', \\ max_depth =",
"django django.setup() # %% import math import pickle import pandas as pd import",
"# print(f'{device_id} - Class acc: {round(np.mean(estimator.predict(X_test) == 1), 2)}, non-class acc: {round(np.mean(estimator.predict(X_non_device) ==",
"import RFE from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10, random_state =",
"RandomOverSampler().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators",
"= SMOTE().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier estimator =",
"12369) from sklearn.feature_selection import SelectKBest, mutual_info_classif selector = SelectKBest(score_func = mutual_info_classif, k=20).fit(X_train, y_train)",
"10) estimator.fit(X_train) tp = np.mean(estimator.predict(X_test) == 1) fn = np.mean(estimator.predict(X_test) == -1) tn",
"np.max])) display(full_df.iloc[:, list(range(144, 180)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(180, 216)) + [216]].groupby('DeviceId').agg([np.min, np.max]))",
"{round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('LOF') accuracies = [] precisions =",
"from sklearn.feature_selection import SelectFromModel from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10,",
"random_state = 12369) from imblearn.combine import SMOTEENN X_oversampled, y_oversampled = SMOTEENN().fit_resample(X_train, y_train) from",
"{device_id}:') print(classification_report(y_test, selector.estimator_.predict(X_test))) report = classification_report(y_test, selector.estimator_.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score']) print(f'Accuracy:",
"import numpy as np import matplotlib.pyplot as plt import seaborn as sns from",
"2)}, precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('IsolationForest')",
"sklearn.ensemble import IsolationForest estimator = IsolationForest(n_estimators = 10) estimator.fit(X_train) tp = np.mean(estimator.predict(X_test) ==",
"= storage_service.download_file(last_run.unlock_data_uri) # full_df: pd.DataFrame = pickle.load(open(unlock_data_path, 'rb')) # full_df = full_df.loc[full_df.DeviceId !=",
"2)}') # %% print('RandomForestClassifier + SelectFromModel') accuracies = [] precisions = [] recalls",
"recalls = [] fscores = [] for device_id in y.unique(): y_device = np.where(y",
"storage_service = Services.storage_service() last_run = profile_service.get_last_profile_creation_run() ## New database full_df: pd.DataFrame = pickle.load(last_run.unlock_data.open('rb'))",
"= 10, random_state = 12369) selector = RFECV(estimator, cv = 5, scoring='f1_weighted', step",
"= Services.profile_service() storage_service = Services.storage_service() last_run = profile_service.get_last_profile_creation_run() ## New database full_df: pd.DataFrame",
"y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.decomposition import PCA",
"2)}, precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('LOF')",
"parameters') accuracies = [] precisions = [] recalls = [] fscores = []",
"= 20) selector = RFE(estimator, n_features_to_select = 20, step = 0.05) selector.fit(X_oversampled, y_oversampled)",
"from yellowbrick.model_selection import RFECV from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10,",
"BalancedRandomForestClassifier(n_estimators = 10, random_state = 12369) selector = RFE(estimator, n_features_to_select = 20, step",
"= 12369) from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators",
"SelectFromModel(estimator, max_features = 20) selector.fit(X_train, y_train) from sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test,",
"= 12369, \\ n_estimators = 50, min_samples_leaf = 1, \\ min_samples_split = 2,",
"'estimator__n_estimators': [10, 50, 100, 200, 500], # 'estimator__max_features': ['auto', 'sqrt', 'log2'], # 'estimator__max_depth':",
"{round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SelectFromModel')",
"y_device, test_size=0.2, random_state = 12369) from sklearn.feature_selection import SelectFromModel from sklearn.ensemble import RandomForestClassifier",
"= train_test_split(X_std, y_device, test_size=0.2, random_state = 12369) from sklearn.ensemble import RandomForestClassifier estimator =",
"-1) grid.fit(X_oversampled, y_oversampled) print(grid.best_params_) # %% print('RandomForestClassifier + SMOTETomek + parameters') accuracies =",
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state = 12369) from sklearn.ensemble",
"df.iloc[:, 0:-1], df.iloc[:, -1] #%% full_df.shape # %% display(full_df.iloc[:, list(range(36)) + [216]].groupby('DeviceId').agg([np.min, np.max]))",
"step = 0.05) selector.fit(X_oversampled, y_oversampled) from sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test, selector.predict(X_test)))",
"import BalancedRandomForestClassifier estimator = BalancedRandomForestClassifier(n_estimators = 10, random_state = 12369) selector = RFE(estimator,",
"= profile_service.get_last_profile_creation_run() ## New database full_df: pd.DataFrame = pickle.load(last_run.unlock_data.open('rb')) # full_df = full_df.loc[full_df.DeviceId",
"{round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SMOTETomek') accuracies = [] precisions = []",
"[10, 50, 100, 200, 500], # 'estimator__max_features': ['auto', 'sqrt', 'log2'], # 'estimator__max_depth': [4,",
"random_state = 12369) from imblearn.over_sampling import RandomOverSampler X_oversampled, y_oversampled = RandomOverSampler().fit_resample(X_train, y_train) from",
":] sns.swarmplot(data = test, x=\"DeviceId\", y=\"RotMgn_median\") # %% test = full_df.loc[:, :] sns.boxplot(data",
"* recall * precision / (recall + precision) accuracies.append(accuracy if not np.isnan(accuracy) else",
"216)) + [216]].groupby('DeviceId').agg([np.min, np.max])) # %% display(full_df.iloc[:, list(range(36)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(36, 72))",
"pca.transform(X_train) X_test = pca.transform(X_test) from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10,",
"from sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test, selector.estimator_.predict(X_test))) report = classification_report(y_test, selector.estimator_.predict(X_test), output_dict=True)",
"{round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('BalancedRandomForestClassifier') accuracies = [] precisions =",
"{round(np.mean(fscores), 2)}') # %% print('LinearSVC') accuracies = [] precisions = [] recalls =",
"train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.feature_selection import SelectFromModel from sklearn.ensemble import",
"import train_test_split X_train, X_test, y_train, y_test = train_test_split(X_device, y_device, test_size=0.2) from sklearn.neighbors import",
"{round(np.mean(fscores), 2)}') # %% print('Hyperparameter tuning') for device_id in y.unique(): y_device = np.where(y",
"sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X_std, y_device, test_size=0.2, random_state =",
"selector.transform(X_train) X_test = selector.transform(X_test) from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10,",
"= 20, step = 0.05) selector.fit(X_oversampled, y_oversampled) from sklearn.metrics import classification_report print(f'Device {device_id}:')",
"sklearn.svm import LinearSVC estimator = LinearSVC(random_state = 12369) estimator.fit(X_train, y_train) from sklearn.metrics import",
"import RandomizedSearchCV param_grid = { 'estimator__n_estimators': [10, 20, 50, 100], 'estimator__max_features': ['auto', 'sqrt',",
"sklearn.neighbors import LocalOutlierFactor estimator = LocalOutlierFactor(n_neighbors = 10, novelty = True, contamination =",
"pickle.load(open(unlock_data_path, 'rb')) # full_df = full_df.loc[full_df.DeviceId != '1439cbc3ad71ac06'].reset_index(drop = True) # %% df",
"X_train = selector.transform(X_train) X_test = selector.transform(X_test) from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators",
"y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.feature_selection import SelectKBest, f_classif",
"2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SMOTE') accuracies = [] precisions",
"y_oversampled = RandomUnderSampler().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier estimator",
"+ fn + fp) precision = tp / (tp + fp) recall =",
"tn) / (tp + tn + fn + fp) precision = tp /",
"= df.iloc[:, 0:-1], df.iloc[:, -1] #%% full_df.shape # %% display(full_df.iloc[:, list(range(36)) + [216]].groupby('DeviceId').agg([np.min,",
"X_test, y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.neighbors import",
"12369) from sklearn.naive_bayes import GaussianNB estimator = GaussianNB() estimator.fit(X_train, y_train) from sklearn.metrics import",
"= 12369) from yellowbrick.model_selection import RFECV from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators",
"+ [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(72, 108)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(108, 144)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:,",
"= np.mean(estimator.predict(X_non_device) == 1) fp = np.mean(estimator.predict(X_non_device) == 1) accuracy = (tp +",
"sns.pairplot(df.loc[df.DeviceId != 3, :], hue=\"DeviceId\", vars=[\"AccMgn_mean\", \"AccMgn_median\"], markers='.') # %% test = df.loc[df.DeviceId",
"= 12369) selector = RFE(estimator, n_features_to_select = 20, step = 0.05) selector.fit(X_train, y_train)",
"# %% print('RandomForestClassifier + RFE20') accuracies = [] precisions = [] recalls =",
"+ RandomUnderSampler') accuracies = [] precisions = [] recalls = [] fscores =",
"fscore = 2 * recall * precision / (recall + precision) accuracies.append(accuracy if",
"IsolationForest(n_estimators = 10) estimator.fit(X_train) tp = np.mean(estimator.predict(X_test) == 1) fn = np.mean(estimator.predict(X_test) ==",
"2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('IsolationForest') accuracies = []",
"# %% print('RandomForestClassifier + PCA') accuracies = [] precisions = [] recalls =",
"from sklearn.svm import LinearSVC estimator = LinearSVC(random_state = 12369) estimator.fit(X_train, y_train) from sklearn.metrics",
"2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SelectFromModel') accuracies = [] precisions",
"0) recalls.append(recall if not np.isnan(recall) else 0) fscores.append(fscore if not np.isnan(fscore) else 0)",
"mutual_info_classif selector = SelectKBest(score_func = mutual_info_classif, k=20).fit(X_train, y_train) X_train = selector.transform(X_train) X_test =",
"classification_report print(f'Device {device_id}:') print(classification_report(y_test, estimator.predict(X_test))) report = classification_report(y_test, estimator.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall'])",
"classification_report(y_test, selector.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score']) print(f'Accuracy: {round(np.mean(accuracies), 2)}, precision: {round(np.mean(precisions), 2)},",
"display(full_df.iloc[:, list(range(36, 72)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(72, 108)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:,",
"train_test_split X_train, X_test, y_train, y_test = train_test_split(X_std, y_device, test_size=0.2, random_state = 12369) from",
"print('BalancedRandomForestClassifier') accuracies = [] precisions = [] recalls = [] fscores = []",
"SelectKBest (mutual_info_classif)') accuracies = [] precisions = [] recalls = [] fscores =",
"from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(random_state = 12369, \\ n_estimators = 50,",
"Old database # unlock_data_path = storage_service.download_file(last_run.unlock_data_uri) # full_df: pd.DataFrame = pickle.load(open(unlock_data_path, 'rb')) #",
"{round(np.mean(fscores), 2)}') # %% print('GaussianNB') accuracies = [] precisions = [] recalls =",
"{round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SelectKBest (f_classif)') accuracies =",
"train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.feature_selection import RFE from imblearn.ensemble import",
"== 1) accuracy = (tp + tn) / (tp + tn + fn",
"fn = np.mean(estimator.predict(X_test) == -1) tn = np.mean(estimator.predict(X_non_device) == 1) fp = np.mean(estimator.predict(X_non_device)",
"fscore: {round(np.mean(fscores), 2)}') # %% print('LinearSVC') accuracies = [] precisions = [] recalls",
"y_device, test_size=0.2, random_state = 12369) from imblearn.over_sampling import SMOTE X_oversampled, y_oversampled = SMOTE().fit_resample(X_train,",
"+ [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(108, 144)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(144, 180)) +",
"{round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + RandomOverSampler') accuracies = [] precisions = []",
"device_id] X_device = X.loc[y == device_id, :] X_non_device = X.loc[y != device_id, :]",
"%% print('RandomForestClassifier') accuracies = [] precisions = [] recalls = [] fscores =",
"y_train, y_test = train_test_split(X, y, test_size=0.2, random_state = 12369) from sklearn.ensemble import RandomForestClassifier",
"(df.DeviceId != 7), :].reset_index(drop = True) X, y = df.iloc[:, 0:-1], df.iloc[:, -1]",
"== device_id, 1, 0) from sklearn.preprocessing import StandardScaler X_std = StandardScaler().fit_transform(X) from sklearn.model_selection",
"# 'estimator__criterion': ['gini', 'entropy'] # } from sklearn.model_selection import RandomizedSearchCV param_grid = {",
"not np.isnan(recall) else 0) fscores.append(fscore if not np.isnan(fscore) else 0) print(f'{device_id} - accuracy:",
"test_size=0.2, random_state = 12369) from sklearn.feature_selection import SelectFromModel from sklearn.ensemble import RandomForestClassifier estimator",
"recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier') accuracies = [] precisions",
"12369) from sklearn.feature_selection import SelectKBest, f_classif selector = SelectKBest(score_func = f_classif, k=20).fit(X_train, y_train)",
"2)}') # %% print('Hyperparameter tuning') for device_id in y.unique(): y_device = np.where(y ==",
"= PCA(n_components=20).fit(X_train) X_train = pca.transform(X_train) X_test = pca.transform(X_test) from sklearn.ensemble import RandomForestClassifier estimator",
"train_test_split(X_std, y_device, test_size=0.2, random_state = 12369) from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(random_state",
"selector.fit(X_train, y_train) selector.show() from sklearn.metrics import classification_report print(classification_report(y_test, selector.predict(X_test))) # %% print('RandomForestClassifier +",
"print('IsolationForest') accuracies = [] precisions = [] recalls = [] fscores = []",
"RandomUnderSampler X_oversampled, y_oversampled = RandomUnderSampler().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble import",
"= np.mean(estimator.predict(X_test) == 1) fn = np.mean(estimator.predict(X_test) == -1) tn = np.mean(estimator.predict(X_non_device) ==",
"os.environ['DJANGO_SETTINGS_MODULE'] = 'MAKDataHub.settings' import django django.setup() # %% import math import pickle import",
"72)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(72, 108)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(108, 144))",
"SelectKBest, mutual_info_classif selector = SelectKBest(score_func = mutual_info_classif, k=20).fit(X_train, y_train) X_train = selector.transform(X_train) X_test",
"y = df.iloc[:, 0:-1], df.iloc[:, -1] #%% full_df.shape # %% display(full_df.iloc[:, list(range(36)) +",
"train_test_split X_train, X_test, y_train, y_test = train_test_split(X_device, y_device, test_size=0.2) from sklearn.neighbors import LocalOutlierFactor",
"print(classification_report(y_test, estimator.predict(X_test))) # %% print('RandomForestClassifier - standardized') accuracies = [] precisions = []",
"%% print('KNeighborsClassifier') accuracies = [] precisions = [] recalls = [] fscores =",
"y_test = train_test_split(X_std, y_device, test_size=0.2, random_state = 12369) from sklearn.ensemble import RandomForestClassifier estimator",
"2)}, non-class acc: {round(np.mean(estimator.predict(X_non_device) == -1), 2)}') print(f'Accuracy: {round(np.mean(accuracies), 2)}, precision: {round(np.mean(precisions), 2)},",
"= classification_report(y_test, estimator.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score']) print(f'Accuracy: {round(np.mean(accuracies), 2)}, precision: {round(np.mean(precisions),",
"= True) ## Old database # unlock_data_path = storage_service.download_file(last_run.unlock_data_uri) # full_df: pd.DataFrame =",
"from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10,",
"{round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SMOTEENN') accuracies = [] precisions = []",
"fscore: {round(np.mean(fscores), 2)}') # %% print('Hyperparameter tuning') for device_id in y.unique(): y_device =",
"{ 'estimator__n_estimators': [10, 20, 50, 100], 'estimator__max_features': ['auto', 'sqrt', 'log2'], 'estimator__max_depth': [int(x) for",
"train_test_split(X, y_device, test_size=0.2, random_state = 12369) from imblearn.over_sampling import RandomOverSampler X_oversampled, y_oversampled =",
"7), :].reset_index(drop = True) X, y = df.iloc[:, 0:-1], df.iloc[:, -1] #%% full_df.shape",
"tp = np.mean(estimator.predict(X_test) == 1) fn = np.mean(estimator.predict(X_test) == -1) tn = np.mean(estimator.predict(X_non_device)",
"{round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + RandomOverSampler') accuracies = []",
"y_device, test_size=0.2) from sklearn.svm import OneClassSVM estimator = OneClassSVM(random_state = 12369) estimator.fit_predict(X_train) tp",
"\\ n_iter = 100, \\ cv = 3, \\ verbose = 2, \\",
"%% display(full_df.iloc[:, list(range(36)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(36, 72)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:,",
"0) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y_device, test_size=0.2,",
"estimator = RandomForestClassifier(n_estimators = 10, random_state = 12369) selector = SelectFromModel(estimator, max_features =",
"imblearn.combine import SMOTEENN X_oversampled, y_oversampled = SMOTEENN().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from",
"storage_service.download_file(last_run.unlock_data_uri) # full_df: pd.DataFrame = pickle.load(open(unlock_data_path, 'rb')) # full_df = full_df.loc[full_df.DeviceId != '1439cbc3ad71ac06'].reset_index(drop",
"= 10, random_state = 12369) estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(f'Device {device_id}:')",
"= 12369) estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test, estimator.predict(X_test))) report",
"sklearn.svm import OneClassSVM estimator = OneClassSVM(random_state = 12369) estimator.fit_predict(X_train) tp = np.mean(estimator.predict(X_test) ==",
"fp = np.mean(estimator.predict(X_non_device) == 1) accuracy = (tp + tn) / (tp +",
"12369) from imblearn.under_sampling import RandomUnderSampler X_oversampled, y_oversampled = RandomUnderSampler().fit_resample(X_train, y_train) from sklearn.feature_selection import",
"selector.estimator_.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score']) print(f'Accuracy: {round(np.mean(accuracies), 2)}, precision: {round(np.mean(precisions), 2)}, recall:",
"estimator.predict(X_test))) # %% print('RandomForestClassifier - standardized') accuracies = [] precisions = [] recalls",
"fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + RandomOverSampler') accuracies = [] precisions =",
"7, 8], # 'estimator__criterion': ['gini', 'entropy'] # } from sklearn.model_selection import RandomizedSearchCV param_grid",
"random_state = 12369) from sklearn.svm import LinearSVC estimator = LinearSVC(random_state = 12369) estimator.fit(X_train,",
"print('RandomForestClassifier + RandomOverSampler') accuracies = [] precisions = [] recalls = [] fscores",
"from sklearn.decomposition import PCA pca = PCA(n_components=20).fit(X_train) X_train = pca.transform(X_train) X_test = pca.transform(X_test)",
"{round(precision, 2)}, recall: {round(recall, 2)}') # print(f'{device_id} - Class acc: {round(np.mean(estimator.predict(X_test) == 1),",
"= 12369) from sklearn.neighbors import KNeighborsClassifier estimator = KNeighborsClassifier() estimator.fit(X_train, y_train) from sklearn.metrics",
"GaussianNB() estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test))) report = classification_report(y_test, estimator.predict(X_test),",
"# os.chdir(\"../../..\") os.environ['DJANGO_SETTINGS_MODULE'] = 'MAKDataHub.settings' import django django.setup() # %% import math import",
"# full_df: pd.DataFrame = pickle.load(open(unlock_data_path, 'rb')) # full_df = full_df.loc[full_df.DeviceId != '1439cbc3ad71ac06'].reset_index(drop =",
"%% print('RandomForestClassifier + SMOTEENN') accuracies = [] precisions = [] recalls = []",
"random_state = 12369) from sklearn.decomposition import PCA pca = PCA(n_components=20).fit(X_train) X_train = pca.transform(X_train)",
"hue=\"DeviceId\", vars=[\"AccMgn_mean\", \"AccMgn_median\"], markers='.') # %% test = df.loc[df.DeviceId != '3', :] sns.swarmplot(data",
"y_oversampled = SMOTEENN().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier estimator",
"train_test_split X_train, X_test, y_train, y_test = train_test_split(X_device, y_device, test_size=0.2) from sklearn.svm import OneClassSVM",
"y_device, test_size=0.2, random_state = 12369) from imblearn.combine import SMOTEENN X_oversampled, y_oversampled = SMOTEENN().fit_resample(X_train,",
"{round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SelectKBest (mutual_info_classif)') accuracies =",
"# print(f'{device_id} - Class acc: {round(np.mean(estimator.predict(X_device) == 1), 2)}, non-class acc: {round(np.mean(estimator.predict(X_non_device) ==",
"%% sns.boxplot(df.DeviceId, df.AccMgn_mean) # %% sns.boxplot(df.DeviceId, df.AccMgn_median) # %% sns.boxplot(df.DeviceId, df.GyrMgn_amax) # %%",
"novelty = True, contamination = 'auto') estimator.fit(X_train) tp = np.mean(estimator.predict(X_test) == 1) fn",
"seaborn as sns from MAKDataHub.services import Services profile_service = Services.profile_service() storage_service = Services.storage_service()",
"train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state = 12369) from",
"+ PCA') accuracies = [] precisions = [] recalls = [] fscores =",
"sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10, random_state = 12369) estimator.fit(X_train, y_train)",
"%% print('RandomForestClassifier + SMOTE') accuracies = [] precisions = [] recalls = []",
"y, test_size=0.2, random_state = 12369) from yellowbrick.model_selection import RFECV from sklearn.ensemble import RandomForestClassifier",
"# %% print('RandomForestClassifier + RFECV') from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test",
"list(range(36, 72)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(72, 108)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(108,",
"test_size=0.2) from sklearn.neighbors import LocalOutlierFactor estimator = LocalOutlierFactor(n_neighbors = 10, novelty = True,",
"f_classif selector = SelectKBest(score_func = f_classif, k=20).fit(X_train, y_train) X_train = selector.transform(X_train) X_test =",
"# %% print('RandomForestClassifier + RandomOverSampler') accuracies = [] precisions = [] recalls =",
"test, x=\"DeviceId\", y=\"RotMgn_median\") # %% test = full_df.loc[:, :] sns.boxplot(data = test, x=\"DeviceId\",",
"from sklearn.preprocessing import StandardScaler X_std = StandardScaler().fit_transform(X) from sklearn.model_selection import train_test_split X_train, X_test,",
"{round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('KNeighborsClassifier') accuracies =",
"bootstrap = False, \\ max_features = 'sqrt', \\ max_depth = 20) selector =",
"= [] for device_id in y.unique(): y_device = y[y == device_id] X_device =",
"y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.feature_selection import SelectKBest,",
"[] fscores = [] for device_id in y.unique(): y_device = y[y == device_id]",
"X_test, y_train, y_test = train_test_split(X_device, y_device, test_size=0.2) from sklearn.svm import OneClassSVM estimator =",
"random_state = 12369) from sklearn.feature_selection import SelectFromModel from sklearn.ensemble import RandomForestClassifier estimator =",
"mutual_info_classif, k=20).fit(X_train, y_train) X_train = selector.transform(X_train) X_test = selector.transform(X_test) from sklearn.ensemble import RandomForestClassifier",
"import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state = 12369)",
"= -1) grid.fit(X_oversampled, y_oversampled) print(grid.best_params_) # %% print('RandomForestClassifier + SMOTETomek + parameters') accuracies",
"y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.svm import LinearSVC",
"print('LOF') accuracies = [] precisions = [] recalls = [] fscores = []",
"estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test))) # %% print('RandomForestClassifier - standardized')",
"pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn",
"if not np.isnan(accuracy) else 0) precisions.append(precision if not np.isnan(precision) else 0) recalls.append(recall if",
"sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test, selector.predict(X_test))) report = classification_report(y_test, selector.predict(X_test), output_dict=True) accuracies.append(report['accuracy'])",
"{round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SelectFromModel') accuracies = [] precisions = []",
"y_train, y_test = train_test_split(X_device, y_device, test_size=0.2) from sklearn.svm import OneClassSVM estimator = OneClassSVM(random_state",
"%% print('BalancedRandomForestClassifier') accuracies = [] precisions = [] recalls = [] fscores =",
"[216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(144, 180)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(180, 216)) + [216]].groupby('DeviceId').agg([np.min,",
"2)}, precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('Hyperparameter",
"{round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + RFECV')",
"fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + RandomUnderSampler') accuracies = [] precisions =",
"LocalOutlierFactor(n_neighbors = 10, novelty = True, contamination = 'auto') estimator.fit(X_train) tp = np.mean(estimator.predict(X_test)",
"train_test_split(X, y_device, test_size=0.2, random_state = 12369) from imblearn.over_sampling import SMOTE X_oversampled, y_oversampled =",
"sns.boxplot(df.DeviceId, df.AccMgn_mean) # %% sns.boxplot(df.DeviceId, df.AccMgn_median) # %% sns.boxplot(df.DeviceId, df.GyrMgn_amax) # %% sns.pairplot(df.loc[df.DeviceId",
"print('RandomForestClassifier + SMOTETomek') accuracies = [] precisions = [] recalls = [] fscores",
"= 0.05) selector.fit(X_train, y_train) from sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test, selector.predict(X_test))) report",
"%% print('RandomForestClassifier + RFE20') accuracies = [] precisions = [] recalls = []",
"y_device, test_size=0.2, random_state = 12369) from sklearn.feature_selection import SelectKBest, f_classif selector = SelectKBest(score_func",
"import SelectKBest, f_classif selector = SelectKBest(score_func = f_classif, k=20).fit(X_train, y_train) X_train = selector.transform(X_train)",
"y_train, y_test = train_test_split(X_std, y_device, test_size=0.2, random_state = 12369) from sklearn.ensemble import RandomForestClassifier",
"profile_service.get_last_profile_creation_run() ## New database full_df: pd.DataFrame = pickle.load(last_run.unlock_data.open('rb')) # full_df = full_df.loc[full_df.DeviceId !=",
"import RFE from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(random_state = 12369, \\ n_estimators",
"{round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + PCA')",
"SMOTE') accuracies = [] precisions = [] recalls = [] fscores = []",
"n_estimators = 50, min_samples_leaf = 1, \\ min_samples_split = 2, \\ bootstrap =",
"!= device_id, :] from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X_device,",
"import matplotlib.pyplot as plt import seaborn as sns from MAKDataHub.services import Services profile_service",
"fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + PCA') accuracies = [] precisions =",
"= train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.feature_selection import RFE from sklearn.ensemble",
"np.isnan(fscore) else 0) print(f'{device_id} - accuracy: {round(accuracy, 2)}, precision: {round(precision, 2)}, recall: {round(recall,",
"{round(np.mean(fscores), 2)}') # %% print('BalancedRandomForestClassifier') accuracies = [] precisions = [] recalls =",
"{round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('BalancedRandomForestClassifier') accuracies =",
"10, novelty = True, contamination = 'auto') estimator.fit(X_train) tp = np.mean(estimator.predict(X_test) == 1)",
"== device_id, 1, 0) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test =",
"X_non_device = X.loc[y != device_id, :] from sklearn.model_selection import train_test_split X_train, X_test, y_train,",
"list(range(144, 180)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(180, 216)) + [216]].groupby('DeviceId').agg([np.min, np.max])) # %%",
"pickle import pandas as pd import numpy as np import matplotlib.pyplot as plt",
"fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SMOTETomek') accuracies = [] precisions =",
"X_train, X_test, y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.feature_selection",
"np.max])) display(full_df.iloc[:, list(range(180, 216)) + [216]].groupby('DeviceId').agg([np.min, np.max])) # %% display(full_df.iloc[:, list(range(36)) + [216]].groupby('DeviceId').agg([np.mean]))",
"0.05) selector.fit(X_train, y_train) selector.show() from sklearn.metrics import classification_report print(classification_report(y_test, selector.predict(X_test))) # %% print('RandomForestClassifier",
"display(full_df.iloc[:, list(range(108, 144)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(144, 180)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:,",
"import classification_report print(classification_report(y_test, selector.predict(X_test))) # %% print('RandomForestClassifier + RFE20') accuracies = [] precisions",
"4, 5], 'estimator__min_samples_leaf': [1, 2, 3], 'estimator__bootstrap': [True, False] } grid = RandomizedSearchCV(estimator",
"train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(random_state",
"estimator = IsolationForest(n_estimators = 10) estimator.fit(X_train) tp = np.mean(estimator.predict(X_test) == 1) fn =",
"num = 2)] + [None], 'estimator__min_samples_split': [2, 3, 4, 5], 'estimator__min_samples_leaf': [1, 2,",
"y_train) from sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test))) # %% print('RandomForestClassifier - standardized') accuracies",
"df.loc[(df.DeviceId != 4) & (df.DeviceId != 7), :].reset_index(drop = True) X, y =",
"+ RandomOverSampler') accuracies = [] precisions = [] recalls = [] fscores =",
"'entropy'] # } from sklearn.model_selection import RandomizedSearchCV param_grid = { 'estimator__n_estimators': [10, 20,",
"list(range(180, 216)) + [216]].groupby('DeviceId').agg([np.mean])) # %% sns.boxplot(df.DeviceId, df.AccMgn_mean) # %% sns.boxplot(df.DeviceId, df.AccMgn_median) #",
"random_state = 12369) from imblearn.combine import SMOTETomek X_oversampled, y_oversampled = SMOTETomek().fit_resample(X_train, y_train) from",
"list(range(108, 144)) + list(range(180, 216)) + [216]].reset_index(drop = True) df = df.loc[(df.DeviceId !=",
"= df.loc[(df.DeviceId != 4) & (df.DeviceId != 7), :].reset_index(drop = True) X, y",
"matplotlib.pyplot as plt import seaborn as sns from MAKDataHub.services import Services profile_service =",
"[216]].groupby('DeviceId').agg([np.mean])) # %% sns.boxplot(df.DeviceId, df.AccMgn_mean) # %% sns.boxplot(df.DeviceId, df.AccMgn_median) # %% sns.boxplot(df.DeviceId, df.GyrMgn_amax)",
"sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test))) # %% print('RandomForestClassifier - standardized') accuracies = []",
"estimator = RandomForestClassifier(n_estimators = 10, random_state = 12369) selector = RFECV(estimator, cv =",
"2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier') accuracies = []",
"print(classification_report(y_test, estimator.predict(X_test))) report = classification_report(y_test, estimator.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score']) print(f'Accuracy: {round(np.mean(accuracies),",
"print('RandomForestClassifier - standardized') accuracies = [] precisions = [] recalls = [] fscores",
"from imblearn.combine import SMOTEENN X_oversampled, y_oversampled = SMOTEENN().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE",
"# %% sns.boxplot(df.DeviceId, df.AccMgn_median) # %% sns.boxplot(df.DeviceId, df.GyrMgn_amax) # %% sns.pairplot(df.loc[df.DeviceId != 3,",
"device_id, 1, 0) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X,",
"pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns",
"y_device = np.where(y == device_id, 1, 0) from sklearn.preprocessing import StandardScaler X_std =",
"X_train, X_test, y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.naive_bayes",
"+ [None], 'estimator__min_samples_split': [2, 3, 4, 5], 'estimator__min_samples_leaf': [1, 2, 3], 'estimator__bootstrap': [True,",
"estimator = GaussianNB() estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test))) report =",
"import django django.setup() # %% import math import pickle import pandas as pd",
"random_state = 12369) from sklearn.feature_selection import SelectKBest, f_classif selector = SelectKBest(score_func = f_classif,",
"y.unique(): y_device = np.where(y == device_id, 1, 0) from sklearn.model_selection import train_test_split X_train,",
"2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('BalancedRandomForestClassifier') accuracies = [] precisions = []",
"SMOTETomek().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(random_state",
"device_id in y.unique(): y_device = np.where(y == device_id, 1, 0) from sklearn.model_selection import",
"{round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + RandomUnderSampler') accuracies = []",
"= LinearSVC(random_state = 12369) estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test))) report",
"2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('GaussianNB') accuracies = []",
"= selector, \\ param_distributions = param_grid, \\ n_iter = 100, \\ cv =",
"fscores.append(fscore if not np.isnan(fscore) else 0) print(f'{device_id} - accuracy: {round(accuracy, 2)}, precision: {round(precision,",
"accuracy: {round(accuracy, 2)}, precision: {round(precision, 2)}, recall: {round(recall, 2)}') # print(f'{device_id} - Class",
"sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X_device, y_device, test_size=0.2) from sklearn.ensemble",
"12369) estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test, estimator.predict(X_test))) report =",
"selector.transform(X_test) from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10, random_state = 12369)",
"SMOTETomek X_oversampled, y_oversampled = SMOTETomek().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble import",
"!= 3].reset_index(drop = True) ## Old database # unlock_data_path = storage_service.download_file(last_run.unlock_data_uri) # full_df:",
"X_test, y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.svm import",
"X_train, X_test, y_train, y_test = train_test_split(X_device, y_device, test_size=0.2) from sklearn.neighbors import LocalOutlierFactor estimator",
"y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.naive_bayes import GaussianNB",
"X_test = selector.transform(X_test) from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10, random_state",
"y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.svm import LinearSVC estimator",
"print(grid.best_params_) # %% print('RandomForestClassifier + SMOTETomek + parameters') accuracies = [] precisions =",
"y_device, test_size=0.2, random_state = 12369) from sklearn.naive_bayes import GaussianNB estimator = GaussianNB() estimator.fit(X_train,",
"\\ n_estimators = 50, min_samples_leaf = 1, \\ min_samples_split = 2, \\ bootstrap",
"SelectKBest (f_classif)') accuracies = [] precisions = [] recalls = [] fscores =",
"random_state = 12369) selector = RFE(estimator, n_features_to_select = 20, step = 0.05) selector.fit(X_oversampled,",
"# %% import os import sys # os.chdir(\"../../..\") os.environ['DJANGO_SETTINGS_MODULE'] = 'MAKDataHub.settings' import django",
"# } from sklearn.model_selection import RandomizedSearchCV param_grid = { 'estimator__n_estimators': [10, 20, 50,",
"{round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('GaussianNB') accuracies =",
"3, 4, 5], 'estimator__min_samples_leaf': [1, 2, 3], 'estimator__bootstrap': [True, False] } grid =",
"{round(np.mean(accuracies), 2)}, precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %%",
"precision / (recall + precision) accuracies.append(accuracy if not np.isnan(accuracy) else 0) precisions.append(precision if",
"{round(np.mean(estimator.predict(X_test) == 1), 2)}, non-class acc: {round(np.mean(estimator.predict(X_non_device) == -1), 2)}') print(f'Accuracy: {round(np.mean(accuracies), 2)},",
"y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from imblearn.combine import SMOTETomek",
"y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from imblearn.over_sampling import SMOTE",
"np.where(y == device_id, 1, 0) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test",
"y.unique(): y_device = np.where(y == device_id, 1, 0) from sklearn.preprocessing import StandardScaler X_std",
"y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from imblearn.over_sampling import SMOTE X_oversampled,",
"y=\"GrvMgn_amax\") # %% print('OneClassSVM') accuracies = [] precisions = [] recalls = []",
"== -1), 2)}') print(f'Accuracy: {round(np.mean(accuracies), 2)}, precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore:",
"12369) from sklearn.feature_selection import RFE from imblearn.ensemble import BalancedRandomForestClassifier estimator = BalancedRandomForestClassifier(n_estimators =",
"12369) estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test))) # %% print('RandomForestClassifier -",
"precision: {round(precision, 2)}, recall: {round(recall, 2)}') # print(f'{device_id} - Class acc: {round(np.mean(estimator.predict(X_test) ==",
"%% print('LOF') accuracies = [] precisions = [] recalls = [] fscores =",
"# full_df = full_df.loc[full_df.DeviceId != 3].reset_index(drop = True) ## Old database # unlock_data_path",
"accuracy = (tp + tn) / (tp + tn + fn + fp)",
"y_device, test_size=0.2, random_state = 12369) from imblearn.over_sampling import RandomOverSampler X_oversampled, y_oversampled = RandomOverSampler().fit_resample(X_train,",
"imblearn.over_sampling import RandomOverSampler X_oversampled, y_oversampled = RandomOverSampler().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from",
"-1) tn = np.mean(estimator.predict(X_non_device) == 1) fp = np.mean(estimator.predict(X_non_device) == 1) accuracy =",
"device_id, :] from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X_device, y_device,",
"RandomizedSearchCV(estimator = selector, \\ param_distributions = param_grid, \\ n_iter = 100, \\ cv",
"random_state = 12369) selector = RFE(estimator, n_features_to_select = 20, step = 0.05) selector.fit(X_train,",
"sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X_device, y_device, test_size=0.2) from sklearn.neighbors",
"max_depth = 20) selector = RFE(estimator, n_features_to_select = 20, step = 0.05) selector.fit(X_oversampled,",
"{round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SelectFromModel') accuracies = []",
"y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.ensemble import RandomForestClassifier estimator",
"2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('IsolationForest') accuracies = [] precisions = []",
"2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('KNeighborsClassifier') accuracies = []",
"[] recalls = [] fscores = [] for device_id in y.unique(): y_device =",
"[10, 20, 50, 100], 'estimator__max_features': ['auto', 'sqrt', 'log2'], 'estimator__max_depth': [int(x) for x in",
"= 12369) from imblearn.under_sampling import RandomUnderSampler X_oversampled, y_oversampled = RandomUnderSampler().fit_resample(X_train, y_train) from sklearn.feature_selection",
"y_train, y_test = train_test_split(X_device, y_device, test_size=0.2) from sklearn.neighbors import LocalOutlierFactor estimator = LocalOutlierFactor(n_neighbors",
"estimator = LocalOutlierFactor(n_neighbors = 10, novelty = True, contamination = 'auto') estimator.fit(X_train) tp",
"y_device, test_size=0.2) from sklearn.ensemble import IsolationForest estimator = IsolationForest(n_estimators = 10) estimator.fit(X_train) tp",
"{round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('IsolationForest') accuracies = [] precisions =",
"'estimator__max_depth': [4, 5, 6, 7, 8], # 'estimator__criterion': ['gini', 'entropy'] # } from",
"= 12369) estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test))) # %% print('RandomForestClassifier",
"= KNeighborsClassifier() estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test))) report = classification_report(y_test,",
"param_grid = { # 'estimator__n_estimators': [10, 50, 100, 200, 500], # 'estimator__max_features': ['auto',",
"step = 0.05) # from sklearn.model_selection import GridSearchCV # param_grid = { #",
"y_device, test_size=0.2, random_state = 12369) from sklearn.neighbors import KNeighborsClassifier estimator = KNeighborsClassifier() estimator.fit(X_train,",
"12369) estimator.fit_predict(X_train) tp = np.mean(estimator.predict(X_test) == 1) fn = np.mean(estimator.predict(X_test) == -1) tn",
"full_df = full_df.loc[full_df.DeviceId != '1439cbc3ad71ac06'].reset_index(drop = True) # %% df = full_df.iloc[:, list(range(36))",
"sklearn.decomposition import PCA pca = PCA(n_components=20).fit(X_train) X_train = pca.transform(X_train) X_test = pca.transform(X_test) from",
"= RandomForestClassifier(random_state = 12369, \\ n_estimators = 50, min_samples_leaf = 1, \\ min_samples_split",
"True) # %% df = full_df.iloc[:, list(range(36)) + list(range(72, 108)) + list(range(108, 144))",
"180)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(180, 216)) + [216]].groupby('DeviceId').agg([np.min, np.max])) # %% display(full_df.iloc[:,",
"%% print('RandomForestClassifier + SMOTETomek + parameters') accuracies = [] precisions = [] recalls",
"SMOTE().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators",
"X_test = pca.transform(X_test) from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10, random_state",
"+ [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(180, 216)) + [216]].groupby('DeviceId').agg([np.mean])) # %% sns.boxplot(df.DeviceId, df.AccMgn_mean) # %%",
"12369) from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(random_state = 12369) estimator.fit(X_train, y_train) from",
"2)}') # %% print('RandomForestClassifier + SelectKBest (mutual_info_classif)') accuracies = [] precisions = []",
"acc: {round(np.mean(estimator.predict(X_test) == 1), 2)}, non-class acc: {round(np.mean(estimator.predict(X_non_device) == -1), 2)}') print(f'Accuracy: {round(np.mean(accuracies),",
"= 'auto') estimator.fit(X_train) tp = np.mean(estimator.predict(X_test) == 1) fn = np.mean(estimator.predict(X_test) == -1)",
"= 20) selector.fit(X_train, y_train) from sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test, selector.estimator_.predict(X_test))) report",
"%% print('RandomForestClassifier + SelectKBest (f_classif)') accuracies = [] precisions = [] recalls =",
"np.linspace(2, 20, num = 2)] + [None], 'estimator__min_samples_split': [2, 3, 4, 5], 'estimator__min_samples_leaf':",
"full_df.shape # %% display(full_df.iloc[:, list(range(36)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(36, 72)) + [216]].groupby('DeviceId').agg([np.min,",
"2)}') # %% print('RandomForestClassifier + SMOTE') accuracies = [] precisions = [] recalls",
"= train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.decomposition import PCA pca =",
"= RandomForestClassifier(n_estimators = 10, random_state = 12369) selector = RFE(estimator, n_features_to_select = 20,",
"= 20, step = 0.05) # from sklearn.model_selection import GridSearchCV # param_grid =",
"+ tn) / (tp + tn + fn + fp) precision = tp",
"y_test = train_test_split(X, y, test_size=0.2, random_state = 12369) from sklearn.ensemble import RandomForestClassifier estimator",
"{round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + RandomUnderSampler') accuracies = [] precisions = []",
"RFECV(estimator, cv = 5, scoring='f1_weighted', step = 0.05) selector.fit(X_train, y_train) selector.show() from sklearn.metrics",
"= 12369) from sklearn.naive_bayes import GaussianNB estimator = GaussianNB() estimator.fit(X_train, y_train) from sklearn.metrics",
"from sklearn.neighbors import KNeighborsClassifier estimator = KNeighborsClassifier() estimator.fit(X_train, y_train) from sklearn.metrics import classification_report",
"# %% print('RandomForestClassifier + SelectKBest (mutual_info_classif)') accuracies = [] precisions = [] recalls",
"from sklearn.svm import OneClassSVM estimator = OneClassSVM(random_state = 12369) estimator.fit_predict(X_train) tp = np.mean(estimator.predict(X_test)",
"math import pickle import pandas as pd import numpy as np import matplotlib.pyplot",
"estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test))) report = classification_report(y_test, estimator.predict(X_test), output_dict=True)",
"= param_grid, \\ n_iter = 100, \\ cv = 3, \\ verbose =",
"SMOTEENN().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators",
"test = df.loc[df.DeviceId != '3', :] sns.swarmplot(data = test, x=\"DeviceId\", y=\"RotMgn_median\") # %%",
"= 3, \\ verbose = 2, \\ random_state = 42, \\ n_jobs =",
"display(full_df.iloc[:, list(range(36, 72)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(72, 108)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(108, 144))",
"[216]].reset_index(drop = True) df = df.loc[(df.DeviceId != 4) & (df.DeviceId != 7), :].reset_index(drop",
"= RFE(estimator, n_features_to_select = 20, step = 0.05) selector.fit(X_oversampled, y_oversampled) from sklearn.metrics import",
"device_id in y.unique(): y_device = y[y == device_id] X_device = X.loc[y == device_id,",
"= GaussianNB() estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test))) report = classification_report(y_test,",
"f_classif, k=20).fit(X_train, y_train) X_train = selector.transform(X_train) X_test = selector.transform(X_test) from sklearn.ensemble import RandomForestClassifier",
"n_iter = 100, \\ cv = 3, \\ verbose = 2, \\ random_state",
"y_device, test_size=0.2) from sklearn.neighbors import LocalOutlierFactor estimator = LocalOutlierFactor(n_neighbors = 10, novelty =",
"6, 7, 8], # 'estimator__criterion': ['gini', 'entropy'] # } from sklearn.model_selection import RandomizedSearchCV",
"= train_test_split(X, y, test_size=0.2, random_state = 12369) from sklearn.ensemble import RandomForestClassifier estimator =",
"%% print('GaussianNB') accuracies = [] precisions = [] recalls = [] fscores =",
"recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('BalancedRandomForestClassifier') accuracies = [] precisions",
"[216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(180, 216)) + [216]].groupby('DeviceId').agg([np.mean])) # %% sns.boxplot(df.DeviceId, df.AccMgn_mean) # %% sns.boxplot(df.DeviceId,",
"= train_test_split(X, y_device, test_size=0.2, random_state = 12369) from imblearn.over_sampling import SMOTE X_oversampled, y_oversampled",
"2, \\ bootstrap = False, \\ max_features = 'sqrt', \\ max_depth = 20)",
"Services profile_service = Services.profile_service() storage_service = Services.storage_service() last_run = profile_service.get_last_profile_creation_run() ## New database",
"{round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + RandomUnderSampler')",
"y_device, test_size=0.2, random_state = 12369) from sklearn.svm import LinearSVC estimator = LinearSVC(random_state =",
"108)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(108, 144)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(144, 180)) + [216]].groupby('DeviceId').agg([np.mean]))",
"y_train) selector.show() from sklearn.metrics import classification_report print(classification_report(y_test, selector.predict(X_test))) # %% print('RandomForestClassifier + RFE20')",
"2)}') print(f'Accuracy: {round(np.mean(accuracies), 2)}, precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}')",
"estimator.predict(X_test))) report = classification_report(y_test, estimator.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score']) print(f'Accuracy: {round(np.mean(accuracies), 2)},",
"classification_report(y_test, selector.estimator_.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score']) print(f'Accuracy: {round(np.mean(accuracies), 2)}, precision: {round(np.mean(precisions), 2)},",
"y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from imblearn.under_sampling import RandomUnderSampler",
"= RandomOverSampler().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier estimator =",
"import SelectKBest, mutual_info_classif selector = SelectKBest(score_func = mutual_info_classif, k=20).fit(X_train, y_train) X_train = selector.transform(X_train)",
"X_oversampled, y_oversampled = RandomUnderSampler().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier",
"plt import seaborn as sns from MAKDataHub.services import Services profile_service = Services.profile_service() storage_service",
"X_train, X_test, y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from imblearn.over_sampling",
"2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('LinearSVC') accuracies = []",
"= 10, novelty = True, contamination = 'auto') estimator.fit(X_train) tp = np.mean(estimator.predict(X_test) ==",
"y_oversampled) from sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test, selector.predict(X_test))) report = classification_report(y_test, selector.predict(X_test),",
"import sys # os.chdir(\"../../..\") os.environ['DJANGO_SETTINGS_MODULE'] = 'MAKDataHub.settings' import django django.setup() # %% import",
"import RandomOverSampler X_oversampled, y_oversampled = RandomOverSampler().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble",
"\\ max_depth = 20) selector = RFE(estimator, n_features_to_select = 20, step = 0.05)",
"== 1) fn = np.mean(estimator.predict(X_test) == -1) tn = np.mean(estimator.predict(X_non_device) == 1) fp",
"sklearn.feature_selection import SelectKBest, f_classif selector = SelectKBest(score_func = f_classif, k=20).fit(X_train, y_train) X_train =",
"random_state = 12369) from sklearn.feature_selection import SelectKBest, mutual_info_classif selector = SelectKBest(score_func = mutual_info_classif,",
"+ [216]].reset_index(drop = True) df = df.loc[(df.DeviceId != 4) & (df.DeviceId != 7),",
"[216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(108, 144)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(144, 180)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(180,",
"= tp / (tp + fp) recall = tp / (tp + fn)",
"from sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test, selector.predict(X_test))) report = classification_report(y_test, selector.predict(X_test), output_dict=True)",
"20, step = 0.05) selector.fit(X_train, y_train) from sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test,",
"= 100, \\ cv = 3, \\ verbose = 2, \\ random_state =",
"np.mean(estimator.predict(X_non_device) == 1) fp = np.mean(estimator.predict(X_non_device) == 1) accuracy = (tp + tn)",
"144)) + list(range(180, 216)) + [216]].reset_index(drop = True) df = df.loc[(df.DeviceId != 4)",
"from imblearn.combine import SMOTETomek X_oversampled, y_oversampled = SMOTETomek().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE",
"{round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('KNeighborsClassifier') accuracies = [] precisions =",
"{round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SMOTETomek') accuracies = []",
"PCA pca = PCA(n_components=20).fit(X_train) X_train = pca.transform(X_train) X_test = pca.transform(X_test) from sklearn.ensemble import",
"import classification_report print(f'Device {device_id}:') print(classification_report(y_test, estimator.predict(X_test))) report = classification_report(y_test, estimator.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision'])",
"20) selector = RFE(estimator, n_features_to_select = 20, step = 0.05) # from sklearn.model_selection",
"= SelectFromModel(estimator, max_features = 20) selector.fit(X_train, y_train) from sklearn.metrics import classification_report print(f'Device {device_id}:')",
"1, 0) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y_device,",
"RandomOverSampler X_oversampled, y_oversampled = RandomOverSampler().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble import",
"12369) from sklearn.neighbors import KNeighborsClassifier estimator = KNeighborsClassifier() estimator.fit(X_train, y_train) from sklearn.metrics import",
"y_device, test_size=0.2, random_state = 12369) from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(random_state =",
"# %% print('RandomForestClassifier') accuracies = [] precisions = [] recalls = [] fscores",
"x in np.linspace(2, 20, num = 2)] + [None], 'estimator__min_samples_split': [2, 3, 4,",
"12369, \\ n_estimators = 50, min_samples_leaf = 1, \\ min_samples_split = 2, \\",
"= train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.feature_selection import SelectKBest, mutual_info_classif selector",
"selector.show() from sklearn.metrics import classification_report print(classification_report(y_test, selector.predict(X_test))) # %% print('RandomForestClassifier + RFE20') accuracies",
"y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from imblearn.under_sampling import RandomUnderSampler X_oversampled,",
"import pickle import pandas as pd import numpy as np import matplotlib.pyplot as",
"y_device, test_size=0.2, random_state = 12369) from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier",
"precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier +",
"= train_test_split(X_device, y_device, test_size=0.2) from sklearn.neighbors import LocalOutlierFactor estimator = LocalOutlierFactor(n_neighbors = 10,",
"fn) fscore = 2 * recall * precision / (recall + precision) accuracies.append(accuracy",
"{round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier') accuracies =",
"in y.unique(): y_device = np.where(y == device_id, 1, 0) from sklearn.model_selection import train_test_split",
"%% print('OneClassSVM') accuracies = [] precisions = [] recalls = [] fscores =",
":] from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X_device, y_device, test_size=0.2)",
"= np.where(y == device_id, 1, 0) from sklearn.preprocessing import StandardScaler X_std = StandardScaler().fit_transform(X)",
"10, random_state = 12369) selector = RFECV(estimator, cv = 5, scoring='f1_weighted', step =",
"/ (recall + precision) accuracies.append(accuracy if not np.isnan(accuracy) else 0) precisions.append(precision if not",
"np.mean(estimator.predict(X_test) == 1) fn = np.mean(estimator.predict(X_test) == -1) tn = np.mean(estimator.predict(X_non_device) == 1)",
"import RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10, random_state = 12369) estimator.fit(X_train, y_train) from",
"2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SelectKBest (mutual_info_classif)')",
"test_size=0.2, random_state = 12369) from sklearn.feature_selection import SelectKBest, mutual_info_classif selector = SelectKBest(score_func =",
"[True, False] } grid = RandomizedSearchCV(estimator = selector, \\ param_distributions = param_grid, \\",
"= 12369) selector = SelectFromModel(estimator, max_features = 20) selector.fit(X_train, y_train) from sklearn.metrics import",
"RandomForestClassifier(n_estimators = 10, random_state = 12369) selector = RFE(estimator, n_features_to_select = 20, step",
"sklearn.model_selection import GridSearchCV # param_grid = { # 'estimator__n_estimators': [10, 50, 100, 200,",
"# full_df = full_df.loc[full_df.DeviceId != '1439cbc3ad71ac06'].reset_index(drop = True) # %% df = full_df.iloc[:,",
"{round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SMOTEENN')",
"selector = SelectKBest(score_func = f_classif, k=20).fit(X_train, y_train) X_train = selector.transform(X_train) X_test = selector.transform(X_test)",
"import KNeighborsClassifier estimator = KNeighborsClassifier() estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test)))",
"from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state",
"acc: {round(np.mean(estimator.predict(X_device) == 1), 2)}, non-class acc: {round(np.mean(estimator.predict(X_non_device) == -1), 2)}') print(f'Accuracy: {round(np.mean(accuracies),",
"%% print('IsolationForest') accuracies = [] precisions = [] recalls = [] fscores =",
"list(range(36)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(36, 72)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(72, 108)) + [216]].groupby('DeviceId').agg([np.mean]))",
"%% print('RandomForestClassifier - global model') from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test",
"accuracies.append(accuracy if not np.isnan(accuracy) else 0) precisions.append(precision if not np.isnan(precision) else 0) recalls.append(recall",
"import os import sys # os.chdir(\"../../..\") os.environ['DJANGO_SETTINGS_MODULE'] = 'MAKDataHub.settings' import django django.setup() #",
"{round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SelectKBest (mutual_info_classif)') accuracies = [] precisions =",
"2)}') # %% print('RandomForestClassifier - global model') from sklearn.model_selection import train_test_split X_train, X_test,",
"train_test_split(X_device, y_device, test_size=0.2) from sklearn.ensemble import IsolationForest estimator = IsolationForest(n_estimators = 10) estimator.fit(X_train)",
"12369) selector = RFE(estimator, n_features_to_select = 20, step = 0.05) selector.fit(X_train, y_train) from",
"X_test, y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.feature_selection import",
"+ SMOTE') accuracies = [] precisions = [] recalls = [] fscores =",
"RandomUnderSampler().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators",
"fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier') accuracies = [] precisions = [] recalls",
"RFECV') from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,",
"y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.feature_selection import SelectFromModel from",
"test_size=0.2, random_state = 12369) from sklearn.svm import LinearSVC estimator = LinearSVC(random_state = 12369)",
"= 2 * recall * precision / (recall + precision) accuracies.append(accuracy if not",
"np.where(y == device_id, 1, 0) from sklearn.preprocessing import StandardScaler X_std = StandardScaler().fit_transform(X) from",
"np.max])) display(full_df.iloc[:, list(range(108, 144)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(144, 180)) + [216]].groupby('DeviceId').agg([np.min, np.max]))",
"RFE(estimator, n_features_to_select = 20, step = 0.05) selector.fit(X_oversampled, y_oversampled) from sklearn.metrics import classification_report",
"2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SMOTEENN') accuracies = [] precisions",
"recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('KNeighborsClassifier') accuracies = [] precisions",
"2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + RandomOverSampler') accuracies",
"%% print('RandomForestClassifier + PCA') accuracies = [] precisions = [] recalls = []",
"sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10, random_state = 12369) selector =",
"recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SMOTEENN') accuracies =",
"+ fp) precision = tp / (tp + fp) recall = tp /",
"y_train, y_test = train_test_split(X, y, test_size=0.2, random_state = 12369) from yellowbrick.model_selection import RFECV",
"[216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(180, 216)) + [216]].groupby('DeviceId').agg([np.min, np.max])) # %% display(full_df.iloc[:, list(range(36)) +",
"y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from imblearn.over_sampling import RandomOverSampler",
"IsolationForest estimator = IsolationForest(n_estimators = 10) estimator.fit(X_train) tp = np.mean(estimator.predict(X_test) == 1) fn",
"= X.loc[y != device_id, :] from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test",
"!= '1439cbc3ad71ac06'].reset_index(drop = True) # %% df = full_df.iloc[:, list(range(36)) + list(range(72, 108))",
"classification_report print(classification_report(y_test, selector.predict(X_test))) # %% print('RandomForestClassifier + RFE20') accuracies = [] precisions =",
"markers='.') # %% test = df.loc[df.DeviceId != '3', :] sns.swarmplot(data = test, x=\"DeviceId\",",
"= 50, min_samples_leaf = 1, \\ min_samples_split = 2, \\ bootstrap = False,",
"from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(random_state = 12369) estimator.fit(X_train, y_train) from sklearn.metrics",
"3].reset_index(drop = True) ## Old database # unlock_data_path = storage_service.download_file(last_run.unlock_data_uri) # full_df: pd.DataFrame",
"+ [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(144, 180)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(180, 216)) +",
"2 * recall * precision / (recall + precision) accuracies.append(accuracy if not np.isnan(accuracy)",
"accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score']) print(f'Accuracy: {round(np.mean(accuracies), 2)}, precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)},",
"# %% display(full_df.iloc[:, list(range(36)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(36, 72)) + [216]].groupby('DeviceId').agg([np.min, np.max]))",
"test_size=0.2, random_state = 12369) from imblearn.combine import SMOTETomek X_oversampled, y_oversampled = SMOTETomek().fit_resample(X_train, y_train)",
"print('KNeighborsClassifier') accuracies = [] precisions = [] recalls = [] fscores = []",
"full_df.loc[:, :] sns.boxplot(data = test, x=\"DeviceId\", y=\"GrvMgn_amax\") # %% print('OneClassSVM') accuracies = []",
"n_jobs = -1) grid.fit(X_oversampled, y_oversampled) print(grid.best_params_) # %% print('RandomForestClassifier + SMOTETomek + parameters')",
"= (tp + tn) / (tp + tn + fn + fp) precision",
"print('RandomForestClassifier') accuracies = [] precisions = [] recalls = [] fscores = []",
"X_test, y_train, y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.ensemble import",
"model') from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,",
"X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state = 12369) from sklearn.ensemble import",
"np.mean(estimator.predict(X_non_device) == 1) accuracy = (tp + tn) / (tp + tn +",
"from sklearn.feature_selection import RFE from imblearn.ensemble import BalancedRandomForestClassifier estimator = BalancedRandomForestClassifier(n_estimators = 10,",
"{round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SMOTE')",
"sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(random_state = 12369, \\ n_estimators = 50, min_samples_leaf",
"2)}') # %% print('BalancedRandomForestClassifier') accuracies = [] precisions = [] recalls = []",
"False, \\ max_features = 'sqrt', \\ max_depth = 20) selector = RFE(estimator, n_features_to_select",
"np.isnan(precision) else 0) recalls.append(recall if not np.isnan(recall) else 0) fscores.append(fscore if not np.isnan(fscore)",
"sys # os.chdir(\"../../..\") os.environ['DJANGO_SETTINGS_MODULE'] = 'MAKDataHub.settings' import django django.setup() # %% import math",
"# %% print('LinearSVC') accuracies = [] precisions = [] recalls = [] fscores",
"# %% print('RandomForestClassifier + SMOTEENN') accuracies = [] precisions = [] recalls =",
"recall: {round(recall, 2)}') # print(f'{device_id} - Class acc: {round(np.mean(estimator.predict(X_device) == 1), 2)}, non-class",
"{round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('LinearSVC') accuracies = [] precisions =",
"= 1, \\ min_samples_split = 2, \\ bootstrap = False, \\ max_features =",
"precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('Hyperparameter tuning')",
"RandomForestClassifier(random_state = 12369) estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(classification_report(y_test, estimator.predict(X_test))) report =",
"print(classification_report(y_test, selector.predict(X_test))) # %% print('RandomForestClassifier + RFE20') accuracies = [] precisions = []",
"print('RandomForestClassifier + SMOTEENN') accuracies = [] precisions = [] recalls = [] fscores",
"%% print('RandomForestClassifier + RandomUnderSampler') accuracies = [] precisions = [] recalls = []",
"import classification_report print(f'Device {device_id}:') print(classification_report(y_test, selector.estimator_.predict(X_test))) report = classification_report(y_test, selector.estimator_.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision'])",
"+ list(range(72, 108)) + list(range(108, 144)) + list(range(180, 216)) + [216]].reset_index(drop = True)",
"{round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SMOTE') accuracies = []",
"0:-1], df.iloc[:, -1] #%% full_df.shape # %% display(full_df.iloc[:, list(range(36)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:,",
"= train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.neighbors import KNeighborsClassifier estimator =",
"['gini', 'entropy'] # } from sklearn.model_selection import RandomizedSearchCV param_grid = { 'estimator__n_estimators': [10,",
"not np.isnan(precision) else 0) recalls.append(recall if not np.isnan(recall) else 0) fscores.append(fscore if not",
"100, \\ cv = 3, \\ verbose = 2, \\ random_state = 42,",
"'estimator__n_estimators': [10, 20, 50, 100], 'estimator__max_features': ['auto', 'sqrt', 'log2'], 'estimator__max_depth': [int(x) for x",
"!= 3, :], hue=\"DeviceId\", vars=[\"AccMgn_mean\", \"AccMgn_median\"], markers='.') # %% test = df.loc[df.DeviceId !=",
"print('RandomForestClassifier + SelectKBest (mutual_info_classif)') accuracies = [] precisions = [] recalls = []",
"{round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('Hyperparameter tuning') for device_id in y.unique():",
"import RandomUnderSampler X_oversampled, y_oversampled = RandomUnderSampler().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble",
"train_test_split(X_device, y_device, test_size=0.2) from sklearn.neighbors import LocalOutlierFactor estimator = LocalOutlierFactor(n_neighbors = 10, novelty",
"precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score']) print(f'Accuracy: {round(np.mean(accuracies), 2)}, precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore:",
"train_test_split(X, y_device, test_size=0.2, random_state = 12369) from imblearn.under_sampling import RandomUnderSampler X_oversampled, y_oversampled =",
"y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.naive_bayes import GaussianNB estimator",
"= 'sqrt', \\ max_depth = 20) selector = RFE(estimator, n_features_to_select = 20, step",
"= SMOTEENN().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier estimator =",
"= RFE(estimator, n_features_to_select = 20, step = 0.05) # from sklearn.model_selection import GridSearchCV",
"8], # 'estimator__criterion': ['gini', 'entropy'] # } from sklearn.model_selection import RandomizedSearchCV param_grid =",
"from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(random_state = 12369,",
"\\ bootstrap = False, \\ max_features = 'sqrt', \\ max_depth = 20) selector",
"0) precisions.append(precision if not np.isnan(precision) else 0) recalls.append(recall if not np.isnan(recall) else 0)",
"print(classification_report(y_test, selector.estimator_.predict(X_test))) report = classification_report(y_test, selector.estimator_.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score']) print(f'Accuracy: {round(np.mean(accuracies),",
"2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SelectKBest (f_classif)')",
"[] fscores = [] for device_id in y.unique(): y_device = np.where(y == device_id,",
"not np.isnan(accuracy) else 0) precisions.append(precision if not np.isnan(precision) else 0) recalls.append(recall if not",
"test_size=0.2, random_state = 12369) from imblearn.over_sampling import SMOTE X_oversampled, y_oversampled = SMOTE().fit_resample(X_train, y_train)",
"y_test = train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.neighbors import KNeighborsClassifier estimator",
"random_state = 12369) from sklearn.neighbors import KNeighborsClassifier estimator = KNeighborsClassifier() estimator.fit(X_train, y_train) from",
"train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.naive_bayes import GaussianNB estimator = GaussianNB()",
"= True) # %% df = full_df.iloc[:, list(range(36)) + list(range(72, 108)) + list(range(108,",
"random_state = 42, \\ n_jobs = -1) grid.fit(X_oversampled, y_oversampled) print(grid.best_params_) # %% print('RandomForestClassifier",
"print('Hyperparameter tuning') for device_id in y.unique(): y_device = np.where(y == device_id, 1, 0)",
"accuracies = [] precisions = [] recalls = [] fscores = [] for",
"np.max])) display(full_df.iloc[:, list(range(36, 72)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(72, 108)) + [216]].groupby('DeviceId').agg([np.min, np.max]))",
"# %% sns.pairplot(df.loc[df.DeviceId != 3, :], hue=\"DeviceId\", vars=[\"AccMgn_mean\", \"AccMgn_median\"], markers='.') # %% test",
"tp / (tp + fn) fscore = 2 * recall * precision /",
"recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SMOTE') accuracies =",
"grid.fit(X_oversampled, y_oversampled) print(grid.best_params_) # %% print('RandomForestClassifier + SMOTETomek + parameters') accuracies = []",
"[216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(36, 72)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(72, 108)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(108,",
"random_state = 12369) selector = RFECV(estimator, cv = 5, scoring='f1_weighted', step = 0.05)",
"# unlock_data_path = storage_service.download_file(last_run.unlock_data_uri) # full_df: pd.DataFrame = pickle.load(open(unlock_data_path, 'rb')) # full_df =",
"= train_test_split(X, y, test_size=0.2, random_state = 12369) from yellowbrick.model_selection import RFECV from sklearn.ensemble",
"= False, \\ max_features = 'sqrt', \\ max_depth = 20) selector = RFE(estimator,",
"= X.loc[y == device_id, :] X_non_device = X.loc[y != device_id, :] from sklearn.model_selection",
"test_size=0.2, random_state = 12369) from sklearn.naive_bayes import GaussianNB estimator = GaussianNB() estimator.fit(X_train, y_train)",
"{round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier') accuracies = [] precisions =",
"selector.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score']) print(f'Accuracy: {round(np.mean(accuracies), 2)}, precision: {round(np.mean(precisions), 2)}, recall:",
"Services.storage_service() last_run = profile_service.get_last_profile_creation_run() ## New database full_df: pd.DataFrame = pickle.load(last_run.unlock_data.open('rb')) # full_df",
":] X_non_device = X.loc[y != device_id, :] from sklearn.model_selection import train_test_split X_train, X_test,",
"/ (tp + tn + fn + fp) precision = tp / (tp",
"2)}, precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('BalancedRandomForestClassifier')",
"RandomForestClassifier estimator = RandomForestClassifier(random_state = 12369) estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(classification_report(y_test,",
"%% import os import sys # os.chdir(\"../../..\") os.environ['DJANGO_SETTINGS_MODULE'] = 'MAKDataHub.settings' import django django.setup()",
"precision: {round(np.mean(precisions), 2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('IsolationForest') accuracies",
"train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.feature_selection import SelectKBest, f_classif selector =",
"X.loc[y != device_id, :] from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test =",
"from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X_std, y_device, test_size=0.2, random_state",
"device_id in y.unique(): y_device = np.where(y == device_id, 1, 0) from sklearn.preprocessing import",
"1) accuracy = (tp + tn) / (tp + tn + fn +",
"[] for device_id in y.unique(): y_device = y[y == device_id] X_device = X.loc[y",
"import OneClassSVM estimator = OneClassSVM(random_state = 12369) estimator.fit_predict(X_train) tp = np.mean(estimator.predict(X_test) == 1)",
"contamination = 'auto') estimator.fit(X_train) tp = np.mean(estimator.predict(X_test) == 1) fn = np.mean(estimator.predict(X_test) ==",
"RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10, random_state = 12369) estimator.fit(X_train, y_train) from sklearn.metrics",
"import GridSearchCV # param_grid = { # 'estimator__n_estimators': [10, 50, 100, 200, 500],",
"= 12369) from imblearn.over_sampling import SMOTE X_oversampled, y_oversampled = SMOTE().fit_resample(X_train, y_train) from sklearn.feature_selection",
"'sqrt', 'log2'], 'estimator__max_depth': [int(x) for x in np.linspace(2, 20, num = 2)] +",
"list(range(144, 180)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(180, 216)) + [216]].groupby('DeviceId').agg([np.mean])) # %% sns.boxplot(df.DeviceId, df.AccMgn_mean)",
"= [] recalls = [] fscores = [] for device_id in y.unique(): y_device",
"SelectKBest, f_classif selector = SelectKBest(score_func = f_classif, k=20).fit(X_train, y_train) X_train = selector.transform(X_train) X_test",
"print(f'{device_id} - Class acc: {round(np.mean(estimator.predict(X_device) == 1), 2)}, non-class acc: {round(np.mean(estimator.predict(X_non_device) == -1),",
"full_df.iloc[:, list(range(36)) + list(range(72, 108)) + list(range(108, 144)) + list(range(180, 216)) + [216]].reset_index(drop",
"train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.svm import LinearSVC estimator = LinearSVC(random_state",
"= train_test_split(X, y_device, test_size=0.2, random_state = 12369) from imblearn.under_sampling import RandomUnderSampler X_oversampled, y_oversampled",
"y_train) from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators =",
"= np.mean(estimator.predict(X_non_device) == 1) accuracy = (tp + tn) / (tp + tn",
"GridSearchCV # param_grid = { # 'estimator__n_estimators': [10, 50, 100, 200, 500], #",
"sns.boxplot(df.DeviceId, df.AccMgn_median) # %% sns.boxplot(df.DeviceId, df.GyrMgn_amax) # %% sns.pairplot(df.loc[df.DeviceId != 3, :], hue=\"DeviceId\",",
"test_size=0.2, random_state = 12369) from sklearn.neighbors import KNeighborsClassifier estimator = KNeighborsClassifier() estimator.fit(X_train, y_train)",
"-1] #%% full_df.shape # %% display(full_df.iloc[:, list(range(36)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(36, 72))",
"from sklearn.naive_bayes import GaussianNB estimator = GaussianNB() estimator.fit(X_train, y_train) from sklearn.metrics import classification_report",
"min_samples_leaf = 1, \\ min_samples_split = 2, \\ bootstrap = False, \\ max_features",
"!= 4) & (df.DeviceId != 7), :].reset_index(drop = True) X, y = df.iloc[:,",
"# %% print('RandomForestClassifier + SMOTETomek + parameters') accuracies = [] precisions = []",
"y_train) from sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test, selector.predict(X_test))) report = classification_report(y_test, selector.predict(X_test),",
"estimator = RandomForestClassifier(random_state = 12369, \\ n_estimators = 50, min_samples_leaf = 1, \\",
"- global model') from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X,",
"= 20, step = 0.05) selector.fit(X_train, y_train) from sklearn.metrics import classification_report print(f'Device {device_id}:')",
"pca.transform(X_test) from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10, random_state = 12369)",
"PCA') accuracies = [] precisions = [] recalls = [] fscores = []",
"full_df: pd.DataFrame = pickle.load(open(unlock_data_path, 'rb')) # full_df = full_df.loc[full_df.DeviceId != '1439cbc3ad71ac06'].reset_index(drop = True)",
"2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('LOF') accuracies = [] precisions = []",
"= train_test_split(X, y_device, test_size=0.2, random_state = 12369) from imblearn.combine import SMOTEENN X_oversampled, y_oversampled",
"== device_id] X_device = X.loc[y == device_id, :] X_non_device = X.loc[y != device_id,",
"print('RandomForestClassifier + RFECV') from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X,",
"recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + PCA') accuracies =",
"2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + RandomUnderSampler') accuracies",
"= full_df.iloc[:, list(range(36)) + list(range(72, 108)) + list(range(108, 144)) + list(range(180, 216)) +",
"\\ max_features = 'sqrt', \\ max_depth = 20) selector = RFE(estimator, n_features_to_select =",
"0) print(f'{device_id} - accuracy: {round(accuracy, 2)}, precision: {round(precision, 2)}, recall: {round(recall, 2)}') #",
"fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SMOTEENN') accuracies = [] precisions =",
"# 'estimator__max_depth': [4, 5, 6, 7, 8], # 'estimator__criterion': ['gini', 'entropy'] # }",
"device_id, 1, 0) from sklearn.preprocessing import StandardScaler X_std = StandardScaler().fit_transform(X) from sklearn.model_selection import",
"precisions.append(precision if not np.isnan(precision) else 0) recalls.append(recall if not np.isnan(recall) else 0) fscores.append(fscore",
"RandomForestClassifier estimator = RandomForestClassifier(random_state = 12369, \\ n_estimators = 50, min_samples_leaf = 1,",
"for device_id in y.unique(): y_device = np.where(y == device_id, 1, 0) from sklearn.model_selection",
"train_test_split(X, y_device, test_size=0.2, random_state = 12369) from sklearn.decomposition import PCA pca = PCA(n_components=20).fit(X_train)",
"(tp + fn) fscore = 2 * recall * precision / (recall +",
"[216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(108, 144)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(144, 180)) + [216]].groupby('DeviceId').agg([np.min,",
"y_test = train_test_split(X_device, y_device, test_size=0.2) from sklearn.neighbors import LocalOutlierFactor estimator = LocalOutlierFactor(n_neighbors =",
"import RandomForestClassifier estimator = RandomForestClassifier(random_state = 12369, \\ n_estimators = 50, min_samples_leaf =",
"X.loc[y == device_id, :] X_non_device = X.loc[y != device_id, :] from sklearn.model_selection import",
"%% test = df.loc[df.DeviceId != '3', :] sns.swarmplot(data = test, x=\"DeviceId\", y=\"RotMgn_median\") #",
"144)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(144, 180)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(180, 216))",
"import RFECV from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10, random_state =",
"+ fp) recall = tp / (tp + fn) fscore = 2 *",
"2)}') # print(f'{device_id} - Class acc: {round(np.mean(estimator.predict(X_device) == 1), 2)}, non-class acc: {round(np.mean(estimator.predict(X_non_device)",
"5, 6, 7, 8], # 'estimator__criterion': ['gini', 'entropy'] # } from sklearn.model_selection import",
"12369) selector = RFECV(estimator, cv = 5, scoring='f1_weighted', step = 0.05) selector.fit(X_train, y_train)",
"SelectFromModel') accuracies = [] precisions = [] recalls = [] fscores = []",
"estimator.fit(X_train, y_train) from sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test, estimator.predict(X_test))) report = classification_report(y_test,",
"= 12369) from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(random_state = 12369) estimator.fit(X_train, y_train)",
"sklearn.preprocessing import StandardScaler X_std = StandardScaler().fit_transform(X) from sklearn.model_selection import train_test_split X_train, X_test, y_train,",
"New database full_df: pd.DataFrame = pickle.load(last_run.unlock_data.open('rb')) # full_df = full_df.loc[full_df.DeviceId != 3].reset_index(drop =",
"precision) accuracies.append(accuracy if not np.isnan(accuracy) else 0) precisions.append(precision if not np.isnan(precision) else 0)",
"= selector.transform(X_test) from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(n_estimators = 10, random_state =",
"= [] fscores = [] for device_id in y.unique(): y_device = y[y ==",
"sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state =",
"2)}, recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + PCA') accuracies",
"X_train, X_test, y_train, y_test = train_test_split(X_device, y_device, test_size=0.2) from sklearn.ensemble import IsolationForest estimator",
"= 5, scoring='f1_weighted', step = 0.05) selector.fit(X_train, y_train) selector.show() from sklearn.metrics import classification_report",
"= pickle.load(open(unlock_data_path, 'rb')) # full_df = full_df.loc[full_df.DeviceId != '1439cbc3ad71ac06'].reset_index(drop = True) # %%",
"sklearn.feature_selection import RFE from imblearn.ensemble import BalancedRandomForestClassifier estimator = BalancedRandomForestClassifier(n_estimators = 10, random_state",
"as plt import seaborn as sns from MAKDataHub.services import Services profile_service = Services.profile_service()",
"np import matplotlib.pyplot as plt import seaborn as sns from MAKDataHub.services import Services",
"list(range(180, 216)) + [216]].reset_index(drop = True) df = df.loc[(df.DeviceId != 4) & (df.DeviceId",
"= y[y == device_id] X_device = X.loc[y == device_id, :] X_non_device = X.loc[y",
"print('LinearSVC') accuracies = [] precisions = [] recalls = [] fscores = []",
"20, step = 0.05) selector.fit(X_oversampled, y_oversampled) from sklearn.metrics import classification_report print(f'Device {device_id}:') print(classification_report(y_test,",
"recall: {round(np.mean(recalls), 2)}, fscore: {round(np.mean(fscores), 2)}') # %% print('RandomForestClassifier + SMOTETomek') accuracies =",
"2)}') # %% print('RandomForestClassifier + SelectKBest (f_classif)') accuracies = [] precisions = []",
"selector = RFE(estimator, n_features_to_select = 20, step = 0.05) selector.fit(X_train, y_train) from sklearn.metrics",
"from imblearn.over_sampling import SMOTE X_oversampled, y_oversampled = SMOTE().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE",
"108)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(108, 144)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(144, 180))",
"== -1) tn = np.mean(estimator.predict(X_non_device) == 1) fp = np.mean(estimator.predict(X_non_device) == 1) accuracy",
"X_oversampled, y_oversampled = SMOTE().fit_resample(X_train, y_train) from sklearn.feature_selection import RFE from sklearn.ensemble import RandomForestClassifier",
"from sklearn.ensemble import IsolationForest estimator = IsolationForest(n_estimators = 10) estimator.fit(X_train) tp = np.mean(estimator.predict(X_test)",
"print(f'{device_id} - accuracy: {round(accuracy, 2)}, precision: {round(precision, 2)}, recall: {round(recall, 2)}') # print(f'{device_id}",
"print('OneClassSVM') accuracies = [] precisions = [] recalls = [] fscores = []",
"# 'estimator__n_estimators': [10, 50, 100, 200, 500], # 'estimator__max_features': ['auto', 'sqrt', 'log2'], #",
"# %% print('KNeighborsClassifier') accuracies = [] precisions = [] recalls = [] fscores",
"display(full_df.iloc[:, list(range(36)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(36, 72)) + [216]].groupby('DeviceId').agg([np.min, np.max])) display(full_df.iloc[:, list(range(72,",
"import StandardScaler X_std = StandardScaler().fit_transform(X) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test",
"SMOTETomek') accuracies = [] precisions = [] recalls = [] fscores = []",
"%% display(full_df.iloc[:, list(range(36)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(36, 72)) + [216]].groupby('DeviceId').agg([np.mean])) display(full_df.iloc[:, list(range(72, 108))",
"else 0) recalls.append(recall if not np.isnan(recall) else 0) fscores.append(fscore if not np.isnan(fscore) else",
"pickle.load(last_run.unlock_data.open('rb')) # full_df = full_df.loc[full_df.DeviceId != 3].reset_index(drop = True) ## Old database #",
"report = classification_report(y_test, selector.predict(X_test), output_dict=True) accuracies.append(report['accuracy']) precisions.append(report['1']['precision']) recalls.append(report['1']['recall']) fscores.append(report['1']['f1-score']) print(f'Accuracy: {round(np.mean(accuracies), 2)}, precision:",
"RFE from sklearn.ensemble import RandomForestClassifier estimator = RandomForestClassifier(random_state = 12369, \\ n_estimators =",
"= RandomizedSearchCV(estimator = selector, \\ param_distributions = param_grid, \\ n_iter = 100, \\",
"numpy as np import matplotlib.pyplot as plt import seaborn as sns from MAKDataHub.services",
"test, x=\"DeviceId\", y=\"GrvMgn_amax\") # %% print('OneClassSVM') accuracies = [] precisions = [] recalls"
] |
[
"= EnvConfig().get('DEBUG_INTERNAL') _pdb = Pdb() if DEBUG_INTERNAL else _Pdb() def wrapper(): if DEBUG_INTERNAL:",
"_pdb.set_trace(this_frame) return wrapper class _Pdb(Pdb): def do_longlist(self, arg): filename = self.curframe.f_code.co_filename breaklist =",
"not retrieved by `sys._getframe()`, # so that we don't need to pass its",
"bytefall._c_api import convert_to_builtin_frame from bytefall.config import EnvConfig __all__ = ['PdbWrapper'] class PdbWrapper(object): @staticmethod",
"vm is what we want here. frame = py_sys._getframe() while frame and frame",
"to convert `self.curframe` to builtin frame # for `getsourcelines`, in which `inspect.findsource()` #",
"EnvConfig().get('DEBUG_INTERNAL') _pdb = Pdb() if DEBUG_INTERNAL else _Pdb() def wrapper(): if DEBUG_INTERNAL: _pdb.set_trace(sys._getframe(3))",
"import check_frame from bytefall._modules import sys as py_sys from bytefall._c_api import convert_to_builtin_frame from",
"we need to replace the implementation of `sys.settrace()` # and `sys._getframe()`. py_sys.settrace(None) #",
"we want here. frame = py_sys._getframe() while frame and frame is not self.botframe:",
"lines, lineno = getsourcelines(converted) except OSError as err: self.error(err) return self._print_lines(lines, lineno, breaklist,",
"__all__ = ['PdbWrapper'] class PdbWrapper(object): @staticmethod @check_frame def set_trace(frame, *args, **kwargs): return pdb_wrapper(frame)()",
"# Here we need to convert `self.curframe` to builtin frame # for `getsourcelines`,",
"convert_to_builtin_frame(self.curframe) lines, lineno = getsourcelines(converted) except OSError as err: self.error(err) return self._print_lines(lines, lineno,",
"set_trace(self, frame=None): self.reset() while frame: frame.f_trace = self.trace_dispatch self.botframe = frame frame =",
"['PdbWrapper'] class PdbWrapper(object): @staticmethod @check_frame def set_trace(frame, *args, **kwargs): return pdb_wrapper(frame)() def pdb_wrapper(this_frame):",
"# for `getsourcelines`, in which `inspect.findsource()` # requires a builtin frame to work.",
"in which `inspect.findsource()` # requires a builtin frame to work. converted = convert_to_builtin_frame(self.curframe)",
"`getsourcelines`, in which `inspect.findsource()` # requires a builtin frame to work. converted =",
"_Pdb(Pdb): def do_longlist(self, arg): filename = self.curframe.f_code.co_filename breaklist = self.get_file_breaks(filename) try: # Here",
"we need to convert `self.curframe` to builtin frame # for `getsourcelines`, in which",
"caller `pyframe.Frame` that calling # `py_sys._getframe()`, but it does not affect the result.",
"DEBUG_INTERNAL: _pdb.set_trace(sys._getframe(3)) else: # Frame to be stepped in is not retrieved by",
"self._print_lines(lines, lineno, breaklist, self.curframe) do_ll = do_longlist def set_continue(self): self._set_stopinfo(self.botframe, None, -1) if",
"from .utils import check_frame from bytefall._modules import sys as py_sys from bytefall._c_api import",
"we cannot get caller `pyframe.Frame` that calling # `py_sys._getframe()`, but it does not",
"_pdb.set_trace(sys._getframe(3)) else: # Frame to be stepped in is not retrieved by `sys._getframe()`,",
"from pdb import Pdb, getsourcelines from .utils import check_frame from bytefall._modules import sys",
"pdb import Pdb, getsourcelines from .utils import check_frame from bytefall._modules import sys as",
"return pdb_wrapper(frame)() def pdb_wrapper(this_frame): DEBUG_INTERNAL = EnvConfig().get('DEBUG_INTERNAL') _pdb = Pdb() if DEBUG_INTERNAL else",
"def pdb_wrapper(this_frame): DEBUG_INTERNAL = EnvConfig().get('DEBUG_INTERNAL') _pdb = Pdb() if DEBUG_INTERNAL else _Pdb() def",
"the implementation of `sys.settrace()` # and `sys._getframe()`. py_sys.settrace(None) # In the original implementation,",
"filename = self.curframe.f_code.co_filename breaklist = self.get_file_breaks(filename) try: # Here we need to convert",
"implementation, here it calls # `sys._getframe().f_back` to get the caller of this method.",
"do_longlist def set_continue(self): self._set_stopinfo(self.botframe, None, -1) if not self.breaks: # Here we need",
"that we don't need to pass its `f_back` into `set_trace()` _pdb.set_trace(this_frame) return wrapper",
"# However, we cannot get caller `pyframe.Frame` that calling # `py_sys._getframe()`, but it",
"= self.get_file_breaks(filename) try: # Here we need to convert `self.curframe` to builtin frame",
"its `f_back` into `set_trace()` _pdb.set_trace(this_frame) return wrapper class _Pdb(Pdb): def do_longlist(self, arg): filename",
"@check_frame def set_trace(frame, *args, **kwargs): return pdb_wrapper(frame)() def pdb_wrapper(this_frame): DEBUG_INTERNAL = EnvConfig().get('DEBUG_INTERNAL') _pdb",
"do_ll = do_longlist def set_continue(self): self._set_stopinfo(self.botframe, None, -1) if not self.breaks: # Here",
"builtin frame to work. converted = convert_to_builtin_frame(self.curframe) lines, lineno = getsourcelines(converted) except OSError",
"work. converted = convert_to_builtin_frame(self.curframe) lines, lineno = getsourcelines(converted) except OSError as err: self.error(err)",
"= ['PdbWrapper'] class PdbWrapper(object): @staticmethod @check_frame def set_trace(frame, *args, **kwargs): return pdb_wrapper(frame)() def",
"retrieved by `sys._getframe()`, # so that we don't need to pass its `f_back`",
"if not self.breaks: # Here we need to replace the implementation of `sys.settrace()`",
"to replace the implementation of `sys.settrace()` # and `sys._getframe()`. py_sys.settrace(None) # In the",
"the original implementation, here it calls # `sys._getframe().f_back` to get the caller of",
"not affect the result. # Because the current running frame in vm is",
"so that we don't need to pass its `f_back` into `set_trace()` _pdb.set_trace(this_frame) return",
"= convert_to_builtin_frame(self.curframe) lines, lineno = getsourcelines(converted) except OSError as err: self.error(err) return self._print_lines(lines,",
"need to pass its `f_back` into `set_trace()` _pdb.set_trace(this_frame) return wrapper class _Pdb(Pdb): def",
"that calling # `py_sys._getframe()`, but it does not affect the result. # Because",
"set_continue(self): self._set_stopinfo(self.botframe, None, -1) if not self.breaks: # Here we need to replace",
"convert_to_builtin_frame from bytefall.config import EnvConfig __all__ = ['PdbWrapper'] class PdbWrapper(object): @staticmethod @check_frame def",
"into `set_trace()` _pdb.set_trace(this_frame) return wrapper class _Pdb(Pdb): def do_longlist(self, arg): filename = self.curframe.f_code.co_filename",
"lineno = getsourcelines(converted) except OSError as err: self.error(err) return self._print_lines(lines, lineno, breaklist, self.curframe)",
"`inspect.findsource()` # requires a builtin frame to work. converted = convert_to_builtin_frame(self.curframe) lines, lineno",
"class PdbWrapper(object): @staticmethod @check_frame def set_trace(frame, *args, **kwargs): return pdb_wrapper(frame)() def pdb_wrapper(this_frame): DEBUG_INTERNAL",
"and `sys._getframe()`. py_sys.settrace(None) # In the original implementation, here it calls # `sys._getframe().f_back`",
"check_frame from bytefall._modules import sys as py_sys from bytefall._c_api import convert_to_builtin_frame from bytefall.config",
"calling # `py_sys._getframe()`, but it does not affect the result. # Because the",
"affect the result. # Because the current running frame in vm is what",
"self.reset() while frame: frame.f_trace = self.trace_dispatch self.botframe = frame frame = frame.f_back self.set_step()",
"bytefall.config import EnvConfig __all__ = ['PdbWrapper'] class PdbWrapper(object): @staticmethod @check_frame def set_trace(frame, *args,",
"calls # `sys._getframe().f_back` to get the caller of this method. # However, we",
"but it does not affect the result. # Because the current running frame",
"else: # Frame to be stepped in is not retrieved by `sys._getframe()`, #",
"here. frame = py_sys._getframe() while frame and frame is not self.botframe: del frame.f_trace",
"del frame.f_trace frame = frame.f_back def set_trace(self, frame=None): self.reset() while frame: frame.f_trace =",
"Pdb() if DEBUG_INTERNAL else _Pdb() def wrapper(): if DEBUG_INTERNAL: _pdb.set_trace(sys._getframe(3)) else: # Frame",
"pdb_wrapper(frame)() def pdb_wrapper(this_frame): DEBUG_INTERNAL = EnvConfig().get('DEBUG_INTERNAL') _pdb = Pdb() if DEBUG_INTERNAL else _Pdb()",
"Pdb, getsourcelines from .utils import check_frame from bytefall._modules import sys as py_sys from",
"in is not retrieved by `sys._getframe()`, # so that we don't need to",
"of this method. # However, we cannot get caller `pyframe.Frame` that calling #",
"while frame: frame.f_trace = self.trace_dispatch self.botframe = frame frame = frame.f_back self.set_step() py_sys.settrace(self.trace_dispatch)",
"# `py_sys._getframe()`, but it does not affect the result. # Because the current",
"def set_trace(frame, *args, **kwargs): return pdb_wrapper(frame)() def pdb_wrapper(this_frame): DEBUG_INTERNAL = EnvConfig().get('DEBUG_INTERNAL') _pdb =",
"if DEBUG_INTERNAL: _pdb.set_trace(sys._getframe(3)) else: # Frame to be stepped in is not retrieved",
"def do_longlist(self, arg): filename = self.curframe.f_code.co_filename breaklist = self.get_file_breaks(filename) try: # Here we",
"here it calls # `sys._getframe().f_back` to get the caller of this method. #",
"self._set_stopinfo(self.botframe, None, -1) if not self.breaks: # Here we need to replace the",
"result. # Because the current running frame in vm is what we want",
"*args, **kwargs): return pdb_wrapper(frame)() def pdb_wrapper(this_frame): DEBUG_INTERNAL = EnvConfig().get('DEBUG_INTERNAL') _pdb = Pdb() if",
"is what we want here. frame = py_sys._getframe() while frame and frame is",
"class _Pdb(Pdb): def do_longlist(self, arg): filename = self.curframe.f_code.co_filename breaklist = self.get_file_breaks(filename) try: #",
"by `sys._getframe()`, # so that we don't need to pass its `f_back` into",
"and frame is not self.botframe: del frame.f_trace frame = frame.f_back def set_trace(self, frame=None):",
"pass its `f_back` into `set_trace()` _pdb.set_trace(this_frame) return wrapper class _Pdb(Pdb): def do_longlist(self, arg):",
"= frame.f_back def set_trace(self, frame=None): self.reset() while frame: frame.f_trace = self.trace_dispatch self.botframe =",
"self.curframe) do_ll = do_longlist def set_continue(self): self._set_stopinfo(self.botframe, None, -1) if not self.breaks: #",
"lineno, breaklist, self.curframe) do_ll = do_longlist def set_continue(self): self._set_stopinfo(self.botframe, None, -1) if not",
"it does not affect the result. # Because the current running frame in",
"@staticmethod @check_frame def set_trace(frame, *args, **kwargs): return pdb_wrapper(frame)() def pdb_wrapper(this_frame): DEBUG_INTERNAL = EnvConfig().get('DEBUG_INTERNAL')",
"`sys.settrace()` # and `sys._getframe()`. py_sys.settrace(None) # In the original implementation, here it calls",
"the caller of this method. # However, we cannot get caller `pyframe.Frame` that",
"frame=None): self.reset() while frame: frame.f_trace = self.trace_dispatch self.botframe = frame frame = frame.f_back",
"as py_sys from bytefall._c_api import convert_to_builtin_frame from bytefall.config import EnvConfig __all__ = ['PdbWrapper']",
"else _Pdb() def wrapper(): if DEBUG_INTERNAL: _pdb.set_trace(sys._getframe(3)) else: # Frame to be stepped",
"we don't need to pass its `f_back` into `set_trace()` _pdb.set_trace(this_frame) return wrapper class",
"be stepped in is not retrieved by `sys._getframe()`, # so that we don't",
"frame in vm is what we want here. frame = py_sys._getframe() while frame",
"which `inspect.findsource()` # requires a builtin frame to work. converted = convert_to_builtin_frame(self.curframe) lines,",
"sys as py_sys from bytefall._c_api import convert_to_builtin_frame from bytefall.config import EnvConfig __all__ =",
"get caller `pyframe.Frame` that calling # `py_sys._getframe()`, but it does not affect the",
"is not retrieved by `sys._getframe()`, # so that we don't need to pass",
"= self.curframe.f_code.co_filename breaklist = self.get_file_breaks(filename) try: # Here we need to convert `self.curframe`",
"in vm is what we want here. frame = py_sys._getframe() while frame and",
"OSError as err: self.error(err) return self._print_lines(lines, lineno, breaklist, self.curframe) do_ll = do_longlist def",
"DEBUG_INTERNAL else _Pdb() def wrapper(): if DEBUG_INTERNAL: _pdb.set_trace(sys._getframe(3)) else: # Frame to be",
"py_sys._getframe() while frame and frame is not self.botframe: del frame.f_trace frame = frame.f_back",
"except OSError as err: self.error(err) return self._print_lines(lines, lineno, breaklist, self.curframe) do_ll = do_longlist",
"self.botframe: del frame.f_trace frame = frame.f_back def set_trace(self, frame=None): self.reset() while frame: frame.f_trace",
"get the caller of this method. # However, we cannot get caller `pyframe.Frame`",
"_pdb = Pdb() if DEBUG_INTERNAL else _Pdb() def wrapper(): if DEBUG_INTERNAL: _pdb.set_trace(sys._getframe(3)) else:",
"Here we need to convert `self.curframe` to builtin frame # for `getsourcelines`, in",
"`set_trace()` _pdb.set_trace(this_frame) return wrapper class _Pdb(Pdb): def do_longlist(self, arg): filename = self.curframe.f_code.co_filename breaklist",
"for `getsourcelines`, in which `inspect.findsource()` # requires a builtin frame to work. converted",
"In the original implementation, here it calls # `sys._getframe().f_back` to get the caller",
"None, -1) if not self.breaks: # Here we need to replace the implementation",
"_Pdb() def wrapper(): if DEBUG_INTERNAL: _pdb.set_trace(sys._getframe(3)) else: # Frame to be stepped in",
"while frame and frame is not self.botframe: del frame.f_trace frame = frame.f_back def",
"def set_continue(self): self._set_stopinfo(self.botframe, None, -1) if not self.breaks: # Here we need to",
"cannot get caller `pyframe.Frame` that calling # `py_sys._getframe()`, but it does not affect",
"stepped in is not retrieved by `sys._getframe()`, # so that we don't need",
"wrapper(): if DEBUG_INTERNAL: _pdb.set_trace(sys._getframe(3)) else: # Frame to be stepped in is not",
"does not affect the result. # Because the current running frame in vm",
"import sys from pdb import Pdb, getsourcelines from .utils import check_frame from bytefall._modules",
"from bytefall.config import EnvConfig __all__ = ['PdbWrapper'] class PdbWrapper(object): @staticmethod @check_frame def set_trace(frame,",
"converted = convert_to_builtin_frame(self.curframe) lines, lineno = getsourcelines(converted) except OSError as err: self.error(err) return",
"breaklist, self.curframe) do_ll = do_longlist def set_continue(self): self._set_stopinfo(self.botframe, None, -1) if not self.breaks:",
"current running frame in vm is what we want here. frame = py_sys._getframe()",
"running frame in vm is what we want here. frame = py_sys._getframe() while",
"need to convert `self.curframe` to builtin frame # for `getsourcelines`, in which `inspect.findsource()`",
"is not self.botframe: del frame.f_trace frame = frame.f_back def set_trace(self, frame=None): self.reset() while",
".utils import check_frame from bytefall._modules import sys as py_sys from bytefall._c_api import convert_to_builtin_frame",
"`py_sys._getframe()`, but it does not affect the result. # Because the current running",
"if DEBUG_INTERNAL else _Pdb() def wrapper(): if DEBUG_INTERNAL: _pdb.set_trace(sys._getframe(3)) else: # Frame to",
"from bytefall._c_api import convert_to_builtin_frame from bytefall.config import EnvConfig __all__ = ['PdbWrapper'] class PdbWrapper(object):",
"frame = frame.f_back def set_trace(self, frame=None): self.reset() while frame: frame.f_trace = self.trace_dispatch self.botframe",
"import Pdb, getsourcelines from .utils import check_frame from bytefall._modules import sys as py_sys",
"`f_back` into `set_trace()` _pdb.set_trace(this_frame) return wrapper class _Pdb(Pdb): def do_longlist(self, arg): filename =",
"as err: self.error(err) return self._print_lines(lines, lineno, breaklist, self.curframe) do_ll = do_longlist def set_continue(self):",
"set_trace(frame, *args, **kwargs): return pdb_wrapper(frame)() def pdb_wrapper(this_frame): DEBUG_INTERNAL = EnvConfig().get('DEBUG_INTERNAL') _pdb = Pdb()",
"implementation of `sys.settrace()` # and `sys._getframe()`. py_sys.settrace(None) # In the original implementation, here",
"self.error(err) return self._print_lines(lines, lineno, breaklist, self.curframe) do_ll = do_longlist def set_continue(self): self._set_stopinfo(self.botframe, None,",
"don't need to pass its `f_back` into `set_trace()` _pdb.set_trace(this_frame) return wrapper class _Pdb(Pdb):",
"`self.curframe` to builtin frame # for `getsourcelines`, in which `inspect.findsource()` # requires a",
"# requires a builtin frame to work. converted = convert_to_builtin_frame(self.curframe) lines, lineno =",
"# Frame to be stepped in is not retrieved by `sys._getframe()`, # so",
"Because the current running frame in vm is what we want here. frame",
"`sys._getframe()`, # so that we don't need to pass its `f_back` into `set_trace()`",
"# Here we need to replace the implementation of `sys.settrace()` # and `sys._getframe()`.",
"frame.f_trace frame = frame.f_back def set_trace(self, frame=None): self.reset() while frame: frame.f_trace = self.trace_dispatch",
"frame = py_sys._getframe() while frame and frame is not self.botframe: del frame.f_trace frame",
"arg): filename = self.curframe.f_code.co_filename breaklist = self.get_file_breaks(filename) try: # Here we need to",
"to pass its `f_back` into `set_trace()` _pdb.set_trace(this_frame) return wrapper class _Pdb(Pdb): def do_longlist(self,",
"-1) if not self.breaks: # Here we need to replace the implementation of",
"try: # Here we need to convert `self.curframe` to builtin frame # for",
"from bytefall._modules import sys as py_sys from bytefall._c_api import convert_to_builtin_frame from bytefall.config import",
"to builtin frame # for `getsourcelines`, in which `inspect.findsource()` # requires a builtin",
"self.curframe.f_code.co_filename breaklist = self.get_file_breaks(filename) try: # Here we need to convert `self.curframe` to",
"caller of this method. # However, we cannot get caller `pyframe.Frame` that calling",
"pdb_wrapper(this_frame): DEBUG_INTERNAL = EnvConfig().get('DEBUG_INTERNAL') _pdb = Pdb() if DEBUG_INTERNAL else _Pdb() def wrapper():",
"err: self.error(err) return self._print_lines(lines, lineno, breaklist, self.curframe) do_ll = do_longlist def set_continue(self): self._set_stopinfo(self.botframe,",
"replace the implementation of `sys.settrace()` # and `sys._getframe()`. py_sys.settrace(None) # In the original",
"py_sys from bytefall._c_api import convert_to_builtin_frame from bytefall.config import EnvConfig __all__ = ['PdbWrapper'] class",
"do_longlist(self, arg): filename = self.curframe.f_code.co_filename breaklist = self.get_file_breaks(filename) try: # Here we need",
"of `sys.settrace()` # and `sys._getframe()`. py_sys.settrace(None) # In the original implementation, here it",
"def set_trace(self, frame=None): self.reset() while frame: frame.f_trace = self.trace_dispatch self.botframe = frame frame",
"wrapper class _Pdb(Pdb): def do_longlist(self, arg): filename = self.curframe.f_code.co_filename breaklist = self.get_file_breaks(filename) try:",
"PdbWrapper(object): @staticmethod @check_frame def set_trace(frame, *args, **kwargs): return pdb_wrapper(frame)() def pdb_wrapper(this_frame): DEBUG_INTERNAL =",
"# Because the current running frame in vm is what we want here.",
"method. # However, we cannot get caller `pyframe.Frame` that calling # `py_sys._getframe()`, but",
"not self.botframe: del frame.f_trace frame = frame.f_back def set_trace(self, frame=None): self.reset() while frame:",
"# and `sys._getframe()`. py_sys.settrace(None) # In the original implementation, here it calls #",
"= py_sys._getframe() while frame and frame is not self.botframe: del frame.f_trace frame =",
"to get the caller of this method. # However, we cannot get caller",
"builtin frame # for `getsourcelines`, in which `inspect.findsource()` # requires a builtin frame",
"frame is not self.botframe: del frame.f_trace frame = frame.f_back def set_trace(self, frame=None): self.reset()",
"import sys as py_sys from bytefall._c_api import convert_to_builtin_frame from bytefall.config import EnvConfig __all__",
"# In the original implementation, here it calls # `sys._getframe().f_back` to get the",
"= getsourcelines(converted) except OSError as err: self.error(err) return self._print_lines(lines, lineno, breaklist, self.curframe) do_ll",
"what we want here. frame = py_sys._getframe() while frame and frame is not",
"**kwargs): return pdb_wrapper(frame)() def pdb_wrapper(this_frame): DEBUG_INTERNAL = EnvConfig().get('DEBUG_INTERNAL') _pdb = Pdb() if DEBUG_INTERNAL",
"requires a builtin frame to work. converted = convert_to_builtin_frame(self.curframe) lines, lineno = getsourcelines(converted)",
"def wrapper(): if DEBUG_INTERNAL: _pdb.set_trace(sys._getframe(3)) else: # Frame to be stepped in is",
"convert `self.curframe` to builtin frame # for `getsourcelines`, in which `inspect.findsource()` # requires",
"breaklist = self.get_file_breaks(filename) try: # Here we need to convert `self.curframe` to builtin",
"import convert_to_builtin_frame from bytefall.config import EnvConfig __all__ = ['PdbWrapper'] class PdbWrapper(object): @staticmethod @check_frame",
"`sys._getframe().f_back` to get the caller of this method. # However, we cannot get",
"to work. converted = convert_to_builtin_frame(self.curframe) lines, lineno = getsourcelines(converted) except OSError as err:",
"import EnvConfig __all__ = ['PdbWrapper'] class PdbWrapper(object): @staticmethod @check_frame def set_trace(frame, *args, **kwargs):",
"to be stepped in is not retrieved by `sys._getframe()`, # so that we",
"= Pdb() if DEBUG_INTERNAL else _Pdb() def wrapper(): if DEBUG_INTERNAL: _pdb.set_trace(sys._getframe(3)) else: #",
"= do_longlist def set_continue(self): self._set_stopinfo(self.botframe, None, -1) if not self.breaks: # Here we",
"# `sys._getframe().f_back` to get the caller of this method. # However, we cannot",
"EnvConfig __all__ = ['PdbWrapper'] class PdbWrapper(object): @staticmethod @check_frame def set_trace(frame, *args, **kwargs): return",
"`sys._getframe()`. py_sys.settrace(None) # In the original implementation, here it calls # `sys._getframe().f_back` to",
"it calls # `sys._getframe().f_back` to get the caller of this method. # However,",
"the result. # Because the current running frame in vm is what we",
"getsourcelines(converted) except OSError as err: self.error(err) return self._print_lines(lines, lineno, breaklist, self.curframe) do_ll =",
"not self.breaks: # Here we need to replace the implementation of `sys.settrace()` #",
"getsourcelines from .utils import check_frame from bytefall._modules import sys as py_sys from bytefall._c_api",
"frame and frame is not self.botframe: del frame.f_trace frame = frame.f_back def set_trace(self,",
"However, we cannot get caller `pyframe.Frame` that calling # `py_sys._getframe()`, but it does",
"Here we need to replace the implementation of `sys.settrace()` # and `sys._getframe()`. py_sys.settrace(None)",
"bytefall._modules import sys as py_sys from bytefall._c_api import convert_to_builtin_frame from bytefall.config import EnvConfig",
"a builtin frame to work. converted = convert_to_builtin_frame(self.curframe) lines, lineno = getsourcelines(converted) except",
"Frame to be stepped in is not retrieved by `sys._getframe()`, # so that",
"self.get_file_breaks(filename) try: # Here we need to convert `self.curframe` to builtin frame #",
"original implementation, here it calls # `sys._getframe().f_back` to get the caller of this",
"frame # for `getsourcelines`, in which `inspect.findsource()` # requires a builtin frame to",
"this method. # However, we cannot get caller `pyframe.Frame` that calling # `py_sys._getframe()`,",
"return self._print_lines(lines, lineno, breaklist, self.curframe) do_ll = do_longlist def set_continue(self): self._set_stopinfo(self.botframe, None, -1)",
"frame.f_back def set_trace(self, frame=None): self.reset() while frame: frame.f_trace = self.trace_dispatch self.botframe = frame",
"py_sys.settrace(None) # In the original implementation, here it calls # `sys._getframe().f_back` to get",
"DEBUG_INTERNAL = EnvConfig().get('DEBUG_INTERNAL') _pdb = Pdb() if DEBUG_INTERNAL else _Pdb() def wrapper(): if",
"the current running frame in vm is what we want here. frame =",
"want here. frame = py_sys._getframe() while frame and frame is not self.botframe: del",
"self.breaks: # Here we need to replace the implementation of `sys.settrace()` # and",
"need to replace the implementation of `sys.settrace()` # and `sys._getframe()`. py_sys.settrace(None) # In",
"frame to work. converted = convert_to_builtin_frame(self.curframe) lines, lineno = getsourcelines(converted) except OSError as",
"# so that we don't need to pass its `f_back` into `set_trace()` _pdb.set_trace(this_frame)",
"return wrapper class _Pdb(Pdb): def do_longlist(self, arg): filename = self.curframe.f_code.co_filename breaklist = self.get_file_breaks(filename)",
"sys from pdb import Pdb, getsourcelines from .utils import check_frame from bytefall._modules import",
"`pyframe.Frame` that calling # `py_sys._getframe()`, but it does not affect the result. #"
] |
[
"StatusProcessing(): success: bool message: str err_stack: str def __init__(self, _success: bool, _message: str,",
"class StatusProcessing(): success: bool message: str err_stack: str def __init__(self, _success: bool, _message:",
"_success: bool, _message: str, _err_stack: str = \"\"): self.success = _success self.message =",
"success: bool message: str err_stack: str def __init__(self, _success: bool, _message: str, _err_stack:",
"_message: str, _err_stack: str = \"\"): self.success = _success self.message = _message self.err_stack",
"message: str err_stack: str def __init__(self, _success: bool, _message: str, _err_stack: str =",
"str def __init__(self, _success: bool, _message: str, _err_stack: str = \"\"): self.success =",
"str err_stack: str def __init__(self, _success: bool, _message: str, _err_stack: str = \"\"):",
"bool, _message: str, _err_stack: str = \"\"): self.success = _success self.message = _message",
"err_stack: str def __init__(self, _success: bool, _message: str, _err_stack: str = \"\"): self.success",
"bool message: str err_stack: str def __init__(self, _success: bool, _message: str, _err_stack: str",
"_err_stack: str = \"\"): self.success = _success self.message = _message self.err_stack = _err_stack",
"str = \"\"): self.success = _success self.message = _message self.err_stack = _err_stack pass",
"def __init__(self, _success: bool, _message: str, _err_stack: str = \"\"): self.success = _success",
"= \"\"): self.success = _success self.message = _message self.err_stack = _err_stack pass pass",
"__init__(self, _success: bool, _message: str, _err_stack: str = \"\"): self.success = _success self.message",
"str, _err_stack: str = \"\"): self.success = _success self.message = _message self.err_stack ="
] |
[
"t*t y = t plt.figure() plt.plot(x,y,'g-') plt.legend(['Path'],loc='best') plt.title('Quadratic Path') plt.show() doty=one dotx=2*t ddoty=0",
"= t plt.figure() plt.plot(x,y,'g-') plt.legend(['Path'],loc='best') plt.title('Quadratic Path') plt.show() doty=one dotx=2*t ddoty=0 ddotx=2*one r",
"yp[0] = 0.0 th[0] = 1.5707963267949 for i in range(N-1): xp[i+1] = xp[i]",
"= t*t y = t plt.figure() plt.plot(x,y,'g-') plt.legend(['Path'],loc='best') plt.title('Quadratic Path') plt.show() doty=one dotx=2*t",
"plt import numpy as np from math import * N=100 t0 = 0.0",
"np.zeros((N)) th = np.zeros((N)) x = t*t y = t plt.figure() plt.plot(x,y,'g-') plt.legend(['Path'],loc='best')",
"+ (r*dt/2.0)*(dotphi1[i]+dotphi2[i])* sin(th[i]) th[i+1] = th[i] + (r*dt/(2.0*L))*(dotphi1[i]-dotphi2[i]) plt.figure() plt.plot(x,y,'g-', xp, yp, 'bx')",
"L = 4.0 v = np.sqrt(dotx*dotx + doty*doty) kappa = (dotx*ddoty - doty*ddotx)/(v*v*v)",
"= np.zeros((N)) th = np.zeros((N)) x = t*t y = t plt.figure() plt.plot(x,y,'g-')",
"xp[i+1] = xp[i] + (r*dt/2.0) * (dotphi1[i]+dotphi2[i]) * cos(th[i]) yp[i+1] = yp[i] +",
"plt.show() doty=one dotx=2*t ddoty=0 ddotx=2*one r = 1.0 L = 4.0 v =",
"kappa = (dotx*ddoty - doty*ddotx)/(v*v*v) dotphi1 = (v/r)*(kappa*L +1) dotphi2 = (v/r)*(-kappa*L+1) plt.plot(t,dotphi1,'b-',",
"np.zeros((N)) yp = np.zeros((N)) th = np.zeros((N)) x = t*t y = t",
"import * N=100 t0 = 0.0 t1 = 2.0 t = np.linspace(t0,t1,N) dt",
"plt.show() xp[0] = 0.0 yp[0] = 0.0 th[0] = 1.5707963267949 for i in",
"= 1.0 L = 4.0 v = np.sqrt(dotx*dotx + doty*doty) kappa = (dotx*ddoty",
"= (t1-t0)/N one = np.ones((N)) xp = np.zeros((N)) yp = np.zeros((N)) th =",
"= np.linspace(t0,t1,N) dt = (t1-t0)/N one = np.ones((N)) xp = np.zeros((N)) yp =",
"np.zeros((N)) x = t*t y = t plt.figure() plt.plot(x,y,'g-') plt.legend(['Path'],loc='best') plt.title('Quadratic Path') plt.show()",
"one = np.ones((N)) xp = np.zeros((N)) yp = np.zeros((N)) th = np.zeros((N)) x",
"1.5707963267949 for i in range(N-1): xp[i+1] = xp[i] + (r*dt/2.0) * (dotphi1[i]+dotphi2[i]) *",
"xp = np.zeros((N)) yp = np.zeros((N)) th = np.zeros((N)) x = t*t y",
"dotx=2*t ddoty=0 ddotx=2*one r = 1.0 L = 4.0 v = np.sqrt(dotx*dotx +",
"as plt import numpy as np from math import * N=100 t0 =",
"t plt.figure() plt.plot(x,y,'g-') plt.legend(['Path'],loc='best') plt.title('Quadratic Path') plt.show() doty=one dotx=2*t ddoty=0 ddotx=2*one r =",
"import pylab as plt import numpy as np from math import * N=100",
"dotphi1 = (v/r)*(kappa*L +1) dotphi2 = (v/r)*(-kappa*L+1) plt.plot(t,dotphi1,'b-', t,dotphi2,'g-') plt.title('Wheel Speeds') plt.legend(['Right', 'Left'],loc='best')",
"plt.plot(t,dotphi1,'b-', t,dotphi2,'g-') plt.title('Wheel Speeds') plt.legend(['Right', 'Left'],loc='best') plt.show() xp[0] = 0.0 yp[0] = 0.0",
"Path') plt.show() doty=one dotx=2*t ddoty=0 ddotx=2*one r = 1.0 L = 4.0 v",
"dotphi2 = (v/r)*(-kappa*L+1) plt.plot(t,dotphi1,'b-', t,dotphi2,'g-') plt.title('Wheel Speeds') plt.legend(['Right', 'Left'],loc='best') plt.show() xp[0] = 0.0",
"= (v/r)*(-kappa*L+1) plt.plot(t,dotphi1,'b-', t,dotphi2,'g-') plt.title('Wheel Speeds') plt.legend(['Right', 'Left'],loc='best') plt.show() xp[0] = 0.0 yp[0]",
"0.0 th[0] = 1.5707963267949 for i in range(N-1): xp[i+1] = xp[i] + (r*dt/2.0)",
"(r*dt/2.0) * (dotphi1[i]+dotphi2[i]) * cos(th[i]) yp[i+1] = yp[i] + (r*dt/2.0)*(dotphi1[i]+dotphi2[i])* sin(th[i]) th[i+1] =",
"(v/r)*(-kappa*L+1) plt.plot(t,dotphi1,'b-', t,dotphi2,'g-') plt.title('Wheel Speeds') plt.legend(['Right', 'Left'],loc='best') plt.show() xp[0] = 0.0 yp[0] =",
"plt.title('Wheel Speeds') plt.legend(['Right', 'Left'],loc='best') plt.show() xp[0] = 0.0 yp[0] = 0.0 th[0] =",
"th[i+1] = th[i] + (r*dt/(2.0*L))*(dotphi1[i]-dotphi2[i]) plt.figure() plt.plot(x,y,'g-', xp, yp, 'bx') plt.legend(['Original Path', 'Robot",
"x = t*t y = t plt.figure() plt.plot(x,y,'g-') plt.legend(['Path'],loc='best') plt.title('Quadratic Path') plt.show() doty=one",
"th = np.zeros((N)) x = t*t y = t plt.figure() plt.plot(x,y,'g-') plt.legend(['Path'],loc='best') plt.title('Quadratic",
"* N=100 t0 = 0.0 t1 = 2.0 t = np.linspace(t0,t1,N) dt =",
"import numpy as np from math import * N=100 t0 = 0.0 t1",
"= np.ones((N)) xp = np.zeros((N)) yp = np.zeros((N)) th = np.zeros((N)) x =",
"xp[0] = 0.0 yp[0] = 0.0 th[0] = 1.5707963267949 for i in range(N-1):",
"* (dotphi1[i]+dotphi2[i]) * cos(th[i]) yp[i+1] = yp[i] + (r*dt/2.0)*(dotphi1[i]+dotphi2[i])* sin(th[i]) th[i+1] = th[i]",
"dt = (t1-t0)/N one = np.ones((N)) xp = np.zeros((N)) yp = np.zeros((N)) th",
"doty*doty) kappa = (dotx*ddoty - doty*ddotx)/(v*v*v) dotphi1 = (v/r)*(kappa*L +1) dotphi2 = (v/r)*(-kappa*L+1)",
"= np.zeros((N)) yp = np.zeros((N)) th = np.zeros((N)) x = t*t y =",
"'Left'],loc='best') plt.show() xp[0] = 0.0 yp[0] = 0.0 th[0] = 1.5707963267949 for i",
"= 0.0 t1 = 2.0 t = np.linspace(t0,t1,N) dt = (t1-t0)/N one =",
"* cos(th[i]) yp[i+1] = yp[i] + (r*dt/2.0)*(dotphi1[i]+dotphi2[i])* sin(th[i]) th[i+1] = th[i] + (r*dt/(2.0*L))*(dotphi1[i]-dotphi2[i])",
"+1) dotphi2 = (v/r)*(-kappa*L+1) plt.plot(t,dotphi1,'b-', t,dotphi2,'g-') plt.title('Wheel Speeds') plt.legend(['Right', 'Left'],loc='best') plt.show() xp[0] =",
"t,dotphi2,'g-') plt.title('Wheel Speeds') plt.legend(['Right', 'Left'],loc='best') plt.show() xp[0] = 0.0 yp[0] = 0.0 th[0]",
"plt.legend(['Right', 'Left'],loc='best') plt.show() xp[0] = 0.0 yp[0] = 0.0 th[0] = 1.5707963267949 for",
"ddoty=0 ddotx=2*one r = 1.0 L = 4.0 v = np.sqrt(dotx*dotx + doty*doty)",
"= np.sqrt(dotx*dotx + doty*doty) kappa = (dotx*ddoty - doty*ddotx)/(v*v*v) dotphi1 = (v/r)*(kappa*L +1)",
"0.0 t1 = 2.0 t = np.linspace(t0,t1,N) dt = (t1-t0)/N one = np.ones((N))",
"t1 = 2.0 t = np.linspace(t0,t1,N) dt = (t1-t0)/N one = np.ones((N)) xp",
"doty*ddotx)/(v*v*v) dotphi1 = (v/r)*(kappa*L +1) dotphi2 = (v/r)*(-kappa*L+1) plt.plot(t,dotphi1,'b-', t,dotphi2,'g-') plt.title('Wheel Speeds') plt.legend(['Right',",
"th[i] + (r*dt/(2.0*L))*(dotphi1[i]-dotphi2[i]) plt.figure() plt.plot(x,y,'g-', xp, yp, 'bx') plt.legend(['Original Path', 'Robot Path'],loc='best') plt.title('Path')",
"(r*dt/2.0)*(dotphi1[i]+dotphi2[i])* sin(th[i]) th[i+1] = th[i] + (r*dt/(2.0*L))*(dotphi1[i]-dotphi2[i]) plt.figure() plt.plot(x,y,'g-', xp, yp, 'bx') plt.legend(['Original",
"plt.legend(['Path'],loc='best') plt.title('Quadratic Path') plt.show() doty=one dotx=2*t ddoty=0 ddotx=2*one r = 1.0 L =",
"= 0.0 yp[0] = 0.0 th[0] = 1.5707963267949 for i in range(N-1): xp[i+1]",
"yp = np.zeros((N)) th = np.zeros((N)) x = t*t y = t plt.figure()",
"numpy as np from math import * N=100 t0 = 0.0 t1 =",
"th[0] = 1.5707963267949 for i in range(N-1): xp[i+1] = xp[i] + (r*dt/2.0) *",
"doty=one dotx=2*t ddoty=0 ddotx=2*one r = 1.0 L = 4.0 v = np.sqrt(dotx*dotx",
"t0 = 0.0 t1 = 2.0 t = np.linspace(t0,t1,N) dt = (t1-t0)/N one",
"np.sqrt(dotx*dotx + doty*doty) kappa = (dotx*ddoty - doty*ddotx)/(v*v*v) dotphi1 = (v/r)*(kappa*L +1) dotphi2",
"np.ones((N)) xp = np.zeros((N)) yp = np.zeros((N)) th = np.zeros((N)) x = t*t",
"= (v/r)*(kappa*L +1) dotphi2 = (v/r)*(-kappa*L+1) plt.plot(t,dotphi1,'b-', t,dotphi2,'g-') plt.title('Wheel Speeds') plt.legend(['Right', 'Left'],loc='best') plt.show()",
"2.0 t = np.linspace(t0,t1,N) dt = (t1-t0)/N one = np.ones((N)) xp = np.zeros((N))",
"= 2.0 t = np.linspace(t0,t1,N) dt = (t1-t0)/N one = np.ones((N)) xp =",
"= 0.0 th[0] = 1.5707963267949 for i in range(N-1): xp[i+1] = xp[i] +",
"np from math import * N=100 t0 = 0.0 t1 = 2.0 t",
"yp[i+1] = yp[i] + (r*dt/2.0)*(dotphi1[i]+dotphi2[i])* sin(th[i]) th[i+1] = th[i] + (r*dt/(2.0*L))*(dotphi1[i]-dotphi2[i]) plt.figure() plt.plot(x,y,'g-',",
"from math import * N=100 t0 = 0.0 t1 = 2.0 t =",
"(v/r)*(kappa*L +1) dotphi2 = (v/r)*(-kappa*L+1) plt.plot(t,dotphi1,'b-', t,dotphi2,'g-') plt.title('Wheel Speeds') plt.legend(['Right', 'Left'],loc='best') plt.show() xp[0]",
"i in range(N-1): xp[i+1] = xp[i] + (r*dt/2.0) * (dotphi1[i]+dotphi2[i]) * cos(th[i]) yp[i+1]",
"np.linspace(t0,t1,N) dt = (t1-t0)/N one = np.ones((N)) xp = np.zeros((N)) yp = np.zeros((N))",
"Speeds') plt.legend(['Right', 'Left'],loc='best') plt.show() xp[0] = 0.0 yp[0] = 0.0 th[0] = 1.5707963267949",
"= 4.0 v = np.sqrt(dotx*dotx + doty*doty) kappa = (dotx*ddoty - doty*ddotx)/(v*v*v) dotphi1",
"sin(th[i]) th[i+1] = th[i] + (r*dt/(2.0*L))*(dotphi1[i]-dotphi2[i]) plt.figure() plt.plot(x,y,'g-', xp, yp, 'bx') plt.legend(['Original Path',",
"plt.plot(x,y,'g-') plt.legend(['Path'],loc='best') plt.title('Quadratic Path') plt.show() doty=one dotx=2*t ddoty=0 ddotx=2*one r = 1.0 L",
"= (dotx*ddoty - doty*ddotx)/(v*v*v) dotphi1 = (v/r)*(kappa*L +1) dotphi2 = (v/r)*(-kappa*L+1) plt.plot(t,dotphi1,'b-', t,dotphi2,'g-')",
"as np from math import * N=100 t0 = 0.0 t1 = 2.0",
"- doty*ddotx)/(v*v*v) dotphi1 = (v/r)*(kappa*L +1) dotphi2 = (v/r)*(-kappa*L+1) plt.plot(t,dotphi1,'b-', t,dotphi2,'g-') plt.title('Wheel Speeds')",
"+ doty*doty) kappa = (dotx*ddoty - doty*ddotx)/(v*v*v) dotphi1 = (v/r)*(kappa*L +1) dotphi2 =",
"0.0 yp[0] = 0.0 th[0] = 1.5707963267949 for i in range(N-1): xp[i+1] =",
"t = np.linspace(t0,t1,N) dt = (t1-t0)/N one = np.ones((N)) xp = np.zeros((N)) yp",
"ddotx=2*one r = 1.0 L = 4.0 v = np.sqrt(dotx*dotx + doty*doty) kappa",
"N=100 t0 = 0.0 t1 = 2.0 t = np.linspace(t0,t1,N) dt = (t1-t0)/N",
"= np.zeros((N)) x = t*t y = t plt.figure() plt.plot(x,y,'g-') plt.legend(['Path'],loc='best') plt.title('Quadratic Path')",
"math import * N=100 t0 = 0.0 t1 = 2.0 t = np.linspace(t0,t1,N)",
"+ (r*dt/(2.0*L))*(dotphi1[i]-dotphi2[i]) plt.figure() plt.plot(x,y,'g-', xp, yp, 'bx') plt.legend(['Original Path', 'Robot Path'],loc='best') plt.title('Path') plt.show()",
"r = 1.0 L = 4.0 v = np.sqrt(dotx*dotx + doty*doty) kappa =",
"for i in range(N-1): xp[i+1] = xp[i] + (r*dt/2.0) * (dotphi1[i]+dotphi2[i]) * cos(th[i])",
"= 1.5707963267949 for i in range(N-1): xp[i+1] = xp[i] + (r*dt/2.0) * (dotphi1[i]+dotphi2[i])",
"range(N-1): xp[i+1] = xp[i] + (r*dt/2.0) * (dotphi1[i]+dotphi2[i]) * cos(th[i]) yp[i+1] = yp[i]",
"y = t plt.figure() plt.plot(x,y,'g-') plt.legend(['Path'],loc='best') plt.title('Quadratic Path') plt.show() doty=one dotx=2*t ddoty=0 ddotx=2*one",
"xp[i] + (r*dt/2.0) * (dotphi1[i]+dotphi2[i]) * cos(th[i]) yp[i+1] = yp[i] + (r*dt/2.0)*(dotphi1[i]+dotphi2[i])* sin(th[i])",
"in range(N-1): xp[i+1] = xp[i] + (r*dt/2.0) * (dotphi1[i]+dotphi2[i]) * cos(th[i]) yp[i+1] =",
"plt.title('Quadratic Path') plt.show() doty=one dotx=2*t ddoty=0 ddotx=2*one r = 1.0 L = 4.0",
"(t1-t0)/N one = np.ones((N)) xp = np.zeros((N)) yp = np.zeros((N)) th = np.zeros((N))",
"4.0 v = np.sqrt(dotx*dotx + doty*doty) kappa = (dotx*ddoty - doty*ddotx)/(v*v*v) dotphi1 =",
"(dotx*ddoty - doty*ddotx)/(v*v*v) dotphi1 = (v/r)*(kappa*L +1) dotphi2 = (v/r)*(-kappa*L+1) plt.plot(t,dotphi1,'b-', t,dotphi2,'g-') plt.title('Wheel",
"v = np.sqrt(dotx*dotx + doty*doty) kappa = (dotx*ddoty - doty*ddotx)/(v*v*v) dotphi1 = (v/r)*(kappa*L",
"+ (r*dt/2.0) * (dotphi1[i]+dotphi2[i]) * cos(th[i]) yp[i+1] = yp[i] + (r*dt/2.0)*(dotphi1[i]+dotphi2[i])* sin(th[i]) th[i+1]",
"cos(th[i]) yp[i+1] = yp[i] + (r*dt/2.0)*(dotphi1[i]+dotphi2[i])* sin(th[i]) th[i+1] = th[i] + (r*dt/(2.0*L))*(dotphi1[i]-dotphi2[i]) plt.figure()",
"yp[i] + (r*dt/2.0)*(dotphi1[i]+dotphi2[i])* sin(th[i]) th[i+1] = th[i] + (r*dt/(2.0*L))*(dotphi1[i]-dotphi2[i]) plt.figure() plt.plot(x,y,'g-', xp, yp,",
"1.0 L = 4.0 v = np.sqrt(dotx*dotx + doty*doty) kappa = (dotx*ddoty -",
"= xp[i] + (r*dt/2.0) * (dotphi1[i]+dotphi2[i]) * cos(th[i]) yp[i+1] = yp[i] + (r*dt/2.0)*(dotphi1[i]+dotphi2[i])*",
"plt.figure() plt.plot(x,y,'g-') plt.legend(['Path'],loc='best') plt.title('Quadratic Path') plt.show() doty=one dotx=2*t ddoty=0 ddotx=2*one r = 1.0",
"= yp[i] + (r*dt/2.0)*(dotphi1[i]+dotphi2[i])* sin(th[i]) th[i+1] = th[i] + (r*dt/(2.0*L))*(dotphi1[i]-dotphi2[i]) plt.figure() plt.plot(x,y,'g-', xp,",
"pylab as plt import numpy as np from math import * N=100 t0",
"(dotphi1[i]+dotphi2[i]) * cos(th[i]) yp[i+1] = yp[i] + (r*dt/2.0)*(dotphi1[i]+dotphi2[i])* sin(th[i]) th[i+1] = th[i] +",
"= th[i] + (r*dt/(2.0*L))*(dotphi1[i]-dotphi2[i]) plt.figure() plt.plot(x,y,'g-', xp, yp, 'bx') plt.legend(['Original Path', 'Robot Path'],loc='best')"
] |
[
"= numpy.zeros(size*LENGTH) print (x) comm.Gather(x_local, x, root=0) #you should notice that only the",
"value for x that #is not \"None\" print (\"process\", rank, \"x:\", x) print",
"numpy.linspace(rank*LENGTH,(rank+1)*LENGTH, LENGTH) print(x_local) if rank == 0: x = numpy.zeros(size*LENGTH) print (x) comm.Gather(x_local,",
"numpy.zeros(size*LENGTH) print (x) comm.Gather(x_local, x, root=0) #you should notice that only the root",
"should notice that only the root process has a value for x that",
"(x) comm.Gather(x_local, x, root=0) #you should notice that only the root process has",
"gatherUpper.py import numpy from mpi4py import MPI comm = MPI.COMM_WORLD rank = comm.Get_rank()",
"0: x = numpy.zeros(size*LENGTH) print (x) comm.Gather(x_local, x, root=0) #you should notice that",
"rank == 0: x = numpy.zeros(size*LENGTH) print (x) comm.Gather(x_local, x, root=0) #you should",
"the root process has a value for x that #is not \"None\" print",
"LENGTH = 3 x = None x_local = numpy.linspace(rank*LENGTH,(rank+1)*LENGTH, LENGTH) print(x_local) if rank",
"x that #is not \"None\" print (\"process\", rank, \"x:\", x) print (\"process\", rank,",
"= comm.Get_rank() size = comm.Get_size() LENGTH = 3 x = None x_local =",
"size = comm.Get_size() LENGTH = 3 x = None x_local = numpy.linspace(rank*LENGTH,(rank+1)*LENGTH, LENGTH)",
"# gatherUpper.py import numpy from mpi4py import MPI comm = MPI.COMM_WORLD rank =",
"print(x_local) if rank == 0: x = numpy.zeros(size*LENGTH) print (x) comm.Gather(x_local, x, root=0)",
"root=0) #you should notice that only the root process has a value for",
"LENGTH) print(x_local) if rank == 0: x = numpy.zeros(size*LENGTH) print (x) comm.Gather(x_local, x,",
"a value for x that #is not \"None\" print (\"process\", rank, \"x:\", x)",
"comm.Get_rank() size = comm.Get_size() LENGTH = 3 x = None x_local = numpy.linspace(rank*LENGTH,(rank+1)*LENGTH,",
"mpi4py import MPI comm = MPI.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size() LENGTH",
"= comm.Get_size() LENGTH = 3 x = None x_local = numpy.linspace(rank*LENGTH,(rank+1)*LENGTH, LENGTH) print(x_local)",
"x = None x_local = numpy.linspace(rank*LENGTH,(rank+1)*LENGTH, LENGTH) print(x_local) if rank == 0: x",
"print (x) comm.Gather(x_local, x, root=0) #you should notice that only the root process",
"from mpi4py import MPI comm = MPI.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size()",
"#you should notice that only the root process has a value for x",
"has a value for x that #is not \"None\" print (\"process\", rank, \"x:\",",
"x_local = numpy.linspace(rank*LENGTH,(rank+1)*LENGTH, LENGTH) print(x_local) if rank == 0: x = numpy.zeros(size*LENGTH) print",
"numpy from mpi4py import MPI comm = MPI.COMM_WORLD rank = comm.Get_rank() size =",
"import MPI comm = MPI.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size() LENGTH =",
"only the root process has a value for x that #is not \"None\"",
"== 0: x = numpy.zeros(size*LENGTH) print (x) comm.Gather(x_local, x, root=0) #you should notice",
"if rank == 0: x = numpy.zeros(size*LENGTH) print (x) comm.Gather(x_local, x, root=0) #you",
"3 x = None x_local = numpy.linspace(rank*LENGTH,(rank+1)*LENGTH, LENGTH) print(x_local) if rank == 0:",
"for x that #is not \"None\" print (\"process\", rank, \"x:\", x) print (\"process\",",
"MPI.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size() LENGTH = 3 x = None",
"process has a value for x that #is not \"None\" print (\"process\", rank,",
"import numpy from mpi4py import MPI comm = MPI.COMM_WORLD rank = comm.Get_rank() size",
"that only the root process has a value for x that #is not",
"rank = comm.Get_rank() size = comm.Get_size() LENGTH = 3 x = None x_local",
"MPI comm = MPI.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size() LENGTH = 3",
"x, root=0) #you should notice that only the root process has a value",
"= 3 x = None x_local = numpy.linspace(rank*LENGTH,(rank+1)*LENGTH, LENGTH) print(x_local) if rank ==",
"= numpy.linspace(rank*LENGTH,(rank+1)*LENGTH, LENGTH) print(x_local) if rank == 0: x = numpy.zeros(size*LENGTH) print (x)",
"comm.Gather(x_local, x, root=0) #you should notice that only the root process has a",
"None x_local = numpy.linspace(rank*LENGTH,(rank+1)*LENGTH, LENGTH) print(x_local) if rank == 0: x = numpy.zeros(size*LENGTH)",
"= None x_local = numpy.linspace(rank*LENGTH,(rank+1)*LENGTH, LENGTH) print(x_local) if rank == 0: x =",
"#is not \"None\" print (\"process\", rank, \"x:\", x) print (\"process\", rank, \"x_local:\", x_local)",
"notice that only the root process has a value for x that #is",
"that #is not \"None\" print (\"process\", rank, \"x:\", x) print (\"process\", rank, \"x_local:\",",
"python # gatherUpper.py import numpy from mpi4py import MPI comm = MPI.COMM_WORLD rank",
"#!/usr/bin/env python # gatherUpper.py import numpy from mpi4py import MPI comm = MPI.COMM_WORLD",
"= MPI.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size() LENGTH = 3 x =",
"x = numpy.zeros(size*LENGTH) print (x) comm.Gather(x_local, x, root=0) #you should notice that only",
"root process has a value for x that #is not \"None\" print (\"process\",",
"comm.Get_size() LENGTH = 3 x = None x_local = numpy.linspace(rank*LENGTH,(rank+1)*LENGTH, LENGTH) print(x_local) if",
"comm = MPI.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size() LENGTH = 3 x"
] |
[
"h not in d: d[h] = [] d[h].append(anagram) return d if not myList",
"[] map[target].append(v) print('building map ', map[target]) result = [] for value in map.values():",
"{} for v in strs: target = ''.join(sorted(v)) print(target) if target not in",
":rtype List[List[str]] \"\"\" map = {} for v in strs: target = ''.join(sorted(v))",
"map[target] = [] map[target].append(v) print('building map ', map[target]) result = [] for value",
"\"\"\" :type strs List[str] :rtype List[List[str]] \"\"\" map = {} for v in",
"convert_strs_to_hashes(myList): d = dict() for anagram in myList: h = sum([ord(i) for i",
"= sum([ord(i) for i in anagram]) if h not in d: d[h] =",
"outputList = [] for key, values in d.items(): outputList.extend(values) return outputList if __name__==\"__main__\":",
"if not myList or len(myList) < 2: return 0 if not myList else",
"[] for value in map.values(): print('anagrams ', value) result += [sorted(value)] return result",
"d[h].append(anagram) return d if not myList or len(myList) < 2: return 0 if",
"key, values in d.items(): outputList.extend(values) return outputList if __name__==\"__main__\": anagrams = [\"acme\", \"acre\",",
"= {} for v in strs: target = ''.join(sorted(v)) print(target) if target not",
":type strs List[str] :rtype List[List[str]] \"\"\" map = {} for v in strs:",
"d: d[h] = [] d[h].append(anagram) return d if not myList or len(myList) <",
"print(target) if target not in map: map[target] = [] map[target].append(v) print('building map ',",
"result = [] for value in map.values(): print('anagrams ', value) result += [sorted(value)]",
"in strs: target = ''.join(sorted(v)) print(target) if target not in map: map[target] =",
"+= [sorted(value)] return result def sort_anagrams(myList): def convert_strs_to_hashes(myList): d = dict() for anagram",
"result def sort_anagrams(myList): def convert_strs_to_hashes(myList): d = dict() for anagram in myList: h",
"dict() for anagram in myList: h = sum([ord(i) for i in anagram]) if",
"strs List[str] :rtype List[List[str]] \"\"\" map = {} for v in strs: target",
"for v in strs: target = ''.join(sorted(v)) print(target) if target not in map:",
"\"came\", \"care\", \"mace\", \"race\"] print(\"Before \", anagrams) print(\"After \", sort_anagrams(anagrams)) anagrams = [\"acme\",",
"myList or len(myList) < 2: return 0 if not myList else 1 d",
"target not in map: map[target] = [] map[target].append(v) print('building map ', map[target]) result",
"= dict() for anagram in myList: h = sum([ord(i) for i in anagram])",
"else 1 d = convert_strs_to_hashes(myList) outputList = [] for key, values in d.items():",
"in map.values(): print('anagrams ', value) result += [sorted(value)] return result def sort_anagrams(myList): def",
"result += [sorted(value)] return result def sort_anagrams(myList): def convert_strs_to_hashes(myList): d = dict() for",
"in d: d[h] = [] d[h].append(anagram) return d if not myList or len(myList)",
"\"acre\", \"came\", \"care\", \"mace\", \"race\"] print(\"Before \", anagrams) print(\"After \", sort_anagrams(anagrams)) anagrams =",
"or len(myList) < 2: return 0 if not myList else 1 d =",
"map[target]) result = [] for value in map.values(): print('anagrams ', value) result +=",
"outputList if __name__==\"__main__\": anagrams = [\"acme\", \"acre\", \"came\", \"care\", \"mace\", \"race\"] print(\"Before \",",
"[] d[h].append(anagram) return d if not myList or len(myList) < 2: return 0",
"myList else 1 d = convert_strs_to_hashes(myList) outputList = [] for key, values in",
"d = convert_strs_to_hashes(myList) outputList = [] for key, values in d.items(): outputList.extend(values) return",
"value) result += [sorted(value)] return result def sort_anagrams(myList): def convert_strs_to_hashes(myList): d = dict()",
"= ''.join(sorted(v)) print(target) if target not in map: map[target] = [] map[target].append(v) print('building",
"in d.items(): outputList.extend(values) return outputList if __name__==\"__main__\": anagrams = [\"acme\", \"acre\", \"came\", \"care\",",
"return result def sort_anagrams(myList): def convert_strs_to_hashes(myList): d = dict() for anagram in myList:",
"\"\"\" map = {} for v in strs: target = ''.join(sorted(v)) print(target) if",
"List[str] :rtype List[List[str]] \"\"\" map = {} for v in strs: target =",
"i in anagram]) if h not in d: d[h] = [] d[h].append(anagram) return",
"for key, values in d.items(): outputList.extend(values) return outputList if __name__==\"__main__\": anagrams = [\"acme\",",
"\"care\", \"mace\", \"race\"] print(\"Before \", anagrams) print(\"After \", sort_anagrams(anagrams)) anagrams = [\"acme\", \"acre\",",
"= [\"acme\", \"acre\", \"came\", \"care\", \"mace\", \"race\"] print(\"Before \", anagrams) print(\"After \", sort_anagrams_1(anagrams))",
"for i in anagram]) if h not in d: d[h] = [] d[h].append(anagram)",
"sort_anagrams_1(strs): \"\"\" :type strs List[str] :rtype List[List[str]] \"\"\" map = {} for v",
"', value) result += [sorted(value)] return result def sort_anagrams(myList): def convert_strs_to_hashes(myList): d =",
"__name__==\"__main__\": anagrams = [\"acme\", \"acre\", \"came\", \"care\", \"mace\", \"race\"] print(\"Before \", anagrams) print(\"After",
"strs: target = ''.join(sorted(v)) print(target) if target not in map: map[target] = []",
"d = dict() for anagram in myList: h = sum([ord(i) for i in",
"return outputList if __name__==\"__main__\": anagrams = [\"acme\", \"acre\", \"came\", \"care\", \"mace\", \"race\"] print(\"Before",
"= [] for key, values in d.items(): outputList.extend(values) return outputList if __name__==\"__main__\": anagrams",
"not in d: d[h] = [] d[h].append(anagram) return d if not myList or",
"in myList: h = sum([ord(i) for i in anagram]) if h not in",
"return 0 if not myList else 1 d = convert_strs_to_hashes(myList) outputList = []",
"', map[target]) result = [] for value in map.values(): print('anagrams ', value) result",
"sum([ord(i) for i in anagram]) if h not in d: d[h] = []",
"h = sum([ord(i) for i in anagram]) if h not in d: d[h]",
"0 if not myList else 1 d = convert_strs_to_hashes(myList) outputList = [] for",
"for anagram in myList: h = sum([ord(i) for i in anagram]) if h",
"map = {} for v in strs: target = ''.join(sorted(v)) print(target) if target",
"myList: h = sum([ord(i) for i in anagram]) if h not in d:",
"if __name__==\"__main__\": anagrams = [\"acme\", \"acre\", \"came\", \"care\", \"mace\", \"race\"] print(\"Before \", anagrams)",
"[\"acme\", \"acre\", \"came\", \"care\", \"mace\", \"race\"] print(\"Before \", anagrams) print(\"After \", sort_anagrams(anagrams)) anagrams",
"map.values(): print('anagrams ', value) result += [sorted(value)] return result def sort_anagrams(myList): def convert_strs_to_hashes(myList):",
"if h not in d: d[h] = [] d[h].append(anagram) return d if not",
"\", anagrams) print(\"After \", sort_anagrams(anagrams)) anagrams = [\"acme\", \"acre\", \"came\", \"care\", \"mace\", \"race\"]",
"= convert_strs_to_hashes(myList) outputList = [] for key, values in d.items(): outputList.extend(values) return outputList",
"anagram]) if h not in d: d[h] = [] d[h].append(anagram) return d if",
"= [\"acme\", \"acre\", \"came\", \"care\", \"mace\", \"race\"] print(\"Before \", anagrams) print(\"After \", sort_anagrams(anagrams))",
"\", sort_anagrams(anagrams)) anagrams = [\"acme\", \"acre\", \"came\", \"care\", \"mace\", \"race\"] print(\"Before \", anagrams)",
"= [] for value in map.values(): print('anagrams ', value) result += [sorted(value)] return",
"value in map.values(): print('anagrams ', value) result += [sorted(value)] return result def sort_anagrams(myList):",
"if target not in map: map[target] = [] map[target].append(v) print('building map ', map[target])",
"len(myList) < 2: return 0 if not myList else 1 d = convert_strs_to_hashes(myList)",
"2: return 0 if not myList else 1 d = convert_strs_to_hashes(myList) outputList =",
"print('anagrams ', value) result += [sorted(value)] return result def sort_anagrams(myList): def convert_strs_to_hashes(myList): d",
"not in map: map[target] = [] map[target].append(v) print('building map ', map[target]) result =",
"anagrams) print(\"After \", sort_anagrams(anagrams)) anagrams = [\"acme\", \"acre\", \"came\", \"care\", \"mace\", \"race\"] print(\"Before",
"in map: map[target] = [] map[target].append(v) print('building map ', map[target]) result = []",
"outputList.extend(values) return outputList if __name__==\"__main__\": anagrams = [\"acme\", \"acre\", \"came\", \"care\", \"mace\", \"race\"]",
"\"mace\", \"race\"] print(\"Before \", anagrams) print(\"After \", sort_anagrams(anagrams)) anagrams = [\"acme\", \"acre\", \"came\",",
"def sort_anagrams(myList): def convert_strs_to_hashes(myList): d = dict() for anagram in myList: h =",
"map: map[target] = [] map[target].append(v) print('building map ', map[target]) result = [] for",
"map[target].append(v) print('building map ', map[target]) result = [] for value in map.values(): print('anagrams",
"[sorted(value)] return result def sort_anagrams(myList): def convert_strs_to_hashes(myList): d = dict() for anagram in",
"anagrams = [\"acme\", \"acre\", \"came\", \"care\", \"mace\", \"race\"] print(\"Before \", anagrams) print(\"After \",",
"if not myList else 1 d = convert_strs_to_hashes(myList) outputList = [] for key,",
"\"race\"] print(\"Before \", anagrams) print(\"After \", sort_anagrams(anagrams)) anagrams = [\"acme\", \"acre\", \"came\", \"care\",",
"return d if not myList or len(myList) < 2: return 0 if not",
"= [] map[target].append(v) print('building map ', map[target]) result = [] for value in",
"for value in map.values(): print('anagrams ', value) result += [sorted(value)] return result def",
"d if not myList or len(myList) < 2: return 0 if not myList",
"not myList else 1 d = convert_strs_to_hashes(myList) outputList = [] for key, values",
"1 d = convert_strs_to_hashes(myList) outputList = [] for key, values in d.items(): outputList.extend(values)",
"sort_anagrams(myList): def convert_strs_to_hashes(myList): d = dict() for anagram in myList: h = sum([ord(i)",
"< 2: return 0 if not myList else 1 d = convert_strs_to_hashes(myList) outputList",
"def sort_anagrams_1(strs): \"\"\" :type strs List[str] :rtype List[List[str]] \"\"\" map = {} for",
"= [] d[h].append(anagram) return d if not myList or len(myList) < 2: return",
"List[List[str]] \"\"\" map = {} for v in strs: target = ''.join(sorted(v)) print(target)",
"print(\"Before \", anagrams) print(\"After \", sort_anagrams(anagrams)) anagrams = [\"acme\", \"acre\", \"came\", \"care\", \"mace\",",
"map ', map[target]) result = [] for value in map.values(): print('anagrams ', value)",
"print(\"After \", sort_anagrams(anagrams)) anagrams = [\"acme\", \"acre\", \"came\", \"care\", \"mace\", \"race\"] print(\"Before \",",
"convert_strs_to_hashes(myList) outputList = [] for key, values in d.items(): outputList.extend(values) return outputList if",
"[] for key, values in d.items(): outputList.extend(values) return outputList if __name__==\"__main__\": anagrams =",
"d.items(): outputList.extend(values) return outputList if __name__==\"__main__\": anagrams = [\"acme\", \"acre\", \"came\", \"care\", \"mace\",",
"not myList or len(myList) < 2: return 0 if not myList else 1",
"values in d.items(): outputList.extend(values) return outputList if __name__==\"__main__\": anagrams = [\"acme\", \"acre\", \"came\",",
"in anagram]) if h not in d: d[h] = [] d[h].append(anagram) return d",
"def convert_strs_to_hashes(myList): d = dict() for anagram in myList: h = sum([ord(i) for",
"d[h] = [] d[h].append(anagram) return d if not myList or len(myList) < 2:",
"sort_anagrams(anagrams)) anagrams = [\"acme\", \"acre\", \"came\", \"care\", \"mace\", \"race\"] print(\"Before \", anagrams) print(\"After",
"''.join(sorted(v)) print(target) if target not in map: map[target] = [] map[target].append(v) print('building map",
"target = ''.join(sorted(v)) print(target) if target not in map: map[target] = [] map[target].append(v)",
"v in strs: target = ''.join(sorted(v)) print(target) if target not in map: map[target]",
"print('building map ', map[target]) result = [] for value in map.values(): print('anagrams ',",
"anagram in myList: h = sum([ord(i) for i in anagram]) if h not"
] |
[
"type. One of: 'poisson', 'negbinom', 'powerlaw'. degseq_sort Should degree sequence be sorted by",
"rewiring. SDA_REP Number of independent realizations of adjacency matrices. SIM_PARAMS degseq_type Degree sequence",
"\"\"\"Run simulations for SDC model. Parameters ---------- N_JOBS Number of cores used for",
"frame gdf = None # graph data frame for s in SPACE: sim(s)",
"import os import gc import numpy as np import pandas as pd from",
"'poisson', 'negbinom', 'powerlaw'. degseq_sort Should degree sequence be sorted by expected node degrees.",
"# Run simulations if RANDOM_SEED is not None: np.random.seed(RANDOM_SEED) sim = lambda s:",
"= 2 # SDA params SDA_PARAMS = { 'k': (30,), 'alpha': (2, 4,",
"= ('uniform', 'lognormal', 'clusters_normal') N = (1000, 2000, 4000, 8000) NDIM = (1,",
"generator. SPACE Types of social space. Available values: 'uniform', 'lognormal', 'clusters_normal'. N Sizes",
"node degrees. \"\"\" import os import gc import numpy as np import pandas",
"('uniform', 'lognormal', 'clusters_normal') N = (1000, 2000, 4000, 8000) NDIM = (1, 2,",
"{ 'degseq_type': ('poisson', 'negbinom', 'powerlaw'), 'sort': (True, False) } @MEMORY.cache(ignore=['n_jobs']) def simulate_cm(space, dparams,",
"drep=DATA_REP, sdaparams=SDA_PARAMS, sdarep=SDA_REP, simparams=SIM_PARAMS, n_jobs=N_JOBS ) df = None # main data frame",
"s in SPACE: print(f\"\\rloading and processing '{s}' space' ...\", end=\"\") _df = sim(s)",
"4000, 8000) NDIM = (1, 2, 4, 8, 16) CENTERS = (4,) DATA_REP",
"separate pickle file. # It will be used for graph visualizations. os.makedirs(DATAPATH, exist_ok=True)",
"Globals ROOT = os.path.dirname(os.path.realpath(__file__)) HERE = ROOT DATAPATH = os.path.join(HERE, 'raw-data') # Persistence",
"Data generation params RANDOM_SEED = 101 SPACE = ('uniform', 'lognormal', 'clusters_normal') N =",
"# Save data ------------------------------------------------------------------- # Standard data get saved as feather file, so",
"so it can be easily # shared with R for data analysis and",
"# shared with R for data analysis and visualization. # Adjacency matrices data",
"# Adjacency matrices data is saved as a separate pickle file. # It",
"os.path.dirname(os.path.realpath(__file__)) HERE = ROOT DATAPATH = os.path.join(HERE, 'raw-data') # Persistence MEMORY = Memory(location='.cache',",
"(1000, 2000, 4000, 8000) NDIM = (1, 2, 4, 8, 16) CENTERS =",
"data as a feather file df.to_feather(os.path.join(DATAPATH, 'sda-data-cm.feather')) # Save graph data as a",
"N = (1000, 2000, 4000, 8000) NDIM = (1, 2, 4, 8, 16)",
"data frame for s in SPACE: sim(s) gc.collect() for s in SPACE: print(f\"\\rloading",
"space' ...\", end=\"\") _df = sim(s) _df.drop(columns=['A', 'labels'], inplace=True) if df is None:",
"inplace=True) if df is None: df = _df else: df = pd.concat((df, _df),",
"networks, NDIM Number of dimensions of simulated social spaces. DATA_REP Number of independent",
"is None: df = _df else: df = pd.concat((df, _df), ignore_index=True) # Save",
"feather file, so it can be easily # shared with R for data",
"(1, 2, 4, 8, 16) CENTERS = (4,) DATA_REP = 2 # SDA",
"of social spaces. SDA_PARAMS k Expected average degree. alpha Homophily level. directed Directed/undirected",
"} SDA_REP = 3 SIM_PARAMS = { 'degseq_type': ('poisson', 'negbinom', 'powerlaw'), 'sort': (True,",
"used for parallelization. RANDOM_SEED Seed for the random numbers generator. SPACE Types of",
"Persistence MEMORY = Memory(location='.cache', verbose=1) N_JOBS = 4 # Data generation params RANDOM_SEED",
"'powerlaw'), 'sort': (True, False) } @MEMORY.cache(ignore=['n_jobs']) def simulate_cm(space, dparams, drep, sdaparams, sdarep, simparams,",
"= pd.concat((df, _df), ignore_index=True) # Save data ------------------------------------------------------------------- # Standard data get saved",
"simulate_cm( space=s, dparams=(N, NDIM, CENTERS), drep=DATA_REP, sdaparams=SDA_PARAMS, sdarep=SDA_REP, simparams=SIM_PARAMS, n_jobs=N_JOBS ) df =",
"visualization. # Adjacency matrices data is saved as a separate pickle file. #",
"N Sizes of networks, NDIM Number of dimensions of simulated social spaces. DATA_REP",
"Save main data as a feather file df.to_feather(os.path.join(DATAPATH, 'sda-data-cm.feather')) # Save graph data",
"= lambda s: simulate_cm( space=s, dparams=(N, NDIM, CENTERS), drep=DATA_REP, sdaparams=SDA_PARAMS, sdarep=SDA_REP, simparams=SIM_PARAMS, n_jobs=N_JOBS",
"degseq_type Degree sequence type. One of: 'poisson', 'negbinom', 'powerlaw'. degseq_sort Should degree sequence",
"s in SPACE: sim(s) gc.collect() for s in SPACE: print(f\"\\rloading and processing '{s}'",
"4, 8, 16) CENTERS = (4,) DATA_REP = 2 # SDA params SDA_PARAMS",
"pd from sklearn.externals.joblib import Memory import _ # Globals ROOT = os.path.dirname(os.path.realpath(__file__)) HERE",
"simparams, n_jobs, simfunc=_.run_sdac) # Run simulations if RANDOM_SEED is not None: np.random.seed(RANDOM_SEED) sim",
"networks. p_rewire Probability of random rewiring. SDA_REP Number of independent realizations of adjacency",
"np import pandas as pd from sklearn.externals.joblib import Memory import _ # Globals",
"DATA_REP = 2 # SDA params SDA_PARAMS = { 'k': (30,), 'alpha': (2,",
"df = pd.concat((df, _df), ignore_index=True) # Save data ------------------------------------------------------------------- # Standard data get",
"graph visualizations. os.makedirs(DATAPATH, exist_ok=True) # Save main data as a feather file df.to_feather(os.path.join(DATAPATH,",
"df = _df else: df = pd.concat((df, _df), ignore_index=True) # Save data -------------------------------------------------------------------",
"Types of social space. Available values: 'uniform', 'lognormal', 'clusters_normal'. N Sizes of networks,",
"# Persistence MEMORY = Memory(location='.cache', verbose=1) N_JOBS = 4 # Data generation params",
"Save data ------------------------------------------------------------------- # Standard data get saved as feather file, so it",
"spaces. DATA_REP Number of independent realizations of social spaces. SDA_PARAMS k Expected average",
"lambda s: simulate_cm( space=s, dparams=(N, NDIM, CENTERS), drep=DATA_REP, sdaparams=SDA_PARAMS, sdarep=SDA_REP, simparams=SIM_PARAMS, n_jobs=N_JOBS )",
"{ 'k': (30,), 'alpha': (2, 4, 8, np.inf), 'directed': (False,), 'p_rewire': (.01,) }",
"sorted by expected node degrees. \"\"\" import os import gc import numpy as",
"'{s}' space' ...\", end=\"\") _df = sim(s) _df.drop(columns=['A', 'labels'], inplace=True) if df is",
"saved as feather file, so it can be easily # shared with R",
"data get saved as feather file, so it can be easily # shared",
"main data frame gdf = None # graph data frame for s in",
"SDA_REP Number of independent realizations of adjacency matrices. SIM_PARAMS degseq_type Degree sequence type.",
"(30,), 'alpha': (2, 4, 8, np.inf), 'directed': (False,), 'p_rewire': (.01,) } SDA_REP =",
"# Standard data get saved as feather file, so it can be easily",
"_.simulate(space, dparams, drep, sdaparams, sdarep, simparams, n_jobs, simfunc=_.run_sdac) # Run simulations if RANDOM_SEED",
"gc import numpy as np import pandas as pd from sklearn.externals.joblib import Memory",
"data ------------------------------------------------------------------- # Standard data get saved as feather file, so it can",
"None: np.random.seed(RANDOM_SEED) sim = lambda s: simulate_cm( space=s, dparams=(N, NDIM, CENTERS), drep=DATA_REP, sdaparams=SDA_PARAMS,",
"used for graph visualizations. os.makedirs(DATAPATH, exist_ok=True) # Save main data as a feather",
"sdarep, simparams, n_jobs, simfunc=_.run_sdac) # Run simulations if RANDOM_SEED is not None: np.random.seed(RANDOM_SEED)",
"RANDOM_SEED Seed for the random numbers generator. SPACE Types of social space. Available",
"One of: 'poisson', 'negbinom', 'powerlaw'. degseq_sort Should degree sequence be sorted by expected",
"file, so it can be easily # shared with R for data analysis",
"can be easily # shared with R for data analysis and visualization. #",
"data analysis and visualization. # Adjacency matrices data is saved as a separate",
"of: 'poisson', 'negbinom', 'powerlaw'. degseq_sort Should degree sequence be sorted by expected node",
"NDIM Number of dimensions of simulated social spaces. DATA_REP Number of independent realizations",
"sdarep, simparams, n_jobs): return _.simulate(space, dparams, drep, sdaparams, sdarep, simparams, n_jobs, simfunc=_.run_sdac) #",
"exist_ok=True) # Save main data as a feather file df.to_feather(os.path.join(DATAPATH, 'sda-data-cm.feather')) # Save",
"model. Parameters ---------- N_JOBS Number of cores used for parallelization. RANDOM_SEED Seed for",
"cores used for parallelization. RANDOM_SEED Seed for the random numbers generator. SPACE Types",
"N_JOBS Number of cores used for parallelization. RANDOM_SEED Seed for the random numbers",
"NDIM, CENTERS), drep=DATA_REP, sdaparams=SDA_PARAMS, sdarep=SDA_REP, simparams=SIM_PARAMS, n_jobs=N_JOBS ) df = None # main",
"# main data frame gdf = None # graph data frame for s",
"data frame gdf = None # graph data frame for s in SPACE:",
"16) CENTERS = (4,) DATA_REP = 2 # SDA params SDA_PARAMS = {",
"= (4,) DATA_REP = 2 # SDA params SDA_PARAMS = { 'k': (30,),",
"dparams=(N, NDIM, CENTERS), drep=DATA_REP, sdaparams=SDA_PARAMS, sdarep=SDA_REP, simparams=SIM_PARAMS, n_jobs=N_JOBS ) df = None #",
"Run simulations if RANDOM_SEED is not None: np.random.seed(RANDOM_SEED) sim = lambda s: simulate_cm(",
"of independent realizations of social spaces. SDA_PARAMS k Expected average degree. alpha Homophily",
"= (1000, 2000, 4000, 8000) NDIM = (1, 2, 4, 8, 16) CENTERS",
"'lognormal', 'clusters_normal') N = (1000, 2000, 4000, 8000) NDIM = (1, 2, 4,",
"degseq_sort Should degree sequence be sorted by expected node degrees. \"\"\" import os",
"Directed/undirected networks. p_rewire Probability of random rewiring. SDA_REP Number of independent realizations of",
"matrices. SIM_PARAMS degseq_type Degree sequence type. One of: 'poisson', 'negbinom', 'powerlaw'. degseq_sort Should",
"'powerlaw'. degseq_sort Should degree sequence be sorted by expected node degrees. \"\"\" import",
"'negbinom', 'powerlaw'. degseq_sort Should degree sequence be sorted by expected node degrees. \"\"\"",
"and processing '{s}' space' ...\", end=\"\") _df = sim(s) _df.drop(columns=['A', 'labels'], inplace=True) if",
"'k': (30,), 'alpha': (2, 4, 8, np.inf), 'directed': (False,), 'p_rewire': (.01,) } SDA_REP",
"file df.to_feather(os.path.join(DATAPATH, 'sda-data-cm.feather')) # Save graph data as a pickle file # joblib.dump(gdf,",
"not None: np.random.seed(RANDOM_SEED) sim = lambda s: simulate_cm( space=s, dparams=(N, NDIM, CENTERS), drep=DATA_REP,",
"the random numbers generator. SPACE Types of social space. Available values: 'uniform', 'lognormal',",
"DATA_REP Number of independent realizations of social spaces. SDA_PARAMS k Expected average degree.",
"social spaces. SDA_PARAMS k Expected average degree. alpha Homophily level. directed Directed/undirected networks.",
"SDA params SDA_PARAMS = { 'k': (30,), 'alpha': (2, 4, 8, np.inf), 'directed':",
"be sorted by expected node degrees. \"\"\" import os import gc import numpy",
"average degree. alpha Homophily level. directed Directed/undirected networks. p_rewire Probability of random rewiring.",
"from sklearn.externals.joblib import Memory import _ # Globals ROOT = os.path.dirname(os.path.realpath(__file__)) HERE =",
"values: 'uniform', 'lognormal', 'clusters_normal'. N Sizes of networks, NDIM Number of dimensions of",
"2000, 4000, 8000) NDIM = (1, 2, 4, 8, 16) CENTERS = (4,)",
"'lognormal', 'clusters_normal'. N Sizes of networks, NDIM Number of dimensions of simulated social",
"(True, False) } @MEMORY.cache(ignore=['n_jobs']) def simulate_cm(space, dparams, drep, sdaparams, sdarep, simparams, n_jobs): return",
"def simulate_cm(space, dparams, drep, sdaparams, sdarep, simparams, n_jobs): return _.simulate(space, dparams, drep, sdaparams,",
"It will be used for graph visualizations. os.makedirs(DATAPATH, exist_ok=True) # Save main data",
"'clusters_normal'. N Sizes of networks, NDIM Number of dimensions of simulated social spaces.",
"with R for data analysis and visualization. # Adjacency matrices data is saved",
"simulations for SDC model. Parameters ---------- N_JOBS Number of cores used for parallelization.",
"# It will be used for graph visualizations. os.makedirs(DATAPATH, exist_ok=True) # Save main",
"np.inf), 'directed': (False,), 'p_rewire': (.01,) } SDA_REP = 3 SIM_PARAMS = { 'degseq_type':",
"numbers generator. SPACE Types of social space. Available values: 'uniform', 'lognormal', 'clusters_normal'. N",
"ignore_index=True) # Save data ------------------------------------------------------------------- # Standard data get saved as feather file,",
"independent realizations of social spaces. SDA_PARAMS k Expected average degree. alpha Homophily level.",
"analysis and visualization. # Adjacency matrices data is saved as a separate pickle",
"for s in SPACE: print(f\"\\rloading and processing '{s}' space' ...\", end=\"\") _df =",
"# Save main data as a feather file df.to_feather(os.path.join(DATAPATH, 'sda-data-cm.feather')) # Save graph",
"level. directed Directed/undirected networks. p_rewire Probability of random rewiring. SDA_REP Number of independent",
"2 # SDA params SDA_PARAMS = { 'k': (30,), 'alpha': (2, 4, 8,",
"None # graph data frame for s in SPACE: sim(s) gc.collect() for s",
"Probability of random rewiring. SDA_REP Number of independent realizations of adjacency matrices. SIM_PARAMS",
"(2, 4, 8, np.inf), 'directed': (False,), 'p_rewire': (.01,) } SDA_REP = 3 SIM_PARAMS",
"sim = lambda s: simulate_cm( space=s, dparams=(N, NDIM, CENTERS), drep=DATA_REP, sdaparams=SDA_PARAMS, sdarep=SDA_REP, simparams=SIM_PARAMS,",
"import gc import numpy as np import pandas as pd from sklearn.externals.joblib import",
"'degseq_type': ('poisson', 'negbinom', 'powerlaw'), 'sort': (True, False) } @MEMORY.cache(ignore=['n_jobs']) def simulate_cm(space, dparams, drep,",
"be used for graph visualizations. os.makedirs(DATAPATH, exist_ok=True) # Save main data as a",
"import pandas as pd from sklearn.externals.joblib import Memory import _ # Globals ROOT",
"= { 'k': (30,), 'alpha': (2, 4, 8, np.inf), 'directed': (False,), 'p_rewire': (.01,)",
"end=\"\") _df = sim(s) _df.drop(columns=['A', 'labels'], inplace=True) if df is None: df =",
"of cores used for parallelization. RANDOM_SEED Seed for the random numbers generator. SPACE",
"for the random numbers generator. SPACE Types of social space. Available values: 'uniform',",
"sdaparams, sdarep, simparams, n_jobs, simfunc=_.run_sdac) # Run simulations if RANDOM_SEED is not None:",
"'raw-data') # Persistence MEMORY = Memory(location='.cache', verbose=1) N_JOBS = 4 # Data generation",
"df is None: df = _df else: df = pd.concat((df, _df), ignore_index=True) #",
"np.random.seed(RANDOM_SEED) sim = lambda s: simulate_cm( space=s, dparams=(N, NDIM, CENTERS), drep=DATA_REP, sdaparams=SDA_PARAMS, sdarep=SDA_REP,",
"= _df else: df = pd.concat((df, _df), ignore_index=True) # Save data ------------------------------------------------------------------- #",
"n_jobs): return _.simulate(space, dparams, drep, sdaparams, sdarep, simparams, n_jobs, simfunc=_.run_sdac) # Run simulations",
"verbose=1) N_JOBS = 4 # Data generation params RANDOM_SEED = 101 SPACE =",
"= os.path.join(HERE, 'raw-data') # Persistence MEMORY = Memory(location='.cache', verbose=1) N_JOBS = 4 #",
"SPACE: sim(s) gc.collect() for s in SPACE: print(f\"\\rloading and processing '{s}' space' ...\",",
"MEMORY = Memory(location='.cache', verbose=1) N_JOBS = 4 # Data generation params RANDOM_SEED =",
"= 4 # Data generation params RANDOM_SEED = 101 SPACE = ('uniform', 'lognormal',",
"# Globals ROOT = os.path.dirname(os.path.realpath(__file__)) HERE = ROOT DATAPATH = os.path.join(HERE, 'raw-data') #",
"adjacency matrices. SIM_PARAMS degseq_type Degree sequence type. One of: 'poisson', 'negbinom', 'powerlaw'. degseq_sort",
"simparams, n_jobs): return _.simulate(space, dparams, drep, sdaparams, sdarep, simparams, n_jobs, simfunc=_.run_sdac) # Run",
"N_JOBS = 4 # Data generation params RANDOM_SEED = 101 SPACE = ('uniform',",
"SIM_PARAMS = { 'degseq_type': ('poisson', 'negbinom', 'powerlaw'), 'sort': (True, False) } @MEMORY.cache(ignore=['n_jobs']) def",
"a separate pickle file. # It will be used for graph visualizations. os.makedirs(DATAPATH,",
"= 3 SIM_PARAMS = { 'degseq_type': ('poisson', 'negbinom', 'powerlaw'), 'sort': (True, False) }",
"s: simulate_cm( space=s, dparams=(N, NDIM, CENTERS), drep=DATA_REP, sdaparams=SDA_PARAMS, sdarep=SDA_REP, simparams=SIM_PARAMS, n_jobs=N_JOBS ) df",
"random rewiring. SDA_REP Number of independent realizations of adjacency matrices. SIM_PARAMS degseq_type Degree",
"of simulated social spaces. DATA_REP Number of independent realizations of social spaces. SDA_PARAMS",
"for parallelization. RANDOM_SEED Seed for the random numbers generator. SPACE Types of social",
"numpy as np import pandas as pd from sklearn.externals.joblib import Memory import _",
"_df = sim(s) _df.drop(columns=['A', 'labels'], inplace=True) if df is None: df = _df",
"p_rewire Probability of random rewiring. SDA_REP Number of independent realizations of adjacency matrices.",
"Degree sequence type. One of: 'poisson', 'negbinom', 'powerlaw'. degseq_sort Should degree sequence be",
"for graph visualizations. os.makedirs(DATAPATH, exist_ok=True) # Save main data as a feather file",
"('poisson', 'negbinom', 'powerlaw'), 'sort': (True, False) } @MEMORY.cache(ignore=['n_jobs']) def simulate_cm(space, dparams, drep, sdaparams,",
"sklearn.externals.joblib import Memory import _ # Globals ROOT = os.path.dirname(os.path.realpath(__file__)) HERE = ROOT",
"None # main data frame gdf = None # graph data frame for",
"realizations of social spaces. SDA_PARAMS k Expected average degree. alpha Homophily level. directed",
"sequence type. One of: 'poisson', 'negbinom', 'powerlaw'. degseq_sort Should degree sequence be sorted",
"Homophily level. directed Directed/undirected networks. p_rewire Probability of random rewiring. SDA_REP Number of",
"file. # It will be used for graph visualizations. os.makedirs(DATAPATH, exist_ok=True) # Save",
"False) } @MEMORY.cache(ignore=['n_jobs']) def simulate_cm(space, dparams, drep, sdaparams, sdarep, simparams, n_jobs): return _.simulate(space,",
"'sort': (True, False) } @MEMORY.cache(ignore=['n_jobs']) def simulate_cm(space, dparams, drep, sdaparams, sdarep, simparams, n_jobs):",
"= { 'degseq_type': ('poisson', 'negbinom', 'powerlaw'), 'sort': (True, False) } @MEMORY.cache(ignore=['n_jobs']) def simulate_cm(space,",
"'sda-data-cm.feather')) # Save graph data as a pickle file # joblib.dump(gdf, os.path.join(DATAPATH, 'sda-graphs-cm.pkl'))",
"ROOT DATAPATH = os.path.join(HERE, 'raw-data') # Persistence MEMORY = Memory(location='.cache', verbose=1) N_JOBS =",
"Number of cores used for parallelization. RANDOM_SEED Seed for the random numbers generator.",
"Sizes of networks, NDIM Number of dimensions of simulated social spaces. DATA_REP Number",
"by expected node degrees. \"\"\" import os import gc import numpy as np",
"SPACE: print(f\"\\rloading and processing '{s}' space' ...\", end=\"\") _df = sim(s) _df.drop(columns=['A', 'labels'],",
"'uniform', 'lognormal', 'clusters_normal'. N Sizes of networks, NDIM Number of dimensions of simulated",
"os.makedirs(DATAPATH, exist_ok=True) # Save main data as a feather file df.to_feather(os.path.join(DATAPATH, 'sda-data-cm.feather')) #",
"simulations if RANDOM_SEED is not None: np.random.seed(RANDOM_SEED) sim = lambda s: simulate_cm( space=s,",
"HERE = ROOT DATAPATH = os.path.join(HERE, 'raw-data') # Persistence MEMORY = Memory(location='.cache', verbose=1)",
"social spaces. DATA_REP Number of independent realizations of social spaces. SDA_PARAMS k Expected",
"matrices data is saved as a separate pickle file. # It will be",
"pickle file. # It will be used for graph visualizations. os.makedirs(DATAPATH, exist_ok=True) #",
"Adjacency matrices data is saved as a separate pickle file. # It will",
"frame for s in SPACE: sim(s) gc.collect() for s in SPACE: print(f\"\\rloading and",
"\"\"\" import os import gc import numpy as np import pandas as pd",
"data is saved as a separate pickle file. # It will be used",
"df.to_feather(os.path.join(DATAPATH, 'sda-data-cm.feather')) # Save graph data as a pickle file # joblib.dump(gdf, os.path.join(DATAPATH,",
"None: df = _df else: df = pd.concat((df, _df), ignore_index=True) # Save data",
"alpha Homophily level. directed Directed/undirected networks. p_rewire Probability of random rewiring. SDA_REP Number",
"= (1, 2, 4, 8, 16) CENTERS = (4,) DATA_REP = 2 #",
"processing '{s}' space' ...\", end=\"\") _df = sim(s) _df.drop(columns=['A', 'labels'], inplace=True) if df",
"in SPACE: print(f\"\\rloading and processing '{s}' space' ...\", end=\"\") _df = sim(s) _df.drop(columns=['A',",
"gdf = None # graph data frame for s in SPACE: sim(s) gc.collect()",
"is saved as a separate pickle file. # It will be used for",
"3 SIM_PARAMS = { 'degseq_type': ('poisson', 'negbinom', 'powerlaw'), 'sort': (True, False) } @MEMORY.cache(ignore=['n_jobs'])",
"'labels'], inplace=True) if df is None: df = _df else: df = pd.concat((df,",
"(4,) DATA_REP = 2 # SDA params SDA_PARAMS = { 'k': (30,), 'alpha':",
"of random rewiring. SDA_REP Number of independent realizations of adjacency matrices. SIM_PARAMS degseq_type",
"Number of dimensions of simulated social spaces. DATA_REP Number of independent realizations of",
"= os.path.dirname(os.path.realpath(__file__)) HERE = ROOT DATAPATH = os.path.join(HERE, 'raw-data') # Persistence MEMORY =",
"df = None # main data frame gdf = None # graph data",
"4, 8, np.inf), 'directed': (False,), 'p_rewire': (.01,) } SDA_REP = 3 SIM_PARAMS =",
"8000) NDIM = (1, 2, 4, 8, 16) CENTERS = (4,) DATA_REP =",
"dparams, drep, sdaparams, sdarep, simparams, n_jobs): return _.simulate(space, dparams, drep, sdaparams, sdarep, simparams,",
"spaces. SDA_PARAMS k Expected average degree. alpha Homophily level. directed Directed/undirected networks. p_rewire",
"SIM_PARAMS degseq_type Degree sequence type. One of: 'poisson', 'negbinom', 'powerlaw'. degseq_sort Should degree",
"SPACE Types of social space. Available values: 'uniform', 'lognormal', 'clusters_normal'. N Sizes of",
"gc.collect() for s in SPACE: print(f\"\\rloading and processing '{s}' space' ...\", end=\"\") _df",
"main data as a feather file df.to_feather(os.path.join(DATAPATH, 'sda-data-cm.feather')) # Save graph data as",
"'p_rewire': (.01,) } SDA_REP = 3 SIM_PARAMS = { 'degseq_type': ('poisson', 'negbinom', 'powerlaw'),",
"import Memory import _ # Globals ROOT = os.path.dirname(os.path.realpath(__file__)) HERE = ROOT DATAPATH",
"Number of independent realizations of adjacency matrices. SIM_PARAMS degseq_type Degree sequence type. One",
"directed Directed/undirected networks. p_rewire Probability of random rewiring. SDA_REP Number of independent realizations",
"for data analysis and visualization. # Adjacency matrices data is saved as a",
"------------------------------------------------------------------- # Standard data get saved as feather file, so it can be",
"generation params RANDOM_SEED = 101 SPACE = ('uniform', 'lognormal', 'clusters_normal') N = (1000,",
"if df is None: df = _df else: df = pd.concat((df, _df), ignore_index=True)",
"= Memory(location='.cache', verbose=1) N_JOBS = 4 # Data generation params RANDOM_SEED = 101",
"as a feather file df.to_feather(os.path.join(DATAPATH, 'sda-data-cm.feather')) # Save graph data as a pickle",
"drep, sdaparams, sdarep, simparams, n_jobs): return _.simulate(space, dparams, drep, sdaparams, sdarep, simparams, n_jobs,",
"degrees. \"\"\" import os import gc import numpy as np import pandas as",
"in SPACE: sim(s) gc.collect() for s in SPACE: print(f\"\\rloading and processing '{s}' space'",
"params SDA_PARAMS = { 'k': (30,), 'alpha': (2, 4, 8, np.inf), 'directed': (False,),",
"parallelization. RANDOM_SEED Seed for the random numbers generator. SPACE Types of social space.",
"CENTERS = (4,) DATA_REP = 2 # SDA params SDA_PARAMS = { 'k':",
"pandas as pd from sklearn.externals.joblib import Memory import _ # Globals ROOT =",
"visualizations. os.makedirs(DATAPATH, exist_ok=True) # Save main data as a feather file df.to_feather(os.path.join(DATAPATH, 'sda-data-cm.feather'))",
"Should degree sequence be sorted by expected node degrees. \"\"\" import os import",
"random numbers generator. SPACE Types of social space. Available values: 'uniform', 'lognormal', 'clusters_normal'.",
"} @MEMORY.cache(ignore=['n_jobs']) def simulate_cm(space, dparams, drep, sdaparams, sdarep, simparams, n_jobs): return _.simulate(space, dparams,",
"_df), ignore_index=True) # Save data ------------------------------------------------------------------- # Standard data get saved as feather",
"graph data frame for s in SPACE: sim(s) gc.collect() for s in SPACE:",
"'alpha': (2, 4, 8, np.inf), 'directed': (False,), 'p_rewire': (.01,) } SDA_REP = 3",
"of adjacency matrices. SIM_PARAMS degseq_type Degree sequence type. One of: 'poisson', 'negbinom', 'powerlaw'.",
"101 SPACE = ('uniform', 'lognormal', 'clusters_normal') N = (1000, 2000, 4000, 8000) NDIM",
"realizations of adjacency matrices. SIM_PARAMS degseq_type Degree sequence type. One of: 'poisson', 'negbinom',",
"simulated social spaces. DATA_REP Number of independent realizations of social spaces. SDA_PARAMS k",
"Memory(location='.cache', verbose=1) N_JOBS = 4 # Data generation params RANDOM_SEED = 101 SPACE",
"as np import pandas as pd from sklearn.externals.joblib import Memory import _ #",
"SDA_REP = 3 SIM_PARAMS = { 'degseq_type': ('poisson', 'negbinom', 'powerlaw'), 'sort': (True, False)",
"RANDOM_SEED is not None: np.random.seed(RANDOM_SEED) sim = lambda s: simulate_cm( space=s, dparams=(N, NDIM,",
"degree sequence be sorted by expected node degrees. \"\"\" import os import gc",
"simfunc=_.run_sdac) # Run simulations if RANDOM_SEED is not None: np.random.seed(RANDOM_SEED) sim = lambda",
"else: df = pd.concat((df, _df), ignore_index=True) # Save data ------------------------------------------------------------------- # Standard data",
"sdaparams, sdarep, simparams, n_jobs): return _.simulate(space, dparams, drep, sdaparams, sdarep, simparams, n_jobs, simfunc=_.run_sdac)",
"import numpy as np import pandas as pd from sklearn.externals.joblib import Memory import",
"easily # shared with R for data analysis and visualization. # Adjacency matrices",
"space. Available values: 'uniform', 'lognormal', 'clusters_normal'. N Sizes of networks, NDIM Number of",
"sdaparams=SDA_PARAMS, sdarep=SDA_REP, simparams=SIM_PARAMS, n_jobs=N_JOBS ) df = None # main data frame gdf",
"sequence be sorted by expected node degrees. \"\"\" import os import gc import",
"of dimensions of simulated social spaces. DATA_REP Number of independent realizations of social",
"SDA_PARAMS = { 'k': (30,), 'alpha': (2, 4, 8, np.inf), 'directed': (False,), 'p_rewire':",
"of networks, NDIM Number of dimensions of simulated social spaces. DATA_REP Number of",
"k Expected average degree. alpha Homophily level. directed Directed/undirected networks. p_rewire Probability of",
"for s in SPACE: sim(s) gc.collect() for s in SPACE: print(f\"\\rloading and processing",
"feather file df.to_feather(os.path.join(DATAPATH, 'sda-data-cm.feather')) # Save graph data as a pickle file #",
"a feather file df.to_feather(os.path.join(DATAPATH, 'sda-data-cm.feather')) # Save graph data as a pickle file",
"= 101 SPACE = ('uniform', 'lognormal', 'clusters_normal') N = (1000, 2000, 4000, 8000)",
"Memory import _ # Globals ROOT = os.path.dirname(os.path.realpath(__file__)) HERE = ROOT DATAPATH =",
"pd.concat((df, _df), ignore_index=True) # Save data ------------------------------------------------------------------- # Standard data get saved as",
"shared with R for data analysis and visualization. # Adjacency matrices data is",
"= None # main data frame gdf = None # graph data frame",
"n_jobs, simfunc=_.run_sdac) # Run simulations if RANDOM_SEED is not None: np.random.seed(RANDOM_SEED) sim =",
"...\", end=\"\") _df = sim(s) _df.drop(columns=['A', 'labels'], inplace=True) if df is None: df",
"os import gc import numpy as np import pandas as pd from sklearn.externals.joblib",
"= None # graph data frame for s in SPACE: sim(s) gc.collect() for",
"dimensions of simulated social spaces. DATA_REP Number of independent realizations of social spaces.",
"4 # Data generation params RANDOM_SEED = 101 SPACE = ('uniform', 'lognormal', 'clusters_normal')",
"degree. alpha Homophily level. directed Directed/undirected networks. p_rewire Probability of random rewiring. SDA_REP",
"of independent realizations of adjacency matrices. SIM_PARAMS degseq_type Degree sequence type. One of:",
"sim(s) _df.drop(columns=['A', 'labels'], inplace=True) if df is None: df = _df else: df",
"dparams, drep, sdaparams, sdarep, simparams, n_jobs, simfunc=_.run_sdac) # Run simulations if RANDOM_SEED is",
"as feather file, so it can be easily # shared with R for",
"# SDA params SDA_PARAMS = { 'k': (30,), 'alpha': (2, 4, 8, np.inf),",
"will be used for graph visualizations. os.makedirs(DATAPATH, exist_ok=True) # Save main data as",
"'clusters_normal') N = (1000, 2000, 4000, 8000) NDIM = (1, 2, 4, 8,",
"8, np.inf), 'directed': (False,), 'p_rewire': (.01,) } SDA_REP = 3 SIM_PARAMS = {",
"get saved as feather file, so it can be easily # shared with",
"of social space. Available values: 'uniform', 'lognormal', 'clusters_normal'. N Sizes of networks, NDIM",
"2, 4, 8, 16) CENTERS = (4,) DATA_REP = 2 # SDA params",
"ROOT = os.path.dirname(os.path.realpath(__file__)) HERE = ROOT DATAPATH = os.path.join(HERE, 'raw-data') # Persistence MEMORY",
"Seed for the random numbers generator. SPACE Types of social space. Available values:",
"simulate_cm(space, dparams, drep, sdaparams, sdarep, simparams, n_jobs): return _.simulate(space, dparams, drep, sdaparams, sdarep,",
"be easily # shared with R for data analysis and visualization. # Adjacency",
"# Data generation params RANDOM_SEED = 101 SPACE = ('uniform', 'lognormal', 'clusters_normal') N",
"as a separate pickle file. # It will be used for graph visualizations.",
"sim(s) gc.collect() for s in SPACE: print(f\"\\rloading and processing '{s}' space' ...\", end=\"\")",
"print(f\"\\rloading and processing '{s}' space' ...\", end=\"\") _df = sim(s) _df.drop(columns=['A', 'labels'], inplace=True)",
"as pd from sklearn.externals.joblib import Memory import _ # Globals ROOT = os.path.dirname(os.path.realpath(__file__))",
"SPACE = ('uniform', 'lognormal', 'clusters_normal') N = (1000, 2000, 4000, 8000) NDIM =",
"simparams=SIM_PARAMS, n_jobs=N_JOBS ) df = None # main data frame gdf = None",
") df = None # main data frame gdf = None # graph",
"Number of independent realizations of social spaces. SDA_PARAMS k Expected average degree. alpha",
"it can be easily # shared with R for data analysis and visualization.",
"---------- N_JOBS Number of cores used for parallelization. RANDOM_SEED Seed for the random",
"DATAPATH = os.path.join(HERE, 'raw-data') # Persistence MEMORY = Memory(location='.cache', verbose=1) N_JOBS = 4",
"R for data analysis and visualization. # Adjacency matrices data is saved as",
"Standard data get saved as feather file, so it can be easily #",
"'negbinom', 'powerlaw'), 'sort': (True, False) } @MEMORY.cache(ignore=['n_jobs']) def simulate_cm(space, dparams, drep, sdaparams, sdarep,",
"return _.simulate(space, dparams, drep, sdaparams, sdarep, simparams, n_jobs, simfunc=_.run_sdac) # Run simulations if",
"import _ # Globals ROOT = os.path.dirname(os.path.realpath(__file__)) HERE = ROOT DATAPATH = os.path.join(HERE,",
"social space. Available values: 'uniform', 'lognormal', 'clusters_normal'. N Sizes of networks, NDIM Number",
"and visualization. # Adjacency matrices data is saved as a separate pickle file.",
"Available values: 'uniform', 'lognormal', 'clusters_normal'. N Sizes of networks, NDIM Number of dimensions",
"n_jobs=N_JOBS ) df = None # main data frame gdf = None #",
"SDA_PARAMS k Expected average degree. alpha Homophily level. directed Directed/undirected networks. p_rewire Probability",
"Expected average degree. alpha Homophily level. directed Directed/undirected networks. p_rewire Probability of random",
"for SDC model. Parameters ---------- N_JOBS Number of cores used for parallelization. RANDOM_SEED",
"drep, sdaparams, sdarep, simparams, n_jobs, simfunc=_.run_sdac) # Run simulations if RANDOM_SEED is not",
"# graph data frame for s in SPACE: sim(s) gc.collect() for s in",
"= sim(s) _df.drop(columns=['A', 'labels'], inplace=True) if df is None: df = _df else:",
"expected node degrees. \"\"\" import os import gc import numpy as np import",
"CENTERS), drep=DATA_REP, sdaparams=SDA_PARAMS, sdarep=SDA_REP, simparams=SIM_PARAMS, n_jobs=N_JOBS ) df = None # main data",
"_ # Globals ROOT = os.path.dirname(os.path.realpath(__file__)) HERE = ROOT DATAPATH = os.path.join(HERE, 'raw-data')",
"SDC model. Parameters ---------- N_JOBS Number of cores used for parallelization. RANDOM_SEED Seed",
"= ROOT DATAPATH = os.path.join(HERE, 'raw-data') # Persistence MEMORY = Memory(location='.cache', verbose=1) N_JOBS",
"saved as a separate pickle file. # It will be used for graph",
"RANDOM_SEED = 101 SPACE = ('uniform', 'lognormal', 'clusters_normal') N = (1000, 2000, 4000,",
"8, 16) CENTERS = (4,) DATA_REP = 2 # SDA params SDA_PARAMS =",
"NDIM = (1, 2, 4, 8, 16) CENTERS = (4,) DATA_REP = 2",
"_df.drop(columns=['A', 'labels'], inplace=True) if df is None: df = _df else: df =",
"_df else: df = pd.concat((df, _df), ignore_index=True) # Save data ------------------------------------------------------------------- # Standard",
"'directed': (False,), 'p_rewire': (.01,) } SDA_REP = 3 SIM_PARAMS = { 'degseq_type': ('poisson',",
"Parameters ---------- N_JOBS Number of cores used for parallelization. RANDOM_SEED Seed for the",
"(False,), 'p_rewire': (.01,) } SDA_REP = 3 SIM_PARAMS = { 'degseq_type': ('poisson', 'negbinom',",
"params RANDOM_SEED = 101 SPACE = ('uniform', 'lognormal', 'clusters_normal') N = (1000, 2000,",
"independent realizations of adjacency matrices. SIM_PARAMS degseq_type Degree sequence type. One of: 'poisson',",
"(.01,) } SDA_REP = 3 SIM_PARAMS = { 'degseq_type': ('poisson', 'negbinom', 'powerlaw'), 'sort':",
"if RANDOM_SEED is not None: np.random.seed(RANDOM_SEED) sim = lambda s: simulate_cm( space=s, dparams=(N,",
"is not None: np.random.seed(RANDOM_SEED) sim = lambda s: simulate_cm( space=s, dparams=(N, NDIM, CENTERS),",
"@MEMORY.cache(ignore=['n_jobs']) def simulate_cm(space, dparams, drep, sdaparams, sdarep, simparams, n_jobs): return _.simulate(space, dparams, drep,",
"os.path.join(HERE, 'raw-data') # Persistence MEMORY = Memory(location='.cache', verbose=1) N_JOBS = 4 # Data",
"sdarep=SDA_REP, simparams=SIM_PARAMS, n_jobs=N_JOBS ) df = None # main data frame gdf =",
"space=s, dparams=(N, NDIM, CENTERS), drep=DATA_REP, sdaparams=SDA_PARAMS, sdarep=SDA_REP, simparams=SIM_PARAMS, n_jobs=N_JOBS ) df = None"
] |
[
"&& %s' % (self.local_path, command), *args, **kwargs) except Exception as e: with color.for_error():",
"&& git reset --hard origin/master' % target) else: self.ops.local('mkdir -p '+target) self.ops.local('cd '+target+\"",
"self.ops = operations self.api = api self.env = api.env def run(self, command, *args,",
"relative, so they will be extracted correct on the remote end file_list =",
"target)) os.unlink(f.name) os.unlink(tmp_archive) def clean_git_checkout(self, git_repo, target): target = self.local_path+'/'+target if os.path.isdir(target+'/.git'): self.ops.local('cd",
"os.unlink(tmp_archive) def clean_git_checkout(self, git_repo, target): target = self.local_path+'/'+target if os.path.isdir(target+'/.git'): self.ops.local('cd %s &&",
"self.run('tar xvf %s -C %s ' % (tmp_archive, target)) os.unlink(f.name) os.unlink(tmp_archive) def clean_git_checkout(self,",
"command), *args, **kwargs) else: return self.ops.run('cd %s && %s' % (self.remote_path, command), *args,",
"*args, **kwargs): try: with color.for_run(): return self.ops.local('cd %s && %s' % (self.local_path, command),",
"color.for_put(): with self.api.settings(warn_only=True): self.ops.put(src, self.normalize_path(dest), *args, **kwargs) def get(self, src, dest='', *args, **kwargs):",
"self.local_path = local_path self.ops = operations self.api = api self.env = api.env def",
"= remote_path self.local_path = local_path self.ops = operations self.api = api self.env =",
"*args, **kwargs): return self.run('sudo %s' % command, *args, **kwargs) def put(self, src, dest='',",
"operations self.api = api self.env = api.env def run(self, command, *args, **kwargs): try:",
"color from fabric import operations, api from fabric.contrib import files from policies import",
"self.name with open(tmp_file_list, 'w') as f: f.write('\\n'.join(file_list)) self.api.local('cd %s && tar cvf -",
"they will be extracted correct on the remote end file_list = [x.replace(self.local_path+'/', '')",
"'') for x in file_list] tmp_file_list = '/tmp/pisetup.%s.transfer.list' % self.name tmp_archive = '/tmp/pisetup.%s.transfer.tar'",
"fabric import operations, api from fabric.contrib import files from policies import PiServicePolicies class",
"self.env = api.env def run(self, command, *args, **kwargs): try: with color.for_run(): if self.is_local():",
"use_sudo=True) self.run('tar xvf %s -C %s ' % (tmp_archive, target)) os.unlink(f.name) os.unlink(tmp_archive) def",
"src, dest='', *args, **kwargs): with color.for_get(): with self.api.settings(warn_only=True): self.ops.get(self.normalize_path(src), dest, *args, **kwargs) def",
"path=\"~/\"): return self.run(path) def file_exists(self, path): if not path: return False method =",
"import files from policies import PiServicePolicies class FabricTaskOperator: def __init__(self, local_path, remote_path): self.remote_path",
"(self.local_path, f.name, tmp_archive)) self.put(tmp_archive, '/tmp/', use_sudo=True) self.run('tar xvf %s -C %s ' %",
"*args, **kwargs) def put(self, src, dest='', *args, **kwargs): with color.for_put(): with self.api.settings(warn_only=True): self.ops.put(src,",
"os.unlink(f.name) os.unlink(tmp_archive) def clean_git_checkout(self, git_repo, target): target = self.local_path+'/'+target if os.path.isdir(target+'/.git'): self.ops.local('cd %s",
"self.ops.local('cd %s && git checkout master' % target) self.ops.local('cd %s && git reset",
"def normalize_path(self, path): if path.startswith('/'): return path return self.remote_path+'/'+path def zip_files_and_copy(self, file_list, target):",
"PiServicePolicies.is_local(): method = os.path.isfile return method(self.normalize_path(path)) def cp(self, i, o): self.sudo('cp %s %s'",
"run(self, command, *args, **kwargs): try: with color.for_run(): if self.is_local(): return self.ops.local('cd %s &&",
"*args, **kwargs): try: with color.for_run(): if self.is_local(): return self.ops.local('cd %s && %s' %",
"with color.for_run(): return self.ops.local('cd %s && %s' % (self.local_path, command), *args, **kwargs) except",
"(self.remote_path, command), *args, combine_stderr=True, pty=False, **kwargs) except Exception as e: with color.for_error(): raise",
"with self.api.settings(warn_only=True): self.ops.put(src, self.normalize_path(dest), *args, **kwargs) def get(self, src, dest='', *args, **kwargs): with",
"with self.api.settings(warn_only=True): self.ops.get(self.normalize_path(src), dest, *args, **kwargs) def cd(self, path=\"~/\"): return self.run(path) def file_exists(self,",
"except Exception as e: with color.for_error(): raise e def local(self, command, *args, **kwargs):",
"%s' % (self.remote_path, command), *args, combine_stderr=True, pty=False, **kwargs) except Exception as e: with",
"% command, *args, **kwargs) def put(self, src, dest='', *args, **kwargs): with color.for_put(): with",
"remote end file_list = [x.replace(self.local_path+'/', '') for x in file_list] tmp_file_list = '/tmp/pisetup.%s.transfer.list'",
"e: with color.for_error(): raise e def sudo(self, command, *args, **kwargs): return self.run('sudo %s'",
"path relative, so they will be extracted correct on the remote end file_list",
"1: return #make path relative, so they will be extracted correct on the",
"'/tmp/', use_sudo=True) self.run('tar xvf %s -C %s ' % (tmp_archive, target)) os.unlink(f.name) os.unlink(tmp_archive)",
"checkout master' % target) self.ops.local('cd %s && git reset --hard origin/master' % target)",
"extracted correct on the remote end file_list = [x.replace(self.local_path+'/', '') for x in",
"% self.name with open(tmp_file_list, 'w') as f: f.write('\\n'.join(file_list)) self.api.local('cd %s && tar cvf",
"self.api = api self.env = api.env def run(self, command, *args, **kwargs): try: with",
"Exception as e: with color.for_error(): raise e def local(self, command, *args, **kwargs): try:",
"*args, **kwargs) except Exception as e: with color.for_error(): raise e def sudo(self, command,",
"*args, **kwargs) else: return self.ops.run('cd %s && %s' % (self.remote_path, command), *args, combine_stderr=True,",
"local_path, remote_path): self.remote_path = remote_path self.local_path = local_path self.ops = operations self.api =",
"combine_stderr=True, pty=False, **kwargs) except Exception as e: with color.for_error(): raise e def local(self,",
"%s' % (self.local_path, command), *args, **kwargs) else: return self.ops.run('cd %s && %s' %",
"%s' % command, *args, **kwargs) def put(self, src, dest='', *args, **kwargs): with color.for_put():",
"will be extracted correct on the remote end file_list = [x.replace(self.local_path+'/', '') for",
"with color.for_put(): with self.api.settings(warn_only=True): self.ops.put(src, self.normalize_path(dest), *args, **kwargs) def get(self, src, dest='', *args,",
"len(file_list) < 1: return #make path relative, so they will be extracted correct",
"cvf - -T %s > %s' % (self.local_path, f.name, tmp_archive)) self.put(tmp_archive, '/tmp/', use_sudo=True)",
"command, *args, **kwargs): return self.run('sudo %s' % command, *args, **kwargs) def put(self, src,",
"on the remote end file_list = [x.replace(self.local_path+'/', '') for x in file_list] tmp_file_list",
"so they will be extracted correct on the remote end file_list = [x.replace(self.local_path+'/',",
"the remote end file_list = [x.replace(self.local_path+'/', '') for x in file_list] tmp_file_list =",
"get(self, src, dest='', *args, **kwargs): with color.for_get(): with self.api.settings(warn_only=True): self.ops.get(self.normalize_path(src), dest, *args, **kwargs)",
"f.write('\\n'.join(file_list)) self.api.local('cd %s && tar cvf - -T %s > %s' % (self.local_path,",
"git checkout master' % target) self.ops.local('cd %s && git reset --hard origin/master' %",
"return self.remote_path+'/'+path def zip_files_and_copy(self, file_list, target): if not file_list or len(file_list) < 1:",
"as f: f.write('\\n'.join(file_list)) self.api.local('cd %s && tar cvf - -T %s > %s'",
"%s' % (self.local_path, command), *args, **kwargs) except Exception as e: with color.for_error(): raise",
"> %s' % (self.local_path, f.name, tmp_archive)) self.put(tmp_archive, '/tmp/', use_sudo=True) self.run('tar xvf %s -C",
"&& git clone \"+git_repo+\" . && git submodule init && git submodule update\")",
"from fabric.contrib import files from policies import PiServicePolicies class FabricTaskOperator: def __init__(self, local_path,",
"def __init__(self, local_path, remote_path): self.remote_path = remote_path self.local_path = local_path self.ops = operations",
"command), *args, **kwargs) except Exception as e: with color.for_error(): raise e def sudo(self,",
"__init__(self, local_path, remote_path): self.remote_path = remote_path self.local_path = local_path self.ops = operations self.api",
"files.exists if PiServicePolicies.is_local(): method = os.path.isfile return method(self.normalize_path(path)) def cp(self, i, o): self.sudo('cp",
"target): target = self.local_path+'/'+target if os.path.isdir(target+'/.git'): self.ops.local('cd %s && git checkout master' %",
"api self.env = api.env def run(self, command, *args, **kwargs): try: with color.for_run(): if",
"clean_git_checkout(self, git_repo, target): target = self.local_path+'/'+target if os.path.isdir(target+'/.git'): self.ops.local('cd %s && git checkout",
"%s -C %s ' % (tmp_archive, target)) os.unlink(f.name) os.unlink(tmp_archive) def clean_git_checkout(self, git_repo, target):",
"command, *args, **kwargs): try: with color.for_run(): if self.is_local(): return self.ops.local('cd %s && %s'",
"path.startswith('/'): return path return self.remote_path+'/'+path def zip_files_and_copy(self, file_list, target): if not file_list or",
"self.ops.run('cd %s && %s' % (self.remote_path, command), *args, combine_stderr=True, pty=False, **kwargs) except Exception",
"if os.path.isdir(target+'/.git'): self.ops.local('cd %s && git checkout master' % target) self.ops.local('cd %s &&",
"color.for_error(): raise e def local(self, command, *args, **kwargs): try: with color.for_run(): return self.ops.local('cd",
"import PiServicePolicies class FabricTaskOperator: def __init__(self, local_path, remote_path): self.remote_path = remote_path self.local_path =",
"False method = files.exists if PiServicePolicies.is_local(): method = os.path.isfile return method(self.normalize_path(path)) def cp(self,",
"**kwargs) def get(self, src, dest='', *args, **kwargs): with color.for_get(): with self.api.settings(warn_only=True): self.ops.get(self.normalize_path(src), dest,",
"% (self.local_path, command), *args, **kwargs) else: return self.ops.run('cd %s && %s' % (self.remote_path,",
"as e: with color.for_error(): raise e def sudo(self, command, *args, **kwargs): return self.run('sudo",
"self.api.settings(warn_only=True): self.ops.put(src, self.normalize_path(dest), *args, **kwargs) def get(self, src, dest='', *args, **kwargs): with color.for_get():",
"method(self.normalize_path(path)) def cp(self, i, o): self.sudo('cp %s %s' % (self.normalize_path(i), self.normalize_path(o))) def normalize_path(self,",
"Exception as e: with color.for_error(): raise e def sudo(self, command, *args, **kwargs): return",
"dest, *args, **kwargs) def cd(self, path=\"~/\"): return self.run(path) def file_exists(self, path): if not",
"raise e def local(self, command, *args, **kwargs): try: with color.for_run(): return self.ops.local('cd %s",
"self.ops.local('cd '+target+\" && git clone \"+git_repo+\" . && git submodule init && git",
"= '/tmp/pisetup.%s.transfer.list' % self.name tmp_archive = '/tmp/pisetup.%s.transfer.tar' % self.name with open(tmp_file_list, 'w') as",
"self.local_path+'/'+target if os.path.isdir(target+'/.git'): self.ops.local('cd %s && git checkout master' % target) self.ops.local('cd %s",
"(self.normalize_path(i), self.normalize_path(o))) def normalize_path(self, path): if path.startswith('/'): return path return self.remote_path+'/'+path def zip_files_and_copy(self,",
"with color.for_error(): raise e def local(self, command, *args, **kwargs): try: with color.for_run(): return",
"color.for_run(): return self.ops.local('cd %s && %s' % (self.local_path, command), *args, **kwargs) except Exception",
"def zip_files_and_copy(self, file_list, target): if not file_list or len(file_list) < 1: return #make",
"% (self.normalize_path(i), self.normalize_path(o))) def normalize_path(self, path): if path.startswith('/'): return path return self.remote_path+'/'+path def",
"return self.ops.run('cd %s && %s' % (self.remote_path, command), *args, combine_stderr=True, pty=False, **kwargs) except",
"<reponame>creative-workflow/pi-setup<filename>lib/piservices/fabops.py import os, color from fabric import operations, api from fabric.contrib import files",
"cp(self, i, o): self.sudo('cp %s %s' % (self.normalize_path(i), self.normalize_path(o))) def normalize_path(self, path): if",
"zip_files_and_copy(self, file_list, target): if not file_list or len(file_list) < 1: return #make path",
"target): if not file_list or len(file_list) < 1: return #make path relative, so",
"'w') as f: f.write('\\n'.join(file_list)) self.api.local('cd %s && tar cvf - -T %s >",
"--hard origin/master' % target) else: self.ops.local('mkdir -p '+target) self.ops.local('cd '+target+\" && git clone",
"FabricTaskOperator: def __init__(self, local_path, remote_path): self.remote_path = remote_path self.local_path = local_path self.ops =",
"*args, **kwargs): with color.for_get(): with self.api.settings(warn_only=True): self.ops.get(self.normalize_path(src), dest, *args, **kwargs) def cd(self, path=\"~/\"):",
"= '/tmp/pisetup.%s.transfer.tar' % self.name with open(tmp_file_list, 'w') as f: f.write('\\n'.join(file_list)) self.api.local('cd %s &&",
"command, *args, **kwargs): try: with color.for_run(): return self.ops.local('cd %s && %s' % (self.local_path,",
"**kwargs): return self.run('sudo %s' % command, *args, **kwargs) def put(self, src, dest='', *args,",
"if path.startswith('/'): return path return self.remote_path+'/'+path def zip_files_and_copy(self, file_list, target): if not file_list",
"x in file_list] tmp_file_list = '/tmp/pisetup.%s.transfer.list' % self.name tmp_archive = '/tmp/pisetup.%s.transfer.tar' % self.name",
"else: return self.ops.run('cd %s && %s' % (self.remote_path, command), *args, combine_stderr=True, pty=False, **kwargs)",
"**kwargs): with color.for_put(): with self.api.settings(warn_only=True): self.ops.put(src, self.normalize_path(dest), *args, **kwargs) def get(self, src, dest='',",
"%s > %s' % (self.local_path, f.name, tmp_archive)) self.put(tmp_archive, '/tmp/', use_sudo=True) self.run('tar xvf %s",
"self.ops.local('cd %s && %s' % (self.local_path, command), *args, **kwargs) except Exception as e:",
"i, o): self.sudo('cp %s %s' % (self.normalize_path(i), self.normalize_path(o))) def normalize_path(self, path): if path.startswith('/'):",
"fabric.contrib import files from policies import PiServicePolicies class FabricTaskOperator: def __init__(self, local_path, remote_path):",
"path): if path.startswith('/'): return path return self.remote_path+'/'+path def zip_files_and_copy(self, file_list, target): if not",
"**kwargs) def cd(self, path=\"~/\"): return self.run(path) def file_exists(self, path): if not path: return",
"local_path self.ops = operations self.api = api self.env = api.env def run(self, command,",
"< 1: return #make path relative, so they will be extracted correct on",
"self.api.settings(warn_only=True): self.ops.get(self.normalize_path(src), dest, *args, **kwargs) def cd(self, path=\"~/\"): return self.run(path) def file_exists(self, path):",
"master' % target) self.ops.local('cd %s && git reset --hard origin/master' % target) else:",
"%s && %s' % (self.local_path, command), *args, **kwargs) except Exception as e: with",
"'+target+\" && git clone \"+git_repo+\" . && git submodule init && git submodule",
"as e: with color.for_error(): raise e def local(self, command, *args, **kwargs): try: with",
"= operations self.api = api self.env = api.env def run(self, command, *args, **kwargs):",
"for x in file_list] tmp_file_list = '/tmp/pisetup.%s.transfer.list' % self.name tmp_archive = '/tmp/pisetup.%s.transfer.tar' %",
"return self.ops.local('cd %s && %s' % (self.local_path, command), *args, **kwargs) else: return self.ops.run('cd",
"- -T %s > %s' % (self.local_path, f.name, tmp_archive)) self.put(tmp_archive, '/tmp/', use_sudo=True) self.run('tar",
"from fabric import operations, api from fabric.contrib import files from policies import PiServicePolicies",
"src, dest='', *args, **kwargs): with color.for_put(): with self.api.settings(warn_only=True): self.ops.put(src, self.normalize_path(dest), *args, **kwargs) def",
"cd(self, path=\"~/\"): return self.run(path) def file_exists(self, path): if not path: return False method",
"def local(self, command, *args, **kwargs): try: with color.for_run(): return self.ops.local('cd %s && %s'",
"reset --hard origin/master' % target) else: self.ops.local('mkdir -p '+target) self.ops.local('cd '+target+\" && git",
"sudo(self, command, *args, **kwargs): return self.run('sudo %s' % command, *args, **kwargs) def put(self,",
"file_exists(self, path): if not path: return False method = files.exists if PiServicePolicies.is_local(): method",
"except Exception as e: with color.for_error(): raise e def sudo(self, command, *args, **kwargs):",
"or len(file_list) < 1: return #make path relative, so they will be extracted",
"def cd(self, path=\"~/\"): return self.run(path) def file_exists(self, path): if not path: return False",
"*args, **kwargs) def cd(self, path=\"~/\"): return self.run(path) def file_exists(self, path): if not path:",
"correct on the remote end file_list = [x.replace(self.local_path+'/', '') for x in file_list]",
"%s && %s' % (self.local_path, command), *args, **kwargs) else: return self.ops.run('cd %s &&",
"self.ops.put(src, self.normalize_path(dest), *args, **kwargs) def get(self, src, dest='', *args, **kwargs): with color.for_get(): with",
"'/tmp/pisetup.%s.transfer.tar' % self.name with open(tmp_file_list, 'w') as f: f.write('\\n'.join(file_list)) self.api.local('cd %s && tar",
"file_list or len(file_list) < 1: return #make path relative, so they will be",
"*args, combine_stderr=True, pty=False, **kwargs) except Exception as e: with color.for_error(): raise e def",
"file_list = [x.replace(self.local_path+'/', '') for x in file_list] tmp_file_list = '/tmp/pisetup.%s.transfer.list' % self.name",
"if self.is_local(): return self.ops.local('cd %s && %s' % (self.local_path, command), *args, **kwargs) else:",
"local(self, command, *args, **kwargs): try: with color.for_run(): return self.ops.local('cd %s && %s' %",
"if not file_list or len(file_list) < 1: return #make path relative, so they",
"tmp_file_list = '/tmp/pisetup.%s.transfer.list' % self.name tmp_archive = '/tmp/pisetup.%s.transfer.tar' % self.name with open(tmp_file_list, 'w')",
"-C %s ' % (tmp_archive, target)) os.unlink(f.name) os.unlink(tmp_archive) def clean_git_checkout(self, git_repo, target): target",
"files from policies import PiServicePolicies class FabricTaskOperator: def __init__(self, local_path, remote_path): self.remote_path =",
"self.run(path) def file_exists(self, path): if not path: return False method = files.exists if",
"xvf %s -C %s ' % (tmp_archive, target)) os.unlink(f.name) os.unlink(tmp_archive) def clean_git_checkout(self, git_repo,",
"path: return False method = files.exists if PiServicePolicies.is_local(): method = os.path.isfile return method(self.normalize_path(path))",
"file_list, target): if not file_list or len(file_list) < 1: return #make path relative,",
"path): if not path: return False method = files.exists if PiServicePolicies.is_local(): method =",
"command), *args, combine_stderr=True, pty=False, **kwargs) except Exception as e: with color.for_error(): raise e",
"% (self.local_path, f.name, tmp_archive)) self.put(tmp_archive, '/tmp/', use_sudo=True) self.run('tar xvf %s -C %s '",
"%s ' % (tmp_archive, target)) os.unlink(f.name) os.unlink(tmp_archive) def clean_git_checkout(self, git_repo, target): target =",
"**kwargs) else: return self.ops.run('cd %s && %s' % (self.remote_path, command), *args, combine_stderr=True, pty=False,",
"os.path.isfile return method(self.normalize_path(path)) def cp(self, i, o): self.sudo('cp %s %s' % (self.normalize_path(i), self.normalize_path(o)))",
"'+target) self.ops.local('cd '+target+\" && git clone \"+git_repo+\" . && git submodule init &&",
"from policies import PiServicePolicies class FabricTaskOperator: def __init__(self, local_path, remote_path): self.remote_path = remote_path",
"**kwargs) except Exception as e: with color.for_error(): raise e def sudo(self, command, *args,",
"file_list] tmp_file_list = '/tmp/pisetup.%s.transfer.list' % self.name tmp_archive = '/tmp/pisetup.%s.transfer.tar' % self.name with open(tmp_file_list,",
"def sudo(self, command, *args, **kwargs): return self.run('sudo %s' % command, *args, **kwargs) def",
"in file_list] tmp_file_list = '/tmp/pisetup.%s.transfer.list' % self.name tmp_archive = '/tmp/pisetup.%s.transfer.tar' % self.name with",
"'/tmp/pisetup.%s.transfer.list' % self.name tmp_archive = '/tmp/pisetup.%s.transfer.tar' % self.name with open(tmp_file_list, 'w') as f:",
"return path return self.remote_path+'/'+path def zip_files_and_copy(self, file_list, target): if not file_list or len(file_list)",
"self.is_local(): return self.ops.local('cd %s && %s' % (self.local_path, command), *args, **kwargs) else: return",
"self.put(tmp_archive, '/tmp/', use_sudo=True) self.run('tar xvf %s -C %s ' % (tmp_archive, target)) os.unlink(f.name)",
"**kwargs): try: with color.for_run(): if self.is_local(): return self.ops.local('cd %s && %s' % (self.local_path,",
"color.for_error(): raise e def sudo(self, command, *args, **kwargs): return self.run('sudo %s' % command,",
"self.api.local('cd %s && tar cvf - -T %s > %s' % (self.local_path, f.name,",
"e def local(self, command, *args, **kwargs): try: with color.for_run(): return self.ops.local('cd %s &&",
"% (tmp_archive, target)) os.unlink(f.name) os.unlink(tmp_archive) def clean_git_checkout(self, git_repo, target): target = self.local_path+'/'+target if",
"(tmp_archive, target)) os.unlink(f.name) os.unlink(tmp_archive) def clean_git_checkout(self, git_repo, target): target = self.local_path+'/'+target if os.path.isdir(target+'/.git'):",
"self.name tmp_archive = '/tmp/pisetup.%s.transfer.tar' % self.name with open(tmp_file_list, 'w') as f: f.write('\\n'.join(file_list)) self.api.local('cd",
"self.normalize_path(dest), *args, **kwargs) def get(self, src, dest='', *args, **kwargs): with color.for_get(): with self.api.settings(warn_only=True):",
"origin/master' % target) else: self.ops.local('mkdir -p '+target) self.ops.local('cd '+target+\" && git clone \"+git_repo+\"",
"% self.name tmp_archive = '/tmp/pisetup.%s.transfer.tar' % self.name with open(tmp_file_list, 'w') as f: f.write('\\n'.join(file_list))",
"method = os.path.isfile return method(self.normalize_path(path)) def cp(self, i, o): self.sudo('cp %s %s' %",
"return self.ops.local('cd %s && %s' % (self.local_path, command), *args, **kwargs) except Exception as",
"self.ops.get(self.normalize_path(src), dest, *args, **kwargs) def cd(self, path=\"~/\"): return self.run(path) def file_exists(self, path): if",
"target = self.local_path+'/'+target if os.path.isdir(target+'/.git'): self.ops.local('cd %s && git checkout master' % target)",
"= local_path self.ops = operations self.api = api self.env = api.env def run(self,",
"operations, api from fabric.contrib import files from policies import PiServicePolicies class FabricTaskOperator: def",
"= api self.env = api.env def run(self, command, *args, **kwargs): try: with color.for_run():",
"def get(self, src, dest='', *args, **kwargs): with color.for_get(): with self.api.settings(warn_only=True): self.ops.get(self.normalize_path(src), dest, *args,",
"&& git checkout master' % target) self.ops.local('cd %s && git reset --hard origin/master'",
"return False method = files.exists if PiServicePolicies.is_local(): method = os.path.isfile return method(self.normalize_path(path)) def",
"return method(self.normalize_path(path)) def cp(self, i, o): self.sudo('cp %s %s' % (self.normalize_path(i), self.normalize_path(o))) def",
"os.path.isdir(target+'/.git'): self.ops.local('cd %s && git checkout master' % target) self.ops.local('cd %s && git",
"self.run('sudo %s' % command, *args, **kwargs) def put(self, src, dest='', *args, **kwargs): with",
"= os.path.isfile return method(self.normalize_path(path)) def cp(self, i, o): self.sudo('cp %s %s' % (self.normalize_path(i),",
"not path: return False method = files.exists if PiServicePolicies.is_local(): method = os.path.isfile return",
"self.ops.local('mkdir -p '+target) self.ops.local('cd '+target+\" && git clone \"+git_repo+\" . && git submodule",
"normalize_path(self, path): if path.startswith('/'): return path return self.remote_path+'/'+path def zip_files_and_copy(self, file_list, target): if",
"remote_path): self.remote_path = remote_path self.local_path = local_path self.ops = operations self.api = api",
"(self.local_path, command), *args, **kwargs) else: return self.ops.run('cd %s && %s' % (self.remote_path, command),",
"color.for_get(): with self.api.settings(warn_only=True): self.ops.get(self.normalize_path(src), dest, *args, **kwargs) def cd(self, path=\"~/\"): return self.run(path) def",
"**kwargs): try: with color.for_run(): return self.ops.local('cd %s && %s' % (self.local_path, command), *args,",
"method = files.exists if PiServicePolicies.is_local(): method = os.path.isfile return method(self.normalize_path(path)) def cp(self, i,",
"%s && tar cvf - -T %s > %s' % (self.local_path, f.name, tmp_archive))",
"**kwargs): with color.for_get(): with self.api.settings(warn_only=True): self.ops.get(self.normalize_path(src), dest, *args, **kwargs) def cd(self, path=\"~/\"): return",
"% (self.remote_path, command), *args, combine_stderr=True, pty=False, **kwargs) except Exception as e: with color.for_error():",
"dest='', *args, **kwargs): with color.for_put(): with self.api.settings(warn_only=True): self.ops.put(src, self.normalize_path(dest), *args, **kwargs) def get(self,",
"self.ops.local('cd %s && git reset --hard origin/master' % target) else: self.ops.local('mkdir -p '+target)",
"else: self.ops.local('mkdir -p '+target) self.ops.local('cd '+target+\" && git clone \"+git_repo+\" . && git",
"raise e def sudo(self, command, *args, **kwargs): return self.run('sudo %s' % command, *args,",
"return self.run(path) def file_exists(self, path): if not path: return False method = files.exists",
"%s' % (self.normalize_path(i), self.normalize_path(o))) def normalize_path(self, path): if path.startswith('/'): return path return self.remote_path+'/'+path",
"% (self.local_path, command), *args, **kwargs) except Exception as e: with color.for_error(): raise e",
"%s && %s' % (self.remote_path, command), *args, combine_stderr=True, pty=False, **kwargs) except Exception as",
"if PiServicePolicies.is_local(): method = os.path.isfile return method(self.normalize_path(path)) def cp(self, i, o): self.sudo('cp %s",
"*args, **kwargs) def get(self, src, dest='', *args, **kwargs): with color.for_get(): with self.api.settings(warn_only=True): self.ops.get(self.normalize_path(src),",
"put(self, src, dest='', *args, **kwargs): with color.for_put(): with self.api.settings(warn_only=True): self.ops.put(src, self.normalize_path(dest), *args, **kwargs)",
"e def sudo(self, command, *args, **kwargs): return self.run('sudo %s' % command, *args, **kwargs)",
"try: with color.for_run(): return self.ops.local('cd %s && %s' % (self.local_path, command), *args, **kwargs)",
"class FabricTaskOperator: def __init__(self, local_path, remote_path): self.remote_path = remote_path self.local_path = local_path self.ops",
"#make path relative, so they will be extracted correct on the remote end",
"dest='', *args, **kwargs): with color.for_get(): with self.api.settings(warn_only=True): self.ops.get(self.normalize_path(src), dest, *args, **kwargs) def cd(self,",
"with color.for_error(): raise e def sudo(self, command, *args, **kwargs): return self.run('sudo %s' %",
"%s' % (self.local_path, f.name, tmp_archive)) self.put(tmp_archive, '/tmp/', use_sudo=True) self.run('tar xvf %s -C %s",
"return self.run('sudo %s' % command, *args, **kwargs) def put(self, src, dest='', *args, **kwargs):",
"= [x.replace(self.local_path+'/', '') for x in file_list] tmp_file_list = '/tmp/pisetup.%s.transfer.list' % self.name tmp_archive",
"self.remote_path = remote_path self.local_path = local_path self.ops = operations self.api = api self.env",
"-T %s > %s' % (self.local_path, f.name, tmp_archive)) self.put(tmp_archive, '/tmp/', use_sudo=True) self.run('tar xvf",
"api from fabric.contrib import files from policies import PiServicePolicies class FabricTaskOperator: def __init__(self,",
"*args, **kwargs): with color.for_put(): with self.api.settings(warn_only=True): self.ops.put(src, self.normalize_path(dest), *args, **kwargs) def get(self, src,",
"git_repo, target): target = self.local_path+'/'+target if os.path.isdir(target+'/.git'): self.ops.local('cd %s && git checkout master'",
"import os, color from fabric import operations, api from fabric.contrib import files from",
"%s %s' % (self.normalize_path(i), self.normalize_path(o))) def normalize_path(self, path): if path.startswith('/'): return path return",
"[x.replace(self.local_path+'/', '') for x in file_list] tmp_file_list = '/tmp/pisetup.%s.transfer.list' % self.name tmp_archive =",
"&& %s' % (self.local_path, command), *args, **kwargs) else: return self.ops.run('cd %s && %s'",
"os, color from fabric import operations, api from fabric.contrib import files from policies",
"def cp(self, i, o): self.sudo('cp %s %s' % (self.normalize_path(i), self.normalize_path(o))) def normalize_path(self, path):",
"with open(tmp_file_list, 'w') as f: f.write('\\n'.join(file_list)) self.api.local('cd %s && tar cvf - -T",
"import operations, api from fabric.contrib import files from policies import PiServicePolicies class FabricTaskOperator:",
"pty=False, **kwargs) except Exception as e: with color.for_error(): raise e def local(self, command,",
"self.ops.local('cd %s && %s' % (self.local_path, command), *args, **kwargs) else: return self.ops.run('cd %s",
"return #make path relative, so they will be extracted correct on the remote",
"open(tmp_file_list, 'w') as f: f.write('\\n'.join(file_list)) self.api.local('cd %s && tar cvf - -T %s",
"**kwargs) def put(self, src, dest='', *args, **kwargs): with color.for_put(): with self.api.settings(warn_only=True): self.ops.put(src, self.normalize_path(dest),",
"&& tar cvf - -T %s > %s' % (self.local_path, f.name, tmp_archive)) self.put(tmp_archive,",
"%s && git reset --hard origin/master' % target) else: self.ops.local('mkdir -p '+target) self.ops.local('cd",
"target) else: self.ops.local('mkdir -p '+target) self.ops.local('cd '+target+\" && git clone \"+git_repo+\" . &&",
"be extracted correct on the remote end file_list = [x.replace(self.local_path+'/', '') for x",
"api.env def run(self, command, *args, **kwargs): try: with color.for_run(): if self.is_local(): return self.ops.local('cd",
"-p '+target) self.ops.local('cd '+target+\" && git clone \"+git_repo+\" . && git submodule init",
"self.normalize_path(o))) def normalize_path(self, path): if path.startswith('/'): return path return self.remote_path+'/'+path def zip_files_and_copy(self, file_list,",
"def file_exists(self, path): if not path: return False method = files.exists if PiServicePolicies.is_local():",
"%s && git checkout master' % target) self.ops.local('cd %s && git reset --hard",
"not file_list or len(file_list) < 1: return #make path relative, so they will",
"self.sudo('cp %s %s' % (self.normalize_path(i), self.normalize_path(o))) def normalize_path(self, path): if path.startswith('/'): return path",
"tmp_archive = '/tmp/pisetup.%s.transfer.tar' % self.name with open(tmp_file_list, 'w') as f: f.write('\\n'.join(file_list)) self.api.local('cd %s",
"**kwargs) except Exception as e: with color.for_error(): raise e def local(self, command, *args,",
"def clean_git_checkout(self, git_repo, target): target = self.local_path+'/'+target if os.path.isdir(target+'/.git'): self.ops.local('cd %s && git",
"e: with color.for_error(): raise e def local(self, command, *args, **kwargs): try: with color.for_run():",
"if not path: return False method = files.exists if PiServicePolicies.is_local(): method = os.path.isfile",
"git reset --hard origin/master' % target) else: self.ops.local('mkdir -p '+target) self.ops.local('cd '+target+\" &&",
"&& %s' % (self.remote_path, command), *args, combine_stderr=True, pty=False, **kwargs) except Exception as e:",
"= api.env def run(self, command, *args, **kwargs): try: with color.for_run(): if self.is_local(): return",
"end file_list = [x.replace(self.local_path+'/', '') for x in file_list] tmp_file_list = '/tmp/pisetup.%s.transfer.list' %",
"f: f.write('\\n'.join(file_list)) self.api.local('cd %s && tar cvf - -T %s > %s' %",
"= self.local_path+'/'+target if os.path.isdir(target+'/.git'): self.ops.local('cd %s && git checkout master' % target) self.ops.local('cd",
"f.name, tmp_archive)) self.put(tmp_archive, '/tmp/', use_sudo=True) self.run('tar xvf %s -C %s ' % (tmp_archive,",
"def run(self, command, *args, **kwargs): try: with color.for_run(): if self.is_local(): return self.ops.local('cd %s",
"target) self.ops.local('cd %s && git reset --hard origin/master' % target) else: self.ops.local('mkdir -p",
"with color.for_get(): with self.api.settings(warn_only=True): self.ops.get(self.normalize_path(src), dest, *args, **kwargs) def cd(self, path=\"~/\"): return self.run(path)",
"self.remote_path+'/'+path def zip_files_and_copy(self, file_list, target): if not file_list or len(file_list) < 1: return",
"def put(self, src, dest='', *args, **kwargs): with color.for_put(): with self.api.settings(warn_only=True): self.ops.put(src, self.normalize_path(dest), *args,",
"' % (tmp_archive, target)) os.unlink(f.name) os.unlink(tmp_archive) def clean_git_checkout(self, git_repo, target): target = self.local_path+'/'+target",
"command, *args, **kwargs) def put(self, src, dest='', *args, **kwargs): with color.for_put(): with self.api.settings(warn_only=True):",
"color.for_run(): if self.is_local(): return self.ops.local('cd %s && %s' % (self.local_path, command), *args, **kwargs)",
"= files.exists if PiServicePolicies.is_local(): method = os.path.isfile return method(self.normalize_path(path)) def cp(self, i, o):",
"path return self.remote_path+'/'+path def zip_files_and_copy(self, file_list, target): if not file_list or len(file_list) <",
"PiServicePolicies class FabricTaskOperator: def __init__(self, local_path, remote_path): self.remote_path = remote_path self.local_path = local_path",
"with color.for_run(): if self.is_local(): return self.ops.local('cd %s && %s' % (self.local_path, command), *args,",
"remote_path self.local_path = local_path self.ops = operations self.api = api self.env = api.env",
"% target) self.ops.local('cd %s && git reset --hard origin/master' % target) else: self.ops.local('mkdir",
"tar cvf - -T %s > %s' % (self.local_path, f.name, tmp_archive)) self.put(tmp_archive, '/tmp/',",
"policies import PiServicePolicies class FabricTaskOperator: def __init__(self, local_path, remote_path): self.remote_path = remote_path self.local_path",
"% target) else: self.ops.local('mkdir -p '+target) self.ops.local('cd '+target+\" && git clone \"+git_repo+\" .",
"try: with color.for_run(): if self.is_local(): return self.ops.local('cd %s && %s' % (self.local_path, command),",
"(self.local_path, command), *args, **kwargs) except Exception as e: with color.for_error(): raise e def",
"o): self.sudo('cp %s %s' % (self.normalize_path(i), self.normalize_path(o))) def normalize_path(self, path): if path.startswith('/'): return",
"tmp_archive)) self.put(tmp_archive, '/tmp/', use_sudo=True) self.run('tar xvf %s -C %s ' % (tmp_archive, target))"
] |
[
"= 'User({0}) logged out'.format(request.user.username) self.logger.info(self.logger.to_request('Logout', msg)) # Must override logged username from POST",
"is not logged in def failed_login(self, credentials, **kwargs): request = get_request() username =",
"this context, when looked from the perspective of the # Django signal system",
"login(self, user, request, **kwargs): self.logger.instance.addFilter(ll_logger.ContextFilter(request)) msg = 'User({0}) logged in'.format(request.user.username) self.logger.info(self.logger.to_request('Login', msg)) def",
"__init__(self, logger): self.logger = logger # self = sender in this context, when",
"= get_request() username = request.POST.get('username', 'Undefined') self.logger.instance.addFilter( ll_logger.ContextFilter(request, overrides={'user':username}) ) msg = 'User({0})",
"from request_provider.signals import get_request import ll_logger from ll_debug import __debugvar__ class SignalHandler: def",
"msg)) def logout(self, user, request, **kwargs): self.logger.instance.addFilter(ll_logger.ContextFilter(request)) msg = 'User({0}) logged out'.format(request.user.username) self.logger.info(self.logger.to_request('Logout',",
"request, **kwargs): self.logger.instance.addFilter(ll_logger.ContextFilter(request)) msg = 'User({0}) logged out'.format(request.user.username) self.logger.info(self.logger.to_request('Logout', msg)) # Must override",
"POST since user is not logged in def failed_login(self, credentials, **kwargs): request =",
"user, request, **kwargs): self.logger.instance.addFilter(ll_logger.ContextFilter(request)) msg = 'User({0}) logged in'.format(request.user.username) self.logger.info(self.logger.to_request('Login', msg)) def logout(self,",
"from ll_debug import __debugvar__ class SignalHandler: def __init__(self, logger): self.logger = logger #",
"# self = sender in this context, when looked from the perspective of",
"Django signal system def login(self, user, request, **kwargs): self.logger.instance.addFilter(ll_logger.ContextFilter(request)) msg = 'User({0}) logged",
"context, when looked from the perspective of the # Django signal system def",
"**kwargs): self.logger.instance.addFilter(ll_logger.ContextFilter(request)) msg = 'User({0}) logged out'.format(request.user.username) self.logger.info(self.logger.to_request('Logout', msg)) # Must override logged",
"Must override logged username from POST since user is not logged in def",
"user_logged_in from request_provider.signals import get_request import ll_logger from ll_debug import __debugvar__ class SignalHandler:",
"__debugvar__ class SignalHandler: def __init__(self, logger): self.logger = logger # self = sender",
"msg = 'User({0}) logged in'.format(request.user.username) self.logger.info(self.logger.to_request('Login', msg)) def logout(self, user, request, **kwargs): self.logger.instance.addFilter(ll_logger.ContextFilter(request))",
"failed_login(self, credentials, **kwargs): request = get_request() username = request.POST.get('username', 'Undefined') self.logger.instance.addFilter( ll_logger.ContextFilter(request, overrides={'user':username})",
"out'.format(request.user.username) self.logger.info(self.logger.to_request('Logout', msg)) # Must override logged username from POST since user is",
"system def login(self, user, request, **kwargs): self.logger.instance.addFilter(ll_logger.ContextFilter(request)) msg = 'User({0}) logged in'.format(request.user.username) self.logger.info(self.logger.to_request('Login',",
"def logout(self, user, request, **kwargs): self.logger.instance.addFilter(ll_logger.ContextFilter(request)) msg = 'User({0}) logged out'.format(request.user.username) self.logger.info(self.logger.to_request('Logout', msg))",
"class SignalHandler: def __init__(self, logger): self.logger = logger # self = sender in",
"from django.contrib.auth.signals import user_logged_in from request_provider.signals import get_request import ll_logger from ll_debug import",
"'User({0}) logged out'.format(request.user.username) self.logger.info(self.logger.to_request('Logout', msg)) # Must override logged username from POST since",
"from the perspective of the # Django signal system def login(self, user, request,",
"perspective of the # Django signal system def login(self, user, request, **kwargs): self.logger.instance.addFilter(ll_logger.ContextFilter(request))",
"sender in this context, when looked from the perspective of the # Django",
"when looked from the perspective of the # Django signal system def login(self,",
"= 'User({0}) logged in'.format(request.user.username) self.logger.info(self.logger.to_request('Login', msg)) def logout(self, user, request, **kwargs): self.logger.instance.addFilter(ll_logger.ContextFilter(request)) msg",
"**kwargs): request = get_request() username = request.POST.get('username', 'Undefined') self.logger.instance.addFilter( ll_logger.ContextFilter(request, overrides={'user':username}) ) msg",
"msg = 'User({0}) logged out'.format(request.user.username) self.logger.info(self.logger.to_request('Logout', msg)) # Must override logged username from",
"in'.format(request.user.username) self.logger.info(self.logger.to_request('Login', msg)) def logout(self, user, request, **kwargs): self.logger.instance.addFilter(ll_logger.ContextFilter(request)) msg = 'User({0}) logged",
"def __init__(self, logger): self.logger = logger # self = sender in this context,",
"user, request, **kwargs): self.logger.instance.addFilter(ll_logger.ContextFilter(request)) msg = 'User({0}) logged out'.format(request.user.username) self.logger.info(self.logger.to_request('Logout', msg)) # Must",
"looked from the perspective of the # Django signal system def login(self, user,",
"get_request import ll_logger from ll_debug import __debugvar__ class SignalHandler: def __init__(self, logger): self.logger",
"self.logger.info(self.logger.to_request('Logout', msg)) # Must override logged username from POST since user is not",
"self.logger = logger # self = sender in this context, when looked from",
"request = get_request() username = request.POST.get('username', 'Undefined') self.logger.instance.addFilter( ll_logger.ContextFilter(request, overrides={'user':username}) ) msg =",
"msg)) # Must override logged username from POST since user is not logged",
"username = request.POST.get('username', 'Undefined') self.logger.instance.addFilter( ll_logger.ContextFilter(request, overrides={'user':username}) ) msg = 'User({0}) failed login'.format(username)",
"in def failed_login(self, credentials, **kwargs): request = get_request() username = request.POST.get('username', 'Undefined') self.logger.instance.addFilter(",
"logout(self, user, request, **kwargs): self.logger.instance.addFilter(ll_logger.ContextFilter(request)) msg = 'User({0}) logged out'.format(request.user.username) self.logger.info(self.logger.to_request('Logout', msg)) #",
"def login(self, user, request, **kwargs): self.logger.instance.addFilter(ll_logger.ContextFilter(request)) msg = 'User({0}) logged in'.format(request.user.username) self.logger.info(self.logger.to_request('Login', msg))",
"logger # self = sender in this context, when looked from the perspective",
"override logged username from POST since user is not logged in def failed_login(self,",
"request.POST.get('username', 'Undefined') self.logger.instance.addFilter( ll_logger.ContextFilter(request, overrides={'user':username}) ) msg = 'User({0}) failed login'.format(username) self.logger.info(self.logger.to_request('Login.fail', msg))",
"request, **kwargs): self.logger.instance.addFilter(ll_logger.ContextFilter(request)) msg = 'User({0}) logged in'.format(request.user.username) self.logger.info(self.logger.to_request('Login', msg)) def logout(self, user,",
"**kwargs): self.logger.instance.addFilter(ll_logger.ContextFilter(request)) msg = 'User({0}) logged in'.format(request.user.username) self.logger.info(self.logger.to_request('Login', msg)) def logout(self, user, request,",
"logger): self.logger = logger # self = sender in this context, when looked",
"the perspective of the # Django signal system def login(self, user, request, **kwargs):",
"username from POST since user is not logged in def failed_login(self, credentials, **kwargs):",
"ll_debug import __debugvar__ class SignalHandler: def __init__(self, logger): self.logger = logger # self",
"since user is not logged in def failed_login(self, credentials, **kwargs): request = get_request()",
"import __debugvar__ class SignalHandler: def __init__(self, logger): self.logger = logger # self =",
"signal system def login(self, user, request, **kwargs): self.logger.instance.addFilter(ll_logger.ContextFilter(request)) msg = 'User({0}) logged in'.format(request.user.username)",
"self.logger.instance.addFilter(ll_logger.ContextFilter(request)) msg = 'User({0}) logged out'.format(request.user.username) self.logger.info(self.logger.to_request('Logout', msg)) # Must override logged username",
"in this context, when looked from the perspective of the # Django signal",
"get_request() username = request.POST.get('username', 'Undefined') self.logger.instance.addFilter( ll_logger.ContextFilter(request, overrides={'user':username}) ) msg = 'User({0}) failed",
"credentials, **kwargs): request = get_request() username = request.POST.get('username', 'Undefined') self.logger.instance.addFilter( ll_logger.ContextFilter(request, overrides={'user':username}) )",
"self.logger.info(self.logger.to_request('Login', msg)) def logout(self, user, request, **kwargs): self.logger.instance.addFilter(ll_logger.ContextFilter(request)) msg = 'User({0}) logged out'.format(request.user.username)",
"import user_logged_in from request_provider.signals import get_request import ll_logger from ll_debug import __debugvar__ class",
"request_provider.signals import get_request import ll_logger from ll_debug import __debugvar__ class SignalHandler: def __init__(self,",
"logged in'.format(request.user.username) self.logger.info(self.logger.to_request('Login', msg)) def logout(self, user, request, **kwargs): self.logger.instance.addFilter(ll_logger.ContextFilter(request)) msg = 'User({0})",
"= sender in this context, when looked from the perspective of the #",
"ll_logger from ll_debug import __debugvar__ class SignalHandler: def __init__(self, logger): self.logger = logger",
"self = sender in this context, when looked from the perspective of the",
"from POST since user is not logged in def failed_login(self, credentials, **kwargs): request",
"logged out'.format(request.user.username) self.logger.info(self.logger.to_request('Logout', msg)) # Must override logged username from POST since user",
"# Must override logged username from POST since user is not logged in",
"# Django signal system def login(self, user, request, **kwargs): self.logger.instance.addFilter(ll_logger.ContextFilter(request)) msg = 'User({0})",
"SignalHandler: def __init__(self, logger): self.logger = logger # self = sender in this",
"def failed_login(self, credentials, **kwargs): request = get_request() username = request.POST.get('username', 'Undefined') self.logger.instance.addFilter( ll_logger.ContextFilter(request,",
"import ll_logger from ll_debug import __debugvar__ class SignalHandler: def __init__(self, logger): self.logger =",
"= logger # self = sender in this context, when looked from the",
"self.logger.instance.addFilter(ll_logger.ContextFilter(request)) msg = 'User({0}) logged in'.format(request.user.username) self.logger.info(self.logger.to_request('Login', msg)) def logout(self, user, request, **kwargs):",
"of the # Django signal system def login(self, user, request, **kwargs): self.logger.instance.addFilter(ll_logger.ContextFilter(request)) msg",
"= request.POST.get('username', 'Undefined') self.logger.instance.addFilter( ll_logger.ContextFilter(request, overrides={'user':username}) ) msg = 'User({0}) failed login'.format(username) self.logger.info(self.logger.to_request('Login.fail',",
"'User({0}) logged in'.format(request.user.username) self.logger.info(self.logger.to_request('Login', msg)) def logout(self, user, request, **kwargs): self.logger.instance.addFilter(ll_logger.ContextFilter(request)) msg =",
"logged username from POST since user is not logged in def failed_login(self, credentials,",
"django.contrib.auth.signals import user_logged_in from request_provider.signals import get_request import ll_logger from ll_debug import __debugvar__",
"not logged in def failed_login(self, credentials, **kwargs): request = get_request() username = request.POST.get('username',",
"the # Django signal system def login(self, user, request, **kwargs): self.logger.instance.addFilter(ll_logger.ContextFilter(request)) msg =",
"<reponame>YmonOy/lastline_api<filename>intel/ll_signals.py<gh_stars>1-10 from django.contrib.auth.signals import user_logged_in from request_provider.signals import get_request import ll_logger from ll_debug",
"user is not logged in def failed_login(self, credentials, **kwargs): request = get_request() username",
"import get_request import ll_logger from ll_debug import __debugvar__ class SignalHandler: def __init__(self, logger):",
"logged in def failed_login(self, credentials, **kwargs): request = get_request() username = request.POST.get('username', 'Undefined')"
] |
[
"a = a, b except IndexError: raise StopCoefficients gamma_sq, err = \\ integrate.quad(self.J,",
"class SpQuadDiscretizedSymmetricBath(BaseDiscretizedSymmetricBath): def __init__(self, J, domain, max_nof_coefficients=100, interval_type='lin', **kwargs): \"\"\" Generates direct discretization",
"of the domain: try: a, b = x_pts_p[int_index], x_pts_p[int_index + 1] # Must",
"domain[1]: print('Domain must contain 0!') raise AssertionError try: self.ignore_zeros = kwargs['ignore_zeros'] except KeyError:",
"stop_n: Index up to which new coefficients are calculated \"\"\" x_pts_p = self.x_pts_p[::-1]",
"the view, because for log-discretization the positive domain grid points are in #",
"default_limit from mapping.star.discretized_bath.stopcoeff import StopCoefficients from mapping.star.discretized_bath.intervals import get_symmetric_interval_points class SpQuadDiscretizedSymmetricBath(BaseDiscretizedSymmetricBath): def __init__(self,",
"by computing the integrals: gamma_i = sqrt(int_i^i+1 J(x) dx) xi_i = int_i^i+1 J(x)",
"= J super().__init__(self.compute_coefficients, max_nof_coefficients=max_nof_coefficients) def compute_coefficients(self, stop_n): \"\"\" Calculates the discretization coefficients up",
"where the integrals for the couplings and energies are evaluated using scipy quad",
"integrations, default is 1e-11 'epsrel': relative tolerance for the scipy integrations, default is",
"< 0 < domain[1]: print('Domain must contain 0!') raise AssertionError try: self.ignore_zeros =",
"to stop_n (actually calculates 2*stop_n - self.next_n coefficients, since the indices are tailored",
"the domain of J. The domain must contain 0. :param max_nof_coefficients: Size of",
"coefficients that can be calculated) :param interval_type: see star.get_discretized_bath for an explanation of",
"part of the domain: try: a, b = x_pts_p[int_index], x_pts_p[int_index + 1] #",
"gamma_i is numerically 0, the corresponding xi_i is also set 0, default is",
"may contain 'ignore_zeros' If one gamma_i is numerically 0, the corresponding xi_i is",
"get_symmetric_interval_points class SpQuadDiscretizedSymmetricBath(BaseDiscretizedSymmetricBath): def __init__(self, J, domain, max_nof_coefficients=100, interval_type='lin', **kwargs): \"\"\" Generates direct",
"of the available types :param kwargs: may contain 'ignore_zeros' If one gamma_i is",
"x_pts_p[int_index], x_pts_p[int_index + 1] # Must invert the view, because for log-discretization the",
"are tailored for asymmetric discretizations) :param stop_n: Index up to which new coefficients",
"self.x_pts_p[::-1] if self.interval_type == 'log' else self.x_pts_p for n in range(2*self._next_n, 2*stop_n, 2):",
"kwargs['epsabs'] except KeyError: self.epsabs = default_epsabs try: self.epsrel = kwargs['epsrel'] except KeyError: self.epsrel",
"err = \\ integrate.quad(self.J, a, b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) xi_numerator, err = \\",
"= get_symmetric_interval_points(domain, max_nof_coefficients, interval_type=interval_type, get_spacing=False, **kwargs) self.J = J super().__init__(self.compute_coefficients, max_nof_coefficients=max_nof_coefficients) def compute_coefficients(self,",
"is numerically 0, the corresponding xi_i is also set 0, default is False",
"and energies are evaluated using scipy quad \"\"\" import numpy as np from",
"absolute tolerance for the scipy integrations, default is 1e-11 'epsrel': relative tolerance for",
"List/tuple of two elements for the left and right boundary of the domain",
"not np.isinf(domain[1]) if not domain[0] < 0 < domain[1]: print('Domain must contain 0!')",
"\"\"\" Generates direct discretization coefficients from a spectral density J, by computing the",
"in the inner part of domain :param domain: List/tuple of two elements for",
"100 \"\"\" assert not np.isinf(domain[0]) and not np.isinf(domain[1]) if not domain[0] < 0",
"interval_type: see star.get_discretized_bath for an explanation of the available types :param kwargs: may",
"tolerance for the scipy integrations, default is 1e-11 'limit': limit parameter for the",
"/ gamma_sq # Coefficients for the negative part of the domain: try: a,",
"'ignore_zeros' If one gamma_i is numerically 0, the corresponding xi_i is also set",
"spectral density J, by computing the integrals: gamma_i = sqrt(int_i^i+1 J(x) dx) xi_i",
"log-discretization the positive domain grid points are in # inverted order if self.interval_type",
"self.epsrel = kwargs['epsrel'] except KeyError: self.epsrel = default_epsrel try: self.limit = kwargs['limit'] except",
"1], self.x_pts_m[int_index] # Must invert the view, because for log-discretization the positive domain",
"for the scipy integrations, default is 1e-11 'limit': limit parameter for the scipy",
"err = \\ integrate.quad(lambda x: x * self.J(x), a, b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit)",
"computing the integrals: gamma_i = sqrt(int_i^i+1 J(x) dx) xi_i = int_i^i+1 J(x) *",
"the indices are tailored for asymmetric discretizations) :param stop_n: Index up to which",
"hold gamma and xi coefficients (maximum number of these coefficients that can be",
"points are in # inverted order if self.interval_type == 'log': b, a =",
"Spectral density. A function defined on 'domain', must be >0 in the inner",
"parameter for the scipy quad function, default is 100 \"\"\" assert not np.isinf(domain[0])",
"self.gamma_buf[n+1] = np.sqrt(gamma_sq) if self.ignore_zeros and gamma_sq == 0: self.xi_buf[n+1] = 0 else:",
"default is 1e-11 'epsrel': relative tolerance for the scipy integrations, default is 1e-11",
"must be >0 in the inner part of domain :param domain: List/tuple of",
"is 1e-11 'limit': limit parameter for the scipy quad function, default is 100",
"False 'epsabs': absolute tolerance for the scipy integrations, default is 1e-11 'epsrel': relative",
"couplings and energies are evaluated using scipy quad \"\"\" import numpy as np",
"self.x_pts_m = get_symmetric_interval_points(domain, max_nof_coefficients, interval_type=interval_type, get_spacing=False, **kwargs) self.J = J super().__init__(self.compute_coefficients, max_nof_coefficients=max_nof_coefficients) def",
"self.xi_buf[n] = 0 else: self.xi_buf[n] = xi_numerator / gamma_sq # Coefficients for the",
"the corresponding xi_i is also set 0, default is False 'epsabs': absolute tolerance",
"= sqrt(int_i^i+1 J(x) dx) xi_i = int_i^i+1 J(x) * x dx/ gamma_i^2 :param",
"that can be calculated) :param interval_type: see star.get_discretized_bath for an explanation of the",
"and xi coefficients (maximum number of these coefficients that can be calculated) :param",
"\"\"\" assert not np.isinf(domain[0]) and not np.isinf(domain[1]) if not domain[0] < 0 <",
"print('Domain must contain 0!') raise AssertionError try: self.ignore_zeros = kwargs['ignore_zeros'] except KeyError: self.ignore_zeros",
"sqrt(int_i^i+1 J(x) dx) xi_i = int_i^i+1 J(x) * x dx/ gamma_i^2 :param J:",
"be calculated) :param interval_type: see star.get_discretized_bath for an explanation of the available types",
"of the buffers which hold gamma and xi coefficients (maximum number of these",
"the buffers which hold gamma and xi coefficients (maximum number of these coefficients",
"for the scipy integrations, default is 1e-11 'epsrel': relative tolerance for the scipy",
"x dx/ gamma_i^2 :param J: Spectral density. A function defined on 'domain', must",
"= default_epsabs try: self.epsrel = kwargs['epsrel'] except KeyError: self.epsrel = default_epsrel try: self.limit",
"(maximum number of these coefficients that can be calculated) :param interval_type: see star.get_discretized_bath",
"for log-discretization the positive domain grid points are in # inverted order if",
"x: x * self.J(x), a, b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) self.gamma_buf[n] = np.sqrt(gamma_sq) if",
"= int_i^i+1 J(x) * x dx/ gamma_i^2 :param J: Spectral density. A function",
"function defined on 'domain', must be >0 in the inner part of domain",
"J(x) * x dx/ gamma_i^2 :param J: Spectral density. A function defined on",
"Size of the buffers which hold gamma and xi coefficients (maximum number of",
"if not domain[0] < 0 < domain[1]: print('Domain must contain 0!') raise AssertionError",
"= a, b except IndexError: raise StopCoefficients gamma_sq, err = \\ integrate.quad(self.J, a,",
"two elements for the left and right boundary of the domain of J.",
"= kwargs['epsrel'] except KeyError: self.epsrel = default_epsrel try: self.limit = kwargs['limit'] except KeyError:",
"try: a, b = x_pts_p[int_index], x_pts_p[int_index + 1] # Must invert the view,",
"1e-11 'limit': limit parameter for the scipy quad function, default is 100 \"\"\"",
"int_index = n // 2 # Coefficients for the positive part of the",
"self.x_pts_p, self.x_pts_m = get_symmetric_interval_points(domain, max_nof_coefficients, interval_type=interval_type, get_spacing=False, **kwargs) self.J = J super().__init__(self.compute_coefficients, max_nof_coefficients=max_nof_coefficients)",
"integrate.quad(lambda x: x * self.J(x), a, b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) self.gamma_buf[n+1] = np.sqrt(gamma_sq)",
"for the generation of direct symmetric discretization coefficients, where the integrals for the",
"= self.x_pts_m[int_index + 1], self.x_pts_m[int_index] # Must invert the view, because for log-discretization",
"= np.sqrt(gamma_sq) if self.ignore_zeros and gamma_sq == 0: self.xi_buf[n+1] = 0 else: self.xi_buf[n+1]",
"except KeyError: self.ignore_zeros = False try: self.epsabs = kwargs['epsabs'] except KeyError: self.epsabs =",
"int_i^i+1 J(x) * x dx/ gamma_i^2 :param J: Spectral density. A function defined",
"= \\ integrate.quad(self.J, a, b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) xi_numerator, err = \\ integrate.quad(lambda",
"if self.ignore_zeros and gamma_sq == 0: self.xi_buf[n+1] = 0 else: self.xi_buf[n+1] = xi_numerator",
"2 # Coefficients for the positive part of the domain: try: a, b",
"J: Spectral density. A function defined on 'domain', must be >0 in the",
"0, the corresponding xi_i is also set 0, default is False 'epsabs': absolute",
"A function defined on 'domain', must be >0 in the inner part of",
"since the indices are tailored for asymmetric discretizations) :param stop_n: Index up to",
"raise StopCoefficients gamma_sq, err = \\ integrate.quad(self.J, a, b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) xi_numerator,",
"\"\"\" x_pts_p = self.x_pts_p[::-1] if self.interval_type == 'log' else self.x_pts_p for n in",
"coefficients from a spectral density J, by computing the integrals: gamma_i = sqrt(int_i^i+1",
"of two elements for the left and right boundary of the domain of",
"epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) xi_numerator, err = \\ integrate.quad(lambda x: x * self.J(x), a,",
"in range(2*self._next_n, 2*stop_n, 2): int_index = n // 2 # Coefficients for the",
"0!') raise AssertionError try: self.ignore_zeros = kwargs['ignore_zeros'] except KeyError: self.ignore_zeros = False try:",
"Generates direct discretization coefficients from a spectral density J, by computing the integrals:",
"xi_numerator, err = \\ integrate.quad(lambda x: x * self.J(x), a, b, epsabs=self.epsabs, epsrel=self.epsrel,",
"import integrate from mapping.star.discretized_bath.base.symmetric import BaseDiscretizedSymmetricBath from mapping.utils.integration_defaults import default_epsabs, default_epsrel, default_limit from",
"range(2*self._next_n, 2*stop_n, 2): int_index = n // 2 # Coefficients for the positive",
"domain must contain 0. :param max_nof_coefficients: Size of the buffers which hold gamma",
"number of these coefficients that can be calculated) :param interval_type: see star.get_discretized_bath for",
"n in range(2*self._next_n, 2*stop_n, 2): int_index = n // 2 # Coefficients for",
"inner part of domain :param domain: List/tuple of two elements for the left",
"domain :param domain: List/tuple of two elements for the left and right boundary",
"star.get_discretized_bath for an explanation of the available types :param kwargs: may contain 'ignore_zeros'",
"\"\"\" import numpy as np from scipy import integrate from mapping.star.discretized_bath.base.symmetric import BaseDiscretizedSymmetricBath",
"self.ignore_zeros = False try: self.epsabs = kwargs['epsabs'] except KeyError: self.epsabs = default_epsabs try:",
"the discretization coefficients up to stop_n (actually calculates 2*stop_n - self.next_n coefficients, since",
"Calculates the discretization coefficients up to stop_n (actually calculates 2*stop_n - self.next_n coefficients,",
"for the negative part of the domain: try: a, b = self.x_pts_m[int_index +",
"np.isinf(domain[0]) and not np.isinf(domain[1]) if not domain[0] < 0 < domain[1]: print('Domain must",
"an explanation of the available types :param kwargs: may contain 'ignore_zeros' If one",
"'epsabs': absolute tolerance for the scipy integrations, default is 1e-11 'epsrel': relative tolerance",
"domain[0] < 0 < domain[1]: print('Domain must contain 0!') raise AssertionError try: self.ignore_zeros",
"Discretized bath for the generation of direct symmetric discretization coefficients, where the integrals",
"quad \"\"\" import numpy as np from scipy import integrate from mapping.star.discretized_bath.base.symmetric import",
"numpy as np from scipy import integrate from mapping.star.discretized_bath.base.symmetric import BaseDiscretizedSymmetricBath from mapping.utils.integration_defaults",
"BaseDiscretizedSymmetricBath from mapping.utils.integration_defaults import default_epsabs, default_epsrel, default_limit from mapping.star.discretized_bath.stopcoeff import StopCoefficients from mapping.star.discretized_bath.intervals",
"integrations, default is 1e-11 'limit': limit parameter for the scipy quad function, default",
"up to stop_n (actually calculates 2*stop_n - self.next_n coefficients, since the indices are",
"= \\ integrate.quad(lambda x: x * self.J(x), a, b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) self.gamma_buf[n]",
"direct symmetric discretization coefficients, where the integrals for the couplings and energies are",
"b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) self.gamma_buf[n] = np.sqrt(gamma_sq) if self.ignore_zeros and gamma_sq == 0:",
"the scipy integrations, default is 1e-11 'limit': limit parameter for the scipy quad",
"self.x_pts_m[int_index] # Must invert the view, because for log-discretization the positive domain grid",
"for an explanation of the available types :param kwargs: may contain 'ignore_zeros' If",
"default_epsrel try: self.limit = kwargs['limit'] except KeyError: self.limit = default_limit self.interval_type = interval_type",
"import StopCoefficients from mapping.star.discretized_bath.intervals import get_symmetric_interval_points class SpQuadDiscretizedSymmetricBath(BaseDiscretizedSymmetricBath): def __init__(self, J, domain, max_nof_coefficients=100,",
"self.x_pts_m[int_index + 1], self.x_pts_m[int_index] # Must invert the view, because for log-discretization the",
"1e-11 'epsrel': relative tolerance for the scipy integrations, default is 1e-11 'limit': limit",
"AssertionError try: self.ignore_zeros = kwargs['ignore_zeros'] except KeyError: self.ignore_zeros = False try: self.epsabs =",
"import BaseDiscretizedSymmetricBath from mapping.utils.integration_defaults import default_epsabs, default_epsrel, default_limit from mapping.star.discretized_bath.stopcoeff import StopCoefficients from",
"gamma_sq # Coefficients for the negative part of the domain: try: a, b",
"are calculated \"\"\" x_pts_p = self.x_pts_p[::-1] if self.interval_type == 'log' else self.x_pts_p for",
"= \\ integrate.quad(lambda x: x * self.J(x), a, b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) self.gamma_buf[n+1]",
"explanation of the available types :param kwargs: may contain 'ignore_zeros' If one gamma_i",
"= n // 2 # Coefficients for the positive part of the domain:",
"else: self.xi_buf[n] = xi_numerator / gamma_sq # Coefficients for the negative part of",
"corresponding xi_i is also set 0, default is False 'epsabs': absolute tolerance for",
"the left and right boundary of the domain of J. The domain must",
"self.gamma_buf[n] = np.sqrt(gamma_sq) if self.ignore_zeros and gamma_sq == 0: self.xi_buf[n] = 0 else:",
"max_nof_coefficients, interval_type=interval_type, get_spacing=False, **kwargs) self.J = J super().__init__(self.compute_coefficients, max_nof_coefficients=max_nof_coefficients) def compute_coefficients(self, stop_n): \"\"\"",
"Coefficients for the negative part of the domain: try: a, b = self.x_pts_m[int_index",
"types :param kwargs: may contain 'ignore_zeros' If one gamma_i is numerically 0, the",
"contain 'ignore_zeros' If one gamma_i is numerically 0, the corresponding xi_i is also",
"for the scipy quad function, default is 100 \"\"\" assert not np.isinf(domain[0]) and",
"asymmetric discretizations) :param stop_n: Index up to which new coefficients are calculated \"\"\"",
"because for log-discretization the positive domain grid points are in # inverted order",
":param domain: List/tuple of two elements for the left and right boundary of",
"max_nof_coefficients=max_nof_coefficients) def compute_coefficients(self, stop_n): \"\"\" Calculates the discretization coefficients up to stop_n (actually",
"a, b = x_pts_p[int_index], x_pts_p[int_index + 1] # Must invert the view, because",
"J super().__init__(self.compute_coefficients, max_nof_coefficients=max_nof_coefficients) def compute_coefficients(self, stop_n): \"\"\" Calculates the discretization coefficients up to",
"= xi_numerator / gamma_sq # Coefficients for the negative part of the domain:",
"+ 1], self.x_pts_m[int_index] # Must invert the view, because for log-discretization the positive",
"gamma_i = sqrt(int_i^i+1 J(x) dx) xi_i = int_i^i+1 J(x) * x dx/ gamma_i^2",
"= default_epsrel try: self.limit = kwargs['limit'] except KeyError: self.limit = default_limit self.interval_type =",
"and gamma_sq == 0: self.xi_buf[n] = 0 else: self.xi_buf[n] = xi_numerator / gamma_sq",
"'limit': limit parameter for the scipy quad function, default is 100 \"\"\" assert",
"density J, by computing the integrals: gamma_i = sqrt(int_i^i+1 J(x) dx) xi_i =",
"\\ integrate.quad(lambda x: x * self.J(x), a, b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) self.gamma_buf[n] =",
"super().__init__(self.compute_coefficients, max_nof_coefficients=max_nof_coefficients) def compute_coefficients(self, stop_n): \"\"\" Calculates the discretization coefficients up to stop_n",
"the positive part of the domain: try: a, b = x_pts_p[int_index], x_pts_p[int_index +",
"function, default is 100 \"\"\" assert not np.isinf(domain[0]) and not np.isinf(domain[1]) if not",
"KeyError: self.limit = default_limit self.interval_type = interval_type self.x_pts_p, self.x_pts_m = get_symmetric_interval_points(domain, max_nof_coefficients, interval_type=interval_type,",
"also set 0, default is False 'epsabs': absolute tolerance for the scipy integrations,",
"using scipy quad \"\"\" import numpy as np from scipy import integrate from",
"contain 0. :param max_nof_coefficients: Size of the buffers which hold gamma and xi",
"quad function, default is 100 \"\"\" assert not np.isinf(domain[0]) and not np.isinf(domain[1]) if",
"xi_i is also set 0, default is False 'epsabs': absolute tolerance for the",
"order if self.interval_type == 'log': b, a = a, b except IndexError: raise",
"see star.get_discretized_bath for an explanation of the available types :param kwargs: may contain",
"x: x * self.J(x), a, b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) self.gamma_buf[n+1] = np.sqrt(gamma_sq) if",
"from mapping.utils.integration_defaults import default_epsabs, default_epsrel, default_limit from mapping.star.discretized_bath.stopcoeff import StopCoefficients from mapping.star.discretized_bath.intervals import",
"default is 1e-11 'limit': limit parameter for the scipy quad function, default is",
"new coefficients are calculated \"\"\" x_pts_p = self.x_pts_p[::-1] if self.interval_type == 'log' else",
"which hold gamma and xi coefficients (maximum number of these coefficients that can",
"discretization coefficients, where the integrals for the couplings and energies are evaluated using",
"the generation of direct symmetric discretization coefficients, where the integrals for the couplings",
"SpQuadDiscretizedSymmetricBath(BaseDiscretizedSymmetricBath): def __init__(self, J, domain, max_nof_coefficients=100, interval_type='lin', **kwargs): \"\"\" Generates direct discretization coefficients",
"0. :param max_nof_coefficients: Size of the buffers which hold gamma and xi coefficients",
"assert not np.isinf(domain[0]) and not np.isinf(domain[1]) if not domain[0] < 0 < domain[1]:",
"= default_limit self.interval_type = interval_type self.x_pts_p, self.x_pts_m = get_symmetric_interval_points(domain, max_nof_coefficients, interval_type=interval_type, get_spacing=False, **kwargs)",
"coefficients, where the integrals for the couplings and energies are evaluated using scipy",
"the inner part of domain :param domain: List/tuple of two elements for the",
"is 100 \"\"\" assert not np.isinf(domain[0]) and not np.isinf(domain[1]) if not domain[0] <",
"raise AssertionError try: self.ignore_zeros = kwargs['ignore_zeros'] except KeyError: self.ignore_zeros = False try: self.epsabs",
"epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) self.gamma_buf[n] = np.sqrt(gamma_sq) if self.ignore_zeros and gamma_sq == 0: self.xi_buf[n]",
"up to which new coefficients are calculated \"\"\" x_pts_p = self.x_pts_p[::-1] if self.interval_type",
"Index up to which new coefficients are calculated \"\"\" x_pts_p = self.x_pts_p[::-1] if",
"gamma_sq == 0: self.xi_buf[n] = 0 else: self.xi_buf[n] = xi_numerator / gamma_sq #",
"* self.J(x), a, b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) self.gamma_buf[n+1] = np.sqrt(gamma_sq) if self.ignore_zeros and",
"a, b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) self.gamma_buf[n+1] = np.sqrt(gamma_sq) if self.ignore_zeros and gamma_sq ==",
"self.ignore_zeros and gamma_sq == 0: self.xi_buf[n+1] = 0 else: self.xi_buf[n+1] = xi_numerator /",
"which new coefficients are calculated \"\"\" x_pts_p = self.x_pts_p[::-1] if self.interval_type == 'log'",
"np.sqrt(gamma_sq) if self.ignore_zeros and gamma_sq == 0: self.xi_buf[n] = 0 else: self.xi_buf[n] =",
"the domain: try: a, b = self.x_pts_m[int_index + 1], self.x_pts_m[int_index] # Must invert",
"If one gamma_i is numerically 0, the corresponding xi_i is also set 0,",
"from mapping.star.discretized_bath.intervals import get_symmetric_interval_points class SpQuadDiscretizedSymmetricBath(BaseDiscretizedSymmetricBath): def __init__(self, J, domain, max_nof_coefficients=100, interval_type='lin', **kwargs):",
"the domain: try: a, b = x_pts_p[int_index], x_pts_p[int_index + 1] # Must invert",
"coefficients are calculated \"\"\" x_pts_p = self.x_pts_p[::-1] if self.interval_type == 'log' else self.x_pts_p",
"KeyError: self.epsabs = default_epsabs try: self.epsrel = kwargs['epsrel'] except KeyError: self.epsrel = default_epsrel",
"gamma_sq, err = \\ integrate.quad(self.J, a, b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) xi_numerator, err =",
"= x_pts_p[int_index], x_pts_p[int_index + 1] # Must invert the view, because for log-discretization",
"the positive domain grid points are in # inverted order if self.interval_type ==",
"if self.interval_type == 'log': b, a = a, b except IndexError: raise StopCoefficients",
"b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) xi_numerator, err = \\ integrate.quad(lambda x: x * self.J(x),",
"kwargs['ignore_zeros'] except KeyError: self.ignore_zeros = False try: self.epsabs = kwargs['epsabs'] except KeyError: self.epsabs",
"symmetric discretization coefficients, where the integrals for the couplings and energies are evaluated",
"try: self.ignore_zeros = kwargs['ignore_zeros'] except KeyError: self.ignore_zeros = False try: self.epsabs = kwargs['epsabs']",
"default is False 'epsabs': absolute tolerance for the scipy integrations, default is 1e-11",
"domain grid points are in # inverted order if self.interval_type == 'log': b,",
"buffers which hold gamma and xi coefficients (maximum number of these coefficients that",
"interval_type='lin', **kwargs): \"\"\" Generates direct discretization coefficients from a spectral density J, by",
"gamma and xi coefficients (maximum number of these coefficients that can be calculated)",
"limit=self.limit) self.gamma_buf[n+1] = np.sqrt(gamma_sq) if self.ignore_zeros and gamma_sq == 0: self.xi_buf[n+1] = 0",
"'epsrel': relative tolerance for the scipy integrations, default is 1e-11 'limit': limit parameter",
"dx) xi_i = int_i^i+1 J(x) * x dx/ gamma_i^2 :param J: Spectral density.",
"discretization coefficients from a spectral density J, by computing the integrals: gamma_i =",
"0 < domain[1]: print('Domain must contain 0!') raise AssertionError try: self.ignore_zeros = kwargs['ignore_zeros']",
"available types :param kwargs: may contain 'ignore_zeros' If one gamma_i is numerically 0,",
"view, because for log-discretization the positive domain grid points are in # inverted",
"kwargs['epsrel'] except KeyError: self.epsrel = default_epsrel try: self.limit = kwargs['limit'] except KeyError: self.limit",
"StopCoefficients gamma_sq, err = \\ integrate.quad(self.J, a, b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) xi_numerator, err",
"2): int_index = n // 2 # Coefficients for the positive part of",
"is 1e-11 'epsrel': relative tolerance for the scipy integrations, default is 1e-11 'limit':",
"(actually calculates 2*stop_n - self.next_n coefficients, since the indices are tailored for asymmetric",
"else self.x_pts_p for n in range(2*self._next_n, 2*stop_n, 2): int_index = n // 2",
"of direct symmetric discretization coefficients, where the integrals for the couplings and energies",
"The domain must contain 0. :param max_nof_coefficients: Size of the buffers which hold",
"and right boundary of the domain of J. The domain must contain 0.",
"inverted order if self.interval_type == 'log': b, a = a, b except IndexError:",
"* self.J(x), a, b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) self.gamma_buf[n] = np.sqrt(gamma_sq) if self.ignore_zeros and",
"= kwargs['ignore_zeros'] except KeyError: self.ignore_zeros = False try: self.epsabs = kwargs['epsabs'] except KeyError:",
"np.isinf(domain[1]) if not domain[0] < 0 < domain[1]: print('Domain must contain 0!') raise",
"limit parameter for the scipy quad function, default is 100 \"\"\" assert not",
"<filename>mapping/star/discretized_bath/symmetric_spquad.py \"\"\" Discretized bath for the generation of direct symmetric discretization coefficients, where",
"self.interval_type == 'log' else self.x_pts_p for n in range(2*self._next_n, 2*stop_n, 2): int_index =",
"integrals: gamma_i = sqrt(int_i^i+1 J(x) dx) xi_i = int_i^i+1 J(x) * x dx/",
"2*stop_n, 2): int_index = n // 2 # Coefficients for the positive part",
"default is 100 \"\"\" assert not np.isinf(domain[0]) and not np.isinf(domain[1]) if not domain[0]",
"domain of J. The domain must contain 0. :param max_nof_coefficients: Size of the",
"np.sqrt(gamma_sq) if self.ignore_zeros and gamma_sq == 0: self.xi_buf[n+1] = 0 else: self.xi_buf[n+1] =",
"mapping.star.discretized_bath.intervals import get_symmetric_interval_points class SpQuadDiscretizedSymmetricBath(BaseDiscretizedSymmetricBath): def __init__(self, J, domain, max_nof_coefficients=100, interval_type='lin', **kwargs): \"\"\"",
"a, b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) self.gamma_buf[n] = np.sqrt(gamma_sq) if self.ignore_zeros and gamma_sq ==",
"gamma_i^2 :param J: Spectral density. A function defined on 'domain', must be >0",
"of the domain of J. The domain must contain 0. :param max_nof_coefficients: Size",
"< domain[1]: print('Domain must contain 0!') raise AssertionError try: self.ignore_zeros = kwargs['ignore_zeros'] except",
"import numpy as np from scipy import integrate from mapping.star.discretized_bath.base.symmetric import BaseDiscretizedSymmetricBath from",
"b, a = a, b except IndexError: raise StopCoefficients gamma_sq, err = \\",
"\\ integrate.quad(self.J, a, b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) xi_numerator, err = \\ integrate.quad(lambda x:",
"for n in range(2*self._next_n, 2*stop_n, 2): int_index = n // 2 # Coefficients",
"xi coefficients (maximum number of these coefficients that can be calculated) :param interval_type:",
"1] # Must invert the view, because for log-discretization the positive domain grid",
"b = x_pts_p[int_index], x_pts_p[int_index + 1] # Must invert the view, because for",
"# Coefficients for the negative part of the domain: try: a, b =",
"import get_symmetric_interval_points class SpQuadDiscretizedSymmetricBath(BaseDiscretizedSymmetricBath): def __init__(self, J, domain, max_nof_coefficients=100, interval_type='lin', **kwargs): \"\"\" Generates",
"for the positive part of the domain: try: a, b = x_pts_p[int_index], x_pts_p[int_index",
"calculated) :param interval_type: see star.get_discretized_bath for an explanation of the available types :param",
"epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) self.gamma_buf[n+1] = np.sqrt(gamma_sq) if self.ignore_zeros and gamma_sq == 0: self.xi_buf[n+1]",
"integrate.quad(self.J, a, b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) xi_numerator, err = \\ integrate.quad(lambda x: x",
"as np from scipy import integrate from mapping.star.discretized_bath.base.symmetric import BaseDiscretizedSymmetricBath from mapping.utils.integration_defaults import",
"not domain[0] < 0 < domain[1]: print('Domain must contain 0!') raise AssertionError try:",
"np from scipy import integrate from mapping.star.discretized_bath.base.symmetric import BaseDiscretizedSymmetricBath from mapping.utils.integration_defaults import default_epsabs,",
"energies are evaluated using scipy quad \"\"\" import numpy as np from scipy",
"is also set 0, default is False 'epsabs': absolute tolerance for the scipy",
"boundary of the domain of J. The domain must contain 0. :param max_nof_coefficients:",
"\\ integrate.quad(lambda x: x * self.J(x), a, b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) self.gamma_buf[n+1] =",
"discretizations) :param stop_n: Index up to which new coefficients are calculated \"\"\" x_pts_p",
"== 0: self.xi_buf[n] = 0 else: self.xi_buf[n] = xi_numerator / gamma_sq # Coefficients",
"2*stop_n - self.next_n coefficients, since the indices are tailored for asymmetric discretizations) :param",
"coefficients (maximum number of these coefficients that can be calculated) :param interval_type: see",
"= interval_type self.x_pts_p, self.x_pts_m = get_symmetric_interval_points(domain, max_nof_coefficients, interval_type=interval_type, get_spacing=False, **kwargs) self.J = J",
"calculated \"\"\" x_pts_p = self.x_pts_p[::-1] if self.interval_type == 'log' else self.x_pts_p for n",
"def __init__(self, J, domain, max_nof_coefficients=100, interval_type='lin', **kwargs): \"\"\" Generates direct discretization coefficients from",
"x_pts_p = self.x_pts_p[::-1] if self.interval_type == 'log' else self.x_pts_p for n in range(2*self._next_n,",
"scipy integrations, default is 1e-11 'epsrel': relative tolerance for the scipy integrations, default",
"and gamma_sq == 0: self.xi_buf[n+1] = 0 else: self.xi_buf[n+1] = xi_numerator / gamma_sq",
"a, b = self.x_pts_m[int_index + 1], self.x_pts_m[int_index] # Must invert the view, because",
"grid points are in # inverted order if self.interval_type == 'log': b, a",
"for the left and right boundary of the domain of J. The domain",
"IndexError: raise StopCoefficients gamma_sq, err = \\ integrate.quad(self.J, a, b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit)",
"the scipy integrations, default is 1e-11 'epsrel': relative tolerance for the scipy integrations,",
"get_symmetric_interval_points(domain, max_nof_coefficients, interval_type=interval_type, get_spacing=False, **kwargs) self.J = J super().__init__(self.compute_coefficients, max_nof_coefficients=max_nof_coefficients) def compute_coefficients(self, stop_n):",
"must contain 0. :param max_nof_coefficients: Size of the buffers which hold gamma and",
"max_nof_coefficients: Size of the buffers which hold gamma and xi coefficients (maximum number",
"calculates 2*stop_n - self.next_n coefficients, since the indices are tailored for asymmetric discretizations)",
"tailored for asymmetric discretizations) :param stop_n: Index up to which new coefficients are",
"self.epsabs = kwargs['epsabs'] except KeyError: self.epsabs = default_epsabs try: self.epsrel = kwargs['epsrel'] except",
":param stop_n: Index up to which new coefficients are calculated \"\"\" x_pts_p =",
"interval_type self.x_pts_p, self.x_pts_m = get_symmetric_interval_points(domain, max_nof_coefficients, interval_type=interval_type, get_spacing=False, **kwargs) self.J = J super().__init__(self.compute_coefficients,",
"density. A function defined on 'domain', must be >0 in the inner part",
"from mapping.star.discretized_bath.stopcoeff import StopCoefficients from mapping.star.discretized_bath.intervals import get_symmetric_interval_points class SpQuadDiscretizedSymmetricBath(BaseDiscretizedSymmetricBath): def __init__(self, J,",
"b = self.x_pts_m[int_index + 1], self.x_pts_m[int_index] # Must invert the view, because for",
"= kwargs['limit'] except KeyError: self.limit = default_limit self.interval_type = interval_type self.x_pts_p, self.x_pts_m =",
"+ 1] # Must invert the view, because for log-discretization the positive domain",
"limit=self.limit) self.gamma_buf[n] = np.sqrt(gamma_sq) if self.ignore_zeros and gamma_sq == 0: self.xi_buf[n] = 0",
"xi_i = int_i^i+1 J(x) * x dx/ gamma_i^2 :param J: Spectral density. A",
"on 'domain', must be >0 in the inner part of domain :param domain:",
"the scipy quad function, default is 100 \"\"\" assert not np.isinf(domain[0]) and not",
"\"\"\" Calculates the discretization coefficients up to stop_n (actually calculates 2*stop_n - self.next_n",
"== 'log' else self.x_pts_p for n in range(2*self._next_n, 2*stop_n, 2): int_index = n",
"# inverted order if self.interval_type == 'log': b, a = a, b except",
"elements for the left and right boundary of the domain of J. The",
"**kwargs) self.J = J super().__init__(self.compute_coefficients, max_nof_coefficients=max_nof_coefficients) def compute_coefficients(self, stop_n): \"\"\" Calculates the discretization",
"limit=self.limit) xi_numerator, err = \\ integrate.quad(lambda x: x * self.J(x), a, b, epsabs=self.epsabs,",
"- self.next_n coefficients, since the indices are tailored for asymmetric discretizations) :param stop_n:",
"== 'log': b, a = a, b except IndexError: raise StopCoefficients gamma_sq, err",
"x_pts_p[int_index + 1] # Must invert the view, because for log-discretization the positive",
"domain: try: a, b = self.x_pts_m[int_index + 1], self.x_pts_m[int_index] # Must invert the",
">0 in the inner part of domain :param domain: List/tuple of two elements",
"self.J = J super().__init__(self.compute_coefficients, max_nof_coefficients=max_nof_coefficients) def compute_coefficients(self, stop_n): \"\"\" Calculates the discretization coefficients",
"x * self.J(x), a, b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) self.gamma_buf[n+1] = np.sqrt(gamma_sq) if self.ignore_zeros",
"evaluated using scipy quad \"\"\" import numpy as np from scipy import integrate",
"a, b except IndexError: raise StopCoefficients gamma_sq, err = \\ integrate.quad(self.J, a, b,",
"set 0, default is False 'epsabs': absolute tolerance for the scipy integrations, default",
"can be calculated) :param interval_type: see star.get_discretized_bath for an explanation of the available",
"n // 2 # Coefficients for the positive part of the domain: try:",
"self.xi_buf[n] = xi_numerator / gamma_sq # Coefficients for the negative part of the",
"these coefficients that can be calculated) :param interval_type: see star.get_discretized_bath for an explanation",
"b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) self.gamma_buf[n+1] = np.sqrt(gamma_sq) if self.ignore_zeros and gamma_sq == 0:",
"kwargs: may contain 'ignore_zeros' If one gamma_i is numerically 0, the corresponding xi_i",
"from scipy import integrate from mapping.star.discretized_bath.base.symmetric import BaseDiscretizedSymmetricBath from mapping.utils.integration_defaults import default_epsabs, default_epsrel,",
"epsrel=self.epsrel, limit=self.limit) self.gamma_buf[n] = np.sqrt(gamma_sq) if self.ignore_zeros and gamma_sq == 0: self.xi_buf[n] =",
"positive part of the domain: try: a, b = x_pts_p[int_index], x_pts_p[int_index + 1]",
"= self.x_pts_p[::-1] if self.interval_type == 'log' else self.x_pts_p for n in range(2*self._next_n, 2*stop_n,",
"scipy import integrate from mapping.star.discretized_bath.base.symmetric import BaseDiscretizedSymmetricBath from mapping.utils.integration_defaults import default_epsabs, default_epsrel, default_limit",
"mapping.star.discretized_bath.base.symmetric import BaseDiscretizedSymmetricBath from mapping.utils.integration_defaults import default_epsabs, default_epsrel, default_limit from mapping.star.discretized_bath.stopcoeff import StopCoefficients",
"integrate from mapping.star.discretized_bath.base.symmetric import BaseDiscretizedSymmetricBath from mapping.utils.integration_defaults import default_epsabs, default_epsrel, default_limit from mapping.star.discretized_bath.stopcoeff",
":param interval_type: see star.get_discretized_bath for an explanation of the available types :param kwargs:",
"gamma_sq == 0: self.xi_buf[n+1] = 0 else: self.xi_buf[n+1] = xi_numerator / gamma_sq self._update_next_n(1)",
"self.x_pts_p for n in range(2*self._next_n, 2*stop_n, 2): int_index = n // 2 #",
"from a spectral density J, by computing the integrals: gamma_i = sqrt(int_i^i+1 J(x)",
"**kwargs): \"\"\" Generates direct discretization coefficients from a spectral density J, by computing",
"x * self.J(x), a, b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) self.gamma_buf[n] = np.sqrt(gamma_sq) if self.ignore_zeros",
"for the couplings and energies are evaluated using scipy quad \"\"\" import numpy",
"get_spacing=False, **kwargs) self.J = J super().__init__(self.compute_coefficients, max_nof_coefficients=max_nof_coefficients) def compute_coefficients(self, stop_n): \"\"\" Calculates the",
"if self.ignore_zeros and gamma_sq == 0: self.xi_buf[n] = 0 else: self.xi_buf[n] = xi_numerator",
"self.ignore_zeros = kwargs['ignore_zeros'] except KeyError: self.ignore_zeros = False try: self.epsabs = kwargs['epsabs'] except",
"domain, max_nof_coefficients=100, interval_type='lin', **kwargs): \"\"\" Generates direct discretization coefficients from a spectral density",
"in # inverted order if self.interval_type == 'log': b, a = a, b",
"J, by computing the integrals: gamma_i = sqrt(int_i^i+1 J(x) dx) xi_i = int_i^i+1",
"except KeyError: self.epsrel = default_epsrel try: self.limit = kwargs['limit'] except KeyError: self.limit =",
"= kwargs['epsabs'] except KeyError: self.epsabs = default_epsabs try: self.epsrel = kwargs['epsrel'] except KeyError:",
"for asymmetric discretizations) :param stop_n: Index up to which new coefficients are calculated",
"'domain', must be >0 in the inner part of domain :param domain: List/tuple",
"= False try: self.epsabs = kwargs['epsabs'] except KeyError: self.epsabs = default_epsabs try: self.epsrel",
"self.limit = default_limit self.interval_type = interval_type self.x_pts_p, self.x_pts_m = get_symmetric_interval_points(domain, max_nof_coefficients, interval_type=interval_type, get_spacing=False,",
"stop_n (actually calculates 2*stop_n - self.next_n coefficients, since the indices are tailored for",
"coefficients up to stop_n (actually calculates 2*stop_n - self.next_n coefficients, since the indices",
"'log': b, a = a, b except IndexError: raise StopCoefficients gamma_sq, err =",
"left and right boundary of the domain of J. The domain must contain",
"of J. The domain must contain 0. :param max_nof_coefficients: Size of the buffers",
"'log' else self.x_pts_p for n in range(2*self._next_n, 2*stop_n, 2): int_index = n //",
"contain 0!') raise AssertionError try: self.ignore_zeros = kwargs['ignore_zeros'] except KeyError: self.ignore_zeros = False",
"to which new coefficients are calculated \"\"\" x_pts_p = self.x_pts_p[::-1] if self.interval_type ==",
"is False 'epsabs': absolute tolerance for the scipy integrations, default is 1e-11 'epsrel':",
"default_limit self.interval_type = interval_type self.x_pts_p, self.x_pts_m = get_symmetric_interval_points(domain, max_nof_coefficients, interval_type=interval_type, get_spacing=False, **kwargs) self.J",
"stop_n): \"\"\" Calculates the discretization coefficients up to stop_n (actually calculates 2*stop_n -",
"from mapping.star.discretized_bath.base.symmetric import BaseDiscretizedSymmetricBath from mapping.utils.integration_defaults import default_epsabs, default_epsrel, default_limit from mapping.star.discretized_bath.stopcoeff import",
"= 0 else: self.xi_buf[n] = xi_numerator / gamma_sq # Coefficients for the negative",
"mapping.star.discretized_bath.stopcoeff import StopCoefficients from mapping.star.discretized_bath.intervals import get_symmetric_interval_points class SpQuadDiscretizedSymmetricBath(BaseDiscretizedSymmetricBath): def __init__(self, J, domain,",
"J. The domain must contain 0. :param max_nof_coefficients: Size of the buffers which",
"scipy integrations, default is 1e-11 'limit': limit parameter for the scipy quad function,",
"epsrel=self.epsrel, limit=self.limit) xi_numerator, err = \\ integrate.quad(lambda x: x * self.J(x), a, b,",
"self.interval_type == 'log': b, a = a, b except IndexError: raise StopCoefficients gamma_sq,",
"mapping.utils.integration_defaults import default_epsabs, default_epsrel, default_limit from mapping.star.discretized_bath.stopcoeff import StopCoefficients from mapping.star.discretized_bath.intervals import get_symmetric_interval_points",
"and not np.isinf(domain[1]) if not domain[0] < 0 < domain[1]: print('Domain must contain",
"dx/ gamma_i^2 :param J: Spectral density. A function defined on 'domain', must be",
"generation of direct symmetric discretization coefficients, where the integrals for the couplings and",
"relative tolerance for the scipy integrations, default is 1e-11 'limit': limit parameter for",
"numerically 0, the corresponding xi_i is also set 0, default is False 'epsabs':",
"import default_epsabs, default_epsrel, default_limit from mapping.star.discretized_bath.stopcoeff import StopCoefficients from mapping.star.discretized_bath.intervals import get_symmetric_interval_points class",
"0 else: self.xi_buf[n] = xi_numerator / gamma_sq # Coefficients for the negative part",
"positive domain grid points are in # inverted order if self.interval_type == 'log':",
"scipy quad \"\"\" import numpy as np from scipy import integrate from mapping.star.discretized_bath.base.symmetric",
"default_epsabs, default_epsrel, default_limit from mapping.star.discretized_bath.stopcoeff import StopCoefficients from mapping.star.discretized_bath.intervals import get_symmetric_interval_points class SpQuadDiscretizedSymmetricBath(BaseDiscretizedSymmetricBath):",
"epsrel=self.epsrel, limit=self.limit) self.gamma_buf[n+1] = np.sqrt(gamma_sq) if self.ignore_zeros and gamma_sq == 0: self.xi_buf[n+1] =",
"KeyError: self.ignore_zeros = False try: self.epsabs = kwargs['epsabs'] except KeyError: self.epsabs = default_epsabs",
"Coefficients for the positive part of the domain: try: a, b = x_pts_p[int_index],",
"are in # inverted order if self.interval_type == 'log': b, a = a,",
"self.epsabs = default_epsabs try: self.epsrel = kwargs['epsrel'] except KeyError: self.epsrel = default_epsrel try:",
"\"\"\" Discretized bath for the generation of direct symmetric discretization coefficients, where the",
":param kwargs: may contain 'ignore_zeros' If one gamma_i is numerically 0, the corresponding",
"part of domain :param domain: List/tuple of two elements for the left and",
"self.interval_type = interval_type self.x_pts_p, self.x_pts_m = get_symmetric_interval_points(domain, max_nof_coefficients, interval_type=interval_type, get_spacing=False, **kwargs) self.J =",
"0: self.xi_buf[n] = 0 else: self.xi_buf[n] = xi_numerator / gamma_sq # Coefficients for",
"kwargs['limit'] except KeyError: self.limit = default_limit self.interval_type = interval_type self.x_pts_p, self.x_pts_m = get_symmetric_interval_points(domain,",
"of these coefficients that can be calculated) :param interval_type: see star.get_discretized_bath for an",
"not np.isinf(domain[0]) and not np.isinf(domain[1]) if not domain[0] < 0 < domain[1]: print('Domain",
"scipy quad function, default is 100 \"\"\" assert not np.isinf(domain[0]) and not np.isinf(domain[1])",
"0, default is False 'epsabs': absolute tolerance for the scipy integrations, default is",
"if self.interval_type == 'log' else self.x_pts_p for n in range(2*self._next_n, 2*stop_n, 2): int_index",
"# Must invert the view, because for log-discretization the positive domain grid points",
"xi_numerator / gamma_sq # Coefficients for the negative part of the domain: try:",
"one gamma_i is numerically 0, the corresponding xi_i is also set 0, default",
"False try: self.epsabs = kwargs['epsabs'] except KeyError: self.epsabs = default_epsabs try: self.epsrel =",
"try: a, b = self.x_pts_m[int_index + 1], self.x_pts_m[int_index] # Must invert the view,",
"try: self.epsrel = kwargs['epsrel'] except KeyError: self.epsrel = default_epsrel try: self.limit = kwargs['limit']",
"self.ignore_zeros and gamma_sq == 0: self.xi_buf[n] = 0 else: self.xi_buf[n] = xi_numerator /",
"indices are tailored for asymmetric discretizations) :param stop_n: Index up to which new",
"self.limit = kwargs['limit'] except KeyError: self.limit = default_limit self.interval_type = interval_type self.x_pts_p, self.x_pts_m",
"the available types :param kwargs: may contain 'ignore_zeros' If one gamma_i is numerically",
"the negative part of the domain: try: a, b = self.x_pts_m[int_index + 1],",
"defined on 'domain', must be >0 in the inner part of domain :param",
"a, b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) xi_numerator, err = \\ integrate.quad(lambda x: x *",
"b except IndexError: raise StopCoefficients gamma_sq, err = \\ integrate.quad(self.J, a, b, epsabs=self.epsabs,",
"invert the view, because for log-discretization the positive domain grid points are in",
"except KeyError: self.epsabs = default_epsabs try: self.epsrel = kwargs['epsrel'] except KeyError: self.epsrel =",
"self.J(x), a, b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) self.gamma_buf[n+1] = np.sqrt(gamma_sq) if self.ignore_zeros and gamma_sq",
"KeyError: self.epsrel = default_epsrel try: self.limit = kwargs['limit'] except KeyError: self.limit = default_limit",
"the integrals for the couplings and energies are evaluated using scipy quad \"\"\"",
"compute_coefficients(self, stop_n): \"\"\" Calculates the discretization coefficients up to stop_n (actually calculates 2*stop_n",
"part of the domain: try: a, b = self.x_pts_m[int_index + 1], self.x_pts_m[int_index] #",
"except IndexError: raise StopCoefficients gamma_sq, err = \\ integrate.quad(self.J, a, b, epsabs=self.epsabs, epsrel=self.epsrel,",
"right boundary of the domain of J. The domain must contain 0. :param",
"negative part of the domain: try: a, b = self.x_pts_m[int_index + 1], self.x_pts_m[int_index]",
"be >0 in the inner part of domain :param domain: List/tuple of two",
"__init__(self, J, domain, max_nof_coefficients=100, interval_type='lin', **kwargs): \"\"\" Generates direct discretization coefficients from a",
"domain: try: a, b = x_pts_p[int_index], x_pts_p[int_index + 1] # Must invert the",
"default_epsrel, default_limit from mapping.star.discretized_bath.stopcoeff import StopCoefficients from mapping.star.discretized_bath.intervals import get_symmetric_interval_points class SpQuadDiscretizedSymmetricBath(BaseDiscretizedSymmetricBath): def",
"J, domain, max_nof_coefficients=100, interval_type='lin', **kwargs): \"\"\" Generates direct discretization coefficients from a spectral",
"discretization coefficients up to stop_n (actually calculates 2*stop_n - self.next_n coefficients, since the",
"def compute_coefficients(self, stop_n): \"\"\" Calculates the discretization coefficients up to stop_n (actually calculates",
"must contain 0!') raise AssertionError try: self.ignore_zeros = kwargs['ignore_zeros'] except KeyError: self.ignore_zeros =",
"direct discretization coefficients from a spectral density J, by computing the integrals: gamma_i",
"Must invert the view, because for log-discretization the positive domain grid points are",
"bath for the generation of direct symmetric discretization coefficients, where the integrals for",
"# Coefficients for the positive part of the domain: try: a, b =",
"integrate.quad(lambda x: x * self.J(x), a, b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) self.gamma_buf[n] = np.sqrt(gamma_sq)",
"of domain :param domain: List/tuple of two elements for the left and right",
"except KeyError: self.limit = default_limit self.interval_type = interval_type self.x_pts_p, self.x_pts_m = get_symmetric_interval_points(domain, max_nof_coefficients,",
"are evaluated using scipy quad \"\"\" import numpy as np from scipy import",
"try: self.epsabs = kwargs['epsabs'] except KeyError: self.epsabs = default_epsabs try: self.epsrel = kwargs['epsrel']",
"integrals for the couplings and energies are evaluated using scipy quad \"\"\" import",
"J(x) dx) xi_i = int_i^i+1 J(x) * x dx/ gamma_i^2 :param J: Spectral",
"= np.sqrt(gamma_sq) if self.ignore_zeros and gamma_sq == 0: self.xi_buf[n] = 0 else: self.xi_buf[n]",
"the integrals: gamma_i = sqrt(int_i^i+1 J(x) dx) xi_i = int_i^i+1 J(x) * x",
"a spectral density J, by computing the integrals: gamma_i = sqrt(int_i^i+1 J(x) dx)",
"* x dx/ gamma_i^2 :param J: Spectral density. A function defined on 'domain',",
":param J: Spectral density. A function defined on 'domain', must be >0 in",
":param max_nof_coefficients: Size of the buffers which hold gamma and xi coefficients (maximum",
"self.next_n coefficients, since the indices are tailored for asymmetric discretizations) :param stop_n: Index",
"coefficients, since the indices are tailored for asymmetric discretizations) :param stop_n: Index up",
"of the domain: try: a, b = self.x_pts_m[int_index + 1], self.x_pts_m[int_index] # Must",
"self.J(x), a, b, epsabs=self.epsabs, epsrel=self.epsrel, limit=self.limit) self.gamma_buf[n] = np.sqrt(gamma_sq) if self.ignore_zeros and gamma_sq",
"interval_type=interval_type, get_spacing=False, **kwargs) self.J = J super().__init__(self.compute_coefficients, max_nof_coefficients=max_nof_coefficients) def compute_coefficients(self, stop_n): \"\"\" Calculates",
"self.epsrel = default_epsrel try: self.limit = kwargs['limit'] except KeyError: self.limit = default_limit self.interval_type",
"StopCoefficients from mapping.star.discretized_bath.intervals import get_symmetric_interval_points class SpQuadDiscretizedSymmetricBath(BaseDiscretizedSymmetricBath): def __init__(self, J, domain, max_nof_coefficients=100, interval_type='lin',",
"max_nof_coefficients=100, interval_type='lin', **kwargs): \"\"\" Generates direct discretization coefficients from a spectral density J,",
"the couplings and energies are evaluated using scipy quad \"\"\" import numpy as",
"default_epsabs try: self.epsrel = kwargs['epsrel'] except KeyError: self.epsrel = default_epsrel try: self.limit =",
"domain: List/tuple of two elements for the left and right boundary of the",
"// 2 # Coefficients for the positive part of the domain: try: a,",
"try: self.limit = kwargs['limit'] except KeyError: self.limit = default_limit self.interval_type = interval_type self.x_pts_p,",
"tolerance for the scipy integrations, default is 1e-11 'epsrel': relative tolerance for the"
] |
[] |
[
"= IOU_CALCULATORS def build_iou_calculator(cfg, default_args=None): \"\"\"Builder of IoU calculator.\"\"\" return build_from_cfg(cfg, ROTATED_IOU_CALCULATORS, default_args)",
"Copyright (c) OpenMMLab. All rights reserved. from mmcv.utils import build_from_cfg from mmdet.core.bbox.iou_calculators.builder import",
"rights reserved. from mmcv.utils import build_from_cfg from mmdet.core.bbox.iou_calculators.builder import IOU_CALCULATORS ROTATED_IOU_CALCULATORS = IOU_CALCULATORS",
"IOU_CALCULATORS ROTATED_IOU_CALCULATORS = IOU_CALCULATORS def build_iou_calculator(cfg, default_args=None): \"\"\"Builder of IoU calculator.\"\"\" return build_from_cfg(cfg,",
"import build_from_cfg from mmdet.core.bbox.iou_calculators.builder import IOU_CALCULATORS ROTATED_IOU_CALCULATORS = IOU_CALCULATORS def build_iou_calculator(cfg, default_args=None): \"\"\"Builder",
"mmcv.utils import build_from_cfg from mmdet.core.bbox.iou_calculators.builder import IOU_CALCULATORS ROTATED_IOU_CALCULATORS = IOU_CALCULATORS def build_iou_calculator(cfg, default_args=None):",
"OpenMMLab. All rights reserved. from mmcv.utils import build_from_cfg from mmdet.core.bbox.iou_calculators.builder import IOU_CALCULATORS ROTATED_IOU_CALCULATORS",
"mmdet.core.bbox.iou_calculators.builder import IOU_CALCULATORS ROTATED_IOU_CALCULATORS = IOU_CALCULATORS def build_iou_calculator(cfg, default_args=None): \"\"\"Builder of IoU calculator.\"\"\"",
"import IOU_CALCULATORS ROTATED_IOU_CALCULATORS = IOU_CALCULATORS def build_iou_calculator(cfg, default_args=None): \"\"\"Builder of IoU calculator.\"\"\" return",
"(c) OpenMMLab. All rights reserved. from mmcv.utils import build_from_cfg from mmdet.core.bbox.iou_calculators.builder import IOU_CALCULATORS",
"# Copyright (c) OpenMMLab. All rights reserved. from mmcv.utils import build_from_cfg from mmdet.core.bbox.iou_calculators.builder",
"reserved. from mmcv.utils import build_from_cfg from mmdet.core.bbox.iou_calculators.builder import IOU_CALCULATORS ROTATED_IOU_CALCULATORS = IOU_CALCULATORS def",
"All rights reserved. from mmcv.utils import build_from_cfg from mmdet.core.bbox.iou_calculators.builder import IOU_CALCULATORS ROTATED_IOU_CALCULATORS =",
"build_from_cfg from mmdet.core.bbox.iou_calculators.builder import IOU_CALCULATORS ROTATED_IOU_CALCULATORS = IOU_CALCULATORS def build_iou_calculator(cfg, default_args=None): \"\"\"Builder of",
"ROTATED_IOU_CALCULATORS = IOU_CALCULATORS def build_iou_calculator(cfg, default_args=None): \"\"\"Builder of IoU calculator.\"\"\" return build_from_cfg(cfg, ROTATED_IOU_CALCULATORS,",
"from mmdet.core.bbox.iou_calculators.builder import IOU_CALCULATORS ROTATED_IOU_CALCULATORS = IOU_CALCULATORS def build_iou_calculator(cfg, default_args=None): \"\"\"Builder of IoU",
"from mmcv.utils import build_from_cfg from mmdet.core.bbox.iou_calculators.builder import IOU_CALCULATORS ROTATED_IOU_CALCULATORS = IOU_CALCULATORS def build_iou_calculator(cfg,"
] |
[
"__future__ import unicode_literals from django.http import Http404 from django.views.generic.detail import DetailView from .utils",
"self.model, self.request.GET.get('hash')) except DraftError: raise Http404('Snapshot does not exist') return self.__object return super(BaseDraftView,",
"self.__object return super(BaseDraftView, self).get_object(*args, **kwargs) def get_context_data(self, *args, **kwargs): context = super(BaseDraftView, self).get_context_data(*args,",
"import Http404 from django.views.generic.detail import DetailView from .utils import load_from_shapshot from .exceptions import",
"load_from_shapshot from .exceptions import DraftError class BaseDraftView(DetailView): \"\"\" View for loading data from",
"load_from_shapshot( self.model, self.request.GET.get('hash')) except DraftError: raise Http404('Snapshot does not exist') return self.__object return",
"Http404('Snapshot does not exist') return self.__object return super(BaseDraftView, self).get_object(*args, **kwargs) def get_context_data(self, *args,",
"except DraftError: raise Http404('Snapshot does not exist') return self.__object return super(BaseDraftView, self).get_object(*args, **kwargs)",
"get_template_names(self): names = super(BaseDraftView, self).get_template_names() preview = names[0].replace('.html', '_preview.html') names.insert(0, preview) return names",
"not exist') return self.__object return super(BaseDraftView, self).get_object(*args, **kwargs) def get_context_data(self, *args, **kwargs): context",
".utils import load_from_shapshot from .exceptions import DraftError class BaseDraftView(DetailView): \"\"\" View for loading",
"# coding: utf-8 from __future__ import unicode_literals from django.http import Http404 from django.views.generic.detail",
"self.request.GET.get('hash')) except DraftError: raise Http404('Snapshot does not exist') return self.__object return super(BaseDraftView, self).get_object(*args,",
"django.http import Http404 from django.views.generic.detail import DetailView from .utils import load_from_shapshot from .exceptions",
"data from model `snapshot` \"\"\" def get_template_names(self): names = super(BaseDraftView, self).get_template_names() preview =",
"'_preview.html') names.insert(0, preview) return names def get_object(self, *args, **kwargs): if getattr(self, '__object', None):",
"*args, **kwargs): if getattr(self, '__object', None): return self.__object if 'hash' in self.request.GET: try:",
"import DetailView from .utils import load_from_shapshot from .exceptions import DraftError class BaseDraftView(DetailView): \"\"\"",
"self.__object if 'hash' in self.request.GET: try: self.__object = load_from_shapshot( self.model, self.request.GET.get('hash')) except DraftError:",
"names.insert(0, preview) return names def get_object(self, *args, **kwargs): if getattr(self, '__object', None): return",
"from django.views.generic.detail import DetailView from .utils import load_from_shapshot from .exceptions import DraftError class",
"self.__object = load_from_shapshot( self.model, self.request.GET.get('hash')) except DraftError: raise Http404('Snapshot does not exist') return",
"class BaseDraftView(DetailView): \"\"\" View for loading data from model `snapshot` \"\"\" def get_template_names(self):",
"does not exist') return self.__object return super(BaseDraftView, self).get_object(*args, **kwargs) def get_context_data(self, *args, **kwargs):",
"import unicode_literals from django.http import Http404 from django.views.generic.detail import DetailView from .utils import",
"get_object(self, *args, **kwargs): if getattr(self, '__object', None): return self.__object if 'hash' in self.request.GET:",
"preview) return names def get_object(self, *args, **kwargs): if getattr(self, '__object', None): return self.__object",
"self.request.GET: try: self.__object = load_from_shapshot( self.model, self.request.GET.get('hash')) except DraftError: raise Http404('Snapshot does not",
"try: self.__object = load_from_shapshot( self.model, self.request.GET.get('hash')) except DraftError: raise Http404('Snapshot does not exist')",
"unicode_literals from django.http import Http404 from django.views.generic.detail import DetailView from .utils import load_from_shapshot",
"from .exceptions import DraftError class BaseDraftView(DetailView): \"\"\" View for loading data from model",
"utf-8 from __future__ import unicode_literals from django.http import Http404 from django.views.generic.detail import DetailView",
"names = super(BaseDraftView, self).get_template_names() preview = names[0].replace('.html', '_preview.html') names.insert(0, preview) return names def",
"self).get_object(*args, **kwargs) def get_context_data(self, *args, **kwargs): context = super(BaseDraftView, self).get_context_data(*args, **kwargs) context['is_draft_preview'] =",
"= names[0].replace('.html', '_preview.html') names.insert(0, preview) return names def get_object(self, *args, **kwargs): if getattr(self,",
"coding: utf-8 from __future__ import unicode_literals from django.http import Http404 from django.views.generic.detail import",
"from model `snapshot` \"\"\" def get_template_names(self): names = super(BaseDraftView, self).get_template_names() preview = names[0].replace('.html',",
"preview = names[0].replace('.html', '_preview.html') names.insert(0, preview) return names def get_object(self, *args, **kwargs): if",
"for loading data from model `snapshot` \"\"\" def get_template_names(self): names = super(BaseDraftView, self).get_template_names()",
"exist') return self.__object return super(BaseDraftView, self).get_object(*args, **kwargs) def get_context_data(self, *args, **kwargs): context =",
"model `snapshot` \"\"\" def get_template_names(self): names = super(BaseDraftView, self).get_template_names() preview = names[0].replace('.html', '_preview.html')",
"**kwargs): if getattr(self, '__object', None): return self.__object if 'hash' in self.request.GET: try: self.__object",
"loading data from model `snapshot` \"\"\" def get_template_names(self): names = super(BaseDraftView, self).get_template_names() preview",
"= load_from_shapshot( self.model, self.request.GET.get('hash')) except DraftError: raise Http404('Snapshot does not exist') return self.__object",
"in self.request.GET: try: self.__object = load_from_shapshot( self.model, self.request.GET.get('hash')) except DraftError: raise Http404('Snapshot does",
"super(BaseDraftView, self).get_template_names() preview = names[0].replace('.html', '_preview.html') names.insert(0, preview) return names def get_object(self, *args,",
"DetailView from .utils import load_from_shapshot from .exceptions import DraftError class BaseDraftView(DetailView): \"\"\" View",
"'__object', None): return self.__object if 'hash' in self.request.GET: try: self.__object = load_from_shapshot( self.model,",
"names[0].replace('.html', '_preview.html') names.insert(0, preview) return names def get_object(self, *args, **kwargs): if getattr(self, '__object',",
"BaseDraftView(DetailView): \"\"\" View for loading data from model `snapshot` \"\"\" def get_template_names(self): names",
"from django.http import Http404 from django.views.generic.detail import DetailView from .utils import load_from_shapshot from",
"def get_object(self, *args, **kwargs): if getattr(self, '__object', None): return self.__object if 'hash' in",
"View for loading data from model `snapshot` \"\"\" def get_template_names(self): names = super(BaseDraftView,",
"return self.__object if 'hash' in self.request.GET: try: self.__object = load_from_shapshot( self.model, self.request.GET.get('hash')) except",
"get_context_data(self, *args, **kwargs): context = super(BaseDraftView, self).get_context_data(*args, **kwargs) context['is_draft_preview'] = True return context",
"\"\"\" View for loading data from model `snapshot` \"\"\" def get_template_names(self): names =",
"return super(BaseDraftView, self).get_object(*args, **kwargs) def get_context_data(self, *args, **kwargs): context = super(BaseDraftView, self).get_context_data(*args, **kwargs)",
"= super(BaseDraftView, self).get_template_names() preview = names[0].replace('.html', '_preview.html') names.insert(0, preview) return names def get_object(self,",
"None): return self.__object if 'hash' in self.request.GET: try: self.__object = load_from_shapshot( self.model, self.request.GET.get('hash'))",
"**kwargs) def get_context_data(self, *args, **kwargs): context = super(BaseDraftView, self).get_context_data(*args, **kwargs) context['is_draft_preview'] = True",
"self).get_template_names() preview = names[0].replace('.html', '_preview.html') names.insert(0, preview) return names def get_object(self, *args, **kwargs):",
".exceptions import DraftError class BaseDraftView(DetailView): \"\"\" View for loading data from model `snapshot`",
"DraftError: raise Http404('Snapshot does not exist') return self.__object return super(BaseDraftView, self).get_object(*args, **kwargs) def",
"from .utils import load_from_shapshot from .exceptions import DraftError class BaseDraftView(DetailView): \"\"\" View for",
"names def get_object(self, *args, **kwargs): if getattr(self, '__object', None): return self.__object if 'hash'",
"if getattr(self, '__object', None): return self.__object if 'hash' in self.request.GET: try: self.__object =",
"def get_template_names(self): names = super(BaseDraftView, self).get_template_names() preview = names[0].replace('.html', '_preview.html') names.insert(0, preview) return",
"return names def get_object(self, *args, **kwargs): if getattr(self, '__object', None): return self.__object if",
"import DraftError class BaseDraftView(DetailView): \"\"\" View for loading data from model `snapshot` \"\"\"",
"def get_context_data(self, *args, **kwargs): context = super(BaseDraftView, self).get_context_data(*args, **kwargs) context['is_draft_preview'] = True return",
"\"\"\" def get_template_names(self): names = super(BaseDraftView, self).get_template_names() preview = names[0].replace('.html', '_preview.html') names.insert(0, preview)",
"raise Http404('Snapshot does not exist') return self.__object return super(BaseDraftView, self).get_object(*args, **kwargs) def get_context_data(self,",
"<gh_stars>1-10 # coding: utf-8 from __future__ import unicode_literals from django.http import Http404 from",
"if 'hash' in self.request.GET: try: self.__object = load_from_shapshot( self.model, self.request.GET.get('hash')) except DraftError: raise",
"Http404 from django.views.generic.detail import DetailView from .utils import load_from_shapshot from .exceptions import DraftError",
"`snapshot` \"\"\" def get_template_names(self): names = super(BaseDraftView, self).get_template_names() preview = names[0].replace('.html', '_preview.html') names.insert(0,",
"import load_from_shapshot from .exceptions import DraftError class BaseDraftView(DetailView): \"\"\" View for loading data",
"'hash' in self.request.GET: try: self.__object = load_from_shapshot( self.model, self.request.GET.get('hash')) except DraftError: raise Http404('Snapshot",
"return self.__object return super(BaseDraftView, self).get_object(*args, **kwargs) def get_context_data(self, *args, **kwargs): context = super(BaseDraftView,",
"super(BaseDraftView, self).get_object(*args, **kwargs) def get_context_data(self, *args, **kwargs): context = super(BaseDraftView, self).get_context_data(*args, **kwargs) context['is_draft_preview']",
"DraftError class BaseDraftView(DetailView): \"\"\" View for loading data from model `snapshot` \"\"\" def",
"from __future__ import unicode_literals from django.http import Http404 from django.views.generic.detail import DetailView from",
"django.views.generic.detail import DetailView from .utils import load_from_shapshot from .exceptions import DraftError class BaseDraftView(DetailView):",
"getattr(self, '__object', None): return self.__object if 'hash' in self.request.GET: try: self.__object = load_from_shapshot("
] |
[
"return anything, modify node in-place instead. \"\"\" while node.next is not None: node.val",
"in-place instead. \"\"\" while node.next is not None: node.val = node.next.val pre =",
"= node node = node.next pre.next = None node1 = ListNode(1) node2 =",
"node1.next = node2 node2.next = node3 solution = Solution() solution.deleteNode(node2) while node1 is",
":rtype: void Do not return anything, modify node in-place instead. \"\"\" while node.next",
"__init__(self, x): self.val = x self.next = None class Solution: def deleteNode(self, node):",
"= x self.next = None class Solution: def deleteNode(self, node): \"\"\" :type node:",
"None class Solution: def deleteNode(self, node): \"\"\" :type node: ListNode :rtype: void Do",
"node3 solution = Solution() solution.deleteNode(node2) while node1 is not None: print(node1.val) node1 =",
"Do not return anything, modify node in-place instead. \"\"\" while node.next is not",
"x self.next = None class Solution: def deleteNode(self, node): \"\"\" :type node: ListNode",
"ListNode(1) node2 = ListNode(2) node3 = ListNode(3) node1.next = node2 node2.next = node3",
"instead. \"\"\" while node.next is not None: node.val = node.next.val pre = node",
"modify node in-place instead. \"\"\" while node.next is not None: node.val = node.next.val",
"ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def",
"= None node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(3) node1.next =",
"= node3 solution = Solution() solution.deleteNode(node2) while node1 is not None: print(node1.val) node1",
"for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next =",
":type node: ListNode :rtype: void Do not return anything, modify node in-place instead.",
"pre = node node = node.next pre.next = None node1 = ListNode(1) node2",
"node = node.next pre.next = None node1 = ListNode(1) node2 = ListNode(2) node3",
"node.next pre.next = None node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(3)",
"= None class Solution: def deleteNode(self, node): \"\"\" :type node: ListNode :rtype: void",
"x): self.val = x self.next = None class Solution: def deleteNode(self, node): \"\"\"",
"Solution: def deleteNode(self, node): \"\"\" :type node: ListNode :rtype: void Do not return",
"= ListNode(2) node3 = ListNode(3) node1.next = node2 node2.next = node3 solution =",
"def __init__(self, x): self.val = x self.next = None class Solution: def deleteNode(self,",
"node): \"\"\" :type node: ListNode :rtype: void Do not return anything, modify node",
"node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(3) node1.next = node2 node2.next",
"not return anything, modify node in-place instead. \"\"\" while node.next is not None:",
"class ListNode: def __init__(self, x): self.val = x self.next = None class Solution:",
"def deleteNode(self, node): \"\"\" :type node: ListNode :rtype: void Do not return anything,",
"singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None",
"Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next",
"node2 node2.next = node3 solution = Solution() solution.deleteNode(node2) while node1 is not None:",
"= node.next pre.next = None node1 = ListNode(1) node2 = ListNode(2) node3 =",
"<reponame>Bit64L/LeetCode-Python-<filename>DeleteNodeinaLinkedList.py<gh_stars>0 # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val =",
"= ListNode(3) node1.next = node2 node2.next = node3 solution = Solution() solution.deleteNode(node2) while",
"node.next is not None: node.val = node.next.val pre = node node = node.next",
"= ListNode(1) node2 = ListNode(2) node3 = ListNode(3) node1.next = node2 node2.next =",
"ListNode :rtype: void Do not return anything, modify node in-place instead. \"\"\" while",
"ListNode(2) node3 = ListNode(3) node1.next = node2 node2.next = node3 solution = Solution()",
"node2 = ListNode(2) node3 = ListNode(3) node1.next = node2 node2.next = node3 solution",
"deleteNode(self, node): \"\"\" :type node: ListNode :rtype: void Do not return anything, modify",
"\"\"\" while node.next is not None: node.val = node.next.val pre = node node",
"list. class ListNode: def __init__(self, x): self.val = x self.next = None class",
"node.val = node.next.val pre = node node = node.next pre.next = None node1",
"anything, modify node in-place instead. \"\"\" while node.next is not None: node.val =",
"node node = node.next pre.next = None node1 = ListNode(1) node2 = ListNode(2)",
"node in-place instead. \"\"\" while node.next is not None: node.val = node.next.val pre",
"self.next = None class Solution: def deleteNode(self, node): \"\"\" :type node: ListNode :rtype:",
"node.next.val pre = node node = node.next pre.next = None node1 = ListNode(1)",
"None node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(3) node1.next = node2",
"node3 = ListNode(3) node1.next = node2 node2.next = node3 solution = Solution() solution.deleteNode(node2)",
"self.val = x self.next = None class Solution: def deleteNode(self, node): \"\"\" :type",
"void Do not return anything, modify node in-place instead. \"\"\" while node.next is",
"class Solution: def deleteNode(self, node): \"\"\" :type node: ListNode :rtype: void Do not",
"# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x",
"while node.next is not None: node.val = node.next.val pre = node node =",
"None: node.val = node.next.val pre = node node = node.next pre.next = None",
"ListNode(3) node1.next = node2 node2.next = node3 solution = Solution() solution.deleteNode(node2) while node1",
"= node2 node2.next = node3 solution = Solution() solution.deleteNode(node2) while node1 is not",
"node2.next = node3 solution = Solution() solution.deleteNode(node2) while node1 is not None: print(node1.val)",
"solution = Solution() solution.deleteNode(node2) while node1 is not None: print(node1.val) node1 = node1.next",
"= node.next.val pre = node node = node.next pre.next = None node1 =",
"node: ListNode :rtype: void Do not return anything, modify node in-place instead. \"\"\"",
"pre.next = None node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(3) node1.next",
"\"\"\" :type node: ListNode :rtype: void Do not return anything, modify node in-place",
"not None: node.val = node.next.val pre = node node = node.next pre.next =",
"is not None: node.val = node.next.val pre = node node = node.next pre.next"
] |
[
"Url2Netloc class TestUrl2Netloc(unittest.TestCase): \"\"\" Tests our internal URL converter. \"\"\" def setUp(self) ->",
"the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in",
"= \"://example.org/\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual)",
"given = \"https://example.org/?is_admin=true\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected,",
"https://github.com/funilrys/PyFunceble Project documentation: https://pyfunceble.readthedocs.io/en/dev/ Project homepage: https://pyfunceble.github.io/ License: :: Copyright 2017, 2018, 2019,",
"explicit port) is given. \"\"\" given = \"https://example.org:8080/hello/world/this/is/a/test\" expected = \"example.org:8080\" self.converter.data_to_convert =",
"from a given URL for the case that a full URL (with params)",
"given URL for the case that the given url starts with 1 slash.",
"self.assertEqual(expected, actual) def test_get_converted_url_startswith_2_slashes(self) -> None: \"\"\" Tests the method which let us",
"self.converter = Url2Netloc() def tearDown(self) -> None: \"\"\" Destroys everything previously created for",
"a given URL for the case that a full URL (with explicit port)",
"╚══════╝╚══════╝ Tests of URL 2 Network Location converter. Author: <NAME>, @funilrys, contactTATAfunilrysTODTODcom Special",
"given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_full_url_with_params(self) -> None: \"\"\" Tests the",
"\"://example.org/?is_admin=true\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def",
"License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required",
"= given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_full_url_with_params(self) -> None: \"\"\" Tests",
"def test_get_converted_full_url_with_params(self) -> None: \"\"\" Tests the method which let us extracts the",
"self.assertEqual(expected, actual) def test_get_converted_url_without_scheme(self) -> None: \"\"\" Tests the method which let us",
"given URL for the case that no scheme (but with params) is given.",
"extracts the netloc from a given URL for the case that no protocol",
"case that the given url starts with 1 slash. \"\"\" given = \"/example.org/hello/world/this/is/a/test\"",
"Author: <NAME>, @funilrys, contactTATAfunilrysTODTODcom Special thanks: https://pyfunceble.github.io/special-thanks.html Contributors: https://pyfunceble.github.io/contributors.html Project link: https://github.com/funilrys/PyFunceble Project",
"link: https://github.com/funilrys/PyFunceble Project documentation: https://pyfunceble.readthedocs.io/en/dev/ Project homepage: https://pyfunceble.github.io/ License: :: Copyright 2017, 2018,",
"a given URL for the case that no protocol is given. \"\"\" given",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the",
"or URL. :: ██████╗ ██╗ ██╗███████╗██╗ ██╗███╗ ██╗ ██████╗███████╗██████╗ ██╗ ███████╗ ██╔══██╗╚██╗ ██╔╝██╔════╝██║",
"case that a full URL (with explicit port) is given. \"\"\" given =",
"\"example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def",
"the availability or syntax of domain, IP or URL. :: ██████╗ ██╗ ██╗███████╗██╗",
"expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_startswith_2_slashes(self)",
"the tests. \"\"\" del self.converter def test_set_data_to_convert_no_string(self) -> None: \"\"\" Tests the method",
"the netloc from a given URL for the case that no protocol (but",
"██████╔╝██║ █████╗ ██╔═══╝ ╚██╔╝ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██╔══╝ ██╔══██╗██║ ██╔══╝ ██║ ██║ ██║",
"██╔══╝ ██╔══██╗██║ ██╔══╝ ██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗███████╗██████╔╝███████╗███████╗ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝",
"def test_get_converted_url_startswith_1_slash(self) -> None: \"\"\" Tests the method which let us extracts the",
"the method which let us set the data to work with for the",
"Project homepage: https://pyfunceble.github.io/ License: :: Copyright 2017, 2018, 2019, 2020, 2021 <NAME> Licensed",
"actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_scheme_and_with_params(self) -> None: \"\"\" Tests the method",
"\"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_protocol(self) -> None:",
"\"\"\" given = \"://example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted()",
"no protocol (but params) is given. \"\"\" given = \"://example.org/?is_admin=true\" expected = \"example.org\"",
"\"://example.org/\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def",
"Tests the method which let us extracts the netloc from a given URL",
"\"\"\" The tool to check the availability or syntax of domain, IP or",
"netloc from a given URL for the case that a full URL (with",
"to check the availability or syntax of domain, IP or URL. :: ██████╗",
"the License for the specific language governing permissions and limitations under the License.",
"\"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_startswith_1_slash(self) -> None:",
"\"\"\" Setups everything needed for the tests. \"\"\" self.converter = Url2Netloc() def tearDown(self)",
"License for the specific language governing permissions and limitations under the License. \"\"\"",
"Unless required by applicable law or agreed to in writing, software distributed under",
"that no protocol is given. \"\"\" given = \"://example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert",
"slashes. \"\"\" given = \"//example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert = given actual =",
"our internal URL converter. \"\"\" def setUp(self) -> None: \"\"\" Setups everything needed",
"given = \"example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected,",
"\"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_scheme_and_with_params(self) -> None:",
"\"https://example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def",
"is given. \"\"\" given = \"https://example.org/?is_admin=true\" expected = \"example.org\" self.converter.data_to_convert = given actual",
"protocol (but params) is given. \"\"\" given = \"://example.org/?is_admin=true\" expected = \"example.org\" self.converter.data_to_convert",
"that a full URL is given. \"\"\" given = \"https://example.org/hello/world/this/is/a/test\" expected = \"example.org\"",
"test_get_converted_url_without_scheme_and_with_params(self) -> None: \"\"\" Tests the method which let us extracts the netloc",
"data to work with for the case that a non-string value is given.",
"actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_protocol_and_path(self) -> None: \"\"\" Tests the method",
"class TestUrl2Netloc(unittest.TestCase): \"\"\" Tests our internal URL converter. \"\"\" def setUp(self) -> None:",
"\"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_protocol_and_path(self) -> None:",
"let us set the data to work with for the case that an",
"= \"https://example.org/?is_admin=true\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual)",
"the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS",
"\"\"\" del self.converter def test_set_data_to_convert_no_string(self) -> None: \"\"\" Tests the method which let",
"actual) def test_get_converted_url_without_scheme_and_with_params(self) -> None: \"\"\" Tests the method which let us extracts",
"URL for the case that the given url starts with 1 slash. \"\"\"",
"starts with 1 slash. \"\"\" given = \"/example.org/hello/world/this/is/a/test\" expected = \"\" self.converter.data_to_convert =",
"License, Version 2.0 (the \"License\"); you may not use this file except in",
"self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_protocol_and_path(self) -> None: \"\"\"",
"╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝╚══════╝╚═════╝ ╚══════╝╚══════╝ Tests of URL 2 Network Location converter.",
"starts with 2 slashes. \"\"\" given = \"//example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert =",
"\"\"\" def setUp(self) -> None: \"\"\" Setups everything needed for the tests. \"\"\"",
"params) is given. \"\"\" given = \"://example.org/?is_admin=true\" expected = \"example.org\" self.converter.data_to_convert = given",
"actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_protocol_and_with_params(self) -> None: \"\"\" Tests the method",
"expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_startswith_1_slash(self)",
"╚████║╚██████╗███████╗██████╔╝███████╗███████╗ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝╚══════╝╚═════╝ ╚══════╝╚══════╝ Tests of URL 2",
"self.assertEqual(expected, actual) def test_get_converted_full_url(self) -> None: \"\"\" Tests the method which let us",
"from a given URL for the case that no scheme (but with params)",
"\"\"\" given = [\"Hello\", \"World\"] self.assertRaises(TypeError, lambda: self.converter.set_data_to_convert(given)) def test_set_data_to_convert_empty_string(self) -> None: \"\"\"",
"given URL for the case that no protocol is given. \"\"\" given =",
"self.assertEqual(expected, actual) def test_get_converted_url_without_protocol_and_path(self) -> None: \"\"\" Tests the method which let us",
"self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_protocol_and_with_params(self) -> None: \"\"\"",
"\"\"\" Destroys everything previously created for the tests. \"\"\" del self.converter def test_set_data_to_convert_no_string(self)",
"██████╔╝ ╚████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ █████╗ ██████╔╝██║ █████╗ ██╔═══╝ ╚██╔╝ ██╔══╝ ██║",
"@funilrys, contactTATAfunilrysTODTODcom Special thanks: https://pyfunceble.github.io/special-thanks.html Contributors: https://pyfunceble.github.io/contributors.html Project link: https://github.com/funilrys/PyFunceble Project documentation: https://pyfunceble.readthedocs.io/en/dev/",
"data to work with for the case that an empty-string value is given.",
"self.assertEqual(expected, actual) def test_get_converted_url_without_scheme_and_with_params(self) -> None: \"\"\" Tests the method which let us",
"for the specific language governing permissions and limitations under the License. \"\"\" import",
"Project link: https://github.com/funilrys/PyFunceble Project documentation: https://pyfunceble.readthedocs.io/en/dev/ Project homepage: https://pyfunceble.github.io/ License: :: Copyright 2017,",
"██║██╔════╝██╔════╝██╔══██╗██║ ██╔════╝ ██████╔╝ ╚████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ █████╗ ██████╔╝██║ █████╗ ██╔═══╝ ╚██╔╝",
"given = \"\" self.assertRaises(ValueError, lambda: self.converter.set_data_to_convert(given)) def test_get_converted_nothing_to_decode(self) -> None: \"\"\" Tests the",
"tests. \"\"\" self.converter = Url2Netloc() def tearDown(self) -> None: \"\"\" Destroys everything previously",
"self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_startswith_1_slash(self) -> None: \"\"\"",
"╚═══╝ ╚═════╝╚══════╝╚═════╝ ╚══════╝╚══════╝ Tests of URL 2 Network Location converter. Author: <NAME>, @funilrys,",
"permissions and limitations under the License. \"\"\" import unittest import unittest.mock from PyFunceble.converter.url2netloc",
"actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_protocol(self) -> None: \"\"\" Tests the method",
"protocol is given. \"\"\" given = \"://example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert = given",
"██║ ╚██████╔╝██║ ╚████║╚██████╗███████╗██████╔╝███████╗███████╗ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝╚══════╝╚═════╝ ╚══════╝╚══════╝ Tests of",
"= given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_protocol(self) -> None: \"\"\" Tests",
"software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT",
"by applicable law or agreed to in writing, software distributed under the License",
"def tearDown(self) -> None: \"\"\" Destroys everything previously created for the tests. \"\"\"",
"for the case that no conversion is needed. \"\"\" given = \"example.org\" expected",
"from a given URL for the case that no scheme is given. \"\"\"",
"to work with for the case that a non-string value is given. \"\"\"",
"actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_full_url_with_port(self) -> None: \"\"\" Tests the method",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License",
"the netloc from a given URL for the case that a full URL",
"= self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_scheme_and_with_params(self) -> None: \"\"\" Tests the method which",
"= given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_full_url_with_port(self) -> None: \"\"\" Tests",
"case that no scheme (but with params) is given. \"\"\" given = \"example.org/?is_admin=true\"",
"that no protocol (but params) is given. \"\"\" given = \"://example.org/?is_admin=true\" expected =",
"██║██║ █████╗ ██████╔╝██║ █████╗ ██╔═══╝ ╚██╔╝ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██╔══╝ ██╔══██╗██║ ██╔══╝ ██║",
"no scheme is given. \"\"\" given = \"example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert =",
"= \"\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) if __name__ ==",
"netloc from a given URL for the case that no scheme (but with",
"= \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_protocol_and_path(self) ->",
"given = [\"Hello\", \"World\"] self.assertRaises(TypeError, lambda: self.converter.set_data_to_convert(given)) def test_set_data_to_convert_empty_string(self) -> None: \"\"\" Tests",
"IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"given. \"\"\" given = \"https://example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert = given actual =",
"a given URL for the case that no conversion is needed. \"\"\" given",
"= self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_full_url(self) -> None: \"\"\" Tests the method which",
"\"\"\" given = \"://example.org/?is_admin=true\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted()",
"in compliance with the License. You may obtain a copy of the License",
"specific language governing permissions and limitations under the License. \"\"\" import unittest import",
"██╔══╝ ██║ ██║██║╚██╗██║██║ ██╔══╝ ██╔══██╗██║ ██╔══╝ ██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗███████╗██████╔╝███████╗███████╗ ╚═╝ ╚═╝",
"KIND, either express or implied. See the License for the specific language governing",
"Network Location converter. Author: <NAME>, @funilrys, contactTATAfunilrysTODTODcom Special thanks: https://pyfunceble.github.io/special-thanks.html Contributors: https://pyfunceble.github.io/contributors.html Project",
"is given. \"\"\" given = \"://example.org/\" expected = \"example.org\" self.converter.data_to_convert = given actual",
"█████╗ ██╔═══╝ ╚██╔╝ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██╔══╝ ██╔══██╗██║ ██╔══╝ ██║ ██║ ██║ ╚██████╔╝██║",
"URL converter. \"\"\" def setUp(self) -> None: \"\"\" Setups everything needed for the",
"-> None: \"\"\" Setups everything needed for the tests. \"\"\" self.converter = Url2Netloc()",
"= \"/example.org/hello/world/this/is/a/test\" expected = \"\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual)",
"self.assertRaises(ValueError, lambda: self.converter.set_data_to_convert(given)) def test_get_converted_nothing_to_decode(self) -> None: \"\"\" Tests the method which let",
"actual) def test_get_converted_url_startswith_1_slash(self) -> None: \"\"\" Tests the method which let us extracts",
"URL (with explicit port) is given. \"\"\" given = \"https://example.org:8080/hello/world/this/is/a/test\" expected = \"example.org:8080\"",
"in writing, software distributed under the License is distributed on an \"AS IS\"",
"URL for the case that no scheme is given. \"\"\" given = \"example.org/hello/world/this/is/a/test\"",
"def test_get_converted_url_without_protocol(self) -> None: \"\"\" Tests the method which let us extracts the",
"self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_protocol_and_path(self) -> None: \"\"\" Tests the method which let",
"writing, software distributed under the License is distributed on an \"AS IS\" BASIS,",
"path is given. \"\"\" given = \"://example.org/\" expected = \"example.org\" self.converter.data_to_convert = given",
"self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_startswith_2_slashes(self) -> None: \"\"\" Tests the method which let",
"case that the given url starts with 2 slashes. \"\"\" given = \"//example.org/hello/world/this/is/a/test\"",
"or agreed to in writing, software distributed under the License is distributed on",
"is given. \"\"\" given = [\"Hello\", \"World\"] self.assertRaises(TypeError, lambda: self.converter.set_data_to_convert(given)) def test_set_data_to_convert_empty_string(self) ->",
"\"\" self.assertRaises(ValueError, lambda: self.converter.set_data_to_convert(given)) def test_get_converted_nothing_to_decode(self) -> None: \"\"\" Tests the method which",
"given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_scheme(self) -> None: \"\"\" Tests the",
"test_set_data_to_convert_no_string(self) -> None: \"\"\" Tests the method which let us set the data",
"URL for the case that a full URL (with params) is given. \"\"\"",
"for the case that the given url starts with 2 slashes. \"\"\" given",
"is given. \"\"\" given = \"://example.org/?is_admin=true\" expected = \"example.org\" self.converter.data_to_convert = given actual",
"= given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_scheme(self) -> None: \"\"\" Tests",
"(but with params) is given. \"\"\" given = \"example.org/?is_admin=true\" expected = \"example.org\" self.converter.data_to_convert",
"= \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_startswith_2_slashes(self) ->",
"self.assertRaises(TypeError, lambda: self.converter.set_data_to_convert(given)) def test_set_data_to_convert_empty_string(self) -> None: \"\"\" Tests the method which let",
"and limitations under the License. \"\"\" import unittest import unittest.mock from PyFunceble.converter.url2netloc import",
"converter. Author: <NAME>, @funilrys, contactTATAfunilrysTODTODcom Special thanks: https://pyfunceble.github.io/special-thanks.html Contributors: https://pyfunceble.github.io/contributors.html Project link: https://github.com/funilrys/PyFunceble",
"case that an empty-string value is given. \"\"\" given = \"\" self.assertRaises(ValueError, lambda:",
"the case that a full URL (with params) is given. \"\"\" given =",
"None: \"\"\" Setups everything needed for the tests. \"\"\" self.converter = Url2Netloc() def",
"[\"Hello\", \"World\"] self.assertRaises(TypeError, lambda: self.converter.set_data_to_convert(given)) def test_set_data_to_convert_empty_string(self) -> None: \"\"\" Tests the method",
"given = \"https://example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected,",
"given url starts with 2 slashes. \"\"\" given = \"//example.org/hello/world/this/is/a/test\" expected = \"example.org\"",
"2021 <NAME> Licensed under the Apache License, Version 2.0 (the \"License\"); you may",
"extracts the netloc from a given URL for the case that no scheme",
"slash. \"\"\" given = \"/example.org/hello/world/this/is/a/test\" expected = \"\" self.converter.data_to_convert = given actual =",
"= \"example.org\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual)",
"given. \"\"\" given = \"example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert = given actual =",
"test_get_converted_full_url_with_params(self) -> None: \"\"\" Tests the method which let us extracts the netloc",
"given = \"https://example.org:8080/hello/world/this/is/a/test\" expected = \"example.org:8080\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected,",
"OR CONDITIONS OF ANY KIND, either express or implied. See the License for",
"no conversion is needed. \"\"\" given = \"example.org\" expected = \"example.org\" self.converter.data_to_convert =",
"= \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_full_url_with_port(self) ->",
"OF ANY KIND, either express or implied. See the License for the specific",
"█████╗ ██║ ██║██╔██╗ ██║██║ █████╗ ██████╔╝██║ █████╗ ██╔═══╝ ╚██╔╝ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██╔══╝",
"██║ ██║██╔██╗ ██║██║ █████╗ ██████╔╝██║ █████╗ ██╔═══╝ ╚██╔╝ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██╔══╝ ██╔══██╗██║",
"self.converter.set_data_to_convert(given)) def test_set_data_to_convert_empty_string(self) -> None: \"\"\" Tests the method which let us set",
"is given. \"\"\" given = \"example.org/?is_admin=true\" expected = \"example.org\" self.converter.data_to_convert = given actual",
"actual) def test_get_converted_url_without_protocol_and_with_params(self) -> None: \"\"\" Tests the method which let us extracts",
"and path is given. \"\"\" given = \"://example.org/\" expected = \"example.org\" self.converter.data_to_convert =",
"from a given URL for the case that a full URL is given.",
"-> None: \"\"\" Tests the method which let us extracts the netloc from",
"may not use this file except in compliance with the License. You may",
"the case that the given url starts with 2 slashes. \"\"\" given =",
"URL for the case that no protocol and path is given. \"\"\" given",
"URL for the case that no conversion is needed. \"\"\" given = \"example.org\"",
"URL 2 Network Location converter. Author: <NAME>, @funilrys, contactTATAfunilrysTODTODcom Special thanks: https://pyfunceble.github.io/special-thanks.html Contributors:",
"under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR",
"TestUrl2Netloc(unittest.TestCase): \"\"\" Tests our internal URL converter. \"\"\" def setUp(self) -> None: \"\"\"",
"= given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_startswith_2_slashes(self) -> None: \"\"\" Tests",
"setUp(self) -> None: \"\"\" Setups everything needed for the tests. \"\"\" self.converter =",
"on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"port) is given. \"\"\" given = \"https://example.org:8080/hello/world/this/is/a/test\" expected = \"example.org:8080\" self.converter.data_to_convert = given",
"███████╗ ██╔══██╗╚██╗ ██╔╝██╔════╝██║ ██║████╗ ██║██╔════╝██╔════╝██╔══██╗██║ ██╔════╝ ██████╔╝ ╚████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ █████╗",
"= \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_startswith_1_slash(self) ->",
"Url2Netloc() def tearDown(self) -> None: \"\"\" Destroys everything previously created for the tests.",
"= [\"Hello\", \"World\"] self.assertRaises(TypeError, lambda: self.converter.set_data_to_convert(given)) def test_set_data_to_convert_empty_string(self) -> None: \"\"\" Tests the",
"= \"example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual)",
"netloc from a given URL for the case that the given url starts",
"the case that the given url starts with 1 slash. \"\"\" given =",
"██╗ ███████╗ ██╔══██╗╚██╗ ██╔╝██╔════╝██║ ██║████╗ ██║██╔════╝██╔════╝██╔══██╗██║ ██╔════╝ ██████╔╝ ╚████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║",
"def test_get_converted_url_without_protocol_and_with_params(self) -> None: \"\"\" Tests the method which let us extracts the",
"License. \"\"\" import unittest import unittest.mock from PyFunceble.converter.url2netloc import Url2Netloc class TestUrl2Netloc(unittest.TestCase): \"\"\"",
"\"\"\" given = \"//example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted()",
"the case that a non-string value is given. \"\"\" given = [\"Hello\", \"World\"]",
"case that a full URL (with params) is given. \"\"\" given = \"https://example.org/?is_admin=true\"",
"lambda: self.converter.set_data_to_convert(given)) def test_get_converted_nothing_to_decode(self) -> None: \"\"\" Tests the method which let us",
"given. \"\"\" given = [\"Hello\", \"World\"] self.assertRaises(TypeError, lambda: self.converter.set_data_to_convert(given)) def test_set_data_to_convert_empty_string(self) -> None:",
"full URL (with explicit port) is given. \"\"\" given = \"https://example.org:8080/hello/world/this/is/a/test\" expected =",
"(with params) is given. \"\"\" given = \"https://example.org/?is_admin=true\" expected = \"example.org\" self.converter.data_to_convert =",
"which let us extracts the netloc from a given URL for the case",
"thanks: https://pyfunceble.github.io/special-thanks.html Contributors: https://pyfunceble.github.io/contributors.html Project link: https://github.com/funilrys/PyFunceble Project documentation: https://pyfunceble.readthedocs.io/en/dev/ Project homepage: https://pyfunceble.github.io/",
"given URL for the case that no scheme is given. \"\"\" given =",
"\"\"\" self.converter = Url2Netloc() def tearDown(self) -> None: \"\"\" Destroys everything previously created",
"given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_protocol_and_path(self) -> None: \"\"\" Tests the",
"given = \"://example.org/\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected,",
"\"\"\" given = \"example.org/?is_admin=true\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted()",
"See the License for the specific language governing permissions and limitations under the",
"License: :: Copyright 2017, 2018, 2019, 2020, 2021 <NAME> Licensed under the Apache",
"the License. \"\"\" import unittest import unittest.mock from PyFunceble.converter.url2netloc import Url2Netloc class TestUrl2Netloc(unittest.TestCase):",
"██████╗███████╗██████╗ ██╗ ███████╗ ██╔══██╗╚██╗ ██╔╝██╔════╝██║ ██║████╗ ██║██╔════╝██╔════╝██╔══██╗██║ ██╔════╝ ██████╔╝ ╚████╔╝ █████╗ ██║ ██║██╔██╗",
"that no conversion is needed. \"\"\" given = \"example.org\" expected = \"example.org\" self.converter.data_to_convert",
"with for the case that an empty-string value is given. \"\"\" given =",
"to work with for the case that an empty-string value is given. \"\"\"",
"\"/example.org/hello/world/this/is/a/test\" expected = \"\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) if",
"test_get_converted_url_startswith_2_slashes(self) -> None: \"\"\" Tests the method which let us extracts the netloc",
"URL. :: ██████╗ ██╗ ██╗███████╗██╗ ██╗███╗ ██╗ ██████╗███████╗██████╗ ██╗ ███████╗ ██╔══██╗╚██╗ ██╔╝██╔════╝██║ ██║████╗",
"given = \"example.org/?is_admin=true\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected,",
"the given url starts with 1 slash. \"\"\" given = \"/example.org/hello/world/this/is/a/test\" expected =",
"given URL for the case that no conversion is needed. \"\"\" given =",
"extracts the netloc from a given URL for the case that a full",
"given. \"\"\" given = \"example.org/?is_admin=true\" expected = \"example.org\" self.converter.data_to_convert = given actual =",
"extracts the netloc from a given URL for the case that no conversion",
"self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_full_url_with_params(self) -> None: \"\"\"",
"PyFunceble.converter.url2netloc import Url2Netloc class TestUrl2Netloc(unittest.TestCase): \"\"\" Tests our internal URL converter. \"\"\" def",
"needed. \"\"\" given = \"example.org\" expected = \"example.org\" self.converter.data_to_convert = given actual =",
"self.assertEqual(expected, actual) def test_get_converted_url_without_protocol_and_with_params(self) -> None: \"\"\" Tests the method which let us",
"netloc from a given URL for the case that no protocol and path",
"this file except in compliance with the License. You may obtain a copy",
"╚═╝ ╚═══╝ ╚═════╝╚══════╝╚═════╝ ╚══════╝╚══════╝ Tests of URL 2 Network Location converter. Author: <NAME>,",
"██████╗ ██╗ ██╗███████╗██╗ ██╗███╗ ██╗ ██████╗███████╗██████╗ ██╗ ███████╗ ██╔══██╗╚██╗ ██╔╝██╔════╝██║ ██║████╗ ██║██╔════╝██╔════╝██╔══██╗██║ ██╔════╝",
"\"License\"); you may not use this file except in compliance with the License.",
"= \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_protocol(self) ->",
"is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"netloc from a given URL for the case that no conversion is needed.",
"the tests. \"\"\" self.converter = Url2Netloc() def tearDown(self) -> None: \"\"\" Destroys everything",
"self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_scheme(self) -> None: \"\"\" Tests the method which let",
"self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_startswith_2_slashes(self) -> None: \"\"\"",
"language governing permissions and limitations under the License. \"\"\" import unittest import unittest.mock",
"you may not use this file except in compliance with the License. You",
"the case that no scheme is given. \"\"\" given = \"example.org/hello/world/this/is/a/test\" expected =",
"https://pyfunceble.readthedocs.io/en/dev/ Project homepage: https://pyfunceble.github.io/ License: :: Copyright 2017, 2018, 2019, 2020, 2021 <NAME>",
"██╔═══╝ ╚██╔╝ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██╔══╝ ██╔══██╗██║ ██╔══╝ ██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗███████╗██████╔╝███████╗███████╗",
"agreed to in writing, software distributed under the License is distributed on an",
"= self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_full_url_with_port(self) -> None: \"\"\" Tests the method which",
"case that no conversion is needed. \"\"\" given = \"example.org\" expected = \"example.org\"",
"expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_protocol(self)",
"<NAME>, @funilrys, contactTATAfunilrysTODTODcom Special thanks: https://pyfunceble.github.io/special-thanks.html Contributors: https://pyfunceble.github.io/contributors.html Project link: https://github.com/funilrys/PyFunceble Project documentation:",
"distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES",
"\"//example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def",
"us extracts the netloc from a given URL for the case that no",
"expected = \"example.org:8080\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_full_url_with_params(self)",
"the netloc from a given URL for the case that no scheme (but",
"full URL is given. \"\"\" given = \"https://example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert =",
"that no scheme (but with params) is given. \"\"\" given = \"example.org/?is_admin=true\" expected",
"\"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_full_url_with_port(self) -> None:",
"may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable",
"scheme (but with params) is given. \"\"\" given = \"example.org/?is_admin=true\" expected = \"example.org\"",
"URL for the case that no protocol is given. \"\"\" given = \"://example.org/hello/world/this/is/a/test\"",
"protocol and path is given. \"\"\" given = \"://example.org/\" expected = \"example.org\" self.converter.data_to_convert",
"implied. See the License for the specific language governing permissions and limitations under",
"the case that an empty-string value is given. \"\"\" given = \"\" self.assertRaises(ValueError,",
"case that a full URL is given. \"\"\" given = \"https://example.org/hello/world/this/is/a/test\" expected =",
"2 slashes. \"\"\" given = \"//example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert = given actual",
"def setUp(self) -> None: \"\"\" Setups everything needed for the tests. \"\"\" self.converter",
":: Copyright 2017, 2018, 2019, 2020, 2021 <NAME> Licensed under the Apache License,",
"given URL for the case that a full URL is given. \"\"\" given",
"a given URL for the case that the given url starts with 1",
"actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_startswith_2_slashes(self) -> None: \"\"\" Tests the method",
"█████╗ ██████╔╝██║ █████╗ ██╔═══╝ ╚██╔╝ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██╔══╝ ██╔══██╗██║ ██╔══╝ ██║ ██║",
"the case that no protocol (but params) is given. \"\"\" given = \"://example.org/?is_admin=true\"",
"╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝╚══════╝╚═════╝ ╚══════╝╚══════╝ Tests of URL 2 Network Location",
"governing permissions and limitations under the License. \"\"\" import unittest import unittest.mock from",
"URL is given. \"\"\" given = \"https://example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert = given",
"= given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_protocol_and_path(self) -> None: \"\"\" Tests",
"internal URL converter. \"\"\" def setUp(self) -> None: \"\"\" Setups everything needed for",
"██╔══╝ ██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗███████╗██████╔╝███████╗███████╗ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝╚══════╝╚═════╝",
"the data to work with for the case that an empty-string value is",
"a non-string value is given. \"\"\" given = [\"Hello\", \"World\"] self.assertRaises(TypeError, lambda: self.converter.set_data_to_convert(given))",
"case that no protocol and path is given. \"\"\" given = \"://example.org/\" expected",
"= self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_protocol_and_with_params(self) -> None: \"\"\" Tests the method which",
"from a given URL for the case that a full URL (with explicit",
"None: \"\"\" Tests the method which let us set the data to work",
"╚═════╝╚══════╝╚═════╝ ╚══════╝╚══════╝ Tests of URL 2 Network Location converter. Author: <NAME>, @funilrys, contactTATAfunilrysTODTODcom",
"def test_set_data_to_convert_no_string(self) -> None: \"\"\" Tests the method which let us set the",
"use this file except in compliance with the License. You may obtain a",
"██╗ ██████╗███████╗██████╗ ██╗ ███████╗ ██╔══██╗╚██╗ ██╔╝██╔════╝██║ ██║████╗ ██║██╔════╝██╔════╝██╔══██╗██║ ██╔════╝ ██████╔╝ ╚████╔╝ █████╗ ██║",
"of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to",
"Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use",
"value is given. \"\"\" given = [\"Hello\", \"World\"] self.assertRaises(TypeError, lambda: self.converter.set_data_to_convert(given)) def test_set_data_to_convert_empty_string(self)",
"that a non-string value is given. \"\"\" given = [\"Hello\", \"World\"] self.assertRaises(TypeError, lambda:",
"self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_full_url_with_params(self) -> None: \"\"\" Tests the method which let",
"a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or",
":: ██████╗ ██╗ ██╗███████╗██╗ ██╗███╗ ██╗ ██████╗███████╗██████╗ ██╗ ███████╗ ██╔══██╗╚██╗ ██╔╝██╔════╝██║ ██║████╗ ██║██╔════╝██╔════╝██╔══██╗██║",
"url starts with 2 slashes. \"\"\" given = \"//example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert",
"╚████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ █████╗ ██████╔╝██║ █████╗ ██╔═══╝ ╚██╔╝ ██╔══╝ ██║ ██║██║╚██╗██║██║",
"case that a non-string value is given. \"\"\" given = [\"Hello\", \"World\"] self.assertRaises(TypeError,",
"the case that a full URL is given. \"\"\" given = \"https://example.org/hello/world/this/is/a/test\" expected",
"actual) def test_get_converted_url_without_protocol(self) -> None: \"\"\" Tests the method which let us extracts",
"expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_protocol_and_path(self)",
"given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_startswith_2_slashes(self) -> None: \"\"\" Tests the",
"\"\"\" given = \"/example.org/hello/world/this/is/a/test\" expected = \"\" self.converter.data_to_convert = given actual = self.converter.get_converted()",
"self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_full_url(self) -> None: \"\"\" Tests the method which let",
"given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_protocol(self) -> None: \"\"\" Tests the",
"method which let us set the data to work with for the case",
"= self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_protocol(self) -> None: \"\"\" Tests the method which",
"given URL for the case that the given url starts with 2 slashes.",
"\"\"\" Tests the method which let us extracts the netloc from a given",
"test_get_converted_url_without_scheme(self) -> None: \"\"\" Tests the method which let us extracts the netloc",
"check the availability or syntax of domain, IP or URL. :: ██████╗ ██╗",
"the case that no conversion is needed. \"\"\" given = \"example.org\" expected =",
"set the data to work with for the case that a non-string value",
"with for the case that a non-string value is given. \"\"\" given =",
"self.converter def test_set_data_to_convert_no_string(self) -> None: \"\"\" Tests the method which let us set",
"expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_scheme(self)",
"given. \"\"\" given = \"://example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert = given actual =",
"required by applicable law or agreed to in writing, software distributed under the",
"for the tests. \"\"\" del self.converter def test_set_data_to_convert_no_string(self) -> None: \"\"\" Tests the",
"self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_full_url(self) -> None: \"\"\"",
"for the case that a full URL is given. \"\"\" given = \"https://example.org/hello/world/this/is/a/test\"",
"-> None: \"\"\" Tests the method which let us set the data to",
"with params) is given. \"\"\" given = \"example.org/?is_admin=true\" expected = \"example.org\" self.converter.data_to_convert =",
"given. \"\"\" given = \"https://example.org/?is_admin=true\" expected = \"example.org\" self.converter.data_to_convert = given actual =",
"test_get_converted_nothing_to_decode(self) -> None: \"\"\" Tests the method which let us extracts the netloc",
"for the tests. \"\"\" self.converter = Url2Netloc() def tearDown(self) -> None: \"\"\" Destroys",
"for the case that a non-string value is given. \"\"\" given = [\"Hello\",",
"the netloc from a given URL for the case that the given url",
"test_get_converted_full_url(self) -> None: \"\"\" Tests the method which let us extracts the netloc",
"\"\"\" Tests our internal URL converter. \"\"\" def setUp(self) -> None: \"\"\" Setups",
"██║████╗ ██║██╔════╝██╔════╝██╔══██╗██║ ██╔════╝ ██████╔╝ ╚████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ █████╗ ██████╔╝██║ █████╗ ██╔═══╝",
"for the case that no protocol and path is given. \"\"\" given =",
"a given URL for the case that the given url starts with 2",
"= \"\" self.assertRaises(ValueError, lambda: self.converter.set_data_to_convert(given)) def test_get_converted_nothing_to_decode(self) -> None: \"\"\" Tests the method",
"from a given URL for the case that no protocol (but params) is",
"Destroys everything previously created for the tests. \"\"\" del self.converter def test_set_data_to_convert_no_string(self) ->",
"given url starts with 1 slash. \"\"\" given = \"/example.org/hello/world/this/is/a/test\" expected = \"\"",
"extracts the netloc from a given URL for the case that the given",
"\"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_scheme(self) -> None:",
"given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_protocol_and_with_params(self) -> None: \"\"\" Tests the",
"URL (with params) is given. \"\"\" given = \"https://example.org/?is_admin=true\" expected = \"example.org\" self.converter.data_to_convert",
"expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_scheme_and_with_params(self)",
"Contributors: https://pyfunceble.github.io/contributors.html Project link: https://github.com/funilrys/PyFunceble Project documentation: https://pyfunceble.readthedocs.io/en/dev/ Project homepage: https://pyfunceble.github.io/ License: ::",
"distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_scheme(self) -> None: \"\"\" Tests the method",
"██╔════╝ ██████╔╝ ╚████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ █████╗ ██████╔╝██║ █████╗ ██╔═══╝ ╚██╔╝ ██╔══╝",
"not use this file except in compliance with the License. You may obtain",
"Location converter. Author: <NAME>, @funilrys, contactTATAfunilrysTODTODcom Special thanks: https://pyfunceble.github.io/special-thanks.html Contributors: https://pyfunceble.github.io/contributors.html Project link:",
"scheme is given. \"\"\" given = \"example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert = given",
"case that no protocol is given. \"\"\" given = \"://example.org/hello/world/this/is/a/test\" expected = \"example.org\"",
"Tests the method which let us set the data to work with for",
"╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝╚══════╝╚═════╝ ╚══════╝╚══════╝ Tests of URL 2 Network",
"2018, 2019, 2020, 2021 <NAME> Licensed under the Apache License, Version 2.0 (the",
"╚═════╝ ╚═╝ ╚═══╝ ╚═════╝╚══════╝╚═════╝ ╚══════╝╚══════╝ Tests of URL 2 Network Location converter. Author:",
"def test_get_converted_url_without_scheme(self) -> None: \"\"\" Tests the method which let us extracts the",
"\"\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) if __name__ == \"__main__\":",
"\"\"\" given = \"example.org\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted()",
"= \"://example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual)",
"a given URL for the case that no scheme (but with params) is",
"url starts with 1 slash. \"\"\" given = \"/example.org/hello/world/this/is/a/test\" expected = \"\" self.converter.data_to_convert",
"syntax of domain, IP or URL. :: ██████╗ ██╗ ██╗███████╗██╗ ██╗███╗ ██╗ ██████╗███████╗██████╗",
"for the case that the given url starts with 1 slash. \"\"\" given",
"██║ ██║██║╚██╗██║██║ ██╔══╝ ██╔══██╗██║ ██╔══╝ ██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗███████╗██████╔╝███████╗███████╗ ╚═╝ ╚═╝ ╚═╝",
"given = \"//example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected,",
"given = \"://example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected,",
"for the case that no protocol is given. \"\"\" given = \"://example.org/hello/world/this/is/a/test\" expected",
"ANY KIND, either express or implied. See the License for the specific language",
"that a full URL (with params) is given. \"\"\" given = \"https://example.org/?is_admin=true\" expected",
"homepage: https://pyfunceble.github.io/ License: :: Copyright 2017, 2018, 2019, 2020, 2021 <NAME> Licensed under",
"of URL 2 Network Location converter. Author: <NAME>, @funilrys, contactTATAfunilrysTODTODcom Special thanks: https://pyfunceble.github.io/special-thanks.html",
"https://pyfunceble.github.io/ License: :: Copyright 2017, 2018, 2019, 2020, 2021 <NAME> Licensed under the",
"self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_protocol_and_with_params(self) -> None: \"\"\" Tests the method which let",
"URL for the case that no protocol (but params) is given. \"\"\" given",
"file except in compliance with the License. You may obtain a copy of",
"work with for the case that an empty-string value is given. \"\"\" given",
"given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_scheme_and_with_params(self) -> None: \"\"\" Tests the",
"the netloc from a given URL for the case that no conversion is",
"tearDown(self) -> None: \"\"\" Destroys everything previously created for the tests. \"\"\" del",
"\"\"\" given = \"\" self.assertRaises(ValueError, lambda: self.converter.set_data_to_convert(given)) def test_get_converted_nothing_to_decode(self) -> None: \"\"\" Tests",
"self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_protocol(self) -> None: \"\"\" Tests the method which let",
"Project documentation: https://pyfunceble.readthedocs.io/en/dev/ Project homepage: https://pyfunceble.github.io/ License: :: Copyright 2017, 2018, 2019, 2020,",
"that a full URL (with explicit port) is given. \"\"\" given = \"https://example.org:8080/hello/world/this/is/a/test\"",
"contactTATAfunilrysTODTODcom Special thanks: https://pyfunceble.github.io/special-thanks.html Contributors: https://pyfunceble.github.io/contributors.html Project link: https://github.com/funilrys/PyFunceble Project documentation: https://pyfunceble.readthedocs.io/en/dev/ Project",
"self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) if __name__ == \"__main__\": unittest.main()",
"actual) def test_get_converted_full_url(self) -> None: \"\"\" Tests the method which let us extracts",
"= \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_scheme(self) ->",
"= \"https://example.org:8080/hello/world/this/is/a/test\" expected = \"example.org:8080\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual)",
"██║██╔██╗ ██║██║ █████╗ ██████╔╝██║ █████╗ ██╔═══╝ ╚██╔╝ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██╔══╝ ██╔══██╗██║ ██╔══╝",
"2.0 (the \"License\"); you may not use this file except in compliance with",
"for the case that no scheme is given. \"\"\" given = \"example.org/hello/world/this/is/a/test\" expected",
"= \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_scheme_and_with_params(self) ->",
"the given url starts with 2 slashes. \"\"\" given = \"//example.org/hello/world/this/is/a/test\" expected =",
"a given URL for the case that no protocol (but params) is given.",
"actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_full_url_with_params(self) -> None: \"\"\" Tests the method",
"for the case that no protocol (but params) is given. \"\"\" given =",
"= given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_protocol_and_with_params(self) -> None: \"\"\" Tests",
"previously created for the tests. \"\"\" del self.converter def test_set_data_to_convert_no_string(self) -> None: \"\"\"",
"netloc from a given URL for the case that no protocol is given.",
"copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed",
"us set the data to work with for the case that a non-string",
"given. \"\"\" given = \"://example.org/\" expected = \"example.org\" self.converter.data_to_convert = given actual =",
"the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless",
"converter. \"\"\" def setUp(self) -> None: \"\"\" Setups everything needed for the tests.",
"= \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_full_url(self) ->",
"that the given url starts with 1 slash. \"\"\" given = \"/example.org/hello/world/this/is/a/test\" expected",
"that no protocol and path is given. \"\"\" given = \"://example.org/\" expected =",
"1 slash. \"\"\" given = \"/example.org/hello/world/this/is/a/test\" expected = \"\" self.converter.data_to_convert = given actual",
"(the \"License\"); you may not use this file except in compliance with the",
"self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_protocol(self) -> None: \"\"\"",
"non-string value is given. \"\"\" given = [\"Hello\", \"World\"] self.assertRaises(TypeError, lambda: self.converter.set_data_to_convert(given)) def",
"tool to check the availability or syntax of domain, IP or URL. ::",
"for the case that an empty-string value is given. \"\"\" given = \"\"",
"IP or URL. :: ██████╗ ██╗ ██╗███████╗██╗ ██╗███╗ ██╗ ██████╗███████╗██████╗ ██╗ ███████╗ ██╔══██╗╚██╗",
"self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_scheme_and_with_params(self) -> None: \"\"\" Tests the method which let",
"value is given. \"\"\" given = \"\" self.assertRaises(ValueError, lambda: self.converter.set_data_to_convert(given)) def test_get_converted_nothing_to_decode(self) ->",
"def test_get_converted_full_url_with_port(self) -> None: \"\"\" Tests the method which let us extracts the",
"is given. \"\"\" given = \"https://example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert = given actual",
"availability or syntax of domain, IP or URL. :: ██████╗ ██╗ ██╗███████╗██╗ ██╗███╗",
"everything previously created for the tests. \"\"\" del self.converter def test_set_data_to_convert_no_string(self) -> None:",
"\"://example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def",
"from PyFunceble.converter.url2netloc import Url2Netloc class TestUrl2Netloc(unittest.TestCase): \"\"\" Tests our internal URL converter. \"\"\"",
"self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_startswith_1_slash(self) -> None: \"\"\" Tests the method which let",
"The tool to check the availability or syntax of domain, IP or URL.",
"██╔══██╗██║ ██╔══╝ ██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗███████╗██████╔╝███████╗███████╗ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝",
"def test_get_converted_url_without_scheme_and_with_params(self) -> None: \"\"\" Tests the method which let us extracts the",
"http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed",
"URL for the case that a full URL (with explicit port) is given.",
"a given URL for the case that no scheme is given. \"\"\" given",
"import Url2Netloc class TestUrl2Netloc(unittest.TestCase): \"\"\" Tests our internal URL converter. \"\"\" def setUp(self)",
"def test_get_converted_nothing_to_decode(self) -> None: \"\"\" Tests the method which let us extracts the",
"2019, 2020, 2021 <NAME> Licensed under the Apache License, Version 2.0 (the \"License\");",
"self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_scheme_and_with_params(self) -> None: \"\"\"",
"License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF",
"self.assertEqual(expected, actual) def test_get_converted_url_startswith_1_slash(self) -> None: \"\"\" Tests the method which let us",
"\"example.org:8080\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_full_url_with_params(self) -> None:",
"method which let us extracts the netloc from a given URL for the",
"<NAME> Licensed under the Apache License, Version 2.0 (the \"License\"); you may not",
"that an empty-string value is given. \"\"\" given = \"\" self.assertRaises(ValueError, lambda: self.converter.set_data_to_convert(given))",
"self.converter.set_data_to_convert(given)) def test_get_converted_nothing_to_decode(self) -> None: \"\"\" Tests the method which let us extracts",
"def test_set_data_to_convert_empty_string(self) -> None: \"\"\" Tests the method which let us set the",
"\"example.org\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def",
"law or agreed to in writing, software distributed under the License is distributed",
"is given. \"\"\" given = \"\" self.assertRaises(ValueError, lambda: self.converter.set_data_to_convert(given)) def test_get_converted_nothing_to_decode(self) -> None:",
"let us extracts the netloc from a given URL for the case that",
"needed for the tests. \"\"\" self.converter = Url2Netloc() def tearDown(self) -> None: \"\"\"",
"is given. \"\"\" given = \"example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert = given actual",
"Version 2.0 (the \"License\"); you may not use this file except in compliance",
"an empty-string value is given. \"\"\" given = \"\" self.assertRaises(ValueError, lambda: self.converter.set_data_to_convert(given)) def",
"https://pyfunceble.github.io/special-thanks.html Contributors: https://pyfunceble.github.io/contributors.html Project link: https://github.com/funilrys/PyFunceble Project documentation: https://pyfunceble.readthedocs.io/en/dev/ Project homepage: https://pyfunceble.github.io/ License:",
"actual) def test_get_converted_url_without_protocol_and_path(self) -> None: \"\"\" Tests the method which let us extracts",
"netloc from a given URL for the case that no scheme is given.",
"the Apache License, Version 2.0 (the \"License\"); you may not use this file",
"a given URL for the case that no protocol and path is given.",
"actual) def test_get_converted_full_url_with_params(self) -> None: \"\"\" Tests the method which let us extracts",
"netloc from a given URL for the case that no protocol (but params)",
"test_get_converted_url_startswith_1_slash(self) -> None: \"\"\" Tests the method which let us extracts the netloc",
"with 1 slash. \"\"\" given = \"/example.org/hello/world/this/is/a/test\" expected = \"\" self.converter.data_to_convert = given",
"2017, 2018, 2019, 2020, 2021 <NAME> Licensed under the Apache License, Version 2.0",
"██╗ ██╗███████╗██╗ ██╗███╗ ██╗ ██████╗███████╗██████╗ ██╗ ███████╗ ██╔══██╗╚██╗ ██╔╝██╔════╝██║ ██║████╗ ██║██╔════╝██╔════╝██╔══██╗██║ ██╔════╝ ██████╔╝",
"under the Apache License, Version 2.0 (the \"License\"); you may not use this",
"created for the tests. \"\"\" del self.converter def test_set_data_to_convert_no_string(self) -> None: \"\"\" Tests",
"with 2 slashes. \"\"\" given = \"//example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert = given",
"= \"example.org:8080\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_full_url_with_params(self) ->",
"either express or implied. See the License for the specific language governing permissions",
"no protocol is given. \"\"\" given = \"://example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert =",
"actual) def test_get_converted_full_url_with_port(self) -> None: \"\"\" Tests the method which let us extracts",
"URL for the case that no scheme (but with params) is given. \"\"\"",
"\"\"\" given = \"https://example.org/?is_admin=true\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted()",
"that the given url starts with 2 slashes. \"\"\" given = \"//example.org/hello/world/this/is/a/test\" expected",
"a full URL is given. \"\"\" given = \"https://example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert",
"\"\"\" import unittest import unittest.mock from PyFunceble.converter.url2netloc import Url2Netloc class TestUrl2Netloc(unittest.TestCase): \"\"\" Tests",
"or syntax of domain, IP or URL. :: ██████╗ ██╗ ██╗███████╗██╗ ██╗███╗ ██╗",
"-> None: \"\"\" Destroys everything previously created for the tests. \"\"\" del self.converter",
"██╗███████╗██╗ ██╗███╗ ██╗ ██████╗███████╗██████╗ ██╗ ███████╗ ██╔══██╗╚██╗ ██╔╝██╔════╝██║ ██║████╗ ██║██╔════╝██╔════╝██╔══██╗██║ ██╔════╝ ██████╔╝ ╚████╔╝",
"test_get_converted_full_url_with_port(self) -> None: \"\"\" Tests the method which let us extracts the netloc",
"\"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_full_url(self) -> None:",
"self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_full_url_with_port(self) -> None: \"\"\" Tests the method which let",
"Apache License, Version 2.0 (the \"License\"); you may not use this file except",
"or implied. See the License for the specific language governing permissions and limitations",
"the method which let us extracts the netloc from a given URL for",
"\"\"\" Tests the method which let us set the data to work with",
"the netloc from a given URL for the case that no scheme is",
"given. \"\"\" given = \"://example.org/?is_admin=true\" expected = \"example.org\" self.converter.data_to_convert = given actual =",
"given = \"example.org\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected,",
"self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_scheme(self) -> None: \"\"\"",
"\"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_protocol_and_with_params(self) -> None:",
"is needed. \"\"\" given = \"example.org\" expected = \"example.org\" self.converter.data_to_convert = given actual",
"= given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_scheme_and_with_params(self) -> None: \"\"\" Tests",
"for the case that no scheme (but with params) is given. \"\"\" given",
"2 Network Location converter. Author: <NAME>, @funilrys, contactTATAfunilrysTODTODcom Special thanks: https://pyfunceble.github.io/special-thanks.html Contributors: https://pyfunceble.github.io/contributors.html",
"CONDITIONS OF ANY KIND, either express or implied. See the License for the",
"self.assertEqual(expected, actual) def test_get_converted_url_without_protocol(self) -> None: \"\"\" Tests the method which let us",
"2020, 2021 <NAME> Licensed under the Apache License, Version 2.0 (the \"License\"); you",
"= \"://example.org/?is_admin=true\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual)",
"to in writing, software distributed under the License is distributed on an \"AS",
"██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗███████╗██████╔╝███████╗███████╗ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝╚══════╝╚═════╝ ╚══════╝╚══════╝",
"a given URL for the case that a full URL is given. \"\"\"",
"given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_full_url(self) -> None: \"\"\" Tests the",
"URL for the case that a full URL is given. \"\"\" given =",
"given. \"\"\" given = \"https://example.org:8080/hello/world/this/is/a/test\" expected = \"example.org:8080\" self.converter.data_to_convert = given actual =",
"empty-string value is given. \"\"\" given = \"\" self.assertRaises(ValueError, lambda: self.converter.set_data_to_convert(given)) def test_get_converted_nothing_to_decode(self)",
"= \"example.org/?is_admin=true\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual)",
"case that no protocol (but params) is given. \"\"\" given = \"://example.org/?is_admin=true\" expected",
"everything needed for the tests. \"\"\" self.converter = Url2Netloc() def tearDown(self) -> None:",
"Copyright 2017, 2018, 2019, 2020, 2021 <NAME> Licensed under the Apache License, Version",
"except in compliance with the License. You may obtain a copy of the",
"= self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_full_url_with_params(self) -> None: \"\"\" Tests the method which",
"\"\"\" given = \"://example.org/\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted()",
"None: \"\"\" Tests the method which let us extracts the netloc from a",
"the specific language governing permissions and limitations under the License. \"\"\" import unittest",
"the case that a full URL (with explicit port) is given. \"\"\" given",
"lambda: self.converter.set_data_to_convert(given)) def test_set_data_to_convert_empty_string(self) -> None: \"\"\" Tests the method which let us",
"given. \"\"\" given = \"\" self.assertRaises(ValueError, lambda: self.converter.set_data_to_convert(given)) def test_get_converted_nothing_to_decode(self) -> None: \"\"\"",
"for the case that a full URL (with explicit port) is given. \"\"\"",
"= given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_startswith_1_slash(self) -> None: \"\"\" Tests",
"\"example.org/?is_admin=true\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def",
"an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"a full URL (with params) is given. \"\"\" given = \"https://example.org/?is_admin=true\" expected =",
"= \"//example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual)",
"no scheme (but with params) is given. \"\"\" given = \"example.org/?is_admin=true\" expected =",
"= Url2Netloc() def tearDown(self) -> None: \"\"\" Destroys everything previously created for the",
"╚██████╔╝██║ ╚████║╚██████╗███████╗██████╔╝███████╗███████╗ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝╚══════╝╚═════╝ ╚══════╝╚══════╝ Tests of URL",
"██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗███████╗██████╔╝███████╗███████╗ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝╚══════╝╚═════╝ ╚══════╝╚══════╝ Tests",
"del self.converter def test_set_data_to_convert_no_string(self) -> None: \"\"\" Tests the method which let us",
"obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law",
"actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_full_url(self) -> None: \"\"\" Tests the method",
"= \"https://example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual)",
"actual) def test_get_converted_url_without_scheme(self) -> None: \"\"\" Tests the method which let us extracts",
"conversion is needed. \"\"\" given = \"example.org\" expected = \"example.org\" self.converter.data_to_convert = given",
"= given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_full_url(self) -> None: \"\"\" Tests",
"the case that no protocol and path is given. \"\"\" given = \"://example.org/\"",
"from a given URL for the case that no protocol is given. \"\"\"",
"= \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_protocol_and_with_params(self) ->",
"test_get_converted_url_without_protocol_and_path(self) -> None: \"\"\" Tests the method which let us extracts the netloc",
"= self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_protocol_and_path(self) -> None: \"\"\" Tests the method which",
"License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing,",
"params) is given. \"\"\" given = \"example.org/?is_admin=true\" expected = \"example.org\" self.converter.data_to_convert = given",
"\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"the data to work with for the case that a non-string value is",
"of domain, IP or URL. :: ██████╗ ██╗ ██╗███████╗██╗ ██╗███╗ ██╗ ██████╗███████╗██████╗ ██╗",
"self.assertEqual(expected, actual) def test_get_converted_full_url_with_params(self) -> None: \"\"\" Tests the method which let us",
"the case that no scheme (but with params) is given. \"\"\" given =",
"is given. \"\"\" given = \"://example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert = given actual",
"URL for the case that the given url starts with 2 slashes. \"\"\"",
"= self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_startswith_2_slashes(self) -> None: \"\"\" Tests the method which",
"given URL for the case that no protocol (but params) is given. \"\"\"",
"██╗███╗ ██╗ ██████╗███████╗██████╗ ██╗ ███████╗ ██╔══██╗╚██╗ ██╔╝██╔════╝██║ ██║████╗ ██║██╔════╝██╔════╝██╔══██╗██║ ██╔════╝ ██████╔╝ ╚████╔╝ █████╗",
"https://pyfunceble.github.io/contributors.html Project link: https://github.com/funilrys/PyFunceble Project documentation: https://pyfunceble.readthedocs.io/en/dev/ Project homepage: https://pyfunceble.github.io/ License: :: Copyright",
"from a given URL for the case that no protocol and path is",
"us set the data to work with for the case that an empty-string",
"(with explicit port) is given. \"\"\" given = \"https://example.org:8080/hello/world/this/is/a/test\" expected = \"example.org:8080\" self.converter.data_to_convert",
"test_get_converted_url_without_protocol_and_with_params(self) -> None: \"\"\" Tests the method which let us extracts the netloc",
"def test_get_converted_full_url(self) -> None: \"\"\" Tests the method which let us extracts the",
"let us set the data to work with for the case that a",
"\"World\"] self.assertRaises(TypeError, lambda: self.converter.set_data_to_convert(given)) def test_set_data_to_convert_empty_string(self) -> None: \"\"\" Tests the method which",
"the netloc from a given URL for the case that no protocol and",
"\"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_startswith_2_slashes(self) -> None:",
"test_get_converted_url_without_protocol(self) -> None: \"\"\" Tests the method which let us extracts the netloc",
"def test_get_converted_url_startswith_2_slashes(self) -> None: \"\"\" Tests the method which let us extracts the",
"documentation: https://pyfunceble.readthedocs.io/en/dev/ Project homepage: https://pyfunceble.github.io/ License: :: Copyright 2017, 2018, 2019, 2020, 2021",
"from a given URL for the case that no conversion is needed. \"\"\"",
"compliance with the License. You may obtain a copy of the License at",
"self.assertEqual(expected, actual) def test_get_converted_full_url_with_port(self) -> None: \"\"\" Tests the method which let us",
"\"\"\" given = \"https://example.org:8080/hello/world/this/is/a/test\" expected = \"example.org:8080\" self.converter.data_to_convert = given actual = self.converter.get_converted()",
"tests. \"\"\" del self.converter def test_set_data_to_convert_no_string(self) -> None: \"\"\" Tests the method which",
"= self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_startswith_1_slash(self) -> None: \"\"\" Tests the method which",
"self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_full_url_with_port(self) -> None: \"\"\"",
"express or implied. See the License for the specific language governing permissions and",
"\"https://example.org:8080/hello/world/this/is/a/test\" expected = \"example.org:8080\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def",
"for the case that a full URL (with params) is given. \"\"\" given",
"netloc from a given URL for the case that a full URL is",
"actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_startswith_1_slash(self) -> None: \"\"\" Tests the method",
"given = \"/example.org/hello/world/this/is/a/test\" expected = \"\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected,",
"a full URL (with explicit port) is given. \"\"\" given = \"https://example.org:8080/hello/world/this/is/a/test\" expected",
"given URL for the case that no protocol and path is given. \"\"\"",
"expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_full_url_with_port(self)",
"limitations under the License. \"\"\" import unittest import unittest.mock from PyFunceble.converter.url2netloc import Url2Netloc",
"set the data to work with for the case that an empty-string value",
"Special thanks: https://pyfunceble.github.io/special-thanks.html Contributors: https://pyfunceble.github.io/contributors.html Project link: https://github.com/funilrys/PyFunceble Project documentation: https://pyfunceble.readthedocs.io/en/dev/ Project homepage:",
"import unittest.mock from PyFunceble.converter.url2netloc import Url2Netloc class TestUrl2Netloc(unittest.TestCase): \"\"\" Tests our internal URL",
"\"\"\" given = \"example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted()",
"expected = \"\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) if __name__",
"us extracts the netloc from a given URL for the case that the",
"that no scheme is given. \"\"\" given = \"example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert",
"unittest import unittest.mock from PyFunceble.converter.url2netloc import Url2Netloc class TestUrl2Netloc(unittest.TestCase): \"\"\" Tests our internal",
"params) is given. \"\"\" given = \"https://example.org/?is_admin=true\" expected = \"example.org\" self.converter.data_to_convert = given",
"You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by",
"a given URL for the case that a full URL (with params) is",
"is given. \"\"\" given = \"https://example.org:8080/hello/world/this/is/a/test\" expected = \"example.org:8080\" self.converter.data_to_convert = given actual",
"(but params) is given. \"\"\" given = \"://example.org/?is_admin=true\" expected = \"example.org\" self.converter.data_to_convert =",
"def test_get_converted_url_without_protocol_and_path(self) -> None: \"\"\" Tests the method which let us extracts the",
"applicable law or agreed to in writing, software distributed under the License is",
"import unittest import unittest.mock from PyFunceble.converter.url2netloc import Url2Netloc class TestUrl2Netloc(unittest.TestCase): \"\"\" Tests our",
"case that no scheme is given. \"\"\" given = \"example.org/hello/world/this/is/a/test\" expected = \"example.org\"",
"██╔╝██╔════╝██║ ██║████╗ ██║██╔════╝██╔════╝██╔══██╗██║ ██╔════╝ ██████╔╝ ╚████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ █████╗ ██████╔╝██║ █████╗",
"\"\"\" given = \"https://example.org/hello/world/this/is/a/test\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted()",
"given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_full_url_with_port(self) -> None: \"\"\" Tests the",
"██╔══██╗╚██╗ ██╔╝██╔════╝██║ ██║████╗ ██║██╔════╝██╔════╝██╔══██╗██║ ██╔════╝ ██████╔╝ ╚████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ █████╗ ██████╔╝██║",
"us extracts the netloc from a given URL for the case that a",
"given URL for the case that a full URL (with explicit port) is",
"test_set_data_to_convert_empty_string(self) -> None: \"\"\" Tests the method which let us set the data",
"BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See",
"no protocol and path is given. \"\"\" given = \"://example.org/\" expected = \"example.org\"",
"Tests of URL 2 Network Location converter. Author: <NAME>, @funilrys, contactTATAfunilrysTODTODcom Special thanks:",
"\"https://example.org/?is_admin=true\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def",
"given = \"://example.org/?is_admin=true\" expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected,",
"Tests our internal URL converter. \"\"\" def setUp(self) -> None: \"\"\" Setups everything",
"domain, IP or URL. :: ██████╗ ██╗ ██╗███████╗██╗ ██╗███╗ ██╗ ██████╗███████╗██████╗ ██╗ ███████╗",
"from a given URL for the case that the given url starts with",
"which let us set the data to work with for the case that",
"the case that no protocol is given. \"\"\" given = \"://example.org/hello/world/this/is/a/test\" expected =",
"Setups everything needed for the tests. \"\"\" self.converter = Url2Netloc() def tearDown(self) ->",
"actual) def test_get_converted_url_startswith_2_slashes(self) -> None: \"\"\" Tests the method which let us extracts",
"under the License. \"\"\" import unittest import unittest.mock from PyFunceble.converter.url2netloc import Url2Netloc class",
"the netloc from a given URL for the case that no protocol is",
"expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_protocol_and_with_params(self)",
"unittest.mock from PyFunceble.converter.url2netloc import Url2Netloc class TestUrl2Netloc(unittest.TestCase): \"\"\" Tests our internal URL converter.",
"work with for the case that a non-string value is given. \"\"\" given",
"given URL for the case that a full URL (with params) is given.",
"= self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_without_scheme(self) -> None: \"\"\" Tests the method which",
"██║██║╚██╗██║██║ ██╔══╝ ██╔══██╗██║ ██╔══╝ ██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗███████╗██████╔╝███████╗███████╗ ╚═╝ ╚═╝ ╚═╝ ╚═════╝",
"given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_url_startswith_1_slash(self) -> None: \"\"\" Tests the",
"╚██╔╝ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██╔══╝ ██╔══██╗██║ ██╔══╝ ██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗███████╗██████╔╝███████╗███████╗ ╚═╝",
"with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0",
"None: \"\"\" Destroys everything previously created for the tests. \"\"\" del self.converter def",
"full URL (with params) is given. \"\"\" given = \"https://example.org/?is_admin=true\" expected = \"example.org\"",
"at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software",
"expected = \"example.org\" self.converter.data_to_convert = given actual = self.converter.get_converted() self.assertEqual(expected, actual) def test_get_converted_full_url(self)"
] |
[
"tell that to the user. If not, print a different appropriate message. \"\"\"",
"print out a different message. 2. Ask the user for two numbers: one",
"odd.\") divisor = int(input(\"Enter a second integer: \")) if number % divisor: print(\"%d",
"Ask the user for two numbers: one number to check (call it num)",
"message. \"\"\" number = int(input(\"Enter an integer: \")) if (number % 4) ==",
"is even.\") else: print(str(number) + \" is odd.\") divisor = int(input(\"Enter a second",
"number. Depending on whether the number is even or odd, print out an",
"\")) if number % divisor: print(\"%d is not a divisor of %d.\" %",
"4, print out a different message. 2. Ask the user for two numbers:",
"whether the number is even or odd, print out an appropriate message to",
"2? Extras: 1. If the number is a multiple of 4, print out",
"to divide by (check). If check divides evenly into num, tell that to",
"appropriate message to the user. Hint: how does an even / odd number",
"is even or odd, print out an appropriate message to the user. Hint:",
"If check divides evenly into num, tell that to the user. If not,",
"number = int(input(\"Enter an integer: \")) if (number % 4) == 0: print(str(number)",
"check (call it num) and one number to divide by (check). If check",
"by 2? Extras: 1. If the number is a multiple of 4, print",
"print(str(number) + \" is even.\") else: print(str(number) + \" is odd.\") divisor =",
"integer: \")) if (number % 4) == 0: print(str(number) + \" is evenly",
"evenly divisible by 4.\") elif ((number %2) == 0): print(str(number) + \" is",
"the number is a multiple of 4, print out a different message. 2.",
"a different message. 2. Ask the user for two numbers: one number to",
"by (check). If check divides evenly into num, tell that to the user.",
"on whether the number is even or odd, print out an appropriate message",
"divisible by 4.\") elif ((number %2) == 0): print(str(number) + \" is even.\")",
"print(str(number) + \" is evenly divisible by 4.\") elif ((number %2) == 0):",
"number to check (call it num) and one number to divide by (check).",
"numbers: one number to check (call it num) and one number to divide",
"not a divisor of %d.\" % (divisor, number)) else: print(\"%d is a divisor",
"\"\"\" https://www.practicepython.org Exercise 2: Odd or Even 1 chile Ask the user for",
"print out an appropriate message to the user. Hint: how does an even",
"Odd or Even 1 chile Ask the user for a number. Depending on",
"Exercise 2: Odd or Even 1 chile Ask the user for a number.",
"the user. Hint: how does an even / odd number react differently when",
"or odd, print out an appropriate message to the user. Hint: how does",
"it num) and one number to divide by (check). If check divides evenly",
"= int(input(\"Enter a second integer: \")) if number % divisor: print(\"%d is not",
"to the user. Hint: how does an even / odd number react differently",
"chile Ask the user for a number. Depending on whether the number is",
"%2) == 0): print(str(number) + \" is even.\") else: print(str(number) + \" is",
"If the number is a multiple of 4, print out a different message.",
"the user for two numbers: one number to check (call it num) and",
"an even / odd number react differently when divided by 2? Extras: 1.",
"different message. 2. Ask the user for two numbers: one number to check",
"to the user. If not, print a different appropriate message. \"\"\" number =",
"or Even 1 chile Ask the user for a number. Depending on whether",
"the number is even or odd, print out an appropriate message to the",
"odd, print out an appropriate message to the user. Hint: how does an",
"even.\") else: print(str(number) + \" is odd.\") divisor = int(input(\"Enter a second integer:",
"\" is even.\") else: print(str(number) + \" is odd.\") divisor = int(input(\"Enter a",
"number % divisor: print(\"%d is not a divisor of %d.\" % (divisor, number))",
"differently when divided by 2? Extras: 1. If the number is a multiple",
"num, tell that to the user. If not, print a different appropriate message.",
"else: print(str(number) + \" is odd.\") divisor = int(input(\"Enter a second integer: \"))",
"is evenly divisible by 4.\") elif ((number %2) == 0): print(str(number) + \"",
"multiple of 4, print out a different message. 2. Ask the user for",
"(call it num) and one number to divide by (check). If check divides",
"a divisor of %d.\" % (divisor, number)) else: print(\"%d is a divisor of",
"the user for a number. Depending on whether the number is even or",
"divides evenly into num, tell that to the user. If not, print a",
"0: print(str(number) + \" is evenly divisible by 4.\") elif ((number %2) ==",
"Depending on whether the number is even or odd, print out an appropriate",
"is odd.\") divisor = int(input(\"Enter a second integer: \")) if number % divisor:",
"number to divide by (check). If check divides evenly into num, tell that",
"if number % divisor: print(\"%d is not a divisor of %d.\" % (divisor,",
"1 chile Ask the user for a number. Depending on whether the number",
"of %d.\" % (divisor, number)) else: print(\"%d is a divisor of %d.\" %",
"odd number react differently when divided by 2? Extras: 1. If the number",
"int(input(\"Enter a second integer: \")) if number % divisor: print(\"%d is not a",
"that to the user. If not, print a different appropriate message. \"\"\" number",
"print(\"%d is not a divisor of %d.\" % (divisor, number)) else: print(\"%d is",
"to check (call it num) and one number to divide by (check). If",
"1. If the number is a multiple of 4, print out a different",
"is not a divisor of %d.\" % (divisor, number)) else: print(\"%d is a",
"when divided by 2? Extras: 1. If the number is a multiple of",
"2: Odd or Even 1 chile Ask the user for a number. Depending",
"+ \" is evenly divisible by 4.\") elif ((number %2) == 0): print(str(number)",
"<reponame>lew18/practicepython.org-mysolutions<filename>ex02-odd_or_even.py \"\"\" https://www.practicepython.org Exercise 2: Odd or Even 1 chile Ask the user",
"message. 2. Ask the user for two numbers: one number to check (call",
"two numbers: one number to check (call it num) and one number to",
"if (number % 4) == 0: print(str(number) + \" is evenly divisible by",
"0): print(str(number) + \" is even.\") else: print(str(number) + \" is odd.\") divisor",
"by 4.\") elif ((number %2) == 0): print(str(number) + \" is even.\") else:",
"second integer: \")) if number % divisor: print(\"%d is not a divisor of",
"divided by 2? Extras: 1. If the number is a multiple of 4,",
"int(input(\"Enter an integer: \")) if (number % 4) == 0: print(str(number) + \"",
"4.\") elif ((number %2) == 0): print(str(number) + \" is even.\") else: print(str(number)",
"/ odd number react differently when divided by 2? Extras: 1. If the",
"= int(input(\"Enter an integer: \")) if (number % 4) == 0: print(str(number) +",
"an integer: \")) if (number % 4) == 0: print(str(number) + \" is",
"(check). If check divides evenly into num, tell that to the user. If",
"one number to check (call it num) and one number to divide by",
"even or odd, print out an appropriate message to the user. Hint: how",
"integer: \")) if number % divisor: print(\"%d is not a divisor of %d.\"",
"== 0): print(str(number) + \" is even.\") else: print(str(number) + \" is odd.\")",
"user. Hint: how does an even / odd number react differently when divided",
"2. Ask the user for two numbers: one number to check (call it",
"not, print a different appropriate message. \"\"\" number = int(input(\"Enter an integer: \"))",
"appropriate message. \"\"\" number = int(input(\"Enter an integer: \")) if (number % 4)",
"of 4, print out a different message. 2. Ask the user for two",
"into num, tell that to the user. If not, print a different appropriate",
"for a number. Depending on whether the number is even or odd, print",
"((number %2) == 0): print(str(number) + \" is even.\") else: print(str(number) + \"",
"an appropriate message to the user. Hint: how does an even / odd",
"number is a multiple of 4, print out a different message. 2. Ask",
"\")) if (number % 4) == 0: print(str(number) + \" is evenly divisible",
"different appropriate message. \"\"\" number = int(input(\"Enter an integer: \")) if (number %",
"out a different message. 2. Ask the user for two numbers: one number",
"Even 1 chile Ask the user for a number. Depending on whether the",
"4) == 0: print(str(number) + \" is evenly divisible by 4.\") elif ((number",
"divisor = int(input(\"Enter a second integer: \")) if number % divisor: print(\"%d is",
"== 0: print(str(number) + \" is evenly divisible by 4.\") elif ((number %2)",
"user. If not, print a different appropriate message. \"\"\" number = int(input(\"Enter an",
"num) and one number to divide by (check). If check divides evenly into",
"% 4) == 0: print(str(number) + \" is evenly divisible by 4.\") elif",
"is a multiple of 4, print out a different message. 2. Ask the",
"divisor of %d.\" % (divisor, number)) else: print(\"%d is a divisor of %d.\"",
"%d.\" % (divisor, number)) else: print(\"%d is a divisor of %d.\" % (divisor,",
"% (divisor, number)) else: print(\"%d is a divisor of %d.\" % (divisor, number))",
"divide by (check). If check divides evenly into num, tell that to the",
"one number to divide by (check). If check divides evenly into num, tell",
"print(str(number) + \" is odd.\") divisor = int(input(\"Enter a second integer: \")) if",
"a different appropriate message. \"\"\" number = int(input(\"Enter an integer: \")) if (number",
"number is even or odd, print out an appropriate message to the user.",
"number react differently when divided by 2? Extras: 1. If the number is",
"divisor: print(\"%d is not a divisor of %d.\" % (divisor, number)) else: print(\"%d",
"If not, print a different appropriate message. \"\"\" number = int(input(\"Enter an integer:",
"+ \" is odd.\") divisor = int(input(\"Enter a second integer: \")) if number",
"Extras: 1. If the number is a multiple of 4, print out a",
"% divisor: print(\"%d is not a divisor of %d.\" % (divisor, number)) else:",
"(number % 4) == 0: print(str(number) + \" is evenly divisible by 4.\")",
"a number. Depending on whether the number is even or odd, print out",
"even / odd number react differently when divided by 2? Extras: 1. If",
"a second integer: \")) if number % divisor: print(\"%d is not a divisor",
"https://www.practicepython.org Exercise 2: Odd or Even 1 chile Ask the user for a",
"\" is evenly divisible by 4.\") elif ((number %2) == 0): print(str(number) +",
"and one number to divide by (check). If check divides evenly into num,",
"how does an even / odd number react differently when divided by 2?",
"print a different appropriate message. \"\"\" number = int(input(\"Enter an integer: \")) if",
"react differently when divided by 2? Extras: 1. If the number is a",
"message to the user. Hint: how does an even / odd number react",
"\" is odd.\") divisor = int(input(\"Enter a second integer: \")) if number %",
"elif ((number %2) == 0): print(str(number) + \" is even.\") else: print(str(number) +",
"user for a number. Depending on whether the number is even or odd,",
"a multiple of 4, print out a different message. 2. Ask the user",
"for two numbers: one number to check (call it num) and one number",
"the user. If not, print a different appropriate message. \"\"\" number = int(input(\"Enter",
"out an appropriate message to the user. Hint: how does an even /",
"\"\"\" number = int(input(\"Enter an integer: \")) if (number % 4) == 0:",
"does an even / odd number react differently when divided by 2? Extras:",
"user for two numbers: one number to check (call it num) and one",
"Hint: how does an even / odd number react differently when divided by",
"check divides evenly into num, tell that to the user. If not, print",
"evenly into num, tell that to the user. If not, print a different",
"+ \" is even.\") else: print(str(number) + \" is odd.\") divisor = int(input(\"Enter",
"Ask the user for a number. Depending on whether the number is even"
] |
[
"<filename>musicrecs/spotify/item/spotify_artist.py from .spotify_item import SpotifyItem class SpotifyArtist(SpotifyItem): \"\"\"Class to hold selected information about",
".spotify_item import SpotifyItem class SpotifyArtist(SpotifyItem): \"\"\"Class to hold selected information about a spotify",
"selected information about a spotify artist\"\"\" def __init__(self, spotify_artist): # Initialize base class",
"from .spotify_item import SpotifyItem class SpotifyArtist(SpotifyItem): \"\"\"Class to hold selected information about a",
"SpotifyItem class SpotifyArtist(SpotifyItem): \"\"\"Class to hold selected information about a spotify artist\"\"\" def",
"information about a spotify artist\"\"\" def __init__(self, spotify_artist): # Initialize base class super().__init__(spotify_artist)",
"import SpotifyItem class SpotifyArtist(SpotifyItem): \"\"\"Class to hold selected information about a spotify artist\"\"\"",
"to hold selected information about a spotify artist\"\"\" def __init__(self, spotify_artist): # Initialize",
"SpotifyArtist(SpotifyItem): \"\"\"Class to hold selected information about a spotify artist\"\"\" def __init__(self, spotify_artist):",
"\"\"\"Class to hold selected information about a spotify artist\"\"\" def __init__(self, spotify_artist): #",
"class SpotifyArtist(SpotifyItem): \"\"\"Class to hold selected information about a spotify artist\"\"\" def __init__(self,",
"hold selected information about a spotify artist\"\"\" def __init__(self, spotify_artist): # Initialize base"
] |
[
"if n == 0: raise FooError('invalid value: %s' % s) return 10 /",
"# bar('0') # except Exception as e: # print(\"----出错了\") # logging.exception(e) class FooError(ValueError):",
"# def main(): # try: # bar('0') # except Exception as e: #",
"def foo(s): # return 10 / int(s) # def bar(s): # return foo(s)",
"# # err_logging.py # import logging # def foo(s): # return 10 /",
"int(s) if n == 0: raise FooError('invalid value: %s' % s) return 10",
"0: raise FooError('invalid value: %s' % s) return 10 / n foo('0') print('END')",
"/ int(s) # def bar(s): # return foo(s) * 2 # def main():",
"Exception as e: # print(\"----出错了\") # logging.exception(e) class FooError(ValueError): pass def foo(s): n",
"try: # bar('0') # except Exception as e: # print(\"----出错了\") # logging.exception(e) class",
"n = int(s) if n == 0: raise FooError('invalid value: %s' % s)",
"class FooError(ValueError): pass def foo(s): n = int(s) if n == 0: raise",
"* 2 # def main(): # try: # bar('0') # except Exception as",
"# import logging # def foo(s): # return 10 / int(s) # def",
"FooError(ValueError): pass def foo(s): n = int(s) if n == 0: raise FooError('invalid",
"# return foo(s) * 2 # def main(): # try: # bar('0') #",
"= int(s) if n == 0: raise FooError('invalid value: %s' % s) return",
"<gh_stars>0 # # err_logging.py # import logging # def foo(s): # return 10",
"as e: # print(\"----出错了\") # logging.exception(e) class FooError(ValueError): pass def foo(s): n =",
"main(): # try: # bar('0') # except Exception as e: # print(\"----出错了\") #",
"bar(s): # return foo(s) * 2 # def main(): # try: # bar('0')",
"except Exception as e: # print(\"----出错了\") # logging.exception(e) class FooError(ValueError): pass def foo(s):",
"logging # def foo(s): # return 10 / int(s) # def bar(s): #",
"# return 10 / int(s) # def bar(s): # return foo(s) * 2",
"# logging.exception(e) class FooError(ValueError): pass def foo(s): n = int(s) if n ==",
"2 # def main(): # try: # bar('0') # except Exception as e:",
"10 / int(s) # def bar(s): # return foo(s) * 2 # def",
"# err_logging.py # import logging # def foo(s): # return 10 / int(s)",
"print(\"----出错了\") # logging.exception(e) class FooError(ValueError): pass def foo(s): n = int(s) if n",
"logging.exception(e) class FooError(ValueError): pass def foo(s): n = int(s) if n == 0:",
"== 0: raise FooError('invalid value: %s' % s) return 10 / n foo('0')",
"bar('0') # except Exception as e: # print(\"----出错了\") # logging.exception(e) class FooError(ValueError): pass",
"def bar(s): # return foo(s) * 2 # def main(): # try: #",
"foo(s): # return 10 / int(s) # def bar(s): # return foo(s) *",
"# def bar(s): # return foo(s) * 2 # def main(): # try:",
"foo(s) * 2 # def main(): # try: # bar('0') # except Exception",
"def foo(s): n = int(s) if n == 0: raise FooError('invalid value: %s'",
"err_logging.py # import logging # def foo(s): # return 10 / int(s) #",
"# print(\"----出错了\") # logging.exception(e) class FooError(ValueError): pass def foo(s): n = int(s) if",
"return 10 / int(s) # def bar(s): # return foo(s) * 2 #",
"e: # print(\"----出错了\") # logging.exception(e) class FooError(ValueError): pass def foo(s): n = int(s)",
"def main(): # try: # bar('0') # except Exception as e: # print(\"----出错了\")",
"# except Exception as e: # print(\"----出错了\") # logging.exception(e) class FooError(ValueError): pass def",
"pass def foo(s): n = int(s) if n == 0: raise FooError('invalid value:",
"n == 0: raise FooError('invalid value: %s' % s) return 10 / n",
"foo(s): n = int(s) if n == 0: raise FooError('invalid value: %s' %",
"# try: # bar('0') # except Exception as e: # print(\"----出错了\") # logging.exception(e)",
"int(s) # def bar(s): # return foo(s) * 2 # def main(): #",
"# def foo(s): # return 10 / int(s) # def bar(s): # return",
"import logging # def foo(s): # return 10 / int(s) # def bar(s):",
"return foo(s) * 2 # def main(): # try: # bar('0') # except"
] |
[
"Cool assert 'Richter+17' in mwcgm.refs SiII_tbl = mwcgm.abs.ion_tbl((14,2)) assert (not np.any(np.isnan(SiII_tbl['logN']))) assert np.sum(SiII_tbl['flag_N']",
"import print_function, absolute_import, division, unicode_literals # TEST_UNICODE_LITERALS import pytest import numpy as np",
"len(ovii_tbl['sig_logN'][0]) == 2 # OVI table ovi_tbl = mwcgm.abs.ion_tbl((8,6)) # Usage coords =",
"0 # Cool assert 'Richter+17' in mwcgm.refs SiII_tbl = mwcgm.abs.ion_tbl((14,2)) assert (not np.any(np.isnan(SiII_tbl['logN'])))",
"mwcgm = GalaxyCGM() assert len(mwcgm.abs.cgm_abs) > 0 # Cool assert 'Richter+17' in mwcgm.refs",
"GalaxyCGM from __future__ import print_function, absolute_import, division, unicode_literals # TEST_UNICODE_LITERALS import pytest import",
"to run tests on GalaxyCGM from __future__ import print_function, absolute_import, division, unicode_literals #",
"as np from pyigm.cgm.galaxy import GalaxyCGM def test_init_light(): mwcgm = GalaxyCGM(load=False) def test_init_full():",
"mwcgm.abs.ion_tbl((8,7)) assert len(ovii_tbl['sig_logN'][0]) == 2 # OVI table ovi_tbl = mwcgm.abs.ion_tbl((8,6)) # Usage",
"assert np.sum(SiII_tbl['flag_N'] > 0) == 188 # Hot assert 'Fang+15' in mwcgm.refs #",
"== 2 # OVI table ovi_tbl = mwcgm.abs.ion_tbl((8,6)) # Usage coords = mwcgm.abs.scoord",
"__future__ import print_function, absolute_import, division, unicode_literals # TEST_UNICODE_LITERALS import pytest import numpy as",
"division, unicode_literals # TEST_UNICODE_LITERALS import pytest import numpy as np from pyigm.cgm.galaxy import",
"# Hot assert 'Fang+15' in mwcgm.refs # OVII table ovii_tbl = mwcgm.abs.ion_tbl((8,7)) assert",
"= GalaxyCGM(load=False) def test_init_full(): mwcgm = GalaxyCGM() assert len(mwcgm.abs.cgm_abs) > 0 # Cool",
"= GalaxyCGM() assert len(mwcgm.abs.cgm_abs) > 0 # Cool assert 'Richter+17' in mwcgm.refs SiII_tbl",
"from __future__ import print_function, absolute_import, division, unicode_literals # TEST_UNICODE_LITERALS import pytest import numpy",
"assert (not np.any(np.isnan(SiII_tbl['logN']))) assert np.sum(SiII_tbl['flag_N'] > 0) == 188 # Hot assert 'Fang+15'",
"# TEST_UNICODE_LITERALS import pytest import numpy as np from pyigm.cgm.galaxy import GalaxyCGM def",
"TEST_UNICODE_LITERALS import pytest import numpy as np from pyigm.cgm.galaxy import GalaxyCGM def test_init_light():",
"OVII table ovii_tbl = mwcgm.abs.ion_tbl((8,7)) assert len(ovii_tbl['sig_logN'][0]) == 2 # OVI table ovi_tbl",
"print_function, absolute_import, division, unicode_literals # TEST_UNICODE_LITERALS import pytest import numpy as np from",
"pytest import numpy as np from pyigm.cgm.galaxy import GalaxyCGM def test_init_light(): mwcgm =",
"run tests on GalaxyCGM from __future__ import print_function, absolute_import, division, unicode_literals # TEST_UNICODE_LITERALS",
"assert len(mwcgm.abs.cgm_abs) > 0 # Cool assert 'Richter+17' in mwcgm.refs SiII_tbl = mwcgm.abs.ion_tbl((14,2))",
"> 0 # Cool assert 'Richter+17' in mwcgm.refs SiII_tbl = mwcgm.abs.ion_tbl((14,2)) assert (not",
"Hot assert 'Fang+15' in mwcgm.refs # OVII table ovii_tbl = mwcgm.abs.ion_tbl((8,7)) assert len(ovii_tbl['sig_logN'][0])",
"'Fang+15' in mwcgm.refs # OVII table ovii_tbl = mwcgm.abs.ion_tbl((8,7)) assert len(ovii_tbl['sig_logN'][0]) == 2",
"(not np.any(np.isnan(SiII_tbl['logN']))) assert np.sum(SiII_tbl['flag_N'] > 0) == 188 # Hot assert 'Fang+15' in",
"def test_init_light(): mwcgm = GalaxyCGM(load=False) def test_init_full(): mwcgm = GalaxyCGM() assert len(mwcgm.abs.cgm_abs) >",
"GalaxyCGM() assert len(mwcgm.abs.cgm_abs) > 0 # Cool assert 'Richter+17' in mwcgm.refs SiII_tbl =",
"<filename>pyigm/cgm/tests/test_galaxy.py # Module to run tests on GalaxyCGM from __future__ import print_function, absolute_import,",
"mwcgm = GalaxyCGM(load=False) def test_init_full(): mwcgm = GalaxyCGM() assert len(mwcgm.abs.cgm_abs) > 0 #",
"'Richter+17' in mwcgm.refs SiII_tbl = mwcgm.abs.ion_tbl((14,2)) assert (not np.any(np.isnan(SiII_tbl['logN']))) assert np.sum(SiII_tbl['flag_N'] > 0)",
"188 # Hot assert 'Fang+15' in mwcgm.refs # OVII table ovii_tbl = mwcgm.abs.ion_tbl((8,7))",
"on GalaxyCGM from __future__ import print_function, absolute_import, division, unicode_literals # TEST_UNICODE_LITERALS import pytest",
"test_init_full(): mwcgm = GalaxyCGM() assert len(mwcgm.abs.cgm_abs) > 0 # Cool assert 'Richter+17' in",
"numpy as np from pyigm.cgm.galaxy import GalaxyCGM def test_init_light(): mwcgm = GalaxyCGM(load=False) def",
"def test_init_full(): mwcgm = GalaxyCGM() assert len(mwcgm.abs.cgm_abs) > 0 # Cool assert 'Richter+17'",
"mwcgm.refs SiII_tbl = mwcgm.abs.ion_tbl((14,2)) assert (not np.any(np.isnan(SiII_tbl['logN']))) assert np.sum(SiII_tbl['flag_N'] > 0) == 188",
"mwcgm.abs.ion_tbl((14,2)) assert (not np.any(np.isnan(SiII_tbl['logN']))) assert np.sum(SiII_tbl['flag_N'] > 0) == 188 # Hot assert",
"in mwcgm.refs SiII_tbl = mwcgm.abs.ion_tbl((14,2)) assert (not np.any(np.isnan(SiII_tbl['logN']))) assert np.sum(SiII_tbl['flag_N'] > 0) ==",
"np.any(np.isnan(SiII_tbl['logN']))) assert np.sum(SiII_tbl['flag_N'] > 0) == 188 # Hot assert 'Fang+15' in mwcgm.refs",
"table ovii_tbl = mwcgm.abs.ion_tbl((8,7)) assert len(ovii_tbl['sig_logN'][0]) == 2 # OVI table ovi_tbl =",
"= mwcgm.abs.ion_tbl((14,2)) assert (not np.any(np.isnan(SiII_tbl['logN']))) assert np.sum(SiII_tbl['flag_N'] > 0) == 188 # Hot",
"ovii_tbl = mwcgm.abs.ion_tbl((8,7)) assert len(ovii_tbl['sig_logN'][0]) == 2 # OVI table ovi_tbl = mwcgm.abs.ion_tbl((8,6))",
"test_init_light(): mwcgm = GalaxyCGM(load=False) def test_init_full(): mwcgm = GalaxyCGM() assert len(mwcgm.abs.cgm_abs) > 0",
"SiII_tbl = mwcgm.abs.ion_tbl((14,2)) assert (not np.any(np.isnan(SiII_tbl['logN']))) assert np.sum(SiII_tbl['flag_N'] > 0) == 188 #",
"GalaxyCGM(load=False) def test_init_full(): mwcgm = GalaxyCGM() assert len(mwcgm.abs.cgm_abs) > 0 # Cool assert",
"mwcgm.refs # OVII table ovii_tbl = mwcgm.abs.ion_tbl((8,7)) assert len(ovii_tbl['sig_logN'][0]) == 2 # OVI",
"# Cool assert 'Richter+17' in mwcgm.refs SiII_tbl = mwcgm.abs.ion_tbl((14,2)) assert (not np.any(np.isnan(SiII_tbl['logN']))) assert",
"# Module to run tests on GalaxyCGM from __future__ import print_function, absolute_import, division,",
"tests on GalaxyCGM from __future__ import print_function, absolute_import, division, unicode_literals # TEST_UNICODE_LITERALS import",
"import numpy as np from pyigm.cgm.galaxy import GalaxyCGM def test_init_light(): mwcgm = GalaxyCGM(load=False)",
"np from pyigm.cgm.galaxy import GalaxyCGM def test_init_light(): mwcgm = GalaxyCGM(load=False) def test_init_full(): mwcgm",
"unicode_literals # TEST_UNICODE_LITERALS import pytest import numpy as np from pyigm.cgm.galaxy import GalaxyCGM",
"pyigm.cgm.galaxy import GalaxyCGM def test_init_light(): mwcgm = GalaxyCGM(load=False) def test_init_full(): mwcgm = GalaxyCGM()",
"= mwcgm.abs.ion_tbl((8,7)) assert len(ovii_tbl['sig_logN'][0]) == 2 # OVI table ovi_tbl = mwcgm.abs.ion_tbl((8,6)) #",
"in mwcgm.refs # OVII table ovii_tbl = mwcgm.abs.ion_tbl((8,7)) assert len(ovii_tbl['sig_logN'][0]) == 2 #",
"# OVII table ovii_tbl = mwcgm.abs.ion_tbl((8,7)) assert len(ovii_tbl['sig_logN'][0]) == 2 # OVI table",
"assert len(ovii_tbl['sig_logN'][0]) == 2 # OVI table ovi_tbl = mwcgm.abs.ion_tbl((8,6)) # Usage coords",
"Module to run tests on GalaxyCGM from __future__ import print_function, absolute_import, division, unicode_literals",
"from pyigm.cgm.galaxy import GalaxyCGM def test_init_light(): mwcgm = GalaxyCGM(load=False) def test_init_full(): mwcgm =",
"> 0) == 188 # Hot assert 'Fang+15' in mwcgm.refs # OVII table",
"assert 'Richter+17' in mwcgm.refs SiII_tbl = mwcgm.abs.ion_tbl((14,2)) assert (not np.any(np.isnan(SiII_tbl['logN']))) assert np.sum(SiII_tbl['flag_N'] >",
"np.sum(SiII_tbl['flag_N'] > 0) == 188 # Hot assert 'Fang+15' in mwcgm.refs # OVII",
"GalaxyCGM def test_init_light(): mwcgm = GalaxyCGM(load=False) def test_init_full(): mwcgm = GalaxyCGM() assert len(mwcgm.abs.cgm_abs)",
"== 188 # Hot assert 'Fang+15' in mwcgm.refs # OVII table ovii_tbl =",
"import pytest import numpy as np from pyigm.cgm.galaxy import GalaxyCGM def test_init_light(): mwcgm",
"assert 'Fang+15' in mwcgm.refs # OVII table ovii_tbl = mwcgm.abs.ion_tbl((8,7)) assert len(ovii_tbl['sig_logN'][0]) ==",
"len(mwcgm.abs.cgm_abs) > 0 # Cool assert 'Richter+17' in mwcgm.refs SiII_tbl = mwcgm.abs.ion_tbl((14,2)) assert",
"absolute_import, division, unicode_literals # TEST_UNICODE_LITERALS import pytest import numpy as np from pyigm.cgm.galaxy",
"0) == 188 # Hot assert 'Fang+15' in mwcgm.refs # OVII table ovii_tbl",
"import GalaxyCGM def test_init_light(): mwcgm = GalaxyCGM(load=False) def test_init_full(): mwcgm = GalaxyCGM() assert"
] |
[
"= (YELLOW) else: pixels[36] = (OFF) if icon == 'partly-cloudy-day' or 'partly-cloudy-night': pixels[34]",
"time.time() + 22.32 * 1 while time.time() < t_end: n = n +",
"print(text) print(icon) print(baro) print(trend) return trend, baro, icon def barometer(): conditions = getconditions()",
"= data['current_conditions']['conditions'] icon = data['current_conditions']['icon'] baro = int(data['current_conditions']['sea_level_pressure']) trend = data['current_conditions']['pressure_trend'] print(text) print(icon)",
"pixels to set top pixel pixel = 906 pixelon = int(baro - pixel)",
"or 'partly-cloudy-night': pixels[34] = (BLUE) else: pixels[34] = (OFF) if icon == 'cloudy':",
"json import time import neopixel import board #Set Colours RED = (255, 0,",
"= (YELLOW) pixels.show() time.sleep (0.1) pixels.fill((0, 0, 0)) pixels.show() print (\"Getting Conditions and",
"n = n + 1 if n >= 144: n = 1 pixels[n]",
"top pixel pixel = 906 pixelon = int(baro - pixel) pixels[pixelon] = (RED)",
"pixels[36] = (OFF) if icon == 'partly-cloudy-day' or 'partly-cloudy-night': pixels[34] = (BLUE) else:",
"'partly-cloudy-day' or 'partly-cloudy-night': pixels[34] = (BLUE) else: pixels[34] = (OFF) if icon ==",
"CYAN = (0, 255, 255) BLUE = (0, 0, 255) PURPLE = (180,",
"(100, 64, 0) GREEN = (0, 255, 0) CYAN = (0, 255, 255)",
"= neopixel.NeoPixel(board.D18, 144, brightness=0.03, auto_write=False) #Start up Lights n = 1 t_end =",
"icon = data['current_conditions']['icon'] baro = int(data['current_conditions']['sea_level_pressure']) trend = data['current_conditions']['pressure_trend'] print(text) print(icon) print(baro) print(trend)",
"print(baro) print(trend) return trend, baro, icon def barometer(): conditions = getconditions() baro =",
"import neopixel import board #Set Colours RED = (255, 0, 0) YELLOW =",
"int(baro - pixel) pixels[pixelon] = (RED) def trendpixel(): conditions = getconditions() trend =",
"== 'possibly-rainy-night': pixels[30] = (BLUE) else: pixels[30] = (OFF) if icon == 'clear-night':",
"brightness=0.03, auto_write=False) #Start up Lights n = 1 t_end = time.time() + 22.32",
"try: response = requests.get('https://swd.weatherflow.com/swd/rest/better_forecast?api_key=db55228a-b708-4325-9166-7f2d04c61baa&station_id=50216&units_temp=c&units_wind=mph&units_pressure=mb&units_precip=mm&units_distance=mi').text except requests.exceptions.RequestException as e: time.sleep(60) data = json.loads(response) text",
"icon == 'partly-cloudy-day' or 'partly-cloudy-night': pixels[34] = (BLUE) else: pixels[34] = (OFF) if",
"255) OFF = (0, 0, 0) #Set NeoPixel Details - Pin/Number Pixels/Brightness etc",
"pixels.show() time.sleep (0.1) pixels.fill((0, 0, 0)) pixels.show() print (\"Getting Conditions and Forecast\") def",
"pixel) pixels[pixelon] = (RED) def trendpixel(): conditions = getconditions() trend = conditions[0] if",
"== 'cloudy': pixels[32] = (BLUE) else: pixels[32] = (OFF) if icon == 'possibly-rainy-day':",
"pixels[30] = (BLUE) else: pixels[30] = (OFF) if icon == 'clear-night': pixels[22] =",
"(\"Getting Conditions and Forecast\") def getconditions(): # Get Data from Weather Flow for",
"etc pixels = neopixel.NeoPixel(board.D18, 144, brightness=0.03, auto_write=False) #Start up Lights n = 1",
"Pressure top 1050 minus number of pixels to set top pixel pixel =",
"= (BLUE) else: pixels[22] = (OFF) while True: getconditions() barometer() trendpixel() icon() pixels.show()",
"= 1 pixels[n] = (RED) pixels[n-1] = (YELLOW) pixels.show() time.sleep (0.1) pixels.fill((0, 0,",
"64, 0) GREEN = (0, 255, 0) CYAN = (0, 255, 255) BLUE",
"(0, 255, 255) BLUE = (0, 0, 255) PURPLE = (180, 0, 255)",
"n = 1 t_end = time.time() + 22.32 * 1 while time.time() <",
"json.loads(response) text = data['current_conditions']['conditions'] icon = data['current_conditions']['icon'] baro = int(data['current_conditions']['sea_level_pressure']) trend = data['current_conditions']['pressure_trend']",
"906 pixelon = int(baro - pixel) pixels[pixelon] = (RED) def trendpixel(): conditions =",
"pixels[12] = (OFF) def icon(): conditions = getconditions() icon = str(conditions[2]) print(\"Icon\") print(icon)",
"minus number of pixels to set top pixel pixel = 906 pixelon =",
"(BLUE) else: pixels[30] = (OFF) if icon == 'possibly-rainy-night': pixels[30] = (BLUE) else:",
"= 1 t_end = time.time() + 22.32 * 1 while time.time() < t_end:",
"from Weather Flow for Station Location try: response = requests.get('https://swd.weatherflow.com/swd/rest/better_forecast?api_key=db55228a-b708-4325-9166-7f2d04c61baa&station_id=50216&units_temp=c&units_wind=mph&units_pressure=mb&units_precip=mm&units_distance=mi').text except requests.exceptions.RequestException as",
"= data['current_conditions']['pressure_trend'] print(text) print(icon) print(baro) print(trend) return trend, baro, icon def barometer(): conditions",
"BLUE = (0, 0, 255) PURPLE = (180, 0, 255) OFF = (0,",
"import requests import json import time import neopixel import board #Set Colours RED",
"= getconditions() baro = conditions[1] # Pressure top 1050 minus number of pixels",
"= getconditions() icon = str(conditions[2]) print(\"Icon\") print(icon) if icon == 'clear-day': pixels[36] =",
"def barometer(): conditions = getconditions() baro = conditions[1] # Pressure top 1050 minus",
"(OFF) if trend == 'rising': pixels[16] = (BLUE) else: pixels[16] = (OFF) if",
"requests.get('https://swd.weatherflow.com/swd/rest/better_forecast?api_key=db55228a-b708-4325-9166-7f2d04c61baa&station_id=50216&units_temp=c&units_wind=mph&units_pressure=mb&units_precip=mm&units_distance=mi').text except requests.exceptions.RequestException as e: time.sleep(60) data = json.loads(response) text = data['current_conditions']['conditions'] icon",
"import board #Set Colours RED = (255, 0, 0) YELLOW = (255, 150,",
"= (0, 0, 255) PURPLE = (180, 0, 255) OFF = (0, 0,",
"(OFF) if icon == 'partly-cloudy-day' or 'partly-cloudy-night': pixels[34] = (BLUE) else: pixels[34] =",
"'possibly-rainy-day': pixels[30] = (BLUE) else: pixels[30] = (OFF) if icon == 'possibly-rainy-night': pixels[30]",
"OFF = (0, 0, 0) #Set NeoPixel Details - Pin/Number Pixels/Brightness etc pixels",
"while time.time() < t_end: n = n + 1 if n >= 144:",
"+ 1 if n >= 144: n = 1 pixels[n] = (RED) pixels[n-1]",
"n = 1 pixels[n] = (RED) pixels[n-1] = (YELLOW) pixels.show() time.sleep (0.1) pixels.fill((0,",
"0, 255) OFF = (0, 0, 0) #Set NeoPixel Details - Pin/Number Pixels/Brightness",
"= (OFF) if trend == 'rising': pixels[16] = (BLUE) else: pixels[16] = (OFF)",
"pixels[34] = (OFF) if icon == 'cloudy': pixels[32] = (BLUE) else: pixels[32] =",
"RED = (255, 0, 0) YELLOW = (255, 150, 0) ORANGE = (100,",
"= data['current_conditions']['icon'] baro = int(data['current_conditions']['sea_level_pressure']) trend = data['current_conditions']['pressure_trend'] print(text) print(icon) print(baro) print(trend) return",
"'cloudy': pixels[32] = (BLUE) else: pixels[32] = (OFF) if icon == 'possibly-rainy-day': pixels[30]",
"pixels = neopixel.NeoPixel(board.D18, 144, brightness=0.03, auto_write=False) #Start up Lights n = 1 t_end",
"conditions = getconditions() trend = conditions[0] if trend == 'steady': pixels[14] = (GREEN)",
"'partly-cloudy-night': pixels[34] = (BLUE) else: pixels[34] = (OFF) if icon == 'cloudy': pixels[32]",
"Pin/Number Pixels/Brightness etc pixels = neopixel.NeoPixel(board.D18, 144, brightness=0.03, auto_write=False) #Start up Lights n",
"== 'steady': pixels[14] = (GREEN) else: pixels[14] = (OFF) if trend == 'rising':",
"time import neopixel import board #Set Colours RED = (255, 0, 0) YELLOW",
"if icon == 'cloudy': pixels[32] = (BLUE) else: pixels[32] = (OFF) if icon",
"(OFF) if icon == 'possibly-rainy-night': pixels[30] = (BLUE) else: pixels[30] = (OFF) if",
"255, 0) CYAN = (0, 255, 255) BLUE = (0, 0, 255) PURPLE",
"= conditions[0] if trend == 'steady': pixels[14] = (GREEN) else: pixels[14] = (OFF)",
"pixels[16] = (BLUE) else: pixels[16] = (OFF) if trend == 'falling': pixels[12] =",
"= (100, 64, 0) GREEN = (0, 255, 0) CYAN = (0, 255,",
"< t_end: n = n + 1 if n >= 144: n =",
"to set top pixel pixel = 906 pixelon = int(baro - pixel) pixels[pixelon]",
"trend = conditions[0] if trend == 'steady': pixels[14] = (GREEN) else: pixels[14] =",
"getconditions() icon = str(conditions[2]) print(\"Icon\") print(icon) if icon == 'clear-day': pixels[36] = (YELLOW)",
"pixels[30] = (BLUE) else: pixels[30] = (OFF) if icon == 'possibly-rainy-night': pixels[30] =",
"pixels[14] = (GREEN) else: pixels[14] = (OFF) if trend == 'rising': pixels[16] =",
"= (GREEN) else: pixels[14] = (OFF) if trend == 'rising': pixels[16] = (BLUE)",
"data['current_conditions']['icon'] baro = int(data['current_conditions']['sea_level_pressure']) trend = data['current_conditions']['pressure_trend'] print(text) print(icon) print(baro) print(trend) return trend,",
"0)) pixels.show() print (\"Getting Conditions and Forecast\") def getconditions(): # Get Data from",
"0) YELLOW = (255, 150, 0) ORANGE = (100, 64, 0) GREEN =",
"(YELLOW) pixels.show() time.sleep (0.1) pixels.fill((0, 0, 0)) pixels.show() print (\"Getting Conditions and Forecast\")",
"(OFF) if icon == 'possibly-rainy-day': pixels[30] = (BLUE) else: pixels[30] = (OFF) if",
"1 while time.time() < t_end: n = n + 1 if n >=",
"GREEN = (0, 255, 0) CYAN = (0, 255, 255) BLUE = (0,",
"Details - Pin/Number Pixels/Brightness etc pixels = neopixel.NeoPixel(board.D18, 144, brightness=0.03, auto_write=False) #Start up",
"if icon == 'possibly-rainy-day': pixels[30] = (BLUE) else: pixels[30] = (OFF) if icon",
"icon = str(conditions[2]) print(\"Icon\") print(icon) if icon == 'clear-day': pixels[36] = (YELLOW) else:",
"= requests.get('https://swd.weatherflow.com/swd/rest/better_forecast?api_key=db55228a-b708-4325-9166-7f2d04c61baa&station_id=50216&units_temp=c&units_wind=mph&units_pressure=mb&units_precip=mm&units_distance=mi').text except requests.exceptions.RequestException as e: time.sleep(60) data = json.loads(response) text = data['current_conditions']['conditions']",
"board #Set Colours RED = (255, 0, 0) YELLOW = (255, 150, 0)",
"icon(): conditions = getconditions() icon = str(conditions[2]) print(\"Icon\") print(icon) if icon == 'clear-day':",
"neopixel import board #Set Colours RED = (255, 0, 0) YELLOW = (255,",
"== 'falling': pixels[12] = (RED) else: pixels[12] = (OFF) def icon(): conditions =",
"print(icon) print(baro) print(trend) return trend, baro, icon def barometer(): conditions = getconditions() baro",
"print(\"Icon\") print(icon) if icon == 'clear-day': pixels[36] = (YELLOW) else: pixels[36] = (OFF)",
"(OFF) if trend == 'falling': pixels[12] = (RED) else: pixels[12] = (OFF) def",
"except requests.exceptions.RequestException as e: time.sleep(60) data = json.loads(response) text = data['current_conditions']['conditions'] icon =",
"= (RED) def trendpixel(): conditions = getconditions() trend = conditions[0] if trend ==",
"PURPLE = (180, 0, 255) OFF = (0, 0, 0) #Set NeoPixel Details",
"#Set Colours RED = (255, 0, 0) YELLOW = (255, 150, 0) ORANGE",
"(OFF) if icon == 'cloudy': pixels[32] = (BLUE) else: pixels[32] = (OFF) if",
"if icon == 'partly-cloudy-day' or 'partly-cloudy-night': pixels[34] = (BLUE) else: pixels[34] = (OFF)",
"else: pixels[30] = (OFF) if icon == 'clear-night': pixels[22] = (BLUE) else: pixels[22]",
"(OFF) if icon == 'clear-night': pixels[22] = (BLUE) else: pixels[22] = (OFF) while",
"255, 255) BLUE = (0, 0, 255) PURPLE = (180, 0, 255) OFF",
"150, 0) ORANGE = (100, 64, 0) GREEN = (0, 255, 0) CYAN",
"= (RED) pixels[n-1] = (YELLOW) pixels.show() time.sleep (0.1) pixels.fill((0, 0, 0)) pixels.show() print",
"(BLUE) else: pixels[22] = (OFF) while True: getconditions() barometer() trendpixel() icon() pixels.show() time.sleep(60)",
"icon == 'possibly-rainy-day': pixels[30] = (BLUE) else: pixels[30] = (OFF) if icon ==",
"- Pin/Number Pixels/Brightness etc pixels = neopixel.NeoPixel(board.D18, 144, brightness=0.03, auto_write=False) #Start up Lights",
"else: pixels[16] = (OFF) if trend == 'falling': pixels[12] = (RED) else: pixels[12]",
"(180, 0, 255) OFF = (0, 0, 0) #Set NeoPixel Details - Pin/Number",
"up Lights n = 1 t_end = time.time() + 22.32 * 1 while",
"t_end: n = n + 1 if n >= 144: n = 1",
"import time import neopixel import board #Set Colours RED = (255, 0, 0)",
"else: pixels[36] = (OFF) if icon == 'partly-cloudy-day' or 'partly-cloudy-night': pixels[34] = (BLUE)",
"= (BLUE) else: pixels[32] = (OFF) if icon == 'possibly-rainy-day': pixels[30] = (BLUE)",
"0, 255) PURPLE = (180, 0, 255) OFF = (0, 0, 0) #Set",
"= (OFF) if trend == 'falling': pixels[12] = (RED) else: pixels[12] = (OFF)",
"baro = conditions[1] # Pressure top 1050 minus number of pixels to set",
"== 'possibly-rainy-day': pixels[30] = (BLUE) else: pixels[30] = (OFF) if icon == 'possibly-rainy-night':",
"baro = int(data['current_conditions']['sea_level_pressure']) trend = data['current_conditions']['pressure_trend'] print(text) print(icon) print(baro) print(trend) return trend, baro,",
"Lights n = 1 t_end = time.time() + 22.32 * 1 while time.time()",
"trend == 'steady': pixels[14] = (GREEN) else: pixels[14] = (OFF) if trend ==",
"Data from Weather Flow for Station Location try: response = requests.get('https://swd.weatherflow.com/swd/rest/better_forecast?api_key=db55228a-b708-4325-9166-7f2d04c61baa&station_id=50216&units_temp=c&units_wind=mph&units_pressure=mb&units_precip=mm&units_distance=mi').text except requests.exceptions.RequestException",
"= json.loads(response) text = data['current_conditions']['conditions'] icon = data['current_conditions']['icon'] baro = int(data['current_conditions']['sea_level_pressure']) trend =",
"if icon == 'clear-day': pixels[36] = (YELLOW) else: pixels[36] = (OFF) if icon",
"pixels[22] = (BLUE) else: pixels[22] = (OFF) while True: getconditions() barometer() trendpixel() icon()",
"pixel pixel = 906 pixelon = int(baro - pixel) pixels[pixelon] = (RED) def",
"0, 0) YELLOW = (255, 150, 0) ORANGE = (100, 64, 0) GREEN",
"Station Location try: response = requests.get('https://swd.weatherflow.com/swd/rest/better_forecast?api_key=db55228a-b708-4325-9166-7f2d04c61baa&station_id=50216&units_temp=c&units_wind=mph&units_pressure=mb&units_precip=mm&units_distance=mi').text except requests.exceptions.RequestException as e: time.sleep(60) data =",
"conditions = getconditions() baro = conditions[1] # Pressure top 1050 minus number of",
"print(trend) return trend, baro, icon def barometer(): conditions = getconditions() baro = conditions[1]",
"= (0, 255, 255) BLUE = (0, 0, 255) PURPLE = (180, 0,",
"print (\"Getting Conditions and Forecast\") def getconditions(): # Get Data from Weather Flow",
"(0, 0, 255) PURPLE = (180, 0, 255) OFF = (0, 0, 0)",
"neopixel.NeoPixel(board.D18, 144, brightness=0.03, auto_write=False) #Start up Lights n = 1 t_end = time.time()",
"auto_write=False) #Start up Lights n = 1 t_end = time.time() + 22.32 *",
"text = data['current_conditions']['conditions'] icon = data['current_conditions']['icon'] baro = int(data['current_conditions']['sea_level_pressure']) trend = data['current_conditions']['pressure_trend'] print(text)",
"data = json.loads(response) text = data['current_conditions']['conditions'] icon = data['current_conditions']['icon'] baro = int(data['current_conditions']['sea_level_pressure']) trend",
"= int(data['current_conditions']['sea_level_pressure']) trend = data['current_conditions']['pressure_trend'] print(text) print(icon) print(baro) print(trend) return trend, baro, icon",
"number of pixels to set top pixel pixel = 906 pixelon = int(baro",
"0) ORANGE = (100, 64, 0) GREEN = (0, 255, 0) CYAN =",
"getconditions() baro = conditions[1] # Pressure top 1050 minus number of pixels to",
"Get Data from Weather Flow for Station Location try: response = requests.get('https://swd.weatherflow.com/swd/rest/better_forecast?api_key=db55228a-b708-4325-9166-7f2d04c61baa&station_id=50216&units_temp=c&units_wind=mph&units_pressure=mb&units_precip=mm&units_distance=mi').text except",
"pixels[16] = (OFF) if trend == 'falling': pixels[12] = (RED) else: pixels[12] =",
"0) #Set NeoPixel Details - Pin/Number Pixels/Brightness etc pixels = neopixel.NeoPixel(board.D18, 144, brightness=0.03,",
"return trend, baro, icon def barometer(): conditions = getconditions() baro = conditions[1] #",
"pixels[14] = (OFF) if trend == 'rising': pixels[16] = (BLUE) else: pixels[16] =",
"icon == 'clear-day': pixels[36] = (YELLOW) else: pixels[36] = (OFF) if icon ==",
"= 906 pixelon = int(baro - pixel) pixels[pixelon] = (RED) def trendpixel(): conditions",
"= (OFF) if icon == 'possibly-rainy-night': pixels[30] = (BLUE) else: pixels[30] = (OFF)",
"(0, 0, 0) #Set NeoPixel Details - Pin/Number Pixels/Brightness etc pixels = neopixel.NeoPixel(board.D18,",
"e: time.sleep(60) data = json.loads(response) text = data['current_conditions']['conditions'] icon = data['current_conditions']['icon'] baro =",
"(255, 150, 0) ORANGE = (100, 64, 0) GREEN = (0, 255, 0)",
"as e: time.sleep(60) data = json.loads(response) text = data['current_conditions']['conditions'] icon = data['current_conditions']['icon'] baro",
"(RED) else: pixels[12] = (OFF) def icon(): conditions = getconditions() icon = str(conditions[2])",
"= str(conditions[2]) print(\"Icon\") print(icon) if icon == 'clear-day': pixels[36] = (YELLOW) else: pixels[36]",
"= (180, 0, 255) OFF = (0, 0, 0) #Set NeoPixel Details -",
"22.32 * 1 while time.time() < t_end: n = n + 1 if",
"= (OFF) if icon == 'clear-night': pixels[22] = (BLUE) else: pixels[22] = (OFF)",
"'clear-day': pixels[36] = (YELLOW) else: pixels[36] = (OFF) if icon == 'partly-cloudy-day' or",
"#Set NeoPixel Details - Pin/Number Pixels/Brightness etc pixels = neopixel.NeoPixel(board.D18, 144, brightness=0.03, auto_write=False)",
"n >= 144: n = 1 pixels[n] = (RED) pixels[n-1] = (YELLOW) pixels.show()",
"requests.exceptions.RequestException as e: time.sleep(60) data = json.loads(response) text = data['current_conditions']['conditions'] icon = data['current_conditions']['icon']",
"str(conditions[2]) print(\"Icon\") print(icon) if icon == 'clear-day': pixels[36] = (YELLOW) else: pixels[36] =",
"def icon(): conditions = getconditions() icon = str(conditions[2]) print(\"Icon\") print(icon) if icon ==",
"255) BLUE = (0, 0, 255) PURPLE = (180, 0, 255) OFF =",
"0, 0) #Set NeoPixel Details - Pin/Number Pixels/Brightness etc pixels = neopixel.NeoPixel(board.D18, 144,",
"if trend == 'steady': pixels[14] = (GREEN) else: pixels[14] = (OFF) if trend",
"else: pixels[12] = (OFF) def icon(): conditions = getconditions() icon = str(conditions[2]) print(\"Icon\")",
"pixels.fill((0, 0, 0)) pixels.show() print (\"Getting Conditions and Forecast\") def getconditions(): # Get",
"trend == 'falling': pixels[12] = (RED) else: pixels[12] = (OFF) def icon(): conditions",
"1 if n >= 144: n = 1 pixels[n] = (RED) pixels[n-1] =",
"trendpixel(): conditions = getconditions() trend = conditions[0] if trend == 'steady': pixels[14] =",
"else: pixels[32] = (OFF) if icon == 'possibly-rainy-day': pixels[30] = (BLUE) else: pixels[30]",
"conditions[1] # Pressure top 1050 minus number of pixels to set top pixel",
"0) CYAN = (0, 255, 255) BLUE = (0, 0, 255) PURPLE =",
"'steady': pixels[14] = (GREEN) else: pixels[14] = (OFF) if trend == 'rising': pixels[16]",
"Flow for Station Location try: response = requests.get('https://swd.weatherflow.com/swd/rest/better_forecast?api_key=db55228a-b708-4325-9166-7f2d04c61baa&station_id=50216&units_temp=c&units_wind=mph&units_pressure=mb&units_precip=mm&units_distance=mi').text except requests.exceptions.RequestException as e: time.sleep(60)",
"print(icon) if icon == 'clear-day': pixels[36] = (YELLOW) else: pixels[36] = (OFF) if",
"= int(baro - pixel) pixels[pixelon] = (RED) def trendpixel(): conditions = getconditions() trend",
"(BLUE) else: pixels[30] = (OFF) if icon == 'clear-night': pixels[22] = (BLUE) else:",
"#Start up Lights n = 1 t_end = time.time() + 22.32 * 1",
"top 1050 minus number of pixels to set top pixel pixel = 906",
"# Get Data from Weather Flow for Station Location try: response = requests.get('https://swd.weatherflow.com/swd/rest/better_forecast?api_key=db55228a-b708-4325-9166-7f2d04c61baa&station_id=50216&units_temp=c&units_wind=mph&units_pressure=mb&units_precip=mm&units_distance=mi').text",
"requests import json import time import neopixel import board #Set Colours RED =",
"t_end = time.time() + 22.32 * 1 while time.time() < t_end: n =",
"trend, baro, icon def barometer(): conditions = getconditions() baro = conditions[1] # Pressure",
"int(data['current_conditions']['sea_level_pressure']) trend = data['current_conditions']['pressure_trend'] print(text) print(icon) print(baro) print(trend) return trend, baro, icon def",
"(0.1) pixels.fill((0, 0, 0)) pixels.show() print (\"Getting Conditions and Forecast\") def getconditions(): #",
"and Forecast\") def getconditions(): # Get Data from Weather Flow for Station Location",
"= (255, 0, 0) YELLOW = (255, 150, 0) ORANGE = (100, 64,",
"pixels.show() print (\"Getting Conditions and Forecast\") def getconditions(): # Get Data from Weather",
"def getconditions(): # Get Data from Weather Flow for Station Location try: response",
"(BLUE) else: pixels[32] = (OFF) if icon == 'possibly-rainy-day': pixels[30] = (BLUE) else:",
"getconditions() trend = conditions[0] if trend == 'steady': pixels[14] = (GREEN) else: pixels[14]",
"Forecast\") def getconditions(): # Get Data from Weather Flow for Station Location try:",
"if n >= 144: n = 1 pixels[n] = (RED) pixels[n-1] = (YELLOW)",
"conditions[0] if trend == 'steady': pixels[14] = (GREEN) else: pixels[14] = (OFF) if",
"'rising': pixels[16] = (BLUE) else: pixels[16] = (OFF) if trend == 'falling': pixels[12]",
"time.sleep (0.1) pixels.fill((0, 0, 0)) pixels.show() print (\"Getting Conditions and Forecast\") def getconditions():",
"= (0, 255, 0) CYAN = (0, 255, 255) BLUE = (0, 0,",
"icon == 'clear-night': pixels[22] = (BLUE) else: pixels[22] = (OFF) while True: getconditions()",
"if icon == 'possibly-rainy-night': pixels[30] = (BLUE) else: pixels[30] = (OFF) if icon",
">= 144: n = 1 pixels[n] = (RED) pixels[n-1] = (YELLOW) pixels.show() time.sleep",
"# Pressure top 1050 minus number of pixels to set top pixel pixel",
"(0, 255, 0) CYAN = (0, 255, 255) BLUE = (0, 0, 255)",
"trend == 'rising': pixels[16] = (BLUE) else: pixels[16] = (OFF) if trend ==",
"= (OFF) def icon(): conditions = getconditions() icon = str(conditions[2]) print(\"Icon\") print(icon) if",
"getconditions(): # Get Data from Weather Flow for Station Location try: response =",
"= (OFF) if icon == 'possibly-rainy-day': pixels[30] = (BLUE) else: pixels[30] = (OFF)",
"= n + 1 if n >= 144: n = 1 pixels[n] =",
"= (BLUE) else: pixels[30] = (OFF) if icon == 'clear-night': pixels[22] = (BLUE)",
"pixels[n] = (RED) pixels[n-1] = (YELLOW) pixels.show() time.sleep (0.1) pixels.fill((0, 0, 0)) pixels.show()",
"1 t_end = time.time() + 22.32 * 1 while time.time() < t_end: n",
"import json import time import neopixel import board #Set Colours RED = (255,",
"(BLUE) else: pixels[16] = (OFF) if trend == 'falling': pixels[12] = (RED) else:",
"pixels[32] = (BLUE) else: pixels[32] = (OFF) if icon == 'possibly-rainy-day': pixels[30] =",
"0) GREEN = (0, 255, 0) CYAN = (0, 255, 255) BLUE =",
"= (255, 150, 0) ORANGE = (100, 64, 0) GREEN = (0, 255,",
"= (0, 0, 0) #Set NeoPixel Details - Pin/Number Pixels/Brightness etc pixels =",
"Pixels/Brightness etc pixels = neopixel.NeoPixel(board.D18, 144, brightness=0.03, auto_write=False) #Start up Lights n =",
"= time.time() + 22.32 * 1 while time.time() < t_end: n = n",
"Conditions and Forecast\") def getconditions(): # Get Data from Weather Flow for Station",
"n + 1 if n >= 144: n = 1 pixels[n] = (RED)",
"time.sleep(60) data = json.loads(response) text = data['current_conditions']['conditions'] icon = data['current_conditions']['icon'] baro = int(data['current_conditions']['sea_level_pressure'])",
"of pixels to set top pixel pixel = 906 pixelon = int(baro -",
"pixels[32] = (OFF) if icon == 'possibly-rainy-day': pixels[30] = (BLUE) else: pixels[30] =",
"if trend == 'falling': pixels[12] = (RED) else: pixels[12] = (OFF) def icon():",
"pixels[36] = (YELLOW) else: pixels[36] = (OFF) if icon == 'partly-cloudy-day' or 'partly-cloudy-night':",
"'clear-night': pixels[22] = (BLUE) else: pixels[22] = (OFF) while True: getconditions() barometer() trendpixel()",
"icon == 'cloudy': pixels[32] = (BLUE) else: pixels[32] = (OFF) if icon ==",
"= (BLUE) else: pixels[34] = (OFF) if icon == 'cloudy': pixels[32] = (BLUE)",
"response = requests.get('https://swd.weatherflow.com/swd/rest/better_forecast?api_key=db55228a-b708-4325-9166-7f2d04c61baa&station_id=50216&units_temp=c&units_wind=mph&units_pressure=mb&units_precip=mm&units_distance=mi').text except requests.exceptions.RequestException as e: time.sleep(60) data = json.loads(response) text =",
"= (BLUE) else: pixels[30] = (OFF) if icon == 'possibly-rainy-night': pixels[30] = (BLUE)",
"Colours RED = (255, 0, 0) YELLOW = (255, 150, 0) ORANGE =",
"pixels[34] = (BLUE) else: pixels[34] = (OFF) if icon == 'cloudy': pixels[32] =",
"= conditions[1] # Pressure top 1050 minus number of pixels to set top",
"(BLUE) else: pixels[34] = (OFF) if icon == 'cloudy': pixels[32] = (BLUE) else:",
"pixelon = int(baro - pixel) pixels[pixelon] = (RED) def trendpixel(): conditions = getconditions()",
"YELLOW = (255, 150, 0) ORANGE = (100, 64, 0) GREEN = (0,",
"1050 minus number of pixels to set top pixel pixel = 906 pixelon",
"== 'partly-cloudy-day' or 'partly-cloudy-night': pixels[34] = (BLUE) else: pixels[34] = (OFF) if icon",
"1 pixels[n] = (RED) pixels[n-1] = (YELLOW) pixels.show() time.sleep (0.1) pixels.fill((0, 0, 0))",
"pixel = 906 pixelon = int(baro - pixel) pixels[pixelon] = (RED) def trendpixel():",
"pixels[pixelon] = (RED) def trendpixel(): conditions = getconditions() trend = conditions[0] if trend",
"icon def barometer(): conditions = getconditions() baro = conditions[1] # Pressure top 1050",
"(RED) def trendpixel(): conditions = getconditions() trend = conditions[0] if trend == 'steady':",
"= (OFF) if icon == 'cloudy': pixels[32] = (BLUE) else: pixels[32] = (OFF)",
"time.time() < t_end: n = n + 1 if n >= 144: n",
"= (RED) else: pixels[12] = (OFF) def icon(): conditions = getconditions() icon =",
"pixels[30] = (OFF) if icon == 'possibly-rainy-night': pixels[30] = (BLUE) else: pixels[30] =",
"icon == 'possibly-rainy-night': pixels[30] = (BLUE) else: pixels[30] = (OFF) if icon ==",
"255) PURPLE = (180, 0, 255) OFF = (0, 0, 0) #Set NeoPixel",
"144, brightness=0.03, auto_write=False) #Start up Lights n = 1 t_end = time.time() +",
"== 'rising': pixels[16] = (BLUE) else: pixels[16] = (OFF) if trend == 'falling':",
"(OFF) def icon(): conditions = getconditions() icon = str(conditions[2]) print(\"Icon\") print(icon) if icon",
"= (OFF) if icon == 'partly-cloudy-day' or 'partly-cloudy-night': pixels[34] = (BLUE) else: pixels[34]",
"else: pixels[14] = (OFF) if trend == 'rising': pixels[16] = (BLUE) else: pixels[16]",
"else: pixels[34] = (OFF) if icon == 'cloudy': pixels[32] = (BLUE) else: pixels[32]",
"+ 22.32 * 1 while time.time() < t_end: n = n + 1",
"baro, icon def barometer(): conditions = getconditions() baro = conditions[1] # Pressure top",
"0, 0)) pixels.show() print (\"Getting Conditions and Forecast\") def getconditions(): # Get Data",
"set top pixel pixel = 906 pixelon = int(baro - pixel) pixels[pixelon] =",
"'falling': pixels[12] = (RED) else: pixels[12] = (OFF) def icon(): conditions = getconditions()",
"if icon == 'clear-night': pixels[22] = (BLUE) else: pixels[22] = (OFF) while True:",
"data['current_conditions']['pressure_trend'] print(text) print(icon) print(baro) print(trend) return trend, baro, icon def barometer(): conditions =",
"(RED) pixels[n-1] = (YELLOW) pixels.show() time.sleep (0.1) pixels.fill((0, 0, 0)) pixels.show() print (\"Getting",
"144: n = 1 pixels[n] = (RED) pixels[n-1] = (YELLOW) pixels.show() time.sleep (0.1)",
"= getconditions() trend = conditions[0] if trend == 'steady': pixels[14] = (GREEN) else:",
"conditions = getconditions() icon = str(conditions[2]) print(\"Icon\") print(icon) if icon == 'clear-day': pixels[36]",
"pixels[n-1] = (YELLOW) pixels.show() time.sleep (0.1) pixels.fill((0, 0, 0)) pixels.show() print (\"Getting Conditions",
"pixels[12] = (RED) else: pixels[12] = (OFF) def icon(): conditions = getconditions() icon",
"* 1 while time.time() < t_end: n = n + 1 if n",
"data['current_conditions']['conditions'] icon = data['current_conditions']['icon'] baro = int(data['current_conditions']['sea_level_pressure']) trend = data['current_conditions']['pressure_trend'] print(text) print(icon) print(baro)",
"'possibly-rainy-night': pixels[30] = (BLUE) else: pixels[30] = (OFF) if icon == 'clear-night': pixels[22]",
"if trend == 'rising': pixels[16] = (BLUE) else: pixels[16] = (OFF) if trend",
"(GREEN) else: pixels[14] = (OFF) if trend == 'rising': pixels[16] = (BLUE) else:",
"trend = data['current_conditions']['pressure_trend'] print(text) print(icon) print(baro) print(trend) return trend, baro, icon def barometer():",
"for Station Location try: response = requests.get('https://swd.weatherflow.com/swd/rest/better_forecast?api_key=db55228a-b708-4325-9166-7f2d04c61baa&station_id=50216&units_temp=c&units_wind=mph&units_pressure=mb&units_precip=mm&units_distance=mi').text except requests.exceptions.RequestException as e: time.sleep(60) data",
"= (BLUE) else: pixels[16] = (OFF) if trend == 'falling': pixels[12] = (RED)",
"Location try: response = requests.get('https://swd.weatherflow.com/swd/rest/better_forecast?api_key=db55228a-b708-4325-9166-7f2d04c61baa&station_id=50216&units_temp=c&units_wind=mph&units_pressure=mb&units_precip=mm&units_distance=mi').text except requests.exceptions.RequestException as e: time.sleep(60) data = json.loads(response)",
"def trendpixel(): conditions = getconditions() trend = conditions[0] if trend == 'steady': pixels[14]",
"NeoPixel Details - Pin/Number Pixels/Brightness etc pixels = neopixel.NeoPixel(board.D18, 144, brightness=0.03, auto_write=False) #Start",
"pixels[30] = (OFF) if icon == 'clear-night': pixels[22] = (BLUE) else: pixels[22] =",
"ORANGE = (100, 64, 0) GREEN = (0, 255, 0) CYAN = (0,",
"(255, 0, 0) YELLOW = (255, 150, 0) ORANGE = (100, 64, 0)",
"- pixel) pixels[pixelon] = (RED) def trendpixel(): conditions = getconditions() trend = conditions[0]",
"barometer(): conditions = getconditions() baro = conditions[1] # Pressure top 1050 minus number",
"else: pixels[30] = (OFF) if icon == 'possibly-rainy-night': pixels[30] = (BLUE) else: pixels[30]",
"== 'clear-day': pixels[36] = (YELLOW) else: pixels[36] = (OFF) if icon == 'partly-cloudy-day'",
"(YELLOW) else: pixels[36] = (OFF) if icon == 'partly-cloudy-day' or 'partly-cloudy-night': pixels[34] =",
"Weather Flow for Station Location try: response = requests.get('https://swd.weatherflow.com/swd/rest/better_forecast?api_key=db55228a-b708-4325-9166-7f2d04c61baa&station_id=50216&units_temp=c&units_wind=mph&units_pressure=mb&units_precip=mm&units_distance=mi').text except requests.exceptions.RequestException as e:",
"== 'clear-night': pixels[22] = (BLUE) else: pixels[22] = (OFF) while True: getconditions() barometer()"
] |
[
"import Auth class Sxg(Auth): _endpoint1 = \"zones\" _endpoint2 = \"amp/sxg\" _endpoint3 = None",
"from aiocloudflare.commons.auth import Auth class Sxg(Auth): _endpoint1 = \"zones\" _endpoint2 = \"amp/sxg\" _endpoint3",
"aiocloudflare.commons.auth import Auth class Sxg(Auth): _endpoint1 = \"zones\" _endpoint2 = \"amp/sxg\" _endpoint3 ="
] |
[
"bits[-1] = bits[-1].replace('.fpickle', '') template_names = [ 'docs/%s.html' % '-'.join([b for b in",
"Path from projects.models import Project def document(request, project, url): try: project = Project.objects.get(slug=project)",
"docroot = Path(project.get_pickle_path()) # First look for <bits>/index.fpickle, then for <bits>.fpickle bits =",
"projects.models import Project def document(request, project, url): try: project = Project.objects.get(slug=project) except Project.DoesNotExist:",
"b]), 'docs/doc.html' ] return render_to_response(template_names, RequestContext(request, { 'doc': pickle.load(open(doc, 'rb')), 'env': pickle.load(open(docroot.child('globalcontext.pickle'), 'rb')),",
"def document(request, project, url): try: project = Project.objects.get(slug=project) except Project.DoesNotExist: raise Http404 docroot",
"not doc.exists(): raise Http404(\"'%s' does not exist\" % doc) bits[-1] = bits[-1].replace('.fpickle', '')",
"= docroot.child(*bits) if not doc.exists(): bits = bits[:-2] + ['%s.fpickle' % bits[-2]] doc",
"raise Http404 docroot = Path(project.get_pickle_path()) # First look for <bits>/index.fpickle, then for <bits>.fpickle",
"from unipath import FSPath as Path from projects.models import Project def document(request, project,",
"'home': project.get_absolute_url(), 'redirect_from': request.GET.get('from', None), })) def update(request, slug): try: project = Project.objects.get(slug=slug)",
"<bits>/index.fpickle, then for <bits>.fpickle bits = url.strip('/').split('/') + ['index.fpickle'] doc = docroot.child(*bits) if",
"as Path from projects.models import Project def document(request, project, url): try: project =",
"exist\" % doc) bits[-1] = bits[-1].replace('.fpickle', '') template_names = [ 'docs/%s.html' % '-'.join([b",
"'rb')), 'update_date': datetime.datetime.fromtimestamp(docroot.child('last_build').mtime()), 'home': project.get_absolute_url(), 'redirect_from': request.GET.get('from', None), })) def update(request, slug): try:",
"project = Project.objects.get(slug=project) except Project.DoesNotExist: raise Http404 docroot = Path(project.get_pickle_path()) # First look",
"render_to_response, get_object_or_404 from django.template import RequestContext from django.http import Http404, HttpResponse from django.core",
"docroot.child(*bits) if not doc.exists(): raise Http404(\"'%s' does not exist\" % doc) bits[-1] =",
"if not doc.exists(): raise Http404(\"'%s' does not exist\" % doc) bits[-1] = bits[-1].replace('.fpickle',",
"for <bits>/index.fpickle, then for <bits>.fpickle bits = url.strip('/').split('/') + ['index.fpickle'] doc = docroot.child(*bits)",
"import urlresolvers from unipath import FSPath as Path from projects.models import Project def",
"except Project.DoesNotExist: raise Http404 docroot = Path(project.get_pickle_path()) # First look for <bits>/index.fpickle, then",
"'redirect_from': request.GET.get('from', None), })) def update(request, slug): try: project = Project.objects.get(slug=slug) except Project.DoesNotExist:",
"})) def update(request, slug): try: project = Project.objects.get(slug=slug) except Project.DoesNotExist: raise Http404 project.update()",
"get_object_or_404 from django.template import RequestContext from django.http import Http404, HttpResponse from django.core import",
"from projects.models import Project def document(request, project, url): try: project = Project.objects.get(slug=project) except",
"doc.exists(): bits = bits[:-2] + ['%s.fpickle' % bits[-2]] doc = docroot.child(*bits) if not",
"bits = bits[:-2] + ['%s.fpickle' % bits[-2]] doc = docroot.child(*bits) if not doc.exists():",
"] return render_to_response(template_names, RequestContext(request, { 'doc': pickle.load(open(doc, 'rb')), 'env': pickle.load(open(docroot.child('globalcontext.pickle'), 'rb')), 'update_date': datetime.datetime.fromtimestamp(docroot.child('last_build').mtime()),",
"'rb')), 'env': pickle.load(open(docroot.child('globalcontext.pickle'), 'rb')), 'update_date': datetime.datetime.fromtimestamp(docroot.child('last_build').mtime()), 'home': project.get_absolute_url(), 'redirect_from': request.GET.get('from', None), })) def",
"document(request, project, url): try: project = Project.objects.get(slug=project) except Project.DoesNotExist: raise Http404 docroot =",
"doc) bits[-1] = bits[-1].replace('.fpickle', '') template_names = [ 'docs/%s.html' % '-'.join([b for b",
"bits[:-2] + ['%s.fpickle' % bits[-2]] doc = docroot.child(*bits) if not doc.exists(): raise Http404(\"'%s'",
"None), })) def update(request, slug): try: project = Project.objects.get(slug=slug) except Project.DoesNotExist: raise Http404",
"if b]), 'docs/doc.html' ] return render_to_response(template_names, RequestContext(request, { 'doc': pickle.load(open(doc, 'rb')), 'env': pickle.load(open(docroot.child('globalcontext.pickle'),",
"pickle.load(open(doc, 'rb')), 'env': pickle.load(open(docroot.child('globalcontext.pickle'), 'rb')), 'update_date': datetime.datetime.fromtimestamp(docroot.child('last_build').mtime()), 'home': project.get_absolute_url(), 'redirect_from': request.GET.get('from', None), }))",
"from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.http import Http404,",
"update(request, slug): try: project = Project.objects.get(slug=slug) except Project.DoesNotExist: raise Http404 project.update() return HttpResponse('done')",
"= url.strip('/').split('/') + ['index.fpickle'] doc = docroot.child(*bits) if not doc.exists(): bits = bits[:-2]",
"import render_to_response, get_object_or_404 from django.template import RequestContext from django.http import Http404, HttpResponse from",
"= bits[:-2] + ['%s.fpickle' % bits[-2]] doc = docroot.child(*bits) if not doc.exists(): raise",
"pickle.load(open(docroot.child('globalcontext.pickle'), 'rb')), 'update_date': datetime.datetime.fromtimestamp(docroot.child('last_build').mtime()), 'home': project.get_absolute_url(), 'redirect_from': request.GET.get('from', None), })) def update(request, slug):",
"+ ['%s.fpickle' % bits[-2]] doc = docroot.child(*bits) if not doc.exists(): raise Http404(\"'%s' does",
"request.GET.get('from', None), })) def update(request, slug): try: project = Project.objects.get(slug=slug) except Project.DoesNotExist: raise",
"<bits>.fpickle bits = url.strip('/').split('/') + ['index.fpickle'] doc = docroot.child(*bits) if not doc.exists(): bits",
"RequestContext from django.http import Http404, HttpResponse from django.core import urlresolvers from unipath import",
"[ 'docs/%s.html' % '-'.join([b for b in bits if b]), 'docs/doc.html' ] return",
"bits[-2]] doc = docroot.child(*bits) if not doc.exists(): raise Http404(\"'%s' does not exist\" %",
"not exist\" % doc) bits[-1] = bits[-1].replace('.fpickle', '') template_names = [ 'docs/%s.html' %",
"'-'.join([b for b in bits if b]), 'docs/doc.html' ] return render_to_response(template_names, RequestContext(request, {",
"'doc': pickle.load(open(doc, 'rb')), 'env': pickle.load(open(docroot.child('globalcontext.pickle'), 'rb')), 'update_date': datetime.datetime.fromtimestamp(docroot.child('last_build').mtime()), 'home': project.get_absolute_url(), 'redirect_from': request.GET.get('from', None),",
"= bits[-1].replace('.fpickle', '') template_names = [ 'docs/%s.html' % '-'.join([b for b in bits",
"% doc) bits[-1] = bits[-1].replace('.fpickle', '') template_names = [ 'docs/%s.html' % '-'.join([b for",
"import RequestContext from django.http import Http404, HttpResponse from django.core import urlresolvers from unipath",
"django.http import Http404, HttpResponse from django.core import urlresolvers from unipath import FSPath as",
"in bits if b]), 'docs/doc.html' ] return render_to_response(template_names, RequestContext(request, { 'doc': pickle.load(open(doc, 'rb')),",
"for <bits>.fpickle bits = url.strip('/').split('/') + ['index.fpickle'] doc = docroot.child(*bits) if not doc.exists():",
"doc = docroot.child(*bits) if not doc.exists(): raise Http404(\"'%s' does not exist\" % doc)",
"+ ['index.fpickle'] doc = docroot.child(*bits) if not doc.exists(): bits = bits[:-2] + ['%s.fpickle'",
"raise Http404(\"'%s' does not exist\" % doc) bits[-1] = bits[-1].replace('.fpickle', '') template_names =",
"project.get_absolute_url(), 'redirect_from': request.GET.get('from', None), })) def update(request, slug): try: project = Project.objects.get(slug=slug) except",
"look for <bits>/index.fpickle, then for <bits>.fpickle bits = url.strip('/').split('/') + ['index.fpickle'] doc =",
"def update(request, slug): try: project = Project.objects.get(slug=slug) except Project.DoesNotExist: raise Http404 project.update() return",
"FSPath as Path from projects.models import Project def document(request, project, url): try: project",
"django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.http import Http404, HttpResponse",
"pickle import datetime from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from",
"bits[-1].replace('.fpickle', '') template_names = [ 'docs/%s.html' % '-'.join([b for b in bits if",
"= Project.objects.get(slug=project) except Project.DoesNotExist: raise Http404 docroot = Path(project.get_pickle_path()) # First look for",
"['%s.fpickle' % bits[-2]] doc = docroot.child(*bits) if not doc.exists(): raise Http404(\"'%s' does not",
"{ 'doc': pickle.load(open(doc, 'rb')), 'env': pickle.load(open(docroot.child('globalcontext.pickle'), 'rb')), 'update_date': datetime.datetime.fromtimestamp(docroot.child('last_build').mtime()), 'home': project.get_absolute_url(), 'redirect_from': request.GET.get('from',",
"project, url): try: project = Project.objects.get(slug=project) except Project.DoesNotExist: raise Http404 docroot = Path(project.get_pickle_path())",
"import FSPath as Path from projects.models import Project def document(request, project, url): try:",
"try: project = Project.objects.get(slug=project) except Project.DoesNotExist: raise Http404 docroot = Path(project.get_pickle_path()) # First",
"= docroot.child(*bits) if not doc.exists(): raise Http404(\"'%s' does not exist\" % doc) bits[-1]",
"cPickle as pickle import datetime from django.shortcuts import render_to_response, get_object_or_404 from django.template import",
"Project def document(request, project, url): try: project = Project.objects.get(slug=project) except Project.DoesNotExist: raise Http404",
"render_to_response(template_names, RequestContext(request, { 'doc': pickle.load(open(doc, 'rb')), 'env': pickle.load(open(docroot.child('globalcontext.pickle'), 'rb')), 'update_date': datetime.datetime.fromtimestamp(docroot.child('last_build').mtime()), 'home': project.get_absolute_url(),",
"= Path(project.get_pickle_path()) # First look for <bits>/index.fpickle, then for <bits>.fpickle bits = url.strip('/').split('/')",
"Http404 docroot = Path(project.get_pickle_path()) # First look for <bits>/index.fpickle, then for <bits>.fpickle bits",
"then for <bits>.fpickle bits = url.strip('/').split('/') + ['index.fpickle'] doc = docroot.child(*bits) if not",
"bits if b]), 'docs/doc.html' ] return render_to_response(template_names, RequestContext(request, { 'doc': pickle.load(open(doc, 'rb')), 'env':",
"'update_date': datetime.datetime.fromtimestamp(docroot.child('last_build').mtime()), 'home': project.get_absolute_url(), 'redirect_from': request.GET.get('from', None), })) def update(request, slug): try: project",
"from django.http import Http404, HttpResponse from django.core import urlresolvers from unipath import FSPath",
"return render_to_response(template_names, RequestContext(request, { 'doc': pickle.load(open(doc, 'rb')), 'env': pickle.load(open(docroot.child('globalcontext.pickle'), 'rb')), 'update_date': datetime.datetime.fromtimestamp(docroot.child('last_build').mtime()), 'home':",
"url.strip('/').split('/') + ['index.fpickle'] doc = docroot.child(*bits) if not doc.exists(): bits = bits[:-2] +",
"import Http404, HttpResponse from django.core import urlresolvers from unipath import FSPath as Path",
"b in bits if b]), 'docs/doc.html' ] return render_to_response(template_names, RequestContext(request, { 'doc': pickle.load(open(doc,",
"from django.template import RequestContext from django.http import Http404, HttpResponse from django.core import urlresolvers",
"import Project def document(request, project, url): try: project = Project.objects.get(slug=project) except Project.DoesNotExist: raise",
"datetime.datetime.fromtimestamp(docroot.child('last_build').mtime()), 'home': project.get_absolute_url(), 'redirect_from': request.GET.get('from', None), })) def update(request, slug): try: project =",
"Project.objects.get(slug=project) except Project.DoesNotExist: raise Http404 docroot = Path(project.get_pickle_path()) # First look for <bits>/index.fpickle,",
"Http404(\"'%s' does not exist\" % doc) bits[-1] = bits[-1].replace('.fpickle', '') template_names = [",
"unipath import FSPath as Path from projects.models import Project def document(request, project, url):",
"'docs/%s.html' % '-'.join([b for b in bits if b]), 'docs/doc.html' ] return render_to_response(template_names,",
"HttpResponse from django.core import urlresolvers from unipath import FSPath as Path from projects.models",
"doc = docroot.child(*bits) if not doc.exists(): bits = bits[:-2] + ['%s.fpickle' % bits[-2]]",
"Path(project.get_pickle_path()) # First look for <bits>/index.fpickle, then for <bits>.fpickle bits = url.strip('/').split('/') +",
"'env': pickle.load(open(docroot.child('globalcontext.pickle'), 'rb')), 'update_date': datetime.datetime.fromtimestamp(docroot.child('last_build').mtime()), 'home': project.get_absolute_url(), 'redirect_from': request.GET.get('from', None), })) def update(request,",
"Project.DoesNotExist: raise Http404 docroot = Path(project.get_pickle_path()) # First look for <bits>/index.fpickle, then for",
"First look for <bits>/index.fpickle, then for <bits>.fpickle bits = url.strip('/').split('/') + ['index.fpickle'] doc",
"% '-'.join([b for b in bits if b]), 'docs/doc.html' ] return render_to_response(template_names, RequestContext(request,",
"urlresolvers from unipath import FSPath as Path from projects.models import Project def document(request,",
"datetime from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.http import",
"import datetime from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.http",
"RequestContext(request, { 'doc': pickle.load(open(doc, 'rb')), 'env': pickle.load(open(docroot.child('globalcontext.pickle'), 'rb')), 'update_date': datetime.datetime.fromtimestamp(docroot.child('last_build').mtime()), 'home': project.get_absolute_url(), 'redirect_from':",
"for b in bits if b]), 'docs/doc.html' ] return render_to_response(template_names, RequestContext(request, { 'doc':",
"Http404, HttpResponse from django.core import urlresolvers from unipath import FSPath as Path from",
"from django.core import urlresolvers from unipath import FSPath as Path from projects.models import",
"'docs/doc.html' ] return render_to_response(template_names, RequestContext(request, { 'doc': pickle.load(open(doc, 'rb')), 'env': pickle.load(open(docroot.child('globalcontext.pickle'), 'rb')), 'update_date':",
"does not exist\" % doc) bits[-1] = bits[-1].replace('.fpickle', '') template_names = [ 'docs/%s.html'",
"django.template import RequestContext from django.http import Http404, HttpResponse from django.core import urlresolvers from",
"as pickle import datetime from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext",
"% bits[-2]] doc = docroot.child(*bits) if not doc.exists(): raise Http404(\"'%s' does not exist\"",
"= [ 'docs/%s.html' % '-'.join([b for b in bits if b]), 'docs/doc.html' ]",
"bits = url.strip('/').split('/') + ['index.fpickle'] doc = docroot.child(*bits) if not doc.exists(): bits =",
"['index.fpickle'] doc = docroot.child(*bits) if not doc.exists(): bits = bits[:-2] + ['%s.fpickle' %",
"if not doc.exists(): bits = bits[:-2] + ['%s.fpickle' % bits[-2]] doc = docroot.child(*bits)",
"docroot.child(*bits) if not doc.exists(): bits = bits[:-2] + ['%s.fpickle' % bits[-2]] doc =",
"import cPickle as pickle import datetime from django.shortcuts import render_to_response, get_object_or_404 from django.template",
"django.core import urlresolvers from unipath import FSPath as Path from projects.models import Project",
"doc.exists(): raise Http404(\"'%s' does not exist\" % doc) bits[-1] = bits[-1].replace('.fpickle', '') template_names",
"url): try: project = Project.objects.get(slug=project) except Project.DoesNotExist: raise Http404 docroot = Path(project.get_pickle_path()) #",
"template_names = [ 'docs/%s.html' % '-'.join([b for b in bits if b]), 'docs/doc.html'",
"not doc.exists(): bits = bits[:-2] + ['%s.fpickle' % bits[-2]] doc = docroot.child(*bits) if",
"# First look for <bits>/index.fpickle, then for <bits>.fpickle bits = url.strip('/').split('/') + ['index.fpickle']",
"'') template_names = [ 'docs/%s.html' % '-'.join([b for b in bits if b]),"
] |
[
": str, shift : int) -> str: uncesar_message = '' for alpha in",
"= 0 shift = None fog_num = None fog_pos = None code_message =",
"fog_num, fog_pos, code_message def clear(message : str, fog_num : int, fog_pos : int)",
"2 ROLLBACK = 90 SECURITY = 'access denied\\n' SHIFT = 0 def verify_code(message",
"fog_pos : int) -> str: clear_message = '' i = FLOOR for alpha",
"== FOG_POS: fog_pos = alpha else: code_message += alpha if alpha == END_LINE:",
"+ FLOOR: uncesar_message += chr(ord_ascii+ROLLBACK-shift) else: uncesar_message += chr(ord(alpha)-shift) return uncesar_message def main():",
"shift, fog_num, fog_pos, code_message = verify_code(encrypt_message) if shift != None and fog_num !=",
"= None code_message = '' for alpha in message: if i == SHIFT:",
"= '' with open(\"code.txt\", \"r\") as file: encrypt_message = file.read() shift, fog_num, fog_pos,",
"uncesar decrypt_message = uncesar(clear_message, ord(shift)) # export with open('message.txt', 'w') as file: file.write(decrypt_message)",
"= 1 FOG_POS = 2 ROLLBACK = 90 SECURITY = 'access denied\\n' SHIFT",
"ROLLBACK = 90 SECURITY = 'access denied\\n' SHIFT = 0 def verify_code(message :",
"i+=1 return shift, fog_num, fog_pos, code_message def clear(message : str, fog_num : int,",
"in message: if i > fog_num: i = FLOOR if i == fog_pos:",
"== FOG_NUM: fog_num = alpha elif i == FOG_POS: fog_pos = alpha else:",
"END_LINE: with open(\"code.txt\", \"w\") as file: file.write(SECURITY) break i+=1 return shift, fog_num, fog_pos,",
"open('message.txt', 'w') as file: file.write(decrypt_message) except: print('There is a problem with: code.txt, Tip:",
"str: uncesar_message = '' for alpha in message: ord_ascii = ord(alpha) if ord_ascii",
"+= chr(ord_ascii+ROLLBACK-shift) else: uncesar_message += chr(ord(alpha)-shift) return uncesar_message def main(): try: # open,",
"= '' for alpha in message: if i == SHIFT: shift = alpha",
"fog_num : int, fog_pos : int) -> str: clear_message = '' i =",
"break i+=1 return shift, fog_num, fog_pos, code_message def clear(message : str, fog_num :",
"file: file.write(SECURITY) break i+=1 return shift, fog_num, fog_pos, code_message def clear(message : str,",
"uncesar(message : str, shift : int) -> str: uncesar_message = '' for alpha",
"and fog_pos != None: # clear clear_message = clear(code_message, ord(fog_num), ord(fog_pos)) # uncesar",
"i = FLOOR if i == fog_pos: clear_message += alpha i += 1",
"None and fog_num != None and fog_pos != None: # clear clear_message =",
"message: if i == SHIFT: shift = alpha elif i == FOG_NUM: fog_num",
"i > fog_num: i = FLOOR if i == fog_pos: clear_message += alpha",
"= 122 END_LINE = '\\n' FLOOR = 32 FOG_NUM = 1 FOG_POS =",
"ord(shift)) # export with open('message.txt', 'w') as file: file.write(decrypt_message) except: print('There is a",
"END_LINE = '\\n' FLOOR = 32 FOG_NUM = 1 FOG_POS = 2 ROLLBACK",
"'w') as file: file.write(decrypt_message) except: print('There is a problem with: code.txt, Tip: verify",
"is a problem with: code.txt, Tip: verify the path') if __name__ == '__main__':",
"<= shift + FLOOR: uncesar_message += chr(ord_ascii+ROLLBACK-shift) else: uncesar_message += chr(ord(alpha)-shift) return uncesar_message",
"except: print('There is a problem with: code.txt, Tip: verify the path') if __name__",
"fog_pos != None: # clear clear_message = clear(code_message, ord(fog_num), ord(fog_pos)) # uncesar decrypt_message",
"fog_pos, code_message = verify_code(encrypt_message) if shift != None and fog_num != None and",
"= ord(alpha) if ord_ascii <= shift + FLOOR: uncesar_message += chr(ord_ascii+ROLLBACK-shift) else: uncesar_message",
"\"r\") as file: encrypt_message = file.read() shift, fog_num, fog_pos, code_message = verify_code(encrypt_message) if",
"FLOOR if i == fog_pos: clear_message += alpha i += 1 return clear_message",
"'' for alpha in message: ord_ascii = ord(alpha) if ord_ascii <= shift +",
"FOG_NUM: fog_num = alpha elif i == FOG_POS: fog_pos = alpha else: code_message",
"decrypt_message = uncesar(clear_message, ord(shift)) # export with open('message.txt', 'w') as file: file.write(decrypt_message) except:",
"= None fog_pos = None code_message = '' for alpha in message: if",
"i = FLOOR for alpha in message: if i > fog_num: i =",
"None: # clear clear_message = clear(code_message, ord(fog_num), ord(fog_pos)) # uncesar decrypt_message = uncesar(clear_message,",
"code_message += alpha if alpha == END_LINE: with open(\"code.txt\", \"w\") as file: file.write(SECURITY)",
"= alpha else: code_message += alpha if alpha == END_LINE: with open(\"code.txt\", \"w\")",
"90 SECURITY = 'access denied\\n' SHIFT = 0 def verify_code(message : str) ->",
"== END_LINE: with open(\"code.txt\", \"w\") as file: file.write(SECURITY) break i+=1 return shift, fog_num,",
"file: file.write(decrypt_message) except: print('There is a problem with: code.txt, Tip: verify the path')",
": str) -> list: i = 0 shift = None fog_num = None",
"= 'access denied\\n' SHIFT = 0 def verify_code(message : str) -> list: i",
"alpha if alpha == END_LINE: with open(\"code.txt\", \"w\") as file: file.write(SECURITY) break i+=1",
": str, fog_num : int, fog_pos : int) -> str: clear_message = ''",
"return uncesar_message def main(): try: # open, read and verify encrypt_message = ''",
"open, read and verify encrypt_message = '' with open(\"code.txt\", \"r\") as file: encrypt_message",
"# uncesar decrypt_message = uncesar(clear_message, ord(shift)) # export with open('message.txt', 'w') as file:",
"ord_ascii = ord(alpha) if ord_ascii <= shift + FLOOR: uncesar_message += chr(ord_ascii+ROLLBACK-shift) else:",
"as file: encrypt_message = file.read() shift, fog_num, fog_pos, code_message = verify_code(encrypt_message) if shift",
"file.read() shift, fog_num, fog_pos, code_message = verify_code(encrypt_message) if shift != None and fog_num",
"clear clear_message = clear(code_message, ord(fog_num), ord(fog_pos)) # uncesar decrypt_message = uncesar(clear_message, ord(shift)) #",
"i += 1 return clear_message def uncesar(message : str, shift : int) ->",
"'' for alpha in message: if i == SHIFT: shift = alpha elif",
"and verify encrypt_message = '' with open(\"code.txt\", \"r\") as file: encrypt_message = file.read()",
"1 return clear_message def uncesar(message : str, shift : int) -> str: uncesar_message",
"= 32 FOG_NUM = 1 FOG_POS = 2 ROLLBACK = 90 SECURITY =",
"0 def verify_code(message : str) -> list: i = 0 shift = None",
"= FLOOR if i == fog_pos: clear_message += alpha i += 1 return",
"alpha else: code_message += alpha if alpha == END_LINE: with open(\"code.txt\", \"w\") as",
"122 END_LINE = '\\n' FLOOR = 32 FOG_NUM = 1 FOG_POS = 2",
"ord(alpha) if ord_ascii <= shift + FLOOR: uncesar_message += chr(ord_ascii+ROLLBACK-shift) else: uncesar_message +=",
"= verify_code(encrypt_message) if shift != None and fog_num != None and fog_pos !=",
"open(\"code.txt\", \"w\") as file: file.write(SECURITY) break i+=1 return shift, fog_num, fog_pos, code_message def",
"verify encrypt_message = '' with open(\"code.txt\", \"r\") as file: encrypt_message = file.read() shift,",
"= 2 ROLLBACK = 90 SECURITY = 'access denied\\n' SHIFT = 0 def",
"'access denied\\n' SHIFT = 0 def verify_code(message : str) -> list: i =",
"print('There is a problem with: code.txt, Tip: verify the path') if __name__ ==",
"= '' i = FLOOR for alpha in message: if i > fog_num:",
"read and verify encrypt_message = '' with open(\"code.txt\", \"r\") as file: encrypt_message =",
"FOG_POS: fog_pos = alpha else: code_message += alpha if alpha == END_LINE: with",
"verify_code(encrypt_message) if shift != None and fog_num != None and fog_pos != None:",
"CEIL = 122 END_LINE = '\\n' FLOOR = 32 FOG_NUM = 1 FOG_POS",
"None fog_pos = None code_message = '' for alpha in message: if i",
"for alpha in message: ord_ascii = ord(alpha) if ord_ascii <= shift + FLOOR:",
"int) -> str: uncesar_message = '' for alpha in message: ord_ascii = ord(alpha)",
"32 FOG_NUM = 1 FOG_POS = 2 ROLLBACK = 90 SECURITY = 'access",
"None code_message = '' for alpha in message: if i == SHIFT: shift",
"def main(): try: # open, read and verify encrypt_message = '' with open(\"code.txt\",",
"0 shift = None fog_num = None fog_pos = None code_message = ''",
"None fog_num = None fog_pos = None code_message = '' for alpha in",
"else: code_message += alpha if alpha == END_LINE: with open(\"code.txt\", \"w\") as file:",
"file.write(SECURITY) break i+=1 return shift, fog_num, fog_pos, code_message def clear(message : str, fog_num",
"= file.read() shift, fog_num, fog_pos, code_message = verify_code(encrypt_message) if shift != None and",
"fog_num = None fog_pos = None code_message = '' for alpha in message:",
"str: clear_message = '' i = FLOOR for alpha in message: if i",
"FLOOR for alpha in message: if i > fog_num: i = FLOOR if",
"-> str: clear_message = '' i = FLOOR for alpha in message: if",
"-> str: uncesar_message = '' for alpha in message: ord_ascii = ord(alpha) if",
"!= None: # clear clear_message = clear(code_message, ord(fog_num), ord(fog_pos)) # uncesar decrypt_message =",
"clear_message = '' i = FLOOR for alpha in message: if i >",
"message: ord_ascii = ord(alpha) if ord_ascii <= shift + FLOOR: uncesar_message += chr(ord_ascii+ROLLBACK-shift)",
"denied\\n' SHIFT = 0 def verify_code(message : str) -> list: i = 0",
"with open(\"code.txt\", \"w\") as file: file.write(SECURITY) break i+=1 return shift, fog_num, fog_pos, code_message",
"alpha == END_LINE: with open(\"code.txt\", \"w\") as file: file.write(SECURITY) break i+=1 return shift,",
"str, shift : int) -> str: uncesar_message = '' for alpha in message:",
"shift = None fog_num = None fog_pos = None code_message = '' for",
"def clear(message : str, fog_num : int, fog_pos : int) -> str: clear_message",
"SHIFT = 0 def verify_code(message : str) -> list: i = 0 shift",
"else: uncesar_message += chr(ord(alpha)-shift) return uncesar_message def main(): try: # open, read and",
"shift != None and fog_num != None and fog_pos != None: # clear",
"uncesar_message = '' for alpha in message: ord_ascii = ord(alpha) if ord_ascii <=",
"encrypt_message = '' with open(\"code.txt\", \"r\") as file: encrypt_message = file.read() shift, fog_num,",
"code_message def clear(message : str, fog_num : int, fog_pos : int) -> str:",
"uncesar_message += chr(ord(alpha)-shift) return uncesar_message def main(): try: # open, read and verify",
"if alpha == END_LINE: with open(\"code.txt\", \"w\") as file: file.write(SECURITY) break i+=1 return",
"None and fog_pos != None: # clear clear_message = clear(code_message, ord(fog_num), ord(fog_pos)) #",
"def verify_code(message : str) -> list: i = 0 shift = None fog_num",
"alpha i += 1 return clear_message def uncesar(message : str, shift : int)",
"elif i == FOG_POS: fog_pos = alpha else: code_message += alpha if alpha",
"ord(fog_pos)) # uncesar decrypt_message = uncesar(clear_message, ord(shift)) # export with open('message.txt', 'w') as",
"FLOOR: uncesar_message += chr(ord_ascii+ROLLBACK-shift) else: uncesar_message += chr(ord(alpha)-shift) return uncesar_message def main(): try:",
"alpha in message: if i == SHIFT: shift = alpha elif i ==",
"= alpha elif i == FOG_POS: fog_pos = alpha else: code_message += alpha",
"a problem with: code.txt, Tip: verify the path') if __name__ == '__main__': main()",
"def uncesar(message : str, shift : int) -> str: uncesar_message = '' for",
"i == SHIFT: shift = alpha elif i == FOG_NUM: fog_num = alpha",
"chr(ord(alpha)-shift) return uncesar_message def main(): try: # open, read and verify encrypt_message =",
"int) -> str: clear_message = '' i = FLOOR for alpha in message:",
"message: if i > fog_num: i = FLOOR if i == fog_pos: clear_message",
"clear_message += alpha i += 1 return clear_message def uncesar(message : str, shift",
"as file: file.write(SECURITY) break i+=1 return shift, fog_num, fog_pos, code_message def clear(message :",
"alpha in message: ord_ascii = ord(alpha) if ord_ascii <= shift + FLOOR: uncesar_message",
"if ord_ascii <= shift + FLOOR: uncesar_message += chr(ord_ascii+ROLLBACK-shift) else: uncesar_message += chr(ord(alpha)-shift)",
"ord_ascii <= shift + FLOOR: uncesar_message += chr(ord_ascii+ROLLBACK-shift) else: uncesar_message += chr(ord(alpha)-shift) return",
": int) -> str: uncesar_message = '' for alpha in message: ord_ascii =",
"clear(message : str, fog_num : int, fog_pos : int) -> str: clear_message =",
"SECURITY = 'access denied\\n' SHIFT = 0 def verify_code(message : str) -> list:",
"main(): try: # open, read and verify encrypt_message = '' with open(\"code.txt\", \"r\")",
"and fog_num != None and fog_pos != None: # clear clear_message = clear(code_message,",
"+= alpha i += 1 return clear_message def uncesar(message : str, shift :",
"'' i = FLOOR for alpha in message: if i > fog_num: i",
"= FLOOR for alpha in message: if i > fog_num: i = FLOOR",
"encrypt_message = file.read() shift, fog_num, fog_pos, code_message = verify_code(encrypt_message) if shift != None",
"alpha elif i == FOG_NUM: fog_num = alpha elif i == FOG_POS: fog_pos",
"try: # open, read and verify encrypt_message = '' with open(\"code.txt\", \"r\") as",
"chr(ord_ascii+ROLLBACK-shift) else: uncesar_message += chr(ord(alpha)-shift) return uncesar_message def main(): try: # open, read",
"return shift, fog_num, fog_pos, code_message def clear(message : str, fog_num : int, fog_pos",
"for alpha in message: if i == SHIFT: shift = alpha elif i",
"in message: ord_ascii = ord(alpha) if ord_ascii <= shift + FLOOR: uncesar_message +=",
"+= chr(ord(alpha)-shift) return uncesar_message def main(): try: # open, read and verify encrypt_message",
"code_message = verify_code(encrypt_message) if shift != None and fog_num != None and fog_pos",
"verify_code(message : str) -> list: i = 0 shift = None fog_num =",
"return clear_message def uncesar(message : str, shift : int) -> str: uncesar_message =",
"export with open('message.txt', 'w') as file: file.write(decrypt_message) except: print('There is a problem with:",
"FLOOR = 32 FOG_NUM = 1 FOG_POS = 2 ROLLBACK = 90 SECURITY",
"== SHIFT: shift = alpha elif i == FOG_NUM: fog_num = alpha elif",
"fog_pos = alpha else: code_message += alpha if alpha == END_LINE: with open(\"code.txt\",",
"'' with open(\"code.txt\", \"r\") as file: encrypt_message = file.read() shift, fog_num, fog_pos, code_message",
"= clear(code_message, ord(fog_num), ord(fog_pos)) # uncesar decrypt_message = uncesar(clear_message, ord(shift)) # export with",
"fog_pos: clear_message += alpha i += 1 return clear_message def uncesar(message : str,",
"int, fog_pos : int) -> str: clear_message = '' i = FLOOR for",
"'\\n' FLOOR = 32 FOG_NUM = 1 FOG_POS = 2 ROLLBACK = 90",
"if i > fog_num: i = FLOOR if i == fog_pos: clear_message +=",
"alpha elif i == FOG_POS: fog_pos = alpha else: code_message += alpha if",
"> fog_num: i = FLOOR if i == fog_pos: clear_message += alpha i",
"i == fog_pos: clear_message += alpha i += 1 return clear_message def uncesar(message",
"# open, read and verify encrypt_message = '' with open(\"code.txt\", \"r\") as file:",
"+= alpha if alpha == END_LINE: with open(\"code.txt\", \"w\") as file: file.write(SECURITY) break",
"i = 0 shift = None fog_num = None fog_pos = None code_message",
"file: encrypt_message = file.read() shift, fog_num, fog_pos, code_message = verify_code(encrypt_message) if shift !=",
"with open('message.txt', 'w') as file: file.write(decrypt_message) except: print('There is a problem with: code.txt,",
"fog_num = alpha elif i == FOG_POS: fog_pos = alpha else: code_message +=",
"elif i == FOG_NUM: fog_num = alpha elif i == FOG_POS: fog_pos =",
"= alpha elif i == FOG_NUM: fog_num = alpha elif i == FOG_POS:",
"as file: file.write(decrypt_message) except: print('There is a problem with: code.txt, Tip: verify the",
"code_message = '' for alpha in message: if i == SHIFT: shift =",
"\"w\") as file: file.write(SECURITY) break i+=1 return shift, fog_num, fog_pos, code_message def clear(message",
"for alpha in message: if i > fog_num: i = FLOOR if i",
"alpha in message: if i > fog_num: i = FLOOR if i ==",
"uncesar_message def main(): try: # open, read and verify encrypt_message = '' with",
"!= None and fog_num != None and fog_pos != None: # clear clear_message",
"clear_message = clear(code_message, ord(fog_num), ord(fog_pos)) # uncesar decrypt_message = uncesar(clear_message, ord(shift)) # export",
"uncesar(clear_message, ord(shift)) # export with open('message.txt', 'w') as file: file.write(decrypt_message) except: print('There is",
"SHIFT: shift = alpha elif i == FOG_NUM: fog_num = alpha elif i",
"file.write(decrypt_message) except: print('There is a problem with: code.txt, Tip: verify the path') if",
"shift + FLOOR: uncesar_message += chr(ord_ascii+ROLLBACK-shift) else: uncesar_message += chr(ord(alpha)-shift) return uncesar_message def",
"FOG_NUM = 1 FOG_POS = 2 ROLLBACK = 90 SECURITY = 'access denied\\n'",
"shift = alpha elif i == FOG_NUM: fog_num = alpha elif i ==",
"# clear clear_message = clear(code_message, ord(fog_num), ord(fog_pos)) # uncesar decrypt_message = uncesar(clear_message, ord(shift))",
"shift : int) -> str: uncesar_message = '' for alpha in message: ord_ascii",
"open(\"code.txt\", \"r\") as file: encrypt_message = file.read() shift, fog_num, fog_pos, code_message = verify_code(encrypt_message)",
"uncesar_message += chr(ord_ascii+ROLLBACK-shift) else: uncesar_message += chr(ord(alpha)-shift) return uncesar_message def main(): try: #",
"= 90 SECURITY = 'access denied\\n' SHIFT = 0 def verify_code(message : str)",
"ord(fog_num), ord(fog_pos)) # uncesar decrypt_message = uncesar(clear_message, ord(shift)) # export with open('message.txt', 'w')",
"= '\\n' FLOOR = 32 FOG_NUM = 1 FOG_POS = 2 ROLLBACK =",
"= uncesar(clear_message, ord(shift)) # export with open('message.txt', 'w') as file: file.write(decrypt_message) except: print('There",
"str) -> list: i = 0 shift = None fog_num = None fog_pos",
"shift, fog_num, fog_pos, code_message def clear(message : str, fog_num : int, fog_pos :",
"fog_num != None and fog_pos != None: # clear clear_message = clear(code_message, ord(fog_num),",
"if i == SHIFT: shift = alpha elif i == FOG_NUM: fog_num =",
"== fog_pos: clear_message += alpha i += 1 return clear_message def uncesar(message :",
"1 FOG_POS = 2 ROLLBACK = 90 SECURITY = 'access denied\\n' SHIFT =",
"# export with open('message.txt', 'w') as file: file.write(decrypt_message) except: print('There is a problem",
"+= 1 return clear_message def uncesar(message : str, shift : int) -> str:",
"with open(\"code.txt\", \"r\") as file: encrypt_message = file.read() shift, fog_num, fog_pos, code_message =",
"clear_message def uncesar(message : str, shift : int) -> str: uncesar_message = ''",
"FOG_POS = 2 ROLLBACK = 90 SECURITY = 'access denied\\n' SHIFT = 0",
"-> list: i = 0 shift = None fog_num = None fog_pos =",
"!= None and fog_pos != None: # clear clear_message = clear(code_message, ord(fog_num), ord(fog_pos))",
"in message: if i == SHIFT: shift = alpha elif i == FOG_NUM:",
"fog_num: i = FLOOR if i == fog_pos: clear_message += alpha i +=",
"= 0 def verify_code(message : str) -> list: i = 0 shift =",
"if i == fog_pos: clear_message += alpha i += 1 return clear_message def",
"= None fog_num = None fog_pos = None code_message = '' for alpha",
"clear(code_message, ord(fog_num), ord(fog_pos)) # uncesar decrypt_message = uncesar(clear_message, ord(shift)) # export with open('message.txt',",
": int) -> str: clear_message = '' i = FLOOR for alpha in",
"i == FOG_POS: fog_pos = alpha else: code_message += alpha if alpha ==",
"list: i = 0 shift = None fog_num = None fog_pos = None",
"fog_pos = None code_message = '' for alpha in message: if i ==",
"i == FOG_NUM: fog_num = alpha elif i == FOG_POS: fog_pos = alpha",
"str, fog_num : int, fog_pos : int) -> str: clear_message = '' i",
"fog_num, fog_pos, code_message = verify_code(encrypt_message) if shift != None and fog_num != None",
"= '' for alpha in message: ord_ascii = ord(alpha) if ord_ascii <= shift",
": int, fog_pos : int) -> str: clear_message = '' i = FLOOR",
"if shift != None and fog_num != None and fog_pos != None: #",
"fog_pos, code_message def clear(message : str, fog_num : int, fog_pos : int) ->"
] |
[
"rsquared]) self._outp[\"query_latency_table\"] = latency_table.get_string() def _populate_output(self): \"\"\"Populates the output object which is passed",
"def _store_query_latency_table(self): \"\"\"Stores the LaTeX string representing the query latency table on the",
"import spar_python.report_generation.common.regression as regression import spar_python.report_generation.common.latex_classes as latex_classes import spar_python.report_generation.ta1.ta1_schema as t1s import",
"compute correctness for every query category: for (dbnr, dbrs, selection_cols, query_cat) in categories:",
"query category: for (dbnr, dbrs, selection_cols, query_cat) in categories: inp = t1ai.Input() inp[t1s.DBF_CAT]",
"outputs=outputs, inputs=inputs) function_string = function.string rsquared = function.get_rsquared(inputs, outputs) except regression.BadRegressionInputError: function_string =",
"every query category: for (dbnr, dbrs, selection_cols, query_cat) in categories: inp = t1ai.Input()",
"= function.get_rsquared(inputs, outputs) except regression.BadRegressionInputError: function_string = \"-\" rsquared = \"-\" latency_table.add_content( [inp.test_db.get_db_num_records_str(),",
"SPAR imports: import spar_python.report_generation.ta1.ta1_section as section import spar_python.report_generation.common.regression as regression import spar_python.report_generation.common.latex_classes as",
"Project: SPAR # Authors: SY # Description: Section class # # # Modifications:",
"the latency table: latency_table = latex_classes.LatexTable( \"Query Latency vs. Number of Records Returned",
"19 Sep 2013 SY Original version # ***************************************************************** # SPAR imports: import spar_python.report_generation.ta1.ta1_section",
"inp = t1ai.Input() inp[t1s.DBF_CAT] = query_cat inp[t1s.DBF_NUMRECORDS] = dbnr inp[t1s.DBF_RECORDSIZE] = dbrs inp[t1s.DBP_SELECTIONCOLS]",
"y_values function = regression.regress( function_to_regress=self._config.ql_all_ftr, outputs=outputs, inputs=inputs) function_string = function.string rsquared = function.get_rsquared(inputs,",
"table on the output object.\"\"\" constraint_list = self._config.get_constraint_list( require_correct=True) categories = self._config.results_db.get_unique_query_values( simple_fields=[(t1s.DBF_TABLENAME,",
"query_cat) in categories: inp = t1ai.Input() inp[t1s.DBF_CAT] = query_cat inp[t1s.DBF_NUMRECORDS] = dbnr inp[t1s.DBF_RECORDSIZE]",
"self._outp[\"query_latency_table\"] = latency_table.get_string() def _populate_output(self): \"\"\"Populates the output object which is passed to",
"create the latency table: latency_table = latex_classes.LatexTable( \"Query Latency vs. Number of Records",
"= self._config.results_db.get_query_values( simple_fields=[ (t1s.DBP_TABLENAME, t1s.DBP_NUMNEWRETURNEDRECORDS), (t1s.DBP_TABLENAME, t1s.DBP_QUERYLATENCY)], constraint_list=this_constraint_list) try: inputs = [x_values] outputs",
"# # # Modifications: # Date Name Modification # ---- ---- ------------ #",
"selection_cols, query_cat, function_string, rsquared]) self._outp[\"query_latency_table\"] = latency_table.get_string() def _populate_output(self): \"\"\"Populates the output object",
"latency_table = latex_classes.LatexTable( \"Query Latency vs. Number of Records Returned Best Fit Functions\",",
"selection_cols, query_cat) in categories: inp = t1ai.Input() inp[t1s.DBF_CAT] = query_cat inp[t1s.DBF_NUMRECORDS] = dbnr",
"in categories: inp = t1ai.Input() inp[t1s.DBF_CAT] = query_cat inp[t1s.DBF_NUMRECORDS] = dbnr inp[t1s.DBF_RECORDSIZE] =",
"Modification # ---- ---- ------------ # 19 Sep 2013 SY Original version #",
"inp.test_db.get_db_record_size_str(), selection_cols, query_cat, function_string, rsquared]) self._outp[\"query_latency_table\"] = latency_table.get_string() def _populate_output(self): \"\"\"Populates the output",
"outputs = y_values function = regression.regress( function_to_regress=self._config.ql_all_ftr, outputs=outputs, inputs=inputs) function_string = function.string rsquared",
"t1s.DBF_NUMRECORDS), (t1s.DBF_TABLENAME, t1s.DBF_RECORDSIZE), (t1s.DBP_TABLENAME, t1s.DBP_SELECTIONCOLS), (t1s.DBF_TABLENAME, t1s.DBF_CAT)], constraint_list=constraint_list) # create the latency table:",
"SY Original version # ***************************************************************** # SPAR imports: import spar_python.report_generation.ta1.ta1_section as section import",
"---- ---- ------------ # 19 Sep 2013 SY Original version # ***************************************************************** #",
"MIT Lincoln Laboratory # Project: SPAR # Authors: SY # Description: Section class",
"# ---- ---- ------------ # 19 Sep 2013 SY Original version # *****************************************************************",
"t1s.DBF_CAT)], constraint_list=constraint_list) # create the latency table: latency_table = latex_classes.LatexTable( \"Query Latency vs.",
"= latex_classes.LatexTable( \"Query Latency vs. Number of Records Returned Best Fit Functions\", \"lat_main\",",
"\"Query Latency vs. Number of Records Returned Best Fit Functions\", \"lat_main\", [\"DBNR\", \"DBRS\",",
"require_correct=True) categories = self._config.results_db.get_unique_query_values( simple_fields=[(t1s.DBF_TABLENAME, t1s.DBF_NUMRECORDS), (t1s.DBF_TABLENAME, t1s.DBF_RECORDSIZE), (t1s.DBP_TABLENAME, t1s.DBP_SELECTIONCOLS), (t1s.DBF_TABLENAME, t1s.DBF_CAT)], constraint_list=constraint_list)",
"# Copyright 2013 MIT Lincoln Laboratory # Project: SPAR # Authors: SY #",
"Type\", \"Best-Fit Func\", \"R-Squared\"]) # compute correctness for every query category: for (dbnr,",
"# ***************************************************************** # Copyright 2013 MIT Lincoln Laboratory # Project: SPAR # Authors:",
"= y_values function = regression.regress( function_to_regress=self._config.ql_all_ftr, outputs=outputs, inputs=inputs) function_string = function.string rsquared =",
"self._config.results_db.get_unique_query_values( simple_fields=[(t1s.DBF_TABLENAME, t1s.DBF_NUMRECORDS), (t1s.DBF_TABLENAME, t1s.DBF_RECORDSIZE), (t1s.DBP_TABLENAME, t1s.DBP_SELECTIONCOLS), (t1s.DBF_TABLENAME, t1s.DBF_CAT)], constraint_list=constraint_list) # create the",
"= constraint_list + inp.get_constraint_list() [x_values, y_values] = self._config.results_db.get_query_values( simple_fields=[ (t1s.DBP_TABLENAME, t1s.DBP_NUMNEWRETURNEDRECORDS), (t1s.DBP_TABLENAME, t1s.DBP_QUERYLATENCY)],",
"categories: inp = t1ai.Input() inp[t1s.DBF_CAT] = query_cat inp[t1s.DBF_NUMRECORDS] = dbnr inp[t1s.DBF_RECORDSIZE] = dbrs",
"table: latency_table = latex_classes.LatexTable( \"Query Latency vs. Number of Records Returned Best Fit",
"categories = self._config.results_db.get_unique_query_values( simple_fields=[(t1s.DBF_TABLENAME, t1s.DBF_NUMRECORDS), (t1s.DBF_TABLENAME, t1s.DBF_RECORDSIZE), (t1s.DBP_TABLENAME, t1s.DBP_SELECTIONCOLS), (t1s.DBF_TABLENAME, t1s.DBF_CAT)], constraint_list=constraint_list) #",
"inputs = [x_values] outputs = y_values function = regression.regress( function_to_regress=self._config.ql_all_ftr, outputs=outputs, inputs=inputs) function_string",
"\"-\" rsquared = \"-\" latency_table.add_content( [inp.test_db.get_db_num_records_str(), inp.test_db.get_db_record_size_str(), selection_cols, query_cat, function_string, rsquared]) self._outp[\"query_latency_table\"] =",
"as t1ai class Ta1LatencySection(section.Ta1Section): \"\"\"The latency section of the TA1 report\"\"\" def _store_query_latency_table(self):",
"function_string, rsquared]) self._outp[\"query_latency_table\"] = latency_table.get_string() def _populate_output(self): \"\"\"Populates the output object which is",
"\"Best-Fit Func\", \"R-Squared\"]) # compute correctness for every query category: for (dbnr, dbrs,",
"of Records Returned Best Fit Functions\", \"lat_main\", [\"DBNR\", \"DBRS\", \"Select\", \"Query Type\", \"Best-Fit",
"t1s.DBP_NUMNEWRETURNEDRECORDS), (t1s.DBP_TABLENAME, t1s.DBP_QUERYLATENCY)], constraint_list=this_constraint_list) try: inputs = [x_values] outputs = y_values function =",
"\"\"\"Populates the output object which is passed to the Jinja tempalte in get_string.\"\"\"",
"the query latency table on the output object.\"\"\" constraint_list = self._config.get_constraint_list( require_correct=True) categories",
"this_constraint_list = constraint_list + inp.get_constraint_list() [x_values, y_values] = self._config.results_db.get_query_values( simple_fields=[ (t1s.DBP_TABLENAME, t1s.DBP_NUMNEWRETURNEDRECORDS), (t1s.DBP_TABLENAME,",
"regression import spar_python.report_generation.common.latex_classes as latex_classes import spar_python.report_generation.ta1.ta1_schema as t1s import spar_python.report_generation.ta1.ta1_analysis_input as t1ai",
"TA1 report\"\"\" def _store_query_latency_table(self): \"\"\"Stores the LaTeX string representing the query latency table",
"***************************************************************** # Copyright 2013 MIT Lincoln Laboratory # Project: SPAR # Authors: SY",
"# Project: SPAR # Authors: SY # Description: Section class # # #",
"Ta1LatencySection(section.Ta1Section): \"\"\"The latency section of the TA1 report\"\"\" def _store_query_latency_table(self): \"\"\"Stores the LaTeX",
"# create the latency table: latency_table = latex_classes.LatexTable( \"Query Latency vs. Number of",
"Description: Section class # # # Modifications: # Date Name Modification # ----",
"as t1s import spar_python.report_generation.ta1.ta1_analysis_input as t1ai class Ta1LatencySection(section.Ta1Section): \"\"\"The latency section of the",
"Number of Records Returned Best Fit Functions\", \"lat_main\", [\"DBNR\", \"DBRS\", \"Select\", \"Query Type\",",
"outputs) except regression.BadRegressionInputError: function_string = \"-\" rsquared = \"-\" latency_table.add_content( [inp.test_db.get_db_num_records_str(), inp.test_db.get_db_record_size_str(), selection_cols,",
"(t1s.DBF_TABLENAME, t1s.DBF_CAT)], constraint_list=constraint_list) # create the latency table: latency_table = latex_classes.LatexTable( \"Query Latency",
"class Ta1LatencySection(section.Ta1Section): \"\"\"The latency section of the TA1 report\"\"\" def _store_query_latency_table(self): \"\"\"Stores the",
"= \"-\" rsquared = \"-\" latency_table.add_content( [inp.test_db.get_db_num_records_str(), inp.test_db.get_db_record_size_str(), selection_cols, query_cat, function_string, rsquared]) self._outp[\"query_latency_table\"]",
"object.\"\"\" constraint_list = self._config.get_constraint_list( require_correct=True) categories = self._config.results_db.get_unique_query_values( simple_fields=[(t1s.DBF_TABLENAME, t1s.DBF_NUMRECORDS), (t1s.DBF_TABLENAME, t1s.DBF_RECORDSIZE), (t1s.DBP_TABLENAME,",
"# Modifications: # Date Name Modification # ---- ---- ------------ # 19 Sep",
"string representing the query latency table on the output object.\"\"\" constraint_list = self._config.get_constraint_list(",
"= query_cat inp[t1s.DBF_NUMRECORDS] = dbnr inp[t1s.DBF_RECORDSIZE] = dbrs inp[t1s.DBP_SELECTIONCOLS] = selection_cols this_constraint_list =",
"self._config.results_db.get_query_values( simple_fields=[ (t1s.DBP_TABLENAME, t1s.DBP_NUMNEWRETURNEDRECORDS), (t1s.DBP_TABLENAME, t1s.DBP_QUERYLATENCY)], constraint_list=this_constraint_list) try: inputs = [x_values] outputs =",
"latency section of the TA1 report\"\"\" def _store_query_latency_table(self): \"\"\"Stores the LaTeX string representing",
"for (dbnr, dbrs, selection_cols, query_cat) in categories: inp = t1ai.Input() inp[t1s.DBF_CAT] = query_cat",
"= t1ai.Input() inp[t1s.DBF_CAT] = query_cat inp[t1s.DBF_NUMRECORDS] = dbnr inp[t1s.DBF_RECORDSIZE] = dbrs inp[t1s.DBP_SELECTIONCOLS] =",
"inp[t1s.DBF_NUMRECORDS] = dbnr inp[t1s.DBF_RECORDSIZE] = dbrs inp[t1s.DBP_SELECTIONCOLS] = selection_cols this_constraint_list = constraint_list +",
"(t1s.DBP_TABLENAME, t1s.DBP_SELECTIONCOLS), (t1s.DBF_TABLENAME, t1s.DBF_CAT)], constraint_list=constraint_list) # create the latency table: latency_table = latex_classes.LatexTable(",
"Name Modification # ---- ---- ------------ # 19 Sep 2013 SY Original version",
"= self._config.results_db.get_unique_query_values( simple_fields=[(t1s.DBF_TABLENAME, t1s.DBF_NUMRECORDS), (t1s.DBF_TABLENAME, t1s.DBF_RECORDSIZE), (t1s.DBP_TABLENAME, t1s.DBP_SELECTIONCOLS), (t1s.DBF_TABLENAME, t1s.DBF_CAT)], constraint_list=constraint_list) # create",
"spar_python.report_generation.common.regression as regression import spar_python.report_generation.common.latex_classes as latex_classes import spar_python.report_generation.ta1.ta1_schema as t1s import spar_python.report_generation.ta1.ta1_analysis_input",
"regression.regress( function_to_regress=self._config.ql_all_ftr, outputs=outputs, inputs=inputs) function_string = function.string rsquared = function.get_rsquared(inputs, outputs) except regression.BadRegressionInputError:",
"as latex_classes import spar_python.report_generation.ta1.ta1_schema as t1s import spar_python.report_generation.ta1.ta1_analysis_input as t1ai class Ta1LatencySection(section.Ta1Section): \"\"\"The",
"function.get_rsquared(inputs, outputs) except regression.BadRegressionInputError: function_string = \"-\" rsquared = \"-\" latency_table.add_content( [inp.test_db.get_db_num_records_str(), inp.test_db.get_db_record_size_str(),",
"_populate_output(self): \"\"\"Populates the output object which is passed to the Jinja tempalte in",
"Modifications: # Date Name Modification # ---- ---- ------------ # 19 Sep 2013",
"= [x_values] outputs = y_values function = regression.regress( function_to_regress=self._config.ql_all_ftr, outputs=outputs, inputs=inputs) function_string =",
"Copyright 2013 MIT Lincoln Laboratory # Project: SPAR # Authors: SY # Description:",
"version # ***************************************************************** # SPAR imports: import spar_python.report_generation.ta1.ta1_section as section import spar_python.report_generation.common.regression as",
"= function.string rsquared = function.get_rsquared(inputs, outputs) except regression.BadRegressionInputError: function_string = \"-\" rsquared =",
"+ inp.get_constraint_list() [x_values, y_values] = self._config.results_db.get_query_values( simple_fields=[ (t1s.DBP_TABLENAME, t1s.DBP_NUMNEWRETURNEDRECORDS), (t1s.DBP_TABLENAME, t1s.DBP_QUERYLATENCY)], constraint_list=this_constraint_list) try:",
"inputs=inputs) function_string = function.string rsquared = function.get_rsquared(inputs, outputs) except regression.BadRegressionInputError: function_string = \"-\"",
"the output object which is passed to the Jinja tempalte in get_string.\"\"\" self._store_query_latency_table()",
"Date Name Modification # ---- ---- ------------ # 19 Sep 2013 SY Original",
"\"lat_main\", [\"DBNR\", \"DBRS\", \"Select\", \"Query Type\", \"Best-Fit Func\", \"R-Squared\"]) # compute correctness for",
"spar_python.report_generation.common.latex_classes as latex_classes import spar_python.report_generation.ta1.ta1_schema as t1s import spar_python.report_generation.ta1.ta1_analysis_input as t1ai class Ta1LatencySection(section.Ta1Section):",
"rsquared = function.get_rsquared(inputs, outputs) except regression.BadRegressionInputError: function_string = \"-\" rsquared = \"-\" latency_table.add_content(",
"function.string rsquared = function.get_rsquared(inputs, outputs) except regression.BadRegressionInputError: function_string = \"-\" rsquared = \"-\"",
"# 19 Sep 2013 SY Original version # ***************************************************************** # SPAR imports: import",
"Authors: SY # Description: Section class # # # Modifications: # Date Name",
"on the output object.\"\"\" constraint_list = self._config.get_constraint_list( require_correct=True) categories = self._config.results_db.get_unique_query_values( simple_fields=[(t1s.DBF_TABLENAME, t1s.DBF_NUMRECORDS),",
"Functions\", \"lat_main\", [\"DBNR\", \"DBRS\", \"Select\", \"Query Type\", \"Best-Fit Func\", \"R-Squared\"]) # compute correctness",
"spar_python.report_generation.ta1.ta1_schema as t1s import spar_python.report_generation.ta1.ta1_analysis_input as t1ai class Ta1LatencySection(section.Ta1Section): \"\"\"The latency section of",
"function_to_regress=self._config.ql_all_ftr, outputs=outputs, inputs=inputs) function_string = function.string rsquared = function.get_rsquared(inputs, outputs) except regression.BadRegressionInputError: function_string",
"constraint_list = self._config.get_constraint_list( require_correct=True) categories = self._config.results_db.get_unique_query_values( simple_fields=[(t1s.DBF_TABLENAME, t1s.DBF_NUMRECORDS), (t1s.DBF_TABLENAME, t1s.DBF_RECORDSIZE), (t1s.DBP_TABLENAME, t1s.DBP_SELECTIONCOLS),",
"\"R-Squared\"]) # compute correctness for every query category: for (dbnr, dbrs, selection_cols, query_cat)",
"# ***************************************************************** # SPAR imports: import spar_python.report_generation.ta1.ta1_section as section import spar_python.report_generation.common.regression as regression",
"dbrs, selection_cols, query_cat) in categories: inp = t1ai.Input() inp[t1s.DBF_CAT] = query_cat inp[t1s.DBF_NUMRECORDS] =",
"latency_table.get_string() def _populate_output(self): \"\"\"Populates the output object which is passed to the Jinja",
"query_cat, function_string, rsquared]) self._outp[\"query_latency_table\"] = latency_table.get_string() def _populate_output(self): \"\"\"Populates the output object which",
"correctness for every query category: for (dbnr, dbrs, selection_cols, query_cat) in categories: inp",
"as section import spar_python.report_generation.common.regression as regression import spar_python.report_generation.common.latex_classes as latex_classes import spar_python.report_generation.ta1.ta1_schema as",
"self._config.get_constraint_list( require_correct=True) categories = self._config.results_db.get_unique_query_values( simple_fields=[(t1s.DBF_TABLENAME, t1s.DBF_NUMRECORDS), (t1s.DBF_TABLENAME, t1s.DBF_RECORDSIZE), (t1s.DBP_TABLENAME, t1s.DBP_SELECTIONCOLS), (t1s.DBF_TABLENAME, t1s.DBF_CAT)],",
"Returned Best Fit Functions\", \"lat_main\", [\"DBNR\", \"DBRS\", \"Select\", \"Query Type\", \"Best-Fit Func\", \"R-Squared\"])",
"\"\"\"Stores the LaTeX string representing the query latency table on the output object.\"\"\"",
"vs. Number of Records Returned Best Fit Functions\", \"lat_main\", [\"DBNR\", \"DBRS\", \"Select\", \"Query",
"= \"-\" latency_table.add_content( [inp.test_db.get_db_num_records_str(), inp.test_db.get_db_record_size_str(), selection_cols, query_cat, function_string, rsquared]) self._outp[\"query_latency_table\"] = latency_table.get_string() def",
"constraint_list=constraint_list) # create the latency table: latency_table = latex_classes.LatexTable( \"Query Latency vs. Number",
"simple_fields=[ (t1s.DBP_TABLENAME, t1s.DBP_NUMNEWRETURNEDRECORDS), (t1s.DBP_TABLENAME, t1s.DBP_QUERYLATENCY)], constraint_list=this_constraint_list) try: inputs = [x_values] outputs = y_values",
"function_string = function.string rsquared = function.get_rsquared(inputs, outputs) except regression.BadRegressionInputError: function_string = \"-\" rsquared",
"Laboratory # Project: SPAR # Authors: SY # Description: Section class # #",
"import spar_python.report_generation.ta1.ta1_analysis_input as t1ai class Ta1LatencySection(section.Ta1Section): \"\"\"The latency section of the TA1 report\"\"\"",
"(t1s.DBP_TABLENAME, t1s.DBP_QUERYLATENCY)], constraint_list=this_constraint_list) try: inputs = [x_values] outputs = y_values function = regression.regress(",
"class # # # Modifications: # Date Name Modification # ---- ---- ------------",
"the output object.\"\"\" constraint_list = self._config.get_constraint_list( require_correct=True) categories = self._config.results_db.get_unique_query_values( simple_fields=[(t1s.DBF_TABLENAME, t1s.DBF_NUMRECORDS), (t1s.DBF_TABLENAME,",
"representing the query latency table on the output object.\"\"\" constraint_list = self._config.get_constraint_list( require_correct=True)",
"= dbrs inp[t1s.DBP_SELECTIONCOLS] = selection_cols this_constraint_list = constraint_list + inp.get_constraint_list() [x_values, y_values] =",
"t1s import spar_python.report_generation.ta1.ta1_analysis_input as t1ai class Ta1LatencySection(section.Ta1Section): \"\"\"The latency section of the TA1",
"Fit Functions\", \"lat_main\", [\"DBNR\", \"DBRS\", \"Select\", \"Query Type\", \"Best-Fit Func\", \"R-Squared\"]) # compute",
"rsquared = \"-\" latency_table.add_content( [inp.test_db.get_db_num_records_str(), inp.test_db.get_db_record_size_str(), selection_cols, query_cat, function_string, rsquared]) self._outp[\"query_latency_table\"] = latency_table.get_string()",
"---- ------------ # 19 Sep 2013 SY Original version # ***************************************************************** # SPAR",
"def _populate_output(self): \"\"\"Populates the output object which is passed to the Jinja tempalte",
"Latency vs. Number of Records Returned Best Fit Functions\", \"lat_main\", [\"DBNR\", \"DBRS\", \"Select\",",
"try: inputs = [x_values] outputs = y_values function = regression.regress( function_to_regress=self._config.ql_all_ftr, outputs=outputs, inputs=inputs)",
"as regression import spar_python.report_generation.common.latex_classes as latex_classes import spar_python.report_generation.ta1.ta1_schema as t1s import spar_python.report_generation.ta1.ta1_analysis_input as",
"query latency table on the output object.\"\"\" constraint_list = self._config.get_constraint_list( require_correct=True) categories =",
"= self._config.get_constraint_list( require_correct=True) categories = self._config.results_db.get_unique_query_values( simple_fields=[(t1s.DBF_TABLENAME, t1s.DBF_NUMRECORDS), (t1s.DBF_TABLENAME, t1s.DBF_RECORDSIZE), (t1s.DBP_TABLENAME, t1s.DBP_SELECTIONCOLS), (t1s.DBF_TABLENAME,",
"(t1s.DBP_TABLENAME, t1s.DBP_NUMNEWRETURNEDRECORDS), (t1s.DBP_TABLENAME, t1s.DBP_QUERYLATENCY)], constraint_list=this_constraint_list) try: inputs = [x_values] outputs = y_values function",
"\"-\" latency_table.add_content( [inp.test_db.get_db_num_records_str(), inp.test_db.get_db_record_size_str(), selection_cols, query_cat, function_string, rsquared]) self._outp[\"query_latency_table\"] = latency_table.get_string() def _populate_output(self):",
"inp[t1s.DBF_RECORDSIZE] = dbrs inp[t1s.DBP_SELECTIONCOLS] = selection_cols this_constraint_list = constraint_list + inp.get_constraint_list() [x_values, y_values]",
"# compute correctness for every query category: for (dbnr, dbrs, selection_cols, query_cat) in",
"constraint_list=this_constraint_list) try: inputs = [x_values] outputs = y_values function = regression.regress( function_to_regress=self._config.ql_all_ftr, outputs=outputs,",
"selection_cols this_constraint_list = constraint_list + inp.get_constraint_list() [x_values, y_values] = self._config.results_db.get_query_values( simple_fields=[ (t1s.DBP_TABLENAME, t1s.DBP_NUMNEWRETURNEDRECORDS),",
"_store_query_latency_table(self): \"\"\"Stores the LaTeX string representing the query latency table on the output",
"dbnr inp[t1s.DBF_RECORDSIZE] = dbrs inp[t1s.DBP_SELECTIONCOLS] = selection_cols this_constraint_list = constraint_list + inp.get_constraint_list() [x_values,",
"query_cat inp[t1s.DBF_NUMRECORDS] = dbnr inp[t1s.DBF_RECORDSIZE] = dbrs inp[t1s.DBP_SELECTIONCOLS] = selection_cols this_constraint_list = constraint_list",
"t1s.DBP_SELECTIONCOLS), (t1s.DBF_TABLENAME, t1s.DBF_CAT)], constraint_list=constraint_list) # create the latency table: latency_table = latex_classes.LatexTable( \"Query",
"section of the TA1 report\"\"\" def _store_query_latency_table(self): \"\"\"Stores the LaTeX string representing the",
"import spar_python.report_generation.ta1.ta1_section as section import spar_python.report_generation.common.regression as regression import spar_python.report_generation.common.latex_classes as latex_classes import",
"\"Query Type\", \"Best-Fit Func\", \"R-Squared\"]) # compute correctness for every query category: for",
"= dbnr inp[t1s.DBF_RECORDSIZE] = dbrs inp[t1s.DBP_SELECTIONCOLS] = selection_cols this_constraint_list = constraint_list + inp.get_constraint_list()",
"[inp.test_db.get_db_num_records_str(), inp.test_db.get_db_record_size_str(), selection_cols, query_cat, function_string, rsquared]) self._outp[\"query_latency_table\"] = latency_table.get_string() def _populate_output(self): \"\"\"Populates the",
"***************************************************************** # SPAR imports: import spar_python.report_generation.ta1.ta1_section as section import spar_python.report_generation.common.regression as regression import",
"Func\", \"R-Squared\"]) # compute correctness for every query category: for (dbnr, dbrs, selection_cols,",
"spar_python.report_generation.ta1.ta1_section as section import spar_python.report_generation.common.regression as regression import spar_python.report_generation.common.latex_classes as latex_classes import spar_python.report_generation.ta1.ta1_schema",
"section import spar_python.report_generation.common.regression as regression import spar_python.report_generation.common.latex_classes as latex_classes import spar_python.report_generation.ta1.ta1_schema as t1s",
"(t1s.DBF_TABLENAME, t1s.DBF_RECORDSIZE), (t1s.DBP_TABLENAME, t1s.DBP_SELECTIONCOLS), (t1s.DBF_TABLENAME, t1s.DBF_CAT)], constraint_list=constraint_list) # create the latency table: latency_table",
"inp[t1s.DBF_CAT] = query_cat inp[t1s.DBF_NUMRECORDS] = dbnr inp[t1s.DBF_RECORDSIZE] = dbrs inp[t1s.DBP_SELECTIONCOLS] = selection_cols this_constraint_list",
"= regression.regress( function_to_regress=self._config.ql_all_ftr, outputs=outputs, inputs=inputs) function_string = function.string rsquared = function.get_rsquared(inputs, outputs) except",
"latex_classes.LatexTable( \"Query Latency vs. Number of Records Returned Best Fit Functions\", \"lat_main\", [\"DBNR\",",
"Records Returned Best Fit Functions\", \"lat_main\", [\"DBNR\", \"DBRS\", \"Select\", \"Query Type\", \"Best-Fit Func\",",
"inp[t1s.DBP_SELECTIONCOLS] = selection_cols this_constraint_list = constraint_list + inp.get_constraint_list() [x_values, y_values] = self._config.results_db.get_query_values( simple_fields=[",
"2013 MIT Lincoln Laboratory # Project: SPAR # Authors: SY # Description: Section",
"of the TA1 report\"\"\" def _store_query_latency_table(self): \"\"\"Stores the LaTeX string representing the query",
"regression.BadRegressionInputError: function_string = \"-\" rsquared = \"-\" latency_table.add_content( [inp.test_db.get_db_num_records_str(), inp.test_db.get_db_record_size_str(), selection_cols, query_cat, function_string,",
"\"\"\"The latency section of the TA1 report\"\"\" def _store_query_latency_table(self): \"\"\"Stores the LaTeX string",
"Sep 2013 SY Original version # ***************************************************************** # SPAR imports: import spar_python.report_generation.ta1.ta1_section as",
"the LaTeX string representing the query latency table on the output object.\"\"\" constraint_list",
"spar_python.report_generation.ta1.ta1_analysis_input as t1ai class Ta1LatencySection(section.Ta1Section): \"\"\"The latency section of the TA1 report\"\"\" def",
"report\"\"\" def _store_query_latency_table(self): \"\"\"Stores the LaTeX string representing the query latency table on",
"Original version # ***************************************************************** # SPAR imports: import spar_python.report_generation.ta1.ta1_section as section import spar_python.report_generation.common.regression",
"t1s.DBP_QUERYLATENCY)], constraint_list=this_constraint_list) try: inputs = [x_values] outputs = y_values function = regression.regress( function_to_regress=self._config.ql_all_ftr,",
"output object.\"\"\" constraint_list = self._config.get_constraint_list( require_correct=True) categories = self._config.results_db.get_unique_query_values( simple_fields=[(t1s.DBF_TABLENAME, t1s.DBF_NUMRECORDS), (t1s.DBF_TABLENAME, t1s.DBF_RECORDSIZE),",
"import spar_python.report_generation.common.latex_classes as latex_classes import spar_python.report_generation.ta1.ta1_schema as t1s import spar_python.report_generation.ta1.ta1_analysis_input as t1ai class",
"\"Select\", \"Query Type\", \"Best-Fit Func\", \"R-Squared\"]) # compute correctness for every query category:",
"(dbnr, dbrs, selection_cols, query_cat) in categories: inp = t1ai.Input() inp[t1s.DBF_CAT] = query_cat inp[t1s.DBF_NUMRECORDS]",
"for every query category: for (dbnr, dbrs, selection_cols, query_cat) in categories: inp =",
"# SPAR imports: import spar_python.report_generation.ta1.ta1_section as section import spar_python.report_generation.common.regression as regression import spar_python.report_generation.common.latex_classes",
"SY # Description: Section class # # # Modifications: # Date Name Modification",
"imports: import spar_python.report_generation.ta1.ta1_section as section import spar_python.report_generation.common.regression as regression import spar_python.report_generation.common.latex_classes as latex_classes",
"Best Fit Functions\", \"lat_main\", [\"DBNR\", \"DBRS\", \"Select\", \"Query Type\", \"Best-Fit Func\", \"R-Squared\"]) #",
"dbrs inp[t1s.DBP_SELECTIONCOLS] = selection_cols this_constraint_list = constraint_list + inp.get_constraint_list() [x_values, y_values] = self._config.results_db.get_query_values(",
"function = regression.regress( function_to_regress=self._config.ql_all_ftr, outputs=outputs, inputs=inputs) function_string = function.string rsquared = function.get_rsquared(inputs, outputs)",
"[x_values, y_values] = self._config.results_db.get_query_values( simple_fields=[ (t1s.DBP_TABLENAME, t1s.DBP_NUMNEWRETURNEDRECORDS), (t1s.DBP_TABLENAME, t1s.DBP_QUERYLATENCY)], constraint_list=this_constraint_list) try: inputs =",
"# Authors: SY # Description: Section class # # # Modifications: # Date",
"t1s.DBF_RECORDSIZE), (t1s.DBP_TABLENAME, t1s.DBP_SELECTIONCOLS), (t1s.DBF_TABLENAME, t1s.DBF_CAT)], constraint_list=constraint_list) # create the latency table: latency_table =",
"import spar_python.report_generation.ta1.ta1_schema as t1s import spar_python.report_generation.ta1.ta1_analysis_input as t1ai class Ta1LatencySection(section.Ta1Section): \"\"\"The latency section",
"\"DBRS\", \"Select\", \"Query Type\", \"Best-Fit Func\", \"R-Squared\"]) # compute correctness for every query",
"# Date Name Modification # ---- ---- ------------ # 19 Sep 2013 SY",
"2013 SY Original version # ***************************************************************** # SPAR imports: import spar_python.report_generation.ta1.ta1_section as section",
"latex_classes import spar_python.report_generation.ta1.ta1_schema as t1s import spar_python.report_generation.ta1.ta1_analysis_input as t1ai class Ta1LatencySection(section.Ta1Section): \"\"\"The latency",
"= latency_table.get_string() def _populate_output(self): \"\"\"Populates the output object which is passed to the",
"category: for (dbnr, dbrs, selection_cols, query_cat) in categories: inp = t1ai.Input() inp[t1s.DBF_CAT] =",
"the TA1 report\"\"\" def _store_query_latency_table(self): \"\"\"Stores the LaTeX string representing the query latency",
"LaTeX string representing the query latency table on the output object.\"\"\" constraint_list =",
"latency table: latency_table = latex_classes.LatexTable( \"Query Latency vs. Number of Records Returned Best",
"[\"DBNR\", \"DBRS\", \"Select\", \"Query Type\", \"Best-Fit Func\", \"R-Squared\"]) # compute correctness for every",
"constraint_list + inp.get_constraint_list() [x_values, y_values] = self._config.results_db.get_query_values( simple_fields=[ (t1s.DBP_TABLENAME, t1s.DBP_NUMNEWRETURNEDRECORDS), (t1s.DBP_TABLENAME, t1s.DBP_QUERYLATENCY)], constraint_list=this_constraint_list)",
"latency_table.add_content( [inp.test_db.get_db_num_records_str(), inp.test_db.get_db_record_size_str(), selection_cols, query_cat, function_string, rsquared]) self._outp[\"query_latency_table\"] = latency_table.get_string() def _populate_output(self): \"\"\"Populates",
"t1ai.Input() inp[t1s.DBF_CAT] = query_cat inp[t1s.DBF_NUMRECORDS] = dbnr inp[t1s.DBF_RECORDSIZE] = dbrs inp[t1s.DBP_SELECTIONCOLS] = selection_cols",
"Lincoln Laboratory # Project: SPAR # Authors: SY # Description: Section class #",
"inp.get_constraint_list() [x_values, y_values] = self._config.results_db.get_query_values( simple_fields=[ (t1s.DBP_TABLENAME, t1s.DBP_NUMNEWRETURNEDRECORDS), (t1s.DBP_TABLENAME, t1s.DBP_QUERYLATENCY)], constraint_list=this_constraint_list) try: inputs",
"y_values] = self._config.results_db.get_query_values( simple_fields=[ (t1s.DBP_TABLENAME, t1s.DBP_NUMNEWRETURNEDRECORDS), (t1s.DBP_TABLENAME, t1s.DBP_QUERYLATENCY)], constraint_list=this_constraint_list) try: inputs = [x_values]",
"simple_fields=[(t1s.DBF_TABLENAME, t1s.DBF_NUMRECORDS), (t1s.DBF_TABLENAME, t1s.DBF_RECORDSIZE), (t1s.DBP_TABLENAME, t1s.DBP_SELECTIONCOLS), (t1s.DBF_TABLENAME, t1s.DBF_CAT)], constraint_list=constraint_list) # create the latency",
"t1ai class Ta1LatencySection(section.Ta1Section): \"\"\"The latency section of the TA1 report\"\"\" def _store_query_latency_table(self): \"\"\"Stores",
"[x_values] outputs = y_values function = regression.regress( function_to_regress=self._config.ql_all_ftr, outputs=outputs, inputs=inputs) function_string = function.string",
"# Description: Section class # # # Modifications: # Date Name Modification #",
"SPAR # Authors: SY # Description: Section class # # # Modifications: #",
"except regression.BadRegressionInputError: function_string = \"-\" rsquared = \"-\" latency_table.add_content( [inp.test_db.get_db_num_records_str(), inp.test_db.get_db_record_size_str(), selection_cols, query_cat,",
"------------ # 19 Sep 2013 SY Original version # ***************************************************************** # SPAR imports:",
"Section class # # # Modifications: # Date Name Modification # ---- ----",
"function_string = \"-\" rsquared = \"-\" latency_table.add_content( [inp.test_db.get_db_num_records_str(), inp.test_db.get_db_record_size_str(), selection_cols, query_cat, function_string, rsquared])",
"= selection_cols this_constraint_list = constraint_list + inp.get_constraint_list() [x_values, y_values] = self._config.results_db.get_query_values( simple_fields=[ (t1s.DBP_TABLENAME,",
"# # Modifications: # Date Name Modification # ---- ---- ------------ # 19",
"latency table on the output object.\"\"\" constraint_list = self._config.get_constraint_list( require_correct=True) categories = self._config.results_db.get_unique_query_values("
] |
[
"#reconstruct all components into one signal D_k = components.dot(activations) y_k = librosa.istft(D_k *",
"S, phase = librosa.magphase(D) #NMF decompose to components components, activations = self.decomposeNMF(hpss_y, S,",
"def reconstructFull(self, activations, phase): #reconstruct all components into one signal D_k = components.dot(activations)",
"y_k = librosa.istft(D_k * phase) #filter out noise using Savitzky-Golay filter component_filtered =",
"scipy.signal as sp import scipy.spatial.distance as sp_dist import librosa class MedianNMF: y, sr",
"Short-time Fourier transform D = librosa.stft(hpss_y) # Separate the magnitude and phase S,",
"activations[i], phase) for i in range(0,len(activations))] def hpss(self, margin=4.0): #extract precussive components through",
"margin=4.0): #extract precussive components through median filtering return librosa.effects.percussive(self.y, margin=margin) def decomposeNMF(self, y,",
"through median filtering return librosa.effects.percussive(self.y, margin=margin) def decomposeNMF(self, y, magnitude, n_components): # Decompose",
"librosa.decompose.decompose(magnitude, n_components, sort=True) def reconstructFull(self, activations, phase): #reconstruct all components into one signal",
"y, sr = None,None n_components = None def __init__(self,y,sr,n_components = 5): self.y, self.sr",
"librosa.istft(D_k * phase) #filter out noise using Savitzky-Golay filter component_filtered = sp.savgol_filter(y_k,11,1) return",
"magnitude and phase S, phase = librosa.magphase(D) #NMF decompose to components components, activations",
"None,None n_components = None def __init__(self,y,sr,n_components = 5): self.y, self.sr = y,sr self.n_components",
"self.y, self.sr = y,sr self.n_components = n_components def decompose(self): #filter out precussive parts",
"self.hpss() #Perform Short-time Fourier transform D = librosa.stft(hpss_y) # Separate the magnitude and",
"into one signal D_k = components.dot(activations) y_k = librosa.istft(D_k * phase) return y_k",
"components through median filtering return librosa.effects.percussive(self.y, margin=margin) def decomposeNMF(self, y, magnitude, n_components): #",
"def reconstructComponent(self, components, activation, phase): D_k = np.multiply.outer(components, activation) y_k = librosa.istft(D_k *",
"precussive components through median filtering return librosa.effects.percussive(self.y, margin=margin) def decomposeNMF(self, y, magnitude, n_components):",
"activations, phase): #reconstruct all components into one signal D_k = components.dot(activations) y_k =",
"= None def __init__(self,y,sr,n_components = 5): self.y, self.sr = y,sr self.n_components = n_components",
"as sp import scipy.spatial.distance as sp_dist import librosa class MedianNMF: y, sr =",
"n_components, sort=True) def reconstructFull(self, activations, phase): #reconstruct all components into one signal D_k",
"self.n_components) #reconstruct and return return [self.reconstructComponent( components[:, i], activations[i], phase) for i in",
"y,sr self.n_components = n_components def decompose(self): #filter out precussive parts hpss_y = self.hpss()",
"np.multiply.outer(components, activation) y_k = librosa.istft(D_k * phase) #filter out noise using Savitzky-Golay filter",
"as sp_dist import librosa class MedianNMF: y, sr = None,None n_components = None",
"#NMF decompose to components components, activations = self.decomposeNMF(hpss_y, S, self.n_components) #reconstruct and return",
"def decompose(self): #filter out precussive parts hpss_y = self.hpss() #Perform Short-time Fourier transform",
"= self.hpss() #Perform Short-time Fourier transform D = librosa.stft(hpss_y) # Separate the magnitude",
"components components, activations = self.decomposeNMF(hpss_y, S, self.n_components) #reconstruct and return return [self.reconstructComponent( components[:,",
"D = librosa.stft(hpss_y) # Separate the magnitude and phase S, phase = librosa.magphase(D)",
"in range(0,len(activations))] def hpss(self, margin=4.0): #extract precussive components through median filtering return librosa.effects.percussive(self.y,",
"import scipy.spatial.distance as sp_dist import librosa class MedianNMF: y, sr = None,None n_components",
"import numpy as np import scipy.signal as sp import scipy.spatial.distance as sp_dist import",
"= y,sr self.n_components = n_components def decompose(self): #filter out precussive parts hpss_y =",
"reconstructFull(self, activations, phase): #reconstruct all components into one signal D_k = components.dot(activations) y_k",
"Separate the magnitude and phase S, phase = librosa.magphase(D) #NMF decompose to components",
"to components components, activations = self.decomposeNMF(hpss_y, S, self.n_components) #reconstruct and return return [self.reconstructComponent(",
"margin=margin) def decomposeNMF(self, y, magnitude, n_components): # Decompose by nmf return librosa.decompose.decompose(magnitude, n_components,",
"n_components def decompose(self): #filter out precussive parts hpss_y = self.hpss() #Perform Short-time Fourier",
"= librosa.istft(D_k * phase) #filter out noise using Savitzky-Golay filter component_filtered = sp.savgol_filter(y_k,11,1)",
"activations = self.decomposeNMF(hpss_y, S, self.n_components) #reconstruct and return return [self.reconstructComponent( components[:, i], activations[i],",
"range(0,len(activations))] def hpss(self, margin=4.0): #extract precussive components through median filtering return librosa.effects.percussive(self.y, margin=margin)",
"components.dot(activations) y_k = librosa.istft(D_k * phase) return y_k def reconstructComponent(self, components, activation, phase):",
"self.n_components = n_components def decompose(self): #filter out precussive parts hpss_y = self.hpss() #Perform",
"= librosa.stft(hpss_y) # Separate the magnitude and phase S, phase = librosa.magphase(D) #NMF",
"librosa.stft(hpss_y) # Separate the magnitude and phase S, phase = librosa.magphase(D) #NMF decompose",
"hpss_y = self.hpss() #Perform Short-time Fourier transform D = librosa.stft(hpss_y) # Separate the",
"transform D = librosa.stft(hpss_y) # Separate the magnitude and phase S, phase =",
"# Decompose by nmf return librosa.decompose.decompose(magnitude, n_components, sort=True) def reconstructFull(self, activations, phase): #reconstruct",
"filtering return librosa.effects.percussive(self.y, margin=margin) def decomposeNMF(self, y, magnitude, n_components): # Decompose by nmf",
"sp import scipy.spatial.distance as sp_dist import librosa class MedianNMF: y, sr = None,None",
"= np.multiply.outer(components, activation) y_k = librosa.istft(D_k * phase) #filter out noise using Savitzky-Golay",
"phase) for i in range(0,len(activations))] def hpss(self, margin=4.0): #extract precussive components through median",
"phase): #reconstruct all components into one signal D_k = components.dot(activations) y_k = librosa.istft(D_k",
"None def __init__(self,y,sr,n_components = 5): self.y, self.sr = y,sr self.n_components = n_components def",
"components into one signal D_k = components.dot(activations) y_k = librosa.istft(D_k * phase) return",
"out precussive parts hpss_y = self.hpss() #Perform Short-time Fourier transform D = librosa.stft(hpss_y)",
"= components.dot(activations) y_k = librosa.istft(D_k * phase) return y_k def reconstructComponent(self, components, activation,",
"self.decomposeNMF(hpss_y, S, self.n_components) #reconstruct and return return [self.reconstructComponent( components[:, i], activations[i], phase) for",
"= librosa.istft(D_k * phase) return y_k def reconstructComponent(self, components, activation, phase): D_k =",
"import librosa class MedianNMF: y, sr = None,None n_components = None def __init__(self,y,sr,n_components",
"y_k def reconstructComponent(self, components, activation, phase): D_k = np.multiply.outer(components, activation) y_k = librosa.istft(D_k",
"# Separate the magnitude and phase S, phase = librosa.magphase(D) #NMF decompose to",
"#Perform Short-time Fourier transform D = librosa.stft(hpss_y) # Separate the magnitude and phase",
"reconstructComponent(self, components, activation, phase): D_k = np.multiply.outer(components, activation) y_k = librosa.istft(D_k * phase)",
"librosa.effects.percussive(self.y, margin=margin) def decomposeNMF(self, y, magnitude, n_components): # Decompose by nmf return librosa.decompose.decompose(magnitude,",
"nmf return librosa.decompose.decompose(magnitude, n_components, sort=True) def reconstructFull(self, activations, phase): #reconstruct all components into",
"phase) return y_k def reconstructComponent(self, components, activation, phase): D_k = np.multiply.outer(components, activation) y_k",
"__init__(self,y,sr,n_components = 5): self.y, self.sr = y,sr self.n_components = n_components def decompose(self): #filter",
"import scipy.signal as sp import scipy.spatial.distance as sp_dist import librosa class MedianNMF: y,",
"components, activations = self.decomposeNMF(hpss_y, S, self.n_components) #reconstruct and return return [self.reconstructComponent( components[:, i],",
"return librosa.decompose.decompose(magnitude, n_components, sort=True) def reconstructFull(self, activations, phase): #reconstruct all components into one",
"* phase) #filter out noise using Savitzky-Golay filter component_filtered = sp.savgol_filter(y_k,11,1) return component_filtered",
"= self.decomposeNMF(hpss_y, S, self.n_components) #reconstruct and return return [self.reconstructComponent( components[:, i], activations[i], phase)",
"D_k = components.dot(activations) y_k = librosa.istft(D_k * phase) return y_k def reconstructComponent(self, components,",
"precussive parts hpss_y = self.hpss() #Perform Short-time Fourier transform D = librosa.stft(hpss_y) #",
"scipy.spatial.distance as sp_dist import librosa class MedianNMF: y, sr = None,None n_components =",
"phase = librosa.magphase(D) #NMF decompose to components components, activations = self.decomposeNMF(hpss_y, S, self.n_components)",
"Decompose by nmf return librosa.decompose.decompose(magnitude, n_components, sort=True) def reconstructFull(self, activations, phase): #reconstruct all",
"hpss(self, margin=4.0): #extract precussive components through median filtering return librosa.effects.percussive(self.y, margin=margin) def decomposeNMF(self,",
"np import scipy.signal as sp import scipy.spatial.distance as sp_dist import librosa class MedianNMF:",
"[self.reconstructComponent( components[:, i], activations[i], phase) for i in range(0,len(activations))] def hpss(self, margin=4.0): #extract",
"i in range(0,len(activations))] def hpss(self, margin=4.0): #extract precussive components through median filtering return",
"librosa.istft(D_k * phase) return y_k def reconstructComponent(self, components, activation, phase): D_k = np.multiply.outer(components,",
"magnitude, n_components): # Decompose by nmf return librosa.decompose.decompose(magnitude, n_components, sort=True) def reconstructFull(self, activations,",
"= None,None n_components = None def __init__(self,y,sr,n_components = 5): self.y, self.sr = y,sr",
"i], activations[i], phase) for i in range(0,len(activations))] def hpss(self, margin=4.0): #extract precussive components",
"sort=True) def reconstructFull(self, activations, phase): #reconstruct all components into one signal D_k =",
"n_components = None def __init__(self,y,sr,n_components = 5): self.y, self.sr = y,sr self.n_components =",
"def decomposeNMF(self, y, magnitude, n_components): # Decompose by nmf return librosa.decompose.decompose(magnitude, n_components, sort=True)",
"y, magnitude, n_components): # Decompose by nmf return librosa.decompose.decompose(magnitude, n_components, sort=True) def reconstructFull(self,",
"= 5): self.y, self.sr = y,sr self.n_components = n_components def decompose(self): #filter out",
"one signal D_k = components.dot(activations) y_k = librosa.istft(D_k * phase) return y_k def",
"librosa class MedianNMF: y, sr = None,None n_components = None def __init__(self,y,sr,n_components =",
"and return return [self.reconstructComponent( components[:, i], activations[i], phase) for i in range(0,len(activations))] def",
"D_k = np.multiply.outer(components, activation) y_k = librosa.istft(D_k * phase) #filter out noise using",
"as np import scipy.signal as sp import scipy.spatial.distance as sp_dist import librosa class",
"components[:, i], activations[i], phase) for i in range(0,len(activations))] def hpss(self, margin=4.0): #extract precussive",
"#filter out precussive parts hpss_y = self.hpss() #Perform Short-time Fourier transform D =",
"for i in range(0,len(activations))] def hpss(self, margin=4.0): #extract precussive components through median filtering",
"sp_dist import librosa class MedianNMF: y, sr = None,None n_components = None def",
"def hpss(self, margin=4.0): #extract precussive components through median filtering return librosa.effects.percussive(self.y, margin=margin) def",
"all components into one signal D_k = components.dot(activations) y_k = librosa.istft(D_k * phase)",
"parts hpss_y = self.hpss() #Perform Short-time Fourier transform D = librosa.stft(hpss_y) # Separate",
"self.sr = y,sr self.n_components = n_components def decompose(self): #filter out precussive parts hpss_y",
"librosa.magphase(D) #NMF decompose to components components, activations = self.decomposeNMF(hpss_y, S, self.n_components) #reconstruct and",
"decompose(self): #filter out precussive parts hpss_y = self.hpss() #Perform Short-time Fourier transform D",
"def __init__(self,y,sr,n_components = 5): self.y, self.sr = y,sr self.n_components = n_components def decompose(self):",
"= librosa.magphase(D) #NMF decompose to components components, activations = self.decomposeNMF(hpss_y, S, self.n_components) #reconstruct",
"return return [self.reconstructComponent( components[:, i], activations[i], phase) for i in range(0,len(activations))] def hpss(self,",
"S, self.n_components) #reconstruct and return return [self.reconstructComponent( components[:, i], activations[i], phase) for i",
"and phase S, phase = librosa.magphase(D) #NMF decompose to components components, activations =",
"5): self.y, self.sr = y,sr self.n_components = n_components def decompose(self): #filter out precussive",
"#extract precussive components through median filtering return librosa.effects.percussive(self.y, margin=margin) def decomposeNMF(self, y, magnitude,",
"* phase) return y_k def reconstructComponent(self, components, activation, phase): D_k = np.multiply.outer(components, activation)",
"#reconstruct and return return [self.reconstructComponent( components[:, i], activations[i], phase) for i in range(0,len(activations))]",
"return [self.reconstructComponent( components[:, i], activations[i], phase) for i in range(0,len(activations))] def hpss(self, margin=4.0):",
"phase): D_k = np.multiply.outer(components, activation) y_k = librosa.istft(D_k * phase) #filter out noise",
"phase S, phase = librosa.magphase(D) #NMF decompose to components components, activations = self.decomposeNMF(hpss_y,",
"n_components): # Decompose by nmf return librosa.decompose.decompose(magnitude, n_components, sort=True) def reconstructFull(self, activations, phase):",
"the magnitude and phase S, phase = librosa.magphase(D) #NMF decompose to components components,",
"return y_k def reconstructComponent(self, components, activation, phase): D_k = np.multiply.outer(components, activation) y_k =",
"decompose to components components, activations = self.decomposeNMF(hpss_y, S, self.n_components) #reconstruct and return return",
"y_k = librosa.istft(D_k * phase) return y_k def reconstructComponent(self, components, activation, phase): D_k",
"components, activation, phase): D_k = np.multiply.outer(components, activation) y_k = librosa.istft(D_k * phase) #filter",
"Fourier transform D = librosa.stft(hpss_y) # Separate the magnitude and phase S, phase",
"= n_components def decompose(self): #filter out precussive parts hpss_y = self.hpss() #Perform Short-time",
"signal D_k = components.dot(activations) y_k = librosa.istft(D_k * phase) return y_k def reconstructComponent(self,",
"return librosa.effects.percussive(self.y, margin=margin) def decomposeNMF(self, y, magnitude, n_components): # Decompose by nmf return",
"class MedianNMF: y, sr = None,None n_components = None def __init__(self,y,sr,n_components = 5):",
"MedianNMF: y, sr = None,None n_components = None def __init__(self,y,sr,n_components = 5): self.y,",
"by nmf return librosa.decompose.decompose(magnitude, n_components, sort=True) def reconstructFull(self, activations, phase): #reconstruct all components",
"sr = None,None n_components = None def __init__(self,y,sr,n_components = 5): self.y, self.sr =",
"activation, phase): D_k = np.multiply.outer(components, activation) y_k = librosa.istft(D_k * phase) #filter out",
"median filtering return librosa.effects.percussive(self.y, margin=margin) def decomposeNMF(self, y, magnitude, n_components): # Decompose by",
"decomposeNMF(self, y, magnitude, n_components): # Decompose by nmf return librosa.decompose.decompose(magnitude, n_components, sort=True) def",
"activation) y_k = librosa.istft(D_k * phase) #filter out noise using Savitzky-Golay filter component_filtered",
"numpy as np import scipy.signal as sp import scipy.spatial.distance as sp_dist import librosa"
] |
[
"# Q-learning (SARSAMAX) method #best_action = np.argmax(self.Q[next_state]) #Gt = reward + self.gamma *",
"0.9 def epsilon_greedy_probs(self, state, epsilon): ''' Calculation of probabilities accordgin to a epsilon",
"np.ones(self.nA) * epsilon / self.nA best_action = np.argmax(self.Q[state]) probs[best_action] = 1 - epsilon",
"def select_action(self, state): \"\"\" Given the state, select an action. Params ====== -",
"episode is complete (True or False) \"\"\" # SARSA method next_action = self.select_action(next_state)",
"====== - nA: number of actions available to the agent \"\"\" self.nA =",
"def __init__(self, nA=6): \"\"\" Initialize agent. Params ====== - nA: number of actions",
"epsilon + (epsilon / self.nA) return probs def select_action(self, state): \"\"\" Given the",
"step(self, state, action, reward, next_state, done): \"\"\" Update the agent's knowledge, using the",
"action, reward, next_state, done): \"\"\" Update the agent's knowledge, using the most recently",
"+ (epsilon / self.nA) return probs def select_action(self, state): \"\"\" Given the state,",
"\"\"\" # SARSA method next_action = self.select_action(next_state) Gt = reward + self.gamma *",
"tuple. Params ====== - state: the previous state of the environment - action:",
"\"\"\" Given the state, select an action. Params ====== - state: the current",
"agent's knowledge, using the most recently sampled tuple. Params ====== - state: the",
"- action: the agent's previous choice of action - reward: last reward received",
"accordgin to a epsilon greedy policy''' probs = np.ones(self.nA) * epsilon / self.nA",
"self.nA) return probs def select_action(self, state): \"\"\" Given the state, select an action.",
"select_action(self, state): \"\"\" Given the state, select an action. Params ====== - state:",
"agent. Params ====== - nA: number of actions available to the agent \"\"\"",
"reward + self.gamma * self.Q[next_state][best_action] self.Q[state][action] += self.alpha * (Gt - self.Q[state][action]) #",
"probs = self.epsilon_greedy_probs(state, epsilon) # Action selection acc. to epsilon-greedy policy action =",
"the previous state of the environment - action: the agent's previous choice of",
"action space \"\"\" # Random action # action = np.random.choice(self.nA) # Epsilon decay",
"action: an integer, compatible with the task's action space \"\"\" # Random action",
"+= self.alpha * (Gt - self.Q[state][action]) # i_episode update for calculation of epsilon",
"(Gt - self.Q[state][action]) # i_episode update for calculation of epsilon decay self.i_episode +=",
"class Agent: def __init__(self, nA=6): \"\"\" Initialize agent. Params ====== - nA: number",
"the agent's previous choice of action - reward: last reward received - next_state:",
"- next_state: the current state of the environment - done: whether the episode",
"action def step(self, state, action, reward, next_state, done): \"\"\" Update the agent's knowledge,",
"policy action = np.random.choice(np.arange(self.nA), p = probs) return action def step(self, state, action,",
"= 0.04 self.gamma = 0.9 def epsilon_greedy_probs(self, state, epsilon): ''' Calculation of probabilities",
"state, action, reward, next_state, done): \"\"\" Update the agent's knowledge, using the most",
"self.i_episode = 1.0 self.alpha = 0.04 self.gamma = 0.9 def epsilon_greedy_probs(self, state, epsilon):",
"probs = np.ones(self.nA) * epsilon / self.nA best_action = np.argmax(self.Q[state]) probs[best_action] = 1",
"previous state of the environment - action: the agent's previous choice of action",
"state, epsilon): ''' Calculation of probabilities accordgin to a epsilon greedy policy''' probs",
"environment - action: the agent's previous choice of action - reward: last reward",
"- done: whether the episode is complete (True or False) \"\"\" # SARSA",
"self.alpha = 0.04 self.gamma = 0.9 def epsilon_greedy_probs(self, state, epsilon): ''' Calculation of",
"= 1 - epsilon + (epsilon / self.nA) return probs def select_action(self, state):",
"environment Returns ======= - action: an integer, compatible with the task's action space",
"np.argmax(self.Q[state]) probs[best_action] = 1 - epsilon + (epsilon / self.nA) return probs def",
"import defaultdict class Agent: def __init__(self, nA=6): \"\"\" Initialize agent. Params ====== -",
"the state, select an action. Params ====== - state: the current state of",
"- state: the current state of the environment Returns ======= - action: an",
"reward, next_state, done): \"\"\" Update the agent's knowledge, using the most recently sampled",
"= np.random.choice(self.nA) # Epsilon decay epsilon = self.epsilon_start / self.i_episode # Epsilon-greedy policy/probabilities",
"self.epsilon_start = 1.0 self.i_episode = 1.0 self.alpha = 0.04 self.gamma = 0.9 def",
"self.Q = defaultdict(lambda: np.zeros(self.nA)) self.epsilon_start = 1.0 self.i_episode = 1.0 self.alpha = 0.04",
"whether the episode is complete (True or False) \"\"\" # SARSA method next_action",
"self.nA = nA self.Q = defaultdict(lambda: np.zeros(self.nA)) self.epsilon_start = 1.0 self.i_episode = 1.0",
"np.argmax(self.Q[next_state]) #Gt = reward + self.gamma * self.Q[next_state][best_action] self.Q[state][action] += self.alpha * (Gt",
"np from collections import defaultdict class Agent: def __init__(self, nA=6): \"\"\" Initialize agent.",
"1.0 self.alpha = 0.04 self.gamma = 0.9 def epsilon_greedy_probs(self, state, epsilon): ''' Calculation",
"selection acc. to epsilon-greedy policy action = np.random.choice(np.arange(self.nA), p = probs) return action",
"np.random.choice(np.arange(self.nA), p = probs) return action def step(self, state, action, reward, next_state, done):",
"the most recently sampled tuple. Params ====== - state: the previous state of",
"self.Q[state][action] += self.alpha * (Gt - self.Q[state][action]) # i_episode update for calculation of",
"of the environment - action: the agent's previous choice of action - reward:",
"epsilon): ''' Calculation of probabilities accordgin to a epsilon greedy policy''' probs =",
"Initialize agent. Params ====== - nA: number of actions available to the agent",
"np.zeros(self.nA)) self.epsilon_start = 1.0 self.i_episode = 1.0 self.alpha = 0.04 self.gamma = 0.9",
"= np.ones(self.nA) * epsilon / self.nA best_action = np.argmax(self.Q[state]) probs[best_action] = 1 -",
"* epsilon / self.nA best_action = np.argmax(self.Q[state]) probs[best_action] = 1 - epsilon +",
"of actions available to the agent \"\"\" self.nA = nA self.Q = defaultdict(lambda:",
"/ self.i_episode # Epsilon-greedy policy/probabilities probs = self.epsilon_greedy_probs(state, epsilon) # Action selection acc.",
"probs[best_action] = 1 - epsilon + (epsilon / self.nA) return probs def select_action(self,",
"- nA: number of actions available to the agent \"\"\" self.nA = nA",
"epsilon_greedy_probs(self, state, epsilon): ''' Calculation of probabilities accordgin to a epsilon greedy policy'''",
"policy''' probs = np.ones(self.nA) * epsilon / self.nA best_action = np.argmax(self.Q[state]) probs[best_action] =",
"state of the environment Returns ======= - action: an integer, compatible with the",
"= self.epsilon_greedy_probs(state, epsilon) # Action selection acc. to epsilon-greedy policy action = np.random.choice(np.arange(self.nA),",
"Params ====== - state: the current state of the environment Returns ======= -",
"of probabilities accordgin to a epsilon greedy policy''' probs = np.ones(self.nA) * epsilon",
"Epsilon decay epsilon = self.epsilon_start / self.i_episode # Epsilon-greedy policy/probabilities probs = self.epsilon_greedy_probs(state,",
"# Action selection acc. to epsilon-greedy policy action = np.random.choice(np.arange(self.nA), p = probs)",
"return probs def select_action(self, state): \"\"\" Given the state, select an action. Params",
"to epsilon-greedy policy action = np.random.choice(np.arange(self.nA), p = probs) return action def step(self,",
"the environment - done: whether the episode is complete (True or False) \"\"\"",
"the current state of the environment Returns ======= - action: an integer, compatible",
"False) \"\"\" # SARSA method next_action = self.select_action(next_state) Gt = reward + self.gamma",
"current state of the environment - done: whether the episode is complete (True",
"an integer, compatible with the task's action space \"\"\" # Random action #",
"# Epsilon decay epsilon = self.epsilon_start / self.i_episode # Epsilon-greedy policy/probabilities probs =",
"complete (True or False) \"\"\" # SARSA method next_action = self.select_action(next_state) Gt =",
"to a epsilon greedy policy''' probs = np.ones(self.nA) * epsilon / self.nA best_action",
"best_action = np.argmax(self.Q[state]) probs[best_action] = 1 - epsilon + (epsilon / self.nA) return",
"action = np.random.choice(self.nA) # Epsilon decay epsilon = self.epsilon_start / self.i_episode # Epsilon-greedy",
"self.gamma * self.Q[next_state][next_action] # Q-learning (SARSAMAX) method #best_action = np.argmax(self.Q[next_state]) #Gt = reward",
"= np.argmax(self.Q[next_state]) #Gt = reward + self.gamma * self.Q[next_state][best_action] self.Q[state][action] += self.alpha *",
"state, select an action. Params ====== - state: the current state of the",
"state: the current state of the environment Returns ======= - action: an integer,",
"greedy policy''' probs = np.ones(self.nA) * epsilon / self.nA best_action = np.argmax(self.Q[state]) probs[best_action]",
"Q-learning (SARSAMAX) method #best_action = np.argmax(self.Q[next_state]) #Gt = reward + self.gamma * self.Q[next_state][best_action]",
"compatible with the task's action space \"\"\" # Random action # action =",
"knowledge, using the most recently sampled tuple. Params ====== - state: the previous",
"of the environment Returns ======= - action: an integer, compatible with the task's",
"= np.random.choice(np.arange(self.nA), p = probs) return action def step(self, state, action, reward, next_state,",
"action. Params ====== - state: the current state of the environment Returns =======",
"action - reward: last reward received - next_state: the current state of the",
"method next_action = self.select_action(next_state) Gt = reward + self.gamma * self.Q[next_state][next_action] # Q-learning",
"\"\"\" Update the agent's knowledge, using the most recently sampled tuple. Params ======",
"self.epsilon_greedy_probs(state, epsilon) # Action selection acc. to epsilon-greedy policy action = np.random.choice(np.arange(self.nA), p",
"def step(self, state, action, reward, next_state, done): \"\"\" Update the agent's knowledge, using",
"using the most recently sampled tuple. Params ====== - state: the previous state",
"next_state: the current state of the environment - done: whether the episode is",
"Calculation of probabilities accordgin to a epsilon greedy policy''' probs = np.ones(self.nA) *",
"- action: an integer, compatible with the task's action space \"\"\" # Random",
"- self.Q[state][action]) # i_episode update for calculation of epsilon decay self.i_episode += 1.0",
"\"\"\" Initialize agent. Params ====== - nA: number of actions available to the",
"policy/probabilities probs = self.epsilon_greedy_probs(state, epsilon) # Action selection acc. to epsilon-greedy policy action",
"previous choice of action - reward: last reward received - next_state: the current",
"Given the state, select an action. Params ====== - state: the current state",
"= nA self.Q = defaultdict(lambda: np.zeros(self.nA)) self.epsilon_start = 1.0 self.i_episode = 1.0 self.alpha",
"\"\"\" # Random action # action = np.random.choice(self.nA) # Epsilon decay epsilon =",
"return action def step(self, state, action, reward, next_state, done): \"\"\" Update the agent's",
"environment - done: whether the episode is complete (True or False) \"\"\" #",
"as np from collections import defaultdict class Agent: def __init__(self, nA=6): \"\"\" Initialize",
"/ self.nA) return probs def select_action(self, state): \"\"\" Given the state, select an",
"integer, compatible with the task's action space \"\"\" # Random action # action",
"Params ====== - nA: number of actions available to the agent \"\"\" self.nA",
"= 1.0 self.alpha = 0.04 self.gamma = 0.9 def epsilon_greedy_probs(self, state, epsilon): '''",
"(True or False) \"\"\" # SARSA method next_action = self.select_action(next_state) Gt = reward",
"next_state, done): \"\"\" Update the agent's knowledge, using the most recently sampled tuple.",
"self.Q[next_state][best_action] self.Q[state][action] += self.alpha * (Gt - self.Q[state][action]) # i_episode update for calculation",
"state of the environment - action: the agent's previous choice of action -",
"0.04 self.gamma = 0.9 def epsilon_greedy_probs(self, state, epsilon): ''' Calculation of probabilities accordgin",
"the task's action space \"\"\" # Random action # action = np.random.choice(self.nA) #",
"from collections import defaultdict class Agent: def __init__(self, nA=6): \"\"\" Initialize agent. Params",
"state of the environment - done: whether the episode is complete (True or",
"Action selection acc. to epsilon-greedy policy action = np.random.choice(np.arange(self.nA), p = probs) return",
"to the agent \"\"\" self.nA = nA self.Q = defaultdict(lambda: np.zeros(self.nA)) self.epsilon_start =",
"of the environment - done: whether the episode is complete (True or False)",
"epsilon greedy policy''' probs = np.ones(self.nA) * epsilon / self.nA best_action = np.argmax(self.Q[state])",
"+ self.gamma * self.Q[next_state][next_action] # Q-learning (SARSAMAX) method #best_action = np.argmax(self.Q[next_state]) #Gt =",
"__init__(self, nA=6): \"\"\" Initialize agent. Params ====== - nA: number of actions available",
"probs) return action def step(self, state, action, reward, next_state, done): \"\"\" Update the",
"self.epsilon_start / self.i_episode # Epsilon-greedy policy/probabilities probs = self.epsilon_greedy_probs(state, epsilon) # Action selection",
"available to the agent \"\"\" self.nA = nA self.Q = defaultdict(lambda: np.zeros(self.nA)) self.epsilon_start",
"done): \"\"\" Update the agent's knowledge, using the most recently sampled tuple. Params",
"action = np.random.choice(np.arange(self.nA), p = probs) return action def step(self, state, action, reward,",
"+ self.gamma * self.Q[next_state][best_action] self.Q[state][action] += self.alpha * (Gt - self.Q[state][action]) # i_episode",
"Random action # action = np.random.choice(self.nA) # Epsilon decay epsilon = self.epsilon_start /",
"reward: last reward received - next_state: the current state of the environment -",
"reward received - next_state: the current state of the environment - done: whether",
"= self.epsilon_start / self.i_episode # Epsilon-greedy policy/probabilities probs = self.epsilon_greedy_probs(state, epsilon) # Action",
"actions available to the agent \"\"\" self.nA = nA self.Q = defaultdict(lambda: np.zeros(self.nA))",
"epsilon / self.nA best_action = np.argmax(self.Q[state]) probs[best_action] = 1 - epsilon + (epsilon",
"====== - state: the previous state of the environment - action: the agent's",
"= defaultdict(lambda: np.zeros(self.nA)) self.epsilon_start = 1.0 self.i_episode = 1.0 self.alpha = 0.04 self.gamma",
"acc. to epsilon-greedy policy action = np.random.choice(np.arange(self.nA), p = probs) return action def",
"* self.Q[next_state][next_action] # Q-learning (SARSAMAX) method #best_action = np.argmax(self.Q[next_state]) #Gt = reward +",
"probs def select_action(self, state): \"\"\" Given the state, select an action. Params ======",
"Update the agent's knowledge, using the most recently sampled tuple. Params ====== -",
"self.alpha * (Gt - self.Q[state][action]) # i_episode update for calculation of epsilon decay",
"the agent \"\"\" self.nA = nA self.Q = defaultdict(lambda: np.zeros(self.nA)) self.epsilon_start = 1.0",
"= self.select_action(next_state) Gt = reward + self.gamma * self.Q[next_state][next_action] # Q-learning (SARSAMAX) method",
"#best_action = np.argmax(self.Q[next_state]) #Gt = reward + self.gamma * self.Q[next_state][best_action] self.Q[state][action] += self.alpha",
"most recently sampled tuple. Params ====== - state: the previous state of the",
"# Epsilon-greedy policy/probabilities probs = self.epsilon_greedy_probs(state, epsilon) # Action selection acc. to epsilon-greedy",
"state: the previous state of the environment - action: the agent's previous choice",
"decay epsilon = self.epsilon_start / self.i_episode # Epsilon-greedy policy/probabilities probs = self.epsilon_greedy_probs(state, epsilon)",
"or False) \"\"\" # SARSA method next_action = self.select_action(next_state) Gt = reward +",
"epsilon-greedy policy action = np.random.choice(np.arange(self.nA), p = probs) return action def step(self, state,",
"1 - epsilon + (epsilon / self.nA) return probs def select_action(self, state): \"\"\"",
"state): \"\"\" Given the state, select an action. Params ====== - state: the",
"with the task's action space \"\"\" # Random action # action = np.random.choice(self.nA)",
"= probs) return action def step(self, state, action, reward, next_state, done): \"\"\" Update",
"self.gamma = 0.9 def epsilon_greedy_probs(self, state, epsilon): ''' Calculation of probabilities accordgin to",
"nA: number of actions available to the agent \"\"\" self.nA = nA self.Q",
"collections import defaultdict class Agent: def __init__(self, nA=6): \"\"\" Initialize agent. Params ======",
"epsilon = self.epsilon_start / self.i_episode # Epsilon-greedy policy/probabilities probs = self.epsilon_greedy_probs(state, epsilon) #",
"Gt = reward + self.gamma * self.Q[next_state][next_action] # Q-learning (SARSAMAX) method #best_action =",
"method #best_action = np.argmax(self.Q[next_state]) #Gt = reward + self.gamma * self.Q[next_state][best_action] self.Q[state][action] +=",
"the episode is complete (True or False) \"\"\" # SARSA method next_action =",
"- reward: last reward received - next_state: the current state of the environment",
"(SARSAMAX) method #best_action = np.argmax(self.Q[next_state]) #Gt = reward + self.gamma * self.Q[next_state][best_action] self.Q[state][action]",
"import numpy as np from collections import defaultdict class Agent: def __init__(self, nA=6):",
"# action = np.random.choice(self.nA) # Epsilon decay epsilon = self.epsilon_start / self.i_episode #",
"# Random action # action = np.random.choice(self.nA) # Epsilon decay epsilon = self.epsilon_start",
"- state: the previous state of the environment - action: the agent's previous",
"agent \"\"\" self.nA = nA self.Q = defaultdict(lambda: np.zeros(self.nA)) self.epsilon_start = 1.0 self.i_episode",
"p = probs) return action def step(self, state, action, reward, next_state, done): \"\"\"",
"last reward received - next_state: the current state of the environment - done:",
"= np.argmax(self.Q[state]) probs[best_action] = 1 - epsilon + (epsilon / self.nA) return probs",
"the environment Returns ======= - action: an integer, compatible with the task's action",
"(epsilon / self.nA) return probs def select_action(self, state): \"\"\" Given the state, select",
"nA self.Q = defaultdict(lambda: np.zeros(self.nA)) self.epsilon_start = 1.0 self.i_episode = 1.0 self.alpha =",
"nA=6): \"\"\" Initialize agent. Params ====== - nA: number of actions available to",
"* (Gt - self.Q[state][action]) # i_episode update for calculation of epsilon decay self.i_episode",
"#Gt = reward + self.gamma * self.Q[next_state][best_action] self.Q[state][action] += self.alpha * (Gt -",
"agent's previous choice of action - reward: last reward received - next_state: the",
"SARSA method next_action = self.select_action(next_state) Gt = reward + self.gamma * self.Q[next_state][next_action] #",
"= 0.9 def epsilon_greedy_probs(self, state, epsilon): ''' Calculation of probabilities accordgin to a",
"Params ====== - state: the previous state of the environment - action: the",
"= reward + self.gamma * self.Q[next_state][best_action] self.Q[state][action] += self.alpha * (Gt - self.Q[state][action])",
"reward + self.gamma * self.Q[next_state][next_action] # Q-learning (SARSAMAX) method #best_action = np.argmax(self.Q[next_state]) #Gt",
"self.nA best_action = np.argmax(self.Q[state]) probs[best_action] = 1 - epsilon + (epsilon / self.nA)",
"the environment - action: the agent's previous choice of action - reward: last",
"task's action space \"\"\" # Random action # action = np.random.choice(self.nA) # Epsilon",
"self.select_action(next_state) Gt = reward + self.gamma * self.Q[next_state][next_action] # Q-learning (SARSAMAX) method #best_action",
"Agent: def __init__(self, nA=6): \"\"\" Initialize agent. Params ====== - nA: number of",
"action # action = np.random.choice(self.nA) # Epsilon decay epsilon = self.epsilon_start / self.i_episode",
"self.i_episode # Epsilon-greedy policy/probabilities probs = self.epsilon_greedy_probs(state, epsilon) # Action selection acc. to",
"action: the agent's previous choice of action - reward: last reward received -",
"- epsilon + (epsilon / self.nA) return probs def select_action(self, state): \"\"\" Given",
"next_action = self.select_action(next_state) Gt = reward + self.gamma * self.Q[next_state][next_action] # Q-learning (SARSAMAX)",
"======= - action: an integer, compatible with the task's action space \"\"\" #",
"''' Calculation of probabilities accordgin to a epsilon greedy policy''' probs = np.ones(self.nA)",
"Returns ======= - action: an integer, compatible with the task's action space \"\"\"",
"an action. Params ====== - state: the current state of the environment Returns",
"= reward + self.gamma * self.Q[next_state][next_action] # Q-learning (SARSAMAX) method #best_action = np.argmax(self.Q[next_state])",
"defaultdict(lambda: np.zeros(self.nA)) self.epsilon_start = 1.0 self.i_episode = 1.0 self.alpha = 0.04 self.gamma =",
"np.random.choice(self.nA) # Epsilon decay epsilon = self.epsilon_start / self.i_episode # Epsilon-greedy policy/probabilities probs",
"recently sampled tuple. Params ====== - state: the previous state of the environment",
"sampled tuple. Params ====== - state: the previous state of the environment -",
"current state of the environment Returns ======= - action: an integer, compatible with",
"/ self.nA best_action = np.argmax(self.Q[state]) probs[best_action] = 1 - epsilon + (epsilon /",
"select an action. Params ====== - state: the current state of the environment",
"done: whether the episode is complete (True or False) \"\"\" # SARSA method",
"of action - reward: last reward received - next_state: the current state of",
"number of actions available to the agent \"\"\" self.nA = nA self.Q =",
"= 1.0 self.i_episode = 1.0 self.alpha = 0.04 self.gamma = 0.9 def epsilon_greedy_probs(self,",
"defaultdict class Agent: def __init__(self, nA=6): \"\"\" Initialize agent. Params ====== - nA:",
"space \"\"\" # Random action # action = np.random.choice(self.nA) # Epsilon decay epsilon",
"received - next_state: the current state of the environment - done: whether the",
"self.gamma * self.Q[next_state][best_action] self.Q[state][action] += self.alpha * (Gt - self.Q[state][action]) # i_episode update",
"* self.Q[next_state][best_action] self.Q[state][action] += self.alpha * (Gt - self.Q[state][action]) # i_episode update for",
"\"\"\" self.nA = nA self.Q = defaultdict(lambda: np.zeros(self.nA)) self.epsilon_start = 1.0 self.i_episode =",
"the current state of the environment - done: whether the episode is complete",
"choice of action - reward: last reward received - next_state: the current state",
"====== - state: the current state of the environment Returns ======= - action:",
"Epsilon-greedy policy/probabilities probs = self.epsilon_greedy_probs(state, epsilon) # Action selection acc. to epsilon-greedy policy",
"is complete (True or False) \"\"\" # SARSA method next_action = self.select_action(next_state) Gt",
"def epsilon_greedy_probs(self, state, epsilon): ''' Calculation of probabilities accordgin to a epsilon greedy",
"# SARSA method next_action = self.select_action(next_state) Gt = reward + self.gamma * self.Q[next_state][next_action]",
"self.Q[next_state][next_action] # Q-learning (SARSAMAX) method #best_action = np.argmax(self.Q[next_state]) #Gt = reward + self.gamma",
"numpy as np from collections import defaultdict class Agent: def __init__(self, nA=6): \"\"\"",
"1.0 self.i_episode = 1.0 self.alpha = 0.04 self.gamma = 0.9 def epsilon_greedy_probs(self, state,",
"probabilities accordgin to a epsilon greedy policy''' probs = np.ones(self.nA) * epsilon /",
"the agent's knowledge, using the most recently sampled tuple. Params ====== - state:",
"epsilon) # Action selection acc. to epsilon-greedy policy action = np.random.choice(np.arange(self.nA), p =",
"a epsilon greedy policy''' probs = np.ones(self.nA) * epsilon / self.nA best_action ="
] |
[
"meets' assemblies under attendee's organization if self.registration and self.registration.assembly.need_age and self.infos.bed_needs < 1",
"'registration'], condition=models.Q(is_removed=False), name=\"attending_attendee_registration\") ] indexes = [ GinIndex(fields=['infos'], name='attending_infos_gin', ), ] @property def",
"reverse('attending_detail', args=[str(self.id)]) class Meta: db_table = 'persons_attendings' ordering = ['registration'] constraints = [",
"the participant\") def get_absolute_url(self): return reverse('attending_detail', args=[str(self.id)]) class Meta: db_table = 'persons_attendings' ordering",
"attending_label(self): return f'({self.registration}) {self.attendee.display_label}' # parentheses needed in datagrid_attendee_update_view.js @cached_property def all_addresses(self): return",
"even no data') # Todo: infos contains the following display data which are",
"@cached_property def all_addresses(self): return '; '.join([a.street for a in self.attendee.places.all()]) def __str__(self): return",
"age, bed_needs, mobility def clean(self): # fetching birthday from attendee record first #",
"= models.ForeignKey(Attendee, null=False, blank=False, on_delete=models.CASCADE, related_name=\"attendings\") gatherings = models.ManyToManyField('occasions.Gathering', through='occasions.Attendance') category = models.CharField(max_length=20,",
"coworker, etc\") meets = models.ManyToManyField('occasions.Meet', through='AttendingMeet', related_name=\"meets\") infos = JSONField(null=True, blank=True, default=dict, help_text='Example:",
"name='attending_infos_gin', ), ] @property def main_contact(self): return self.registration.registrant @cached_property def meet_names(self): return \",\".join([d.display_name",
"return \",\".join([d.display_name for d in self.meets.all()]) @property def attending_label(self): return f'({self.registration}) {self.attendee.display_label}' #",
"return f'({self.registration}) {self.attendee.display_label}' # parentheses needed in datagrid_attendee_update_view.js @cached_property def all_addresses(self): return ';",
"help_text=\"normal, not_going, coworker, etc\") meets = models.ManyToManyField('occasions.Meet', through='AttendingMeet', related_name=\"meets\") infos = JSONField(null=True, blank=True,",
"models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') registration = models.ForeignKey(Registration, null=True, blank=True, on_delete=models.SET_NULL) attendee = models.ForeignKey(Attendee,",
"def attending_label(self): return f'({self.registration}) {self.attendee.display_label}' # parentheses needed in datagrid_attendee_update_view.js @cached_property def all_addresses(self):",
"from django.utils.functional import cached_property from model_utils.models import TimeStampedModel, SoftDeletableModel from . import Note,",
"args=[str(self.id)]) class Meta: db_table = 'persons_attendings' ordering = ['registration'] constraints = [ models.UniqueConstraint(fields=['attendee',",
"are not for table join/query: age, bed_needs, mobility def clean(self): # fetching birthday",
"= models.ForeignKey(Registration, null=True, blank=True, on_delete=models.SET_NULL) attendee = models.ForeignKey(Attendee, null=False, blank=False, on_delete=models.CASCADE, related_name=\"attendings\") gatherings",
"here even no data') # Todo: infos contains the following display data which",
"etc\") meets = models.ManyToManyField('occasions.Meet', through='AttendingMeet', related_name=\"meets\") infos = JSONField(null=True, blank=True, default=dict, help_text='Example: {\"grade\":",
"bed_needs, mobility def clean(self): # fetching birthday from attendee record first # Todo:",
"registration = models.ForeignKey(Registration, null=True, blank=True, on_delete=models.SET_NULL) attendee = models.ForeignKey(Attendee, null=False, blank=False, on_delete=models.CASCADE, related_name=\"attendings\")",
"\"bed_needs\": 1, \"mobility\": 300}. Please keep {} here even no data') # Todo:",
"models.ForeignKey(Registration, null=True, blank=True, on_delete=models.SET_NULL) attendee = models.ForeignKey(Attendee, null=False, blank=False, on_delete=models.CASCADE, related_name=\"attendings\") gatherings =",
"django.core.exceptions import ValidationError from django.urls import reverse from django.contrib.contenttypes.fields import GenericRelation from django.contrib.postgres.fields.jsonb",
"category = models.CharField(max_length=20, null=False, blank=False, default=\"normal\", help_text=\"normal, not_going, coworker, etc\") meets = models.ManyToManyField('occasions.Meet',",
"organization if self.registration and self.registration.assembly.need_age and self.infos.bed_needs < 1 and self.info.age is None:",
"None: raise ValidationError(\"You must specify age for the participant\") def get_absolute_url(self): return reverse('attending_detail',",
"attendee = models.ForeignKey(Attendee, null=False, blank=False, on_delete=models.CASCADE, related_name=\"attendings\") gatherings = models.ManyToManyField('occasions.Gathering', through='occasions.Attendance') category =",
"help_text='Example: {\"grade\": 5, \"age\": 11, \"bed_needs\": 1, \"mobility\": 300}. Please keep {} here",
"constraints = [ models.UniqueConstraint(fields=['attendee', 'registration'], condition=models.Q(is_removed=False), name=\"attending_attendee_registration\") ] indexes = [ GinIndex(fields=['infos'], name='attending_infos_gin',",
"import Note, Utility, Attendee, Registration class Attending(TimeStampedModel, SoftDeletableModel, Utility): notes = GenericRelation(Note) id",
"contains the following display data which are not for table join/query: age, bed_needs,",
"import GenericRelation from django.contrib.postgres.fields.jsonb import JSONField from django.contrib.postgres.indexes import GinIndex from django.utils.functional import",
"import reverse from django.contrib.contenttypes.fields import GenericRelation from django.contrib.postgres.fields.jsonb import JSONField from django.contrib.postgres.indexes import",
"import cached_property from model_utils.models import TimeStampedModel, SoftDeletableModel from . import Note, Utility, Attendee,",
"age for the participant\") def get_absolute_url(self): return reverse('attending_detail', args=[str(self.id)]) class Meta: db_table =",
"# Todo: check if meets' assemblies under attendee's organization if self.registration and self.registration.assembly.need_age",
"1 and self.info.age is None: raise ValidationError(\"You must specify age for the participant\")",
"indexes = [ GinIndex(fields=['infos'], name='attending_infos_gin', ), ] @property def main_contact(self): return self.registration.registrant @cached_property",
". import Note, Utility, Attendee, Registration class Attending(TimeStampedModel, SoftDeletableModel, Utility): notes = GenericRelation(Note)",
"ValidationError(\"You must specify age for the participant\") def get_absolute_url(self): return reverse('attending_detail', args=[str(self.id)]) class",
"from django.urls import reverse from django.contrib.contenttypes.fields import GenericRelation from django.contrib.postgres.fields.jsonb import JSONField from",
"JSONField from django.contrib.postgres.indexes import GinIndex from django.utils.functional import cached_property from model_utils.models import TimeStampedModel,",
"data which are not for table join/query: age, bed_needs, mobility def clean(self): #",
"from django.contrib.postgres.indexes import GinIndex from django.utils.functional import cached_property from model_utils.models import TimeStampedModel, SoftDeletableModel",
"data') # Todo: infos contains the following display data which are not for",
"blank=False, default=\"normal\", help_text=\"normal, not_going, coworker, etc\") meets = models.ManyToManyField('occasions.Meet', through='AttendingMeet', related_name=\"meets\") infos =",
"specify age for the participant\") def get_absolute_url(self): return reverse('attending_detail', args=[str(self.id)]) class Meta: db_table",
"{\"grade\": 5, \"age\": 11, \"bed_needs\": 1, \"mobility\": 300}. Please keep {} here even",
"from django.core.exceptions import ValidationError from django.urls import reverse from django.contrib.contenttypes.fields import GenericRelation from",
"return '; '.join([a.street for a in self.attendee.places.all()]) def __str__(self): return '%s %s' %",
"clean(self): # fetching birthday from attendee record first # Todo: check if meets'",
"blank=True, on_delete=models.SET_NULL) attendee = models.ForeignKey(Attendee, null=False, blank=False, on_delete=models.CASCADE, related_name=\"attendings\") gatherings = models.ManyToManyField('occasions.Gathering', through='occasions.Attendance')",
"\"age\": 11, \"bed_needs\": 1, \"mobility\": 300}. Please keep {} here even no data')",
"# Todo: infos contains the following display data which are not for table",
"models.ForeignKey(Attendee, null=False, blank=False, on_delete=models.CASCADE, related_name=\"attendings\") gatherings = models.ManyToManyField('occasions.Gathering', through='occasions.Attendance') category = models.CharField(max_length=20, null=False,",
"id = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') registration = models.ForeignKey(Registration, null=True, blank=True, on_delete=models.SET_NULL) attendee",
"related_name=\"attendings\") gatherings = models.ManyToManyField('occasions.Gathering', through='occasions.Attendance') category = models.CharField(max_length=20, null=False, blank=False, default=\"normal\", help_text=\"normal, not_going,",
"reverse from django.contrib.contenttypes.fields import GenericRelation from django.contrib.postgres.fields.jsonb import JSONField from django.contrib.postgres.indexes import GinIndex",
"def all_addresses(self): return '; '.join([a.street for a in self.attendee.places.all()]) def __str__(self): return '%s",
"Utility, Attendee, Registration class Attending(TimeStampedModel, SoftDeletableModel, Utility): notes = GenericRelation(Note) id = models.BigAutoField(auto_created=True,",
"# fetching birthday from attendee record first # Todo: check if meets' assemblies",
"import models from django.core.exceptions import ValidationError from django.urls import reverse from django.contrib.contenttypes.fields import",
"blank=True, default=dict, help_text='Example: {\"grade\": 5, \"age\": 11, \"bed_needs\": 1, \"mobility\": 300}. Please keep",
"Attending(TimeStampedModel, SoftDeletableModel, Utility): notes = GenericRelation(Note) id = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') registration",
"table join/query: age, bed_needs, mobility def clean(self): # fetching birthday from attendee record",
"TimeStampedModel, SoftDeletableModel from . import Note, Utility, Attendee, Registration class Attending(TimeStampedModel, SoftDeletableModel, Utility):",
"in datagrid_attendee_update_view.js @cached_property def all_addresses(self): return '; '.join([a.street for a in self.attendee.places.all()]) def",
"under attendee's organization if self.registration and self.registration.assembly.need_age and self.infos.bed_needs < 1 and self.info.age",
"if meets' assemblies under attendee's organization if self.registration and self.registration.assembly.need_age and self.infos.bed_needs <",
"raise ValidationError(\"You must specify age for the participant\") def get_absolute_url(self): return reverse('attending_detail', args=[str(self.id)])",
"verbose_name='ID') registration = models.ForeignKey(Registration, null=True, blank=True, on_delete=models.SET_NULL) attendee = models.ForeignKey(Attendee, null=False, blank=False, on_delete=models.CASCADE,",
"11, \"bed_needs\": 1, \"mobility\": 300}. Please keep {} here even no data') #",
"\",\".join([d.display_name for d in self.meets.all()]) @property def attending_label(self): return f'({self.registration}) {self.attendee.display_label}' # parentheses",
"null=False, blank=False, on_delete=models.CASCADE, related_name=\"attendings\") gatherings = models.ManyToManyField('occasions.Gathering', through='occasions.Attendance') category = models.CharField(max_length=20, null=False, blank=False,",
"primary_key=True, serialize=False, verbose_name='ID') registration = models.ForeignKey(Registration, null=True, blank=True, on_delete=models.SET_NULL) attendee = models.ForeignKey(Attendee, null=False,",
"GinIndex from django.utils.functional import cached_property from model_utils.models import TimeStampedModel, SoftDeletableModel from . import",
"through='occasions.Attendance') category = models.CharField(max_length=20, null=False, blank=False, default=\"normal\", help_text=\"normal, not_going, coworker, etc\") meets =",
"self.registration.assembly.need_age and self.infos.bed_needs < 1 and self.info.age is None: raise ValidationError(\"You must specify",
"# parentheses needed in datagrid_attendee_update_view.js @cached_property def all_addresses(self): return '; '.join([a.street for a",
"@property def attending_label(self): return f'({self.registration}) {self.attendee.display_label}' # parentheses needed in datagrid_attendee_update_view.js @cached_property def",
"default=\"normal\", help_text=\"normal, not_going, coworker, etc\") meets = models.ManyToManyField('occasions.Meet', through='AttendingMeet', related_name=\"meets\") infos = JSONField(null=True,",
"= [ models.UniqueConstraint(fields=['attendee', 'registration'], condition=models.Q(is_removed=False), name=\"attending_attendee_registration\") ] indexes = [ GinIndex(fields=['infos'], name='attending_infos_gin', ),",
"must specify age for the participant\") def get_absolute_url(self): return reverse('attending_detail', args=[str(self.id)]) class Meta:",
"all_addresses(self): return '; '.join([a.street for a in self.attendee.places.all()]) def __str__(self): return '%s %s'",
"django.contrib.contenttypes.fields import GenericRelation from django.contrib.postgres.fields.jsonb import JSONField from django.contrib.postgres.indexes import GinIndex from django.utils.functional",
"Registration class Attending(TimeStampedModel, SoftDeletableModel, Utility): notes = GenericRelation(Note) id = models.BigAutoField(auto_created=True, primary_key=True, serialize=False,",
"@cached_property def meet_names(self): return \",\".join([d.display_name for d in self.meets.all()]) @property def attending_label(self): return",
"blank=False, on_delete=models.CASCADE, related_name=\"attendings\") gatherings = models.ManyToManyField('occasions.Gathering', through='occasions.Attendance') category = models.CharField(max_length=20, null=False, blank=False, default=\"normal\",",
"import TimeStampedModel, SoftDeletableModel from . import Note, Utility, Attendee, Registration class Attending(TimeStampedModel, SoftDeletableModel,",
"join/query: age, bed_needs, mobility def clean(self): # fetching birthday from attendee record first",
"and self.info.age is None: raise ValidationError(\"You must specify age for the participant\") def",
"5, \"age\": 11, \"bed_needs\": 1, \"mobility\": 300}. Please keep {} here even no",
"not_going, coworker, etc\") meets = models.ManyToManyField('occasions.Meet', through='AttendingMeet', related_name=\"meets\") infos = JSONField(null=True, blank=True, default=dict,",
"following display data which are not for table join/query: age, bed_needs, mobility def",
"from model_utils.models import TimeStampedModel, SoftDeletableModel from . import Note, Utility, Attendee, Registration class",
"[ GinIndex(fields=['infos'], name='attending_infos_gin', ), ] @property def main_contact(self): return self.registration.registrant @cached_property def meet_names(self):",
"Meta: db_table = 'persons_attendings' ordering = ['registration'] constraints = [ models.UniqueConstraint(fields=['attendee', 'registration'], condition=models.Q(is_removed=False),",
"parentheses needed in datagrid_attendee_update_view.js @cached_property def all_addresses(self): return '; '.join([a.street for a in",
"self.registration.registrant @cached_property def meet_names(self): return \",\".join([d.display_name for d in self.meets.all()]) @property def attending_label(self):",
"null=True, blank=True, on_delete=models.SET_NULL) attendee = models.ForeignKey(Attendee, null=False, blank=False, on_delete=models.CASCADE, related_name=\"attendings\") gatherings = models.ManyToManyField('occasions.Gathering',",
"meet_names(self): return \",\".join([d.display_name for d in self.meets.all()]) @property def attending_label(self): return f'({self.registration}) {self.attendee.display_label}'",
"through='AttendingMeet', related_name=\"meets\") infos = JSONField(null=True, blank=True, default=dict, help_text='Example: {\"grade\": 5, \"age\": 11, \"bed_needs\":",
"\"mobility\": 300}. Please keep {} here even no data') # Todo: infos contains",
"'; '.join([a.street for a in self.attendee.places.all()]) def __str__(self): return '%s %s' % (self.attendee,",
"serialize=False, verbose_name='ID') registration = models.ForeignKey(Registration, null=True, blank=True, on_delete=models.SET_NULL) attendee = models.ForeignKey(Attendee, null=False, blank=False,",
"self.meets.all()]) @property def attending_label(self): return f'({self.registration}) {self.attendee.display_label}' # parentheses needed in datagrid_attendee_update_view.js @cached_property",
"SoftDeletableModel from . import Note, Utility, Attendee, Registration class Attending(TimeStampedModel, SoftDeletableModel, Utility): notes",
"{} here even no data') # Todo: infos contains the following display data",
"and self.infos.bed_needs < 1 and self.info.age is None: raise ValidationError(\"You must specify age",
"django.contrib.postgres.fields.jsonb import JSONField from django.contrib.postgres.indexes import GinIndex from django.utils.functional import cached_property from model_utils.models",
"self.info.age is None: raise ValidationError(\"You must specify age for the participant\") def get_absolute_url(self):",
"models from django.core.exceptions import ValidationError from django.urls import reverse from django.contrib.contenttypes.fields import GenericRelation",
"on_delete=models.SET_NULL) attendee = models.ForeignKey(Attendee, null=False, blank=False, on_delete=models.CASCADE, related_name=\"attendings\") gatherings = models.ManyToManyField('occasions.Gathering', through='occasions.Attendance') category",
"assemblies under attendee's organization if self.registration and self.registration.assembly.need_age and self.infos.bed_needs < 1 and",
"{self.attendee.display_label}' # parentheses needed in datagrid_attendee_update_view.js @cached_property def all_addresses(self): return '; '.join([a.street for",
"= models.ManyToManyField('occasions.Meet', through='AttendingMeet', related_name=\"meets\") infos = JSONField(null=True, blank=True, default=dict, help_text='Example: {\"grade\": 5, \"age\":",
"cached_property from model_utils.models import TimeStampedModel, SoftDeletableModel from . import Note, Utility, Attendee, Registration",
"mobility def clean(self): # fetching birthday from attendee record first # Todo: check",
"import ValidationError from django.urls import reverse from django.contrib.contenttypes.fields import GenericRelation from django.contrib.postgres.fields.jsonb import",
"the following display data which are not for table join/query: age, bed_needs, mobility",
"condition=models.Q(is_removed=False), name=\"attending_attendee_registration\") ] indexes = [ GinIndex(fields=['infos'], name='attending_infos_gin', ), ] @property def main_contact(self):",
"import GinIndex from django.utils.functional import cached_property from model_utils.models import TimeStampedModel, SoftDeletableModel from .",
"django.urls import reverse from django.contrib.contenttypes.fields import GenericRelation from django.contrib.postgres.fields.jsonb import JSONField from django.contrib.postgres.indexes",
"= ['registration'] constraints = [ models.UniqueConstraint(fields=['attendee', 'registration'], condition=models.Q(is_removed=False), name=\"attending_attendee_registration\") ] indexes = [",
"main_contact(self): return self.registration.registrant @cached_property def meet_names(self): return \",\".join([d.display_name for d in self.meets.all()]) @property",
"Note, Utility, Attendee, Registration class Attending(TimeStampedModel, SoftDeletableModel, Utility): notes = GenericRelation(Note) id =",
"300}. Please keep {} here even no data') # Todo: infos contains the",
"self.registration and self.registration.assembly.need_age and self.infos.bed_needs < 1 and self.info.age is None: raise ValidationError(\"You",
"not for table join/query: age, bed_needs, mobility def clean(self): # fetching birthday from",
"from attendee record first # Todo: check if meets' assemblies under attendee's organization",
"['registration'] constraints = [ models.UniqueConstraint(fields=['attendee', 'registration'], condition=models.Q(is_removed=False), name=\"attending_attendee_registration\") ] indexes = [ GinIndex(fields=['infos'],",
"django.utils.functional import cached_property from model_utils.models import TimeStampedModel, SoftDeletableModel from . import Note, Utility,",
"default=dict, help_text='Example: {\"grade\": 5, \"age\": 11, \"bed_needs\": 1, \"mobility\": 300}. Please keep {}",
"fetching birthday from attendee record first # Todo: check if meets' assemblies under",
"keep {} here even no data') # Todo: infos contains the following display",
"participant\") def get_absolute_url(self): return reverse('attending_detail', args=[str(self.id)]) class Meta: db_table = 'persons_attendings' ordering =",
"attendee's organization if self.registration and self.registration.assembly.need_age and self.infos.bed_needs < 1 and self.info.age is",
"Attendee, Registration class Attending(TimeStampedModel, SoftDeletableModel, Utility): notes = GenericRelation(Note) id = models.BigAutoField(auto_created=True, primary_key=True,",
"Utility): notes = GenericRelation(Note) id = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') registration = models.ForeignKey(Registration,",
"from django.contrib.contenttypes.fields import GenericRelation from django.contrib.postgres.fields.jsonb import JSONField from django.contrib.postgres.indexes import GinIndex from",
"models.UniqueConstraint(fields=['attendee', 'registration'], condition=models.Q(is_removed=False), name=\"attending_attendee_registration\") ] indexes = [ GinIndex(fields=['infos'], name='attending_infos_gin', ), ] @property",
"def get_absolute_url(self): return reverse('attending_detail', args=[str(self.id)]) class Meta: db_table = 'persons_attendings' ordering = ['registration']",
"from django.contrib.postgres.fields.jsonb import JSONField from django.contrib.postgres.indexes import GinIndex from django.utils.functional import cached_property from",
"birthday from attendee record first # Todo: check if meets' assemblies under attendee's",
"= JSONField(null=True, blank=True, default=dict, help_text='Example: {\"grade\": 5, \"age\": 11, \"bed_needs\": 1, \"mobility\": 300}.",
"= models.ManyToManyField('occasions.Gathering', through='occasions.Attendance') category = models.CharField(max_length=20, null=False, blank=False, default=\"normal\", help_text=\"normal, not_going, coworker, etc\")",
"if self.registration and self.registration.assembly.need_age and self.infos.bed_needs < 1 and self.info.age is None: raise",
"and self.registration.assembly.need_age and self.infos.bed_needs < 1 and self.info.age is None: raise ValidationError(\"You must",
"= [ GinIndex(fields=['infos'], name='attending_infos_gin', ), ] @property def main_contact(self): return self.registration.registrant @cached_property def",
"def meet_names(self): return \",\".join([d.display_name for d in self.meets.all()]) @property def attending_label(self): return f'({self.registration})",
"def clean(self): # fetching birthday from attendee record first # Todo: check if",
"'persons_attendings' ordering = ['registration'] constraints = [ models.UniqueConstraint(fields=['attendee', 'registration'], condition=models.Q(is_removed=False), name=\"attending_attendee_registration\") ] indexes",
"notes = GenericRelation(Note) id = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') registration = models.ForeignKey(Registration, null=True,",
"[ models.UniqueConstraint(fields=['attendee', 'registration'], condition=models.Q(is_removed=False), name=\"attending_attendee_registration\") ] indexes = [ GinIndex(fields=['infos'], name='attending_infos_gin', ), ]",
"< 1 and self.info.age is None: raise ValidationError(\"You must specify age for the",
"models.ManyToManyField('occasions.Gathering', through='occasions.Attendance') category = models.CharField(max_length=20, null=False, blank=False, default=\"normal\", help_text=\"normal, not_going, coworker, etc\") meets",
"<filename>attendees/persons/models/attending.py from django.db import models from django.core.exceptions import ValidationError from django.urls import reverse",
"get_absolute_url(self): return reverse('attending_detail', args=[str(self.id)]) class Meta: db_table = 'persons_attendings' ordering = ['registration'] constraints",
"return self.registration.registrant @cached_property def meet_names(self): return \",\".join([d.display_name for d in self.meets.all()]) @property def",
"), ] @property def main_contact(self): return self.registration.registrant @cached_property def meet_names(self): return \",\".join([d.display_name for",
"GenericRelation(Note) id = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') registration = models.ForeignKey(Registration, null=True, blank=True, on_delete=models.SET_NULL)",
"datagrid_attendee_update_view.js @cached_property def all_addresses(self): return '; '.join([a.street for a in self.attendee.places.all()]) def __str__(self):",
"from . import Note, Utility, Attendee, Registration class Attending(TimeStampedModel, SoftDeletableModel, Utility): notes =",
"meets = models.ManyToManyField('occasions.Meet', through='AttendingMeet', related_name=\"meets\") infos = JSONField(null=True, blank=True, default=dict, help_text='Example: {\"grade\": 5,",
"for the participant\") def get_absolute_url(self): return reverse('attending_detail', args=[str(self.id)]) class Meta: db_table = 'persons_attendings'",
"GenericRelation from django.contrib.postgres.fields.jsonb import JSONField from django.contrib.postgres.indexes import GinIndex from django.utils.functional import cached_property",
"return reverse('attending_detail', args=[str(self.id)]) class Meta: db_table = 'persons_attendings' ordering = ['registration'] constraints =",
"model_utils.models import TimeStampedModel, SoftDeletableModel from . import Note, Utility, Attendee, Registration class Attending(TimeStampedModel,",
"name=\"attending_attendee_registration\") ] indexes = [ GinIndex(fields=['infos'], name='attending_infos_gin', ), ] @property def main_contact(self): return",
"self.infos.bed_needs < 1 and self.info.age is None: raise ValidationError(\"You must specify age for",
"check if meets' assemblies under attendee's organization if self.registration and self.registration.assembly.need_age and self.infos.bed_needs",
"from django.db import models from django.core.exceptions import ValidationError from django.urls import reverse from",
"= models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') registration = models.ForeignKey(Registration, null=True, blank=True, on_delete=models.SET_NULL) attendee =",
"django.db import models from django.core.exceptions import ValidationError from django.urls import reverse from django.contrib.contenttypes.fields",
"django.contrib.postgres.indexes import GinIndex from django.utils.functional import cached_property from model_utils.models import TimeStampedModel, SoftDeletableModel from",
"db_table = 'persons_attendings' ordering = ['registration'] constraints = [ models.UniqueConstraint(fields=['attendee', 'registration'], condition=models.Q(is_removed=False), name=\"attending_attendee_registration\")",
"for d in self.meets.all()]) @property def attending_label(self): return f'({self.registration}) {self.attendee.display_label}' # parentheses needed",
"attendee record first # Todo: check if meets' assemblies under attendee's organization if",
"record first # Todo: check if meets' assemblies under attendee's organization if self.registration",
"is None: raise ValidationError(\"You must specify age for the participant\") def get_absolute_url(self): return",
"] @property def main_contact(self): return self.registration.registrant @cached_property def meet_names(self): return \",\".join([d.display_name for d",
"'.join([a.street for a in self.attendee.places.all()]) def __str__(self): return '%s %s' % (self.attendee, self.meet_names)",
"GinIndex(fields=['infos'], name='attending_infos_gin', ), ] @property def main_contact(self): return self.registration.registrant @cached_property def meet_names(self): return",
"related_name=\"meets\") infos = JSONField(null=True, blank=True, default=dict, help_text='Example: {\"grade\": 5, \"age\": 11, \"bed_needs\": 1,",
"JSONField(null=True, blank=True, default=dict, help_text='Example: {\"grade\": 5, \"age\": 11, \"bed_needs\": 1, \"mobility\": 300}. Please",
"Todo: infos contains the following display data which are not for table join/query:",
"infos contains the following display data which are not for table join/query: age,",
"f'({self.registration}) {self.attendee.display_label}' # parentheses needed in datagrid_attendee_update_view.js @cached_property def all_addresses(self): return '; '.join([a.street",
"Todo: check if meets' assemblies under attendee's organization if self.registration and self.registration.assembly.need_age and",
"SoftDeletableModel, Utility): notes = GenericRelation(Note) id = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') registration =",
"infos = JSONField(null=True, blank=True, default=dict, help_text='Example: {\"grade\": 5, \"age\": 11, \"bed_needs\": 1, \"mobility\":",
"which are not for table join/query: age, bed_needs, mobility def clean(self): # fetching",
"d in self.meets.all()]) @property def attending_label(self): return f'({self.registration}) {self.attendee.display_label}' # parentheses needed in",
"= GenericRelation(Note) id = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') registration = models.ForeignKey(Registration, null=True, blank=True,",
"on_delete=models.CASCADE, related_name=\"attendings\") gatherings = models.ManyToManyField('occasions.Gathering', through='occasions.Attendance') category = models.CharField(max_length=20, null=False, blank=False, default=\"normal\", help_text=\"normal,",
"] indexes = [ GinIndex(fields=['infos'], name='attending_infos_gin', ), ] @property def main_contact(self): return self.registration.registrant",
"gatherings = models.ManyToManyField('occasions.Gathering', through='occasions.Attendance') category = models.CharField(max_length=20, null=False, blank=False, default=\"normal\", help_text=\"normal, not_going, coworker,",
"display data which are not for table join/query: age, bed_needs, mobility def clean(self):",
"models.CharField(max_length=20, null=False, blank=False, default=\"normal\", help_text=\"normal, not_going, coworker, etc\") meets = models.ManyToManyField('occasions.Meet', through='AttendingMeet', related_name=\"meets\")",
"for table join/query: age, bed_needs, mobility def clean(self): # fetching birthday from attendee",
"ValidationError from django.urls import reverse from django.contrib.contenttypes.fields import GenericRelation from django.contrib.postgres.fields.jsonb import JSONField",
"no data') # Todo: infos contains the following display data which are not",
"class Meta: db_table = 'persons_attendings' ordering = ['registration'] constraints = [ models.UniqueConstraint(fields=['attendee', 'registration'],",
"needed in datagrid_attendee_update_view.js @cached_property def all_addresses(self): return '; '.join([a.street for a in self.attendee.places.all()])",
"first # Todo: check if meets' assemblies under attendee's organization if self.registration and",
"@property def main_contact(self): return self.registration.registrant @cached_property def meet_names(self): return \",\".join([d.display_name for d in",
"null=False, blank=False, default=\"normal\", help_text=\"normal, not_going, coworker, etc\") meets = models.ManyToManyField('occasions.Meet', through='AttendingMeet', related_name=\"meets\") infos",
"class Attending(TimeStampedModel, SoftDeletableModel, Utility): notes = GenericRelation(Note) id = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')",
"ordering = ['registration'] constraints = [ models.UniqueConstraint(fields=['attendee', 'registration'], condition=models.Q(is_removed=False), name=\"attending_attendee_registration\") ] indexes =",
"= 'persons_attendings' ordering = ['registration'] constraints = [ models.UniqueConstraint(fields=['attendee', 'registration'], condition=models.Q(is_removed=False), name=\"attending_attendee_registration\") ]",
"def main_contact(self): return self.registration.registrant @cached_property def meet_names(self): return \",\".join([d.display_name for d in self.meets.all()])",
"import JSONField from django.contrib.postgres.indexes import GinIndex from django.utils.functional import cached_property from model_utils.models import",
"models.ManyToManyField('occasions.Meet', through='AttendingMeet', related_name=\"meets\") infos = JSONField(null=True, blank=True, default=dict, help_text='Example: {\"grade\": 5, \"age\": 11,",
"in self.meets.all()]) @property def attending_label(self): return f'({self.registration}) {self.attendee.display_label}' # parentheses needed in datagrid_attendee_update_view.js",
"1, \"mobility\": 300}. Please keep {} here even no data') # Todo: infos",
"= models.CharField(max_length=20, null=False, blank=False, default=\"normal\", help_text=\"normal, not_going, coworker, etc\") meets = models.ManyToManyField('occasions.Meet', through='AttendingMeet',",
"Please keep {} here even no data') # Todo: infos contains the following"
] |
[
"{}, nickname='UserSubscription', address=address) @property def active(self) -> bool: return self.call_getter('isActive', {'_answer_id': 0}) @property",
"-> bool: return self.call_getter('isActive', {'_answer_id': 0}) @property def auto_renew(self) -> bool: return self.call_getter('isAutoRenew',",
"address=address) @property def active(self) -> bool: return self.call_getter('isActive', {'_answer_id': 0}) @property def auto_renew(self)",
"address: ts4.Address): super().__init__('UserSubscription', {}, nickname='UserSubscription', address=address) @property def active(self) -> bool: return self.call_getter('isActive',",
"ts4.Address): super().__init__('UserSubscription', {}, nickname='UserSubscription', address=address) @property def active(self) -> bool: return self.call_getter('isActive', {'_answer_id':",
"class UserSubscription(ts4.BaseContract): def __init__(self, address: ts4.Address): super().__init__('UserSubscription', {}, nickname='UserSubscription', address=address) @property def active(self)",
"UserSubscription(ts4.BaseContract): def __init__(self, address: ts4.Address): super().__init__('UserSubscription', {}, nickname='UserSubscription', address=address) @property def active(self) ->",
"def active(self) -> bool: return self.call_getter('isActive', {'_answer_id': 0}) @property def auto_renew(self) -> bool:",
"tonos_ts4 import ts4 class UserSubscription(ts4.BaseContract): def __init__(self, address: ts4.Address): super().__init__('UserSubscription', {}, nickname='UserSubscription', address=address)",
"import ts4 class UserSubscription(ts4.BaseContract): def __init__(self, address: ts4.Address): super().__init__('UserSubscription', {}, nickname='UserSubscription', address=address) @property",
"__init__(self, address: ts4.Address): super().__init__('UserSubscription', {}, nickname='UserSubscription', address=address) @property def active(self) -> bool: return",
"bool: return self.call_getter('isActive', {'_answer_id': 0}) @property def auto_renew(self) -> bool: return self.call_getter('isAutoRenew', {'_answer_id':",
"<gh_stars>0 from tonos_ts4 import ts4 class UserSubscription(ts4.BaseContract): def __init__(self, address: ts4.Address): super().__init__('UserSubscription', {},",
"nickname='UserSubscription', address=address) @property def active(self) -> bool: return self.call_getter('isActive', {'_answer_id': 0}) @property def",
"@property def active(self) -> bool: return self.call_getter('isActive', {'_answer_id': 0}) @property def auto_renew(self) ->",
"from tonos_ts4 import ts4 class UserSubscription(ts4.BaseContract): def __init__(self, address: ts4.Address): super().__init__('UserSubscription', {}, nickname='UserSubscription',",
"def __init__(self, address: ts4.Address): super().__init__('UserSubscription', {}, nickname='UserSubscription', address=address) @property def active(self) -> bool:",
"ts4 class UserSubscription(ts4.BaseContract): def __init__(self, address: ts4.Address): super().__init__('UserSubscription', {}, nickname='UserSubscription', address=address) @property def",
"return self.call_getter('isActive', {'_answer_id': 0}) @property def auto_renew(self) -> bool: return self.call_getter('isAutoRenew', {'_answer_id': 0})",
"super().__init__('UserSubscription', {}, nickname='UserSubscription', address=address) @property def active(self) -> bool: return self.call_getter('isActive', {'_answer_id': 0})",
"active(self) -> bool: return self.call_getter('isActive', {'_answer_id': 0}) @property def auto_renew(self) -> bool: return"
] |
[
"import socket from geventconnpool import ConnectionPool class MyPool(ConnectionPool): def _new_connection(self): return socket.create_connection((\"www.baidu.com\", 80))",
"gevent import socket from geventconnpool import ConnectionPool class MyPool(ConnectionPool): def _new_connection(self): return socket.create_connection((\"www.baidu.com\",",
"socket from geventconnpool import ConnectionPool class MyPool(ConnectionPool): def _new_connection(self): return socket.create_connection((\"www.baidu.com\", 80)) if",
"class MyPool(ConnectionPool): def _new_connection(self): return socket.create_connection((\"www.baidu.com\", 80)) if __name__ == '__main__': pool =",
"def _new_connection(self): return socket.create_connection((\"www.baidu.com\", 80)) if __name__ == '__main__': pool = MyPool(20) with",
"geventconnpool import ConnectionPool class MyPool(ConnectionPool): def _new_connection(self): return socket.create_connection((\"www.baidu.com\", 80)) if __name__ ==",
"import ConnectionPool class MyPool(ConnectionPool): def _new_connection(self): return socket.create_connection((\"www.baidu.com\", 80)) if __name__ == '__main__':",
"from geventconnpool import ConnectionPool class MyPool(ConnectionPool): def _new_connection(self): return socket.create_connection((\"www.baidu.com\", 80)) if __name__",
"MyPool(ConnectionPool): def _new_connection(self): return socket.create_connection((\"www.baidu.com\", 80)) if __name__ == '__main__': pool = MyPool(20)",
"<reponame>by46/geek from gevent import socket from geventconnpool import ConnectionPool class MyPool(ConnectionPool): def _new_connection(self):",
"return socket.create_connection((\"www.baidu.com\", 80)) if __name__ == '__main__': pool = MyPool(20) with pool.get() as",
"socket.create_connection((\"www.baidu.com\", 80)) if __name__ == '__main__': pool = MyPool(20) with pool.get() as conn:",
"ConnectionPool class MyPool(ConnectionPool): def _new_connection(self): return socket.create_connection((\"www.baidu.com\", 80)) if __name__ == '__main__': pool",
"from gevent import socket from geventconnpool import ConnectionPool class MyPool(ConnectionPool): def _new_connection(self): return",
"_new_connection(self): return socket.create_connection((\"www.baidu.com\", 80)) if __name__ == '__main__': pool = MyPool(20) with pool.get()",
"80)) if __name__ == '__main__': pool = MyPool(20) with pool.get() as conn: conn.send(\"PING\\n\")"
] |
[
"[('output_image', 'in_segm')]), (sel_labels, get_wm, [('out_wm', 'op1')]), (sel_labels, get_gm, [('out_gm', 'op1')]), (get_gm, fill_gm, [('output_image',",
"# MultiplyImages ${DIMENSION} ${EXTRACTION_GM} ${ATROPOS_GM_CLASS_LABEL} ${EXTRACTION_GM} # ImageMath ${DIMENSION} ${EXTRACTION_SEGMENTATION} addtozero ${EXTRACTION_WM} ${EXTRACTION_GM}",
"# Split segmentation in binary masks sel_labels = pe.Node(niu.Function(function=_select_labels, output_names=['out_wm', 'out_gm', 'out_csf']), name='04_sel_labels')",
"[('output_image', 'op1')]), (relabel_wm, depad_wm, [('output_product_image', 'op1')]), (relabel_gm, depad_gm, [('output_product_image', 'op1')]), (sel_labels, depad_csf, [('out_csf',",
"mrf_radius=[1, 1, 1], mrf_smoothing_factor=0.1, likelihood_model='Gaussian', use_random_seed=use_random_seed), name='01_atropos', n_procs=omp_nthreads, mem_gb=mem_gb) # massage outputs pad_segm",
"${EXTRACTION_GM} fill_gm = pe.Node(ImageMath(operation='FillHoles', op2='2'), name='07_fill_gm') mult_gm = pe.Node(MultiplyImages(dimension=3), name='08_mult_gm') # MultiplyImages ${DIMENSION}",
"<gh_stars>0 from collections import OrderedDict from nipype.pipeline import engine as pe from nipype.interfaces",
"outputnode, [('output_image', 'out_segm')]), (merge_tpms, outputnode, [('out', 'out_tpms')]), ]) return wf def _select_labels(in_segm, labels):",
"(relabel_wm, depad_wm, [('output_product_image', 'op1')]), (relabel_gm, depad_gm, [('output_product_image', 'op1')]), (sel_labels, depad_csf, [('out_csf', 'op1')]), (depad_csf,",
"name : str, optional Workflow name (default: atropos_wf) **Inputs** in_files :abbr:`INU (intensity non-uniformity)`-corrected",
"holes and calculate intersection # ImageMath ${DIMENSION} ${EXTRACTION_TMP} FillHoles ${EXTRACTION_GM} 2 # MultiplyImages",
"(add_7_2, md_7_2, [('output_image', 'op1')]), (md_7_2, me_7_2, [('output_image', 'op1')]), (me_7_2, depad_mask, [('output_image', 'op1')]), (add_gm_wm,",
"me_7_2, [('output_image', 'op1')]), (me_7_2, depad_mask, [('output_image', 'op1')]), (add_gm_wm, depad_segm, [('output_image', 'op1')]), (relabel_wm, depad_wm,",
"md_7, [('output_image', 'op1')]), (md_7, fill_7, [('output_image', 'op1')]), (fill_7, add_7_2, [('output_image', 'op1')]), (pad_mask, add_7_2,",
"${EXTRACTION_GM} add_gm = pe.Node(ImageMath(operation='addtozero'), name='11_add_gm') relabel_gm = pe.Node(MultiplyImages(dimension=3, second_input=in_segmentation_model[-2]), name='12_relabel_gm') add_gm_wm = pe.Node(ImageMath(operation='addtozero'),",
"= pe.Node(ImageMath(operation='ME', op2='2'), name='16_me_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} GetLargestComponent ${EXTRACTION_MASK} comp_7 = pe.Node(ImageMath(operation='GetLargestComponent'),",
"depad_csf = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='27_depad_csf') merge_tpms = pe.Node(niu.Merge(in_segmentation_model[0]), name='merge_tpms') wf.connect([ (inputnode,",
"pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='23_depad_mask') depad_segm = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='24_depad_segm') depad_gm",
"use_random_seed=True, omp_nthreads=None, mem_gb=3.0, padding=10, in_segmentation_model=list(ATROPOS_MODELS['T1'].values())): \"\"\" Implements supersteps 6 and 7 of ``antsBrainExtraction.sh``,",
"'out_tpms')]), ]) return wf def _select_labels(in_segm, labels): from os import getcwd import numpy",
"'out_csf']), name='14_sel_labels2') sel_labels2.inputs.labels = list(reversed(in_segmentation_model[1:])) # ImageMath ${DIMENSION} ${EXTRACTION_MASK} addtozero ${EXTRACTION_MASK} ${EXTRACTION_TMP} add_7",
"('gm', 3), ('wm', 2), ]), } def init_atropos_wf(name='atropos_wf', use_random_seed=True, omp_nthreads=None, mem_gb=3.0, padding=10, in_segmentation_model=list(ATROPOS_MODELS['T1'].values())):",
"(core node) atropos = pe.Node(Atropos( dimension=3, initialization='KMeans', number_of_tissue_classes=in_segmentation_model[0], n_iterations=3, convergence_threshold=0.0, mrf_radius=[1, 1, 1],",
"ME ${EXTRACTION_MASK} 2 me_7 = pe.Node(ImageMath(operation='ME', op2='2'), name='16_me_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} GetLargestComponent",
"op2='-%d' % padding), name='23_depad_mask') depad_segm = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='24_depad_segm') depad_gm =",
"peak memory consumption of the most hungry nodes in the workflow padding :",
"{ 'T1': OrderedDict([ ('nclasses', 3), ('csf', 1), ('gm', 2), ('wm', 3), ]), 'T2':",
"may use mem_gb : float Estimated peak memory consumption of the most hungry",
":abbr:`INU (intensity non-uniformity)`-corrected files. in_mask Brain mask calculated previously **Outputs** out_mask Refined brain",
"images with zeros before processing in_segmentation_model : tuple A k-means segmentation is run",
"(relabel_gm, add_gm_wm, [('output_product_image', 'op2')]), (add_gm_wm, sel_labels2, [('output_image', 'in_segm')]), (sel_labels2, add_7, [('out_wm', 'op1'), ('out_gm',",
"getcwd() nii = nb.load(in_segm) for l in labels: data = (nii.get_data() == l).astype(np.uint8)",
"padding=10, in_segmentation_model=list(ATROPOS_MODELS['T1'].values())): \"\"\" Implements supersteps 6 and 7 of ``antsBrainExtraction.sh``, which refine the",
"(add_gm, relabel_gm, [('output_image', 'first_input'), (('output_image', _gen_name), 'output_product_image')]), (relabel_wm, add_gm_wm, [('output_product_image', 'op1')]), (relabel_gm, add_gm_wm,",
"# Superstep 7 # Split segmentation in binary masks sel_labels2 = pe.Node(niu.Function(function=_select_labels, output_names=['out_wm',",
"# ImageMath ${DIMENSION} ${EXTRACTION_GM} addtozero ${EXTRACTION_GM} ${EXTRACTION_TMP} # MultiplyImages ${DIMENSION} ${EXTRACTION_GM} ${ATROPOS_GM_CLASS_LABEL} ${EXTRACTION_GM}",
"'op1'), ('out_gm', 'op2')]), (add_7, me_7, [('output_image', 'op1')]), (me_7, comp_7, [('output_image', 'op1')]), (comp_7, md_7,",
"mem_gb : float Estimated peak memory consumption of the most hungry nodes in",
"merge_tpms, [('output_image', 'in3')]), (depad_mask, outputnode, [('output_image', 'out_mask')]), (depad_segm, outputnode, [('output_image', 'out_segm')]), (merge_tpms, outputnode,",
"ImageMath ATROPOS_MODELS = { 'T1': OrderedDict([ ('nclasses', 3), ('csf', 1), ('gm', 2), ('wm',",
"= getcwd() nii = nb.load(in_segm) for l in labels: data = (nii.get_data() ==",
"= pe.Node(niu.Merge(in_segmentation_model[0]), name='merge_tpms') wf.connect([ (inputnode, pad_mask, [('in_mask', 'op1')]), (inputnode, atropos, [('in_files', 'intensity_images'), ('in_mask',",
"= nii.__class__(data, nii.affine, nii.header) newnii.set_data_dtype('uint8') out_file = fname_presuffix(in_segm, suffix='class-%02d' % l, newpath=cwd) newnii.to_filename(out_file)",
"CSF, gray and white matter. Format (K, csfLabel, gmLabel, wmLabel). Examples: - ``(3,1,2,3)``",
"${DIMENSION} ${EXTRACTION_MASK} addtozero ${EXTRACTION_MASK} \\ # ${EXTRACTION_MASK_PRIOR_WARPED} add_7_2 = pe.Node(ImageMath(operation='addtozero'), name='20_add_7_2') # ImageMath",
"out_file = fname_presuffix(in_segm, suffix='class-%02d' % l, newpath=cwd) newnii.to_filename(out_file) out_files.append(out_file) return out_files def _gen_name(in_file):",
"[('output_image', 'out_segm')]), (merge_tpms, outputnode, [('out', 'out_tpms')]), ]) return wf def _select_labels(in_segm, labels): from",
"7 of ``antsBrainExtraction.sh``, which refine the mask previously computed with the spatial normalization",
"% padding), name='03_pad_mask') # Split segmentation in binary masks sel_labels = pe.Node(niu.Function(function=_select_labels, output_names=['out_wm',",
"outputnode, [('output_image', 'out_mask')]), (depad_segm, outputnode, [('output_image', 'out_segm')]), (merge_tpms, outputnode, [('out', 'out_tpms')]), ]) return",
": tuple A k-means segmentation is run to find gray or white matter",
"% l, newpath=cwd) newnii.to_filename(out_file) out_files.append(out_file) return out_files def _gen_name(in_file): import os from nipype.utils.filemanip",
"(fill_7, add_7_2, [('output_image', 'op1')]), (pad_mask, add_7_2, [('output_image', 'op2')]), (add_7_2, md_7_2, [('output_image', 'op1')]), (md_7_2,",
"3), ('csf', 1), ('gm', 2), ('wm', 3), ]), 'T2': OrderedDict([ ('nclasses', 3), ('csf',",
"segmentation in binary masks sel_labels = pe.Node(niu.Function(function=_select_labels, output_names=['out_wm', 'out_gm', 'out_csf']), name='04_sel_labels') sel_labels.inputs.labels =",
"name='26_depad_wm') depad_csf = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='27_depad_csf') merge_tpms = pe.Node(niu.Merge(in_segmentation_model[0]), name='merge_tpms') wf.connect([",
"binary masks sel_labels2 = pe.Node(niu.Function(function=_select_labels, output_names=['out_wm', 'out_gm', 'out_csf']), name='14_sel_labels2') sel_labels2.inputs.labels = list(reversed(in_segmentation_model[1:])) #",
"GM=3, WM=2 - ``(4,4,2,3)`` uses K=4, CSF=4, GM=2, WM=3 name : str, optional",
"${EXTRACTION_MASK} FillHoles ${EXTRACTION_MASK} 2 fill_7 = pe.Node(ImageMath(operation='FillHoles', op2='2'), name='19_fill_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK}",
"'FLAIR': OrderedDict([ ('nclasses', 3), ('csf', 1), ('gm', 3), ('wm', 2), ]), } def",
"'in3')]), (depad_mask, outputnode, [('output_image', 'out_mask')]), (depad_segm, outputnode, [('output_image', 'out_segm')]), (merge_tpms, outputnode, [('out', 'out_tpms')]),",
"WM=3 (default) - ``(3,3,2,1)`` for T2 with K=3, CSF=3, GM=2, WM=1 - ``(3,1,3,2)``",
"for T2 with K=3, CSF=3, GM=2, WM=1 - ``(3,1,3,2)`` for FLAIR with K=3,",
"${EXTRACTION_GM} ${ATROPOS_GM_CLASS_LABEL} ${EXTRACTION_GM} # ImageMath ${DIMENSION} ${EXTRACTION_SEGMENTATION} addtozero ${EXTRACTION_WM} ${EXTRACTION_GM} add_gm = pe.Node(ImageMath(operation='addtozero'),",
"= pe.Node(niu.IdentityInterface(fields=['in_files', 'in_mask']), name='inputnode') outputnode = pe.Node(niu.IdentityInterface( fields=['out_mask', 'out_segm', 'out_tpms']), name='outputnode') # Run",
"(pad_mask, add_7_2, [('output_image', 'op2')]), (add_7_2, md_7_2, [('output_image', 'op1')]), (md_7_2, me_7_2, [('output_image', 'op1')]), (me_7_2,",
"atropos, [('in_files', 'intensity_images'), ('in_mask', 'mask_image')]), (atropos, pad_segm, [('classified_image', 'op1')]), (pad_segm, sel_labels, [('output_image', 'in_segm')]),",
"'in_segm')]), (sel_labels, get_wm, [('out_wm', 'op1')]), (sel_labels, get_gm, [('out_gm', 'op1')]), (get_gm, fill_gm, [('output_image', 'op1')]),",
"(depad_csf, merge_tpms, [('output_image', 'in1')]), (depad_gm, merge_tpms, [('output_image', 'in2')]), (depad_wm, merge_tpms, [('output_image', 'in3')]), (depad_mask,",
"and tell the script which classes represent CSF, gray and white matter. Format",
"CSF=1, GM=2, WM=3 (default) - ``(3,3,2,1)`` for T2 with K=3, CSF=3, GM=2, WM=1",
"- ``(4,4,2,3)`` uses K=4, CSF=4, GM=2, WM=3 name : str, optional Workflow name",
"is run to find gray or white matter around the edge of the",
"pe.Node(ImageMath(operation='ME', op2='10'), name='10_me_csf') # ImageMath ${DIMENSION} ${EXTRACTION_GM} addtozero ${EXTRACTION_GM} ${EXTRACTION_TMP} # MultiplyImages ${DIMENSION}",
"OrderedDict from nipype.pipeline import engine as pe from nipype.interfaces import utility as niu",
"Maximum number of threads an individual process may use mem_gb : float Estimated",
"= pe.Node(Atropos( dimension=3, initialization='KMeans', number_of_tissue_classes=in_segmentation_model[0], n_iterations=3, convergence_threshold=0.0, mrf_radius=[1, 1, 1], mrf_smoothing_factor=0.1, likelihood_model='Gaussian', use_random_seed=use_random_seed),",
"('out_gm', 'op2')]), (add_7, me_7, [('output_image', 'op1')]), (me_7, comp_7, [('output_image', 'op1')]), (comp_7, md_7, [('output_image',",
"of threads an individual process may use mem_gb : float Estimated peak memory",
"optional Workflow name (default: atropos_wf) **Inputs** in_files :abbr:`INU (intensity non-uniformity)`-corrected files. in_mask Brain",
"${EXTRACTION_MASK} addtozero ${EXTRACTION_MASK} \\ # ${EXTRACTION_MASK_PRIOR_WARPED} add_7_2 = pe.Node(ImageMath(operation='addtozero'), name='20_add_7_2') # ImageMath ${DIMENSION}",
"me_7_2 = pe.Node(ImageMath(operation='ME', op2='5'), name='22_me_7_2') # De-pad depad_mask = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding),",
"fill_7, [('output_image', 'op1')]), (fill_7, add_7_2, [('output_image', 'op1')]), (pad_mask, add_7_2, [('output_image', 'op2')]), (add_7_2, md_7_2,",
"ATROPOS should generate a random seed based on the system's clock omp_nthreads :",
"= pe.Node(ImageMath(operation='GetLargestComponent'), name='17_comp_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} MD ${EXTRACTION_MASK} 4 md_7 = pe.Node(ImageMath(operation='MD',",
"# ImageMath ${DIMENSION} ${EXTRACTION_TMP} ME ${EXTRACTION_CSF} 10 relabel_wm = pe.Node(MultiplyImages(dimension=3, second_input=in_segmentation_model[-1]), name='09_relabel_wm') me_csf",
"from nipype.interfaces.ants import Atropos, MultiplyImages from ..interfaces.ants import ImageMath ATROPOS_MODELS = { 'T1':",
"def init_atropos_wf(name='atropos_wf', use_random_seed=True, omp_nthreads=None, mem_gb=3.0, padding=10, in_segmentation_model=list(ATROPOS_MODELS['T1'].values())): \"\"\" Implements supersteps 6 and 7",
"data = (nii.get_data() == l).astype(np.uint8) newnii = nii.__class__(data, nii.affine, nii.header) newnii.set_data_dtype('uint8') out_file =",
"out_segm Output segmentation out_tpms Output :abbr:`TPMs (tissue probability maps)` \"\"\" wf = pe.Workflow(name)",
"a segmentation image with :math:`$K$` classes, ordered by mean intensity in increasing order.",
"CSF=1 GM=3, WM=2 - ``(4,4,2,3)`` uses K=4, CSF=4, GM=2, WM=3 name : str,",
"'T2': OrderedDict([ ('nclasses', 3), ('csf', 3), ('gm', 2), ('wm', 1), ]), 'FLAIR': OrderedDict([",
"maps)` \"\"\" wf = pe.Workflow(name) inputnode = pe.Node(niu.IdentityInterface(fields=['in_files', 'in_mask']), name='inputnode') outputnode = pe.Node(niu.IdentityInterface(",
"[('output_image', 'op1')]), (md_7_2, me_7_2, [('output_image', 'op1')]), (me_7_2, depad_mask, [('output_image', 'op1')]), (add_gm_wm, depad_segm, [('output_image',",
"GM=2, WM=3 (default) - ``(3,3,2,1)`` for T2 with K=3, CSF=3, GM=2, WM=1 -",
"pe.Node(niu.IdentityInterface( fields=['out_mask', 'out_segm', 'out_tpms']), name='outputnode') # Run atropos (core node) atropos = pe.Node(Atropos(",
"${EXTRACTION_WM} # ImageMath ${DIMENSION} ${EXTRACTION_TMP} ME ${EXTRACTION_CSF} 10 relabel_wm = pe.Node(MultiplyImages(dimension=3, second_input=in_segmentation_model[-1]), name='09_relabel_wm')",
"add_7_2 = pe.Node(ImageMath(operation='addtozero'), name='20_add_7_2') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} MD ${EXTRACTION_MASK} 5 md_7_2 =",
"pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='27_depad_csf') merge_tpms = pe.Node(niu.Merge(in_segmentation_model[0]), name='merge_tpms') wf.connect([ (inputnode, pad_mask, [('in_mask',",
"]) return wf def _select_labels(in_segm, labels): from os import getcwd import numpy as",
"l, newpath=cwd) newnii.to_filename(out_file) out_files.append(out_file) return out_files def _gen_name(in_file): import os from nipype.utils.filemanip import",
"6 and 7 of ``antsBrainExtraction.sh``, which refine the mask previously computed with the",
"relabel_gm, [('output_image', 'first_input'), (('output_image', _gen_name), 'output_product_image')]), (relabel_wm, add_gm_wm, [('output_product_image', 'op1')]), (relabel_gm, add_gm_wm, [('output_product_image',",
"me_7 = pe.Node(ImageMath(operation='ME', op2='2'), name='16_me_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} GetLargestComponent ${EXTRACTION_MASK} comp_7 =",
"wf def _select_labels(in_segm, labels): from os import getcwd import numpy as np import",
"from os import getcwd import numpy as np import nibabel as nb from",
"tell the script which classes represent CSF, gray and white matter. Format (K,",
"(relabel_gm, depad_gm, [('output_product_image', 'op1')]), (sel_labels, depad_csf, [('out_csf', 'op1')]), (depad_csf, merge_tpms, [('output_image', 'in1')]), (depad_gm,",
"= pe.Node(ImageMath(operation='addtozero'), name='13_add_gm_wm') # Superstep 7 # Split segmentation in binary masks sel_labels2",
"cwd = getcwd() nii = nb.load(in_segm) for l in labels: data = (nii.get_data()",
"Split segmentation in binary masks sel_labels2 = pe.Node(niu.Function(function=_select_labels, output_names=['out_wm', 'out_gm', 'out_csf']), name='14_sel_labels2') sel_labels2.inputs.labels",
"'out_segm')]), (merge_tpms, outputnode, [('out', 'out_tpms')]), ]) return wf def _select_labels(in_segm, labels): from os",
"and calculate intersection # ImageMath ${DIMENSION} ${EXTRACTION_TMP} FillHoles ${EXTRACTION_GM} 2 # MultiplyImages ${DIMENSION}",
"[('output_product_image', 'op1')]), (sel_labels, depad_csf, [('out_csf', 'op1')]), (depad_csf, merge_tpms, [('output_image', 'in1')]), (depad_gm, merge_tpms, [('output_image',",
"produces a segmentation image with :math:`$K$` classes, ordered by mean intensity in increasing",
"to the template. **Parameters** use_random_seed : bool Whether ATROPOS should generate a random",
"``(4,4,2,3)`` uses K=4, CSF=4, GM=2, WM=3 name : str, optional Workflow name (default:",
"2), ('wm', 1), ]), 'FLAIR': OrderedDict([ ('nclasses', 3), ('csf', 1), ('gm', 3), ('wm',",
"'out_mask')]), (depad_segm, outputnode, [('output_image', 'out_segm')]), (merge_tpms, outputnode, [('out', 'out_tpms')]), ]) return wf def",
"\\ # ${EXTRACTION_MASK_PRIOR_WARPED} add_7_2 = pe.Node(ImageMath(operation='addtozero'), name='20_add_7_2') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} MD ${EXTRACTION_MASK}",
"niu from nipype.interfaces.ants import Atropos, MultiplyImages from ..interfaces.ants import ImageMath ATROPOS_MODELS = {",
"you can control :math:`$K$` and tell the script which classes represent CSF, gray",
"gray or white matter around the edge of the initial brain mask warped",
"T1 with K=3, CSF=1, GM=2, WM=3 (default) - ``(3,3,2,1)`` for T2 with K=3,",
"= list(reversed(in_segmentation_model[1:])) # ImageMath ${DIMENSION} ${EXTRACTION_MASK} addtozero ${EXTRACTION_MASK} ${EXTRACTION_TMP} add_7 = pe.Node(ImageMath(operation='addtozero'), name='15_add_7')",
"${DIMENSION} ${EXTRACTION_SEGMENTATION} addtozero ${EXTRACTION_WM} ${EXTRACTION_GM} add_gm = pe.Node(ImageMath(operation='addtozero'), name='11_add_gm') relabel_gm = pe.Node(MultiplyImages(dimension=3, second_input=in_segmentation_model[-2]),",
"padding), name='03_pad_mask') # Split segmentation in binary masks sel_labels = pe.Node(niu.Function(function=_select_labels, output_names=['out_wm', 'out_gm',",
"inputnode = pe.Node(niu.IdentityInterface(fields=['in_files', 'in_mask']), name='inputnode') outputnode = pe.Node(niu.IdentityInterface( fields=['out_mask', 'out_segm', 'out_tpms']), name='outputnode') #",
"ImageMath ${DIMENSION} ${EXTRACTION_GM} addtozero ${EXTRACTION_GM} ${EXTRACTION_TMP} # MultiplyImages ${DIMENSION} ${EXTRACTION_GM} ${ATROPOS_GM_CLASS_LABEL} ${EXTRACTION_GM} #",
"ImageMath ${DIMENSION} ${EXTRACTION_MASK} ME ${EXTRACTION_MASK} 2 me_7 = pe.Node(ImageMath(operation='ME', op2='2'), name='16_me_7') # ImageMath",
"${DIMENSION} ${EXTRACTION_MASK} GetLargestComponent ${EXTRACTION_MASK} comp_7 = pe.Node(ImageMath(operation='GetLargestComponent'), name='17_comp_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} MD",
"script which classes represent CSF, gray and white matter. Format (K, csfLabel, gmLabel,",
"the edge of the initial brain mask warped from the template. This produces",
"newpath=cwd) newnii.to_filename(out_file) out_files.append(out_file) return out_files def _gen_name(in_file): import os from nipype.utils.filemanip import fname_presuffix",
"= pe.Node(ImageMath(operation='addtozero'), name='11_add_gm') relabel_gm = pe.Node(MultiplyImages(dimension=3, second_input=in_segmentation_model[-2]), name='12_relabel_gm') add_gm_wm = pe.Node(ImageMath(operation='addtozero'), name='13_add_gm_wm') #",
"= pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='27_depad_csf') merge_tpms = pe.Node(niu.Merge(in_segmentation_model[0]), name='merge_tpms') wf.connect([ (inputnode, pad_mask,",
"for T1 with K=3, CSF=1, GM=2, WM=3 (default) - ``(3,3,2,1)`` for T2 with",
"addtozero ${EXTRACTION_MASK} \\ # ${EXTRACTION_MASK_PRIOR_WARPED} add_7_2 = pe.Node(ImageMath(operation='addtozero'), name='20_add_7_2') # ImageMath ${DIMENSION} ${EXTRACTION_MASK}",
"(depad_wm, merge_tpms, [('output_image', 'in3')]), (depad_mask, outputnode, [('output_image', 'out_mask')]), (depad_segm, outputnode, [('output_image', 'out_segm')]), (merge_tpms,",
"2), ]), } def init_atropos_wf(name='atropos_wf', use_random_seed=True, omp_nthreads=None, mem_gb=3.0, padding=10, in_segmentation_model=list(ATROPOS_MODELS['T1'].values())): \"\"\" Implements supersteps",
"name='19_fill_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} addtozero ${EXTRACTION_MASK} \\ # ${EXTRACTION_MASK_PRIOR_WARPED} add_7_2 = pe.Node(ImageMath(operation='addtozero'),",
"sel_labels = pe.Node(niu.Function(function=_select_labels, output_names=['out_wm', 'out_gm', 'out_csf']), name='04_sel_labels') sel_labels.inputs.labels = list(reversed(in_segmentation_model[1:])) # Select largest",
"# ImageMath ${DIMENSION} ${EXTRACTION_MASK} addtozero ${EXTRACTION_MASK} ${EXTRACTION_TMP} add_7 = pe.Node(ImageMath(operation='addtozero'), name='15_add_7') # ImageMath",
"'op2')]), (add_gm_wm, sel_labels2, [('output_image', 'in_segm')]), (sel_labels2, add_7, [('out_wm', 'op1'), ('out_gm', 'op2')]), (add_7, me_7,",
"name='03_pad_mask') # Split segmentation in binary masks sel_labels = pe.Node(niu.Function(function=_select_labels, output_names=['out_wm', 'out_gm', 'out_csf']),",
"get_gm = pe.Node(ImageMath(operation='GetLargestComponent'), name='06_get_gm') # Fill holes and calculate intersection # ImageMath ${DIMENSION}",
"ImageMath ${DIMENSION} ${EXTRACTION_MASK} GetLargestComponent ${EXTRACTION_MASK} comp_7 = pe.Node(ImageMath(operation='GetLargestComponent'), name='17_comp_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK}",
"segmentation image with :math:`$K$` classes, ordered by mean intensity in increasing order. With",
"(add_7, me_7, [('output_image', 'op1')]), (me_7, comp_7, [('output_image', 'op1')]), (comp_7, md_7, [('output_image', 'op1')]), (md_7,",
"an individual process may use mem_gb : float Estimated peak memory consumption of",
"('nclasses', 3), ('csf', 3), ('gm', 2), ('wm', 1), ]), 'FLAIR': OrderedDict([ ('nclasses', 3),",
"name='13_add_gm_wm') # Superstep 7 # Split segmentation in binary masks sel_labels2 = pe.Node(niu.Function(function=_select_labels,",
"Superstep 7 # Split segmentation in binary masks sel_labels2 = pe.Node(niu.Function(function=_select_labels, output_names=['out_wm', 'out_gm',",
"newnii.set_data_dtype('uint8') out_file = fname_presuffix(in_segm, suffix='class-%02d' % l, newpath=cwd) newnii.to_filename(out_file) out_files.append(out_file) return out_files def",
"padding), name='27_depad_csf') merge_tpms = pe.Node(niu.Merge(in_segmentation_model[0]), name='merge_tpms') wf.connect([ (inputnode, pad_mask, [('in_mask', 'op1')]), (inputnode, atropos,",
"def _select_labels(in_segm, labels): from os import getcwd import numpy as np import nibabel",
"K=3, CSF=1 GM=3, WM=2 - ``(4,4,2,3)`` uses K=4, CSF=4, GM=2, WM=3 name :",
"pe.Node(MultiplyImages(dimension=3, second_input=in_segmentation_model[-1]), name='09_relabel_wm') me_csf = pe.Node(ImageMath(operation='ME', op2='10'), name='10_me_csf') # ImageMath ${DIMENSION} ${EXTRACTION_GM} addtozero",
"as pe from nipype.interfaces import utility as niu from nipype.interfaces.ants import Atropos, MultiplyImages",
"name (default: atropos_wf) **Inputs** in_files :abbr:`INU (intensity non-uniformity)`-corrected files. in_mask Brain mask calculated",
"${EXTRACTION_GM} addtozero ${EXTRACTION_GM} ${EXTRACTION_TMP} # MultiplyImages ${DIMENSION} ${EXTRACTION_GM} ${ATROPOS_GM_CLASS_LABEL} ${EXTRACTION_GM} # ImageMath ${DIMENSION}",
"the template. **Parameters** use_random_seed : bool Whether ATROPOS should generate a random seed",
"output_names=['out_wm', 'out_gm', 'out_csf']), name='14_sel_labels2') sel_labels2.inputs.labels = list(reversed(in_segmentation_model[1:])) # ImageMath ${DIMENSION} ${EXTRACTION_MASK} addtozero ${EXTRACTION_MASK}",
"padding), name='26_depad_wm') depad_csf = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='27_depad_csf') merge_tpms = pe.Node(niu.Merge(in_segmentation_model[0]), name='merge_tpms')",
"'first_input'), (('output_image', _gen_name), 'output_product_image')]), (sel_labels, me_csf, [('out_csf', 'op1')]), (mult_gm, add_gm, [('output_product_image', 'op1')]), (me_csf,",
"depad_gm, [('output_product_image', 'op1')]), (sel_labels, depad_csf, [('out_csf', 'op1')]), (depad_csf, merge_tpms, [('output_image', 'in1')]), (depad_gm, merge_tpms,",
"${EXTRACTION_MASK} addtozero ${EXTRACTION_MASK} ${EXTRACTION_TMP} add_7 = pe.Node(ImageMath(operation='addtozero'), name='15_add_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} ME",
"use_random_seed : bool Whether ATROPOS should generate a random seed based on the",
":abbr:`TPMs (tissue probability maps)` \"\"\" wf = pe.Workflow(name) inputnode = pe.Node(niu.IdentityInterface(fields=['in_files', 'in_mask']), name='inputnode')",
"${EXTRACTION_MASK} 5 md_7_2 = pe.Node(ImageMath(operation='MD', op2='5'), name='21_md_7_2') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} ME ${EXTRACTION_MASK}",
"1), ('gm', 3), ('wm', 2), ]), } def init_atropos_wf(name='atropos_wf', use_random_seed=True, omp_nthreads=None, mem_gb=3.0, padding=10,",
"matter around the edge of the initial brain mask warped from the template.",
"ImageMath ${DIMENSION} ${EXTRACTION_SEGMENTATION} addtozero ${EXTRACTION_WM} ${EXTRACTION_GM} add_gm = pe.Node(ImageMath(operation='addtozero'), name='11_add_gm') relabel_gm = pe.Node(MultiplyImages(dimension=3,",
"('in_mask', 'mask_image')]), (atropos, pad_segm, [('classified_image', 'op1')]), (pad_segm, sel_labels, [('output_image', 'in_segm')]), (sel_labels, get_wm, [('out_wm',",
"${EXTRACTION_TMP} FillHoles ${EXTRACTION_GM} 2 # MultiplyImages ${DIMENSION} ${EXTRACTION_GM} ${EXTRACTION_TMP} ${EXTRACTION_GM} fill_gm = pe.Node(ImageMath(operation='FillHoles',",
"(('output_image', _gen_name), 'output_product_image')]), (sel_labels, me_csf, [('out_csf', 'op1')]), (mult_gm, add_gm, [('output_product_image', 'op1')]), (me_csf, add_gm,",
"second_input=in_segmentation_model[-1]), name='09_relabel_wm') me_csf = pe.Node(ImageMath(operation='ME', op2='10'), name='10_me_csf') # ImageMath ${DIMENSION} ${EXTRACTION_GM} addtozero ${EXTRACTION_GM}",
"= pe.Node(niu.IdentityInterface( fields=['out_mask', 'out_segm', 'out_tpms']), name='outputnode') # Run atropos (core node) atropos =",
"csfLabel, gmLabel, wmLabel). Examples: - ``(3,1,2,3)`` for T1 with K=3, CSF=1, GM=2, WM=3",
"padding), name='23_depad_mask') depad_segm = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='24_depad_segm') depad_gm = pe.Node(ImageMath(operation='PadImage', op2='-%d'",
"[('out_gm', 'op1')]), (get_gm, fill_gm, [('output_image', 'op1')]), (get_gm, mult_gm, [('output_image', 'first_input'), (('output_image', _gen_name), 'output_product_image')]),",
"newnii = nii.__class__(data, nii.affine, nii.header) newnii.set_data_dtype('uint8') out_file = fname_presuffix(in_segm, suffix='class-%02d' % l, newpath=cwd)",
"MultiplyImages ${DIMENSION} ${EXTRACTION_WM} ${ATROPOS_WM_CLASS_LABEL} ${EXTRACTION_WM} # ImageMath ${DIMENSION} ${EXTRACTION_TMP} ME ${EXTRACTION_CSF} 10 relabel_wm",
"'op1')]), (me_7, comp_7, [('output_image', 'op1')]), (comp_7, md_7, [('output_image', 'op1')]), (md_7, fill_7, [('output_image', 'op1')]),",
"${DIMENSION} ${EXTRACTION_GM} ${EXTRACTION_TMP} ${EXTRACTION_GM} fill_gm = pe.Node(ImageMath(operation='FillHoles', op2='2'), name='07_fill_gm') mult_gm = pe.Node(MultiplyImages(dimension=3), name='08_mult_gm')",
"'out_gm', 'out_csf']), name='04_sel_labels') sel_labels.inputs.labels = list(reversed(in_segmentation_model[1:])) # Select largest components (GM, WM) #",
"(mult_gm, add_gm, [('output_product_image', 'op1')]), (me_csf, add_gm, [('output_image', 'op2')]), (add_gm, relabel_gm, [('output_image', 'first_input'), (('output_image',",
"depad_mask, [('output_image', 'op1')]), (add_gm_wm, depad_segm, [('output_image', 'op1')]), (relabel_wm, depad_wm, [('output_product_image', 'op1')]), (relabel_gm, depad_gm,",
"md_7_2, [('output_image', 'op1')]), (md_7_2, me_7_2, [('output_image', 'op1')]), (me_7_2, depad_mask, [('output_image', 'op1')]), (add_gm_wm, depad_segm,",
"${EXTRACTION_GM} ${EXTRACTION_TMP} ${EXTRACTION_GM} fill_gm = pe.Node(ImageMath(operation='FillHoles', op2='2'), name='07_fill_gm') mult_gm = pe.Node(MultiplyImages(dimension=3), name='08_mult_gm') #",
": bool Whether ATROPOS should generate a random seed based on the system's",
"utility as niu from nipype.interfaces.ants import Atropos, MultiplyImages from ..interfaces.ants import ImageMath ATROPOS_MODELS",
"labels: data = (nii.get_data() == l).astype(np.uint8) newnii = nii.__class__(data, nii.affine, nii.header) newnii.set_data_dtype('uint8') out_file",
"'op1')]), (get_gm, mult_gm, [('output_image', 'first_input'), (('output_image', _gen_name), 'output_product_image')]), (fill_gm, mult_gm, [('output_image', 'second_input')]), (get_wm,",
"and 7 of ``antsBrainExtraction.sh``, which refine the mask previously computed with the spatial",
"OrderedDict([ ('nclasses', 3), ('csf', 1), ('gm', 2), ('wm', 3), ]), 'T2': OrderedDict([ ('nclasses',",
"around the edge of the initial brain mask warped from the template. This",
"${DIMENSION} ${EXTRACTION_MASK} MD ${EXTRACTION_MASK} 4 md_7 = pe.Node(ImageMath(operation='MD', op2='4'), name='18_md_7') # ImageMath ${DIMENSION}",
"md_7 = pe.Node(ImageMath(operation='MD', op2='4'), name='18_md_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} FillHoles ${EXTRACTION_MASK} 2 fill_7",
"[('output_image', 'first_input'), (('output_image', _gen_name), 'output_product_image')]), (relabel_wm, add_gm_wm, [('output_product_image', 'op1')]), (relabel_gm, add_gm_wm, [('output_product_image', 'op2')]),",
"op2='2'), name='16_me_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} GetLargestComponent ${EXTRACTION_MASK} comp_7 = pe.Node(ImageMath(operation='GetLargestComponent'), name='17_comp_7') #",
"ImageMath ${DIMENSION} ${EXTRACTION_MASK} FillHoles ${EXTRACTION_MASK} 2 fill_7 = pe.Node(ImageMath(operation='FillHoles', op2='2'), name='19_fill_7') # ImageMath",
"FillHoles ${EXTRACTION_MASK} 2 fill_7 = pe.Node(ImageMath(operation='FillHoles', op2='2'), name='19_fill_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} addtozero",
"non-uniformity)`-corrected files. in_mask Brain mask calculated previously **Outputs** out_mask Refined brain mask out_segm",
"]), 'FLAIR': OrderedDict([ ('nclasses', 3), ('csf', 1), ('gm', 3), ('wm', 2), ]), }",
"pad_mask = pe.Node(ImageMath(operation='PadImage', op2='%d' % padding), name='03_pad_mask') # Split segmentation in binary masks",
"float Estimated peak memory consumption of the most hungry nodes in the workflow",
"('csf', 1), ('gm', 2), ('wm', 3), ]), 'T2': OrderedDict([ ('nclasses', 3), ('csf', 3),",
"= pe.Node(ImageMath(operation='PadImage', op2='%d' % padding), name='02_pad_segm') pad_mask = pe.Node(ImageMath(operation='PadImage', op2='%d' % padding), name='03_pad_mask')",
"== l).astype(np.uint8) newnii = nii.__class__(data, nii.affine, nii.header) newnii.set_data_dtype('uint8') out_file = fname_presuffix(in_segm, suffix='class-%02d' %",
"(add_gm_wm, sel_labels2, [('output_image', 'in_segm')]), (sel_labels2, add_7, [('out_wm', 'op1'), ('out_gm', 'op2')]), (add_7, me_7, [('output_image',",
"fname_presuffix(in_segm, suffix='class-%02d' % l, newpath=cwd) newnii.to_filename(out_file) out_files.append(out_file) return out_files def _gen_name(in_file): import os",
"labels): from os import getcwd import numpy as np import nibabel as nb",
"name='21_md_7_2') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} ME ${EXTRACTION_MASK} 5 me_7_2 = pe.Node(ImageMath(operation='ME', op2='5'), name='22_me_7_2')",
"'mask_image')]), (atropos, pad_segm, [('classified_image', 'op1')]), (pad_segm, sel_labels, [('output_image', 'in_segm')]), (sel_labels, get_wm, [('out_wm', 'op1')]),",
"(md_7, fill_7, [('output_image', 'op1')]), (fill_7, add_7_2, [('output_image', 'op1')]), (pad_mask, add_7_2, [('output_image', 'op2')]), (add_7_2,",
"from collections import OrderedDict from nipype.pipeline import engine as pe from nipype.interfaces import",
"use_random_seed=use_random_seed), name='01_atropos', n_procs=omp_nthreads, mem_gb=mem_gb) # massage outputs pad_segm = pe.Node(ImageMath(operation='PadImage', op2='%d' % padding),",
"mult_gm = pe.Node(MultiplyImages(dimension=3), name='08_mult_gm') # MultiplyImages ${DIMENSION} ${EXTRACTION_WM} ${ATROPOS_WM_CLASS_LABEL} ${EXTRACTION_WM} # ImageMath ${DIMENSION}",
"sel_labels2 = pe.Node(niu.Function(function=_select_labels, output_names=['out_wm', 'out_gm', 'out_csf']), name='14_sel_labels2') sel_labels2.inputs.labels = list(reversed(in_segmentation_model[1:])) # ImageMath ${DIMENSION}",
"'intensity_images'), ('in_mask', 'mask_image')]), (atropos, pad_segm, [('classified_image', 'op1')]), (pad_segm, sel_labels, [('output_image', 'in_segm')]), (sel_labels, get_wm,",
"pe from nipype.interfaces import utility as niu from nipype.interfaces.ants import Atropos, MultiplyImages from",
"ImageMath ${DIMENSION} ${EXTRACTION_WM} GetLargestComponent ${EXTRACTION_WM} get_wm = pe.Node(ImageMath(operation='GetLargestComponent'), name='05_get_wm') get_gm = pe.Node(ImageMath(operation='GetLargestComponent'), name='06_get_gm')",
"with K=3, CSF=3, GM=2, WM=1 - ``(3,1,3,2)`` for FLAIR with K=3, CSF=1 GM=3,",
"= pe.Node(ImageMath(operation='MD', op2='5'), name='21_md_7_2') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} ME ${EXTRACTION_MASK} 5 me_7_2 =",
"[('output_image', 'first_input'), (('output_image', _gen_name), 'output_product_image')]), (fill_gm, mult_gm, [('output_image', 'second_input')]), (get_wm, relabel_wm, [('output_image', 'first_input'),",
"op2='-%d' % padding), name='27_depad_csf') merge_tpms = pe.Node(niu.Merge(in_segmentation_model[0]), name='merge_tpms') wf.connect([ (inputnode, pad_mask, [('in_mask', 'op1')]),",
"outputnode, [('out', 'out_tpms')]), ]) return wf def _select_labels(in_segm, labels): from os import getcwd",
"add_gm, [('output_product_image', 'op1')]), (me_csf, add_gm, [('output_image', 'op2')]), (add_gm, relabel_gm, [('output_image', 'first_input'), (('output_image', _gen_name),",
"pe.Node(ImageMath(operation='GetLargestComponent'), name='17_comp_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} MD ${EXTRACTION_MASK} 4 md_7 = pe.Node(ImageMath(operation='MD', op2='4'),",
"(('output_image', _gen_name), 'output_product_image')]), (fill_gm, mult_gm, [('output_image', 'second_input')]), (get_wm, relabel_wm, [('output_image', 'first_input'), (('output_image', _gen_name),",
"process may use mem_gb : float Estimated peak memory consumption of the most",
"Output :abbr:`TPMs (tissue probability maps)` \"\"\" wf = pe.Workflow(name) inputnode = pe.Node(niu.IdentityInterface(fields=['in_files', 'in_mask']),",
"3), ]), 'T2': OrderedDict([ ('nclasses', 3), ('csf', 3), ('gm', 2), ('wm', 1), ]),",
"pe.Node(ImageMath(operation='MD', op2='4'), name='18_md_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} FillHoles ${EXTRACTION_MASK} 2 fill_7 = pe.Node(ImageMath(operation='FillHoles',",
"${EXTRACTION_MASK} \\ # ${EXTRACTION_MASK_PRIOR_WARPED} add_7_2 = pe.Node(ImageMath(operation='addtozero'), name='20_add_7_2') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} MD",
"me_7, [('output_image', 'op1')]), (me_7, comp_7, [('output_image', 'op1')]), (comp_7, md_7, [('output_image', 'op1')]), (md_7, fill_7,",
"pe.Node(ImageMath(operation='GetLargestComponent'), name='05_get_wm') get_gm = pe.Node(ImageMath(operation='GetLargestComponent'), name='06_get_gm') # Fill holes and calculate intersection #",
"'op1')]), (md_7, fill_7, [('output_image', 'op1')]), (fill_7, add_7_2, [('output_image', 'op1')]), (pad_mask, add_7_2, [('output_image', 'op2')]),",
"merge_tpms = pe.Node(niu.Merge(in_segmentation_model[0]), name='merge_tpms') wf.connect([ (inputnode, pad_mask, [('in_mask', 'op1')]), (inputnode, atropos, [('in_files', 'intensity_images'),",
"classes represent CSF, gray and white matter. Format (K, csfLabel, gmLabel, wmLabel). Examples:",
"brain mask warped from the template. This produces a segmentation image with :math:`$K$`",
"brain mask out_segm Output segmentation out_tpms Output :abbr:`TPMs (tissue probability maps)` \"\"\" wf",
"fill_7 = pe.Node(ImageMath(operation='FillHoles', op2='2'), name='19_fill_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} addtozero ${EXTRACTION_MASK} \\ #",
"Pad images with zeros before processing in_segmentation_model : tuple A k-means segmentation is",
"% padding), name='24_depad_segm') depad_gm = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='25_depad_gm') depad_wm = pe.Node(ImageMath(operation='PadImage',",
"'op1')]), (get_gm, fill_gm, [('output_image', 'op1')]), (get_gm, mult_gm, [('output_image', 'first_input'), (('output_image', _gen_name), 'output_product_image')]), (fill_gm,",
"(fill_gm, mult_gm, [('output_image', 'second_input')]), (get_wm, relabel_wm, [('output_image', 'first_input'), (('output_image', _gen_name), 'output_product_image')]), (sel_labels, me_csf,",
"(merge_tpms, outputnode, [('out', 'out_tpms')]), ]) return wf def _select_labels(in_segm, labels): from os import",
":math:`$K$` and tell the script which classes represent CSF, gray and white matter.",
":math:`$K$` classes, ordered by mean intensity in increasing order. With this option, you",
"of the most hungry nodes in the workflow padding : int Pad images",
"[('output_image', 'op1')]), (comp_7, md_7, [('output_image', 'op1')]), (md_7, fill_7, [('output_image', 'op1')]), (fill_7, add_7_2, [('output_image',",
"(get_gm, fill_gm, [('output_image', 'op1')]), (get_gm, mult_gm, [('output_image', 'first_input'), (('output_image', _gen_name), 'output_product_image')]), (fill_gm, mult_gm,",
"[('output_image', 'op1')]), (me_7, comp_7, [('output_image', 'op1')]), (comp_7, md_7, [('output_image', 'op1')]), (md_7, fill_7, [('output_image',",
"1, 1], mrf_smoothing_factor=0.1, likelihood_model='Gaussian', use_random_seed=use_random_seed), name='01_atropos', n_procs=omp_nthreads, mem_gb=mem_gb) # massage outputs pad_segm =",
"[('output_image', 'first_input'), (('output_image', _gen_name), 'output_product_image')]), (sel_labels, me_csf, [('out_csf', 'op1')]), (mult_gm, add_gm, [('output_product_image', 'op1')]),",
"in_files :abbr:`INU (intensity non-uniformity)`-corrected files. in_mask Brain mask calculated previously **Outputs** out_mask Refined",
"${EXTRACTION_MASK} 5 me_7_2 = pe.Node(ImageMath(operation='ME', op2='5'), name='22_me_7_2') # De-pad depad_mask = pe.Node(ImageMath(operation='PadImage', op2='-%d'",
"= list(reversed(in_segmentation_model[1:])) # Select largest components (GM, WM) # ImageMath ${DIMENSION} ${EXTRACTION_WM} GetLargestComponent",
"in binary masks sel_labels = pe.Node(niu.Function(function=_select_labels, output_names=['out_wm', 'out_gm', 'out_csf']), name='04_sel_labels') sel_labels.inputs.labels = list(reversed(in_segmentation_model[1:]))",
"pe.Node(ImageMath(operation='GetLargestComponent'), name='06_get_gm') # Fill holes and calculate intersection # ImageMath ${DIMENSION} ${EXTRACTION_TMP} FillHoles",
"${EXTRACTION_WM} GetLargestComponent ${EXTRACTION_WM} get_wm = pe.Node(ImageMath(operation='GetLargestComponent'), name='05_get_wm') get_gm = pe.Node(ImageMath(operation='GetLargestComponent'), name='06_get_gm') # Fill",
"[('output_image', 'second_input')]), (get_wm, relabel_wm, [('output_image', 'first_input'), (('output_image', _gen_name), 'output_product_image')]), (sel_labels, me_csf, [('out_csf', 'op1')]),",
"as nb from nipype.utils.filemanip import fname_presuffix out_files = [] cwd = getcwd() nii",
"2 me_7 = pe.Node(ImageMath(operation='ME', op2='2'), name='16_me_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} GetLargestComponent ${EXTRACTION_MASK} comp_7",
"'out_gm', 'out_csf']), name='14_sel_labels2') sel_labels2.inputs.labels = list(reversed(in_segmentation_model[1:])) # ImageMath ${DIMENSION} ${EXTRACTION_MASK} addtozero ${EXTRACTION_MASK} ${EXTRACTION_TMP}",
"name='20_add_7_2') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} MD ${EXTRACTION_MASK} 5 md_7_2 = pe.Node(ImageMath(operation='MD', op2='5'), name='21_md_7_2')",
"name='outputnode') # Run atropos (core node) atropos = pe.Node(Atropos( dimension=3, initialization='KMeans', number_of_tissue_classes=in_segmentation_model[0], n_iterations=3,",
"A k-means segmentation is run to find gray or white matter around the",
"the template. This produces a segmentation image with :math:`$K$` classes, ordered by mean",
"GM=2, WM=1 - ``(3,1,3,2)`` for FLAIR with K=3, CSF=1 GM=3, WM=2 - ``(4,4,2,3)``",
"'op1')]), (mult_gm, add_gm, [('output_product_image', 'op1')]), (me_csf, add_gm, [('output_image', 'op2')]), (add_gm, relabel_gm, [('output_image', 'first_input'),",
"as np import nibabel as nb from nipype.utils.filemanip import fname_presuffix out_files = []",
"sel_labels2, [('output_image', 'in_segm')]), (sel_labels2, add_7, [('out_wm', 'op1'), ('out_gm', 'op2')]), (add_7, me_7, [('output_image', 'op1')]),",
"from nipype.pipeline import engine as pe from nipype.interfaces import utility as niu from",
"hungry nodes in the workflow padding : int Pad images with zeros before",
"name='12_relabel_gm') add_gm_wm = pe.Node(ImageMath(operation='addtozero'), name='13_add_gm_wm') # Superstep 7 # Split segmentation in binary",
"in_segmentation_model : tuple A k-means segmentation is run to find gray or white",
"name='27_depad_csf') merge_tpms = pe.Node(niu.Merge(in_segmentation_model[0]), name='merge_tpms') wf.connect([ (inputnode, pad_mask, [('in_mask', 'op1')]), (inputnode, atropos, [('in_files',",
"collections import OrderedDict from nipype.pipeline import engine as pe from nipype.interfaces import utility",
"add_gm_wm = pe.Node(ImageMath(operation='addtozero'), name='13_add_gm_wm') # Superstep 7 # Split segmentation in binary masks",
"Estimated peak memory consumption of the most hungry nodes in the workflow padding",
"workflow padding : int Pad images with zeros before processing in_segmentation_model : tuple",
"pe.Node(MultiplyImages(dimension=3), name='08_mult_gm') # MultiplyImages ${DIMENSION} ${EXTRACTION_WM} ${ATROPOS_WM_CLASS_LABEL} ${EXTRACTION_WM} # ImageMath ${DIMENSION} ${EXTRACTION_TMP} ME",
"_gen_name), 'output_product_image')]), (sel_labels, me_csf, [('out_csf', 'op1')]), (mult_gm, add_gm, [('output_product_image', 'op1')]), (me_csf, add_gm, [('output_image',",
"(('output_image', _gen_name), 'output_product_image')]), (relabel_wm, add_gm_wm, [('output_product_image', 'op1')]), (relabel_gm, add_gm_wm, [('output_product_image', 'op2')]), (add_gm_wm, sel_labels2,",
"= pe.Node(ImageMath(operation='addtozero'), name='20_add_7_2') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} MD ${EXTRACTION_MASK} 5 md_7_2 = pe.Node(ImageMath(operation='MD',",
"segmentation is run to find gray or white matter around the edge of",
"'in1')]), (depad_gm, merge_tpms, [('output_image', 'in2')]), (depad_wm, merge_tpms, [('output_image', 'in3')]), (depad_mask, outputnode, [('output_image', 'out_mask')]),",
"${EXTRACTION_MASK} GetLargestComponent ${EXTRACTION_MASK} comp_7 = pe.Node(ImageMath(operation='GetLargestComponent'), name='17_comp_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} MD ${EXTRACTION_MASK}",
"5 md_7_2 = pe.Node(ImageMath(operation='MD', op2='5'), name='21_md_7_2') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} ME ${EXTRACTION_MASK} 5",
"'out_segm', 'out_tpms']), name='outputnode') # Run atropos (core node) atropos = pe.Node(Atropos( dimension=3, initialization='KMeans',",
"``(3,3,2,1)`` for T2 with K=3, CSF=3, GM=2, WM=1 - ``(3,1,3,2)`` for FLAIR with",
"(default: atropos_wf) **Inputs** in_files :abbr:`INU (intensity non-uniformity)`-corrected files. in_mask Brain mask calculated previously",
"this option, you can control :math:`$K$` and tell the script which classes represent",
"out_tpms Output :abbr:`TPMs (tissue probability maps)` \"\"\" wf = pe.Workflow(name) inputnode = pe.Node(niu.IdentityInterface(fields=['in_files',",
"${DIMENSION} ${EXTRACTION_GM} addtozero ${EXTRACTION_GM} ${EXTRACTION_TMP} # MultiplyImages ${DIMENSION} ${EXTRACTION_GM} ${ATROPOS_GM_CLASS_LABEL} ${EXTRACTION_GM} # ImageMath",
"(inputnode, atropos, [('in_files', 'intensity_images'), ('in_mask', 'mask_image')]), (atropos, pad_segm, [('classified_image', 'op1')]), (pad_segm, sel_labels, [('output_image',",
"``antsBrainExtraction.sh``, which refine the mask previously computed with the spatial normalization to the",
"% padding), name='02_pad_segm') pad_mask = pe.Node(ImageMath(operation='PadImage', op2='%d' % padding), name='03_pad_mask') # Split segmentation",
"% padding), name='23_depad_mask') depad_segm = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='24_depad_segm') depad_gm = pe.Node(ImageMath(operation='PadImage',",
"(atropos, pad_segm, [('classified_image', 'op1')]), (pad_segm, sel_labels, [('output_image', 'in_segm')]), (sel_labels, get_wm, [('out_wm', 'op1')]), (sel_labels,",
"${EXTRACTION_MASK} ME ${EXTRACTION_MASK} 2 me_7 = pe.Node(ImageMath(operation='ME', op2='2'), name='16_me_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK}",
"to find gray or white matter around the edge of the initial brain",
"mask calculated previously **Outputs** out_mask Refined brain mask out_segm Output segmentation out_tpms Output",
"With this option, you can control :math:`$K$` and tell the script which classes",
"mem_gb=3.0, padding=10, in_segmentation_model=list(ATROPOS_MODELS['T1'].values())): \"\"\" Implements supersteps 6 and 7 of ``antsBrainExtraction.sh``, which refine",
"the script which classes represent CSF, gray and white matter. Format (K, csfLabel,",
"'op1')]), (md_7_2, me_7_2, [('output_image', 'op1')]), (me_7_2, depad_mask, [('output_image', 'op1')]), (add_gm_wm, depad_segm, [('output_image', 'op1')]),",
"l).astype(np.uint8) newnii = nii.__class__(data, nii.affine, nii.header) newnii.set_data_dtype('uint8') out_file = fname_presuffix(in_segm, suffix='class-%02d' % l,",
"masks sel_labels = pe.Node(niu.Function(function=_select_labels, output_names=['out_wm', 'out_gm', 'out_csf']), name='04_sel_labels') sel_labels.inputs.labels = list(reversed(in_segmentation_model[1:])) # Select",
"[] cwd = getcwd() nii = nb.load(in_segm) for l in labels: data =",
"'in2')]), (depad_wm, merge_tpms, [('output_image', 'in3')]), (depad_mask, outputnode, [('output_image', 'out_mask')]), (depad_segm, outputnode, [('output_image', 'out_segm')]),",
"find gray or white matter around the edge of the initial brain mask",
"outputs pad_segm = pe.Node(ImageMath(operation='PadImage', op2='%d' % padding), name='02_pad_segm') pad_mask = pe.Node(ImageMath(operation='PadImage', op2='%d' %",
"``(3,1,3,2)`` for FLAIR with K=3, CSF=1 GM=3, WM=2 - ``(4,4,2,3)`` uses K=4, CSF=4,",
"intersection # ImageMath ${DIMENSION} ${EXTRACTION_TMP} FillHoles ${EXTRACTION_GM} 2 # MultiplyImages ${DIMENSION} ${EXTRACTION_GM} ${EXTRACTION_TMP}",
"[('out_csf', 'op1')]), (mult_gm, add_gm, [('output_product_image', 'op1')]), (me_csf, add_gm, [('output_image', 'op2')]), (add_gm, relabel_gm, [('output_image',",
"merge_tpms, [('output_image', 'in2')]), (depad_wm, merge_tpms, [('output_image', 'in3')]), (depad_mask, outputnode, [('output_image', 'out_mask')]), (depad_segm, outputnode,",
"(sel_labels2, add_7, [('out_wm', 'op1'), ('out_gm', 'op2')]), (add_7, me_7, [('output_image', 'op1')]), (me_7, comp_7, [('output_image',",
"K=3, CSF=1, GM=2, WM=3 (default) - ``(3,3,2,1)`` for T2 with K=3, CSF=3, GM=2,",
"Workflow name (default: atropos_wf) **Inputs** in_files :abbr:`INU (intensity non-uniformity)`-corrected files. in_mask Brain mask",
"name='inputnode') outputnode = pe.Node(niu.IdentityInterface( fields=['out_mask', 'out_segm', 'out_tpms']), name='outputnode') # Run atropos (core node)",
"[('in_files', 'intensity_images'), ('in_mask', 'mask_image')]), (atropos, pad_segm, [('classified_image', 'op1')]), (pad_segm, sel_labels, [('output_image', 'in_segm')]), (sel_labels,",
"= pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='25_depad_gm') depad_wm = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='26_depad_wm')",
"depad_wm = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='26_depad_wm') depad_csf = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding),",
"number_of_tissue_classes=in_segmentation_model[0], n_iterations=3, convergence_threshold=0.0, mrf_radius=[1, 1, 1], mrf_smoothing_factor=0.1, likelihood_model='Gaussian', use_random_seed=use_random_seed), name='01_atropos', n_procs=omp_nthreads, mem_gb=mem_gb) #",
"pe.Node(ImageMath(operation='addtozero'), name='13_add_gm_wm') # Superstep 7 # Split segmentation in binary masks sel_labels2 =",
"tuple A k-means segmentation is run to find gray or white matter around",
"matter. Format (K, csfLabel, gmLabel, wmLabel). Examples: - ``(3,1,2,3)`` for T1 with K=3,",
"``(3,1,2,3)`` for T1 with K=3, CSF=1, GM=2, WM=3 (default) - ``(3,3,2,1)`` for T2",
"name='14_sel_labels2') sel_labels2.inputs.labels = list(reversed(in_segmentation_model[1:])) # ImageMath ${DIMENSION} ${EXTRACTION_MASK} addtozero ${EXTRACTION_MASK} ${EXTRACTION_TMP} add_7 =",
"import utility as niu from nipype.interfaces.ants import Atropos, MultiplyImages from ..interfaces.ants import ImageMath",
"with the spatial normalization to the template. **Parameters** use_random_seed : bool Whether ATROPOS",
"np import nibabel as nb from nipype.utils.filemanip import fname_presuffix out_files = [] cwd",
"uses K=4, CSF=4, GM=2, WM=3 name : str, optional Workflow name (default: atropos_wf)",
"binary masks sel_labels = pe.Node(niu.Function(function=_select_labels, output_names=['out_wm', 'out_gm', 'out_csf']), name='04_sel_labels') sel_labels.inputs.labels = list(reversed(in_segmentation_model[1:])) #",
"# De-pad depad_mask = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='23_depad_mask') depad_segm = pe.Node(ImageMath(operation='PadImage', op2='-%d'",
"clock omp_nthreads : int Maximum number of threads an individual process may use",
"mask out_segm Output segmentation out_tpms Output :abbr:`TPMs (tissue probability maps)` \"\"\" wf =",
"# ImageMath ${DIMENSION} ${EXTRACTION_MASK} MD ${EXTRACTION_MASK} 4 md_7 = pe.Node(ImageMath(operation='MD', op2='4'), name='18_md_7') #",
"'out_csf']), name='04_sel_labels') sel_labels.inputs.labels = list(reversed(in_segmentation_model[1:])) # Select largest components (GM, WM) # ImageMath",
"(get_wm, relabel_wm, [('output_image', 'first_input'), (('output_image', _gen_name), 'output_product_image')]), (sel_labels, me_csf, [('out_csf', 'op1')]), (mult_gm, add_gm,",
"control :math:`$K$` and tell the script which classes represent CSF, gray and white",
"= pe.Node(MultiplyImages(dimension=3), name='08_mult_gm') # MultiplyImages ${DIMENSION} ${EXTRACTION_WM} ${ATROPOS_WM_CLASS_LABEL} ${EXTRACTION_WM} # ImageMath ${DIMENSION} ${EXTRACTION_TMP}",
"= pe.Node(ImageMath(operation='ME', op2='5'), name='22_me_7_2') # De-pad depad_mask = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='23_depad_mask')",
"**Parameters** use_random_seed : bool Whether ATROPOS should generate a random seed based on",
"${DIMENSION} ${EXTRACTION_WM} GetLargestComponent ${EXTRACTION_WM} get_wm = pe.Node(ImageMath(operation='GetLargestComponent'), name='05_get_wm') get_gm = pe.Node(ImageMath(operation='GetLargestComponent'), name='06_get_gm') #",
"% padding), name='27_depad_csf') merge_tpms = pe.Node(niu.Merge(in_segmentation_model[0]), name='merge_tpms') wf.connect([ (inputnode, pad_mask, [('in_mask', 'op1')]), (inputnode,",
"out_mask Refined brain mask out_segm Output segmentation out_tpms Output :abbr:`TPMs (tissue probability maps)`",
"the spatial normalization to the template. **Parameters** use_random_seed : bool Whether ATROPOS should",
"${DIMENSION} ${EXTRACTION_TMP} FillHoles ${EXTRACTION_GM} 2 # MultiplyImages ${DIMENSION} ${EXTRACTION_GM} ${EXTRACTION_TMP} ${EXTRACTION_GM} fill_gm =",
"op2='4'), name='18_md_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} FillHoles ${EXTRACTION_MASK} 2 fill_7 = pe.Node(ImageMath(operation='FillHoles', op2='2'),",
"n_iterations=3, convergence_threshold=0.0, mrf_radius=[1, 1, 1], mrf_smoothing_factor=0.1, likelihood_model='Gaussian', use_random_seed=use_random_seed), name='01_atropos', n_procs=omp_nthreads, mem_gb=mem_gb) # massage",
"Select largest components (GM, WM) # ImageMath ${DIMENSION} ${EXTRACTION_WM} GetLargestComponent ${EXTRACTION_WM} get_wm =",
"name='07_fill_gm') mult_gm = pe.Node(MultiplyImages(dimension=3), name='08_mult_gm') # MultiplyImages ${DIMENSION} ${EXTRACTION_WM} ${ATROPOS_WM_CLASS_LABEL} ${EXTRACTION_WM} # ImageMath",
"GetLargestComponent ${EXTRACTION_WM} get_wm = pe.Node(ImageMath(operation='GetLargestComponent'), name='05_get_wm') get_gm = pe.Node(ImageMath(operation='GetLargestComponent'), name='06_get_gm') # Fill holes",
"spatial normalization to the template. **Parameters** use_random_seed : bool Whether ATROPOS should generate",
"intensity in increasing order. With this option, you can control :math:`$K$` and tell",
"# ImageMath ${DIMENSION} ${EXTRACTION_MASK} FillHoles ${EXTRACTION_MASK} 2 fill_7 = pe.Node(ImageMath(operation='FillHoles', op2='2'), name='19_fill_7') #",
"Brain mask calculated previously **Outputs** out_mask Refined brain mask out_segm Output segmentation out_tpms",
"list(reversed(in_segmentation_model[1:])) # Select largest components (GM, WM) # ImageMath ${DIMENSION} ${EXTRACTION_WM} GetLargestComponent ${EXTRACTION_WM}",
"'op1')]), (fill_7, add_7_2, [('output_image', 'op1')]), (pad_mask, add_7_2, [('output_image', 'op2')]), (add_7_2, md_7_2, [('output_image', 'op1')]),",
"${DIMENSION} ${EXTRACTION_MASK} addtozero ${EXTRACTION_MASK} ${EXTRACTION_TMP} add_7 = pe.Node(ImageMath(operation='addtozero'), name='15_add_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK}",
"(depad_gm, merge_tpms, [('output_image', 'in2')]), (depad_wm, merge_tpms, [('output_image', 'in3')]), (depad_mask, outputnode, [('output_image', 'out_mask')]), (depad_segm,",
"pe.Node(niu.IdentityInterface(fields=['in_files', 'in_mask']), name='inputnode') outputnode = pe.Node(niu.IdentityInterface( fields=['out_mask', 'out_segm', 'out_tpms']), name='outputnode') # Run atropos",
"classes, ordered by mean intensity in increasing order. With this option, you can",
"output_names=['out_wm', 'out_gm', 'out_csf']), name='04_sel_labels') sel_labels.inputs.labels = list(reversed(in_segmentation_model[1:])) # Select largest components (GM, WM)",
"in the workflow padding : int Pad images with zeros before processing in_segmentation_model",
"pe.Node(Atropos( dimension=3, initialization='KMeans', number_of_tissue_classes=in_segmentation_model[0], n_iterations=3, convergence_threshold=0.0, mrf_radius=[1, 1, 1], mrf_smoothing_factor=0.1, likelihood_model='Gaussian', use_random_seed=use_random_seed), name='01_atropos',",
"= pe.Node(ImageMath(operation='addtozero'), name='15_add_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} ME ${EXTRACTION_MASK} 2 me_7 = pe.Node(ImageMath(operation='ME',",
"n_procs=omp_nthreads, mem_gb=mem_gb) # massage outputs pad_segm = pe.Node(ImageMath(operation='PadImage', op2='%d' % padding), name='02_pad_segm') pad_mask",
"calculate intersection # ImageMath ${DIMENSION} ${EXTRACTION_TMP} FillHoles ${EXTRACTION_GM} 2 # MultiplyImages ${DIMENSION} ${EXTRACTION_GM}",
"in binary masks sel_labels2 = pe.Node(niu.Function(function=_select_labels, output_names=['out_wm', 'out_gm', 'out_csf']), name='14_sel_labels2') sel_labels2.inputs.labels = list(reversed(in_segmentation_model[1:]))",
"[('out_wm', 'op1')]), (sel_labels, get_gm, [('out_gm', 'op1')]), (get_gm, fill_gm, [('output_image', 'op1')]), (get_gm, mult_gm, [('output_image',",
"2 # MultiplyImages ${DIMENSION} ${EXTRACTION_GM} ${EXTRACTION_TMP} ${EXTRACTION_GM} fill_gm = pe.Node(ImageMath(operation='FillHoles', op2='2'), name='07_fill_gm') mult_gm",
"${EXTRACTION_WM} ${EXTRACTION_GM} add_gm = pe.Node(ImageMath(operation='addtozero'), name='11_add_gm') relabel_gm = pe.Node(MultiplyImages(dimension=3, second_input=in_segmentation_model[-2]), name='12_relabel_gm') add_gm_wm =",
"name='05_get_wm') get_gm = pe.Node(ImageMath(operation='GetLargestComponent'), name='06_get_gm') # Fill holes and calculate intersection # ImageMath",
"import ImageMath ATROPOS_MODELS = { 'T1': OrderedDict([ ('nclasses', 3), ('csf', 1), ('gm', 2),",
"wf = pe.Workflow(name) inputnode = pe.Node(niu.IdentityInterface(fields=['in_files', 'in_mask']), name='inputnode') outputnode = pe.Node(niu.IdentityInterface( fields=['out_mask', 'out_segm',",
"depad_wm, [('output_product_image', 'op1')]), (relabel_gm, depad_gm, [('output_product_image', 'op1')]), (sel_labels, depad_csf, [('out_csf', 'op1')]), (depad_csf, merge_tpms,",
"refine the mask previously computed with the spatial normalization to the template. **Parameters**",
"padding : int Pad images with zeros before processing in_segmentation_model : tuple A",
"**Outputs** out_mask Refined brain mask out_segm Output segmentation out_tpms Output :abbr:`TPMs (tissue probability",
"[('output_image', 'in_segm')]), (sel_labels2, add_7, [('out_wm', 'op1'), ('out_gm', 'op2')]), (add_7, me_7, [('output_image', 'op1')]), (me_7,",
"Split segmentation in binary masks sel_labels = pe.Node(niu.Function(function=_select_labels, output_names=['out_wm', 'out_gm', 'out_csf']), name='04_sel_labels') sel_labels.inputs.labels",
"OrderedDict([ ('nclasses', 3), ('csf', 3), ('gm', 2), ('wm', 1), ]), 'FLAIR': OrderedDict([ ('nclasses',",
"= pe.Node(MultiplyImages(dimension=3, second_input=in_segmentation_model[-2]), name='12_relabel_gm') add_gm_wm = pe.Node(ImageMath(operation='addtozero'), name='13_add_gm_wm') # Superstep 7 # Split",
"(depad_segm, outputnode, [('output_image', 'out_segm')]), (merge_tpms, outputnode, [('out', 'out_tpms')]), ]) return wf def _select_labels(in_segm,",
"(sel_labels, depad_csf, [('out_csf', 'op1')]), (depad_csf, merge_tpms, [('output_image', 'in1')]), (depad_gm, merge_tpms, [('output_image', 'in2')]), (depad_wm,",
"${DIMENSION} ${EXTRACTION_WM} ${ATROPOS_WM_CLASS_LABEL} ${EXTRACTION_WM} # ImageMath ${DIMENSION} ${EXTRACTION_TMP} ME ${EXTRACTION_CSF} 10 relabel_wm =",
"_gen_name), 'output_product_image')]), (relabel_wm, add_gm_wm, [('output_product_image', 'op1')]), (relabel_gm, add_gm_wm, [('output_product_image', 'op2')]), (add_gm_wm, sel_labels2, [('output_image',",
"name='15_add_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} ME ${EXTRACTION_MASK} 2 me_7 = pe.Node(ImageMath(operation='ME', op2='2'), name='16_me_7')",
"pe.Node(MultiplyImages(dimension=3, second_input=in_segmentation_model[-2]), name='12_relabel_gm') add_gm_wm = pe.Node(ImageMath(operation='addtozero'), name='13_add_gm_wm') # Superstep 7 # Split segmentation",
"4 md_7 = pe.Node(ImageMath(operation='MD', op2='4'), name='18_md_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} FillHoles ${EXTRACTION_MASK} 2",
"[('output_image', 'op1')]), (md_7, fill_7, [('output_image', 'op1')]), (fill_7, add_7_2, [('output_image', 'op1')]), (pad_mask, add_7_2, [('output_image',",
"${EXTRACTION_MASK_PRIOR_WARPED} add_7_2 = pe.Node(ImageMath(operation='addtozero'), name='20_add_7_2') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} MD ${EXTRACTION_MASK} 5 md_7_2",
"(me_7, comp_7, [('output_image', 'op1')]), (comp_7, md_7, [('output_image', 'op1')]), (md_7, fill_7, [('output_image', 'op1')]), (fill_7,",
"pe.Node(ImageMath(operation='ME', op2='2'), name='16_me_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} GetLargestComponent ${EXTRACTION_MASK} comp_7 = pe.Node(ImageMath(operation='GetLargestComponent'), name='17_comp_7')",
"[('out_wm', 'op1'), ('out_gm', 'op2')]), (add_7, me_7, [('output_image', 'op1')]), (me_7, comp_7, [('output_image', 'op1')]), (comp_7,",
"individual process may use mem_gb : float Estimated peak memory consumption of the",
"of the initial brain mask warped from the template. This produces a segmentation",
"# massage outputs pad_segm = pe.Node(ImageMath(operation='PadImage', op2='%d' % padding), name='02_pad_segm') pad_mask = pe.Node(ImageMath(operation='PadImage',",
"= nb.load(in_segm) for l in labels: data = (nii.get_data() == l).astype(np.uint8) newnii =",
"init_atropos_wf(name='atropos_wf', use_random_seed=True, omp_nthreads=None, mem_gb=3.0, padding=10, in_segmentation_model=list(ATROPOS_MODELS['T1'].values())): \"\"\" Implements supersteps 6 and 7 of",
"padding), name='24_depad_segm') depad_gm = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='25_depad_gm') depad_wm = pe.Node(ImageMath(operation='PadImage', op2='-%d'",
"(GM, WM) # ImageMath ${DIMENSION} ${EXTRACTION_WM} GetLargestComponent ${EXTRACTION_WM} get_wm = pe.Node(ImageMath(operation='GetLargestComponent'), name='05_get_wm') get_gm",
"ImageMath ${DIMENSION} ${EXTRACTION_MASK} ME ${EXTRACTION_MASK} 5 me_7_2 = pe.Node(ImageMath(operation='ME', op2='5'), name='22_me_7_2') # De-pad",
"# ImageMath ${DIMENSION} ${EXTRACTION_MASK} GetLargestComponent ${EXTRACTION_MASK} comp_7 = pe.Node(ImageMath(operation='GetLargestComponent'), name='17_comp_7') # ImageMath ${DIMENSION}",
"with K=3, CSF=1 GM=3, WM=2 - ``(4,4,2,3)`` uses K=4, CSF=4, GM=2, WM=3 name",
"'T1': OrderedDict([ ('nclasses', 3), ('csf', 1), ('gm', 2), ('wm', 3), ]), 'T2': OrderedDict([",
"('gm', 2), ('wm', 3), ]), 'T2': OrderedDict([ ('nclasses', 3), ('csf', 3), ('gm', 2),",
"name='25_depad_gm') depad_wm = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='26_depad_wm') depad_csf = pe.Node(ImageMath(operation='PadImage', op2='-%d' %",
"..interfaces.ants import ImageMath ATROPOS_MODELS = { 'T1': OrderedDict([ ('nclasses', 3), ('csf', 1), ('gm',",
"${DIMENSION} ${EXTRACTION_MASK} ME ${EXTRACTION_MASK} 2 me_7 = pe.Node(ImageMath(operation='ME', op2='2'), name='16_me_7') # ImageMath ${DIMENSION}",
"1), ]), 'FLAIR': OrderedDict([ ('nclasses', 3), ('csf', 1), ('gm', 3), ('wm', 2), ]),",
"(intensity non-uniformity)`-corrected files. in_mask Brain mask calculated previously **Outputs** out_mask Refined brain mask",
"most hungry nodes in the workflow padding : int Pad images with zeros",
"(default) - ``(3,3,2,1)`` for T2 with K=3, CSF=3, GM=2, WM=1 - ``(3,1,3,2)`` for",
"${EXTRACTION_CSF} 10 relabel_wm = pe.Node(MultiplyImages(dimension=3, second_input=in_segmentation_model[-1]), name='09_relabel_wm') me_csf = pe.Node(ImageMath(operation='ME', op2='10'), name='10_me_csf') #",
"= pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='24_depad_segm') depad_gm = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='25_depad_gm')",
"[('in_mask', 'op1')]), (inputnode, atropos, [('in_files', 'intensity_images'), ('in_mask', 'mask_image')]), (atropos, pad_segm, [('classified_image', 'op1')]), (pad_segm,",
"generate a random seed based on the system's clock omp_nthreads : int Maximum",
"nodes in the workflow padding : int Pad images with zeros before processing",
"= pe.Node(ImageMath(operation='GetLargestComponent'), name='05_get_wm') get_gm = pe.Node(ImageMath(operation='GetLargestComponent'), name='06_get_gm') # Fill holes and calculate intersection",
"${EXTRACTION_MASK} 2 me_7 = pe.Node(ImageMath(operation='ME', op2='2'), name='16_me_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} GetLargestComponent ${EXTRACTION_MASK}",
"addtozero ${EXTRACTION_WM} ${EXTRACTION_GM} add_gm = pe.Node(ImageMath(operation='addtozero'), name='11_add_gm') relabel_gm = pe.Node(MultiplyImages(dimension=3, second_input=in_segmentation_model[-2]), name='12_relabel_gm') add_gm_wm",
"import numpy as np import nibabel as nb from nipype.utils.filemanip import fname_presuffix out_files",
"in increasing order. With this option, you can control :math:`$K$` and tell the",
"memory consumption of the most hungry nodes in the workflow padding : int",
"pad_segm = pe.Node(ImageMath(operation='PadImage', op2='%d' % padding), name='02_pad_segm') pad_mask = pe.Node(ImageMath(operation='PadImage', op2='%d' % padding),",
"(get_gm, mult_gm, [('output_image', 'first_input'), (('output_image', _gen_name), 'output_product_image')]), (fill_gm, mult_gm, [('output_image', 'second_input')]), (get_wm, relabel_wm,",
"md_7_2 = pe.Node(ImageMath(operation='MD', op2='5'), name='21_md_7_2') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} ME ${EXTRACTION_MASK} 5 me_7_2",
"= [] cwd = getcwd() nii = nb.load(in_segm) for l in labels: data",
"'first_input'), (('output_image', _gen_name), 'output_product_image')]), (fill_gm, mult_gm, [('output_image', 'second_input')]), (get_wm, relabel_wm, [('output_image', 'first_input'), (('output_image',",
"number of threads an individual process may use mem_gb : float Estimated peak",
"name='merge_tpms') wf.connect([ (inputnode, pad_mask, [('in_mask', 'op1')]), (inputnode, atropos, [('in_files', 'intensity_images'), ('in_mask', 'mask_image')]), (atropos,",
"(depad_mask, outputnode, [('output_image', 'out_mask')]), (depad_segm, outputnode, [('output_image', 'out_segm')]), (merge_tpms, outputnode, [('out', 'out_tpms')]), ])",
"T2 with K=3, CSF=3, GM=2, WM=1 - ``(3,1,3,2)`` for FLAIR with K=3, CSF=1",
"import engine as pe from nipype.interfaces import utility as niu from nipype.interfaces.ants import",
"newnii.to_filename(out_file) out_files.append(out_file) return out_files def _gen_name(in_file): import os from nipype.utils.filemanip import fname_presuffix return",
"('wm', 1), ]), 'FLAIR': OrderedDict([ ('nclasses', 3), ('csf', 1), ('gm', 3), ('wm', 2),",
"'op1')]), (pad_mask, add_7_2, [('output_image', 'op2')]), (add_7_2, md_7_2, [('output_image', 'op1')]), (md_7_2, me_7_2, [('output_image', 'op1')]),",
"in labels: data = (nii.get_data() == l).astype(np.uint8) newnii = nii.__class__(data, nii.affine, nii.header) newnii.set_data_dtype('uint8')",
"pe.Node(ImageMath(operation='MD', op2='5'), name='21_md_7_2') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} ME ${EXTRACTION_MASK} 5 me_7_2 = pe.Node(ImageMath(operation='ME',",
"components (GM, WM) # ImageMath ${DIMENSION} ${EXTRACTION_WM} GetLargestComponent ${EXTRACTION_WM} get_wm = pe.Node(ImageMath(operation='GetLargestComponent'), name='05_get_wm')",
"add_gm, [('output_image', 'op2')]), (add_gm, relabel_gm, [('output_image', 'first_input'), (('output_image', _gen_name), 'output_product_image')]), (relabel_wm, add_gm_wm, [('output_product_image',",
"atropos = pe.Node(Atropos( dimension=3, initialization='KMeans', number_of_tissue_classes=in_segmentation_model[0], n_iterations=3, convergence_threshold=0.0, mrf_radius=[1, 1, 1], mrf_smoothing_factor=0.1, likelihood_model='Gaussian',",
": int Maximum number of threads an individual process may use mem_gb :",
"and white matter. Format (K, csfLabel, gmLabel, wmLabel). Examples: - ``(3,1,2,3)`` for T1",
"# MultiplyImages ${DIMENSION} ${EXTRACTION_GM} ${EXTRACTION_TMP} ${EXTRACTION_GM} fill_gm = pe.Node(ImageMath(operation='FillHoles', op2='2'), name='07_fill_gm') mult_gm =",
"return out_files def _gen_name(in_file): import os from nipype.utils.filemanip import fname_presuffix return os.path.basename(fname_presuffix(in_file, suffix='processed'))",
"nb.load(in_segm) for l in labels: data = (nii.get_data() == l).astype(np.uint8) newnii = nii.__class__(data,",
"ImageMath ${DIMENSION} ${EXTRACTION_MASK} MD ${EXTRACTION_MASK} 4 md_7 = pe.Node(ImageMath(operation='MD', op2='4'), name='18_md_7') # ImageMath",
"should generate a random seed based on the system's clock omp_nthreads : int",
"# Split segmentation in binary masks sel_labels2 = pe.Node(niu.Function(function=_select_labels, output_names=['out_wm', 'out_gm', 'out_csf']), name='14_sel_labels2')",
"from the template. This produces a segmentation image with :math:`$K$` classes, ordered by",
"[('output_image', 'op2')]), (add_gm, relabel_gm, [('output_image', 'first_input'), (('output_image', _gen_name), 'output_product_image')]), (relabel_wm, add_gm_wm, [('output_product_image', 'op1')]),",
"WM) # ImageMath ${DIMENSION} ${EXTRACTION_WM} GetLargestComponent ${EXTRACTION_WM} get_wm = pe.Node(ImageMath(operation='GetLargestComponent'), name='05_get_wm') get_gm =",
"which classes represent CSF, gray and white matter. Format (K, csfLabel, gmLabel, wmLabel).",
"add_7 = pe.Node(ImageMath(operation='addtozero'), name='15_add_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} ME ${EXTRACTION_MASK} 2 me_7 =",
"sel_labels2.inputs.labels = list(reversed(in_segmentation_model[1:])) # ImageMath ${DIMENSION} ${EXTRACTION_MASK} addtozero ${EXTRACTION_MASK} ${EXTRACTION_TMP} add_7 = pe.Node(ImageMath(operation='addtozero'),",
"# ImageMath ${DIMENSION} ${EXTRACTION_WM} GetLargestComponent ${EXTRACTION_WM} get_wm = pe.Node(ImageMath(operation='GetLargestComponent'), name='05_get_wm') get_gm = pe.Node(ImageMath(operation='GetLargestComponent'),",
"('csf', 3), ('gm', 2), ('wm', 1), ]), 'FLAIR': OrderedDict([ ('nclasses', 3), ('csf', 1),",
"MD ${EXTRACTION_MASK} 5 md_7_2 = pe.Node(ImageMath(operation='MD', op2='5'), name='21_md_7_2') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} ME",
"import Atropos, MultiplyImages from ..interfaces.ants import ImageMath ATROPOS_MODELS = { 'T1': OrderedDict([ ('nclasses',",
"# ${EXTRACTION_MASK_PRIOR_WARPED} add_7_2 = pe.Node(ImageMath(operation='addtozero'), name='20_add_7_2') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} MD ${EXTRACTION_MASK} 5",
"merge_tpms, [('output_image', 'in1')]), (depad_gm, merge_tpms, [('output_image', 'in2')]), (depad_wm, merge_tpms, [('output_image', 'in3')]), (depad_mask, outputnode,",
"name='02_pad_segm') pad_mask = pe.Node(ImageMath(operation='PadImage', op2='%d' % padding), name='03_pad_mask') # Split segmentation in binary",
"random seed based on the system's clock omp_nthreads : int Maximum number of",
"[('classified_image', 'op1')]), (pad_segm, sel_labels, [('output_image', 'in_segm')]), (sel_labels, get_wm, [('out_wm', 'op1')]), (sel_labels, get_gm, [('out_gm',",
"from nipype.utils.filemanip import fname_presuffix out_files = [] cwd = getcwd() nii = nb.load(in_segm)",
"= { 'T1': OrderedDict([ ('nclasses', 3), ('csf', 1), ('gm', 2), ('wm', 3), ]),",
"Format (K, csfLabel, gmLabel, wmLabel). Examples: - ``(3,1,2,3)`` for T1 with K=3, CSF=1,",
"can control :math:`$K$` and tell the script which classes represent CSF, gray and",
"seed based on the system's clock omp_nthreads : int Maximum number of threads",
"fields=['out_mask', 'out_segm', 'out_tpms']), name='outputnode') # Run atropos (core node) atropos = pe.Node(Atropos( dimension=3,",
"initialization='KMeans', number_of_tissue_classes=in_segmentation_model[0], n_iterations=3, convergence_threshold=0.0, mrf_radius=[1, 1, 1], mrf_smoothing_factor=0.1, likelihood_model='Gaussian', use_random_seed=use_random_seed), name='01_atropos', n_procs=omp_nthreads, mem_gb=mem_gb)",
"# ImageMath ${DIMENSION} ${EXTRACTION_MASK} ME ${EXTRACTION_MASK} 5 me_7_2 = pe.Node(ImageMath(operation='ME', op2='5'), name='22_me_7_2') #",
"use mem_gb : float Estimated peak memory consumption of the most hungry nodes",
"'op1')]), (add_gm_wm, depad_segm, [('output_image', 'op1')]), (relabel_wm, depad_wm, [('output_product_image', 'op1')]), (relabel_gm, depad_gm, [('output_product_image', 'op1')]),",
"'op1')]), (relabel_gm, add_gm_wm, [('output_product_image', 'op2')]), (add_gm_wm, sel_labels2, [('output_image', 'in_segm')]), (sel_labels2, add_7, [('out_wm', 'op1'),",
"pad_segm, [('classified_image', 'op1')]), (pad_segm, sel_labels, [('output_image', 'in_segm')]), (sel_labels, get_wm, [('out_wm', 'op1')]), (sel_labels, get_gm,",
"ME ${EXTRACTION_CSF} 10 relabel_wm = pe.Node(MultiplyImages(dimension=3, second_input=in_segmentation_model[-1]), name='09_relabel_wm') me_csf = pe.Node(ImageMath(operation='ME', op2='10'), name='10_me_csf')",
"by mean intensity in increasing order. With this option, you can control :math:`$K$`",
"'out_tpms']), name='outputnode') # Run atropos (core node) atropos = pe.Node(Atropos( dimension=3, initialization='KMeans', number_of_tissue_classes=in_segmentation_model[0],",
"files. in_mask Brain mask calculated previously **Outputs** out_mask Refined brain mask out_segm Output",
"in_mask Brain mask calculated previously **Outputs** out_mask Refined brain mask out_segm Output segmentation",
"5 me_7_2 = pe.Node(ImageMath(operation='ME', op2='5'), name='22_me_7_2') # De-pad depad_mask = pe.Node(ImageMath(operation='PadImage', op2='-%d' %",
"sel_labels.inputs.labels = list(reversed(in_segmentation_model[1:])) # Select largest components (GM, WM) # ImageMath ${DIMENSION} ${EXTRACTION_WM}",
"[('output_product_image', 'op1')]), (relabel_gm, depad_gm, [('output_product_image', 'op1')]), (sel_labels, depad_csf, [('out_csf', 'op1')]), (depad_csf, merge_tpms, [('output_image',",
"of ``antsBrainExtraction.sh``, which refine the mask previously computed with the spatial normalization to",
"a random seed based on the system's clock omp_nthreads : int Maximum number",
"= pe.Node(ImageMath(operation='GetLargestComponent'), name='06_get_gm') # Fill holes and calculate intersection # ImageMath ${DIMENSION} ${EXTRACTION_TMP}",
"fname_presuffix out_files = [] cwd = getcwd() nii = nb.load(in_segm) for l in",
"[('output_product_image', 'op2')]), (add_gm_wm, sel_labels2, [('output_image', 'in_segm')]), (sel_labels2, add_7, [('out_wm', 'op1'), ('out_gm', 'op2')]), (add_7,",
"gmLabel, wmLabel). Examples: - ``(3,1,2,3)`` for T1 with K=3, CSF=1, GM=2, WM=3 (default)",
"pe.Node(niu.Function(function=_select_labels, output_names=['out_wm', 'out_gm', 'out_csf']), name='04_sel_labels') sel_labels.inputs.labels = list(reversed(in_segmentation_model[1:])) # Select largest components (GM,",
"= (nii.get_data() == l).astype(np.uint8) newnii = nii.__class__(data, nii.affine, nii.header) newnii.set_data_dtype('uint8') out_file = fname_presuffix(in_segm,",
"fill_gm, [('output_image', 'op1')]), (get_gm, mult_gm, [('output_image', 'first_input'), (('output_image', _gen_name), 'output_product_image')]), (fill_gm, mult_gm, [('output_image',",
"('nclasses', 3), ('csf', 1), ('gm', 3), ('wm', 2), ]), } def init_atropos_wf(name='atropos_wf', use_random_seed=True,",
"white matter around the edge of the initial brain mask warped from the",
"import getcwd import numpy as np import nibabel as nb from nipype.utils.filemanip import",
"op2='-%d' % padding), name='25_depad_gm') depad_wm = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='26_depad_wm') depad_csf =",
"'op1')]), (pad_segm, sel_labels, [('output_image', 'in_segm')]), (sel_labels, get_wm, [('out_wm', 'op1')]), (sel_labels, get_gm, [('out_gm', 'op1')]),",
"based on the system's clock omp_nthreads : int Maximum number of threads an",
"relabel_gm = pe.Node(MultiplyImages(dimension=3, second_input=in_segmentation_model[-2]), name='12_relabel_gm') add_gm_wm = pe.Node(ImageMath(operation='addtozero'), name='13_add_gm_wm') # Superstep 7 #",
"[('output_product_image', 'op1')]), (me_csf, add_gm, [('output_image', 'op2')]), (add_gm, relabel_gm, [('output_image', 'first_input'), (('output_image', _gen_name), 'output_product_image')]),",
"nipype.interfaces.ants import Atropos, MultiplyImages from ..interfaces.ants import ImageMath ATROPOS_MODELS = { 'T1': OrderedDict([",
"# ImageMath ${DIMENSION} ${EXTRACTION_SEGMENTATION} addtozero ${EXTRACTION_WM} ${EXTRACTION_GM} add_gm = pe.Node(ImageMath(operation='addtozero'), name='11_add_gm') relabel_gm =",
"= pe.Node(ImageMath(operation='MD', op2='4'), name='18_md_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} FillHoles ${EXTRACTION_MASK} 2 fill_7 =",
"[('output_image', 'op1')]), (me_7_2, depad_mask, [('output_image', 'op1')]), (add_gm_wm, depad_segm, [('output_image', 'op1')]), (relabel_wm, depad_wm, [('output_product_image',",
"omp_nthreads : int Maximum number of threads an individual process may use mem_gb",
"from nipype.interfaces import utility as niu from nipype.interfaces.ants import Atropos, MultiplyImages from ..interfaces.ants",
"${DIMENSION} ${EXTRACTION_TMP} ME ${EXTRACTION_CSF} 10 relabel_wm = pe.Node(MultiplyImages(dimension=3, second_input=in_segmentation_model[-1]), name='09_relabel_wm') me_csf = pe.Node(ImageMath(operation='ME',",
"supersteps 6 and 7 of ``antsBrainExtraction.sh``, which refine the mask previously computed with",
"${DIMENSION} ${EXTRACTION_GM} ${ATROPOS_GM_CLASS_LABEL} ${EXTRACTION_GM} # ImageMath ${DIMENSION} ${EXTRACTION_SEGMENTATION} addtozero ${EXTRACTION_WM} ${EXTRACTION_GM} add_gm =",
"normalization to the template. **Parameters** use_random_seed : bool Whether ATROPOS should generate a",
"int Pad images with zeros before processing in_segmentation_model : tuple A k-means segmentation",
"${DIMENSION} ${EXTRACTION_MASK} ME ${EXTRACTION_MASK} 5 me_7_2 = pe.Node(ImageMath(operation='ME', op2='5'), name='22_me_7_2') # De-pad depad_mask",
"]), 'T2': OrderedDict([ ('nclasses', 3), ('csf', 3), ('gm', 2), ('wm', 1), ]), 'FLAIR':",
"${EXTRACTION_TMP} ME ${EXTRACTION_CSF} 10 relabel_wm = pe.Node(MultiplyImages(dimension=3, second_input=in_segmentation_model[-1]), name='09_relabel_wm') me_csf = pe.Node(ImageMath(operation='ME', op2='10'),",
"[('output_image', 'in1')]), (depad_gm, merge_tpms, [('output_image', 'in2')]), (depad_wm, merge_tpms, [('output_image', 'in3')]), (depad_mask, outputnode, [('output_image',",
"'op1')]), (inputnode, atropos, [('in_files', 'intensity_images'), ('in_mask', 'mask_image')]), (atropos, pad_segm, [('classified_image', 'op1')]), (pad_segm, sel_labels,",
"[('output_image', 'op1')]), (fill_7, add_7_2, [('output_image', 'op1')]), (pad_mask, add_7_2, [('output_image', 'op2')]), (add_7_2, md_7_2, [('output_image',",
"'output_product_image')]), (relabel_wm, add_gm_wm, [('output_product_image', 'op1')]), (relabel_gm, add_gm_wm, [('output_product_image', 'op2')]), (add_gm_wm, sel_labels2, [('output_image', 'in_segm')]),",
"op2='2'), name='19_fill_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} addtozero ${EXTRACTION_MASK} \\ # ${EXTRACTION_MASK_PRIOR_WARPED} add_7_2 =",
"system's clock omp_nthreads : int Maximum number of threads an individual process may",
"add_gm_wm, [('output_product_image', 'op2')]), (add_gm_wm, sel_labels2, [('output_image', 'in_segm')]), (sel_labels2, add_7, [('out_wm', 'op1'), ('out_gm', 'op2')]),",
"gray and white matter. Format (K, csfLabel, gmLabel, wmLabel). Examples: - ``(3,1,2,3)`` for",
"depad_csf, [('out_csf', 'op1')]), (depad_csf, merge_tpms, [('output_image', 'in1')]), (depad_gm, merge_tpms, [('output_image', 'in2')]), (depad_wm, merge_tpms,",
"= pe.Node(niu.Function(function=_select_labels, output_names=['out_wm', 'out_gm', 'out_csf']), name='14_sel_labels2') sel_labels2.inputs.labels = list(reversed(in_segmentation_model[1:])) # ImageMath ${DIMENSION} ${EXTRACTION_MASK}",
"\"\"\" wf = pe.Workflow(name) inputnode = pe.Node(niu.IdentityInterface(fields=['in_files', 'in_mask']), name='inputnode') outputnode = pe.Node(niu.IdentityInterface( fields=['out_mask',",
"pe.Node(ImageMath(operation='FillHoles', op2='2'), name='19_fill_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} addtozero ${EXTRACTION_MASK} \\ # ${EXTRACTION_MASK_PRIOR_WARPED} add_7_2",
"(K, csfLabel, gmLabel, wmLabel). Examples: - ``(3,1,2,3)`` for T1 with K=3, CSF=1, GM=2,",
"pe.Node(ImageMath(operation='FillHoles', op2='2'), name='07_fill_gm') mult_gm = pe.Node(MultiplyImages(dimension=3), name='08_mult_gm') # MultiplyImages ${DIMENSION} ${EXTRACTION_WM} ${ATROPOS_WM_CLASS_LABEL} ${EXTRACTION_WM}",
"# ImageMath ${DIMENSION} ${EXTRACTION_MASK} MD ${EXTRACTION_MASK} 5 md_7_2 = pe.Node(ImageMath(operation='MD', op2='5'), name='21_md_7_2') #",
"'op1')]), (relabel_wm, depad_wm, [('output_product_image', 'op1')]), (relabel_gm, depad_gm, [('output_product_image', 'op1')]), (sel_labels, depad_csf, [('out_csf', 'op1')]),",
"name='11_add_gm') relabel_gm = pe.Node(MultiplyImages(dimension=3, second_input=in_segmentation_model[-2]), name='12_relabel_gm') add_gm_wm = pe.Node(ImageMath(operation='addtozero'), name='13_add_gm_wm') # Superstep 7",
"atropos_wf) **Inputs** in_files :abbr:`INU (intensity non-uniformity)`-corrected files. in_mask Brain mask calculated previously **Outputs**",
"CSF=3, GM=2, WM=1 - ``(3,1,3,2)`` for FLAIR with K=3, CSF=1 GM=3, WM=2 -",
"MultiplyImages from ..interfaces.ants import ImageMath ATROPOS_MODELS = { 'T1': OrderedDict([ ('nclasses', 3), ('csf',",
"nibabel as nb from nipype.utils.filemanip import fname_presuffix out_files = [] cwd = getcwd()",
"option, you can control :math:`$K$` and tell the script which classes represent CSF,",
"MD ${EXTRACTION_MASK} 4 md_7 = pe.Node(ImageMath(operation='MD', op2='4'), name='18_md_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} FillHoles",
"${DIMENSION} ${EXTRACTION_MASK} FillHoles ${EXTRACTION_MASK} 2 fill_7 = pe.Node(ImageMath(operation='FillHoles', op2='2'), name='19_fill_7') # ImageMath ${DIMENSION}",
"K=3, CSF=3, GM=2, WM=1 - ``(3,1,3,2)`` for FLAIR with K=3, CSF=1 GM=3, WM=2",
"pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='24_depad_segm') depad_gm = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='25_depad_gm') depad_wm",
"(me_csf, add_gm, [('output_image', 'op2')]), (add_gm, relabel_gm, [('output_image', 'first_input'), (('output_image', _gen_name), 'output_product_image')]), (relabel_wm, add_gm_wm,",
"add_7_2, [('output_image', 'op2')]), (add_7_2, md_7_2, [('output_image', 'op1')]), (md_7_2, me_7_2, [('output_image', 'op1')]), (me_7_2, depad_mask,",
"nii = nb.load(in_segm) for l in labels: data = (nii.get_data() == l).astype(np.uint8) newnii",
"ImageMath ${DIMENSION} ${EXTRACTION_TMP} ME ${EXTRACTION_CSF} 10 relabel_wm = pe.Node(MultiplyImages(dimension=3, second_input=in_segmentation_model[-1]), name='09_relabel_wm') me_csf =",
"[('output_image', 'op1')]), (pad_mask, add_7_2, [('output_image', 'op2')]), (add_7_2, md_7_2, [('output_image', 'op1')]), (md_7_2, me_7_2, [('output_image',",
"previously computed with the spatial normalization to the template. **Parameters** use_random_seed : bool",
"name='10_me_csf') # ImageMath ${DIMENSION} ${EXTRACTION_GM} addtozero ${EXTRACTION_GM} ${EXTRACTION_TMP} # MultiplyImages ${DIMENSION} ${EXTRACTION_GM} ${ATROPOS_GM_CLASS_LABEL}",
"- ``(3,1,3,2)`` for FLAIR with K=3, CSF=1 GM=3, WM=2 - ``(4,4,2,3)`` uses K=4,",
"name='04_sel_labels') sel_labels.inputs.labels = list(reversed(in_segmentation_model[1:])) # Select largest components (GM, WM) # ImageMath ${DIMENSION}",
"increasing order. With this option, you can control :math:`$K$` and tell the script",
"= pe.Node(ImageMath(operation='PadImage', op2='%d' % padding), name='03_pad_mask') # Split segmentation in binary masks sel_labels",
"outputnode = pe.Node(niu.IdentityInterface( fields=['out_mask', 'out_segm', 'out_tpms']), name='outputnode') # Run atropos (core node) atropos",
"${EXTRACTION_GM} ${EXTRACTION_TMP} # MultiplyImages ${DIMENSION} ${EXTRACTION_GM} ${ATROPOS_GM_CLASS_LABEL} ${EXTRACTION_GM} # ImageMath ${DIMENSION} ${EXTRACTION_SEGMENTATION} addtozero",
"threads an individual process may use mem_gb : float Estimated peak memory consumption",
"Atropos, MultiplyImages from ..interfaces.ants import ImageMath ATROPOS_MODELS = { 'T1': OrderedDict([ ('nclasses', 3),",
"white matter. Format (K, csfLabel, gmLabel, wmLabel). Examples: - ``(3,1,2,3)`` for T1 with",
"7 # Split segmentation in binary masks sel_labels2 = pe.Node(niu.Function(function=_select_labels, output_names=['out_wm', 'out_gm', 'out_csf']),",
"segmentation out_tpms Output :abbr:`TPMs (tissue probability maps)` \"\"\" wf = pe.Workflow(name) inputnode =",
"name='08_mult_gm') # MultiplyImages ${DIMENSION} ${EXTRACTION_WM} ${ATROPOS_WM_CLASS_LABEL} ${EXTRACTION_WM} # ImageMath ${DIMENSION} ${EXTRACTION_TMP} ME ${EXTRACTION_CSF}",
"'op2')]), (add_7_2, md_7_2, [('output_image', 'op1')]), (md_7_2, me_7_2, [('output_image', 'op1')]), (me_7_2, depad_mask, [('output_image', 'op1')]),",
"This produces a segmentation image with :math:`$K$` classes, ordered by mean intensity in",
"before processing in_segmentation_model : tuple A k-means segmentation is run to find gray",
"Run atropos (core node) atropos = pe.Node(Atropos( dimension=3, initialization='KMeans', number_of_tissue_classes=in_segmentation_model[0], n_iterations=3, convergence_threshold=0.0, mrf_radius=[1,",
"nii.header) newnii.set_data_dtype('uint8') out_file = fname_presuffix(in_segm, suffix='class-%02d' % l, newpath=cwd) newnii.to_filename(out_file) out_files.append(out_file) return out_files",
"- ``(3,3,2,1)`` for T2 with K=3, CSF=3, GM=2, WM=1 - ``(3,1,3,2)`` for FLAIR",
"relabel_wm = pe.Node(MultiplyImages(dimension=3, second_input=in_segmentation_model[-1]), name='09_relabel_wm') me_csf = pe.Node(ImageMath(operation='ME', op2='10'), name='10_me_csf') # ImageMath ${DIMENSION}",
"${ATROPOS_GM_CLASS_LABEL} ${EXTRACTION_GM} # ImageMath ${DIMENSION} ${EXTRACTION_SEGMENTATION} addtozero ${EXTRACTION_WM} ${EXTRACTION_GM} add_gm = pe.Node(ImageMath(operation='addtozero'), name='11_add_gm')",
"as niu from nipype.interfaces.ants import Atropos, MultiplyImages from ..interfaces.ants import ImageMath ATROPOS_MODELS =",
"[('output_image', 'in2')]), (depad_wm, merge_tpms, [('output_image', 'in3')]), (depad_mask, outputnode, [('output_image', 'out_mask')]), (depad_segm, outputnode, [('output_image',",
"% padding), name='26_depad_wm') depad_csf = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='27_depad_csf') merge_tpms = pe.Node(niu.Merge(in_segmentation_model[0]),",
"out_files = [] cwd = getcwd() nii = nb.load(in_segm) for l in labels:",
"out_files.append(out_file) return out_files def _gen_name(in_file): import os from nipype.utils.filemanip import fname_presuffix return os.path.basename(fname_presuffix(in_file,",
"= pe.Node(ImageMath(operation='FillHoles', op2='2'), name='07_fill_gm') mult_gm = pe.Node(MultiplyImages(dimension=3), name='08_mult_gm') # MultiplyImages ${DIMENSION} ${EXTRACTION_WM} ${ATROPOS_WM_CLASS_LABEL}",
"int Maximum number of threads an individual process may use mem_gb : float",
"(sel_labels, get_gm, [('out_gm', 'op1')]), (get_gm, fill_gm, [('output_image', 'op1')]), (get_gm, mult_gm, [('output_image', 'first_input'), (('output_image',",
"(me_7_2, depad_mask, [('output_image', 'op1')]), (add_gm_wm, depad_segm, [('output_image', 'op1')]), (relabel_wm, depad_wm, [('output_product_image', 'op1')]), (relabel_gm,",
"name='01_atropos', n_procs=omp_nthreads, mem_gb=mem_gb) # massage outputs pad_segm = pe.Node(ImageMath(operation='PadImage', op2='%d' % padding), name='02_pad_segm')",
"engine as pe from nipype.interfaces import utility as niu from nipype.interfaces.ants import Atropos,",
"with :math:`$K$` classes, ordered by mean intensity in increasing order. With this option,",
"pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='26_depad_wm') depad_csf = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='27_depad_csf') merge_tpms",
"getcwd import numpy as np import nibabel as nb from nipype.utils.filemanip import fname_presuffix",
"${ATROPOS_WM_CLASS_LABEL} ${EXTRACTION_WM} # ImageMath ${DIMENSION} ${EXTRACTION_TMP} ME ${EXTRACTION_CSF} 10 relabel_wm = pe.Node(MultiplyImages(dimension=3, second_input=in_segmentation_model[-1]),",
"atropos (core node) atropos = pe.Node(Atropos( dimension=3, initialization='KMeans', number_of_tissue_classes=in_segmentation_model[0], n_iterations=3, convergence_threshold=0.0, mrf_radius=[1, 1,",
"comp_7, [('output_image', 'op1')]), (comp_7, md_7, [('output_image', 'op1')]), (md_7, fill_7, [('output_image', 'op1')]), (fill_7, add_7_2,",
"'op1')]), (comp_7, md_7, [('output_image', 'op1')]), (md_7, fill_7, [('output_image', 'op1')]), (fill_7, add_7_2, [('output_image', 'op1')]),",
"(inputnode, pad_mask, [('in_mask', 'op1')]), (inputnode, atropos, [('in_files', 'intensity_images'), ('in_mask', 'mask_image')]), (atropos, pad_segm, [('classified_image',",
"for FLAIR with K=3, CSF=1 GM=3, WM=2 - ``(4,4,2,3)`` uses K=4, CSF=4, GM=2,",
"numpy as np import nibabel as nb from nipype.utils.filemanip import fname_presuffix out_files =",
"'in_mask']), name='inputnode') outputnode = pe.Node(niu.IdentityInterface( fields=['out_mask', 'out_segm', 'out_tpms']), name='outputnode') # Run atropos (core",
"add_gm = pe.Node(ImageMath(operation='addtozero'), name='11_add_gm') relabel_gm = pe.Node(MultiplyImages(dimension=3, second_input=in_segmentation_model[-2]), name='12_relabel_gm') add_gm_wm = pe.Node(ImageMath(operation='addtozero'), name='13_add_gm_wm')",
"'second_input')]), (get_wm, relabel_wm, [('output_image', 'first_input'), (('output_image', _gen_name), 'output_product_image')]), (sel_labels, me_csf, [('out_csf', 'op1')]), (mult_gm,",
"'in_segm')]), (sel_labels2, add_7, [('out_wm', 'op1'), ('out_gm', 'op2')]), (add_7, me_7, [('output_image', 'op1')]), (me_7, comp_7,",
"${EXTRACTION_MASK} 4 md_7 = pe.Node(ImageMath(operation='MD', op2='4'), name='18_md_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} FillHoles ${EXTRACTION_MASK}",
"largest components (GM, WM) # ImageMath ${DIMENSION} ${EXTRACTION_WM} GetLargestComponent ${EXTRACTION_WM} get_wm = pe.Node(ImageMath(operation='GetLargestComponent'),",
"nipype.pipeline import engine as pe from nipype.interfaces import utility as niu from nipype.interfaces.ants",
"op2='2'), name='07_fill_gm') mult_gm = pe.Node(MultiplyImages(dimension=3), name='08_mult_gm') # MultiplyImages ${DIMENSION} ${EXTRACTION_WM} ${ATROPOS_WM_CLASS_LABEL} ${EXTRACTION_WM} #",
"[('output_image', 'op2')]), (add_7_2, md_7_2, [('output_image', 'op1')]), (md_7_2, me_7_2, [('output_image', 'op1')]), (me_7_2, depad_mask, [('output_image',",
"processing in_segmentation_model : tuple A k-means segmentation is run to find gray or",
"omp_nthreads=None, mem_gb=3.0, padding=10, in_segmentation_model=list(ATROPOS_MODELS['T1'].values())): \"\"\" Implements supersteps 6 and 7 of ``antsBrainExtraction.sh``, which",
"2 fill_7 = pe.Node(ImageMath(operation='FillHoles', op2='2'), name='19_fill_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} addtozero ${EXTRACTION_MASK} \\",
"mrf_smoothing_factor=0.1, likelihood_model='Gaussian', use_random_seed=use_random_seed), name='01_atropos', n_procs=omp_nthreads, mem_gb=mem_gb) # massage outputs pad_segm = pe.Node(ImageMath(operation='PadImage', op2='%d'",
"FillHoles ${EXTRACTION_GM} 2 # MultiplyImages ${DIMENSION} ${EXTRACTION_GM} ${EXTRACTION_TMP} ${EXTRACTION_GM} fill_gm = pe.Node(ImageMath(operation='FillHoles', op2='2'),",
"addtozero ${EXTRACTION_MASK} ${EXTRACTION_TMP} add_7 = pe.Node(ImageMath(operation='addtozero'), name='15_add_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} ME ${EXTRACTION_MASK}",
"pe.Node(niu.Function(function=_select_labels, output_names=['out_wm', 'out_gm', 'out_csf']), name='14_sel_labels2') sel_labels2.inputs.labels = list(reversed(in_segmentation_model[1:])) # ImageMath ${DIMENSION} ${EXTRACTION_MASK} addtozero",
"(comp_7, md_7, [('output_image', 'op1')]), (md_7, fill_7, [('output_image', 'op1')]), (fill_7, add_7_2, [('output_image', 'op1')]), (pad_mask,",
"add_7, [('out_wm', 'op1'), ('out_gm', 'op2')]), (add_7, me_7, [('output_image', 'op1')]), (me_7, comp_7, [('output_image', 'op1')]),",
"(add_gm_wm, depad_segm, [('output_image', 'op1')]), (relabel_wm, depad_wm, [('output_product_image', 'op1')]), (relabel_gm, depad_gm, [('output_product_image', 'op1')]), (sel_labels,",
"pe.Node(ImageMath(operation='PadImage', op2='%d' % padding), name='03_pad_mask') # Split segmentation in binary masks sel_labels =",
"get_wm = pe.Node(ImageMath(operation='GetLargestComponent'), name='05_get_wm') get_gm = pe.Node(ImageMath(operation='GetLargestComponent'), name='06_get_gm') # Fill holes and calculate",
"[('out', 'out_tpms')]), ]) return wf def _select_labels(in_segm, labels): from os import getcwd import",
"ImageMath ${DIMENSION} ${EXTRACTION_MASK} addtozero ${EXTRACTION_MASK} \\ # ${EXTRACTION_MASK_PRIOR_WARPED} add_7_2 = pe.Node(ImageMath(operation='addtozero'), name='20_add_7_2') #",
"ImageMath ${DIMENSION} ${EXTRACTION_TMP} FillHoles ${EXTRACTION_GM} 2 # MultiplyImages ${DIMENSION} ${EXTRACTION_GM} ${EXTRACTION_TMP} ${EXTRACTION_GM} fill_gm",
"name='24_depad_segm') depad_gm = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='25_depad_gm') depad_wm = pe.Node(ImageMath(operation='PadImage', op2='-%d' %",
"initial brain mask warped from the template. This produces a segmentation image with",
"name='23_depad_mask') depad_segm = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='24_depad_segm') depad_gm = pe.Node(ImageMath(operation='PadImage', op2='-%d' %",
"% padding), name='25_depad_gm') depad_wm = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='26_depad_wm') depad_csf = pe.Node(ImageMath(operation='PadImage',",
"_gen_name), 'output_product_image')]), (fill_gm, mult_gm, [('output_image', 'second_input')]), (get_wm, relabel_wm, [('output_image', 'first_input'), (('output_image', _gen_name), 'output_product_image')]),",
"ImageMath ${DIMENSION} ${EXTRACTION_MASK} addtozero ${EXTRACTION_MASK} ${EXTRACTION_TMP} add_7 = pe.Node(ImageMath(operation='addtozero'), name='15_add_7') # ImageMath ${DIMENSION}",
"padding), name='02_pad_segm') pad_mask = pe.Node(ImageMath(operation='PadImage', op2='%d' % padding), name='03_pad_mask') # Split segmentation in",
"${EXTRACTION_TMP} ${EXTRACTION_GM} fill_gm = pe.Node(ImageMath(operation='FillHoles', op2='2'), name='07_fill_gm') mult_gm = pe.Node(MultiplyImages(dimension=3), name='08_mult_gm') # MultiplyImages",
"node) atropos = pe.Node(Atropos( dimension=3, initialization='KMeans', number_of_tissue_classes=in_segmentation_model[0], n_iterations=3, convergence_threshold=0.0, mrf_radius=[1, 1, 1], mrf_smoothing_factor=0.1,",
"Fill holes and calculate intersection # ImageMath ${DIMENSION} ${EXTRACTION_TMP} FillHoles ${EXTRACTION_GM} 2 #",
"nii.affine, nii.header) newnii.set_data_dtype('uint8') out_file = fname_presuffix(in_segm, suffix='class-%02d' % l, newpath=cwd) newnii.to_filename(out_file) out_files.append(out_file) return",
"add_7_2, [('output_image', 'op1')]), (pad_mask, add_7_2, [('output_image', 'op2')]), (add_7_2, md_7_2, [('output_image', 'op1')]), (md_7_2, me_7_2,",
"${EXTRACTION_TMP} add_7 = pe.Node(ImageMath(operation='addtozero'), name='15_add_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} ME ${EXTRACTION_MASK} 2 me_7",
"ME ${EXTRACTION_MASK} 5 me_7_2 = pe.Node(ImageMath(operation='ME', op2='5'), name='22_me_7_2') # De-pad depad_mask = pe.Node(ImageMath(operation='PadImage',",
"Whether ATROPOS should generate a random seed based on the system's clock omp_nthreads",
"name='16_me_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} GetLargestComponent ${EXTRACTION_MASK} comp_7 = pe.Node(ImageMath(operation='GetLargestComponent'), name='17_comp_7') # ImageMath",
"${EXTRACTION_MASK} comp_7 = pe.Node(ImageMath(operation='GetLargestComponent'), name='17_comp_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} MD ${EXTRACTION_MASK} 4 md_7",
"comp_7 = pe.Node(ImageMath(operation='GetLargestComponent'), name='17_comp_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} MD ${EXTRACTION_MASK} 4 md_7 =",
"(sel_labels, get_wm, [('out_wm', 'op1')]), (sel_labels, get_gm, [('out_gm', 'op1')]), (get_gm, fill_gm, [('output_image', 'op1')]), (get_gm,",
"\"\"\" Implements supersteps 6 and 7 of ``antsBrainExtraction.sh``, which refine the mask previously",
"import OrderedDict from nipype.pipeline import engine as pe from nipype.interfaces import utility as",
"the mask previously computed with the spatial normalization to the template. **Parameters** use_random_seed",
"# ImageMath ${DIMENSION} ${EXTRACTION_MASK} ME ${EXTRACTION_MASK} 2 me_7 = pe.Node(ImageMath(operation='ME', op2='2'), name='16_me_7') #",
"depad_gm = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='25_depad_gm') depad_wm = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding),",
"me_csf, [('out_csf', 'op1')]), (mult_gm, add_gm, [('output_product_image', 'op1')]), (me_csf, add_gm, [('output_image', 'op2')]), (add_gm, relabel_gm,",
"WM=3 name : str, optional Workflow name (default: atropos_wf) **Inputs** in_files :abbr:`INU (intensity",
"'op2')]), (add_7, me_7, [('output_image', 'op1')]), (me_7, comp_7, [('output_image', 'op1')]), (comp_7, md_7, [('output_image', 'op1')]),",
"('nclasses', 3), ('csf', 1), ('gm', 2), ('wm', 3), ]), 'T2': OrderedDict([ ('nclasses', 3),",
"nii.__class__(data, nii.affine, nii.header) newnii.set_data_dtype('uint8') out_file = fname_presuffix(in_segm, suffix='class-%02d' % l, newpath=cwd) newnii.to_filename(out_file) out_files.append(out_file)",
"[('out_csf', 'op1')]), (depad_csf, merge_tpms, [('output_image', 'in1')]), (depad_gm, merge_tpms, [('output_image', 'in2')]), (depad_wm, merge_tpms, [('output_image',",
"template. **Parameters** use_random_seed : bool Whether ATROPOS should generate a random seed based",
"name='22_me_7_2') # De-pad depad_mask = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='23_depad_mask') depad_segm = pe.Node(ImageMath(operation='PadImage',",
"${EXTRACTION_GM} 2 # MultiplyImages ${DIMENSION} ${EXTRACTION_GM} ${EXTRACTION_TMP} ${EXTRACTION_GM} fill_gm = pe.Node(ImageMath(operation='FillHoles', op2='2'), name='07_fill_gm')",
": int Pad images with zeros before processing in_segmentation_model : tuple A k-means",
"nipype.interfaces import utility as niu from nipype.interfaces.ants import Atropos, MultiplyImages from ..interfaces.ants import",
"[('output_image', 'out_mask')]), (depad_segm, outputnode, [('output_image', 'out_segm')]), (merge_tpms, outputnode, [('out', 'out_tpms')]), ]) return wf",
"fill_gm = pe.Node(ImageMath(operation='FillHoles', op2='2'), name='07_fill_gm') mult_gm = pe.Node(MultiplyImages(dimension=3), name='08_mult_gm') # MultiplyImages ${DIMENSION} ${EXTRACTION_WM}",
"op2='%d' % padding), name='02_pad_segm') pad_mask = pe.Node(ImageMath(operation='PadImage', op2='%d' % padding), name='03_pad_mask') # Split",
"pe.Node(niu.Merge(in_segmentation_model[0]), name='merge_tpms') wf.connect([ (inputnode, pad_mask, [('in_mask', 'op1')]), (inputnode, atropos, [('in_files', 'intensity_images'), ('in_mask', 'mask_image')]),",
"[('output_image', 'op1')]), (get_gm, mult_gm, [('output_image', 'first_input'), (('output_image', _gen_name), 'output_product_image')]), (fill_gm, mult_gm, [('output_image', 'second_input')]),",
"import nibabel as nb from nipype.utils.filemanip import fname_presuffix out_files = [] cwd =",
"op2='%d' % padding), name='03_pad_mask') # Split segmentation in binary masks sel_labels = pe.Node(niu.Function(function=_select_labels,",
"'output_product_image')]), (sel_labels, me_csf, [('out_csf', 'op1')]), (mult_gm, add_gm, [('output_product_image', 'op1')]), (me_csf, add_gm, [('output_image', 'op2')]),",
"${EXTRACTION_MASK} MD ${EXTRACTION_MASK} 4 md_7 = pe.Node(ImageMath(operation='MD', op2='4'), name='18_md_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK}",
"- ``(3,1,2,3)`` for T1 with K=3, CSF=1, GM=2, WM=3 (default) - ``(3,3,2,1)`` for",
"'op1')]), (sel_labels, get_gm, [('out_gm', 'op1')]), (get_gm, fill_gm, [('output_image', 'op1')]), (get_gm, mult_gm, [('output_image', 'first_input'),",
"which refine the mask previously computed with the spatial normalization to the template.",
"# ImageMath ${DIMENSION} ${EXTRACTION_MASK} addtozero ${EXTRACTION_MASK} \\ # ${EXTRACTION_MASK_PRIOR_WARPED} add_7_2 = pe.Node(ImageMath(operation='addtozero'), name='20_add_7_2')",
"k-means segmentation is run to find gray or white matter around the edge",
"bool Whether ATROPOS should generate a random seed based on the system's clock",
"convergence_threshold=0.0, mrf_radius=[1, 1, 1], mrf_smoothing_factor=0.1, likelihood_model='Gaussian', use_random_seed=use_random_seed), name='01_atropos', n_procs=omp_nthreads, mem_gb=mem_gb) # massage outputs",
"(tissue probability maps)` \"\"\" wf = pe.Workflow(name) inputnode = pe.Node(niu.IdentityInterface(fields=['in_files', 'in_mask']), name='inputnode') outputnode",
"depad_segm = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='24_depad_segm') depad_gm = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding),",
"the most hungry nodes in the workflow padding : int Pad images with",
"sel_labels, [('output_image', 'in_segm')]), (sel_labels, get_wm, [('out_wm', 'op1')]), (sel_labels, get_gm, [('out_gm', 'op1')]), (get_gm, fill_gm,",
"${EXTRACTION_MASK} ME ${EXTRACTION_MASK} 5 me_7_2 = pe.Node(ImageMath(operation='ME', op2='5'), name='22_me_7_2') # De-pad depad_mask =",
"'op1')]), (me_csf, add_gm, [('output_image', 'op2')]), (add_gm, relabel_gm, [('output_image', 'first_input'), (('output_image', _gen_name), 'output_product_image')]), (relabel_wm,",
"${DIMENSION} ${EXTRACTION_MASK} MD ${EXTRACTION_MASK} 5 md_7_2 = pe.Node(ImageMath(operation='MD', op2='5'), name='21_md_7_2') # ImageMath ${DIMENSION}",
"pe.Workflow(name) inputnode = pe.Node(niu.IdentityInterface(fields=['in_files', 'in_mask']), name='inputnode') outputnode = pe.Node(niu.IdentityInterface( fields=['out_mask', 'out_segm', 'out_tpms']), name='outputnode')",
"list(reversed(in_segmentation_model[1:])) # ImageMath ${DIMENSION} ${EXTRACTION_MASK} addtozero ${EXTRACTION_MASK} ${EXTRACTION_TMP} add_7 = pe.Node(ImageMath(operation='addtozero'), name='15_add_7') #",
"get_gm, [('out_gm', 'op1')]), (get_gm, fill_gm, [('output_image', 'op1')]), (get_gm, mult_gm, [('output_image', 'first_input'), (('output_image', _gen_name),",
"pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='25_depad_gm') depad_wm = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='26_depad_wm') depad_csf",
"**Inputs** in_files :abbr:`INU (intensity non-uniformity)`-corrected files. in_mask Brain mask calculated previously **Outputs** out_mask",
"add_gm_wm, [('output_product_image', 'op1')]), (relabel_gm, add_gm_wm, [('output_product_image', 'op2')]), (add_gm_wm, sel_labels2, [('output_image', 'in_segm')]), (sel_labels2, add_7,",
"edge of the initial brain mask warped from the template. This produces a",
"warped from the template. This produces a segmentation image with :math:`$K$` classes, ordered",
"wf.connect([ (inputnode, pad_mask, [('in_mask', 'op1')]), (inputnode, atropos, [('in_files', 'intensity_images'), ('in_mask', 'mask_image')]), (atropos, pad_segm,",
"= pe.Node(ImageMath(operation='FillHoles', op2='2'), name='19_fill_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} addtozero ${EXTRACTION_MASK} \\ # ${EXTRACTION_MASK_PRIOR_WARPED}",
": str, optional Workflow name (default: atropos_wf) **Inputs** in_files :abbr:`INU (intensity non-uniformity)`-corrected files.",
"for l in labels: data = (nii.get_data() == l).astype(np.uint8) newnii = nii.__class__(data, nii.affine,",
"De-pad depad_mask = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='23_depad_mask') depad_segm = pe.Node(ImageMath(operation='PadImage', op2='-%d' %",
"depad_segm, [('output_image', 'op1')]), (relabel_wm, depad_wm, [('output_product_image', 'op1')]), (relabel_gm, depad_gm, [('output_product_image', 'op1')]), (sel_labels, depad_csf,",
"GM=2, WM=3 name : str, optional Workflow name (default: atropos_wf) **Inputs** in_files :abbr:`INU",
"${EXTRACTION_WM} ${ATROPOS_WM_CLASS_LABEL} ${EXTRACTION_WM} # ImageMath ${DIMENSION} ${EXTRACTION_TMP} ME ${EXTRACTION_CSF} 10 relabel_wm = pe.Node(MultiplyImages(dimension=3,",
"OrderedDict([ ('nclasses', 3), ('csf', 1), ('gm', 3), ('wm', 2), ]), } def init_atropos_wf(name='atropos_wf',",
"2), ('wm', 3), ]), 'T2': OrderedDict([ ('nclasses', 3), ('csf', 3), ('gm', 2), ('wm',",
"CSF=4, GM=2, WM=3 name : str, optional Workflow name (default: atropos_wf) **Inputs** in_files",
"with zeros before processing in_segmentation_model : tuple A k-means segmentation is run to",
"[('output_image', 'in3')]), (depad_mask, outputnode, [('output_image', 'out_mask')]), (depad_segm, outputnode, [('output_image', 'out_segm')]), (merge_tpms, outputnode, [('out',",
"pe.Node(ImageMath(operation='addtozero'), name='20_add_7_2') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} MD ${EXTRACTION_MASK} 5 md_7_2 = pe.Node(ImageMath(operation='MD', op2='5'),",
"'op1')]), (relabel_gm, depad_gm, [('output_product_image', 'op1')]), (sel_labels, depad_csf, [('out_csf', 'op1')]), (depad_csf, merge_tpms, [('output_image', 'in1')]),",
"name='17_comp_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} MD ${EXTRACTION_MASK} 4 md_7 = pe.Node(ImageMath(operation='MD', op2='4'), name='18_md_7')",
"depad_mask = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='23_depad_mask') depad_segm = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding),",
"GetLargestComponent ${EXTRACTION_MASK} comp_7 = pe.Node(ImageMath(operation='GetLargestComponent'), name='17_comp_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} MD ${EXTRACTION_MASK} 4",
"represent CSF, gray and white matter. Format (K, csfLabel, gmLabel, wmLabel). Examples: -",
"mean intensity in increasing order. With this option, you can control :math:`$K$` and",
"pad_mask, [('in_mask', 'op1')]), (inputnode, atropos, [('in_files', 'intensity_images'), ('in_mask', 'mask_image')]), (atropos, pad_segm, [('classified_image', 'op1')]),",
"1), ('gm', 2), ('wm', 3), ]), 'T2': OrderedDict([ ('nclasses', 3), ('csf', 3), ('gm',",
"pe.Node(ImageMath(operation='addtozero'), name='11_add_gm') relabel_gm = pe.Node(MultiplyImages(dimension=3, second_input=in_segmentation_model[-2]), name='12_relabel_gm') add_gm_wm = pe.Node(ImageMath(operation='addtozero'), name='13_add_gm_wm') # Superstep",
"10 relabel_wm = pe.Node(MultiplyImages(dimension=3, second_input=in_segmentation_model[-1]), name='09_relabel_wm') me_csf = pe.Node(ImageMath(operation='ME', op2='10'), name='10_me_csf') # ImageMath",
"segmentation in binary masks sel_labels2 = pe.Node(niu.Function(function=_select_labels, output_names=['out_wm', 'out_gm', 'out_csf']), name='14_sel_labels2') sel_labels2.inputs.labels =",
"(pad_segm, sel_labels, [('output_image', 'in_segm')]), (sel_labels, get_wm, [('out_wm', 'op1')]), (sel_labels, get_gm, [('out_gm', 'op1')]), (get_gm,",
"pe.Node(ImageMath(operation='addtozero'), name='15_add_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} ME ${EXTRACTION_MASK} 2 me_7 = pe.Node(ImageMath(operation='ME', op2='2'),",
"K=4, CSF=4, GM=2, WM=3 name : str, optional Workflow name (default: atropos_wf) **Inputs**",
"Implements supersteps 6 and 7 of ``antsBrainExtraction.sh``, which refine the mask previously computed",
"wmLabel). Examples: - ``(3,1,2,3)`` for T1 with K=3, CSF=1, GM=2, WM=3 (default) -",
"pe.Node(ImageMath(operation='PadImage', op2='%d' % padding), name='02_pad_segm') pad_mask = pe.Node(ImageMath(operation='PadImage', op2='%d' % padding), name='03_pad_mask') #",
"3), ('wm', 2), ]), } def init_atropos_wf(name='atropos_wf', use_random_seed=True, omp_nthreads=None, mem_gb=3.0, padding=10, in_segmentation_model=list(ATROPOS_MODELS['T1'].values())): \"\"\"",
"3), ('csf', 3), ('gm', 2), ('wm', 1), ]), 'FLAIR': OrderedDict([ ('nclasses', 3), ('csf',",
"'first_input'), (('output_image', _gen_name), 'output_product_image')]), (relabel_wm, add_gm_wm, [('output_product_image', 'op1')]), (relabel_gm, add_gm_wm, [('output_product_image', 'op2')]), (add_gm_wm,",
"= pe.Node(ImageMath(operation='ME', op2='10'), name='10_me_csf') # ImageMath ${DIMENSION} ${EXTRACTION_GM} addtozero ${EXTRACTION_GM} ${EXTRACTION_TMP} # MultiplyImages",
"[('output_product_image', 'op1')]), (relabel_gm, add_gm_wm, [('output_product_image', 'op2')]), (add_gm_wm, sel_labels2, [('output_image', 'in_segm')]), (sel_labels2, add_7, [('out_wm',",
"${EXTRACTION_MASK} 2 fill_7 = pe.Node(ImageMath(operation='FillHoles', op2='2'), name='19_fill_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} addtozero ${EXTRACTION_MASK}",
"op2='5'), name='22_me_7_2') # De-pad depad_mask = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='23_depad_mask') depad_segm =",
"('wm', 3), ]), 'T2': OrderedDict([ ('nclasses', 3), ('csf', 3), ('gm', 2), ('wm', 1),",
"('wm', 2), ]), } def init_atropos_wf(name='atropos_wf', use_random_seed=True, omp_nthreads=None, mem_gb=3.0, padding=10, in_segmentation_model=list(ATROPOS_MODELS['T1'].values())): \"\"\" Implements",
"_select_labels(in_segm, labels): from os import getcwd import numpy as np import nibabel as",
"# MultiplyImages ${DIMENSION} ${EXTRACTION_WM} ${ATROPOS_WM_CLASS_LABEL} ${EXTRACTION_WM} # ImageMath ${DIMENSION} ${EXTRACTION_TMP} ME ${EXTRACTION_CSF} 10",
"nb from nipype.utils.filemanip import fname_presuffix out_files = [] cwd = getcwd() nii =",
": float Estimated peak memory consumption of the most hungry nodes in the",
"pe.Node(ImageMath(operation='ME', op2='5'), name='22_me_7_2') # De-pad depad_mask = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='23_depad_mask') depad_segm",
"'op1')]), (me_7_2, depad_mask, [('output_image', 'op1')]), (add_gm_wm, depad_segm, [('output_image', 'op1')]), (relabel_wm, depad_wm, [('output_product_image', 'op1')]),",
"'output_product_image')]), (fill_gm, mult_gm, [('output_image', 'second_input')]), (get_wm, relabel_wm, [('output_image', 'first_input'), (('output_image', _gen_name), 'output_product_image')]), (sel_labels,",
"MultiplyImages ${DIMENSION} ${EXTRACTION_GM} ${EXTRACTION_TMP} ${EXTRACTION_GM} fill_gm = pe.Node(ImageMath(operation='FillHoles', op2='2'), name='07_fill_gm') mult_gm = pe.Node(MultiplyImages(dimension=3),",
"name='09_relabel_wm') me_csf = pe.Node(ImageMath(operation='ME', op2='10'), name='10_me_csf') # ImageMath ${DIMENSION} ${EXTRACTION_GM} addtozero ${EXTRACTION_GM} ${EXTRACTION_TMP}",
"op2='-%d' % padding), name='26_depad_wm') depad_csf = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='27_depad_csf') merge_tpms =",
"Refined brain mask out_segm Output segmentation out_tpms Output :abbr:`TPMs (tissue probability maps)` \"\"\"",
"= pe.Workflow(name) inputnode = pe.Node(niu.IdentityInterface(fields=['in_files', 'in_mask']), name='inputnode') outputnode = pe.Node(niu.IdentityInterface( fields=['out_mask', 'out_segm', 'out_tpms']),",
"template. This produces a segmentation image with :math:`$K$` classes, ordered by mean intensity",
"= fname_presuffix(in_segm, suffix='class-%02d' % l, newpath=cwd) newnii.to_filename(out_file) out_files.append(out_file) return out_files def _gen_name(in_file): import",
"previously **Outputs** out_mask Refined brain mask out_segm Output segmentation out_tpms Output :abbr:`TPMs (tissue",
"name='06_get_gm') # Fill holes and calculate intersection # ImageMath ${DIMENSION} ${EXTRACTION_TMP} FillHoles ${EXTRACTION_GM}",
"the system's clock omp_nthreads : int Maximum number of threads an individual process",
"Examples: - ``(3,1,2,3)`` for T1 with K=3, CSF=1, GM=2, WM=3 (default) - ``(3,3,2,1)``",
"op2='10'), name='10_me_csf') # ImageMath ${DIMENSION} ${EXTRACTION_GM} addtozero ${EXTRACTION_GM} ${EXTRACTION_TMP} # MultiplyImages ${DIMENSION} ${EXTRACTION_GM}",
"second_input=in_segmentation_model[-2]), name='12_relabel_gm') add_gm_wm = pe.Node(ImageMath(operation='addtozero'), name='13_add_gm_wm') # Superstep 7 # Split segmentation in",
"${EXTRACTION_WM} get_wm = pe.Node(ImageMath(operation='GetLargestComponent'), name='05_get_wm') get_gm = pe.Node(ImageMath(operation='GetLargestComponent'), name='06_get_gm') # Fill holes and",
"3), ('csf', 1), ('gm', 3), ('wm', 2), ]), } def init_atropos_wf(name='atropos_wf', use_random_seed=True, omp_nthreads=None,",
"image with :math:`$K$` classes, ordered by mean intensity in increasing order. With this",
"${EXTRACTION_GM} # ImageMath ${DIMENSION} ${EXTRACTION_SEGMENTATION} addtozero ${EXTRACTION_WM} ${EXTRACTION_GM} add_gm = pe.Node(ImageMath(operation='addtozero'), name='11_add_gm') relabel_gm",
"} def init_atropos_wf(name='atropos_wf', use_random_seed=True, omp_nthreads=None, mem_gb=3.0, padding=10, in_segmentation_model=list(ATROPOS_MODELS['T1'].values())): \"\"\" Implements supersteps 6 and",
"= pe.Node(MultiplyImages(dimension=3, second_input=in_segmentation_model[-1]), name='09_relabel_wm') me_csf = pe.Node(ImageMath(operation='ME', op2='10'), name='10_me_csf') # ImageMath ${DIMENSION} ${EXTRACTION_GM}",
"${EXTRACTION_MASK} MD ${EXTRACTION_MASK} 5 md_7_2 = pe.Node(ImageMath(operation='MD', op2='5'), name='21_md_7_2') # ImageMath ${DIMENSION} ${EXTRACTION_MASK}",
"op2='5'), name='21_md_7_2') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} ME ${EXTRACTION_MASK} 5 me_7_2 = pe.Node(ImageMath(operation='ME', op2='5'),",
"(md_7_2, me_7_2, [('output_image', 'op1')]), (me_7_2, depad_mask, [('output_image', 'op1')]), (add_gm_wm, depad_segm, [('output_image', 'op1')]), (relabel_wm,",
"return wf def _select_labels(in_segm, labels): from os import getcwd import numpy as np",
"mult_gm, [('output_image', 'second_input')]), (get_wm, relabel_wm, [('output_image', 'first_input'), (('output_image', _gen_name), 'output_product_image')]), (sel_labels, me_csf, [('out_csf',",
"calculated previously **Outputs** out_mask Refined brain mask out_segm Output segmentation out_tpms Output :abbr:`TPMs",
"mult_gm, [('output_image', 'first_input'), (('output_image', _gen_name), 'output_product_image')]), (fill_gm, mult_gm, [('output_image', 'second_input')]), (get_wm, relabel_wm, [('output_image',",
"${EXTRACTION_SEGMENTATION} addtozero ${EXTRACTION_WM} ${EXTRACTION_GM} add_gm = pe.Node(ImageMath(operation='addtozero'), name='11_add_gm') relabel_gm = pe.Node(MultiplyImages(dimension=3, second_input=in_segmentation_model[-2]), name='12_relabel_gm')",
"l in labels: data = (nii.get_data() == l).astype(np.uint8) newnii = nii.__class__(data, nii.affine, nii.header)",
"= pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='23_depad_mask') depad_segm = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='24_depad_segm')",
"'op2')]), (add_gm, relabel_gm, [('output_image', 'first_input'), (('output_image', _gen_name), 'output_product_image')]), (relabel_wm, add_gm_wm, [('output_product_image', 'op1')]), (relabel_gm,",
"${EXTRACTION_TMP} # MultiplyImages ${DIMENSION} ${EXTRACTION_GM} ${ATROPOS_GM_CLASS_LABEL} ${EXTRACTION_GM} # ImageMath ${DIMENSION} ${EXTRACTION_SEGMENTATION} addtozero ${EXTRACTION_WM}",
"mask previously computed with the spatial normalization to the template. **Parameters** use_random_seed :",
"op2='-%d' % padding), name='24_depad_segm') depad_gm = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='25_depad_gm') depad_wm =",
"import fname_presuffix out_files = [] cwd = getcwd() nii = nb.load(in_segm) for l",
"order. With this option, you can control :math:`$K$` and tell the script which",
"# Run atropos (core node) atropos = pe.Node(Atropos( dimension=3, initialization='KMeans', number_of_tissue_classes=in_segmentation_model[0], n_iterations=3, convergence_threshold=0.0,",
"(sel_labels, me_csf, [('out_csf', 'op1')]), (mult_gm, add_gm, [('output_product_image', 'op1')]), (me_csf, add_gm, [('output_image', 'op2')]), (add_gm,",
"probability maps)` \"\"\" wf = pe.Workflow(name) inputnode = pe.Node(niu.IdentityInterface(fields=['in_files', 'in_mask']), name='inputnode') outputnode =",
"mask warped from the template. This produces a segmentation image with :math:`$K$` classes,",
"massage outputs pad_segm = pe.Node(ImageMath(operation='PadImage', op2='%d' % padding), name='02_pad_segm') pad_mask = pe.Node(ImageMath(operation='PadImage', op2='%d'",
"(relabel_wm, add_gm_wm, [('output_product_image', 'op1')]), (relabel_gm, add_gm_wm, [('output_product_image', 'op2')]), (add_gm_wm, sel_labels2, [('output_image', 'in_segm')]), (sel_labels2,",
"= pe.Node(niu.Function(function=_select_labels, output_names=['out_wm', 'out_gm', 'out_csf']), name='04_sel_labels') sel_labels.inputs.labels = list(reversed(in_segmentation_model[1:])) # Select largest components",
"in_segmentation_model=list(ATROPOS_MODELS['T1'].values())): \"\"\" Implements supersteps 6 and 7 of ``antsBrainExtraction.sh``, which refine the mask",
"[('output_image', 'op1')]), (add_gm_wm, depad_segm, [('output_image', 'op1')]), (relabel_wm, depad_wm, [('output_product_image', 'op1')]), (relabel_gm, depad_gm, [('output_product_image',",
"]), } def init_atropos_wf(name='atropos_wf', use_random_seed=True, omp_nthreads=None, mem_gb=3.0, padding=10, in_segmentation_model=list(ATROPOS_MODELS['T1'].values())): \"\"\" Implements supersteps 6",
"run to find gray or white matter around the edge of the initial",
"${EXTRACTION_MASK} ${EXTRACTION_TMP} add_7 = pe.Node(ImageMath(operation='addtozero'), name='15_add_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} ME ${EXTRACTION_MASK} 2",
"ATROPOS_MODELS = { 'T1': OrderedDict([ ('nclasses', 3), ('csf', 1), ('gm', 2), ('wm', 3),",
"os import getcwd import numpy as np import nibabel as nb from nipype.utils.filemanip",
"the workflow padding : int Pad images with zeros before processing in_segmentation_model :",
"on the system's clock omp_nthreads : int Maximum number of threads an individual",
"or white matter around the edge of the initial brain mask warped from",
"= pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='26_depad_wm') depad_csf = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='27_depad_csf')",
"(nii.get_data() == l).astype(np.uint8) newnii = nii.__class__(data, nii.affine, nii.header) newnii.set_data_dtype('uint8') out_file = fname_presuffix(in_segm, suffix='class-%02d'",
"Output segmentation out_tpms Output :abbr:`TPMs (tissue probability maps)` \"\"\" wf = pe.Workflow(name) inputnode",
"# ImageMath ${DIMENSION} ${EXTRACTION_TMP} FillHoles ${EXTRACTION_GM} 2 # MultiplyImages ${DIMENSION} ${EXTRACTION_GM} ${EXTRACTION_TMP} ${EXTRACTION_GM}",
"padding), name='25_depad_gm') depad_wm = pe.Node(ImageMath(operation='PadImage', op2='-%d' % padding), name='26_depad_wm') depad_csf = pe.Node(ImageMath(operation='PadImage', op2='-%d'",
"name='18_md_7') # ImageMath ${DIMENSION} ${EXTRACTION_MASK} FillHoles ${EXTRACTION_MASK} 2 fill_7 = pe.Node(ImageMath(operation='FillHoles', op2='2'), name='19_fill_7')",
"relabel_wm, [('output_image', 'first_input'), (('output_image', _gen_name), 'output_product_image')]), (sel_labels, me_csf, [('out_csf', 'op1')]), (mult_gm, add_gm, [('output_product_image',",
"'op1')]), (sel_labels, depad_csf, [('out_csf', 'op1')]), (depad_csf, merge_tpms, [('output_image', 'in1')]), (depad_gm, merge_tpms, [('output_image', 'in2')]),",
"ordered by mean intensity in increasing order. With this option, you can control",
"addtozero ${EXTRACTION_GM} ${EXTRACTION_TMP} # MultiplyImages ${DIMENSION} ${EXTRACTION_GM} ${ATROPOS_GM_CLASS_LABEL} ${EXTRACTION_GM} # ImageMath ${DIMENSION} ${EXTRACTION_SEGMENTATION}",
"me_csf = pe.Node(ImageMath(operation='ME', op2='10'), name='10_me_csf') # ImageMath ${DIMENSION} ${EXTRACTION_GM} addtozero ${EXTRACTION_GM} ${EXTRACTION_TMP} #",
"str, optional Workflow name (default: atropos_wf) **Inputs** in_files :abbr:`INU (intensity non-uniformity)`-corrected files. in_mask",
"'op1')]), (depad_csf, merge_tpms, [('output_image', 'in1')]), (depad_gm, merge_tpms, [('output_image', 'in2')]), (depad_wm, merge_tpms, [('output_image', 'in3')]),",
"('gm', 2), ('wm', 1), ]), 'FLAIR': OrderedDict([ ('nclasses', 3), ('csf', 1), ('gm', 3),",
"# Fill holes and calculate intersection # ImageMath ${DIMENSION} ${EXTRACTION_TMP} FillHoles ${EXTRACTION_GM} 2",
"mem_gb=mem_gb) # massage outputs pad_segm = pe.Node(ImageMath(operation='PadImage', op2='%d' % padding), name='02_pad_segm') pad_mask =",
"suffix='class-%02d' % l, newpath=cwd) newnii.to_filename(out_file) out_files.append(out_file) return out_files def _gen_name(in_file): import os from",
"3), ('gm', 2), ('wm', 1), ]), 'FLAIR': OrderedDict([ ('nclasses', 3), ('csf', 1), ('gm',",
"consumption of the most hungry nodes in the workflow padding : int Pad",
"get_wm, [('out_wm', 'op1')]), (sel_labels, get_gm, [('out_gm', 'op1')]), (get_gm, fill_gm, [('output_image', 'op1')]), (get_gm, mult_gm,",
"nipype.utils.filemanip import fname_presuffix out_files = [] cwd = getcwd() nii = nb.load(in_segm) for",
"from ..interfaces.ants import ImageMath ATROPOS_MODELS = { 'T1': OrderedDict([ ('nclasses', 3), ('csf', 1),",
"WM=2 - ``(4,4,2,3)`` uses K=4, CSF=4, GM=2, WM=3 name : str, optional Workflow",
"dimension=3, initialization='KMeans', number_of_tissue_classes=in_segmentation_model[0], n_iterations=3, convergence_threshold=0.0, mrf_radius=[1, 1, 1], mrf_smoothing_factor=0.1, likelihood_model='Gaussian', use_random_seed=use_random_seed), name='01_atropos', n_procs=omp_nthreads,",
"zeros before processing in_segmentation_model : tuple A k-means segmentation is run to find",
"1], mrf_smoothing_factor=0.1, likelihood_model='Gaussian', use_random_seed=use_random_seed), name='01_atropos', n_procs=omp_nthreads, mem_gb=mem_gb) # massage outputs pad_segm = pe.Node(ImageMath(operation='PadImage',",
"masks sel_labels2 = pe.Node(niu.Function(function=_select_labels, output_names=['out_wm', 'out_gm', 'out_csf']), name='14_sel_labels2') sel_labels2.inputs.labels = list(reversed(in_segmentation_model[1:])) # ImageMath",
"# Select largest components (GM, WM) # ImageMath ${DIMENSION} ${EXTRACTION_WM} GetLargestComponent ${EXTRACTION_WM} get_wm",
"ImageMath ${DIMENSION} ${EXTRACTION_MASK} MD ${EXTRACTION_MASK} 5 md_7_2 = pe.Node(ImageMath(operation='MD', op2='5'), name='21_md_7_2') # ImageMath",
"with K=3, CSF=1, GM=2, WM=3 (default) - ``(3,3,2,1)`` for T2 with K=3, CSF=3,",
"('csf', 1), ('gm', 3), ('wm', 2), ]), } def init_atropos_wf(name='atropos_wf', use_random_seed=True, omp_nthreads=None, mem_gb=3.0,",
"FLAIR with K=3, CSF=1 GM=3, WM=2 - ``(4,4,2,3)`` uses K=4, CSF=4, GM=2, WM=3",
"MultiplyImages ${DIMENSION} ${EXTRACTION_GM} ${ATROPOS_GM_CLASS_LABEL} ${EXTRACTION_GM} # ImageMath ${DIMENSION} ${EXTRACTION_SEGMENTATION} addtozero ${EXTRACTION_WM} ${EXTRACTION_GM} add_gm",
"WM=1 - ``(3,1,3,2)`` for FLAIR with K=3, CSF=1 GM=3, WM=2 - ``(4,4,2,3)`` uses",
"the initial brain mask warped from the template. This produces a segmentation image",
"computed with the spatial normalization to the template. **Parameters** use_random_seed : bool Whether",
"likelihood_model='Gaussian', use_random_seed=use_random_seed), name='01_atropos', n_procs=omp_nthreads, mem_gb=mem_gb) # massage outputs pad_segm = pe.Node(ImageMath(operation='PadImage', op2='%d' %"
] |
[
"status1=data[\"soap:Envelope\"][\"soap:Body\"][\"RetrieveResponseMsg\"][\"Results\"] status2 = loads(dumps(status1)) except Exception as e: return \"There are no records",
"<a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address> </a:ReplyTo> <a:To s:mustUnderstand=\"1\">https://webservice.s6.exacttarget.com/Service.asmx</a:To> <fueloauth xmlms=\"http://exacttarget.com\">{accessToken}</fueloauth> </s:Header> <s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <UpdateRequest xmlns=\"http://exacttarget.com/wsdl/partnerAPI\"> <Objects",
"verify=False ) # req.close() return req.json() cred = auth('<KEY>','<KEY>','6291063') token = (cred[\"access_token\"]) print(\"Access",
"</RetrieveRequestMsg> </s:Body> </s:Envelope> \"\"\" url = \"https://webservice.s6.exacttarget.com/Service.asmx\" headers = {'content-type': 'text/xml'} body =",
"<Value>False</Value> </Property> <Property> <Name>Status</Name> <Value>Hold Out</Value> </Property> </Properties> </Objects> </UpdateRequest> </s:Body> </s:Envelope> \"\"\"",
"</Properties> </Objects> </UpdateRequest> </s:Body> </s:Envelope> \"\"\" url = \"https://webservice.s6.exacttarget.com/Service.asmx\" headers = {'content-type': 'text/xml'}",
"> 0: for element in cust_1: soapbody = f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">",
"ele in cust_list if ele not in cust_1] print(cust_2) if len(cust_2) > 9:",
"in cust_list if ele not in cust_1] print(cust_2) if len(cust_2) > 9: #",
"cust_key= item[\"Properties\"][\"Property\"][0]['Value'] cust_list.append(cust_key) print(\"UnProcessed List\",cust_list) n= len(cust_list)%10 print(n) cust_1 = [] for i",
"import ceil import jxmlease import operator import random from operator import itemgetter import",
"requests.Response: end_point = \"https://mc4pytkknrp1gsz0v23m93b3055y.auth.marketingcloudapis.com/v2/token\" headers = {'Content-type': 'application/json;charset=UTF-8'} payload = { \"grant_type\":\"client_credentials\", \"client_id\":",
"req.close() return req.json() cred = auth('<KEY>','<KEY>','6291063') token = (cred[\"access_token\"]) print(\"Access Token : \",token)",
"for element in hold_list: soapbody = f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action",
"= loads(dumps(status1)) except Exception as e: return \"There are no records for holding",
"len(cust_2) > 9: # hold_list = cust_list[::10] hold_list = [cust_2[x*10-1] for x in",
"holdout_rec) res_list = tuple(set(holdout_rec)^set(cust_2)) print(\"Without Holdout: \", res_list) for element in res_list: soapbody",
"body = soapbody resp = requests.post(url, data=body, headers=headers) print(resp.status_code) # print(resp.text) if len(cust_1)",
"<Client> <ID>{account_id}</ID> </Client> <ObjectID xsi:nil=\"true\"/> <CustomerKey>{de_external_key}</CustomerKey> <Properties> <Property> <Name>Name</Name> <Value>{element}</Value> </Property> <Property> <Name>Flag</Name>",
"= \"https://webservice.s6.exacttarget.com/Service.asmx\" headers = {'content-type': 'text/xml'} body = soapbody resp = requests.post(url, data=body,",
"xsi:nil=\"true\"/> <CustomerKey>{de_external_key}</CustomerKey> <Properties> <Property> <Name>Name</Name> <Value>{element}</Value> </Property> <Property> <Name>Flag</Name> <Value>True</Value> </Property> <Property> <Name>Status</Name>",
"accountId:str ) -> requests.Response: end_point = \"https://mc4pytkknrp1gsz0v23m93b3055y.auth.marketingcloudapis.com/v2/token\" headers = {'Content-type': 'application/json;charset=UTF-8'} payload =",
"[] for i in range(0,n): cust_1.append(cust_list.pop()) print(cust_1) cust_2 = [ele for ele in",
"try: accessToken = token account_id = \"6291063\" de_name = \"Test_HoldOut_Group\" de_external_key = \"5E4FE032-6C0E-42E8-8B81-99F167D7DFC9\"",
"= \"Test_HoldOut_Group\" de_external_key = \"5E4FE032-6C0E-42E8-8B81-99F167D7DFC9\" except Exception as e: return \"There is some",
"<s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <UpdateRequest xmlns=\"http://exacttarget.com/wsdl/partnerAPI\"> <Objects xsi:type=\"DataExtensionObject\"> <PartnerKey xsi:nil=\"true\"/> <Client> <ID>{account_id}</ID> </Client> <ObjectID",
"clientSecret, \"account_id\": accountId, } req = requests.post( end_point, payload, {\"headers\" : headers} #",
"headers=headers) response = resp.text # print(response) data = jxmlease.parse(response) status1=data[\"soap:Envelope\"][\"soap:Body\"][\"RetrieveResponseMsg\"][\"Results\"] status2 = loads(dumps(status1))",
"= hold_list # print(\"HoldOut Records: \", holdout_rec) res_list = tuple(set(holdout_rec)^set(cust_2)) print(\"Without Holdout: \",",
"<UpdateRequest xmlns=\"http://exacttarget.com/wsdl/partnerAPI\"> <Objects xsi:type=\"DataExtensionObject\"> <PartnerKey xsi:nil=\"true\"/> <Client> <ID>{account_id}</ID> </Client> <ObjectID xsi:nil=\"true\"/> <CustomerKey>{de_external_key}</CustomerKey> <Properties>",
"resp = requests.post(url, data=body, headers=headers) print(resp.status_code) # print(resp.text) return \"All Records Processed Sucessfully...\"",
"response = resp.text # print(response) data = jxmlease.parse(response) status1=data[\"soap:Envelope\"][\"soap:Body\"][\"RetrieveResponseMsg\"][\"Results\"] status2 = loads(dumps(status1)) except",
"in cust_1: soapbody = f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action s:mustUnderstand=\"1\">Update</a:Action> <a:MessageID>urn:uuid:7e0cca04-57bd-4481-864c-6ea8039d2ea0</a:MessageID>",
"9: # hold_list = cust_list[::10] hold_list = [cust_2[x*10-1] for x in range(1,len(cust_2)) if",
"# verify=False ) # req.close() return req.json() cred = auth('<KEY>','<KEY>','6291063') token = (cred[\"access_token\"])",
"res_list = tuple(set(holdout_rec)^set(cust_2)) print(\"Without Holdout: \", res_list) for element in res_list: soapbody =",
"print(\"Without Holdout: \", res_list) for element in res_list: soapbody = f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\"",
"Records: \", holdout_rec) res_list = tuple(set(holdout_rec)^set(cust_2)) print(\"Without Holdout: \", res_list) for element in",
"xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action s:mustUnderstand=\"1\">Update</a:Action> <a:MessageID>urn:uuid:7e0cca04-57bd-4481-864c-6ea8039d2ea0</a:MessageID> <a:ReplyTo> <a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address> </a:ReplyTo> <a:To s:mustUnderstand=\"1\">https://webservice.s6.exacttarget.com/Service.asmx</a:To> <fueloauth",
"element in res_list: soapbody = f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action s:mustUnderstand=\"1\">Update</a:Action>",
"<s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <RetrieveRequestMsg xmlns=\"http://exacttarget.com/wsdl/partnerAPI\"> <RetrieveRequest> <ObjectType>DataExtensionObject[{de_name}]</ObjectType> <Properties>NAME</Properties> <Properties>Flag</Properties> <Properties>Status</Properties> <Filter xsi:type=\"SimpleFilterPart\"> <Property>Status</Property>",
"s:mustUnderstand=\"1\">https://webservice.s6.exacttarget.com/Service.asmx</a:To> <fueloauth xmlns=\"http://exacttarget.com\">{accessToken}</fueloauth> </s:Header> <s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <RetrieveRequestMsg xmlns=\"http://exacttarget.com/wsdl/partnerAPI\"> <RetrieveRequest> <ObjectType>DataExtensionObject[{de_name}]</ObjectType> <Properties>NAME</Properties> <Properties>Flag</Properties>",
"headers=headers) print(resp.status_code) # print(resp.text) if len(cust_1) > 0: for element in cust_1: soapbody",
"</Client> <ObjectID xsi:nil=\"true\"/> <CustomerKey>{de_external_key}</CustomerKey> <Properties> <Property> <Name>Name</Name> <Value>{element}</Value> </Property> <Property> <Name>Flag</Name> <Value>True</Value> </Property>",
"len(cust_list)%10 print(n) cust_1 = [] for i in range(0,n): cust_1.append(cust_list.pop()) print(cust_1) cust_2 =",
"import json import xmltodict import datetime from math import ceil import jxmlease import",
"cust_1 = [] for i in range(0,n): cust_1.append(cust_list.pop()) print(cust_1) cust_2 = [ele for",
"= {'content-type': 'text/xml'} body = soapbody resp = requests.post(url, data=body, headers=headers) print(resp.status_code) #",
"<Property> <Name>Flag</Name> <Value>True</Value> </Property> <Property> <Name>Status</Name> <Value>Processed</Value> </Property> </Properties> </Objects> </UpdateRequest> </s:Body> </s:Envelope>",
"= {'Content-type': 'application/json;charset=UTF-8'} payload = { \"grant_type\":\"client_credentials\", \"client_id\": clientId, \"client_secret\": clientSecret, \"account_id\": accountId,",
"accountId, } req = requests.post( end_point, payload, {\"headers\" : headers} # verify=False )",
"'application/json;charset=UTF-8'} payload = { \"grant_type\":\"client_credentials\", \"client_id\": clientId, \"client_secret\": clientSecret, \"account_id\": accountId, } req",
"resp = requests.post(url, data=body, headers=headers) response = resp.text # print(response) data = jxmlease.parse(response)",
"data = jxmlease.parse(response) status1=data[\"soap:Envelope\"][\"soap:Body\"][\"RetrieveResponseMsg\"][\"Results\"] status2 = loads(dumps(status1)) except Exception as e: return \"There",
"in res_list: soapbody = f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action s:mustUnderstand=\"1\">Update</a:Action> <a:MessageID>urn:uuid:7e0cca04-57bd-4481-864c-6ea8039d2ea0</a:MessageID>",
"problem with the Credentials Provided...\",e try: descbody =f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header>",
"</Property> <Property> <Name>Status</Name> <Value>Processed</Value> </Property> </Properties> </Objects> </UpdateRequest> </s:Body> </s:Envelope> \"\"\" url =",
"data=body, headers=headers) print(resp.status_code) # print(resp.text) if len(cust_1) > 0: for element in cust_1:",
"de_name = \"Test_HoldOut_Group\" de_external_key = \"5E4FE032-6C0E-42E8-8B81-99F167D7DFC9\" except Exception as e: return \"There is",
"cust_1: soapbody = f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action s:mustUnderstand=\"1\">Update</a:Action> <a:MessageID>urn:uuid:7e0cca04-57bd-4481-864c-6ea8039d2ea0</a:MessageID> <a:ReplyTo>",
"range(0,n): cust_1.append(cust_list.pop()) print(cust_1) cust_2 = [ele for ele in cust_list if ele not",
"xmlns=\"http://exacttarget.com/wsdl/partnerAPI\"> <RetrieveRequest> <ObjectType>DataExtensionObject[{de_name}]</ObjectType> <Properties>NAME</Properties> <Properties>Flag</Properties> <Properties>Status</Properties> <Filter xsi:type=\"SimpleFilterPart\"> <Property>Status</Property> <SimpleOperator>equals</SimpleOperator> <Value>Unprocessed</Value> </Filter> </RetrieveRequest>",
"Holdout: \", res_list) for element in res_list: soapbody = f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\"",
"<s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action s:mustUnderstand=\"1\">Retrieve</a:Action> <a:To s:mustUnderstand=\"1\">https://webservice.s6.exacttarget.com/Service.asmx</a:To> <fueloauth xmlns=\"http://exacttarget.com\">{accessToken}</fueloauth> </s:Header> <s:Body",
"(cred[\"access_token\"]) print(\"Access Token : \",token) def dataextension2(): try: accessToken = token account_id =",
"f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action s:mustUnderstand=\"1\">Update</a:Action> <a:MessageID>urn:uuid:7e0cca04-57bd-4481-864c-6ea8039d2ea0</a:MessageID> <a:ReplyTo> <a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address> </a:ReplyTo> <a:To",
"[cust_2[x*10-1] for x in range(1,len(cust_2)) if x*10<=len(cust_2)] print(hold_list) for element in hold_list: soapbody",
"res_list) for element in res_list: soapbody = f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header>",
"for ele in cust_list if ele not in cust_1] print(cust_2) if len(cust_2) >",
"range(1,len(cust_2)) if x*10<=len(cust_2)] print(hold_list) for element in hold_list: soapbody = f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\"",
"print(cust_2) if len(cust_2) > 9: # hold_list = cust_list[::10] hold_list = [cust_2[x*10-1] for",
"\"account_id\": accountId, } req = requests.post( end_point, payload, {\"headers\" : headers} # verify=False",
"out...\",e else: cust_list=[] # print(status2) for item in status2: cust_key= item[\"Properties\"][\"Property\"][0]['Value'] cust_list.append(cust_key) print(\"UnProcessed",
"= cust_list[::10] hold_list = [cust_2[x*10-1] for x in range(1,len(cust_2)) if x*10<=len(cust_2)] print(hold_list) for",
"<Name>Flag</Name> <Value>True</Value> </Property> <Property> <Name>Status</Name> <Value>Processed</Value> </Property> </Properties> </Objects> </UpdateRequest> </s:Body> </s:Envelope> \"\"\"",
"s:mustUnderstand=\"1\">Update</a:Action> <a:MessageID>urn:uuid:7e0cca04-57bd-4481-864c-6ea8039d2ea0</a:MessageID> <a:ReplyTo> <a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address> </a:ReplyTo> <a:To s:mustUnderstand=\"1\">https://webservice.s6.exacttarget.com/Service.asmx</a:To> <fueloauth xmlms=\"http://exacttarget.com\">{accessToken}</fueloauth> </s:Header> <s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">",
"headers} # verify=False ) # req.close() return req.json() cred = auth('<KEY>','<KEY>','6291063') token =",
"tuple(set(holdout_rec)^set(cust_2)) print(\"Without Holdout: \", res_list) for element in res_list: soapbody = f\"\"\" <s:Envelope",
"Provided...\",e try: descbody =f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action s:mustUnderstand=\"1\">Retrieve</a:Action> <a:To s:mustUnderstand=\"1\">https://webservice.s6.exacttarget.com/Service.asmx</a:To>",
"soapbody resp = requests.post(url, data=body, headers=headers) print(resp.status_code) # print(resp.text) holdout_rec = hold_list #",
"= [ele for ele in cust_list if ele not in cust_1] print(cust_2) if",
"jxmlease.parse(response) status1=data[\"soap:Envelope\"][\"soap:Body\"][\"RetrieveResponseMsg\"][\"Results\"] status2 = loads(dumps(status1)) except Exception as e: return \"There are no",
"from json import loads, dumps def auth(clientId: str, clientSecret: str, accountId:str ) ->",
"\"https://webservice.s6.exacttarget.com/Service.asmx\" headers = {'content-type': 'text/xml'} body = soapbody resp = requests.post(url, data=body, headers=headers)",
"xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action s:mustUnderstand=\"1\">Update</a:Action> <a:MessageID>urn:uuid:7e0cca04-57bd-4481-864c-6ea8039d2ea0</a:MessageID> <a:ReplyTo> <a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address> </a:ReplyTo> <a:To s:mustUnderstand=\"1\">https://webservice.s6.exacttarget.com/Service.asmx</a:To> <fueloauth xmlms=\"http://exacttarget.com\">{accessToken}</fueloauth> </s:Header>",
"= soapbody resp = requests.post(url, data=body, headers=headers) print(resp.status_code) # print(resp.text) holdout_rec = hold_list",
"print(response) data = jxmlease.parse(response) status1=data[\"soap:Envelope\"][\"soap:Body\"][\"RetrieveResponseMsg\"][\"Results\"] status2 = loads(dumps(status1)) except Exception as e: return",
"hold_list = cust_list[::10] hold_list = [cust_2[x*10-1] for x in range(1,len(cust_2)) if x*10<=len(cust_2)] print(hold_list)",
"= soapbody resp = requests.post(url, data=body, headers=headers) print(resp.status_code) # print(resp.text) if len(cust_1) >",
"<Value>True</Value> </Property> <Property> <Name>Status</Name> <Value>Processed</Value> </Property> </Properties> </Objects> </UpdateRequest> </s:Body> </s:Envelope> \"\"\" url",
"requests import json import xmltodict import datetime from math import ceil import jxmlease",
"requests.post(url, data=body, headers=headers) print(resp.status_code) # print(resp.text) if len(cust_1) > 0: for element in",
"= requests.post(url, data=body, headers=headers) response = resp.text # print(response) data = jxmlease.parse(response) status1=data[\"soap:Envelope\"][\"soap:Body\"][\"RetrieveResponseMsg\"][\"Results\"]",
"<Properties>Status</Properties> <Filter xsi:type=\"SimpleFilterPart\"> <Property>Status</Property> <SimpleOperator>equals</SimpleOperator> <Value>Unprocessed</Value> </Filter> </RetrieveRequest> </RetrieveRequestMsg> </s:Body> </s:Envelope> \"\"\" url",
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <RetrieveRequestMsg xmlns=\"http://exacttarget.com/wsdl/partnerAPI\"> <RetrieveRequest> <ObjectType>DataExtensionObject[{de_name}]</ObjectType> <Properties>NAME</Properties> <Properties>Flag</Properties> <Properties>Status</Properties> <Filter xsi:type=\"SimpleFilterPart\"> <Property>Status</Property> <SimpleOperator>equals</SimpleOperator> <Value>Unprocessed</Value>",
"xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action s:mustUnderstand=\"1\">Retrieve</a:Action> <a:To s:mustUnderstand=\"1\">https://webservice.s6.exacttarget.com/Service.asmx</a:To> <fueloauth xmlns=\"http://exacttarget.com\">{accessToken}</fueloauth> </s:Header> <s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">",
"json import xmltodict import datetime from math import ceil import jxmlease import operator",
"body = soapbody resp = requests.post(url, data=body, headers=headers) print(resp.status_code) # print(resp.text) return \"All",
"<CustomerKey>{de_external_key}</CustomerKey> <Properties> <Property> <Name>Name</Name> <Value>{element}</Value> </Property> <Property> <Name>Flag</Name> <Value>True</Value> </Property> <Property> <Name>Status</Name> <Value>Processed</Value>",
"records for holding out...\",e else: cust_list=[] # print(status2) for item in status2: cust_key=",
"= jxmlease.parse(response) status1=data[\"soap:Envelope\"][\"soap:Body\"][\"RetrieveResponseMsg\"][\"Results\"] status2 = loads(dumps(status1)) except Exception as e: return \"There are",
"import time from json import loads, dumps def auth(clientId: str, clientSecret: str, accountId:str",
"from math import ceil import jxmlease import operator import random from operator import",
"print(resp.status_code) # print(resp.text) if len(cust_1) > 0: for element in cust_1: soapbody =",
"<Property> <Name>Status</Name> <Value>Hold Out</Value> </Property> </Properties> </Objects> </UpdateRequest> </s:Body> </s:Envelope> \"\"\" url =",
"<Name>Flag</Name> <Value>False</Value> </Property> <Property> <Name>Status</Name> <Value>Hold Out</Value> </Property> </Properties> </Objects> </UpdateRequest> </s:Body> </s:Envelope>",
"</s:Body> </s:Envelope> \"\"\" url = \"https://webservice.s6.exacttarget.com/Service.asmx\" headers = {'content-type': 'text/xml'} body = soapbody",
"status2 = loads(dumps(status1)) except Exception as e: return \"There are no records for",
"accessToken = token account_id = \"6291063\" de_name = \"Test_HoldOut_Group\" de_external_key = \"5E4FE032-6C0E-42E8-8B81-99F167D7DFC9\" except",
"token = (cred[\"access_token\"]) print(\"Access Token : \",token) def dataextension2(): try: accessToken = token",
"= {'content-type': 'text/xml'} body = descbody resp = requests.post(url, data=body, headers=headers) response =",
"import requests import json import xmltodict import datetime from math import ceil import",
"<RetrieveRequest> <ObjectType>DataExtensionObject[{de_name}]</ObjectType> <Properties>NAME</Properties> <Properties>Flag</Properties> <Properties>Status</Properties> <Filter xsi:type=\"SimpleFilterPart\"> <Property>Status</Property> <SimpleOperator>equals</SimpleOperator> <Value>Unprocessed</Value> </Filter> </RetrieveRequest> </RetrieveRequestMsg>",
"<ID>{account_id}</ID> </Client> <ObjectID xsi:nil=\"true\"/> <CustomerKey>{de_external_key}</CustomerKey> <Properties> <Property> <Name>Name</Name> <Value>{element}</Value> </Property> <Property> <Name>Flag</Name> <Value>False</Value>",
"Token : \",token) def dataextension2(): try: accessToken = token account_id = \"6291063\" de_name",
"for element in res_list: soapbody = f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action",
"token account_id = \"6291063\" de_name = \"Test_HoldOut_Group\" de_external_key = \"5E4FE032-6C0E-42E8-8B81-99F167D7DFC9\" except Exception as",
"= tuple(set(holdout_rec)^set(cust_2)) print(\"Without Holdout: \", res_list) for element in res_list: soapbody = f\"\"\"",
"= (cred[\"access_token\"]) print(\"Access Token : \",token) def dataextension2(): try: accessToken = token account_id",
"if ele not in cust_1] print(cust_2) if len(cust_2) > 9: # hold_list =",
"cust_list if ele not in cust_1] print(cust_2) if len(cust_2) > 9: # hold_list",
"<Name>Status</Name> <Value>Unprocessed</Value> </Property> </Properties> </Objects> </UpdateRequest> </s:Body> </s:Envelope> \"\"\" url = \"https://webservice.s6.exacttarget.com/Service.asmx\" headers",
"ceil import jxmlease import operator import random from operator import itemgetter import time",
"<Value>Unprocessed</Value> </Filter> </RetrieveRequest> </RetrieveRequestMsg> </s:Body> </s:Envelope> \"\"\" url = \"https://webservice.s6.exacttarget.com/Service.asmx\" headers = {'content-type':",
"\", res_list) for element in res_list: soapbody = f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">",
"payload, {\"headers\" : headers} # verify=False ) # req.close() return req.json() cred =",
"return \"There are no records for holding out...\",e else: cust_list=[] # print(status2) for",
"in status2: cust_key= item[\"Properties\"][\"Property\"][0]['Value'] cust_list.append(cust_key) print(\"UnProcessed List\",cust_list) n= len(cust_list)%10 print(n) cust_1 = []",
"{'content-type': 'text/xml'} body = soapbody resp = requests.post(url, data=body, headers=headers) print(resp.status_code) # print(resp.text)",
"return req.json() cred = auth('<KEY>','<KEY>','6291063') token = (cred[\"access_token\"]) print(\"Access Token : \",token) def",
"print(\"HoldOut Records: \", holdout_rec) res_list = tuple(set(holdout_rec)^set(cust_2)) print(\"Without Holdout: \", res_list) for element",
"> 9: # hold_list = cust_list[::10] hold_list = [cust_2[x*10-1] for x in range(1,len(cust_2))",
") # req.close() return req.json() cred = auth('<KEY>','<KEY>','6291063') token = (cred[\"access_token\"]) print(\"Access Token",
": \",token) def dataextension2(): try: accessToken = token account_id = \"6291063\" de_name =",
"= \"https://mc4pytkknrp1gsz0v23m93b3055y.auth.marketingcloudapis.com/v2/token\" headers = {'Content-type': 'application/json;charset=UTF-8'} payload = { \"grant_type\":\"client_credentials\", \"client_id\": clientId, \"client_secret\":",
"is some problem with the Credentials Provided...\",e try: descbody =f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\"",
"</UpdateRequest> </s:Body> </s:Envelope> \"\"\" url = \"https://webservice.s6.exacttarget.com/Service.asmx\" headers = {'content-type': 'text/xml'} body =",
"clientId, \"client_secret\": clientSecret, \"account_id\": accountId, } req = requests.post( end_point, payload, {\"headers\" :",
"</Property> <Property> <Name>Flag</Name> <Value>False</Value> </Property> <Property> <Name>Status</Name> <Value>Hold Out</Value> </Property> </Properties> </Objects> </UpdateRequest>",
"json import loads, dumps def auth(clientId: str, clientSecret: str, accountId:str ) -> requests.Response:",
"res_list: soapbody = f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action s:mustUnderstand=\"1\">Update</a:Action> <a:MessageID>urn:uuid:7e0cca04-57bd-4481-864c-6ea8039d2ea0</a:MessageID> <a:ReplyTo>",
"\"https://mc4pytkknrp1gsz0v23m93b3055y.auth.marketingcloudapis.com/v2/token\" headers = {'Content-type': 'application/json;charset=UTF-8'} payload = { \"grant_type\":\"client_credentials\", \"client_id\": clientId, \"client_secret\": clientSecret,",
"</Property> <Property> <Name>Status</Name> <Value>Hold Out</Value> </Property> </Properties> </Objects> </UpdateRequest> </s:Body> </s:Envelope> \"\"\" url",
"= [cust_2[x*10-1] for x in range(1,len(cust_2)) if x*10<=len(cust_2)] print(hold_list) for element in hold_list:",
") -> requests.Response: end_point = \"https://mc4pytkknrp1gsz0v23m93b3055y.auth.marketingcloudapis.com/v2/token\" headers = {'Content-type': 'application/json;charset=UTF-8'} payload = {",
"account_id = \"6291063\" de_name = \"Test_HoldOut_Group\" de_external_key = \"5E4FE032-6C0E-42E8-8B81-99F167D7DFC9\" except Exception as e:",
"\"\"\" url = \"https://webservice.s6.exacttarget.com/Service.asmx\" headers = {'content-type': 'text/xml'} body = descbody resp =",
"cust_1] print(cust_2) if len(cust_2) > 9: # hold_list = cust_list[::10] hold_list = [cust_2[x*10-1]",
"xsi:type=\"DataExtensionObject\"> <PartnerKey xsi:nil=\"true\"/> <Client> <ID>{account_id}</ID> </Client> <ObjectID xsi:nil=\"true\"/> <CustomerKey>{de_external_key}</CustomerKey> <Properties> <Property> <Name>Name</Name> <Value>{element}</Value>",
"0: for element in cust_1: soapbody = f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header>",
"</Property> <Property> <Name>Status</Name> <Value>Unprocessed</Value> </Property> </Properties> </Objects> </UpdateRequest> </s:Body> </s:Envelope> \"\"\" url =",
"<ID>{account_id}</ID> </Client> <ObjectID xsi:nil=\"true\"/> <CustomerKey>{de_external_key}</CustomerKey> <Properties> <Property> <Name>Name</Name> <Value>{element}</Value> </Property> <Property> <Name>Flag</Name> <Value>True</Value>",
"<Value>Unprocessed</Value> </Property> </Properties> </Objects> </UpdateRequest> </s:Body> </s:Envelope> \"\"\" url = \"https://webservice.s6.exacttarget.com/Service.asmx\" headers =",
"{'content-type': 'text/xml'} body = descbody resp = requests.post(url, data=body, headers=headers) response = resp.text",
"<Property> <Name>Flag</Name> <Value>False</Value> </Property> <Property> <Name>Status</Name> <Value>Hold Out</Value> </Property> </Properties> </Objects> </UpdateRequest> </s:Body>",
"requests.post(url, data=body, headers=headers) print(resp.status_code) # print(resp.text) holdout_rec = hold_list # print(\"HoldOut Records: \",",
"cust_list=[] # print(status2) for item in status2: cust_key= item[\"Properties\"][\"Property\"][0]['Value'] cust_list.append(cust_key) print(\"UnProcessed List\",cust_list) n=",
"import operator import random from operator import itemgetter import time from json import",
"for item in status2: cust_key= item[\"Properties\"][\"Property\"][0]['Value'] cust_list.append(cust_key) print(\"UnProcessed List\",cust_list) n= len(cust_list)%10 print(n) cust_1",
"except Exception as e: return \"There are no records for holding out...\",e else:",
"<fueloauth xmlms=\"http://exacttarget.com\">{accessToken}</fueloauth> </s:Header> <s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <UpdateRequest xmlns=\"http://exacttarget.com/wsdl/partnerAPI\"> <Objects xsi:type=\"DataExtensionObject\"> <PartnerKey xsi:nil=\"true\"/> <Client>",
"end_point = \"https://mc4pytkknrp1gsz0v23m93b3055y.auth.marketingcloudapis.com/v2/token\" headers = {'Content-type': 'application/json;charset=UTF-8'} payload = { \"grant_type\":\"client_credentials\", \"client_id\": clientId,",
"<Property> <Name>Name</Name> <Value>{element}</Value> </Property> <Property> <Name>Flag</Name> <Value>True</Value> </Property> <Property> <Name>Status</Name> <Value>Processed</Value> </Property> </Properties>",
"soapbody resp = requests.post(url, data=body, headers=headers) print(resp.status_code) # print(resp.text) return \"All Records Processed",
"hold_list: soapbody = f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action s:mustUnderstand=\"1\">Update</a:Action> <a:MessageID>urn:uuid:7e0cca04-57bd-4481-864c-6ea8039d2ea0</a:MessageID> <a:ReplyTo>",
"'text/xml'} body = soapbody resp = requests.post(url, data=body, headers=headers) print(resp.status_code) # print(resp.text) holdout_rec",
"= token account_id = \"6291063\" de_name = \"Test_HoldOut_Group\" de_external_key = \"5E4FE032-6C0E-42E8-8B81-99F167D7DFC9\" except Exception",
"</s:Envelope> \"\"\" url = \"https://webservice.s6.exacttarget.com/Service.asmx\" headers = {'content-type': 'text/xml'} body = descbody resp",
"headers = {'Content-type': 'application/json;charset=UTF-8'} payload = { \"grant_type\":\"client_credentials\", \"client_id\": clientId, \"client_secret\": clientSecret, \"account_id\":",
"= requests.post(url, data=body, headers=headers) print(resp.status_code) # print(resp.text) return \"All Records Processed Sucessfully...\" dataextension2()",
"print(status2) for item in status2: cust_key= item[\"Properties\"][\"Property\"][0]['Value'] cust_list.append(cust_key) print(\"UnProcessed List\",cust_list) n= len(cust_list)%10 print(n)",
"<Property> <Name>Flag</Name> <Value>True</Value> </Property> <Property> <Name>Status</Name> <Value>Unprocessed</Value> </Property> </Properties> </Objects> </UpdateRequest> </s:Body> </s:Envelope>",
"data=body, headers=headers) print(resp.status_code) # print(resp.text) holdout_rec = hold_list # print(\"HoldOut Records: \", holdout_rec)",
"# print(status2) for item in status2: cust_key= item[\"Properties\"][\"Property\"][0]['Value'] cust_list.append(cust_key) print(\"UnProcessed List\",cust_list) n= len(cust_list)%10",
"itemgetter import time from json import loads, dumps def auth(clientId: str, clientSecret: str,",
"math import ceil import jxmlease import operator import random from operator import itemgetter",
"\"Test_HoldOut_Group\" de_external_key = \"5E4FE032-6C0E-42E8-8B81-99F167D7DFC9\" except Exception as e: return \"There is some problem",
"'text/xml'} body = descbody resp = requests.post(url, data=body, headers=headers) response = resp.text #",
"<fueloauth xmlns=\"http://exacttarget.com\">{accessToken}</fueloauth> </s:Header> <s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <RetrieveRequestMsg xmlns=\"http://exacttarget.com/wsdl/partnerAPI\"> <RetrieveRequest> <ObjectType>DataExtensionObject[{de_name}]</ObjectType> <Properties>NAME</Properties> <Properties>Flag</Properties> <Properties>Status</Properties>",
"import datetime from math import ceil import jxmlease import operator import random from",
"= \"6291063\" de_name = \"Test_HoldOut_Group\" de_external_key = \"5E4FE032-6C0E-42E8-8B81-99F167D7DFC9\" except Exception as e: return",
"headers=headers) print(resp.status_code) # print(resp.text) holdout_rec = hold_list # print(\"HoldOut Records: \", holdout_rec) res_list",
"</s:Body> </s:Envelope> \"\"\" url = \"https://webservice.s6.exacttarget.com/Service.asmx\" headers = {'content-type': 'text/xml'} body = descbody",
"else: cust_list=[] # print(status2) for item in status2: cust_key= item[\"Properties\"][\"Property\"][0]['Value'] cust_list.append(cust_key) print(\"UnProcessed List\",cust_list)",
"<ObjectType>DataExtensionObject[{de_name}]</ObjectType> <Properties>NAME</Properties> <Properties>Flag</Properties> <Properties>Status</Properties> <Filter xsi:type=\"SimpleFilterPart\"> <Property>Status</Property> <SimpleOperator>equals</SimpleOperator> <Value>Unprocessed</Value> </Filter> </RetrieveRequest> </RetrieveRequestMsg> </s:Body>",
"<Name>Name</Name> <Value>{element}</Value> </Property> <Property> <Name>Flag</Name> <Value>True</Value> </Property> <Property> <Name>Status</Name> <Value>Unprocessed</Value> </Property> </Properties> </Objects>",
"<s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action s:mustUnderstand=\"1\">Update</a:Action> <a:MessageID>urn:uuid:7e0cca04-57bd-4481-864c-6ea8039d2ea0</a:MessageID> <a:ReplyTo> <a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address> </a:ReplyTo> <a:To s:mustUnderstand=\"1\">https://webservice.s6.exacttarget.com/Service.asmx</a:To>",
"<Name>Status</Name> <Value>Hold Out</Value> </Property> </Properties> </Objects> </UpdateRequest> </s:Body> </s:Envelope> \"\"\" url = \"https://webservice.s6.exacttarget.com/Service.asmx\"",
"soapbody = f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action s:mustUnderstand=\"1\">Update</a:Action> <a:MessageID>urn:uuid:7e0cca04-57bd-4481-864c-6ea8039d2ea0</a:MessageID> <a:ReplyTo> <a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address>",
"time from json import loads, dumps def auth(clientId: str, clientSecret: str, accountId:str )",
"soapbody resp = requests.post(url, data=body, headers=headers) print(resp.status_code) # print(resp.text) if len(cust_1) > 0:",
"{\"headers\" : headers} # verify=False ) # req.close() return req.json() cred = auth('<KEY>','<KEY>','6291063')",
"url = \"https://webservice.s6.exacttarget.com/Service.asmx\" headers = {'content-type': 'text/xml'} body = descbody resp = requests.post(url,",
"<Property> <Name>Name</Name> <Value>{element}</Value> </Property> <Property> <Name>Flag</Name> <Value>True</Value> </Property> <Property> <Name>Status</Name> <Value>Unprocessed</Value> </Property> </Properties>",
"= { \"grant_type\":\"client_credentials\", \"client_id\": clientId, \"client_secret\": clientSecret, \"account_id\": accountId, } req = requests.post(",
"<a:MessageID>urn:uuid:7e0cca04-57bd-4481-864c-6ea8039d2ea0</a:MessageID> <a:ReplyTo> <a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address> </a:ReplyTo> <a:To s:mustUnderstand=\"1\">https://webservice.s6.exacttarget.com/Service.asmx</a:To> <fueloauth xmlms=\"http://exacttarget.com\">{accessToken}</fueloauth> </s:Header> <s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <UpdateRequest",
": headers} # verify=False ) # req.close() return req.json() cred = auth('<KEY>','<KEY>','6291063') token",
"\"There are no records for holding out...\",e else: cust_list=[] # print(status2) for item",
"= [] for i in range(0,n): cust_1.append(cust_list.pop()) print(cust_1) cust_2 = [ele for ele",
"print(resp.status_code) # print(resp.text) holdout_rec = hold_list # print(\"HoldOut Records: \", holdout_rec) res_list =",
"import jxmlease import operator import random from operator import itemgetter import time from",
"<ObjectID xsi:nil=\"true\"/> <CustomerKey>{de_external_key}</CustomerKey> <Properties> <Property> <Name>Name</Name> <Value>{element}</Value> </Property> <Property> <Name>Flag</Name> <Value>False</Value> </Property> <Property>",
"\",token) def dataextension2(): try: accessToken = token account_id = \"6291063\" de_name = \"Test_HoldOut_Group\"",
"ele not in cust_1] print(cust_2) if len(cust_2) > 9: # hold_list = cust_list[::10]",
"= soapbody resp = requests.post(url, data=body, headers=headers) print(resp.status_code) # print(resp.text) return \"All Records",
"= auth('<KEY>','<KEY>','6291063') token = (cred[\"access_token\"]) print(\"Access Token : \",token) def dataextension2(): try: accessToken",
"print(\"Access Token : \",token) def dataextension2(): try: accessToken = token account_id = \"6291063\"",
"'text/xml'} body = soapbody resp = requests.post(url, data=body, headers=headers) print(resp.status_code) # print(resp.text) if",
"return \"There is some problem with the Credentials Provided...\",e try: descbody =f\"\"\" <s:Envelope",
"if x*10<=len(cust_2)] print(hold_list) for element in hold_list: soapbody = f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\"",
"=f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action s:mustUnderstand=\"1\">Retrieve</a:Action> <a:To s:mustUnderstand=\"1\">https://webservice.s6.exacttarget.com/Service.asmx</a:To> <fueloauth xmlns=\"http://exacttarget.com\">{accessToken}</fueloauth> </s:Header>",
"as e: return \"There are no records for holding out...\",e else: cust_list=[] #",
"some problem with the Credentials Provided...\",e try: descbody =f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">",
"cust_list[::10] hold_list = [cust_2[x*10-1] for x in range(1,len(cust_2)) if x*10<=len(cust_2)] print(hold_list) for element",
"import random from operator import itemgetter import time from json import loads, dumps",
"in range(0,n): cust_1.append(cust_list.pop()) print(cust_1) cust_2 = [ele for ele in cust_list if ele",
"for x in range(1,len(cust_2)) if x*10<=len(cust_2)] print(hold_list) for element in hold_list: soapbody =",
"import xmltodict import datetime from math import ceil import jxmlease import operator import",
"auth('<KEY>','<KEY>','6291063') token = (cred[\"access_token\"]) print(\"Access Token : \",token) def dataextension2(): try: accessToken =",
"in hold_list: soapbody = f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action s:mustUnderstand=\"1\">Update</a:Action> <a:MessageID>urn:uuid:7e0cca04-57bd-4481-864c-6ea8039d2ea0</a:MessageID>",
"e: return \"There is some problem with the Credentials Provided...\",e try: descbody =f\"\"\"",
"= requests.post( end_point, payload, {\"headers\" : headers} # verify=False ) # req.close() return",
"item in status2: cust_key= item[\"Properties\"][\"Property\"][0]['Value'] cust_list.append(cust_key) print(\"UnProcessed List\",cust_list) n= len(cust_list)%10 print(n) cust_1 =",
"{ \"grant_type\":\"client_credentials\", \"client_id\": clientId, \"client_secret\": clientSecret, \"account_id\": accountId, } req = requests.post( end_point,",
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <UpdateRequest xmlns=\"http://exacttarget.com/wsdl/partnerAPI\"> <Objects xsi:type=\"DataExtensionObject\"> <PartnerKey xsi:nil=\"true\"/> <Client> <ID>{account_id}</ID> </Client> <ObjectID xsi:nil=\"true\"/> <CustomerKey>{de_external_key}</CustomerKey>",
"= requests.post(url, data=body, headers=headers) print(resp.status_code) # print(resp.text) if len(cust_1) > 0: for element",
"\"\"\" url = \"https://webservice.s6.exacttarget.com/Service.asmx\" headers = {'content-type': 'text/xml'} body = soapbody resp =",
"end_point, payload, {\"headers\" : headers} # verify=False ) # req.close() return req.json() cred",
"\"5E4FE032-6C0E-42E8-8B81-99F167D7DFC9\" except Exception as e: return \"There is some problem with the Credentials",
"operator import random from operator import itemgetter import time from json import loads,",
"cust_2 = [ele for ele in cust_list if ele not in cust_1] print(cust_2)",
"</Property> <Property> <Name>Flag</Name> <Value>True</Value> </Property> <Property> <Name>Status</Name> <Value>Unprocessed</Value> </Property> </Properties> </Objects> </UpdateRequest> </s:Body>",
"x in range(1,len(cust_2)) if x*10<=len(cust_2)] print(hold_list) for element in hold_list: soapbody = f\"\"\"",
"dataextension2(): try: accessToken = token account_id = \"6291063\" de_name = \"Test_HoldOut_Group\" de_external_key =",
"dumps def auth(clientId: str, clientSecret: str, accountId:str ) -> requests.Response: end_point = \"https://mc4pytkknrp1gsz0v23m93b3055y.auth.marketingcloudapis.com/v2/token\"",
"<a:Action s:mustUnderstand=\"1\">Retrieve</a:Action> <a:To s:mustUnderstand=\"1\">https://webservice.s6.exacttarget.com/Service.asmx</a:To> <fueloauth xmlns=\"http://exacttarget.com\">{accessToken}</fueloauth> </s:Header> <s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <RetrieveRequestMsg xmlns=\"http://exacttarget.com/wsdl/partnerAPI\"> <RetrieveRequest>",
"print(\"UnProcessed List\",cust_list) n= len(cust_list)%10 print(n) cust_1 = [] for i in range(0,n): cust_1.append(cust_list.pop())",
"{'Content-type': 'application/json;charset=UTF-8'} payload = { \"grant_type\":\"client_credentials\", \"client_id\": clientId, \"client_secret\": clientSecret, \"account_id\": accountId, }",
"str, clientSecret: str, accountId:str ) -> requests.Response: end_point = \"https://mc4pytkknrp1gsz0v23m93b3055y.auth.marketingcloudapis.com/v2/token\" headers = {'Content-type':",
"with the Credentials Provided...\",e try: descbody =f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action",
"def auth(clientId: str, clientSecret: str, accountId:str ) -> requests.Response: end_point = \"https://mc4pytkknrp1gsz0v23m93b3055y.auth.marketingcloudapis.com/v2/token\" headers",
"<a:To s:mustUnderstand=\"1\">https://webservice.s6.exacttarget.com/Service.asmx</a:To> <fueloauth xmlms=\"http://exacttarget.com\">{accessToken}</fueloauth> </s:Header> <s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <UpdateRequest xmlns=\"http://exacttarget.com/wsdl/partnerAPI\"> <Objects xsi:type=\"DataExtensionObject\"> <PartnerKey",
"<Properties> <Property> <Name>Name</Name> <Value>{element}</Value> </Property> <Property> <Name>Flag</Name> <Value>False</Value> </Property> <Property> <Name>Status</Name> <Value>Hold Out</Value>",
"<Properties> <Property> <Name>Name</Name> <Value>{element}</Value> </Property> <Property> <Name>Flag</Name> <Value>True</Value> </Property> <Property> <Name>Status</Name> <Value>Processed</Value> </Property>",
"<CustomerKey>{de_external_key}</CustomerKey> <Properties> <Property> <Name>Name</Name> <Value>{element}</Value> </Property> <Property> <Name>Flag</Name> <Value>False</Value> </Property> <Property> <Name>Status</Name> <Value>Hold",
"<Name>Status</Name> <Value>Processed</Value> </Property> </Properties> </Objects> </UpdateRequest> </s:Body> </s:Envelope> \"\"\" url = \"https://webservice.s6.exacttarget.com/Service.asmx\" headers",
"s:mustUnderstand=\"1\">https://webservice.s6.exacttarget.com/Service.asmx</a:To> <fueloauth xmlms=\"http://exacttarget.com\">{accessToken}</fueloauth> </s:Header> <s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <UpdateRequest xmlns=\"http://exacttarget.com/wsdl/partnerAPI\"> <Objects xsi:type=\"DataExtensionObject\"> <PartnerKey xsi:nil=\"true\"/>",
"<Value>{element}</Value> </Property> <Property> <Name>Flag</Name> <Value>True</Value> </Property> <Property> <Name>Status</Name> <Value>Processed</Value> </Property> </Properties> </Objects> </UpdateRequest>",
"<a:To s:mustUnderstand=\"1\">https://webservice.s6.exacttarget.com/Service.asmx</a:To> <fueloauth xmlns=\"http://exacttarget.com\">{accessToken}</fueloauth> </s:Header> <s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <RetrieveRequestMsg xmlns=\"http://exacttarget.com/wsdl/partnerAPI\"> <RetrieveRequest> <ObjectType>DataExtensionObject[{de_name}]</ObjectType> <Properties>NAME</Properties>",
"s:mustUnderstand=\"1\">Retrieve</a:Action> <a:To s:mustUnderstand=\"1\">https://webservice.s6.exacttarget.com/Service.asmx</a:To> <fueloauth xmlns=\"http://exacttarget.com\">{accessToken}</fueloauth> </s:Header> <s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <RetrieveRequestMsg xmlns=\"http://exacttarget.com/wsdl/partnerAPI\"> <RetrieveRequest> <ObjectType>DataExtensionObject[{de_name}]</ObjectType>",
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <RetrieveRequestMsg xmlns=\"http://exacttarget.com/wsdl/partnerAPI\"> <RetrieveRequest> <ObjectType>DataExtensionObject[{de_name}]</ObjectType> <Properties>NAME</Properties> <Properties>Flag</Properties> <Properties>Status</Properties> <Filter xsi:type=\"SimpleFilterPart\"> <Property>Status</Property> <SimpleOperator>equals</SimpleOperator>",
"<Name>Name</Name> <Value>{element}</Value> </Property> <Property> <Name>Flag</Name> <Value>True</Value> </Property> <Property> <Name>Status</Name> <Value>Processed</Value> </Property> </Properties> </Objects>",
"clientSecret: str, accountId:str ) -> requests.Response: end_point = \"https://mc4pytkknrp1gsz0v23m93b3055y.auth.marketingcloudapis.com/v2/token\" headers = {'Content-type': 'application/json;charset=UTF-8'}",
"Out</Value> </Property> </Properties> </Objects> </UpdateRequest> </s:Body> </s:Envelope> \"\"\" url = \"https://webservice.s6.exacttarget.com/Service.asmx\" headers =",
"</a:ReplyTo> <a:To s:mustUnderstand=\"1\">https://webservice.s6.exacttarget.com/Service.asmx</a:To> <fueloauth xmlms=\"http://exacttarget.com\">{accessToken}</fueloauth> </s:Header> <s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <UpdateRequest xmlns=\"http://exacttarget.com/wsdl/partnerAPI\"> <Objects xsi:type=\"DataExtensionObject\">",
"<Objects xsi:type=\"DataExtensionObject\"> <PartnerKey xsi:nil=\"true\"/> <Client> <ID>{account_id}</ID> </Client> <ObjectID xsi:nil=\"true\"/> <CustomerKey>{de_external_key}</CustomerKey> <Properties> <Property> <Name>Name</Name>",
"not in cust_1] print(cust_2) if len(cust_2) > 9: # hold_list = cust_list[::10] hold_list",
"req.json() cred = auth('<KEY>','<KEY>','6291063') token = (cred[\"access_token\"]) print(\"Access Token : \",token) def dataextension2():",
"= descbody resp = requests.post(url, data=body, headers=headers) response = resp.text # print(response) data",
"n= len(cust_list)%10 print(n) cust_1 = [] for i in range(0,n): cust_1.append(cust_list.pop()) print(cust_1) cust_2",
"<CustomerKey>{de_external_key}</CustomerKey> <Properties> <Property> <Name>Name</Name> <Value>{element}</Value> </Property> <Property> <Name>Flag</Name> <Value>True</Value> </Property> <Property> <Name>Status</Name> <Value>Unprocessed</Value>",
"except Exception as e: return \"There is some problem with the Credentials Provided...\",e",
"</RetrieveRequest> </RetrieveRequestMsg> </s:Body> </s:Envelope> \"\"\" url = \"https://webservice.s6.exacttarget.com/Service.asmx\" headers = {'content-type': 'text/xml'} body",
"headers = {'content-type': 'text/xml'} body = descbody resp = requests.post(url, data=body, headers=headers) response",
"<Properties> <Property> <Name>Name</Name> <Value>{element}</Value> </Property> <Property> <Name>Flag</Name> <Value>True</Value> </Property> <Property> <Name>Status</Name> <Value>Unprocessed</Value> </Property>",
"\", holdout_rec) res_list = tuple(set(holdout_rec)^set(cust_2)) print(\"Without Holdout: \", res_list) for element in res_list:",
"xsi:nil=\"true\"/> <CustomerKey>{de_external_key}</CustomerKey> <Properties> <Property> <Name>Name</Name> <Value>{element}</Value> </Property> <Property> <Name>Flag</Name> <Value>False</Value> </Property> <Property> <Name>Status</Name>",
"resp.text # print(response) data = jxmlease.parse(response) status1=data[\"soap:Envelope\"][\"soap:Body\"][\"RetrieveResponseMsg\"][\"Results\"] status2 = loads(dumps(status1)) except Exception as",
"\"client_secret\": clientSecret, \"account_id\": accountId, } req = requests.post( end_point, payload, {\"headers\" : headers}",
"<Value>{element}</Value> </Property> <Property> <Name>Flag</Name> <Value>True</Value> </Property> <Property> <Name>Status</Name> <Value>Unprocessed</Value> </Property> </Properties> </Objects> </UpdateRequest>",
"</Objects> </UpdateRequest> </s:Body> </s:Envelope> \"\"\" url = \"https://webservice.s6.exacttarget.com/Service.asmx\" headers = {'content-type': 'text/xml'} body",
"<Value>True</Value> </Property> <Property> <Name>Status</Name> <Value>Unprocessed</Value> </Property> </Properties> </Objects> </UpdateRequest> </s:Body> </s:Envelope> \"\"\" url",
"descbody =f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action s:mustUnderstand=\"1\">Retrieve</a:Action> <a:To s:mustUnderstand=\"1\">https://webservice.s6.exacttarget.com/Service.asmx</a:To> <fueloauth xmlns=\"http://exacttarget.com\">{accessToken}</fueloauth>",
"e: return \"There are no records for holding out...\",e else: cust_list=[] # print(status2)",
"x*10<=len(cust_2)] print(hold_list) for element in hold_list: soapbody = f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">",
"<Value>Hold Out</Value> </Property> </Properties> </Objects> </UpdateRequest> </s:Body> </s:Envelope> \"\"\" url = \"https://webservice.s6.exacttarget.com/Service.asmx\" headers",
"hold_list = [cust_2[x*10-1] for x in range(1,len(cust_2)) if x*10<=len(cust_2)] print(hold_list) for element in",
"loads(dumps(status1)) except Exception as e: return \"There are no records for holding out...\",e",
"from operator import itemgetter import time from json import loads, dumps def auth(clientId:",
"<Properties>Flag</Properties> <Properties>Status</Properties> <Filter xsi:type=\"SimpleFilterPart\"> <Property>Status</Property> <SimpleOperator>equals</SimpleOperator> <Value>Unprocessed</Value> </Filter> </RetrieveRequest> </RetrieveRequestMsg> </s:Body> </s:Envelope> \"\"\"",
"= resp.text # print(response) data = jxmlease.parse(response) status1=data[\"soap:Envelope\"][\"soap:Body\"][\"RetrieveResponseMsg\"][\"Results\"] status2 = loads(dumps(status1)) except Exception",
"requests.post( end_point, payload, {\"headers\" : headers} # verify=False ) # req.close() return req.json()",
"resp = requests.post(url, data=body, headers=headers) print(resp.status_code) # print(resp.text) if len(cust_1) > 0: for",
"print(resp.text) if len(cust_1) > 0: for element in cust_1: soapbody = f\"\"\" <s:Envelope",
"<ObjectID xsi:nil=\"true\"/> <CustomerKey>{de_external_key}</CustomerKey> <Properties> <Property> <Name>Name</Name> <Value>{element}</Value> </Property> <Property> <Name>Flag</Name> <Value>True</Value> </Property> <Property>",
"auth(clientId: str, clientSecret: str, accountId:str ) -> requests.Response: end_point = \"https://mc4pytkknrp1gsz0v23m93b3055y.auth.marketingcloudapis.com/v2/token\" headers =",
"resp = requests.post(url, data=body, headers=headers) print(resp.status_code) # print(resp.text) holdout_rec = hold_list # print(\"HoldOut",
"} req = requests.post( end_point, payload, {\"headers\" : headers} # verify=False ) #",
"i in range(0,n): cust_1.append(cust_list.pop()) print(cust_1) cust_2 = [ele for ele in cust_list if",
"= requests.post(url, data=body, headers=headers) print(resp.status_code) # print(resp.text) holdout_rec = hold_list # print(\"HoldOut Records:",
"</s:Header> <s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <UpdateRequest xmlns=\"http://exacttarget.com/wsdl/partnerAPI\"> <Objects xsi:type=\"DataExtensionObject\"> <PartnerKey xsi:nil=\"true\"/> <Client> <ID>{account_id}</ID> </Client>",
"payload = { \"grant_type\":\"client_credentials\", \"client_id\": clientId, \"client_secret\": clientSecret, \"account_id\": accountId, } req =",
"<Property> <Name>Name</Name> <Value>{element}</Value> </Property> <Property> <Name>Flag</Name> <Value>False</Value> </Property> <Property> <Name>Status</Name> <Value>Hold Out</Value> </Property>",
"for i in range(0,n): cust_1.append(cust_list.pop()) print(cust_1) cust_2 = [ele for ele in cust_list",
"</Client> <ObjectID xsi:nil=\"true\"/> <CustomerKey>{de_external_key}</CustomerKey> <Properties> <Property> <Name>Name</Name> <Value>{element}</Value> </Property> <Property> <Name>Flag</Name> <Value>False</Value> </Property>",
"random from operator import itemgetter import time from json import loads, dumps def",
"</Property> </Properties> </Objects> </UpdateRequest> </s:Body> </s:Envelope> \"\"\" url = \"https://webservice.s6.exacttarget.com/Service.asmx\" headers = {'content-type':",
"<Value>Processed</Value> </Property> </Properties> </Objects> </UpdateRequest> </s:Body> </s:Envelope> \"\"\" url = \"https://webservice.s6.exacttarget.com/Service.asmx\" headers =",
"Credentials Provided...\",e try: descbody =f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action s:mustUnderstand=\"1\">Retrieve</a:Action> <a:To",
"headers = {'content-type': 'text/xml'} body = soapbody resp = requests.post(url, data=body, headers=headers) print(resp.status_code)",
"xmlms=\"http://exacttarget.com\">{accessToken}</fueloauth> </s:Header> <s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <UpdateRequest xmlns=\"http://exacttarget.com/wsdl/partnerAPI\"> <Objects xsi:type=\"DataExtensionObject\"> <PartnerKey xsi:nil=\"true\"/> <Client> <ID>{account_id}</ID>",
"<Name>Flag</Name> <Value>True</Value> </Property> <Property> <Name>Status</Name> <Value>Unprocessed</Value> </Property> </Properties> </Objects> </UpdateRequest> </s:Body> </s:Envelope> \"\"\"",
"<s:Header> <a:Action s:mustUnderstand=\"1\">Retrieve</a:Action> <a:To s:mustUnderstand=\"1\">https://webservice.s6.exacttarget.com/Service.asmx</a:To> <fueloauth xmlns=\"http://exacttarget.com\">{accessToken}</fueloauth> </s:Header> <s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <RetrieveRequestMsg xmlns=\"http://exacttarget.com/wsdl/partnerAPI\">",
"<filename>public/pylib/holdoutgroup.py import requests import json import xmltodict import datetime from math import ceil",
"for element in cust_1: soapbody = f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action",
"= f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action s:mustUnderstand=\"1\">Update</a:Action> <a:MessageID>urn:uuid:7e0cca04-57bd-4481-864c-6ea8039d2ea0</a:MessageID> <a:ReplyTo> <a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address> </a:ReplyTo>",
"de_external_key = \"5E4FE032-6C0E-42E8-8B81-99F167D7DFC9\" except Exception as e: return \"There is some problem with",
"element in hold_list: soapbody = f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action s:mustUnderstand=\"1\">Update</a:Action>",
"hold_list # print(\"HoldOut Records: \", holdout_rec) res_list = tuple(set(holdout_rec)^set(cust_2)) print(\"Without Holdout: \", res_list)",
"# print(resp.text) if len(cust_1) > 0: for element in cust_1: soapbody = f\"\"\"",
"xmlns=\"http://exacttarget.com/wsdl/partnerAPI\"> <Objects xsi:type=\"DataExtensionObject\"> <PartnerKey xsi:nil=\"true\"/> <Client> <ID>{account_id}</ID> </Client> <ObjectID xsi:nil=\"true\"/> <CustomerKey>{de_external_key}</CustomerKey> <Properties> <Property>",
"the Credentials Provided...\",e try: descbody =f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action s:mustUnderstand=\"1\">Retrieve</a:Action>",
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <UpdateRequest xmlns=\"http://exacttarget.com/wsdl/partnerAPI\"> <Objects xsi:type=\"DataExtensionObject\"> <PartnerKey xsi:nil=\"true\"/> <Client> <ID>{account_id}</ID> </Client> <ObjectID xsi:nil=\"true\"/>",
"in range(1,len(cust_2)) if x*10<=len(cust_2)] print(hold_list) for element in hold_list: soapbody = f\"\"\" <s:Envelope",
"\"6291063\" de_name = \"Test_HoldOut_Group\" de_external_key = \"5E4FE032-6C0E-42E8-8B81-99F167D7DFC9\" except Exception as e: return \"There",
"cust_list.append(cust_key) print(\"UnProcessed List\",cust_list) n= len(cust_list)%10 print(n) cust_1 = [] for i in range(0,n):",
"<Property> <Name>Status</Name> <Value>Processed</Value> </Property> </Properties> </Objects> </UpdateRequest> </s:Body> </s:Envelope> \"\"\" url = \"https://webservice.s6.exacttarget.com/Service.asmx\"",
"\"grant_type\":\"client_credentials\", \"client_id\": clientId, \"client_secret\": clientSecret, \"account_id\": accountId, } req = requests.post( end_point, payload,",
"holdout_rec = hold_list # print(\"HoldOut Records: \", holdout_rec) res_list = tuple(set(holdout_rec)^set(cust_2)) print(\"Without Holdout:",
"holding out...\",e else: cust_list=[] # print(status2) for item in status2: cust_key= item[\"Properties\"][\"Property\"][0]['Value'] cust_list.append(cust_key)",
"if len(cust_1) > 0: for element in cust_1: soapbody = f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\"",
"element in cust_1: soapbody = f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action s:mustUnderstand=\"1\">Update</a:Action>",
"datetime from math import ceil import jxmlease import operator import random from operator",
"\"https://webservice.s6.exacttarget.com/Service.asmx\" headers = {'content-type': 'text/xml'} body = descbody resp = requests.post(url, data=body, headers=headers)",
"</s:Header> <s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <RetrieveRequestMsg xmlns=\"http://exacttarget.com/wsdl/partnerAPI\"> <RetrieveRequest> <ObjectType>DataExtensionObject[{de_name}]</ObjectType> <Properties>NAME</Properties> <Properties>Flag</Properties> <Properties>Status</Properties> <Filter xsi:type=\"SimpleFilterPart\">",
"<RetrieveRequestMsg xmlns=\"http://exacttarget.com/wsdl/partnerAPI\"> <RetrieveRequest> <ObjectType>DataExtensionObject[{de_name}]</ObjectType> <Properties>NAME</Properties> <Properties>Flag</Properties> <Properties>Status</Properties> <Filter xsi:type=\"SimpleFilterPart\"> <Property>Status</Property> <SimpleOperator>equals</SimpleOperator> <Value>Unprocessed</Value> </Filter>",
"print(cust_1) cust_2 = [ele for ele in cust_list if ele not in cust_1]",
"</s:Envelope> \"\"\" url = \"https://webservice.s6.exacttarget.com/Service.asmx\" headers = {'content-type': 'text/xml'} body = soapbody resp",
"status2: cust_key= item[\"Properties\"][\"Property\"][0]['Value'] cust_list.append(cust_key) print(\"UnProcessed List\",cust_list) n= len(cust_list)%10 print(n) cust_1 = [] for",
"import itemgetter import time from json import loads, dumps def auth(clientId: str, clientSecret:",
"as e: return \"There is some problem with the Credentials Provided...\",e try: descbody",
"cred = auth('<KEY>','<KEY>','6291063') token = (cred[\"access_token\"]) print(\"Access Token : \",token) def dataextension2(): try:",
"<Properties>NAME</Properties> <Properties>Flag</Properties> <Properties>Status</Properties> <Filter xsi:type=\"SimpleFilterPart\"> <Property>Status</Property> <SimpleOperator>equals</SimpleOperator> <Value>Unprocessed</Value> </Filter> </RetrieveRequest> </RetrieveRequestMsg> </s:Body> </s:Envelope>",
"requests.post(url, data=body, headers=headers) response = resp.text # print(response) data = jxmlease.parse(response) status1=data[\"soap:Envelope\"][\"soap:Body\"][\"RetrieveResponseMsg\"][\"Results\"] status2",
"<a:Action s:mustUnderstand=\"1\">Update</a:Action> <a:MessageID>urn:uuid:7e0cca04-57bd-4481-864c-6ea8039d2ea0</a:MessageID> <a:ReplyTo> <a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address> </a:ReplyTo> <a:To s:mustUnderstand=\"1\">https://webservice.s6.exacttarget.com/Service.asmx</a:To> <fueloauth xmlms=\"http://exacttarget.com\">{accessToken}</fueloauth> </s:Header> <s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"",
"# hold_list = cust_list[::10] hold_list = [cust_2[x*10-1] for x in range(1,len(cust_2)) if x*10<=len(cust_2)]",
"# print(response) data = jxmlease.parse(response) status1=data[\"soap:Envelope\"][\"soap:Body\"][\"RetrieveResponseMsg\"][\"Results\"] status2 = loads(dumps(status1)) except Exception as e:",
"xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action s:mustUnderstand=\"1\">Update</a:Action> <a:MessageID>urn:uuid:7e0cca04-57bd-4481-864c-6ea8039d2ea0</a:MessageID> <a:ReplyTo> <a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address> </a:ReplyTo> <a:To s:mustUnderstand=\"1\">https://webservice.s6.exacttarget.com/Service.asmx</a:To> <fueloauth xmlms=\"http://exacttarget.com\">{accessToken}</fueloauth>",
"data=body, headers=headers) response = resp.text # print(response) data = jxmlease.parse(response) status1=data[\"soap:Envelope\"][\"soap:Body\"][\"RetrieveResponseMsg\"][\"Results\"] status2 =",
"body = descbody resp = requests.post(url, data=body, headers=headers) response = resp.text # print(response)",
"body = soapbody resp = requests.post(url, data=body, headers=headers) print(resp.status_code) # print(resp.text) holdout_rec =",
"loads, dumps def auth(clientId: str, clientSecret: str, accountId:str ) -> requests.Response: end_point =",
"len(cust_1) > 0: for element in cust_1: soapbody = f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\"",
"Exception as e: return \"There is some problem with the Credentials Provided...\",e try:",
"xmlns=\"http://exacttarget.com\">{accessToken}</fueloauth> </s:Header> <s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <RetrieveRequestMsg xmlns=\"http://exacttarget.com/wsdl/partnerAPI\"> <RetrieveRequest> <ObjectType>DataExtensionObject[{de_name}]</ObjectType> <Properties>NAME</Properties> <Properties>Flag</Properties> <Properties>Status</Properties> <Filter",
"import loads, dumps def auth(clientId: str, clientSecret: str, accountId:str ) -> requests.Response: end_point",
"<Property>Status</Property> <SimpleOperator>equals</SimpleOperator> <Value>Unprocessed</Value> </Filter> </RetrieveRequest> </RetrieveRequestMsg> </s:Body> </s:Envelope> \"\"\" url = \"https://webservice.s6.exacttarget.com/Service.asmx\" headers",
"Exception as e: return \"There are no records for holding out...\",e else: cust_list=[]",
"List\",cust_list) n= len(cust_list)%10 print(n) cust_1 = [] for i in range(0,n): cust_1.append(cust_list.pop()) print(cust_1)",
"'text/xml'} body = soapbody resp = requests.post(url, data=body, headers=headers) print(resp.status_code) # print(resp.text) return",
"\"client_id\": clientId, \"client_secret\": clientSecret, \"account_id\": accountId, } req = requests.post( end_point, payload, {\"headers\"",
"jxmlease import operator import random from operator import itemgetter import time from json",
"<SimpleOperator>equals</SimpleOperator> <Value>Unprocessed</Value> </Filter> </RetrieveRequest> </RetrieveRequestMsg> </s:Body> </s:Envelope> \"\"\" url = \"https://webservice.s6.exacttarget.com/Service.asmx\" headers =",
"xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action s:mustUnderstand=\"1\">Retrieve</a:Action> <a:To s:mustUnderstand=\"1\">https://webservice.s6.exacttarget.com/Service.asmx</a:To> <fueloauth xmlns=\"http://exacttarget.com\">{accessToken}</fueloauth> </s:Header> <s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"",
"xmltodict import datetime from math import ceil import jxmlease import operator import random",
"# print(\"HoldOut Records: \", holdout_rec) res_list = tuple(set(holdout_rec)^set(cust_2)) print(\"Without Holdout: \", res_list) for",
"descbody resp = requests.post(url, data=body, headers=headers) response = resp.text # print(response) data =",
"</Filter> </RetrieveRequest> </RetrieveRequestMsg> </s:Body> </s:Envelope> \"\"\" url = \"https://webservice.s6.exacttarget.com/Service.asmx\" headers = {'content-type': 'text/xml'}",
"</Property> <Property> <Name>Flag</Name> <Value>True</Value> </Property> <Property> <Name>Status</Name> <Value>Processed</Value> </Property> </Properties> </Objects> </UpdateRequest> </s:Body>",
"str, accountId:str ) -> requests.Response: end_point = \"https://mc4pytkknrp1gsz0v23m93b3055y.auth.marketingcloudapis.com/v2/token\" headers = {'Content-type': 'application/json;charset=UTF-8'} payload",
"if len(cust_2) > 9: # hold_list = cust_list[::10] hold_list = [cust_2[x*10-1] for x",
"<Filter xsi:type=\"SimpleFilterPart\"> <Property>Status</Property> <SimpleOperator>equals</SimpleOperator> <Value>Unprocessed</Value> </Filter> </RetrieveRequest> </RetrieveRequestMsg> </s:Body> </s:Envelope> \"\"\" url =",
"# print(resp.text) holdout_rec = hold_list # print(\"HoldOut Records: \", holdout_rec) res_list = tuple(set(holdout_rec)^set(cust_2))",
"xsi:type=\"SimpleFilterPart\"> <Property>Status</Property> <SimpleOperator>equals</SimpleOperator> <Value>Unprocessed</Value> </Filter> </RetrieveRequest> </RetrieveRequestMsg> </s:Body> </s:Envelope> \"\"\" url = \"https://webservice.s6.exacttarget.com/Service.asmx\"",
"cust_1.append(cust_list.pop()) print(cust_1) cust_2 = [ele for ele in cust_list if ele not in",
"are no records for holding out...\",e else: cust_list=[] # print(status2) for item in",
"<PartnerKey xsi:nil=\"true\"/> <Client> <ID>{account_id}</ID> </Client> <ObjectID xsi:nil=\"true\"/> <CustomerKey>{de_external_key}</CustomerKey> <Properties> <Property> <Name>Name</Name> <Value>{element}</Value> </Property>",
"<s:Header> <a:Action s:mustUnderstand=\"1\">Update</a:Action> <a:MessageID>urn:uuid:7e0cca04-57bd-4481-864c-6ea8039d2ea0</a:MessageID> <a:ReplyTo> <a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address> </a:ReplyTo> <a:To s:mustUnderstand=\"1\">https://webservice.s6.exacttarget.com/Service.asmx</a:To> <fueloauth xmlms=\"http://exacttarget.com\">{accessToken}</fueloauth> </s:Header> <s:Body",
"xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action s:mustUnderstand=\"1\">Retrieve</a:Action> <a:To s:mustUnderstand=\"1\">https://webservice.s6.exacttarget.com/Service.asmx</a:To> <fueloauth xmlns=\"http://exacttarget.com\">{accessToken}</fueloauth> </s:Header> <s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <RetrieveRequestMsg",
"<a:ReplyTo> <a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address> </a:ReplyTo> <a:To s:mustUnderstand=\"1\">https://webservice.s6.exacttarget.com/Service.asmx</a:To> <fueloauth xmlms=\"http://exacttarget.com\">{accessToken}</fueloauth> </s:Header> <s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <UpdateRequest xmlns=\"http://exacttarget.com/wsdl/partnerAPI\">",
"# req.close() return req.json() cred = auth('<KEY>','<KEY>','6291063') token = (cred[\"access_token\"]) print(\"Access Token :",
"-> requests.Response: end_point = \"https://mc4pytkknrp1gsz0v23m93b3055y.auth.marketingcloudapis.com/v2/token\" headers = {'Content-type': 'application/json;charset=UTF-8'} payload = { \"grant_type\":\"client_credentials\",",
"xsi:nil=\"true\"/> <Client> <ID>{account_id}</ID> </Client> <ObjectID xsi:nil=\"true\"/> <CustomerKey>{de_external_key}</CustomerKey> <Properties> <Property> <Name>Name</Name> <Value>{element}</Value> </Property> <Property>",
"no records for holding out...\",e else: cust_list=[] # print(status2) for item in status2:",
"item[\"Properties\"][\"Property\"][0]['Value'] cust_list.append(cust_key) print(\"UnProcessed List\",cust_list) n= len(cust_list)%10 print(n) cust_1 = [] for i in",
"req = requests.post( end_point, payload, {\"headers\" : headers} # verify=False ) # req.close()",
"print(n) cust_1 = [] for i in range(0,n): cust_1.append(cust_list.pop()) print(cust_1) cust_2 = [ele",
"operator import itemgetter import time from json import loads, dumps def auth(clientId: str,",
"def dataextension2(): try: accessToken = token account_id = \"6291063\" de_name = \"Test_HoldOut_Group\" de_external_key",
"for holding out...\",e else: cust_list=[] # print(status2) for item in status2: cust_key= item[\"Properties\"][\"Property\"][0]['Value']",
"print(hold_list) for element in hold_list: soapbody = f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header>",
"[ele for ele in cust_list if ele not in cust_1] print(cust_2) if len(cust_2)",
"url = \"https://webservice.s6.exacttarget.com/Service.asmx\" headers = {'content-type': 'text/xml'} body = soapbody resp = requests.post(url,",
"= \"https://webservice.s6.exacttarget.com/Service.asmx\" headers = {'content-type': 'text/xml'} body = descbody resp = requests.post(url, data=body,",
"try: descbody =f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"> <s:Header> <a:Action s:mustUnderstand=\"1\">Retrieve</a:Action> <a:To s:mustUnderstand=\"1\">https://webservice.s6.exacttarget.com/Service.asmx</a:To> <fueloauth",
"<Value>{element}</Value> </Property> <Property> <Name>Flag</Name> <Value>False</Value> </Property> <Property> <Name>Status</Name> <Value>Hold Out</Value> </Property> </Properties> </Objects>",
"<Name>Name</Name> <Value>{element}</Value> </Property> <Property> <Name>Flag</Name> <Value>False</Value> </Property> <Property> <Name>Status</Name> <Value>Hold Out</Value> </Property> </Properties>",
"print(resp.text) holdout_rec = hold_list # print(\"HoldOut Records: \", holdout_rec) res_list = tuple(set(holdout_rec)^set(cust_2)) print(\"Without",
"<Property> <Name>Status</Name> <Value>Unprocessed</Value> </Property> </Properties> </Objects> </UpdateRequest> </s:Body> </s:Envelope> \"\"\" url = \"https://webservice.s6.exacttarget.com/Service.asmx\"",
"\"There is some problem with the Credentials Provided...\",e try: descbody =f\"\"\" <s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\"",
"= \"5E4FE032-6C0E-42E8-8B81-99F167D7DFC9\" except Exception as e: return \"There is some problem with the",
"in cust_1] print(cust_2) if len(cust_2) > 9: # hold_list = cust_list[::10] hold_list ="
] |
[
"headers={'How-Many': '1'}) r = resp.json() if len(r) == 0: print('job stream not found')",
"the engine as defined in the TWSz Connector', required=True, metavar=\"<engine_name>\") parser.add_argument('-j','--jsName', help='job stream',",
"{\"inputArrivalTime\": now} # now we can submit the js print \"submit parameters: \"",
"TWSz plan') parser.add_argument('-e','--engineName', help='name of the engine as defined in the TWSz Connector',",
"# now we can submit the js print \"submit parameters: \" +str(submit) resp",
"----------------------------------------------------- conn = waconn.WAConn('waconn.ini','/twsz/v1/'+args.engineName) # ----------------------------------------------------- # Query the model and get the",
"js id is: \" + jsId) # ----------------------------------------------------- # Now submit the jobstream",
"# Now submit the jobstream to the plan # ----------------------------------------------------- submit = {\"inputArrivalTime\":",
"parser.add_argument('-e','--engineName', help='name of the engine as defined in the TWSz Connector', required=True, metavar=\"<engine_name>\")",
"to the TWSz plan') parser.add_argument('-e','--engineName', help='name of the engine as defined in the",
"= conn.post('/plan/current/jobstream/' + jsId + '/action/submit_jobstream', json=submit) r = resp.json() for js in",
"and get the js id # ----------------------------------------------------- resp = conn.post('/model/jobstream/header/query', json={\"filters\": {\"jobstreamFilter\": {\"jobStreamName\":",
"= datetime.datetime.utcnow().isoformat() # ----------------------------------------------------- # Intialize the client utility module # ----------------------------------------------------- conn",
"reserved. # * Trademark of HCL Technologies Limited ############################################################################# import waconn import argparse",
"# * Trademark of HCL Technologies Limited ############################################################################# import waconn import argparse import",
"Copyright HCL Technologies Ltd. 2017, 2018 All rights reserved. # * Trademark of",
"jobstream to the plan # ----------------------------------------------------- submit = {\"inputArrivalTime\": now} # now we",
"'1'}) r = resp.json() if len(r) == 0: print('job stream not found') exit(2)",
"Define and parse command line arguments # ----------------------------------------------------- parser = argparse.ArgumentParser(description='Submit a job",
"# ----------------------------------------------------- # Now submit the jobstream to the plan # ----------------------------------------------------- submit",
"required=True, metavar=\"<engine_name>\") parser.add_argument('-j','--jsName', help='job stream', required=True, metavar=\"<job_stream_name>\") args = parser.parse_args() now = datetime.datetime.utcnow().isoformat()",
"conn = waconn.WAConn('waconn.ini','/twsz/v1/'+args.engineName) # ----------------------------------------------------- # Query the model and get the js",
"\" +str(submit) resp = conn.post('/plan/current/jobstream/' + jsId + '/action/submit_jobstream', json=submit) r = resp.json()",
"----------------------------------------------------- # Intialize the client utility module # ----------------------------------------------------- conn = waconn.WAConn('waconn.ini','/twsz/v1/'+args.engineName) #",
"Licensed Materials - Property of HCL* # (C) Copyright HCL Technologies Ltd. 2017,",
"js id # ----------------------------------------------------- resp = conn.post('/model/jobstream/header/query', json={\"filters\": {\"jobstreamFilter\": {\"jobStreamName\": args.jsName,\"validIn\": now}}}, headers={'How-Many':",
"now} # now we can submit the js print \"submit parameters: \" +str(submit)",
"HCL Technologies Limited ############################################################################# import waconn import argparse import datetime # ----------------------------------------------------- #",
"{\"jobStreamName\": args.jsName,\"validIn\": now}}}, headers={'How-Many': '1'}) r = resp.json() if len(r) == 0: print('job",
"the js id # ----------------------------------------------------- resp = conn.post('/model/jobstream/header/query', json={\"filters\": {\"jobstreamFilter\": {\"jobStreamName\": args.jsName,\"validIn\": now}}},",
"of HCL* # (C) Copyright HCL Technologies Ltd. 2017, 2018 All rights reserved.",
"in the TWSz Connector', required=True, metavar=\"<engine_name>\") parser.add_argument('-j','--jsName', help='job stream', required=True, metavar=\"<job_stream_name>\") args =",
"# ----------------------------------------------------- # Query the model and get the js id # -----------------------------------------------------",
"plan') parser.add_argument('-e','--engineName', help='name of the engine as defined in the TWSz Connector', required=True,",
"conn.post('/model/jobstream/header/query', json={\"filters\": {\"jobstreamFilter\": {\"jobStreamName\": args.jsName,\"validIn\": now}}}, headers={'How-Many': '1'}) r = resp.json() if len(r)",
"metavar=\"<engine_name>\") parser.add_argument('-j','--jsName', help='job stream', required=True, metavar=\"<job_stream_name>\") args = parser.parse_args() now = datetime.datetime.utcnow().isoformat() #",
"= conn.post('/model/jobstream/header/query', json={\"filters\": {\"jobstreamFilter\": {\"jobStreamName\": args.jsName,\"validIn\": now}}}, headers={'How-Many': '1'}) r = resp.json() if",
"= parser.parse_args() now = datetime.datetime.utcnow().isoformat() # ----------------------------------------------------- # Intialize the client utility module",
"= {\"inputArrivalTime\": now} # now we can submit the js print \"submit parameters:",
"# (C) Copyright HCL Technologies Ltd. 2017, 2018 All rights reserved. # *",
"\"submit parameters: \" +str(submit) resp = conn.post('/plan/current/jobstream/' + jsId + '/action/submit_jobstream', json=submit) r",
"import argparse import datetime # ----------------------------------------------------- # Define and parse command line arguments",
"# Query the model and get the js id # ----------------------------------------------------- resp =",
"js print \"submit parameters: \" +str(submit) resp = conn.post('/plan/current/jobstream/' + jsId + '/action/submit_jobstream',",
"#!/usr/bin/python ############################################################################# # Licensed Materials - Property of HCL* # (C) Copyright HCL",
"args = parser.parse_args() now = datetime.datetime.utcnow().isoformat() # ----------------------------------------------------- # Intialize the client utility",
"waconn import argparse import datetime # ----------------------------------------------------- # Define and parse command line",
"parse command line arguments # ----------------------------------------------------- parser = argparse.ArgumentParser(description='Submit a job stream to",
"HCL Technologies Ltd. 2017, 2018 All rights reserved. # * Trademark of HCL",
"+ '/action/submit_jobstream', json=submit) r = resp.json() for js in r: print ('Submitted: '+js)",
"we can submit the js print \"submit parameters: \" +str(submit) resp = conn.post('/plan/current/jobstream/'",
"+ jsId) # ----------------------------------------------------- # Now submit the jobstream to the plan #",
"Query the model and get the js id # ----------------------------------------------------- resp = conn.post('/model/jobstream/header/query',",
"import waconn import argparse import datetime # ----------------------------------------------------- # Define and parse command",
"now}}}, headers={'How-Many': '1'}) r = resp.json() if len(r) == 0: print('job stream not",
"of HCL Technologies Limited ############################################################################# import waconn import argparse import datetime # -----------------------------------------------------",
"== 0: print('job stream not found') exit(2) jsId=r[0][\"id\"] print(\"the js id is: \"",
"engine as defined in the TWSz Connector', required=True, metavar=\"<engine_name>\") parser.add_argument('-j','--jsName', help='job stream', required=True,",
"of the engine as defined in the TWSz Connector', required=True, metavar=\"<engine_name>\") parser.add_argument('-j','--jsName', help='job",
"the plan # ----------------------------------------------------- submit = {\"inputArrivalTime\": now} # now we can submit",
"+str(submit) resp = conn.post('/plan/current/jobstream/' + jsId + '/action/submit_jobstream', json=submit) r = resp.json() for",
"required=True, metavar=\"<job_stream_name>\") args = parser.parse_args() now = datetime.datetime.utcnow().isoformat() # ----------------------------------------------------- # Intialize the",
"HCL* # (C) Copyright HCL Technologies Ltd. 2017, 2018 All rights reserved. #",
"parser.parse_args() now = datetime.datetime.utcnow().isoformat() # ----------------------------------------------------- # Intialize the client utility module #",
"is: \" + jsId) # ----------------------------------------------------- # Now submit the jobstream to the",
"# ----------------------------------------------------- resp = conn.post('/model/jobstream/header/query', json={\"filters\": {\"jobstreamFilter\": {\"jobStreamName\": args.jsName,\"validIn\": now}}}, headers={'How-Many': '1'}) r",
"can submit the js print \"submit parameters: \" +str(submit) resp = conn.post('/plan/current/jobstream/' +",
"submit = {\"inputArrivalTime\": now} # now we can submit the js print \"submit",
"Intialize the client utility module # ----------------------------------------------------- conn = waconn.WAConn('waconn.ini','/twsz/v1/'+args.engineName) # ----------------------------------------------------- #",
"stream to the TWSz plan') parser.add_argument('-e','--engineName', help='name of the engine as defined in",
"json={\"filters\": {\"jobstreamFilter\": {\"jobStreamName\": args.jsName,\"validIn\": now}}}, headers={'How-Many': '1'}) r = resp.json() if len(r) ==",
"the TWSz Connector', required=True, metavar=\"<engine_name>\") parser.add_argument('-j','--jsName', help='job stream', required=True, metavar=\"<job_stream_name>\") args = parser.parse_args()",
"argparse.ArgumentParser(description='Submit a job stream to the TWSz plan') parser.add_argument('-e','--engineName', help='name of the engine",
"jsId + '/action/submit_jobstream', json=submit) r = resp.json() for js in r: print ('Submitted:",
"help='name of the engine as defined in the TWSz Connector', required=True, metavar=\"<engine_name>\") parser.add_argument('-j','--jsName',",
"# Define and parse command line arguments # ----------------------------------------------------- parser = argparse.ArgumentParser(description='Submit a",
"conn.post('/plan/current/jobstream/' + jsId + '/action/submit_jobstream', json=submit) r = resp.json() for js in r:",
"metavar=\"<job_stream_name>\") args = parser.parse_args() now = datetime.datetime.utcnow().isoformat() # ----------------------------------------------------- # Intialize the client",
"parser.add_argument('-j','--jsName', help='job stream', required=True, metavar=\"<job_stream_name>\") args = parser.parse_args() now = datetime.datetime.utcnow().isoformat() # -----------------------------------------------------",
"- Property of HCL* # (C) Copyright HCL Technologies Ltd. 2017, 2018 All",
"############################################################################# # Licensed Materials - Property of HCL* # (C) Copyright HCL Technologies",
"All rights reserved. # * Trademark of HCL Technologies Limited ############################################################################# import waconn",
"# ----------------------------------------------------- # Intialize the client utility module # ----------------------------------------------------- conn = waconn.WAConn('waconn.ini','/twsz/v1/'+args.engineName)",
"Property of HCL* # (C) Copyright HCL Technologies Ltd. 2017, 2018 All rights",
"rights reserved. # * Trademark of HCL Technologies Limited ############################################################################# import waconn import",
"2017, 2018 All rights reserved. # * Trademark of HCL Technologies Limited #############################################################################",
"----------------------------------------------------- # Now submit the jobstream to the plan # ----------------------------------------------------- submit =",
"now we can submit the js print \"submit parameters: \" +str(submit) resp =",
"stream not found') exit(2) jsId=r[0][\"id\"] print(\"the js id is: \" + jsId) #",
"Technologies Limited ############################################################################# import waconn import argparse import datetime # ----------------------------------------------------- # Define",
"TWSz Connector', required=True, metavar=\"<engine_name>\") parser.add_argument('-j','--jsName', help='job stream', required=True, metavar=\"<job_stream_name>\") args = parser.parse_args() now",
"----------------------------------------------------- submit = {\"inputArrivalTime\": now} # now we can submit the js print",
"# ----------------------------------------------------- # Define and parse command line arguments # ----------------------------------------------------- parser =",
"print \"submit parameters: \" +str(submit) resp = conn.post('/plan/current/jobstream/' + jsId + '/action/submit_jobstream', json=submit)",
"# ----------------------------------------------------- parser = argparse.ArgumentParser(description='Submit a job stream to the TWSz plan') parser.add_argument('-e','--engineName',",
"now = datetime.datetime.utcnow().isoformat() # ----------------------------------------------------- # Intialize the client utility module # -----------------------------------------------------",
"module # ----------------------------------------------------- conn = waconn.WAConn('waconn.ini','/twsz/v1/'+args.engineName) # ----------------------------------------------------- # Query the model and",
"resp.json() if len(r) == 0: print('job stream not found') exit(2) jsId=r[0][\"id\"] print(\"the js",
"jsId) # ----------------------------------------------------- # Now submit the jobstream to the plan # -----------------------------------------------------",
"datetime.datetime.utcnow().isoformat() # ----------------------------------------------------- # Intialize the client utility module # ----------------------------------------------------- conn =",
"############################################################################# import waconn import argparse import datetime # ----------------------------------------------------- # Define and parse",
"and parse command line arguments # ----------------------------------------------------- parser = argparse.ArgumentParser(description='Submit a job stream",
"submit the jobstream to the plan # ----------------------------------------------------- submit = {\"inputArrivalTime\": now} #",
"print(\"the js id is: \" + jsId) # ----------------------------------------------------- # Now submit the",
"defined in the TWSz Connector', required=True, metavar=\"<engine_name>\") parser.add_argument('-j','--jsName', help='job stream', required=True, metavar=\"<job_stream_name>\") args",
"0: print('job stream not found') exit(2) jsId=r[0][\"id\"] print(\"the js id is: \" +",
"help='job stream', required=True, metavar=\"<job_stream_name>\") args = parser.parse_args() now = datetime.datetime.utcnow().isoformat() # ----------------------------------------------------- #",
"# ----------------------------------------------------- conn = waconn.WAConn('waconn.ini','/twsz/v1/'+args.engineName) # ----------------------------------------------------- # Query the model and get",
"* Trademark of HCL Technologies Limited ############################################################################# import waconn import argparse import datetime",
"----------------------------------------------------- resp = conn.post('/model/jobstream/header/query', json={\"filters\": {\"jobstreamFilter\": {\"jobStreamName\": args.jsName,\"validIn\": now}}}, headers={'How-Many': '1'}) r =",
"Connector', required=True, metavar=\"<engine_name>\") parser.add_argument('-j','--jsName', help='job stream', required=True, metavar=\"<job_stream_name>\") args = parser.parse_args() now =",
"command line arguments # ----------------------------------------------------- parser = argparse.ArgumentParser(description='Submit a job stream to the",
"exit(2) jsId=r[0][\"id\"] print(\"the js id is: \" + jsId) # ----------------------------------------------------- # Now",
"as defined in the TWSz Connector', required=True, metavar=\"<engine_name>\") parser.add_argument('-j','--jsName', help='job stream', required=True, metavar=\"<job_stream_name>\")",
"args.jsName,\"validIn\": now}}}, headers={'How-Many': '1'}) r = resp.json() if len(r) == 0: print('job stream",
"= waconn.WAConn('waconn.ini','/twsz/v1/'+args.engineName) # ----------------------------------------------------- # Query the model and get the js id",
"the js print \"submit parameters: \" +str(submit) resp = conn.post('/plan/current/jobstream/' + jsId +",
"----------------------------------------------------- parser = argparse.ArgumentParser(description='Submit a job stream to the TWSz plan') parser.add_argument('-e','--engineName', help='name",
"jsId=r[0][\"id\"] print(\"the js id is: \" + jsId) # ----------------------------------------------------- # Now submit",
"the TWSz plan') parser.add_argument('-e','--engineName', help='name of the engine as defined in the TWSz",
"+ jsId + '/action/submit_jobstream', json=submit) r = resp.json() for js in r: print",
"import datetime # ----------------------------------------------------- # Define and parse command line arguments # -----------------------------------------------------",
"get the js id # ----------------------------------------------------- resp = conn.post('/model/jobstream/header/query', json={\"filters\": {\"jobstreamFilter\": {\"jobStreamName\": args.jsName,\"validIn\":",
"len(r) == 0: print('job stream not found') exit(2) jsId=r[0][\"id\"] print(\"the js id is:",
"----------------------------------------------------- # Query the model and get the js id # ----------------------------------------------------- resp",
"resp = conn.post('/plan/current/jobstream/' + jsId + '/action/submit_jobstream', json=submit) r = resp.json() for js",
"Technologies Ltd. 2017, 2018 All rights reserved. # * Trademark of HCL Technologies",
"plan # ----------------------------------------------------- submit = {\"inputArrivalTime\": now} # now we can submit the",
"parser = argparse.ArgumentParser(description='Submit a job stream to the TWSz plan') parser.add_argument('-e','--engineName', help='name of",
"the client utility module # ----------------------------------------------------- conn = waconn.WAConn('waconn.ini','/twsz/v1/'+args.engineName) # ----------------------------------------------------- # Query",
"(C) Copyright HCL Technologies Ltd. 2017, 2018 All rights reserved. # * Trademark",
"# Licensed Materials - Property of HCL* # (C) Copyright HCL Technologies Ltd.",
"to the plan # ----------------------------------------------------- submit = {\"inputArrivalTime\": now} # now we can",
"Materials - Property of HCL* # (C) Copyright HCL Technologies Ltd. 2017, 2018",
"2018 All rights reserved. # * Trademark of HCL Technologies Limited ############################################################################# import",
"\" + jsId) # ----------------------------------------------------- # Now submit the jobstream to the plan",
"the model and get the js id # ----------------------------------------------------- resp = conn.post('/model/jobstream/header/query', json={\"filters\":",
"stream', required=True, metavar=\"<job_stream_name>\") args = parser.parse_args() now = datetime.datetime.utcnow().isoformat() # ----------------------------------------------------- # Intialize",
"a job stream to the TWSz plan') parser.add_argument('-e','--engineName', help='name of the engine as",
"Now submit the jobstream to the plan # ----------------------------------------------------- submit = {\"inputArrivalTime\": now}",
"id is: \" + jsId) # ----------------------------------------------------- # Now submit the jobstream to",
"= resp.json() if len(r) == 0: print('job stream not found') exit(2) jsId=r[0][\"id\"] print(\"the",
"if len(r) == 0: print('job stream not found') exit(2) jsId=r[0][\"id\"] print(\"the js id",
"job stream to the TWSz plan') parser.add_argument('-e','--engineName', help='name of the engine as defined",
"# Intialize the client utility module # ----------------------------------------------------- conn = waconn.WAConn('waconn.ini','/twsz/v1/'+args.engineName) # -----------------------------------------------------",
"{\"jobstreamFilter\": {\"jobStreamName\": args.jsName,\"validIn\": now}}}, headers={'How-Many': '1'}) r = resp.json() if len(r) == 0:",
"Ltd. 2017, 2018 All rights reserved. # * Trademark of HCL Technologies Limited",
"not found') exit(2) jsId=r[0][\"id\"] print(\"the js id is: \" + jsId) # -----------------------------------------------------",
"# ----------------------------------------------------- submit = {\"inputArrivalTime\": now} # now we can submit the js",
"found') exit(2) jsId=r[0][\"id\"] print(\"the js id is: \" + jsId) # ----------------------------------------------------- #",
"utility module # ----------------------------------------------------- conn = waconn.WAConn('waconn.ini','/twsz/v1/'+args.engineName) # ----------------------------------------------------- # Query the model",
"parameters: \" +str(submit) resp = conn.post('/plan/current/jobstream/' + jsId + '/action/submit_jobstream', json=submit) r =",
"r = resp.json() if len(r) == 0: print('job stream not found') exit(2) jsId=r[0][\"id\"]",
"the jobstream to the plan # ----------------------------------------------------- submit = {\"inputArrivalTime\": now} # now",
"print('job stream not found') exit(2) jsId=r[0][\"id\"] print(\"the js id is: \" + jsId)",
"Limited ############################################################################# import waconn import argparse import datetime # ----------------------------------------------------- # Define and",
"datetime # ----------------------------------------------------- # Define and parse command line arguments # ----------------------------------------------------- parser",
"model and get the js id # ----------------------------------------------------- resp = conn.post('/model/jobstream/header/query', json={\"filters\": {\"jobstreamFilter\":",
"id # ----------------------------------------------------- resp = conn.post('/model/jobstream/header/query', json={\"filters\": {\"jobstreamFilter\": {\"jobStreamName\": args.jsName,\"validIn\": now}}}, headers={'How-Many': '1'})",
"line arguments # ----------------------------------------------------- parser = argparse.ArgumentParser(description='Submit a job stream to the TWSz",
"= argparse.ArgumentParser(description='Submit a job stream to the TWSz plan') parser.add_argument('-e','--engineName', help='name of the",
"waconn.WAConn('waconn.ini','/twsz/v1/'+args.engineName) # ----------------------------------------------------- # Query the model and get the js id #",
"----------------------------------------------------- # Define and parse command line arguments # ----------------------------------------------------- parser = argparse.ArgumentParser(description='Submit",
"arguments # ----------------------------------------------------- parser = argparse.ArgumentParser(description='Submit a job stream to the TWSz plan')",
"resp = conn.post('/model/jobstream/header/query', json={\"filters\": {\"jobstreamFilter\": {\"jobStreamName\": args.jsName,\"validIn\": now}}}, headers={'How-Many': '1'}) r = resp.json()",
"Trademark of HCL Technologies Limited ############################################################################# import waconn import argparse import datetime #",
"client utility module # ----------------------------------------------------- conn = waconn.WAConn('waconn.ini','/twsz/v1/'+args.engineName) # ----------------------------------------------------- # Query the",
"submit the js print \"submit parameters: \" +str(submit) resp = conn.post('/plan/current/jobstream/' + jsId",
"argparse import datetime # ----------------------------------------------------- # Define and parse command line arguments #"
] |
[
"norm=norm, filter_size=(1, 1), pad=\"SAME\", name=\"fconv1x1\") g = conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1), pad=\"SAME\",",
"= conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1), pad=\"SAME\", name=\"fconv1x1\") g = conv2d(x, num_filters=orig_shp[-1], norm=norm,",
"tf.nn.softmax(tf.matmul(g, tf.transpose(f, [1, 0]))) o = tf.matmul(beta, h) o = tf.reshape(o, [-1] +",
"# make f, g, h f = conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1), pad=\"SAME\",",
"tensorflow as tf def attention(x, l=1.0, norm=None, name=\"att\"): \"\"\" Args: Returns: Notes: \"\"\"",
"17:13:47 # Brief: # ============================================================================ import tensorflow as tf def attention(x, l=1.0, norm=None,",
"Returns: Notes: \"\"\" with tf.variable_scope(name): orig_shp = x.get_shape().as_list() # make f, g, h",
"l=1.0, norm=None, name=\"att\"): \"\"\" Args: Returns: Notes: \"\"\" with tf.variable_scope(name): orig_shp = x.get_shape().as_list()",
"\"\"\" Args: Returns: Notes: \"\"\" with tf.variable_scope(name): orig_shp = x.get_shape().as_list() # make f,",
"f = tf.reshape(f, [-1, orig_shp[-1]]) g = tf.reshape(g, [-1, orig_shp[-1]]) h = tf.reshape(h,",
"h) o = tf.reshape(o, [-1] + orig_shp[1:]) out = l * o +",
"norm=norm, filter_size=(1, 1), pad=\"SAME\", name=\"gconv1x1\") h = conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1), pad=\"SAME\",",
"# Email: <<EMAIL>> # Date: 2018-09-02 17:13:47 # Brief: # ============================================================================ import tensorflow",
"o = tf.matmul(beta, h) o = tf.reshape(o, [-1] + orig_shp[1:]) out = l",
"tf.reshape(h, [-1, orig_shp[-1]]) beta = tf.nn.softmax(tf.matmul(g, tf.transpose(f, [1, 0]))) o = tf.matmul(beta, h)",
"= tf.reshape(h, [-1, orig_shp[-1]]) beta = tf.nn.softmax(tf.matmul(g, tf.transpose(f, [1, 0]))) o = tf.matmul(beta,",
"conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1), pad=\"SAME\", name=\"fconv1x1\") g = conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1,",
"orig_shp = x.get_shape().as_list() # make f, g, h f = conv2d(x, num_filters=orig_shp[-1], norm=norm,",
"0]))) o = tf.matmul(beta, h) o = tf.reshape(o, [-1] + orig_shp[1:]) out =",
"f, g, h f = conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1), pad=\"SAME\", name=\"fconv1x1\") g",
"= conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1), pad=\"SAME\", name=\"hconv1x1\") f = tf.reshape(f, [-1, orig_shp[-1]])",
"tf def attention(x, l=1.0, norm=None, name=\"att\"): \"\"\" Args: Returns: Notes: \"\"\" with tf.variable_scope(name):",
"2018-09-02 17:13:47 # Brief: # ============================================================================ import tensorflow as tf def attention(x, l=1.0,",
"# ============================================================================ import tensorflow as tf def attention(x, l=1.0, norm=None, name=\"att\"): \"\"\" Args:",
"tf.reshape(f, [-1, orig_shp[-1]]) g = tf.reshape(g, [-1, orig_shp[-1]]) h = tf.reshape(h, [-1, orig_shp[-1]])",
"attention(x, l=1.0, norm=None, name=\"att\"): \"\"\" Args: Returns: Notes: \"\"\" with tf.variable_scope(name): orig_shp =",
"pad=\"SAME\", name=\"fconv1x1\") g = conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1), pad=\"SAME\", name=\"gconv1x1\") h =",
"conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1), pad=\"SAME\", name=\"hconv1x1\") f = tf.reshape(f, [-1, orig_shp[-1]]) g",
"[-1, orig_shp[-1]]) g = tf.reshape(g, [-1, orig_shp[-1]]) h = tf.reshape(h, [-1, orig_shp[-1]]) beta",
"tf.variable_scope(name): orig_shp = x.get_shape().as_list() # make f, g, h f = conv2d(x, num_filters=orig_shp[-1],",
"filter_size=(1, 1), pad=\"SAME\", name=\"fconv1x1\") g = conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1), pad=\"SAME\", name=\"gconv1x1\")",
"name=\"fconv1x1\") g = conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1), pad=\"SAME\", name=\"gconv1x1\") h = conv2d(x,",
"h = conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1), pad=\"SAME\", name=\"hconv1x1\") f = tf.reshape(f, [-1,",
"<NAME> # Email: <<EMAIL>> # Date: 2018-09-02 17:13:47 # Brief: # ============================================================================ import",
"orig_shp[-1]]) beta = tf.nn.softmax(tf.matmul(g, tf.transpose(f, [1, 0]))) o = tf.matmul(beta, h) o =",
"import tensorflow as tf def attention(x, l=1.0, norm=None, name=\"att\"): \"\"\" Args: Returns: Notes:",
"# Author: <NAME> # Email: <<EMAIL>> # Date: 2018-09-02 17:13:47 # Brief: #",
"num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1), pad=\"SAME\", name=\"hconv1x1\") f = tf.reshape(f, [-1, orig_shp[-1]]) g =",
"name=\"hconv1x1\") f = tf.reshape(f, [-1, orig_shp[-1]]) g = tf.reshape(g, [-1, orig_shp[-1]]) h =",
"g = conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1), pad=\"SAME\", name=\"gconv1x1\") h = conv2d(x, num_filters=orig_shp[-1],",
"Brief: # ============================================================================ import tensorflow as tf def attention(x, l=1.0, norm=None, name=\"att\"): \"\"\"",
"name=\"gconv1x1\") h = conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1), pad=\"SAME\", name=\"hconv1x1\") f = tf.reshape(f,",
"= tf.matmul(beta, h) o = tf.reshape(o, [-1] + orig_shp[1:]) out = l *",
"norm=norm, filter_size=(1, 1), pad=\"SAME\", name=\"hconv1x1\") f = tf.reshape(f, [-1, orig_shp[-1]]) g = tf.reshape(g,",
"[-1, orig_shp[-1]]) beta = tf.nn.softmax(tf.matmul(g, tf.transpose(f, [1, 0]))) o = tf.matmul(beta, h) o",
"============================================================================ # Author: <NAME> # Email: <<EMAIL>> # Date: 2018-09-02 17:13:47 # Brief:",
"num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1), pad=\"SAME\", name=\"gconv1x1\") h = conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1),",
"= tf.reshape(f, [-1, orig_shp[-1]]) g = tf.reshape(g, [-1, orig_shp[-1]]) h = tf.reshape(h, [-1,",
"orig_shp[-1]]) g = tf.reshape(g, [-1, orig_shp[-1]]) h = tf.reshape(h, [-1, orig_shp[-1]]) beta =",
"Date: 2018-09-02 17:13:47 # Brief: # ============================================================================ import tensorflow as tf def attention(x,",
"============================================================================ import tensorflow as tf def attention(x, l=1.0, norm=None, name=\"att\"): \"\"\" Args: Returns:",
"tf.matmul(beta, h) o = tf.reshape(o, [-1] + orig_shp[1:]) out = l * o",
"conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1), pad=\"SAME\", name=\"gconv1x1\") h = conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1,",
"# Date: 2018-09-02 17:13:47 # Brief: # ============================================================================ import tensorflow as tf def",
"[-1, orig_shp[-1]]) h = tf.reshape(h, [-1, orig_shp[-1]]) beta = tf.nn.softmax(tf.matmul(g, tf.transpose(f, [1, 0])))",
"h = tf.reshape(h, [-1, orig_shp[-1]]) beta = tf.nn.softmax(tf.matmul(g, tf.transpose(f, [1, 0]))) o =",
"# Brief: # ============================================================================ import tensorflow as tf def attention(x, l=1.0, norm=None, name=\"att\"):",
"def attention(x, l=1.0, norm=None, name=\"att\"): \"\"\" Args: Returns: Notes: \"\"\" with tf.variable_scope(name): orig_shp",
"= tf.nn.softmax(tf.matmul(g, tf.transpose(f, [1, 0]))) o = tf.matmul(beta, h) o = tf.reshape(o, [-1]",
"1), pad=\"SAME\", name=\"gconv1x1\") h = conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1), pad=\"SAME\", name=\"hconv1x1\") f",
"tf.reshape(g, [-1, orig_shp[-1]]) h = tf.reshape(h, [-1, orig_shp[-1]]) beta = tf.nn.softmax(tf.matmul(g, tf.transpose(f, [1,",
"= x.get_shape().as_list() # make f, g, h f = conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1,",
"pad=\"SAME\", name=\"hconv1x1\") f = tf.reshape(f, [-1, orig_shp[-1]]) g = tf.reshape(g, [-1, orig_shp[-1]]) h",
"tf.transpose(f, [1, 0]))) o = tf.matmul(beta, h) o = tf.reshape(o, [-1] + orig_shp[1:])",
"\"\"\" with tf.variable_scope(name): orig_shp = x.get_shape().as_list() # make f, g, h f =",
"[1, 0]))) o = tf.matmul(beta, h) o = tf.reshape(o, [-1] + orig_shp[1:]) out",
"Args: Returns: Notes: \"\"\" with tf.variable_scope(name): orig_shp = x.get_shape().as_list() # make f, g,",
"f = conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1), pad=\"SAME\", name=\"fconv1x1\") g = conv2d(x, num_filters=orig_shp[-1],",
"Email: <<EMAIL>> # Date: 2018-09-02 17:13:47 # Brief: # ============================================================================ import tensorflow as",
"= tf.reshape(g, [-1, orig_shp[-1]]) h = tf.reshape(h, [-1, orig_shp[-1]]) beta = tf.nn.softmax(tf.matmul(g, tf.transpose(f,",
"as tf def attention(x, l=1.0, norm=None, name=\"att\"): \"\"\" Args: Returns: Notes: \"\"\" with",
"= tf.reshape(o, [-1] + orig_shp[1:]) out = l * o + x return",
"h f = conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1), pad=\"SAME\", name=\"fconv1x1\") g = conv2d(x,",
"= conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1), pad=\"SAME\", name=\"gconv1x1\") h = conv2d(x, num_filters=orig_shp[-1], norm=norm,",
"g, h f = conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1), pad=\"SAME\", name=\"fconv1x1\") g =",
"1), pad=\"SAME\", name=\"fconv1x1\") g = conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1), pad=\"SAME\", name=\"gconv1x1\") h",
"orig_shp[-1]]) h = tf.reshape(h, [-1, orig_shp[-1]]) beta = tf.nn.softmax(tf.matmul(g, tf.transpose(f, [1, 0]))) o",
"<reponame>gobrewers14/gans # ============================================================================ # Author: <NAME> # Email: <<EMAIL>> # Date: 2018-09-02 17:13:47",
"name=\"att\"): \"\"\" Args: Returns: Notes: \"\"\" with tf.variable_scope(name): orig_shp = x.get_shape().as_list() # make",
"1), pad=\"SAME\", name=\"hconv1x1\") f = tf.reshape(f, [-1, orig_shp[-1]]) g = tf.reshape(g, [-1, orig_shp[-1]])",
"x.get_shape().as_list() # make f, g, h f = conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1),",
"filter_size=(1, 1), pad=\"SAME\", name=\"gconv1x1\") h = conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1), pad=\"SAME\", name=\"hconv1x1\")",
"<<EMAIL>> # Date: 2018-09-02 17:13:47 # Brief: # ============================================================================ import tensorflow as tf",
"num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1), pad=\"SAME\", name=\"fconv1x1\") g = conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1),",
"beta = tf.nn.softmax(tf.matmul(g, tf.transpose(f, [1, 0]))) o = tf.matmul(beta, h) o = tf.reshape(o,",
"pad=\"SAME\", name=\"gconv1x1\") h = conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1), pad=\"SAME\", name=\"hconv1x1\") f =",
"o = tf.reshape(o, [-1] + orig_shp[1:]) out = l * o + x",
"make f, g, h f = conv2d(x, num_filters=orig_shp[-1], norm=norm, filter_size=(1, 1), pad=\"SAME\", name=\"fconv1x1\")",
"norm=None, name=\"att\"): \"\"\" Args: Returns: Notes: \"\"\" with tf.variable_scope(name): orig_shp = x.get_shape().as_list() #",
"with tf.variable_scope(name): orig_shp = x.get_shape().as_list() # make f, g, h f = conv2d(x,",
"Author: <NAME> # Email: <<EMAIL>> # Date: 2018-09-02 17:13:47 # Brief: # ============================================================================",
"Notes: \"\"\" with tf.variable_scope(name): orig_shp = x.get_shape().as_list() # make f, g, h f",
"# ============================================================================ # Author: <NAME> # Email: <<EMAIL>> # Date: 2018-09-02 17:13:47 #",
"g = tf.reshape(g, [-1, orig_shp[-1]]) h = tf.reshape(h, [-1, orig_shp[-1]]) beta = tf.nn.softmax(tf.matmul(g,",
"filter_size=(1, 1), pad=\"SAME\", name=\"hconv1x1\") f = tf.reshape(f, [-1, orig_shp[-1]]) g = tf.reshape(g, [-1,",
"tf.reshape(o, [-1] + orig_shp[1:]) out = l * o + x return out"
] |
[
"'msr_paraphrase_testsent' + str(stp) + '.pickle' tscore = src_dir + 'msr_paraphrase_testscore' + str(stp) +",
"nscore_txt = out_dir + 'test_orig_score.pickle' src_dir = base_dir + 'test/' file_list = os.listdir(src_dir)",
"line_processing(a[2])] except IndexError: pass wds = extract_batchfeature_using_senna(all_sents) wd_len = len(wds) wd_count = 0",
"'file processing' asents_vect = [] asent_score = [] asents = [] nscore =",
"wd_count < wd_len: try: temp_score, _, s_matrix = get_rae_score_by_wd_dep(wds[wd_count], wds[wd_count + 1],mtype=mtype) except",
"all_sents += [line1, line2] nfeat.append(get_n_feature(line1, line2)) except IndexError: pass wds = extract_batchfeature_using_senna(all_sents) wd_len",
"sent_fd.read().split('\\n') slen = len(sents) # slen = 3000 schk = 10 scount =",
"sent in sents: a = sent.split('\\t') if len(a) < 3: continue score.append(float(a[0])) line1",
"+ 'test/' file_list = os.listdir(src_dir) if os.path.isfile(v_csv_file): if open(v_csv_file,'r').readline(): # print \"Already present",
"tscore = src_dir + 'msr_paraphrase_testscore' + str(stp) + '.pickle' tnfeat = src_dir +",
"+ 1],mtype=mtype) except KeyError: scor_count += 1 wd_count += 2 continue except IndexError:",
"pickle.dump(all_nscore,open(nscore_txt, 'wb')) data_csv_fd.close() sents_fd.close() return v_csv_file, sent_file def wd_making(fname,stp): sent_fd = open(fname) sents",
"while scount < slen: lscount = scount + schk if slen - scount",
"asent_score, nscore, nfeat def get_vect_data(fname, pool_size, pf): # # print fname, 'th sentence",
"1 wd_count += 2 scount = lscount # print scount, # print sent_fd.close()",
"= src_dir + 'msr_paraphrase_testscore' + str(stp) + '.pickle' tnfeat = src_dir + 'msr_paraphrase_testnfeat'",
"data_csv_fd.write(csv_txt) sents_fd.write(sent_txt) pickle.dump(all_nscore,open(nscore_txt, 'wb')) data_csv_fd.close() sents_fd.close() return v_csv_file, sent_file def data_set_maker_by_wd(flag=None, base_dir =",
"'test/' file_list = os.listdir(src_dir) if os.path.isfile(v_csv_file): if open(v_csv_file,'r').readline(): # print \"Already present :\"",
"in nfeat[i]: csv_txt += ',' + str(j) csv_txt += '\\n' data_csv_fd.write(csv_txt) sents_fd.write(sent_txt) pickle.dump(all_nscore,open(nscore_txt,",
"score, nscore, nfeat = test_get_vect_data_by_dep(fpickle = tpickle,fsent=tsent, fscore=tscore, fnfeat=tnfeat, pool_size=pool_size, mtype=mtype, pf=pf) all_nscore",
"'msr_paraphrase_trainnfeat'+ str(stp) + '.pickle' elif flag == 'test': v_csv_file = out_dir + 'test_vector_dataset.csv'",
"asents, asents_vect, asent_score, nscore, nfeat def test_get_vect_data_by_dep(fsent, fpickle, fscore, fnfeat, pool_size, mtype, pf):",
"in sents[scount:lscount]: a = sent.split('\\t') if len(a) < 3: continue score.append(float(a[0])) all_sents +=",
"line1 = line_processing(a[1]) line2 = line_processing(a[2]) all_sents += [line1, line2] nfeat.append(get_n_feature(line1, line2)) except",
"pickle.load(open(fscore,'rb')) nfeats = pickle.load(open(fnfeat,'rb')) for i in range(len(sents)): temp_score, _, s_matrix = get_rae_score_by_wd_dep(wds[i][0],",
"= sent_fd.read().split('\\n') slen = len(sents) # slen = 3 schk = 20 scount",
"tpickle = src_dir+'msr_paraphrase_test'+str(stp)+'.pickle' tsent = src_dir + 'msr_paraphrase_testsent' + str(stp) + '.pickle' tscore",
"10 scount = 0 asents_vect = [] asent_score = [] nscore = []",
"scount, # # print sent_fd.close() return asents, asents_vect, asent_score, nscore def test_data_set_maker_by_wd(flag=None, base_dir",
"return v_csv_file, sent_file data_csv_fd = open(v_csv_file,'w') sents_fd = open(sent_file,'w') all_nscore = [] all_nfeat",
"fname, 'th sentence processing' sent_fd = open(fname) sents = sent_fd.read().split('\\n') slen = len(sents)",
"get_rae_score_by_wd_dep(wds[wd_count], wds[wd_count + 1],mtype=mtype) except KeyError: scor_count += 1 wd_count += 2 continue",
"trainf = '/media/zero/41FF48D81730BD9B/Final_Thesies/data/NN-dataset/MSRParaphraseCorpus/train/msr_paraphrase_train.txt' Global.init() # Global.init_wv_self(0,50) # wd_making(testf,0) # wd_making(trainf,0) Global.init_wv_self(1,50) wd_making(testf,1) wd_making(trainf,1)",
"= sent_fd.read().rstrip(' |\\n').split('\\n') count = 1 nfeat = [] wds = [] all_sents",
"2 continue except IndexError: pass sents_vect = get_dynamic_pool(s_matrix, pool_size=pool_size, pf=pf) if not np.any(sents_vect):",
"= out_dir + 'test_sent_dataset.csv' nscore_txt = out_dir + 'test_orig_score.pickle' src_dir = base_dir +",
"lscount # # print scount, # # print sent_fd.close() return asents, asents_vect, asent_score,",
"# print fname, 'file processing' asents_vect = [] asent_score = [] asents =",
":\" return v_csv_file, sent_file data_csv_fd = open(v_csv_file,'w') sents_fd = open(sent_file,'w') all_nscore = []",
"+ 'test_sent_dataset.csv' nscore_txt = out_dir + 'test_orig_score.pickle' src_dir = base_dir + 'test/' tpickle",
"sent_file def data_set_maker_by_wd(flag=None, base_dir = None, out_dir=None, pool_size=10, num_feat=1, mtype='Normal', pf=None): if flag",
"testf = '/media/zero/41FF48D81730BD9B/Final_Thesies/data/NN-dataset/MSRParaphraseCorpus/test/msr_paraphrase_test.txt' trainf = '/media/zero/41FF48D81730BD9B/Final_Thesies/data/NN-dataset/MSRParaphraseCorpus/train/msr_paraphrase_train.txt' Global.init() # Global.init_wv_self(0,50) # wd_making(testf,0) # wd_making(trainf,0)",
"< slen: lscount = scount + schk if slen - scount > schk",
"0 while wd_count < wd_len: try: temp_score, _, s_matrix = get_rae_score_by_wd_dep(wds[wd_count], wds[wd_count +",
"in range(len(sents)): temp_score, _, s_matrix = get_rae_score_by_wd_dep(wds[i][0], wds[i][1],mtype=mtype) sents_vect = get_dynamic_pool(s_matrix, pool_size=pool_size, pf=pf)",
"'test': v_csv_file = out_dir + 'test_vector_dataset.csv' sent_file = out_dir + 'test_sent_dataset.csv' nscore_txt =",
"sents: a = sent.split('\\t') if len(a) < 3: continue score.append(float(a[0])) line1 = line_processing(a[1])",
"= '' sent_txt = '' for i in range(len(sents_vect)): csv_txt += str(score[i]) sent_txt",
"wds[i][1],mtype=mtype) sents_vect = get_dynamic_pool(s_matrix, pool_size=pool_size, pf=pf) if not np.any(sents_vect): continue asents_vect.append(sents_vect) asent_score.append(scores[i]) nscore.append(temp_score)",
"str(j) csv_txt += '\\n' data_csv_fd.write(csv_txt) sents_fd.write(sent_txt) pickle.dump(all_nscore,open(nscore_txt, 'wb')) data_csv_fd.close() sents_fd.close() return v_csv_file, sent_file",
"else slen all_sents = [] score = [] try: for sent in sents[scount:lscount]:",
"# # # print fname, 'file processing' sent_fd = open(fname) sents = sent_fd.read().split('\\n')",
"sentences parsed !!\" pass wds.append(temp) count +=1 pickle.dump(wds,open(fname.split('.')[0]+str(stp)+'.pickle','wb')) pickle.dump(all_sents,open(fname.split('.')[0]+'sent'+str(stp)+'.pickle','wb')) pickle.dump(score,open(fname.split('.')[0]+'score'+str(stp)+'.pickle','wb')) pickle.dump(nfeat,open(fname.split('.')[0]+'nfeat'+str(stp)+'.pickle','wb')) return import",
"mtype='Normal', pf=None): if flag == 'train': v_csv_file = out_dir + 'train_vector_dataset.csv' sent_file =",
"'train': v_csv_file = out_dir + 'train_vector_dataset.csv' sent_file = out_dir + 'train_sent_dataset.txt' nscore_txt =",
"nfeat.append(get_n_feature(line1, line2)) except IndexError: pass wds = extract_batchfeature_using_senna(all_sents) wd_len = len(wds) wd_count =",
"[] while scount < slen: lscount = scount + schk if slen -",
"line_processing, get_n_feature import numpy as np import pickle def get_vect_data_by_dep(fname, pool_size, mtype, pf):",
"out_dir + 'training_orig_score.pickle' src_dir = base_dir + 'train/' tpickle = src_dir + 'msr_paraphrase_train'",
"asents_vect, asent_score, nscore, nfeat def test_get_vect_data_by_dep(fsent, fpickle, fscore, fnfeat, pool_size, mtype, pf): #",
"data_csv_fd = open(v_csv_file,'w') sents_fd = open(sent_file,'w') all_nscore = [] all_nfeat = [] sents,",
"= 20 scount = 0 asents_vect = [] asent_score = [] asents =",
"wd_len: try: temp_score, _, s_matrix = get_rae_score_by_wd_dep(wds[wd_count], wds[wd_count + 1],mtype=mtype) except KeyError: scor_count",
"sents_vect[i].reshape(pool_size*pool_size): csv_txt += ','+str(j) if num_feat == 1: for j in nfeat[i]: csv_txt",
"= line_processing(a[2]) all_sents.append([line1, line2]) nfeat.append(get_n_feature(line1, line2)) temp = extract_batchfeature_using_senna([line1, line2]) print count, if",
"print \"not all sentences parsed !!\" pass wds.append(temp) count +=1 pickle.dump(wds,open(fname.split('.')[0]+str(stp)+'.pickle','wb')) pickle.dump(all_sents,open(fname.split('.')[0]+'sent'+str(stp)+'.pickle','wb')) pickle.dump(score,open(fname.split('.')[0]+'score'+str(stp)+'.pickle','wb'))",
"3 schk = 20 scount = 0 asents_vect = [] asent_score = []",
"0 scor_count = 0 while wd_count < wd_len: try: temp_score, _, s_matrix =",
"# print scount, # # print sent_fd.close() return asents, asents_vect, asent_score, nscore def",
"scount + schk if slen - scount > schk else slen all_sents =",
"sent_txt += sents[i]+'\\n' for j in sents_vect[i].reshape(pool_size*pool_size): csv_txt += ','+str(j) if num_feat ==",
"== 1: for j in nfeat[i]: csv_txt += ',' + str(j) csv_txt +=",
"pool_size=10, num_feat=1, mtype='Normal', pf=None): if flag == 'train': v_csv_file = out_dir + 'train_vector_dataset.csv'",
"a = sent.split('\\t') if len(a) < 3: continue score.append(float(a[0])) line1 = line_processing(a[1]) line2",
"1],mtype=mtype) except KeyError: scor_count += 1 wd_count += 2 continue except IndexError: pass",
"slen all_sents = [] score = [] try: for sent in sents[scount:lscount]: a",
"sents = sent_fd.read().split('\\n') slen = len(sents) # slen = 3 schk = 20",
"wd_count += 2 continue asents_vect.append(sents_vect) asent_score.append(score[scor_count]) nscore.append(temp_score) asents.append(all_sents[wd_count]+'\\t'+all_sents[wd_count+1]) scor_count += 1 wd_count +=",
"+ 'test_vector_dataset.csv' sent_file = out_dir + 'test_sent_dataset.csv' nscore_txt = out_dir + 'test_orig_score.pickle' src_dir",
"get_n_feature import numpy as np import pickle def get_vect_data_by_dep(fname, pool_size, mtype, pf): #",
"asents.append(all_sents[wd_count]+'\\t'+all_sents[wd_count+1]) scor_count += 1 wd_count += 2 scount = lscount # print scount,",
"score.append(float(a[0])) all_sents += [line_processing(a[1]), line_processing(a[2])] except IndexError: pass wds = extract_batchfeature_using_senna(all_sents) wd_len =",
"src_dir + 'msr_paraphrase_train' + str(stp) + '.pickle' tsent= src_dir+ 'msr_paraphrase_trainsent'+ str(stp) + '.pickle'",
"= [] asents = [] while scount < slen: lscount = scount +",
"nfeat csv_txt = '' sent_txt = '' for i in range(len(sents_vect)): csv_txt +=",
"continue score.append(float(a[0])) all_sents += [line_processing(a[1]), line_processing(a[2])] except IndexError: pass wds = extract_batchfeature_using_senna(all_sents) wd_len",
"sents_fd = open(sent_file,'w') all_nscore = [] all_nfeat = [] sents, sents_vect, score, nscore,",
"= [] for i in range(len(file_list)): sents, sents_vect, score, nscore, nfeat = get_vect_data_by_dep(src_dir",
"score_calc import get_rae_score_by_wd, get_rae_score_by_wd_dep from dynamic_pooling import get_dynamic_pool from text_process1 import line_processing, get_n_feature",
"= len(sents) # slen = 3000 schk = 10 scount = 0 asents_vect",
"all sentences parsed !!\" pass wds.append(temp) count +=1 pickle.dump(wds,open(fname.split('.')[0]+str(stp)+'.pickle','wb')) pickle.dump(all_sents,open(fname.split('.')[0]+'sent'+str(stp)+'.pickle','wb')) pickle.dump(score,open(fname.split('.')[0]+'score'+str(stp)+'.pickle','wb')) pickle.dump(nfeat,open(fname.split('.')[0]+'nfeat'+str(stp)+'.pickle','wb')) return",
"= pickle.load(open(fnfeat,'rb')) for i in range(len(sents)): temp_score, _, s_matrix = get_rae_score_by_wd_dep(wds[i][0], wds[i][1],mtype=mtype) sents_vect",
"get_parents, get_dep, get_words_id, pdep_2_deporder_dep, dep_2_hid_var from score_calc import get_rae_score_by_wd, get_rae_score_by_wd_dep from dynamic_pooling import",
"tnfeat= src_dir+ 'msr_paraphrase_trainnfeat'+ str(stp) + '.pickle' elif flag == 'test': v_csv_file = out_dir",
"= get_vect_data_by_dep(src_dir +file_list[i], pool_size=pool_size, mtype=mtype, pf=pf) all_nscore += score all_nfeat += nfeat csv_txt",
"import Global if __name__=='__main__': testf = '/media/zero/41FF48D81730BD9B/Final_Thesies/data/NN-dataset/MSRParaphraseCorpus/test/msr_paraphrase_test.txt' trainf = '/media/zero/41FF48D81730BD9B/Final_Thesies/data/NN-dataset/MSRParaphraseCorpus/train/msr_paraphrase_train.txt' Global.init() # Global.init_wv_self(0,50)",
"+ 'train/' tpickle = src_dir + 'msr_paraphrase_train' + str(stp) + '.pickle' tsent= src_dir+",
"sent_file def wd_making(fname,stp): sent_fd = open(fname) sents = sent_fd.read().rstrip(' |\\n').split('\\n') count = 1",
"for j in sents_vect[i].reshape(pool_size*pool_size): csv_txt += ','+str(j) if num_feat == 1: for j",
"< 3: continue score.append(float(a[0])) line1 = line_processing(a[1]) line2 = line_processing(a[2]) all_sents += [line1,",
"0 while wd_count < wd_len: try: temp_score, _, s_matrix = get_rae_score_by_wd(wds[wd_count], wds[wd_count +",
"line_processing(a[2]) all_sents += [line1, line2] nfeat.append(get_n_feature(line1, line2)) except IndexError: pass wds = extract_batchfeature_using_senna(all_sents)",
"all_nscore += score all_nfeat += nfeat csv_txt = '' sent_txt = '' for",
"[] nfeat = [] wds = pickle.load(open(fpickle,'rb')) sents = pickle.load(open(fsent,'rb')) scores = pickle.load(open(fscore,'rb'))",
"in sents[scount:lscount]: a = sent.split('\\t') if len(a) < 3: continue score.append(float(a[0])) line1 =",
"\"not all sentences parsed !!\" pass wds.append(temp) count +=1 pickle.dump(wds,open(fname.split('.')[0]+str(stp)+'.pickle','wb')) pickle.dump(all_sents,open(fname.split('.')[0]+'sent'+str(stp)+'.pickle','wb')) pickle.dump(score,open(fname.split('.')[0]+'score'+str(stp)+'.pickle','wb')) pickle.dump(nfeat,open(fname.split('.')[0]+'nfeat'+str(stp)+'.pickle','wb'))",
"'wb')) data_csv_fd.close() sents_fd.close() return v_csv_file, sent_file def data_set_maker_by_wd(flag=None, base_dir = None, out_dir=None, pool_size=10,",
"print fname, 'file processing' sent_fd = open(fname) sents = sent_fd.read().split('\\n') slen = len(sents)",
"+ 'test_sent_dataset.csv' nscore_txt = out_dir + 'test_orig_score.pickle' src_dir = base_dir + 'test/' file_list",
"scount < slen: lscount = scount + schk if slen - scount >",
"wd_len = len(wds) wd_count = 0 scor_count = 0 while wd_count < wd_len:",
"sent_fd = open(fname) sents = sent_fd.read().split('\\n') slen = len(sents) # slen = 3000",
"src_dir+ 'msr_paraphrase_trainnfeat'+ str(stp) + '.pickle' elif flag == 'test': v_csv_file = out_dir +",
"= [] try: for sent in sents[scount:lscount]: a = sent.split('\\t') if len(a) <",
"line_processing(a[1]) line2 = line_processing(a[2]) all_sents += [line1, line2] nfeat.append(get_n_feature(line1, line2)) except IndexError: pass",
"str(stp) + '.pickle' elif flag == 'test': v_csv_file = out_dir + 'test_vector_dataset.csv' sent_file",
"tnfeat = src_dir + 'msr_paraphrase_testnfeat' + str(stp) + '.pickle' if os.path.isfile(v_csv_file): if open(v_csv_file,'r').readline():",
"all_nscore = [] all_nfeat = [] sents, sents_vect, score, nscore, nfeat = test_get_vect_data_by_dep(fpickle",
"v_csv_file, sent_file def data_set_maker_by_wd(flag=None, base_dir = None, out_dir=None, pool_size=10, num_feat=1, mtype='Normal', pf=None): if",
"scor_count += 1 wd_count += 2 continue except IndexError: pass sents_vect = get_dynamic_pool(s_matrix,",
"[] try: for sent in sents[scount:lscount]: a = sent.split('\\t') if len(a) < 3:",
"pickle.dump(all_sents,open(fname.split('.')[0]+'sent'+str(stp)+'.pickle','wb')) pickle.dump(score,open(fname.split('.')[0]+'score'+str(stp)+'.pickle','wb')) pickle.dump(nfeat,open(fname.split('.')[0]+'nfeat'+str(stp)+'.pickle','wb')) return import Global if __name__=='__main__': testf = '/media/zero/41FF48D81730BD9B/Final_Thesies/data/NN-dataset/MSRParaphraseCorpus/test/msr_paraphrase_test.txt' trainf =",
"nscore, nfeat = get_vect_data_by_dep(src_dir +file_list[i], pool_size=pool_size, mtype=mtype, pf=pf) all_nscore += score all_nfeat +=",
"slen = 3000 schk = 10 scount = 0 asents_vect = [] asent_score",
"mtype, pf): # # # print fname, 'file processing' sent_fd = open(fname) sents",
"+file_list[i], pool_size=pool_size, mtype=mtype, pf=pf) all_nscore += score all_nfeat += nfeat csv_txt = ''",
"out_dir=None, pool_size=10, num_feat=1, stp=None, mtype='Normal', pf=None): if flag == 'train': v_csv_file = out_dir",
"= base_dir + 'test/' tpickle = src_dir+'msr_paraphrase_test'+str(stp)+'.pickle' tsent = src_dir + 'msr_paraphrase_testsent' +",
"str(stp) + '.pickle' tnfeat= src_dir+ 'msr_paraphrase_trainnfeat'+ str(stp) + '.pickle' elif flag == 'test':",
"= sent_fd.read().split('\\n') slen = len(sents) # slen = 3000 schk = 10 scount",
"src_dir + 'msr_paraphrase_testsent' + str(stp) + '.pickle' tscore = src_dir + 'msr_paraphrase_testscore' +",
"test_get_vect_data_by_dep(fsent, fpickle, fscore, fnfeat, pool_size, mtype, pf): # print pf # # #",
"print fname, 'th sentence processing' sent_fd = open(fname) sents = sent_fd.read().split('\\n') slen =",
"+ 'train_vector_dataset.csv' sent_file = out_dir + 'train_sent_dataset.txt' nscore_txt = out_dir + 'training_orig_score.pickle' src_dir",
"[] all_nfeat = [] sents, sents_vect, score, nscore, nfeat = test_get_vect_data_by_dep(fpickle = tpickle,fsent=tsent,",
"= [] asents = [] nscore = [] nfeat = [] wds =",
"# # print fname, 'file processing' sent_fd = open(fname) sents = sent_fd.read().split('\\n') slen",
"pass wds = extract_batchfeature_using_senna(all_sents) wd_len = len(wds) wd_count = 0 scor_count = 0",
"fnfeat, pool_size, mtype, pf): # print pf # # # print fname, 'file",
"= [] all_nfeat = [] sents, sents_vect, score, nscore, nfeat = test_get_vect_data_by_dep(fpickle =",
"len(a) < 3: continue score.append(float(a[0])) line1 = line_processing(a[1]) line2 = line_processing(a[2]) all_sents.append([line1, line2])",
"+ '.pickle' if os.path.isfile(v_csv_file): if open(v_csv_file,'r').readline(): # print \"Already present :\" return v_csv_file,",
"str(stp) + '.pickle' if os.path.isfile(v_csv_file): if open(v_csv_file,'r').readline(): # print \"Already present :\" return",
"src_dir + 'msr_paraphrase_testscore' + str(stp) + '.pickle' tnfeat = src_dir + 'msr_paraphrase_testnfeat' +",
"in sents: a = sent.split('\\t') if len(a) < 3: continue score.append(float(a[0])) line1 =",
"+= 2 continue asents_vect.append(sents_vect) asent_score.append(score[scor_count]) nscore.append(temp_score) asents.append(all_sents[wd_count]+'\\t'+all_sents[wd_count+1]) scor_count += 1 wd_count += 2",
"out_dir=None, pool_size=10, num_feat=1, mtype='Normal', pf=None): if flag == 'train': v_csv_file = out_dir +",
"< 3: continue score.append(float(a[0])) all_sents += [line_processing(a[1]), line_processing(a[2])] except IndexError: pass wds =",
"np.any(sents_vect): scor_count += 1 wd_count += 2 continue asents_vect.append(sents_vect) asent_score.append(score[scor_count]) nscore.append(temp_score) asents.append(all_sents[wd_count]+'\\t'+all_sents[wd_count+1]) scor_count",
"[] asents = [] while scount < slen: lscount = scount + schk",
"'train/' file_list = os.listdir(src_dir) elif flag == 'test': v_csv_file = out_dir + 'test_vector_dataset.csv'",
"pf=None): if flag == 'train': v_csv_file = out_dir + 'train_vector_dataset.csv' sent_file = out_dir",
"sents_fd.write(sent_txt) pickle.dump(all_nscore,open(nscore_txt, 'wb')) data_csv_fd.close() sents_fd.close() return v_csv_file, sent_file def data_set_maker_by_wd(flag=None, base_dir = None,",
"base_dir + 'test/' file_list = os.listdir(src_dir) if os.path.isfile(v_csv_file): if open(v_csv_file,'r').readline(): # print \"Already",
"open(sent_file,'w') all_nscore = [] all_nfeat = [] for i in range(len(file_list)): sents, sents_vect,",
"sents_fd.close() return v_csv_file, sent_file def data_set_maker_by_wd(flag=None, base_dir = None, out_dir=None, pool_size=10, num_feat=1, mtype='Normal',",
"slen = 3 schk = 20 scount = 0 asents_vect = [] asent_score",
"wds[wd_count + 1],mtype=mtype) except KeyError: scor_count += 1 wd_count += 2 continue except",
"+= 2 scount = lscount # # print scount, # # print sent_fd.close()",
"import line_processing, get_n_feature import numpy as np import pickle def get_vect_data_by_dep(fname, pool_size, mtype,",
"numpy as np import pickle def get_vect_data_by_dep(fname, pool_size, mtype, pf): # # #",
"# slen = 3 schk = 20 scount = 0 asents_vect = []",
"[] nscore = [] nfeat = [] wds = pickle.load(open(fpickle,'rb')) sents = pickle.load(open(fsent,'rb'))",
"[] wds = pickle.load(open(fpickle,'rb')) sents = pickle.load(open(fsent,'rb')) scores = pickle.load(open(fscore,'rb')) nfeats = pickle.load(open(fnfeat,'rb'))",
"def test_get_vect_data_by_dep(fsent, fpickle, fscore, fnfeat, pool_size, mtype, pf): # print pf # #",
"+ '.pickle' tscore= src_dir+ 'msr_paraphrase_trainscore'+ str(stp) + '.pickle' tnfeat= src_dir+ 'msr_paraphrase_trainnfeat'+ str(stp) +",
"'training_orig_score.pickle' src_dir = base_dir + 'train/' tpickle = src_dir + 'msr_paraphrase_train' + str(stp)",
"open(fname) sents = sent_fd.read().split('\\n') slen = len(sents) # slen = 3 schk =",
"'test_orig_score.pickle' src_dir = base_dir + 'test/' tpickle = src_dir+'msr_paraphrase_test'+str(stp)+'.pickle' tsent = src_dir +",
"not np.any(sents_vect): continue asents_vect.append(sents_vect) asent_score.append(scores[i]) nscore.append(temp_score) asents.append(sents[i][0]+'\\t'+sents[i][1]) nfeat.append(nfeats[i]) return asents, asents_vect, asent_score, nscore,",
"'.pickle' tscore = src_dir + 'msr_paraphrase_testscore' + str(stp) + '.pickle' tnfeat = src_dir",
"num_feat=1, mtype='Normal', pf=None): if flag == 'train': v_csv_file = out_dir + 'train_vector_dataset.csv' sent_file",
"get_vect_data_by_dep(src_dir +file_list[i], pool_size=pool_size, mtype=mtype, pf=pf) all_nscore += score all_nfeat += nfeat csv_txt =",
"line1 = line_processing(a[1]) line2 = line_processing(a[2]) all_sents.append([line1, line2]) nfeat.append(get_n_feature(line1, line2)) temp = extract_batchfeature_using_senna([line1,",
"'.pickle' if os.path.isfile(v_csv_file): if open(v_csv_file,'r').readline(): # print \"Already present :\" return v_csv_file, sent_file",
"+= str(score[i]) sent_txt += sents[i]+'\\n' for j in sents_vect[i].reshape(pool_size*pool_size): csv_txt += ','+str(j) if",
"os.path.isfile(v_csv_file): if open(v_csv_file,'r').readline(): # print \"Already present :\" return v_csv_file, sent_file data_csv_fd =",
"# print pf # # # print fname, 'file processing' asents_vect = []",
"temp_score, _, s_matrix = get_rae_score_by_wd_dep(wds[i][0], wds[i][1],mtype=mtype) sents_vect = get_dynamic_pool(s_matrix, pool_size=pool_size, pf=pf) if not",
"nscore, nfeat def get_vect_data(fname, pool_size, pf): # # print fname, 'th sentence processing'",
"= src_dir + 'msr_paraphrase_train' + str(stp) + '.pickle' tsent= src_dir+ 'msr_paraphrase_trainsent'+ str(stp) +",
"dep_2_hid_var from score_calc import get_rae_score_by_wd, get_rae_score_by_wd_dep from dynamic_pooling import get_dynamic_pool from text_process1 import",
"get_vect_data(fname, pool_size, pf): # # print fname, 'th sentence processing' sent_fd = open(fname)",
"csv_txt += str(score[i]) sent_txt += sents[i]+'\\n' for j in sents_vect[i].reshape(pool_size*pool_size): csv_txt += ','+str(j)",
"pdep_2_deporder_dep, dep_2_hid_var from score_calc import get_rae_score_by_wd, get_rae_score_by_wd_dep from dynamic_pooling import get_dynamic_pool from text_process1",
"all_sents.append([line1, line2]) nfeat.append(get_n_feature(line1, line2)) temp = extract_batchfeature_using_senna([line1, line2]) print count, if len(temp) !=2:",
"get_dynamic_pool(s_matrix, pool_size=pool_size, pf=pf) if not np.any(sents_vect): scor_count += 1 wd_count += 2 continue",
"scor_count += 1 wd_count += 2 scount = lscount # # print scount,",
"get_dynamic_pool from text_process1 import line_processing, get_n_feature import numpy as np import pickle def",
"nfeat.append(get_n_feature(line1, line2)) temp = extract_batchfeature_using_senna([line1, line2]) print count, if len(temp) !=2: print \"not",
"'test_vector_dataset.csv' sent_file = out_dir + 'test_sent_dataset.csv' nscore_txt = out_dir + 'test_orig_score.pickle' src_dir =",
"= [] nfeat = [] wds = pickle.load(open(fpickle,'rb')) sents = pickle.load(open(fsent,'rb')) scores =",
"i in range(len(file_list)): sents, sents_vect, score, nscore, nfeat = get_vect_data_by_dep(src_dir +file_list[i], pool_size=pool_size, mtype=mtype,",
"asents = [] nscore = [] nfeat = [] while scount < slen:",
"0 asents_vect = [] asent_score = [] asents = [] nscore = []",
"all_sents += [line_processing(a[1]), line_processing(a[2])] except IndexError: pass wds = extract_batchfeature_using_senna(all_sents) wd_len = len(wds)",
"if os.path.isfile(v_csv_file): if open(v_csv_file,'r').readline(): # print \"Already present :\" return v_csv_file, sent_file data_csv_fd",
"[] all_sents = [] score = [] for sent in sents: a =",
"wd_count += 2 scount = lscount # print scount, # print sent_fd.close() return",
"nscore = [] nfeat = [] wds = pickle.load(open(fpickle,'rb')) sents = pickle.load(open(fsent,'rb')) scores",
"src_dir+'msr_paraphrase_test'+str(stp)+'.pickle' tsent = src_dir + 'msr_paraphrase_testsent' + str(stp) + '.pickle' tscore = src_dir",
"= line_processing(a[1]) line2 = line_processing(a[2]) all_sents += [line1, line2] nfeat.append(get_n_feature(line1, line2)) except IndexError:",
"'.pickle' tnfeat = src_dir + 'msr_paraphrase_testnfeat' + str(stp) + '.pickle' if os.path.isfile(v_csv_file): if",
"_, s_matrix = get_rae_score_by_wd_dep(wds[wd_count], wds[wd_count + 1],mtype=mtype) except KeyError: scor_count += 1 wd_count",
"sents_vect = get_dynamic_pool(s_matrix, pool_size=pool_size, pf=pf) if not np.any(sents_vect): continue asents_vect.append(sents_vect) asent_score.append(scores[i]) nscore.append(temp_score) asents.append(sents[i][0]+'\\t'+sents[i][1])",
"sent_file data_csv_fd = open(v_csv_file,'w') sents_fd = open(sent_file,'w') all_nscore = [] all_nfeat = []",
"extract_batchfeature_using_senna([line1, line2]) print count, if len(temp) !=2: print \"not all sentences parsed !!\"",
"2 scount = lscount # print scount, # print sent_fd.close() return asents, asents_vect,",
"test_get_vect_data_by_dep(fpickle = tpickle,fsent=tsent, fscore=tscore, fnfeat=tnfeat, pool_size=pool_size, mtype=mtype, pf=pf) all_nscore += score all_nfeat +=",
"pf # # # print fname, 'file processing' asents_vect = [] asent_score =",
"sent in sents[scount:lscount]: a = sent.split('\\t') if len(a) < 3: continue score.append(float(a[0])) line1",
"nscore_txt = out_dir + 'training_orig_score.pickle' src_dir = base_dir + 'train/' file_list = os.listdir(src_dir)",
"< 3: continue score.append(float(a[0])) line1 = line_processing(a[1]) line2 = line_processing(a[2]) all_sents.append([line1, line2]) nfeat.append(get_n_feature(line1,",
"= 10 scount = 0 asents_vect = [] asent_score = [] nscore =",
"+ 'training_orig_score.pickle' src_dir = base_dir + 'train/' tpickle = src_dir + 'msr_paraphrase_train' +",
"+ 'msr_paraphrase_train' + str(stp) + '.pickle' tsent= src_dir+ 'msr_paraphrase_trainsent'+ str(stp) + '.pickle' tscore=",
"+ 'train_sent_dataset.txt' nscore_txt = out_dir + 'training_orig_score.pickle' src_dir = base_dir + 'train/' tpickle",
"pickle.dump(all_nscore,open(nscore_txt, 'wb')) data_csv_fd.close() sents_fd.close() return v_csv_file, sent_file def data_set_maker_by_wd(flag=None, base_dir = None, out_dir=None,",
"file_list = os.listdir(src_dir) if os.path.isfile(v_csv_file): if open(v_csv_file,'r').readline(): # print \"Already present :\" return",
"pool_size=10, num_feat=1, stp=None, mtype='Normal', pf=None): if flag == 'train': v_csv_file = out_dir +",
"wd_count += 2 continue except IndexError: pass sents_vect = get_dynamic_pool(s_matrix, pool_size=pool_size, pf=pf) if",
"+ 'msr_paraphrase_testsent' + str(stp) + '.pickle' tscore = src_dir + 'msr_paraphrase_testscore' + str(stp)",
"if len(a) < 3: continue score.append(float(a[0])) line1 = line_processing(a[1]) line2 = line_processing(a[2]) all_sents",
"_, s_matrix = get_rae_score_by_wd_dep(wds[i][0], wds[i][1],mtype=mtype) sents_vect = get_dynamic_pool(s_matrix, pool_size=pool_size, pf=pf) if not np.any(sents_vect):",
"sents_vect = get_dynamic_pool(s_matrix, pool_size=pool_size, pf=pf) if not np.any(sents_vect): scor_count += 1 wd_count +=",
"asents_vect, asent_score, nscore def test_data_set_maker_by_wd(flag=None, base_dir = None, out_dir=None, pool_size=10, num_feat=1, stp=None, mtype='Normal',",
"+ str(stp) + '.pickle' tscore = src_dir + 'msr_paraphrase_testscore' + str(stp) + '.pickle'",
"nfeat = [] wds = pickle.load(open(fpickle,'rb')) sents = pickle.load(open(fsent,'rb')) scores = pickle.load(open(fscore,'rb')) nfeats",
"sents[scount:lscount]: a = sent.split('\\t') if len(a) < 3: continue score.append(float(a[0])) line1 = line_processing(a[1])",
"= src_dir+'msr_paraphrase_test'+str(stp)+'.pickle' tsent = src_dir + 'msr_paraphrase_testsent' + str(stp) + '.pickle' tscore =",
"+ str(stp) + '.pickle' tnfeat = src_dir + 'msr_paraphrase_testnfeat' + str(stp) + '.pickle'",
"out_dir + 'training_orig_score.pickle' src_dir = base_dir + 'train/' file_list = os.listdir(src_dir) elif flag",
"print sent_fd.close() return asents, asents_vect, asent_score, nscore def test_data_set_maker_by_wd(flag=None, base_dir = None, out_dir=None,",
"'train_sent_dataset.txt' nscore_txt = out_dir + 'training_orig_score.pickle' src_dir = base_dir + 'train/' tpickle =",
"'test/' tpickle = src_dir+'msr_paraphrase_test'+str(stp)+'.pickle' tsent = src_dir + 'msr_paraphrase_testsent' + str(stp) + '.pickle'",
"scount > schk else slen all_sents = [] score = [] try: for",
"import get_rae_score_by_wd, get_rae_score_by_wd_dep from dynamic_pooling import get_dynamic_pool from text_process1 import line_processing, get_n_feature import",
"schk else slen all_sents = [] score = [] try: for sent in",
"pickle.dump(nfeat,open(fname.split('.')[0]+'nfeat'+str(stp)+'.pickle','wb')) return import Global if __name__=='__main__': testf = '/media/zero/41FF48D81730BD9B/Final_Thesies/data/NN-dataset/MSRParaphraseCorpus/test/msr_paraphrase_test.txt' trainf = '/media/zero/41FF48D81730BD9B/Final_Thesies/data/NN-dataset/MSRParaphraseCorpus/train/msr_paraphrase_train.txt' Global.init()",
"'th sentence processing' sent_fd = open(fname) sents = sent_fd.read().split('\\n') slen = len(sents) #",
"pool_size, mtype, pf): # print pf # # # print fname, 'file processing'",
"# # print sent_fd.close() return asents, asents_vect, asent_score, nscore def test_data_set_maker_by_wd(flag=None, base_dir =",
"3: continue score.append(float(a[0])) all_sents += [line_processing(a[1]), line_processing(a[2])] except IndexError: pass wds = extract_batchfeature_using_senna(all_sents)",
"nscore.append(temp_score) asents.append(all_sents[wd_count]+'\\t'+all_sents[wd_count+1]) scor_count += 1 wd_count += 2 scount = lscount # #",
"= [] score = [] try: for sent in sents[scount:lscount]: a = sent.split('\\t')",
"tpickle = src_dir + 'msr_paraphrase_train' + str(stp) + '.pickle' tsent= src_dir+ 'msr_paraphrase_trainsent'+ str(stp)",
"from utility1 import extract_batchfeature_using_senna, get_parents, get_dep, get_words_id, pdep_2_deporder_dep, dep_2_hid_var from score_calc import get_rae_score_by_wd,",
"fscore=tscore, fnfeat=tnfeat, pool_size=pool_size, mtype=mtype, pf=pf) all_nscore += score all_nfeat += nfeat csv_txt =",
"+= [line_processing(a[1]), line_processing(a[2])] except IndexError: pass wds = extract_batchfeature_using_senna(all_sents) wd_len = len(wds) wd_count",
"= get_rae_score_by_wd_dep(wds[wd_count], wds[wd_count + 1],mtype=mtype) except KeyError: scor_count += 1 wd_count += 2",
"+= score all_nfeat += nfeat csv_txt = '' sent_txt = '' for i",
"nscore_txt = out_dir + 'training_orig_score.pickle' src_dir = base_dir + 'train/' tpickle = src_dir",
"import get_dynamic_pool from text_process1 import line_processing, get_n_feature import numpy as np import pickle",
"tsent= src_dir+ 'msr_paraphrase_trainsent'+ str(stp) + '.pickle' tscore= src_dir+ 'msr_paraphrase_trainscore'+ str(stp) + '.pickle' tnfeat=",
"fnfeat=tnfeat, pool_size=pool_size, mtype=mtype, pf=pf) all_nscore += score all_nfeat += nfeat csv_txt = ''",
"asents, asents_vect, asent_score, nscore, nfeat def get_vect_data(fname, pool_size, pf): # # print fname,",
"asents = [] nscore = [] nfeat = [] wds = pickle.load(open(fpickle,'rb')) sents",
"count +=1 pickle.dump(wds,open(fname.split('.')[0]+str(stp)+'.pickle','wb')) pickle.dump(all_sents,open(fname.split('.')[0]+'sent'+str(stp)+'.pickle','wb')) pickle.dump(score,open(fname.split('.')[0]+'score'+str(stp)+'.pickle','wb')) pickle.dump(nfeat,open(fname.split('.')[0]+'nfeat'+str(stp)+'.pickle','wb')) return import Global if __name__=='__main__': testf =",
"return import Global if __name__=='__main__': testf = '/media/zero/41FF48D81730BD9B/Final_Thesies/data/NN-dataset/MSRParaphraseCorpus/test/msr_paraphrase_test.txt' trainf = '/media/zero/41FF48D81730BD9B/Final_Thesies/data/NN-dataset/MSRParaphraseCorpus/train/msr_paraphrase_train.txt' Global.init() #",
"+= 1 wd_count += 2 scount = lscount # # print scount, #",
"'test_sent_dataset.csv' nscore_txt = out_dir + 'test_orig_score.pickle' src_dir = base_dir + 'test/' file_list =",
"[] for sent in sents: a = sent.split('\\t') if len(a) < 3: continue",
"[] nscore = [] nfeat = [] while scount < slen: lscount =",
"import pickle def get_vect_data_by_dep(fname, pool_size, mtype, pf): # # # print fname, 'file",
"[line1, line2] nfeat.append(get_n_feature(line1, line2)) except IndexError: pass wds = extract_batchfeature_using_senna(all_sents) wd_len = len(wds)",
"wds[wd_count + 1], mtype='deep') except KeyError: scor_count += 1 wd_count += 2 continue",
"nfeat = [] while scount < slen: lscount = scount + schk if",
"all_nfeat = [] for i in range(len(file_list)): sents, sents_vect, score, nscore, nfeat =",
"# print sent_fd.close() return asents, asents_vect, asent_score, nscore def test_data_set_maker_by_wd(flag=None, base_dir = None,",
"nscore = [] nfeat = [] while scount < slen: lscount = scount",
"= pickle.load(open(fpickle,'rb')) sents = pickle.load(open(fsent,'rb')) scores = pickle.load(open(fscore,'rb')) nfeats = pickle.load(open(fnfeat,'rb')) for i",
"= get_rae_score_by_wd_dep(wds[i][0], wds[i][1],mtype=mtype) sents_vect = get_dynamic_pool(s_matrix, pool_size=pool_size, pf=pf) if not np.any(sents_vect): continue asents_vect.append(sents_vect)",
"nfeat = get_vect_data_by_dep(src_dir +file_list[i], pool_size=pool_size, mtype=mtype, pf=pf) all_nscore += score all_nfeat += nfeat",
"if __name__=='__main__': testf = '/media/zero/41FF48D81730BD9B/Final_Thesies/data/NN-dataset/MSRParaphraseCorpus/test/msr_paraphrase_test.txt' trainf = '/media/zero/41FF48D81730BD9B/Final_Thesies/data/NN-dataset/MSRParaphraseCorpus/train/msr_paraphrase_train.txt' Global.init() # Global.init_wv_self(0,50) # wd_making(testf,0)",
"v_csv_file = out_dir + 'train_vector_dataset.csv' sent_file = out_dir + 'train_sent_dataset.txt' nscore_txt = out_dir",
"1], mtype='deep') except KeyError: scor_count += 1 wd_count += 2 continue except IndexError:",
"= open(v_csv_file,'w') sents_fd = open(sent_file,'w') all_nscore = [] all_nfeat = [] for i",
"str(stp) + '.pickle' tsent= src_dir+ 'msr_paraphrase_trainsent'+ str(stp) + '.pickle' tscore= src_dir+ 'msr_paraphrase_trainscore'+ str(stp)",
"< wd_len: try: temp_score, _, s_matrix = get_rae_score_by_wd(wds[wd_count], wds[wd_count + 1], mtype='deep') except",
"return v_csv_file, sent_file def data_set_maker_by_wd(flag=None, base_dir = None, out_dir=None, pool_size=10, num_feat=1, mtype='Normal', pf=None):",
"= pickle.load(open(fsent,'rb')) scores = pickle.load(open(fscore,'rb')) nfeats = pickle.load(open(fnfeat,'rb')) for i in range(len(sents)): temp_score,",
"data_csv_fd.close() sents_fd.close() return v_csv_file, sent_file def data_set_maker_by_wd(flag=None, base_dir = None, out_dir=None, pool_size=10, num_feat=1,",
"mtype=mtype, pf=pf) all_nscore += score all_nfeat += nfeat csv_txt = '' sent_txt =",
"'msr_paraphrase_testnfeat' + str(stp) + '.pickle' if os.path.isfile(v_csv_file): if open(v_csv_file,'r').readline(): # print \"Already present",
"= [] nscore = [] asents = [] while scount < slen: lscount",
"pf): # print pf # # # print fname, 'file processing' asents_vect =",
"schk if slen - scount > schk else slen all_sents = [] score",
"return asents, asents_vect, asent_score, nscore def test_data_set_maker_by_wd(flag=None, base_dir = None, out_dir=None, pool_size=10, num_feat=1,",
"get_dynamic_pool(s_matrix, pool_size=pool_size, pf=pf) if not np.any(sents_vect): continue asents_vect.append(sents_vect) asent_score.append(scores[i]) nscore.append(temp_score) asents.append(sents[i][0]+'\\t'+sents[i][1]) nfeat.append(nfeats[i]) return",
"scount = 0 asents_vect = [] asent_score = [] nscore = [] asents",
"pool_size, pf): # # print fname, 'th sentence processing' sent_fd = open(fname) sents",
"+ 'train/' file_list = os.listdir(src_dir) elif flag == 'test': v_csv_file = out_dir +",
"base_dir + 'train/' tpickle = src_dir + 'msr_paraphrase_train' + str(stp) + '.pickle' tsent=",
"= base_dir + 'train/' file_list = os.listdir(src_dir) elif flag == 'test': v_csv_file =",
"open(fname) sents = sent_fd.read().rstrip(' |\\n').split('\\n') count = 1 nfeat = [] wds =",
"+ schk if slen - scount > schk else slen all_sents = []",
"= base_dir + 'train/' tpickle = src_dir + 'msr_paraphrase_train' + str(stp) + '.pickle'",
"+= nfeat csv_txt = '' sent_txt = '' for i in range(len(sents_vect)): csv_txt",
"for i in range(len(sents)): temp_score, _, s_matrix = get_rae_score_by_wd_dep(wds[i][0], wds[i][1],mtype=mtype) sents_vect = get_dynamic_pool(s_matrix,",
"|\\n').split('\\n') count = 1 nfeat = [] wds = [] all_sents = []",
"= [] wds = [] all_sents = [] score = [] for sent",
"'train/' tpickle = src_dir + 'msr_paraphrase_train' + str(stp) + '.pickle' tsent= src_dir+ 'msr_paraphrase_trainsent'+",
"j in sents_vect[i].reshape(pool_size*pool_size): csv_txt += ','+str(j) if num_feat == 1: for j in",
"= extract_batchfeature_using_senna(all_sents) wd_len = len(wds) wd_count = 0 scor_count = 0 while wd_count",
"sent_file = out_dir + 'train_sent_dataset.txt' nscore_txt = out_dir + 'training_orig_score.pickle' src_dir = base_dir",
"pool_size=pool_size, pf=pf) if not np.any(sents_vect): scor_count += 1 wd_count += 2 continue asents_vect.append(sents_vect)",
"temp_score, _, s_matrix = get_rae_score_by_wd(wds[wd_count], wds[wd_count + 1], mtype='deep') except KeyError: scor_count +=",
"= out_dir + 'test_vector_dataset.csv' sent_file = out_dir + 'test_sent_dataset.csv' nscore_txt = out_dir +",
"= sent.split('\\t') if len(a) < 3: continue score.append(float(a[0])) all_sents += [line_processing(a[1]), line_processing(a[2])] except",
"_, s_matrix = get_rae_score_by_wd(wds[wd_count], wds[wd_count + 1], mtype='deep') except KeyError: scor_count += 1",
"v_csv_file = out_dir + 'test_vector_dataset.csv' sent_file = out_dir + 'test_sent_dataset.csv' nscore_txt = out_dir",
"pickle def get_vect_data_by_dep(fname, pool_size, mtype, pf): # # # print fname, 'file processing'",
"sent_txt = '' for i in range(len(sents_vect)): csv_txt += str(score[i]) sent_txt += sents[i]+'\\n'",
"print sent_fd.close() return asents, asents_vect, asent_score, nscore, nfeat def test_get_vect_data_by_dep(fsent, fpickle, fscore, fnfeat,",
"+= 2 scount = lscount # print scount, # print sent_fd.close() return asents,",
"pool_size, mtype, pf): # # # print fname, 'file processing' sent_fd = open(fname)",
"= [] nfeat = [] while scount < slen: lscount = scount +",
"= [] for sent in sents: a = sent.split('\\t') if len(a) < 3:",
"IndexError: pass sents_vect = get_dynamic_pool(s_matrix, pool_size=pool_size, pf=pf) if not np.any(sents_vect): scor_count += 1",
"+= [line1, line2] nfeat.append(get_n_feature(line1, line2)) except IndexError: pass wds = extract_batchfeature_using_senna(all_sents) wd_len =",
"print count, if len(temp) !=2: print \"not all sentences parsed !!\" pass wds.append(temp)",
"os.listdir(src_dir) elif flag == 'test': v_csv_file = out_dir + 'test_vector_dataset.csv' sent_file = out_dir",
"= out_dir + 'train_vector_dataset.csv' sent_file = out_dir + 'train_sent_dataset.txt' nscore_txt = out_dir +",
"data_set_maker_by_wd(flag=None, base_dir = None, out_dir=None, pool_size=10, num_feat=1, mtype='Normal', pf=None): if flag == 'train':",
"scores = pickle.load(open(fscore,'rb')) nfeats = pickle.load(open(fnfeat,'rb')) for i in range(len(sents)): temp_score, _, s_matrix",
"',' + str(j) csv_txt += '\\n' data_csv_fd.write(csv_txt) sents_fd.write(sent_txt) pickle.dump(all_nscore,open(nscore_txt, 'wb')) data_csv_fd.close() sents_fd.close() return",
"sents[i]+'\\n' for j in sents_vect[i].reshape(pool_size*pool_size): csv_txt += ','+str(j) if num_feat == 1: for",
"[] asents = [] nscore = [] nfeat = [] wds = pickle.load(open(fpickle,'rb'))",
"continue asents_vect.append(sents_vect) asent_score.append(score[scor_count]) nscore.append(temp_score) asents.append(all_sents[wd_count]+'\\t'+all_sents[wd_count+1]) scor_count += 1 wd_count += 2 scount =",
"base_dir + 'test/' tpickle = src_dir+'msr_paraphrase_test'+str(stp)+'.pickle' tsent = src_dir + 'msr_paraphrase_testsent' + str(stp)",
"asents_vect = [] asent_score = [] asents = [] nscore = [] nfeat",
"= 0 asents_vect = [] asent_score = [] asents = [] nscore =",
"temp_score, _, s_matrix = get_rae_score_by_wd_dep(wds[wd_count], wds[wd_count + 1],mtype=mtype) except KeyError: scor_count += 1",
"fname, 'file processing' sent_fd = open(fname) sents = sent_fd.read().split('\\n') slen = len(sents) #",
"pool_size=pool_size, mtype=mtype, pf=pf) all_nscore += score all_nfeat += nfeat csv_txt = '' sent_txt",
"sents_fd.close() return v_csv_file, sent_file def wd_making(fname,stp): sent_fd = open(fname) sents = sent_fd.read().rstrip(' |\\n').split('\\n')",
"# # print fname, 'file processing' asents_vect = [] asent_score = [] asents",
"scount, # print sent_fd.close() return asents, asents_vect, asent_score, nscore, nfeat def test_get_vect_data_by_dep(fsent, fpickle,",
"s_matrix = get_rae_score_by_wd(wds[wd_count], wds[wd_count + 1], mtype='deep') except KeyError: scor_count += 1 wd_count",
"0 asents_vect = [] asent_score = [] nscore = [] asents = []",
"present :\" return v_csv_file, sent_file data_csv_fd = open(v_csv_file,'w') sents_fd = open(sent_file,'w') all_nscore =",
"KeyError: scor_count += 1 wd_count += 2 continue except IndexError: pass sents_vect =",
"score all_nfeat += nfeat csv_txt = '' sent_txt = '' for i in",
"line_processing(a[1]) line2 = line_processing(a[2]) all_sents.append([line1, line2]) nfeat.append(get_n_feature(line1, line2)) temp = extract_batchfeature_using_senna([line1, line2]) print",
"+ 'test/' tpickle = src_dir+'msr_paraphrase_test'+str(stp)+'.pickle' tsent = src_dir + 'msr_paraphrase_testsent' + str(stp) +",
"+= 1 wd_count += 2 continue except IndexError: pass sents_vect = get_dynamic_pool(s_matrix, pool_size=pool_size,",
"i in range(len(sents)): temp_score, _, s_matrix = get_rae_score_by_wd_dep(wds[i][0], wds[i][1],mtype=mtype) sents_vect = get_dynamic_pool(s_matrix, pool_size=pool_size,",
"get_rae_score_by_wd_dep(wds[i][0], wds[i][1],mtype=mtype) sents_vect = get_dynamic_pool(s_matrix, pool_size=pool_size, pf=pf) if not np.any(sents_vect): continue asents_vect.append(sents_vect) asent_score.append(scores[i])",
"pickle.dump(score,open(fname.split('.')[0]+'score'+str(stp)+'.pickle','wb')) pickle.dump(nfeat,open(fname.split('.')[0]+'nfeat'+str(stp)+'.pickle','wb')) return import Global if __name__=='__main__': testf = '/media/zero/41FF48D81730BD9B/Final_Thesies/data/NN-dataset/MSRParaphraseCorpus/test/msr_paraphrase_test.txt' trainf = '/media/zero/41FF48D81730BD9B/Final_Thesies/data/NN-dataset/MSRParaphraseCorpus/train/msr_paraphrase_train.txt'",
"score = [] for sent in sents: a = sent.split('\\t') if len(a) <",
"np.any(sents_vect): continue asents_vect.append(sents_vect) asent_score.append(scores[i]) nscore.append(temp_score) asents.append(sents[i][0]+'\\t'+sents[i][1]) nfeat.append(nfeats[i]) return asents, asents_vect, asent_score, nscore, nfeat",
"lscount = scount + schk if slen - scount > schk else slen",
"for j in nfeat[i]: csv_txt += ',' + str(j) csv_txt += '\\n' data_csv_fd.write(csv_txt)",
"nfeat = test_get_vect_data_by_dep(fpickle = tpickle,fsent=tsent, fscore=tscore, fnfeat=tnfeat, pool_size=pool_size, mtype=mtype, pf=pf) all_nscore += score",
"def get_vect_data(fname, pool_size, pf): # # print fname, 'th sentence processing' sent_fd =",
"while wd_count < wd_len: try: temp_score, _, s_matrix = get_rae_score_by_wd(wds[wd_count], wds[wd_count + 1],",
"+= 1 wd_count += 2 scount = lscount # print scount, # print",
"for i in range(len(file_list)): sents, sents_vect, score, nscore, nfeat = get_vect_data_by_dep(src_dir +file_list[i], pool_size=pool_size,",
"continue score.append(float(a[0])) line1 = line_processing(a[1]) line2 = line_processing(a[2]) all_sents.append([line1, line2]) nfeat.append(get_n_feature(line1, line2)) temp",
"score = [] try: for sent in sents[scount:lscount]: a = sent.split('\\t') if len(a)",
"+ '.pickle' elif flag == 'test': v_csv_file = out_dir + 'test_vector_dataset.csv' sent_file =",
"3: continue score.append(float(a[0])) line1 = line_processing(a[1]) line2 = line_processing(a[2]) all_sents += [line1, line2]",
"= out_dir + 'training_orig_score.pickle' src_dir = base_dir + 'train/' file_list = os.listdir(src_dir) elif",
"src_dir = base_dir + 'test/' tpickle = src_dir+'msr_paraphrase_test'+str(stp)+'.pickle' tsent = src_dir + 'msr_paraphrase_testsent'",
"sent_file = out_dir + 'test_sent_dataset.csv' nscore_txt = out_dir + 'test_orig_score.pickle' src_dir = base_dir",
"+ str(stp) + '.pickle' tsent= src_dir+ 'msr_paraphrase_trainsent'+ str(stp) + '.pickle' tscore= src_dir+ 'msr_paraphrase_trainscore'+",
"line2)) except IndexError: pass wds = extract_batchfeature_using_senna(all_sents) wd_len = len(wds) wd_count = 0",
"lscount # print scount, # print sent_fd.close() return asents, asents_vect, asent_score, nscore, nfeat",
"slen - scount > schk else slen all_sents = [] score = []",
"sents = sent_fd.read().split('\\n') slen = len(sents) # slen = 3000 schk = 10",
"out_dir + 'train_sent_dataset.txt' nscore_txt = out_dir + 'training_orig_score.pickle' src_dir = base_dir + 'train/'",
"1: for j in nfeat[i]: csv_txt += ',' + str(j) csv_txt += '\\n'",
"= src_dir + 'msr_paraphrase_testsent' + str(stp) + '.pickle' tscore = src_dir + 'msr_paraphrase_testscore'",
"continue asents_vect.append(sents_vect) asent_score.append(scores[i]) nscore.append(temp_score) asents.append(sents[i][0]+'\\t'+sents[i][1]) nfeat.append(nfeats[i]) return asents, asents_vect, asent_score, nscore, nfeat def",
"out_dir + 'train_vector_dataset.csv' sent_file = out_dir + 'train_sent_dataset.txt' nscore_txt = out_dir + 'training_orig_score.pickle'",
"= open(fname) sents = sent_fd.read().split('\\n') slen = len(sents) # slen = 3 schk",
"scor_count += 1 wd_count += 2 scount = lscount # print scount, #",
"get_rae_score_by_wd(wds[wd_count], wds[wd_count + 1], mtype='deep') except KeyError: scor_count += 1 wd_count += 2",
"line2]) print count, if len(temp) !=2: print \"not all sentences parsed !!\" pass",
"except IndexError: pass wds = extract_batchfeature_using_senna(all_sents) wd_len = len(wds) wd_count = 0 scor_count",
"nscore, nfeat def test_get_vect_data_by_dep(fsent, fpickle, fscore, fnfeat, pool_size, mtype, pf): # print pf",
"'msr_paraphrase_testscore' + str(stp) + '.pickle' tnfeat = src_dir + 'msr_paraphrase_testnfeat' + str(stp) +",
"get_vect_data_by_dep(fname, pool_size, mtype, pf): # # # print fname, 'file processing' sent_fd =",
"'test_orig_score.pickle' src_dir = base_dir + 'test/' file_list = os.listdir(src_dir) if os.path.isfile(v_csv_file): if open(v_csv_file,'r').readline():",
"[] score = [] for sent in sents: a = sent.split('\\t') if len(a)",
"= open(sent_file,'w') all_nscore = [] all_nfeat = [] sents, sents_vect, score, nscore, nfeat",
"scount = lscount # # print scount, # # print sent_fd.close() return asents,",
"str(score[i]) sent_txt += sents[i]+'\\n' for j in sents_vect[i].reshape(pool_size*pool_size): csv_txt += ','+str(j) if num_feat",
"= 1 nfeat = [] wds = [] all_sents = [] score =",
"wd_making(fname,stp): sent_fd = open(fname) sents = sent_fd.read().rstrip(' |\\n').split('\\n') count = 1 nfeat =",
"asent_score, nscore def test_data_set_maker_by_wd(flag=None, base_dir = None, out_dir=None, pool_size=10, num_feat=1, stp=None, mtype='Normal', pf=None):",
"','+str(j) if num_feat == 1: for j in nfeat[i]: csv_txt += ',' +",
"nfeat.append(nfeats[i]) return asents, asents_vect, asent_score, nscore, nfeat def get_vect_data(fname, pool_size, pf): # #",
"len(wds) wd_count = 0 scor_count = 0 while wd_count < wd_len: try: temp_score,",
"= extract_batchfeature_using_senna([line1, line2]) print count, if len(temp) !=2: print \"not all sentences parsed",
"def test_data_set_maker_by_wd(flag=None, base_dir = None, out_dir=None, pool_size=10, num_feat=1, stp=None, mtype='Normal', pf=None): if flag",
"num_feat == 1: for j in nfeat[i]: csv_txt += ',' + str(j) csv_txt",
"src_dir+ 'msr_paraphrase_trainscore'+ str(stp) + '.pickle' tnfeat= src_dir+ 'msr_paraphrase_trainnfeat'+ str(stp) + '.pickle' elif flag",
"src_dir = base_dir + 'train/' file_list = os.listdir(src_dir) elif flag == 'test': v_csv_file",
"# print sent_fd.close() return asents, asents_vect, asent_score, nscore, nfeat def test_get_vect_data_by_dep(fsent, fpickle, fscore,",
"stp=None, mtype='Normal', pf=None): if flag == 'train': v_csv_file = out_dir + 'train_vector_dataset.csv' sent_file",
"asent_score = [] nscore = [] asents = [] while scount < slen:",
"if open(v_csv_file,'r').readline(): # print \"Already present :\" return v_csv_file, sent_file data_csv_fd = open(v_csv_file,'w')",
"scount = lscount # print scount, # print sent_fd.close() return asents, asents_vect, asent_score,",
"open(sent_file,'w') all_nscore = [] all_nfeat = [] sents, sents_vect, score, nscore, nfeat =",
"# # print scount, # # print sent_fd.close() return asents, asents_vect, asent_score, nscore",
"test_data_set_maker_by_wd(flag=None, base_dir = None, out_dir=None, pool_size=10, num_feat=1, stp=None, mtype='Normal', pf=None): if flag ==",
"range(len(sents_vect)): csv_txt += str(score[i]) sent_txt += sents[i]+'\\n' for j in sents_vect[i].reshape(pool_size*pool_size): csv_txt +=",
"+ 'msr_paraphrase_testscore' + str(stp) + '.pickle' tnfeat = src_dir + 'msr_paraphrase_testnfeat' + str(stp)",
"open(v_csv_file,'w') sents_fd = open(sent_file,'w') all_nscore = [] all_nfeat = [] sents, sents_vect, score,",
"base_dir + 'train/' file_list = os.listdir(src_dir) elif flag == 'test': v_csv_file = out_dir",
"'msr_paraphrase_trainscore'+ str(stp) + '.pickle' tnfeat= src_dir+ 'msr_paraphrase_trainnfeat'+ str(stp) + '.pickle' elif flag ==",
"sents_vect, score, nscore, nfeat = get_vect_data_by_dep(src_dir +file_list[i], pool_size=pool_size, mtype=mtype, pf=pf) all_nscore += score",
"for sent in sents[scount:lscount]: a = sent.split('\\t') if len(a) < 3: continue score.append(float(a[0]))",
"out_dir + 'test_orig_score.pickle' src_dir = base_dir + 'test/' file_list = os.listdir(src_dir) if os.path.isfile(v_csv_file):",
"sent_fd.read().split('\\n') slen = len(sents) # slen = 3 schk = 20 scount =",
"+ '.pickle' tnfeat= src_dir+ 'msr_paraphrase_trainnfeat'+ str(stp) + '.pickle' elif flag == 'test': v_csv_file",
"asents_vect = [] asent_score = [] nscore = [] asents = [] while",
"= open(v_csv_file,'w') sents_fd = open(sent_file,'w') all_nscore = [] all_nfeat = [] sents, sents_vect,",
"tsent = src_dir + 'msr_paraphrase_testsent' + str(stp) + '.pickle' tscore = src_dir +",
"= get_dynamic_pool(s_matrix, pool_size=pool_size, pf=pf) if not np.any(sents_vect): continue asents_vect.append(sents_vect) asent_score.append(scores[i]) nscore.append(temp_score) asents.append(sents[i][0]+'\\t'+sents[i][1]) nfeat.append(nfeats[i])",
"text_process1 import line_processing, get_n_feature import numpy as np import pickle def get_vect_data_by_dep(fname, pool_size,",
"sents = sent_fd.read().rstrip(' |\\n').split('\\n') count = 1 nfeat = [] wds = []",
"wd_count += 2 scount = lscount # # print scount, # # print",
"all_nfeat = [] sents, sents_vect, score, nscore, nfeat = test_get_vect_data_by_dep(fpickle = tpickle,fsent=tsent, fscore=tscore,",
"= len(sents) # slen = 3 schk = 20 scount = 0 asents_vect",
"nfeat = [] wds = [] all_sents = [] score = [] for",
"line2 = line_processing(a[2]) all_sents.append([line1, line2]) nfeat.append(get_n_feature(line1, line2)) temp = extract_batchfeature_using_senna([line1, line2]) print count,",
"= 0 asents_vect = [] asent_score = [] nscore = [] asents =",
"3000 schk = 10 scount = 0 asents_vect = [] asent_score = []",
"str(stp) + '.pickle' tscore= src_dir+ 'msr_paraphrase_trainscore'+ str(stp) + '.pickle' tnfeat= src_dir+ 'msr_paraphrase_trainnfeat'+ str(stp)",
"[] asent_score = [] nscore = [] asents = [] while scount <",
"= None, out_dir=None, pool_size=10, num_feat=1, stp=None, mtype='Normal', pf=None): if flag == 'train': v_csv_file",
"+ 'msr_paraphrase_testnfeat' + str(stp) + '.pickle' if os.path.isfile(v_csv_file): if open(v_csv_file,'r').readline(): # print \"Already",
"flag == 'train': v_csv_file = out_dir + 'train_vector_dataset.csv' sent_file = out_dir + 'train_sent_dataset.txt'",
"file_list = os.listdir(src_dir) elif flag == 'test': v_csv_file = out_dir + 'test_vector_dataset.csv' sent_file",
"src_dir + 'msr_paraphrase_testnfeat' + str(stp) + '.pickle' if os.path.isfile(v_csv_file): if open(v_csv_file,'r').readline(): # print",
"fscore, fnfeat, pool_size, mtype, pf): # print pf # # # print fname,",
"= 0 while wd_count < wd_len: try: temp_score, _, s_matrix = get_rae_score_by_wd(wds[wd_count], wds[wd_count",
"nscore, nfeat = test_get_vect_data_by_dep(fpickle = tpickle,fsent=tsent, fscore=tscore, fnfeat=tnfeat, pool_size=pool_size, mtype=mtype, pf=pf) all_nscore +=",
"utility1 import extract_batchfeature_using_senna, get_parents, get_dep, get_words_id, pdep_2_deporder_dep, dep_2_hid_var from score_calc import get_rae_score_by_wd, get_rae_score_by_wd_dep",
"def wd_making(fname,stp): sent_fd = open(fname) sents = sent_fd.read().rstrip(' |\\n').split('\\n') count = 1 nfeat",
"get_words_id, pdep_2_deporder_dep, dep_2_hid_var from score_calc import get_rae_score_by_wd, get_rae_score_by_wd_dep from dynamic_pooling import get_dynamic_pool from",
"!=2: print \"not all sentences parsed !!\" pass wds.append(temp) count +=1 pickle.dump(wds,open(fname.split('.')[0]+str(stp)+'.pickle','wb')) pickle.dump(all_sents,open(fname.split('.')[0]+'sent'+str(stp)+'.pickle','wb'))",
"get_dep, get_words_id, pdep_2_deporder_dep, dep_2_hid_var from score_calc import get_rae_score_by_wd, get_rae_score_by_wd_dep from dynamic_pooling import get_dynamic_pool",
"= 3 schk = 20 scount = 0 asents_vect = [] asent_score =",
"pickle.load(open(fsent,'rb')) scores = pickle.load(open(fscore,'rb')) nfeats = pickle.load(open(fnfeat,'rb')) for i in range(len(sents)): temp_score, _,",
"== 'train': v_csv_file = out_dir + 'train_vector_dataset.csv' sent_file = out_dir + 'train_sent_dataset.txt' nscore_txt",
"= [] sents, sents_vect, score, nscore, nfeat = test_get_vect_data_by_dep(fpickle = tpickle,fsent=tsent, fscore=tscore, fnfeat=tnfeat,",
"slen = len(sents) # slen = 3 schk = 20 scount = 0",
"sent_fd.read().rstrip(' |\\n').split('\\n') count = 1 nfeat = [] wds = [] all_sents =",
"except KeyError: scor_count += 1 wd_count += 2 continue except IndexError: pass sents_vect",
"= out_dir + 'train_sent_dataset.txt' nscore_txt = out_dir + 'training_orig_score.pickle' src_dir = base_dir +",
"= out_dir + 'training_orig_score.pickle' src_dir = base_dir + 'train/' tpickle = src_dir +",
"nfeat[i]: csv_txt += ',' + str(j) csv_txt += '\\n' data_csv_fd.write(csv_txt) sents_fd.write(sent_txt) pickle.dump(all_nscore,open(nscore_txt, 'wb'))",
"1 wd_count += 2 continue asents_vect.append(sents_vect) asent_score.append(score[scor_count]) nscore.append(temp_score) asents.append(all_sents[wd_count]+'\\t'+all_sents[wd_count+1]) scor_count += 1 wd_count",
"len(temp) !=2: print \"not all sentences parsed !!\" pass wds.append(temp) count +=1 pickle.dump(wds,open(fname.split('.')[0]+str(stp)+'.pickle','wb'))",
"= len(wds) wd_count = 0 scor_count = 0 while wd_count < wd_len: try:",
"print pf # # # print fname, 'file processing' asents_vect = [] asent_score",
"while wd_count < wd_len: try: temp_score, _, s_matrix = get_rae_score_by_wd_dep(wds[wd_count], wds[wd_count + 1],mtype=mtype)",
"len(a) < 3: continue score.append(float(a[0])) line1 = line_processing(a[1]) line2 = line_processing(a[2]) all_sents +=",
"os.listdir(src_dir) if os.path.isfile(v_csv_file): if open(v_csv_file,'r').readline(): # print \"Already present :\" return v_csv_file, sent_file",
"base_dir = None, out_dir=None, pool_size=10, num_feat=1, mtype='Normal', pf=None): if flag == 'train': v_csv_file",
"processing' sent_fd = open(fname) sents = sent_fd.read().split('\\n') slen = len(sents) # slen =",
"+ '.pickle' tnfeat = src_dir + 'msr_paraphrase_testnfeat' + str(stp) + '.pickle' if os.path.isfile(v_csv_file):",
"= open(fname) sents = sent_fd.read().rstrip(' |\\n').split('\\n') count = 1 nfeat = [] wds",
"+= '\\n' data_csv_fd.write(csv_txt) sents_fd.write(sent_txt) pickle.dump(all_nscore,open(nscore_txt, 'wb')) data_csv_fd.close() sents_fd.close() return v_csv_file, sent_file def data_set_maker_by_wd(flag=None,",
"asents_vect, asent_score, nscore, nfeat def get_vect_data(fname, pool_size, pf): # # print fname, 'th",
"if not np.any(sents_vect): scor_count += 1 wd_count += 2 continue asents_vect.append(sents_vect) asent_score.append(score[scor_count]) nscore.append(temp_score)",
"print scount, # # print sent_fd.close() return asents, asents_vect, asent_score, nscore def test_data_set_maker_by_wd(flag=None,",
"slen: lscount = scount + schk if slen - scount > schk else",
"pf): # # print fname, 'th sentence processing' sent_fd = open(fname) sents =",
"asents.append(sents[i][0]+'\\t'+sents[i][1]) nfeat.append(nfeats[i]) return asents, asents_vect, asent_score, nscore, nfeat def get_vect_data(fname, pool_size, pf): #",
"src_dir = base_dir + 'test/' file_list = os.listdir(src_dir) if os.path.isfile(v_csv_file): if open(v_csv_file,'r').readline(): #",
"as np import pickle def get_vect_data_by_dep(fname, pool_size, mtype, pf): # # # print",
"num_feat=1, stp=None, mtype='Normal', pf=None): if flag == 'train': v_csv_file = out_dir + 'train_vector_dataset.csv'",
"count, if len(temp) !=2: print \"not all sentences parsed !!\" pass wds.append(temp) count",
"1 wd_count += 2 continue except IndexError: pass sents_vect = get_dynamic_pool(s_matrix, pool_size=pool_size, pf=pf)",
"= get_dynamic_pool(s_matrix, pool_size=pool_size, pf=pf) if not np.any(sents_vect): scor_count += 1 wd_count += 2",
"print fname, 'file processing' asents_vect = [] asent_score = [] asents = []",
"sents, sents_vect, score, nscore, nfeat = test_get_vect_data_by_dep(fpickle = tpickle,fsent=tsent, fscore=tscore, fnfeat=tnfeat, pool_size=pool_size, mtype=mtype,",
"str(stp) + '.pickle' tscore = src_dir + 'msr_paraphrase_testscore' + str(stp) + '.pickle' tnfeat",
"1 nfeat = [] wds = [] all_sents = [] score = []",
"[] score = [] try: for sent in sents[scount:lscount]: a = sent.split('\\t') if",
"nfeats = pickle.load(open(fnfeat,'rb')) for i in range(len(sents)): temp_score, _, s_matrix = get_rae_score_by_wd_dep(wds[i][0], wds[i][1],mtype=mtype)",
"sents, sents_vect, score, nscore, nfeat = get_vect_data_by_dep(src_dir +file_list[i], pool_size=pool_size, mtype=mtype, pf=pf) all_nscore +=",
"all_nfeat += nfeat csv_txt = '' sent_txt = '' for i in range(len(sents_vect)):",
"'\\n' data_csv_fd.write(csv_txt) sents_fd.write(sent_txt) pickle.dump(all_nscore,open(nscore_txt, 'wb')) data_csv_fd.close() sents_fd.close() return v_csv_file, sent_file def data_set_maker_by_wd(flag=None, base_dir",
"sents_fd.write(sent_txt) pickle.dump(all_nscore,open(nscore_txt, 'wb')) data_csv_fd.close() sents_fd.close() return v_csv_file, sent_file def wd_making(fname,stp): sent_fd = open(fname)",
"+=1 pickle.dump(wds,open(fname.split('.')[0]+str(stp)+'.pickle','wb')) pickle.dump(all_sents,open(fname.split('.')[0]+'sent'+str(stp)+'.pickle','wb')) pickle.dump(score,open(fname.split('.')[0]+'score'+str(stp)+'.pickle','wb')) pickle.dump(nfeat,open(fname.split('.')[0]+'nfeat'+str(stp)+'.pickle','wb')) return import Global if __name__=='__main__': testf = '/media/zero/41FF48D81730BD9B/Final_Thesies/data/NN-dataset/MSRParaphraseCorpus/test/msr_paraphrase_test.txt'",
"for sent in sents: a = sent.split('\\t') if len(a) < 3: continue score.append(float(a[0]))",
"!!\" pass wds.append(temp) count +=1 pickle.dump(wds,open(fname.split('.')[0]+str(stp)+'.pickle','wb')) pickle.dump(all_sents,open(fname.split('.')[0]+'sent'+str(stp)+'.pickle','wb')) pickle.dump(score,open(fname.split('.')[0]+'score'+str(stp)+'.pickle','wb')) pickle.dump(nfeat,open(fname.split('.')[0]+'nfeat'+str(stp)+'.pickle','wb')) return import Global if",
"2 scount = lscount # # print scount, # # print sent_fd.close() return",
"range(len(file_list)): sents, sents_vect, score, nscore, nfeat = get_vect_data_by_dep(src_dir +file_list[i], pool_size=pool_size, mtype=mtype, pf=pf) all_nscore",
"= [] while scount < slen: lscount = scount + schk if slen",
"nscore.append(temp_score) asents.append(sents[i][0]+'\\t'+sents[i][1]) nfeat.append(nfeats[i]) return asents, asents_vect, asent_score, nscore, nfeat def get_vect_data(fname, pool_size, pf):",
"1 wd_count += 2 scount = lscount # # print scount, # #",
"v_csv_file, sent_file data_csv_fd = open(v_csv_file,'w') sents_fd = open(sent_file,'w') all_nscore = [] all_nfeat =",
"+= ','+str(j) if num_feat == 1: for j in nfeat[i]: csv_txt += ','",
"+= 2 continue except IndexError: pass sents_vect = get_dynamic_pool(s_matrix, pool_size=pool_size, pf=pf) if not",
"sent_fd = open(fname) sents = sent_fd.read().split('\\n') slen = len(sents) # slen = 3",
"temp = extract_batchfeature_using_senna([line1, line2]) print count, if len(temp) !=2: print \"not all sentences",
"os from utility1 import extract_batchfeature_using_senna, get_parents, get_dep, get_words_id, pdep_2_deporder_dep, dep_2_hid_var from score_calc import",
"if len(a) < 3: continue score.append(float(a[0])) line1 = line_processing(a[1]) line2 = line_processing(a[2]) all_sents.append([line1,",
"base_dir = None, out_dir=None, pool_size=10, num_feat=1, stp=None, mtype='Normal', pf=None): if flag == 'train':",
"sent_fd = open(fname) sents = sent_fd.read().rstrip(' |\\n').split('\\n') count = 1 nfeat = []",
"wds = pickle.load(open(fpickle,'rb')) sents = pickle.load(open(fsent,'rb')) scores = pickle.load(open(fscore,'rb')) nfeats = pickle.load(open(fnfeat,'rb')) for",
"= open(fname) sents = sent_fd.read().split('\\n') slen = len(sents) # slen = 3000 schk",
"if not np.any(sents_vect): continue asents_vect.append(sents_vect) asent_score.append(scores[i]) nscore.append(temp_score) asents.append(sents[i][0]+'\\t'+sents[i][1]) nfeat.append(nfeats[i]) return asents, asents_vect, asent_score,",
"if num_feat == 1: for j in nfeat[i]: csv_txt += ',' + str(j)",
"elif flag == 'test': v_csv_file = out_dir + 'test_vector_dataset.csv' sent_file = out_dir +",
"import numpy as np import pickle def get_vect_data_by_dep(fname, pool_size, mtype, pf): # #",
"'\\n' data_csv_fd.write(csv_txt) sents_fd.write(sent_txt) pickle.dump(all_nscore,open(nscore_txt, 'wb')) data_csv_fd.close() sents_fd.close() return v_csv_file, sent_file def wd_making(fname,stp): sent_fd",
"= out_dir + 'test_orig_score.pickle' src_dir = base_dir + 'test/' file_list = os.listdir(src_dir) if",
"len(sents) # slen = 3000 schk = 10 scount = 0 asents_vect =",
"pass wds.append(temp) count +=1 pickle.dump(wds,open(fname.split('.')[0]+str(stp)+'.pickle','wb')) pickle.dump(all_sents,open(fname.split('.')[0]+'sent'+str(stp)+'.pickle','wb')) pickle.dump(score,open(fname.split('.')[0]+'score'+str(stp)+'.pickle','wb')) pickle.dump(nfeat,open(fname.split('.')[0]+'nfeat'+str(stp)+'.pickle','wb')) return import Global if __name__=='__main__':",
"+ 'train_sent_dataset.txt' nscore_txt = out_dir + 'training_orig_score.pickle' src_dir = base_dir + 'train/' file_list",
"nfeat def test_get_vect_data_by_dep(fsent, fpickle, fscore, fnfeat, pool_size, mtype, pf): # print pf #",
"= 3000 schk = 10 scount = 0 asents_vect = [] asent_score =",
"sent.split('\\t') if len(a) < 3: continue score.append(float(a[0])) line1 = line_processing(a[1]) line2 = line_processing(a[2])",
"nscore.append(temp_score) asents.append(all_sents[wd_count]+'\\t'+all_sents[wd_count+1]) scor_count += 1 wd_count += 2 scount = lscount # print",
"+ 1], mtype='deep') except KeyError: scor_count += 1 wd_count += 2 continue except",
"data_csv_fd = open(v_csv_file,'w') sents_fd = open(sent_file,'w') all_nscore = [] all_nfeat = [] for",
"schk = 10 scount = 0 asents_vect = [] asent_score = [] nscore",
"= [] all_nfeat = [] for i in range(len(file_list)): sents, sents_vect, score, nscore,",
"= [] nscore = [] nfeat = [] wds = pickle.load(open(fpickle,'rb')) sents =",
"j in nfeat[i]: csv_txt += ',' + str(j) csv_txt += '\\n' data_csv_fd.write(csv_txt) sents_fd.write(sent_txt)",
"# print \"Already present :\" return v_csv_file, sent_file data_csv_fd = open(v_csv_file,'w') sents_fd =",
"'msr_paraphrase_train' + str(stp) + '.pickle' tsent= src_dir+ 'msr_paraphrase_trainsent'+ str(stp) + '.pickle' tscore= src_dir+",
"'.pickle' tnfeat= src_dir+ 'msr_paraphrase_trainnfeat'+ str(stp) + '.pickle' elif flag == 'test': v_csv_file =",
"from score_calc import get_rae_score_by_wd, get_rae_score_by_wd_dep from dynamic_pooling import get_dynamic_pool from text_process1 import line_processing,",
"= os.listdir(src_dir) elif flag == 'test': v_csv_file = out_dir + 'test_vector_dataset.csv' sent_file =",
"mtype='deep') except KeyError: scor_count += 1 wd_count += 2 continue except IndexError: pass",
"nscore_txt = out_dir + 'test_orig_score.pickle' src_dir = base_dir + 'test/' tpickle = src_dir+'msr_paraphrase_test'+str(stp)+'.pickle'",
"+ str(j) csv_txt += '\\n' data_csv_fd.write(csv_txt) sents_fd.write(sent_txt) pickle.dump(all_nscore,open(nscore_txt, 'wb')) data_csv_fd.close() sents_fd.close() return v_csv_file,",
"# print fname, 'file processing' sent_fd = open(fname) sents = sent_fd.read().split('\\n') slen =",
"[line_processing(a[1]), line_processing(a[2])] except IndexError: pass wds = extract_batchfeature_using_senna(all_sents) wd_len = len(wds) wd_count =",
"all_sents = [] score = [] for sent in sents: a = sent.split('\\t')",
"import os from utility1 import extract_batchfeature_using_senna, get_parents, get_dep, get_words_id, pdep_2_deporder_dep, dep_2_hid_var from score_calc",
"[] nscore = [] asents = [] while scount < slen: lscount =",
"= [] asent_score = [] asents = [] nscore = [] nfeat =",
"not np.any(sents_vect): scor_count += 1 wd_count += 2 continue asents_vect.append(sents_vect) asent_score.append(score[scor_count]) nscore.append(temp_score) asents.append(all_sents[wd_count]+'\\t'+all_sents[wd_count+1])",
"3: continue score.append(float(a[0])) line1 = line_processing(a[1]) line2 = line_processing(a[2]) all_sents.append([line1, line2]) nfeat.append(get_n_feature(line1, line2))",
"[] for i in range(len(file_list)): sents, sents_vect, score, nscore, nfeat = get_vect_data_by_dep(src_dir +file_list[i],",
"line_processing(a[2]) all_sents.append([line1, line2]) nfeat.append(get_n_feature(line1, line2)) temp = extract_batchfeature_using_senna([line1, line2]) print count, if len(temp)",
"= '' for i in range(len(sents_vect)): csv_txt += str(score[i]) sent_txt += sents[i]+'\\n' for",
"v_csv_file, sent_file def wd_making(fname,stp): sent_fd = open(fname) sents = sent_fd.read().rstrip(' |\\n').split('\\n') count =",
"20 scount = 0 asents_vect = [] asent_score = [] asents = []",
"= [] asent_score = [] nscore = [] asents = [] while scount",
"csv_txt += '\\n' data_csv_fd.write(csv_txt) sents_fd.write(sent_txt) pickle.dump(all_nscore,open(nscore_txt, 'wb')) data_csv_fd.close() sents_fd.close() return v_csv_file, sent_file def",
"pool_size=pool_size, pf=pf) if not np.any(sents_vect): continue asents_vect.append(sents_vect) asent_score.append(scores[i]) nscore.append(temp_score) asents.append(sents[i][0]+'\\t'+sents[i][1]) nfeat.append(nfeats[i]) return asents,",
"[] all_nfeat = [] for i in range(len(file_list)): sents, sents_vect, score, nscore, nfeat",
"= lscount # print scount, # print sent_fd.close() return asents, asents_vect, asent_score, nscore,",
"scor_count = 0 while wd_count < wd_len: try: temp_score, _, s_matrix = get_rae_score_by_wd_dep(wds[wd_count],",
"try: temp_score, _, s_matrix = get_rae_score_by_wd(wds[wd_count], wds[wd_count + 1], mtype='deep') except KeyError: scor_count",
"len(sents) # slen = 3 schk = 20 scount = 0 asents_vect =",
"asent_score = [] asents = [] nscore = [] nfeat = [] wds",
"sents = pickle.load(open(fsent,'rb')) scores = pickle.load(open(fscore,'rb')) nfeats = pickle.load(open(fnfeat,'rb')) for i in range(len(sents)):",
"# slen = 3000 schk = 10 scount = 0 asents_vect = []",
"scor_count = 0 while wd_count < wd_len: try: temp_score, _, s_matrix = get_rae_score_by_wd(wds[wd_count],",
"nscore def test_data_set_maker_by_wd(flag=None, base_dir = None, out_dir=None, pool_size=10, num_feat=1, stp=None, mtype='Normal', pf=None): if",
"get_rae_score_by_wd_dep from dynamic_pooling import get_dynamic_pool from text_process1 import line_processing, get_n_feature import numpy as",
"if len(temp) !=2: print \"not all sentences parsed !!\" pass wds.append(temp) count +=1",
"nscore = [] asents = [] while scount < slen: lscount = scount",
"csv_txt = '' sent_txt = '' for i in range(len(sents_vect)): csv_txt += str(score[i])",
"scount = 0 asents_vect = [] asent_score = [] asents = [] nscore",
"+= 1 wd_count += 2 continue asents_vect.append(sents_vect) asent_score.append(score[scor_count]) nscore.append(temp_score) asents.append(all_sents[wd_count]+'\\t'+all_sents[wd_count+1]) scor_count += 1",
"s_matrix = get_rae_score_by_wd_dep(wds[i][0], wds[i][1],mtype=mtype) sents_vect = get_dynamic_pool(s_matrix, pool_size=pool_size, pf=pf) if not np.any(sents_vect): continue",
"all_nscore = [] all_nfeat = [] for i in range(len(file_list)): sents, sents_vect, score,",
"data_csv_fd.close() sents_fd.close() return v_csv_file, sent_file def wd_making(fname,stp): sent_fd = open(fname) sents = sent_fd.read().rstrip('",
"'training_orig_score.pickle' src_dir = base_dir + 'train/' file_list = os.listdir(src_dir) elif flag == 'test':",
"'/media/zero/41FF48D81730BD9B/Final_Thesies/data/NN-dataset/MSRParaphraseCorpus/test/msr_paraphrase_test.txt' trainf = '/media/zero/41FF48D81730BD9B/Final_Thesies/data/NN-dataset/MSRParaphraseCorpus/train/msr_paraphrase_train.txt' Global.init() # Global.init_wv_self(0,50) # wd_making(testf,0) # wd_making(trainf,0) Global.init_wv_self(1,50) wd_making(testf,1)",
"'test_sent_dataset.csv' nscore_txt = out_dir + 'test_orig_score.pickle' src_dir = base_dir + 'test/' tpickle =",
"pass sents_vect = get_dynamic_pool(s_matrix, pool_size=pool_size, pf=pf) if not np.any(sents_vect): scor_count += 1 wd_count",
"asents = [] while scount < slen: lscount = scount + schk if",
"= [] all_sents = [] score = [] for sent in sents: a",
"= [] wds = pickle.load(open(fpickle,'rb')) sents = pickle.load(open(fsent,'rb')) scores = pickle.load(open(fscore,'rb')) nfeats =",
"__name__=='__main__': testf = '/media/zero/41FF48D81730BD9B/Final_Thesies/data/NN-dataset/MSRParaphraseCorpus/test/msr_paraphrase_test.txt' trainf = '/media/zero/41FF48D81730BD9B/Final_Thesies/data/NN-dataset/MSRParaphraseCorpus/train/msr_paraphrase_train.txt' Global.init() # Global.init_wv_self(0,50) # wd_making(testf,0) #",
"# # # print fname, 'file processing' asents_vect = [] asent_score = []",
"pickle.load(open(fnfeat,'rb')) for i in range(len(sents)): temp_score, _, s_matrix = get_rae_score_by_wd_dep(wds[i][0], wds[i][1],mtype=mtype) sents_vect =",
"flag == 'test': v_csv_file = out_dir + 'test_vector_dataset.csv' sent_file = out_dir + 'test_sent_dataset.csv'",
"pf=pf) if not np.any(sents_vect): scor_count += 1 wd_count += 2 continue asents_vect.append(sents_vect) asent_score.append(score[scor_count])",
"+ 'training_orig_score.pickle' src_dir = base_dir + 'train/' file_list = os.listdir(src_dir) elif flag ==",
"= test_get_vect_data_by_dep(fpickle = tpickle,fsent=tsent, fscore=tscore, fnfeat=tnfeat, pool_size=pool_size, mtype=mtype, pf=pf) all_nscore += score all_nfeat",
"pf): # # # print fname, 'file processing' sent_fd = open(fname) sents =",
"out_dir + 'test_orig_score.pickle' src_dir = base_dir + 'test/' tpickle = src_dir+'msr_paraphrase_test'+str(stp)+'.pickle' tsent =",
"[] wds = [] all_sents = [] score = [] for sent in",
"dynamic_pooling import get_dynamic_pool from text_process1 import line_processing, get_n_feature import numpy as np import",
"# print fname, 'th sentence processing' sent_fd = open(fname) sents = sent_fd.read().split('\\n') slen",
"== 'test': v_csv_file = out_dir + 'test_vector_dataset.csv' sent_file = out_dir + 'test_sent_dataset.csv' nscore_txt",
"= tpickle,fsent=tsent, fscore=tscore, fnfeat=tnfeat, pool_size=pool_size, mtype=mtype, pf=pf) all_nscore += score all_nfeat += nfeat",
"= 0 scor_count = 0 while wd_count < wd_len: try: temp_score, _, s_matrix",
"- scount > schk else slen all_sents = [] score = [] try:",
"asent_score.append(scores[i]) nscore.append(temp_score) asents.append(sents[i][0]+'\\t'+sents[i][1]) nfeat.append(nfeats[i]) return asents, asents_vect, asent_score, nscore, nfeat def get_vect_data(fname, pool_size,",
"sent.split('\\t') if len(a) < 3: continue score.append(float(a[0])) all_sents += [line_processing(a[1]), line_processing(a[2])] except IndexError:",
"= out_dir + 'test_orig_score.pickle' src_dir = base_dir + 'test/' tpickle = src_dir+'msr_paraphrase_test'+str(stp)+'.pickle' tsent",
"in range(len(sents_vect)): csv_txt += str(score[i]) sent_txt += sents[i]+'\\n' for j in sents_vect[i].reshape(pool_size*pool_size): csv_txt",
"= base_dir + 'test/' file_list = os.listdir(src_dir) if os.path.isfile(v_csv_file): if open(v_csv_file,'r').readline(): # print",
"def data_set_maker_by_wd(flag=None, base_dir = None, out_dir=None, pool_size=10, num_feat=1, mtype='Normal', pf=None): if flag ==",
"wds.append(temp) count +=1 pickle.dump(wds,open(fname.split('.')[0]+str(stp)+'.pickle','wb')) pickle.dump(all_sents,open(fname.split('.')[0]+'sent'+str(stp)+'.pickle','wb')) pickle.dump(score,open(fname.split('.')[0]+'score'+str(stp)+'.pickle','wb')) pickle.dump(nfeat,open(fname.split('.')[0]+'nfeat'+str(stp)+'.pickle','wb')) return import Global if __name__=='__main__': testf",
"pf=pf) if not np.any(sents_vect): continue asents_vect.append(sents_vect) asent_score.append(scores[i]) nscore.append(temp_score) asents.append(sents[i][0]+'\\t'+sents[i][1]) nfeat.append(nfeats[i]) return asents, asents_vect,",
"+= ',' + str(j) csv_txt += '\\n' data_csv_fd.write(csv_txt) sents_fd.write(sent_txt) pickle.dump(all_nscore,open(nscore_txt, 'wb')) data_csv_fd.close() sents_fd.close()",
"return asents, asents_vect, asent_score, nscore, nfeat def get_vect_data(fname, pool_size, pf): # # print",
"= os.listdir(src_dir) if os.path.isfile(v_csv_file): if open(v_csv_file,'r').readline(): # print \"Already present :\" return v_csv_file,",
"sent_fd.close() return asents, asents_vect, asent_score, nscore def test_data_set_maker_by_wd(flag=None, base_dir = None, out_dir=None, pool_size=10,",
"= lscount # # print scount, # # print sent_fd.close() return asents, asents_vect,",
"'file processing' sent_fd = open(fname) sents = sent_fd.read().split('\\n') slen = len(sents) # slen",
"'train_sent_dataset.txt' nscore_txt = out_dir + 'training_orig_score.pickle' src_dir = base_dir + 'train/' file_list =",
"None, out_dir=None, pool_size=10, num_feat=1, mtype='Normal', pf=None): if flag == 'train': v_csv_file = out_dir",
"[] asents = [] nscore = [] nfeat = [] while scount <",
"= open(sent_file,'w') all_nscore = [] all_nfeat = [] for i in range(len(file_list)): sents,",
"\"Already present :\" return v_csv_file, sent_file data_csv_fd = open(v_csv_file,'w') sents_fd = open(sent_file,'w') all_nscore",
"a = sent.split('\\t') if len(a) < 3: continue score.append(float(a[0])) all_sents += [line_processing(a[1]), line_processing(a[2])]",
"= [] asents = [] nscore = [] nfeat = [] while scount",
"'msr_paraphrase_trainsent'+ str(stp) + '.pickle' tscore= src_dir+ 'msr_paraphrase_trainscore'+ str(stp) + '.pickle' tnfeat= src_dir+ 'msr_paraphrase_trainnfeat'+",
"in sents_vect[i].reshape(pool_size*pool_size): csv_txt += ','+str(j) if num_feat == 1: for j in nfeat[i]:",
"sent_fd.close() return asents, asents_vect, asent_score, nscore, nfeat def test_get_vect_data_by_dep(fsent, fpickle, fscore, fnfeat, pool_size,",
"= line_processing(a[1]) line2 = line_processing(a[2]) all_sents.append([line1, line2]) nfeat.append(get_n_feature(line1, line2)) temp = extract_batchfeature_using_senna([line1, line2])",
"score.append(float(a[0])) line1 = line_processing(a[1]) line2 = line_processing(a[2]) all_sents.append([line1, line2]) nfeat.append(get_n_feature(line1, line2)) temp =",
"continue score.append(float(a[0])) line1 = line_processing(a[1]) line2 = line_processing(a[2]) all_sents += [line1, line2] nfeat.append(get_n_feature(line1,",
"wd_count < wd_len: try: temp_score, _, s_matrix = get_rae_score_by_wd(wds[wd_count], wds[wd_count + 1], mtype='deep')",
"extract_batchfeature_using_senna, get_parents, get_dep, get_words_id, pdep_2_deporder_dep, dep_2_hid_var from score_calc import get_rae_score_by_wd, get_rae_score_by_wd_dep from dynamic_pooling",
"try: temp_score, _, s_matrix = get_rae_score_by_wd_dep(wds[wd_count], wds[wd_count + 1],mtype=mtype) except KeyError: scor_count +=",
"range(len(sents)): temp_score, _, s_matrix = get_rae_score_by_wd_dep(wds[i][0], wds[i][1],mtype=mtype) sents_vect = get_dynamic_pool(s_matrix, pool_size=pool_size, pf=pf) if",
"i in range(len(sents_vect)): csv_txt += str(score[i]) sent_txt += sents[i]+'\\n' for j in sents_vect[i].reshape(pool_size*pool_size):",
"schk = 20 scount = 0 asents_vect = [] asent_score = [] asents",
"'' for i in range(len(sents_vect)): csv_txt += str(score[i]) sent_txt += sents[i]+'\\n' for j",
"out_dir + 'test_sent_dataset.csv' nscore_txt = out_dir + 'test_orig_score.pickle' src_dir = base_dir + 'test/'",
"= scount + schk if slen - scount > schk else slen all_sents",
"except IndexError: pass sents_vect = get_dynamic_pool(s_matrix, pool_size=pool_size, pf=pf) if not np.any(sents_vect): scor_count +=",
"parsed !!\" pass wds.append(temp) count +=1 pickle.dump(wds,open(fname.split('.')[0]+str(stp)+'.pickle','wb')) pickle.dump(all_sents,open(fname.split('.')[0]+'sent'+str(stp)+'.pickle','wb')) pickle.dump(score,open(fname.split('.')[0]+'score'+str(stp)+'.pickle','wb')) pickle.dump(nfeat,open(fname.split('.')[0]+'nfeat'+str(stp)+'.pickle','wb')) return import Global",
"wd_count = 0 scor_count = 0 while wd_count < wd_len: try: temp_score, _,",
"= None, out_dir=None, pool_size=10, num_feat=1, mtype='Normal', pf=None): if flag == 'train': v_csv_file =",
"= sent.split('\\t') if len(a) < 3: continue score.append(float(a[0])) line1 = line_processing(a[1]) line2 =",
"out_dir + 'test_vector_dataset.csv' sent_file = out_dir + 'test_sent_dataset.csv' nscore_txt = out_dir + 'test_orig_score.pickle'",
"[] asent_score = [] asents = [] nscore = [] nfeat = []",
"= 0 while wd_count < wd_len: try: temp_score, _, s_matrix = get_rae_score_by_wd_dep(wds[wd_count], wds[wd_count",
"for i in range(len(sents_vect)): csv_txt += str(score[i]) sent_txt += sents[i]+'\\n' for j in",
"extract_batchfeature_using_senna(all_sents) wd_len = len(wds) wd_count = 0 scor_count = 0 while wd_count <",
"tpickle,fsent=tsent, fscore=tscore, fnfeat=tnfeat, pool_size=pool_size, mtype=mtype, pf=pf) all_nscore += score all_nfeat += nfeat csv_txt",
"src_dir = base_dir + 'train/' tpickle = src_dir + 'msr_paraphrase_train' + str(stp) +",
"# # print fname, 'th sentence processing' sent_fd = open(fname) sents = sent_fd.read().split('\\n')",
"nfeat def get_vect_data(fname, pool_size, pf): # # print fname, 'th sentence processing' sent_fd",
"'' sent_txt = '' for i in range(len(sents_vect)): csv_txt += str(score[i]) sent_txt +=",
"processing' asents_vect = [] asent_score = [] asents = [] nscore = []",
"[] nfeat = [] while scount < slen: lscount = scount + schk",
"'train_vector_dataset.csv' sent_file = out_dir + 'train_sent_dataset.txt' nscore_txt = out_dir + 'training_orig_score.pickle' src_dir =",
"= [] score = [] for sent in sents: a = sent.split('\\t') if",
"continue except IndexError: pass sents_vect = get_dynamic_pool(s_matrix, pool_size=pool_size, pf=pf) if not np.any(sents_vect): scor_count",
"open(v_csv_file,'r').readline(): # print \"Already present :\" return v_csv_file, sent_file data_csv_fd = open(v_csv_file,'w') sents_fd",
"+= sents[i]+'\\n' for j in sents_vect[i].reshape(pool_size*pool_size): csv_txt += ','+str(j) if num_feat == 1:",
"pickle.dump(wds,open(fname.split('.')[0]+str(stp)+'.pickle','wb')) pickle.dump(all_sents,open(fname.split('.')[0]+'sent'+str(stp)+'.pickle','wb')) pickle.dump(score,open(fname.split('.')[0]+'score'+str(stp)+'.pickle','wb')) pickle.dump(nfeat,open(fname.split('.')[0]+'nfeat'+str(stp)+'.pickle','wb')) return import Global if __name__=='__main__': testf = '/media/zero/41FF48D81730BD9B/Final_Thesies/data/NN-dataset/MSRParaphraseCorpus/test/msr_paraphrase_test.txt' trainf",
"str(stp) + '.pickle' tnfeat = src_dir + 'msr_paraphrase_testnfeat' + str(stp) + '.pickle' if",
"open(fname) sents = sent_fd.read().split('\\n') slen = len(sents) # slen = 3000 schk =",
"sents_fd = open(sent_file,'w') all_nscore = [] all_nfeat = [] for i in range(len(file_list)):",
"= get_rae_score_by_wd(wds[wd_count], wds[wd_count + 1], mtype='deep') except KeyError: scor_count += 1 wd_count +=",
"= '/media/zero/41FF48D81730BD9B/Final_Thesies/data/NN-dataset/MSRParaphraseCorpus/test/msr_paraphrase_test.txt' trainf = '/media/zero/41FF48D81730BD9B/Final_Thesies/data/NN-dataset/MSRParaphraseCorpus/train/msr_paraphrase_train.txt' Global.init() # Global.init_wv_self(0,50) # wd_making(testf,0) # wd_making(trainf,0) Global.init_wv_self(1,50)",
"def get_vect_data_by_dep(fname, pool_size, mtype, pf): # # # print fname, 'file processing' sent_fd",
"line2 = line_processing(a[2]) all_sents += [line1, line2] nfeat.append(get_n_feature(line1, line2)) except IndexError: pass wds",
"sents_vect, score, nscore, nfeat = test_get_vect_data_by_dep(fpickle = tpickle,fsent=tsent, fscore=tscore, fnfeat=tnfeat, pool_size=pool_size, mtype=mtype, pf=pf)",
"from dynamic_pooling import get_dynamic_pool from text_process1 import line_processing, get_n_feature import numpy as np",
"print \"Already present :\" return v_csv_file, sent_file data_csv_fd = open(v_csv_file,'w') sents_fd = open(sent_file,'w')",
"+ 'test_orig_score.pickle' src_dir = base_dir + 'test/' file_list = os.listdir(src_dir) if os.path.isfile(v_csv_file): if",
"> schk else slen all_sents = [] score = [] try: for sent",
"wds = [] all_sents = [] score = [] for sent in sents:",
"'wb')) data_csv_fd.close() sents_fd.close() return v_csv_file, sent_file def wd_making(fname,stp): sent_fd = open(fname) sents =",
"get_rae_score_by_wd, get_rae_score_by_wd_dep from dynamic_pooling import get_dynamic_pool from text_process1 import line_processing, get_n_feature import numpy",
"pickle.load(open(fpickle,'rb')) sents = pickle.load(open(fsent,'rb')) scores = pickle.load(open(fscore,'rb')) nfeats = pickle.load(open(fnfeat,'rb')) for i in",
"tscore= src_dir+ 'msr_paraphrase_trainscore'+ str(stp) + '.pickle' tnfeat= src_dir+ 'msr_paraphrase_trainnfeat'+ str(stp) + '.pickle' elif",
"# print scount, # print sent_fd.close() return asents, asents_vect, asent_score, nscore, nfeat def",
"< wd_len: try: temp_score, _, s_matrix = get_rae_score_by_wd_dep(wds[wd_count], wds[wd_count + 1],mtype=mtype) except KeyError:",
"np import pickle def get_vect_data_by_dep(fname, pool_size, mtype, pf): # # # print fname,",
"if flag == 'train': v_csv_file = out_dir + 'train_vector_dataset.csv' sent_file = out_dir +",
"asent_score = [] asents = [] nscore = [] nfeat = [] while",
"+ '.pickle' tscore = src_dir + 'msr_paraphrase_testscore' + str(stp) + '.pickle' tnfeat =",
"all_sents = [] score = [] try: for sent in sents[scount:lscount]: a =",
"asents_vect.append(sents_vect) asent_score.append(score[scor_count]) nscore.append(temp_score) asents.append(all_sents[wd_count]+'\\t'+all_sents[wd_count+1]) scor_count += 1 wd_count += 2 scount = lscount",
"import extract_batchfeature_using_senna, get_parents, get_dep, get_words_id, pdep_2_deporder_dep, dep_2_hid_var from score_calc import get_rae_score_by_wd, get_rae_score_by_wd_dep from",
"asents_vect.append(sents_vect) asent_score.append(scores[i]) nscore.append(temp_score) asents.append(sents[i][0]+'\\t'+sents[i][1]) nfeat.append(nfeats[i]) return asents, asents_vect, asent_score, nscore, nfeat def get_vect_data(fname,",
"slen = len(sents) # slen = 3000 schk = 10 scount = 0",
"scor_count += 1 wd_count += 2 continue asents_vect.append(sents_vect) asent_score.append(score[scor_count]) nscore.append(temp_score) asents.append(all_sents[wd_count]+'\\t'+all_sents[wd_count+1]) scor_count +=",
"fpickle, fscore, fnfeat, pool_size, mtype, pf): # print pf # # # print",
"+ str(stp) + '.pickle' if os.path.isfile(v_csv_file): if open(v_csv_file,'r').readline(): # print \"Already present :\"",
"line2] nfeat.append(get_n_feature(line1, line2)) except IndexError: pass wds = extract_batchfeature_using_senna(all_sents) wd_len = len(wds) wd_count",
"+ '.pickle' tsent= src_dir+ 'msr_paraphrase_trainsent'+ str(stp) + '.pickle' tscore= src_dir+ 'msr_paraphrase_trainscore'+ str(stp) +",
"if slen - scount > schk else slen all_sents = [] score =",
"sents[scount:lscount]: a = sent.split('\\t') if len(a) < 3: continue score.append(float(a[0])) all_sents += [line_processing(a[1]),",
"len(a) < 3: continue score.append(float(a[0])) all_sents += [line_processing(a[1]), line_processing(a[2])] except IndexError: pass wds",
"s_matrix = get_rae_score_by_wd_dep(wds[wd_count], wds[wd_count + 1],mtype=mtype) except KeyError: scor_count += 1 wd_count +=",
"if len(a) < 3: continue score.append(float(a[0])) all_sents += [line_processing(a[1]), line_processing(a[2])] except IndexError: pass",
"'.pickle' tsent= src_dir+ 'msr_paraphrase_trainsent'+ str(stp) + '.pickle' tscore= src_dir+ 'msr_paraphrase_trainscore'+ str(stp) + '.pickle'",
"in range(len(file_list)): sents, sents_vect, score, nscore, nfeat = get_vect_data_by_dep(src_dir +file_list[i], pool_size=pool_size, mtype=mtype, pf=pf)",
"score, nscore, nfeat = get_vect_data_by_dep(src_dir +file_list[i], pool_size=pool_size, mtype=mtype, pf=pf) all_nscore += score all_nfeat",
"score.append(float(a[0])) line1 = line_processing(a[1]) line2 = line_processing(a[2]) all_sents += [line1, line2] nfeat.append(get_n_feature(line1, line2))",
"= line_processing(a[2]) all_sents += [line1, line2] nfeat.append(get_n_feature(line1, line2)) except IndexError: pass wds =",
"try: for sent in sents[scount:lscount]: a = sent.split('\\t') if len(a) < 3: continue",
"csv_txt += ','+str(j) if num_feat == 1: for j in nfeat[i]: csv_txt +=",
"sentence processing' sent_fd = open(fname) sents = sent_fd.read().split('\\n') slen = len(sents) # slen",
"'.pickle' elif flag == 'test': v_csv_file = out_dir + 'test_vector_dataset.csv' sent_file = out_dir",
"sent in sents[scount:lscount]: a = sent.split('\\t') if len(a) < 3: continue score.append(float(a[0])) all_sents",
"mtype, pf): # print pf # # # print fname, 'file processing' asents_vect",
"None, out_dir=None, pool_size=10, num_feat=1, stp=None, mtype='Normal', pf=None): if flag == 'train': v_csv_file =",
"asents, asents_vect, asent_score, nscore def test_data_set_maker_by_wd(flag=None, base_dir = None, out_dir=None, pool_size=10, num_feat=1, stp=None,",
"print scount, # print sent_fd.close() return asents, asents_vect, asent_score, nscore, nfeat def test_get_vect_data_by_dep(fsent,",
"wd_len: try: temp_score, _, s_matrix = get_rae_score_by_wd(wds[wd_count], wds[wd_count + 1], mtype='deep') except KeyError:",
"+ 'test_orig_score.pickle' src_dir = base_dir + 'test/' tpickle = src_dir+'msr_paraphrase_test'+str(stp)+'.pickle' tsent = src_dir",
"count = 1 nfeat = [] wds = [] all_sents = [] score",
"return v_csv_file, sent_file def wd_making(fname,stp): sent_fd = open(fname) sents = sent_fd.read().rstrip(' |\\n').split('\\n') count",
"fname, 'file processing' asents_vect = [] asent_score = [] asents = [] nscore",
"line2)) temp = extract_batchfeature_using_senna([line1, line2]) print count, if len(temp) !=2: print \"not all",
"src_dir+ 'msr_paraphrase_trainsent'+ str(stp) + '.pickle' tscore= src_dir+ 'msr_paraphrase_trainscore'+ str(stp) + '.pickle' tnfeat= src_dir+",
"= src_dir + 'msr_paraphrase_testnfeat' + str(stp) + '.pickle' if os.path.isfile(v_csv_file): if open(v_csv_file,'r').readline(): #",
"from text_process1 import line_processing, get_n_feature import numpy as np import pickle def get_vect_data_by_dep(fname,",
"2 continue asents_vect.append(sents_vect) asent_score.append(score[scor_count]) nscore.append(temp_score) asents.append(all_sents[wd_count]+'\\t'+all_sents[wd_count+1]) scor_count += 1 wd_count += 2 scount",
"= [] nscore = [] nfeat = [] while scount < slen: lscount",
"= pickle.load(open(fscore,'rb')) nfeats = pickle.load(open(fnfeat,'rb')) for i in range(len(sents)): temp_score, _, s_matrix =",
"asent_score.append(score[scor_count]) nscore.append(temp_score) asents.append(all_sents[wd_count]+'\\t'+all_sents[wd_count+1]) scor_count += 1 wd_count += 2 scount = lscount #",
"open(v_csv_file,'w') sents_fd = open(sent_file,'w') all_nscore = [] all_nfeat = [] for i in",
"wds = extract_batchfeature_using_senna(all_sents) wd_len = len(wds) wd_count = 0 scor_count = 0 while",
"asents.append(all_sents[wd_count]+'\\t'+all_sents[wd_count+1]) scor_count += 1 wd_count += 2 scount = lscount # # print",
"IndexError: pass wds = extract_batchfeature_using_senna(all_sents) wd_len = len(wds) wd_count = 0 scor_count =",
"csv_txt += ',' + str(j) csv_txt += '\\n' data_csv_fd.write(csv_txt) sents_fd.write(sent_txt) pickle.dump(all_nscore,open(nscore_txt, 'wb')) data_csv_fd.close()",
"data_csv_fd.write(csv_txt) sents_fd.write(sent_txt) pickle.dump(all_nscore,open(nscore_txt, 'wb')) data_csv_fd.close() sents_fd.close() return v_csv_file, sent_file def wd_making(fname,stp): sent_fd =",
"line2]) nfeat.append(get_n_feature(line1, line2)) temp = extract_batchfeature_using_senna([line1, line2]) print count, if len(temp) !=2: print",
"pf=pf) all_nscore += score all_nfeat += nfeat csv_txt = '' sent_txt = ''",
"[] sents, sents_vect, score, nscore, nfeat = test_get_vect_data_by_dep(fpickle = tpickle,fsent=tsent, fscore=tscore, fnfeat=tnfeat, pool_size=pool_size,",
"asent_score, nscore, nfeat def test_get_vect_data_by_dep(fsent, fpickle, fscore, fnfeat, pool_size, mtype, pf): # print",
"Global if __name__=='__main__': testf = '/media/zero/41FF48D81730BD9B/Final_Thesies/data/NN-dataset/MSRParaphraseCorpus/test/msr_paraphrase_test.txt' trainf = '/media/zero/41FF48D81730BD9B/Final_Thesies/data/NN-dataset/MSRParaphraseCorpus/train/msr_paraphrase_train.txt' Global.init() # Global.init_wv_self(0,50) #",
"return asents, asents_vect, asent_score, nscore, nfeat def test_get_vect_data_by_dep(fsent, fpickle, fscore, fnfeat, pool_size, mtype,",
"<filename>training_dataset_maker1.py import os from utility1 import extract_batchfeature_using_senna, get_parents, get_dep, get_words_id, pdep_2_deporder_dep, dep_2_hid_var from",
"'.pickle' tscore= src_dir+ 'msr_paraphrase_trainscore'+ str(stp) + '.pickle' tnfeat= src_dir+ 'msr_paraphrase_trainnfeat'+ str(stp) + '.pickle'",
"+= '\\n' data_csv_fd.write(csv_txt) sents_fd.write(sent_txt) pickle.dump(all_nscore,open(nscore_txt, 'wb')) data_csv_fd.close() sents_fd.close() return v_csv_file, sent_file def wd_making(fname,stp):"
] |
[
"sys import timeit from nemo.parser import NemoParser from mako.template import Template if len(sys.argv)",
"so mako won't render a result return '' def nemo_render(str, debug=False): return NemoParser(debug=debug).parse(str)",
"= 10000 t_mako = timeit.Timer('mako_temp.render()', 'from __main__ import mako_temp') t_nemo = timeit.Timer('nemo_temp.render()', 'from",
"Nothing so mako won't render a result return '' def nemo_render(str, debug=False): return",
"'from __main__ import nemo_temp') t_nemo_render = timeit.Timer('nemo_temp_render.render()', 'from __main__ import nemo_temp_render') mako_time =",
"if len(sys.argv) > 1: filename = sys.argv[1] else: print 'A filename is required'",
"def nemo_render(str, debug=False): return NemoParser(debug=debug).parse(str) mako_temp = Template(filename=filename, input_encoding='utf-8', output_encoding='utf-8',) nemo_temp = Template(filename=filename,",
"* mako_time) print 'Nemo (w/o mako render): %.2f ms' % (1000 * nemo_time)",
"nemo_temp_render = Template(filename=filename, preprocessor=nemo_render, input_encoding='utf-8', output_encoding='utf-8',) number = 10000 t_mako = timeit.Timer('mako_temp.render()', 'from",
"'Mako (full render w/o nemo): %.2f ms' % (1000 * mako_time) print 'Nemo",
"w/o nemo): %.2f ms' % (1000 * mako_time) print 'Nemo (w/o mako render):",
"input_encoding='utf-8', output_encoding='utf-8',) nemo_temp_render = Template(filename=filename, preprocessor=nemo_render, input_encoding='utf-8', output_encoding='utf-8',) number = 10000 t_mako =",
"sys.argv[1] else: print 'A filename is required' exit() def nemo(str, debug=False): NemoParser(debug=debug).parse(str) #",
"'' def nemo_render(str, debug=False): return NemoParser(debug=debug).parse(str) mako_temp = Template(filename=filename, input_encoding='utf-8', output_encoding='utf-8',) nemo_temp =",
"filename = sys.argv[1] else: print 'A filename is required' exit() def nemo(str, debug=False):",
"def nemo(str, debug=False): NemoParser(debug=debug).parse(str) # Return Nothing so mako won't render a result",
"NemoParser(debug=debug).parse(str) # Return Nothing so mako won't render a result return '' def",
"t_mako = timeit.Timer('mako_temp.render()', 'from __main__ import mako_temp') t_nemo = timeit.Timer('nemo_temp.render()', 'from __main__ import",
"required' exit() def nemo(str, debug=False): NemoParser(debug=debug).parse(str) # Return Nothing so mako won't render",
"t_nemo = timeit.Timer('nemo_temp.render()', 'from __main__ import nemo_temp') t_nemo_render = timeit.Timer('nemo_temp_render.render()', 'from __main__ import",
"= t_nemo_render.timeit(number=number) / number print 'Mako (full render w/o nemo): %.2f ms' %",
"/ number print 'Mako (full render w/o nemo): %.2f ms' % (1000 *",
"= t_nemo.timeit(number=number) / number nemo_time_render = t_nemo_render.timeit(number=number) / number print 'Mako (full render",
"Template(filename=filename, preprocessor=nemo, input_encoding='utf-8', output_encoding='utf-8',) nemo_temp_render = Template(filename=filename, preprocessor=nemo_render, input_encoding='utf-8', output_encoding='utf-8',) number = 10000",
"__main__ import mako_temp') t_nemo = timeit.Timer('nemo_temp.render()', 'from __main__ import nemo_temp') t_nemo_render = timeit.Timer('nemo_temp_render.render()',",
"result return '' def nemo_render(str, debug=False): return NemoParser(debug=debug).parse(str) mako_temp = Template(filename=filename, input_encoding='utf-8', output_encoding='utf-8',)",
"ms' % (1000 * mako_time) print 'Nemo (w/o mako render): %.2f ms' %",
"%.2f ms' % (1000 * mako_time) print 'Nemo (w/o mako render): %.2f ms'",
"(w/o mako render): %.2f ms' % (1000 * nemo_time) print 'Nemo (w/ mako",
"= Template(filename=filename, input_encoding='utf-8', output_encoding='utf-8',) nemo_temp = Template(filename=filename, preprocessor=nemo, input_encoding='utf-8', output_encoding='utf-8',) nemo_temp_render = Template(filename=filename,",
"import NemoParser from mako.template import Template if len(sys.argv) > 1: filename = sys.argv[1]",
"Template if len(sys.argv) > 1: filename = sys.argv[1] else: print 'A filename is",
"nemo_temp_render') mako_time = t_mako.timeit(number=number) / number nemo_time = t_nemo.timeit(number=number) / number nemo_time_render =",
"(1000 * mako_time) print 'Nemo (w/o mako render): %.2f ms' % (1000 *",
"NemoParser(debug=debug).parse(str) mako_temp = Template(filename=filename, input_encoding='utf-8', output_encoding='utf-8',) nemo_temp = Template(filename=filename, preprocessor=nemo, input_encoding='utf-8', output_encoding='utf-8',) nemo_temp_render",
"nemo_render(str, debug=False): return NemoParser(debug=debug).parse(str) mako_temp = Template(filename=filename, input_encoding='utf-8', output_encoding='utf-8',) nemo_temp = Template(filename=filename, preprocessor=nemo,",
"% (1000 * nemo_time) print 'Nemo (w/ mako render): %.2f ms' % (1000",
"t_nemo.timeit(number=number) / number nemo_time_render = t_nemo_render.timeit(number=number) / number print 'Mako (full render w/o",
"nemo_temp') t_nemo_render = timeit.Timer('nemo_temp_render.render()', 'from __main__ import nemo_temp_render') mako_time = t_mako.timeit(number=number) / number",
"print 'Nemo (w/o mako render): %.2f ms' % (1000 * nemo_time) print 'Nemo",
"'Nemo (w/o mako render): %.2f ms' % (1000 * nemo_time) print 'Nemo (w/",
"mako_time = t_mako.timeit(number=number) / number nemo_time = t_nemo.timeit(number=number) / number nemo_time_render = t_nemo_render.timeit(number=number)",
"from mako.template import Template if len(sys.argv) > 1: filename = sys.argv[1] else: print",
"import sys import timeit from nemo.parser import NemoParser from mako.template import Template if",
"timeit.Timer('mako_temp.render()', 'from __main__ import mako_temp') t_nemo = timeit.Timer('nemo_temp.render()', 'from __main__ import nemo_temp') t_nemo_render",
"timeit.Timer('nemo_temp.render()', 'from __main__ import nemo_temp') t_nemo_render = timeit.Timer('nemo_temp_render.render()', 'from __main__ import nemo_temp_render') mako_time",
"output_encoding='utf-8',) nemo_temp = Template(filename=filename, preprocessor=nemo, input_encoding='utf-8', output_encoding='utf-8',) nemo_temp_render = Template(filename=filename, preprocessor=nemo_render, input_encoding='utf-8', output_encoding='utf-8',)",
"# Return Nothing so mako won't render a result return '' def nemo_render(str,",
"(full render w/o nemo): %.2f ms' % (1000 * mako_time) print 'Nemo (w/o",
"import timeit from nemo.parser import NemoParser from mako.template import Template if len(sys.argv) >",
"import Template if len(sys.argv) > 1: filename = sys.argv[1] else: print 'A filename",
"nemo): %.2f ms' % (1000 * mako_time) print 'Nemo (w/o mako render): %.2f",
"input_encoding='utf-8', output_encoding='utf-8',) number = 10000 t_mako = timeit.Timer('mako_temp.render()', 'from __main__ import mako_temp') t_nemo",
"= timeit.Timer('nemo_temp_render.render()', 'from __main__ import nemo_temp_render') mako_time = t_mako.timeit(number=number) / number nemo_time =",
"output_encoding='utf-8',) nemo_temp_render = Template(filename=filename, preprocessor=nemo_render, input_encoding='utf-8', output_encoding='utf-8',) number = 10000 t_mako = timeit.Timer('mako_temp.render()',",
"1: filename = sys.argv[1] else: print 'A filename is required' exit() def nemo(str,",
"__main__ import nemo_temp') t_nemo_render = timeit.Timer('nemo_temp_render.render()', 'from __main__ import nemo_temp_render') mako_time = t_mako.timeit(number=number)",
"number = 10000 t_mako = timeit.Timer('mako_temp.render()', 'from __main__ import mako_temp') t_nemo = timeit.Timer('nemo_temp.render()',",
"import nemo_temp_render') mako_time = t_mako.timeit(number=number) / number nemo_time = t_nemo.timeit(number=number) / number nemo_time_render",
"won't render a result return '' def nemo_render(str, debug=False): return NemoParser(debug=debug).parse(str) mako_temp =",
"/ number nemo_time = t_nemo.timeit(number=number) / number nemo_time_render = t_nemo_render.timeit(number=number) / number print",
"preprocessor=nemo_render, input_encoding='utf-8', output_encoding='utf-8',) number = 10000 t_mako = timeit.Timer('mako_temp.render()', 'from __main__ import mako_temp')",
"__main__ import nemo_temp_render') mako_time = t_mako.timeit(number=number) / number nemo_time = t_nemo.timeit(number=number) / number",
"from nemo.parser import NemoParser from mako.template import Template if len(sys.argv) > 1: filename",
"'from __main__ import nemo_temp_render') mako_time = t_mako.timeit(number=number) / number nemo_time = t_nemo.timeit(number=number) /",
"* nemo_time) print 'Nemo (w/ mako render): %.2f ms' % (1000 * nemo_time_render)",
"Return Nothing so mako won't render a result return '' def nemo_render(str, debug=False):",
"Template(filename=filename, preprocessor=nemo_render, input_encoding='utf-8', output_encoding='utf-8',) number = 10000 t_mako = timeit.Timer('mako_temp.render()', 'from __main__ import",
"<reponame>KaySackey/Nemo<filename>nemo_benchmark.py<gh_stars>1-10 import sys import timeit from nemo.parser import NemoParser from mako.template import Template",
"= Template(filename=filename, preprocessor=nemo_render, input_encoding='utf-8', output_encoding='utf-8',) number = 10000 t_mako = timeit.Timer('mako_temp.render()', 'from __main__",
"nemo_temp = Template(filename=filename, preprocessor=nemo, input_encoding='utf-8', output_encoding='utf-8',) nemo_temp_render = Template(filename=filename, preprocessor=nemo_render, input_encoding='utf-8', output_encoding='utf-8',) number",
"preprocessor=nemo, input_encoding='utf-8', output_encoding='utf-8',) nemo_temp_render = Template(filename=filename, preprocessor=nemo_render, input_encoding='utf-8', output_encoding='utf-8',) number = 10000 t_mako",
"number nemo_time_render = t_nemo_render.timeit(number=number) / number print 'Mako (full render w/o nemo): %.2f",
"len(sys.argv) > 1: filename = sys.argv[1] else: print 'A filename is required' exit()",
"%.2f ms' % (1000 * nemo_time) print 'Nemo (w/ mako render): %.2f ms'",
"= sys.argv[1] else: print 'A filename is required' exit() def nemo(str, debug=False): NemoParser(debug=debug).parse(str)",
"mako.template import Template if len(sys.argv) > 1: filename = sys.argv[1] else: print 'A",
"render): %.2f ms' % (1000 * nemo_time) print 'Nemo (w/ mako render): %.2f",
"Template(filename=filename, input_encoding='utf-8', output_encoding='utf-8',) nemo_temp = Template(filename=filename, preprocessor=nemo, input_encoding='utf-8', output_encoding='utf-8',) nemo_temp_render = Template(filename=filename, preprocessor=nemo_render,",
"mako won't render a result return '' def nemo_render(str, debug=False): return NemoParser(debug=debug).parse(str) mako_temp",
"10000 t_mako = timeit.Timer('mako_temp.render()', 'from __main__ import mako_temp') t_nemo = timeit.Timer('nemo_temp.render()', 'from __main__",
"mako_temp') t_nemo = timeit.Timer('nemo_temp.render()', 'from __main__ import nemo_temp') t_nemo_render = timeit.Timer('nemo_temp_render.render()', 'from __main__",
"mako render): %.2f ms' % (1000 * nemo_time) print 'Nemo (w/ mako render):",
"exit() def nemo(str, debug=False): NemoParser(debug=debug).parse(str) # Return Nothing so mako won't render a",
"input_encoding='utf-8', output_encoding='utf-8',) nemo_temp = Template(filename=filename, preprocessor=nemo, input_encoding='utf-8', output_encoding='utf-8',) nemo_temp_render = Template(filename=filename, preprocessor=nemo_render, input_encoding='utf-8',",
"debug=False): NemoParser(debug=debug).parse(str) # Return Nothing so mako won't render a result return ''",
"return NemoParser(debug=debug).parse(str) mako_temp = Template(filename=filename, input_encoding='utf-8', output_encoding='utf-8',) nemo_temp = Template(filename=filename, preprocessor=nemo, input_encoding='utf-8', output_encoding='utf-8',)",
"import nemo_temp') t_nemo_render = timeit.Timer('nemo_temp_render.render()', 'from __main__ import nemo_temp_render') mako_time = t_mako.timeit(number=number) /",
"nemo_time_render = t_nemo_render.timeit(number=number) / number print 'Mako (full render w/o nemo): %.2f ms'",
"else: print 'A filename is required' exit() def nemo(str, debug=False): NemoParser(debug=debug).parse(str) # Return",
"> 1: filename = sys.argv[1] else: print 'A filename is required' exit() def",
"'from __main__ import mako_temp') t_nemo = timeit.Timer('nemo_temp.render()', 'from __main__ import nemo_temp') t_nemo_render =",
"= timeit.Timer('mako_temp.render()', 'from __main__ import mako_temp') t_nemo = timeit.Timer('nemo_temp.render()', 'from __main__ import nemo_temp')",
"t_nemo_render = timeit.Timer('nemo_temp_render.render()', 'from __main__ import nemo_temp_render') mako_time = t_mako.timeit(number=number) / number nemo_time",
"is required' exit() def nemo(str, debug=False): NemoParser(debug=debug).parse(str) # Return Nothing so mako won't",
"output_encoding='utf-8',) number = 10000 t_mako = timeit.Timer('mako_temp.render()', 'from __main__ import mako_temp') t_nemo =",
"= timeit.Timer('nemo_temp.render()', 'from __main__ import nemo_temp') t_nemo_render = timeit.Timer('nemo_temp_render.render()', 'from __main__ import nemo_temp_render')",
"= t_mako.timeit(number=number) / number nemo_time = t_nemo.timeit(number=number) / number nemo_time_render = t_nemo_render.timeit(number=number) /",
"nemo.parser import NemoParser from mako.template import Template if len(sys.argv) > 1: filename =",
"'A filename is required' exit() def nemo(str, debug=False): NemoParser(debug=debug).parse(str) # Return Nothing so",
"(1000 * nemo_time) print 'Nemo (w/ mako render): %.2f ms' % (1000 *",
"number print 'Mako (full render w/o nemo): %.2f ms' % (1000 * mako_time)",
"nemo_time = t_nemo.timeit(number=number) / number nemo_time_render = t_nemo_render.timeit(number=number) / number print 'Mako (full",
"number nemo_time = t_nemo.timeit(number=number) / number nemo_time_render = t_nemo_render.timeit(number=number) / number print 'Mako",
"print 'Mako (full render w/o nemo): %.2f ms' % (1000 * mako_time) print",
"t_nemo_render.timeit(number=number) / number print 'Mako (full render w/o nemo): %.2f ms' % (1000",
"/ number nemo_time_render = t_nemo_render.timeit(number=number) / number print 'Mako (full render w/o nemo):",
"NemoParser from mako.template import Template if len(sys.argv) > 1: filename = sys.argv[1] else:",
"nemo(str, debug=False): NemoParser(debug=debug).parse(str) # Return Nothing so mako won't render a result return",
"a result return '' def nemo_render(str, debug=False): return NemoParser(debug=debug).parse(str) mako_temp = Template(filename=filename, input_encoding='utf-8',",
"% (1000 * mako_time) print 'Nemo (w/o mako render): %.2f ms' % (1000",
"mako_temp = Template(filename=filename, input_encoding='utf-8', output_encoding='utf-8',) nemo_temp = Template(filename=filename, preprocessor=nemo, input_encoding='utf-8', output_encoding='utf-8',) nemo_temp_render =",
"t_mako.timeit(number=number) / number nemo_time = t_nemo.timeit(number=number) / number nemo_time_render = t_nemo_render.timeit(number=number) / number",
"return '' def nemo_render(str, debug=False): return NemoParser(debug=debug).parse(str) mako_temp = Template(filename=filename, input_encoding='utf-8', output_encoding='utf-8',) nemo_temp",
"render a result return '' def nemo_render(str, debug=False): return NemoParser(debug=debug).parse(str) mako_temp = Template(filename=filename,",
"print 'A filename is required' exit() def nemo(str, debug=False): NemoParser(debug=debug).parse(str) # Return Nothing",
"import mako_temp') t_nemo = timeit.Timer('nemo_temp.render()', 'from __main__ import nemo_temp') t_nemo_render = timeit.Timer('nemo_temp_render.render()', 'from",
"timeit.Timer('nemo_temp_render.render()', 'from __main__ import nemo_temp_render') mako_time = t_mako.timeit(number=number) / number nemo_time = t_nemo.timeit(number=number)",
"filename is required' exit() def nemo(str, debug=False): NemoParser(debug=debug).parse(str) # Return Nothing so mako",
"ms' % (1000 * nemo_time) print 'Nemo (w/ mako render): %.2f ms' %",
"render w/o nemo): %.2f ms' % (1000 * mako_time) print 'Nemo (w/o mako",
"mako_time) print 'Nemo (w/o mako render): %.2f ms' % (1000 * nemo_time) print",
"= Template(filename=filename, preprocessor=nemo, input_encoding='utf-8', output_encoding='utf-8',) nemo_temp_render = Template(filename=filename, preprocessor=nemo_render, input_encoding='utf-8', output_encoding='utf-8',) number =",
"debug=False): return NemoParser(debug=debug).parse(str) mako_temp = Template(filename=filename, input_encoding='utf-8', output_encoding='utf-8',) nemo_temp = Template(filename=filename, preprocessor=nemo, input_encoding='utf-8',",
"timeit from nemo.parser import NemoParser from mako.template import Template if len(sys.argv) > 1:"
] |
[
"from rply import LexingError, ParsingError from lang.lexer import Lexer from lang.parser import Parser",
"lexer_output=False, opt=False): try: tokens = lexer.lex(source) if lexer_output: print(\"LEXER OUTPUT\") for token in",
"lexer_output: print(\"LEXER OUTPUT\") for token in copy.copy(tokens): print(token) print() print(\"PROGRAM OUTPUT\") ast =",
"arg_parser = argparse.ArgumentParser() arg_parser.add_argument(\"file\", nargs=\"?\", help=\"path to script\") arg_parser.add_argument( \"-a\", \"--ast\", help=\"draw abstract",
"= Lexer() parser = Parser(lexer.tokens) def execute(scope, source, draw=False, lexer_output=False, opt=False): try: tokens",
"scope.last_pop) except KeyboardInterrupt: break def run_file(path, draw=False, lexer_output=False): scope = Scope() with open(path,",
"syntax tree\", action=\"store_true\" ) arg_parser.add_argument( \"-l\", \"--lexer\", help=\"print lexer output\", action=\"store_true\" ) args",
"ast.eval(True, scope) result = ast.eval(False, scope) # Draw AST graph if draw: g",
"opt: ast.eval(True, scope) result = ast.eval(False, scope) # Draw AST graph if draw:",
"True: try: source = input(\"> \") result = execute(scope, source) if result is",
"source, draw=False, lexer_output=False, opt=False): try: tokens = lexer.lex(source) if lexer_output: print(\"LEXER OUTPUT\") for",
"sys import copy from graphviz import Digraph from rply import LexingError, ParsingError from",
"Parser from lang.scope import Scope lexer = Lexer() parser = Parser(lexer.tokens) def execute(scope,",
"source = input(\"> \") result = execute(scope, source) if result is not None:",
"ast.eval(False, scope) # Draw AST graph if draw: g = Digraph() ast.draw(g) g.render(\"ast\",",
"None: scope.symbols_stack.insert(0, scope.last_pop) except KeyboardInterrupt: break def run_file(path, draw=False, lexer_output=False): scope = Scope()",
"from lang.scope import Scope lexer = Lexer() parser = Parser(lexer.tokens) def execute(scope, source,",
"f.read() execute(scope, source, draw=draw, lexer_output=lexer_output) if __name__ == \"__main__\": arg_parser = argparse.ArgumentParser() arg_parser.add_argument(\"file\",",
"OUTPUT\") for token in copy.copy(tokens): print(token) print() print(\"PROGRAM OUTPUT\") ast = parser.parse(tokens) #",
"scope = Scope() with open(path, \"r\") as f: source = f.read() execute(scope, source,",
"AST graph if draw: g = Digraph() ast.draw(g) g.render(\"ast\", format=\"png\", view=True, cleanup=True) return",
"= Scope() while True: try: source = input(\"> \") result = execute(scope, source)",
"argparse.ArgumentParser() arg_parser.add_argument(\"file\", nargs=\"?\", help=\"path to script\") arg_parser.add_argument( \"-a\", \"--ast\", help=\"draw abstract syntax tree\",",
"run_file(path, draw=False, lexer_output=False): scope = Scope() with open(path, \"r\") as f: source =",
"arg_parser.add_argument( \"-a\", \"--ast\", help=\"draw abstract syntax tree\", action=\"store_true\" ) arg_parser.add_argument( \"-l\", \"--lexer\", help=\"print",
"import argparse import sys import copy from graphviz import Digraph from rply import",
"= lexer.lex(source) if lexer_output: print(\"LEXER OUTPUT\") for token in copy.copy(tokens): print(token) print() print(\"PROGRAM",
"help=\"print lexer output\", action=\"store_true\" ) args = arg_parser.parse_args() if args.file: run_file(args.file, draw=args.ast, lexer_output=args.lexer)",
"except KeyboardInterrupt: break def run_file(path, draw=False, lexer_output=False): scope = Scope() with open(path, \"r\")",
"if __name__ == \"__main__\": arg_parser = argparse.ArgumentParser() arg_parser.add_argument(\"file\", nargs=\"?\", help=\"path to script\") arg_parser.add_argument(",
"= ast.eval(False, scope) # Draw AST graph if draw: g = Digraph() ast.draw(g)",
"not None: print(result) if scope.last_pop is not None: scope.symbols_stack.insert(0, scope.last_pop) except KeyboardInterrupt: break",
"scope.symbols_stack.insert(0, scope.last_pop) except KeyboardInterrupt: break def run_file(path, draw=False, lexer_output=False): scope = Scope() with",
"scope = Scope() while True: try: source = input(\"> \") result = execute(scope,",
"from graphviz import Digraph from rply import LexingError, ParsingError from lang.lexer import Lexer",
"Digraph from rply import LexingError, ParsingError from lang.lexer import Lexer from lang.parser import",
"try: source = input(\"> \") result = execute(scope, source) if result is not",
"error\") def run_repl(): scope = Scope() while True: try: source = input(\"> \")",
"result is not None: print(result) if scope.last_pop is not None: scope.symbols_stack.insert(0, scope.last_pop) except",
"nargs=\"?\", help=\"path to script\") arg_parser.add_argument( \"-a\", \"--ast\", help=\"draw abstract syntax tree\", action=\"store_true\" )",
"import sys import copy from graphviz import Digraph from rply import LexingError, ParsingError",
"lang.lexer import Lexer from lang.parser import Parser from lang.scope import Scope lexer =",
"# Draw AST graph if draw: g = Digraph() ast.draw(g) g.render(\"ast\", format=\"png\", view=True,",
"g.render(\"ast\", format=\"png\", view=True, cleanup=True) return result except ValueError as err: print(err) except LexingError:",
"help=\"draw abstract syntax tree\", action=\"store_true\" ) arg_parser.add_argument( \"-l\", \"--lexer\", help=\"print lexer output\", action=\"store_true\"",
"format=\"png\", view=True, cleanup=True) return result except ValueError as err: print(err) except LexingError: print(\"Lexing",
"if draw: g = Digraph() ast.draw(g) g.render(\"ast\", format=\"png\", view=True, cleanup=True) return result except",
"execute(scope, source) if result is not None: print(result) if scope.last_pop is not None:",
"\"r\") as f: source = f.read() execute(scope, source, draw=draw, lexer_output=lexer_output) if __name__ ==",
"print(\"LEXER OUTPUT\") for token in copy.copy(tokens): print(token) print() print(\"PROGRAM OUTPUT\") ast = parser.parse(tokens)",
"action=\"store_true\" ) arg_parser.add_argument( \"-l\", \"--lexer\", help=\"print lexer output\", action=\"store_true\" ) args = arg_parser.parse_args()",
"KeyboardInterrupt: break def run_file(path, draw=False, lexer_output=False): scope = Scope() with open(path, \"r\") as",
"= Scope() with open(path, \"r\") as f: source = f.read() execute(scope, source, draw=draw,",
"ast.draw(g) g.render(\"ast\", format=\"png\", view=True, cleanup=True) return result except ValueError as err: print(err) except",
"= input(\"> \") result = execute(scope, source) if result is not None: print(result)",
"output\", action=\"store_true\" ) args = arg_parser.parse_args() if args.file: run_file(args.file, draw=args.ast, lexer_output=args.lexer) else: run_repl()",
"lexer = Lexer() parser = Parser(lexer.tokens) def execute(scope, source, draw=False, lexer_output=False, opt=False): try:",
"cleanup=True) return result except ValueError as err: print(err) except LexingError: print(\"Lexing error\") except",
"import Scope lexer = Lexer() parser = Parser(lexer.tokens) def execute(scope, source, draw=False, lexer_output=False,",
"Lexer from lang.parser import Parser from lang.scope import Scope lexer = Lexer() parser",
"\") result = execute(scope, source) if result is not None: print(result) if scope.last_pop",
"lang.parser import Parser from lang.scope import Scope lexer = Lexer() parser = Parser(lexer.tokens)",
"source) if result is not None: print(result) if scope.last_pop is not None: scope.symbols_stack.insert(0,",
"break def run_file(path, draw=False, lexer_output=False): scope = Scope() with open(path, \"r\") as f:",
"draw: g = Digraph() ast.draw(g) g.render(\"ast\", format=\"png\", view=True, cleanup=True) return result except ValueError",
"LexingError, ParsingError from lang.lexer import Lexer from lang.parser import Parser from lang.scope import",
"def execute(scope, source, draw=False, lexer_output=False, opt=False): try: tokens = lexer.lex(source) if lexer_output: print(\"LEXER",
"for token in copy.copy(tokens): print(token) print() print(\"PROGRAM OUTPUT\") ast = parser.parse(tokens) # Optimize",
"graphviz import Digraph from rply import LexingError, ParsingError from lang.lexer import Lexer from",
"with open(path, \"r\") as f: source = f.read() execute(scope, source, draw=draw, lexer_output=lexer_output) if",
"source, draw=draw, lexer_output=lexer_output) if __name__ == \"__main__\": arg_parser = argparse.ArgumentParser() arg_parser.add_argument(\"file\", nargs=\"?\", help=\"path",
"= Digraph() ast.draw(g) g.render(\"ast\", format=\"png\", view=True, cleanup=True) return result except ValueError as err:",
"import Digraph from rply import LexingError, ParsingError from lang.lexer import Lexer from lang.parser",
"if lexer_output: print(\"LEXER OUTPUT\") for token in copy.copy(tokens): print(token) print() print(\"PROGRAM OUTPUT\") ast",
"view=True, cleanup=True) return result except ValueError as err: print(err) except LexingError: print(\"Lexing error\")",
"== \"__main__\": arg_parser = argparse.ArgumentParser() arg_parser.add_argument(\"file\", nargs=\"?\", help=\"path to script\") arg_parser.add_argument( \"-a\", \"--ast\",",
"\"-a\", \"--ast\", help=\"draw abstract syntax tree\", action=\"store_true\" ) arg_parser.add_argument( \"-l\", \"--lexer\", help=\"print lexer",
"is not None: scope.symbols_stack.insert(0, scope.last_pop) except KeyboardInterrupt: break def run_file(path, draw=False, lexer_output=False): scope",
"return result except ValueError as err: print(err) except LexingError: print(\"Lexing error\") except ParsingError:",
"tokens = lexer.lex(source) if lexer_output: print(\"LEXER OUTPUT\") for token in copy.copy(tokens): print(token) print()",
"ast = parser.parse(tokens) # Optimize if opt: ast.eval(True, scope) result = ast.eval(False, scope)",
"import Lexer from lang.parser import Parser from lang.scope import Scope lexer = Lexer()",
"Draw AST graph if draw: g = Digraph() ast.draw(g) g.render(\"ast\", format=\"png\", view=True, cleanup=True)",
"from lang.parser import Parser from lang.scope import Scope lexer = Lexer() parser =",
"rply import LexingError, ParsingError from lang.lexer import Lexer from lang.parser import Parser from",
"result = ast.eval(False, scope) # Draw AST graph if draw: g = Digraph()",
"OUTPUT\") ast = parser.parse(tokens) # Optimize if opt: ast.eval(True, scope) result = ast.eval(False,",
"except LexingError: print(\"Lexing error\") except ParsingError: print(\"Parsing error\") def run_repl(): scope = Scope()",
"draw=draw, lexer_output=lexer_output) if __name__ == \"__main__\": arg_parser = argparse.ArgumentParser() arg_parser.add_argument(\"file\", nargs=\"?\", help=\"path to",
"print(result) if scope.last_pop is not None: scope.symbols_stack.insert(0, scope.last_pop) except KeyboardInterrupt: break def run_file(path,",
"while True: try: source = input(\"> \") result = execute(scope, source) if result",
"if opt: ast.eval(True, scope) result = ast.eval(False, scope) # Draw AST graph if",
"argparse import sys import copy from graphviz import Digraph from rply import LexingError,",
"import copy from graphviz import Digraph from rply import LexingError, ParsingError from lang.lexer",
"= parser.parse(tokens) # Optimize if opt: ast.eval(True, scope) result = ast.eval(False, scope) #",
"token in copy.copy(tokens): print(token) print() print(\"PROGRAM OUTPUT\") ast = parser.parse(tokens) # Optimize if",
"Scope lexer = Lexer() parser = Parser(lexer.tokens) def execute(scope, source, draw=False, lexer_output=False, opt=False):",
"run_repl(): scope = Scope() while True: try: source = input(\"> \") result =",
"import LexingError, ParsingError from lang.lexer import Lexer from lang.parser import Parser from lang.scope",
"= f.read() execute(scope, source, draw=draw, lexer_output=lexer_output) if __name__ == \"__main__\": arg_parser = argparse.ArgumentParser()",
"to script\") arg_parser.add_argument( \"-a\", \"--ast\", help=\"draw abstract syntax tree\", action=\"store_true\" ) arg_parser.add_argument( \"-l\",",
"lexer output\", action=\"store_true\" ) args = arg_parser.parse_args() if args.file: run_file(args.file, draw=args.ast, lexer_output=args.lexer) else:",
"in copy.copy(tokens): print(token) print() print(\"PROGRAM OUTPUT\") ast = parser.parse(tokens) # Optimize if opt:",
"parser.parse(tokens) # Optimize if opt: ast.eval(True, scope) result = ast.eval(False, scope) # Draw",
"\"-l\", \"--lexer\", help=\"print lexer output\", action=\"store_true\" ) args = arg_parser.parse_args() if args.file: run_file(args.file,",
"lang.scope import Scope lexer = Lexer() parser = Parser(lexer.tokens) def execute(scope, source, draw=False,",
"except ParsingError: print(\"Parsing error\") def run_repl(): scope = Scope() while True: try: source",
"input(\"> \") result = execute(scope, source) if result is not None: print(result) if",
"import Parser from lang.scope import Scope lexer = Lexer() parser = Parser(lexer.tokens) def",
"ValueError as err: print(err) except LexingError: print(\"Lexing error\") except ParsingError: print(\"Parsing error\") def",
"LexingError: print(\"Lexing error\") except ParsingError: print(\"Parsing error\") def run_repl(): scope = Scope() while",
"try: tokens = lexer.lex(source) if lexer_output: print(\"LEXER OUTPUT\") for token in copy.copy(tokens): print(token)",
"open(path, \"r\") as f: source = f.read() execute(scope, source, draw=draw, lexer_output=lexer_output) if __name__",
"print(\"Parsing error\") def run_repl(): scope = Scope() while True: try: source = input(\">",
"error\") except ParsingError: print(\"Parsing error\") def run_repl(): scope = Scope() while True: try:",
"scope) # Draw AST graph if draw: g = Digraph() ast.draw(g) g.render(\"ast\", format=\"png\",",
"f: source = f.read() execute(scope, source, draw=draw, lexer_output=lexer_output) if __name__ == \"__main__\": arg_parser",
"script\") arg_parser.add_argument( \"-a\", \"--ast\", help=\"draw abstract syntax tree\", action=\"store_true\" ) arg_parser.add_argument( \"-l\", \"--lexer\",",
"lexer.lex(source) if lexer_output: print(\"LEXER OUTPUT\") for token in copy.copy(tokens): print(token) print() print(\"PROGRAM OUTPUT\")",
"source = f.read() execute(scope, source, draw=draw, lexer_output=lexer_output) if __name__ == \"__main__\": arg_parser =",
"\"--ast\", help=\"draw abstract syntax tree\", action=\"store_true\" ) arg_parser.add_argument( \"-l\", \"--lexer\", help=\"print lexer output\",",
"Scope() while True: try: source = input(\"> \") result = execute(scope, source) if",
"opt=False): try: tokens = lexer.lex(source) if lexer_output: print(\"LEXER OUTPUT\") for token in copy.copy(tokens):",
"not None: scope.symbols_stack.insert(0, scope.last_pop) except KeyboardInterrupt: break def run_file(path, draw=False, lexer_output=False): scope =",
"arg_parser.add_argument( \"-l\", \"--lexer\", help=\"print lexer output\", action=\"store_true\" ) args = arg_parser.parse_args() if args.file:",
"lexer_output=lexer_output) if __name__ == \"__main__\": arg_parser = argparse.ArgumentParser() arg_parser.add_argument(\"file\", nargs=\"?\", help=\"path to script\")",
"def run_repl(): scope = Scope() while True: try: source = input(\"> \") result",
"except ValueError as err: print(err) except LexingError: print(\"Lexing error\") except ParsingError: print(\"Parsing error\")",
"as err: print(err) except LexingError: print(\"Lexing error\") except ParsingError: print(\"Parsing error\") def run_repl():",
"as f: source = f.read() execute(scope, source, draw=draw, lexer_output=lexer_output) if __name__ == \"__main__\":",
"\"__main__\": arg_parser = argparse.ArgumentParser() arg_parser.add_argument(\"file\", nargs=\"?\", help=\"path to script\") arg_parser.add_argument( \"-a\", \"--ast\", help=\"draw",
"if scope.last_pop is not None: scope.symbols_stack.insert(0, scope.last_pop) except KeyboardInterrupt: break def run_file(path, draw=False,",
"result = execute(scope, source) if result is not None: print(result) if scope.last_pop is",
"Digraph() ast.draw(g) g.render(\"ast\", format=\"png\", view=True, cleanup=True) return result except ValueError as err: print(err)",
"arg_parser.add_argument(\"file\", nargs=\"?\", help=\"path to script\") arg_parser.add_argument( \"-a\", \"--ast\", help=\"draw abstract syntax tree\", action=\"store_true\"",
") arg_parser.add_argument( \"-l\", \"--lexer\", help=\"print lexer output\", action=\"store_true\" ) args = arg_parser.parse_args() if",
"ParsingError from lang.lexer import Lexer from lang.parser import Parser from lang.scope import Scope",
"from lang.lexer import Lexer from lang.parser import Parser from lang.scope import Scope lexer",
"draw=False, lexer_output=False, opt=False): try: tokens = lexer.lex(source) if lexer_output: print(\"LEXER OUTPUT\") for token",
"Optimize if opt: ast.eval(True, scope) result = ast.eval(False, scope) # Draw AST graph",
"Scope() with open(path, \"r\") as f: source = f.read() execute(scope, source, draw=draw, lexer_output=lexer_output)",
"\"--lexer\", help=\"print lexer output\", action=\"store_true\" ) args = arg_parser.parse_args() if args.file: run_file(args.file, draw=args.ast,",
"execute(scope, source, draw=draw, lexer_output=lexer_output) if __name__ == \"__main__\": arg_parser = argparse.ArgumentParser() arg_parser.add_argument(\"file\", nargs=\"?\",",
"Lexer() parser = Parser(lexer.tokens) def execute(scope, source, draw=False, lexer_output=False, opt=False): try: tokens =",
"copy from graphviz import Digraph from rply import LexingError, ParsingError from lang.lexer import",
"= Parser(lexer.tokens) def execute(scope, source, draw=False, lexer_output=False, opt=False): try: tokens = lexer.lex(source) if",
"g = Digraph() ast.draw(g) g.render(\"ast\", format=\"png\", view=True, cleanup=True) return result except ValueError as",
"ParsingError: print(\"Parsing error\") def run_repl(): scope = Scope() while True: try: source =",
"tree\", action=\"store_true\" ) arg_parser.add_argument( \"-l\", \"--lexer\", help=\"print lexer output\", action=\"store_true\" ) args =",
"lexer_output=False): scope = Scope() with open(path, \"r\") as f: source = f.read() execute(scope,",
"def run_file(path, draw=False, lexer_output=False): scope = Scope() with open(path, \"r\") as f: source",
"print(\"PROGRAM OUTPUT\") ast = parser.parse(tokens) # Optimize if opt: ast.eval(True, scope) result =",
"= argparse.ArgumentParser() arg_parser.add_argument(\"file\", nargs=\"?\", help=\"path to script\") arg_parser.add_argument( \"-a\", \"--ast\", help=\"draw abstract syntax",
"= execute(scope, source) if result is not None: print(result) if scope.last_pop is not",
"None: print(result) if scope.last_pop is not None: scope.symbols_stack.insert(0, scope.last_pop) except KeyboardInterrupt: break def",
"__name__ == \"__main__\": arg_parser = argparse.ArgumentParser() arg_parser.add_argument(\"file\", nargs=\"?\", help=\"path to script\") arg_parser.add_argument( \"-a\",",
"Parser(lexer.tokens) def execute(scope, source, draw=False, lexer_output=False, opt=False): try: tokens = lexer.lex(source) if lexer_output:",
"print(\"Lexing error\") except ParsingError: print(\"Parsing error\") def run_repl(): scope = Scope() while True:",
"print() print(\"PROGRAM OUTPUT\") ast = parser.parse(tokens) # Optimize if opt: ast.eval(True, scope) result",
"print(err) except LexingError: print(\"Lexing error\") except ParsingError: print(\"Parsing error\") def run_repl(): scope =",
"abstract syntax tree\", action=\"store_true\" ) arg_parser.add_argument( \"-l\", \"--lexer\", help=\"print lexer output\", action=\"store_true\" )",
"graph if draw: g = Digraph() ast.draw(g) g.render(\"ast\", format=\"png\", view=True, cleanup=True) return result",
"if result is not None: print(result) if scope.last_pop is not None: scope.symbols_stack.insert(0, scope.last_pop)",
"execute(scope, source, draw=False, lexer_output=False, opt=False): try: tokens = lexer.lex(source) if lexer_output: print(\"LEXER OUTPUT\")",
"scope.last_pop is not None: scope.symbols_stack.insert(0, scope.last_pop) except KeyboardInterrupt: break def run_file(path, draw=False, lexer_output=False):",
"copy.copy(tokens): print(token) print() print(\"PROGRAM OUTPUT\") ast = parser.parse(tokens) # Optimize if opt: ast.eval(True,",
"help=\"path to script\") arg_parser.add_argument( \"-a\", \"--ast\", help=\"draw abstract syntax tree\", action=\"store_true\" ) arg_parser.add_argument(",
"draw=False, lexer_output=False): scope = Scope() with open(path, \"r\") as f: source = f.read()",
"scope) result = ast.eval(False, scope) # Draw AST graph if draw: g =",
"result except ValueError as err: print(err) except LexingError: print(\"Lexing error\") except ParsingError: print(\"Parsing",
"is not None: print(result) if scope.last_pop is not None: scope.symbols_stack.insert(0, scope.last_pop) except KeyboardInterrupt:",
"print(token) print() print(\"PROGRAM OUTPUT\") ast = parser.parse(tokens) # Optimize if opt: ast.eval(True, scope)",
"# Optimize if opt: ast.eval(True, scope) result = ast.eval(False, scope) # Draw AST",
"err: print(err) except LexingError: print(\"Lexing error\") except ParsingError: print(\"Parsing error\") def run_repl(): scope",
"parser = Parser(lexer.tokens) def execute(scope, source, draw=False, lexer_output=False, opt=False): try: tokens = lexer.lex(source)"
] |
[
"and automatically clears the text widget for you. On the txt file, entries",
"tk.PhotoImage(\"borderImage\", data=borderImageData) focusBorderImage = tk.PhotoImage(\"focusBorderImage\", data=focusBorderImageData) style.element_create(\"RoundedFrame\", \"image\", borderImage, (\"focus\", focusBorderImage), border=20, sticky=\"nsew\")",
"lambda event: frames[i].state([\"!focus\"])) text.insert(\"end\", \"\") texts.append(text) # CREATING THE BUTTONS FOLLOWING THE GIVEN",
"those widgets, # so I am using two base64-encoded gifs of a rounded-corner",
"THE BUTTON USING THE INDEX (\"i\") AS ARGUMENT button_check = tk.Button(frames[i], image =",
"root.configure(background=\"#BAD9D0\") #BAD9D0 #cfffff #D4F1B2 frameL.pack(side=tk.LEFT, fill=\"both\", expand=True) # side=tk.LEFT places frames side by",
"file with the same data, in which case only the time of writing",
"= 0, wrap = \"word\", width = 10, height = 5) text.pack(fill =",
"button clears the text widget (note: I had that link to a function",
"TO ACCESS THEM LATER frames.append(frame) # CREATING THE TEXT WIDGETS (I.E. THE INPUT",
"PARTIAL (IN \"command\") ALLOW US TO SET A COMMAND FOR THE BUTTON USING",
"i) elif i == 2: main_button = functions.create_buttons(frameL, functions.openJALL, \"JALL\", i) #Journal African",
"FRAME TO THE LIST TO ACCESS THEM LATER frames.append(frame) # CREATING THE TEXT",
"over those widgets, # so I am using two base64-encoded gifs of a",
"one is black (no-selection color). # CALLING A FUNCTION TO USE A BASE64-ENCODED",
"THE LEFT if i <= 2: frame = ttk.Frame(frameL, style=\"RoundedFrame\", padding=10) # THE",
"import filedialog import os import ctypes import functions from functools import partial import",
"style.element_create(\"RoundedFrame\", \"image\", borderImage, (\"focus\", focusBorderImage), border=20, sticky=\"nsew\") style.layout(\"RoundedFrame\", [(\"RoundedFrame\", {\"sticky\": \"nsew\"})]) style.configure('TFrame', background=",
"img_check = img_check.resize((30,30), Image.ANTIALIAS) img_photo_chk = ImageTk.PhotoImage(img_check) for i in range(6): # THE",
"African Languages & Linguistics elif i == 3: main_button = functions.create_buttons(frameR, functions.openheaviness, \"Heavi\",",
"button, # and I still haven't gotten around to linking it again) #",
"= functions.create_buttons(frameR, functions.openmisc, \"MISC\", i) main_button.config(image = img) main_button.pack(pady = 5) # SHOWING",
"1 # (\"Misc\", from \"Miscellaneous\"for taking impromptu notes on anything else that is",
"version of this code, then I removed the function but left the button,",
"want to be able to update multiple documents at the same # time",
"is black (no-selection color). # CALLING A FUNCTION TO USE A BASE64-ENCODED GIF",
"unless there is already an entry # on that txt file with the",
"if i <= 2: frame = ttk.Frame(frameL, style=\"RoundedFrame\", padding=10) # THE LAST 3",
"the name of the corresponding # project. If clicked, that button opens the",
"WIDGETS EACH frameL = tk.Frame(root, bg=\"#BAD9D0\") # cD4F1B2 is a light green color",
"img_cross = img_cross.resize((30,30), Image.ANTIALIAS) img_photo_crs = ImageTk.PhotoImage(img_cross) img_check = Image.open('check1.png') img_check = img_check.resize((30,30),",
"ROUNDED-CORNER SQUARE WITH A BLACK BORDER borderImageData = functions.border_string() style = ttk.Style() borderImage",
"fill=\"both\", expand=True) # side=tk.LEFT places frames side by side frameR.pack(side=tk.LEFT, fill=\"both\", expand=True) #",
"fill = \"both\", expand = True, padx = 30) # ADDING THE BUTTONS",
"text widget (note: I had that link to a function in # a",
"but left the button, # and I still haven't gotten around to linking",
"(no-selection color). # CALLING A FUNCTION TO USE A BASE64-ENCODED GIF OF A",
"SET A COMMAND FOR THE BUTTON USING THE INDEX (\"i\") AS ARGUMENT button_check",
"2 FRAMES, A LEFT AND A RIGHT FRAME, WHERE TO HOST 3 TEXT",
"5 different projects, 1 # (\"Misc\", from \"Miscellaneous\"for taking impromptu notes on anything",
"range(6): # THE FIRST 3 SUBFRAMES GO TO THE LEFT if i <=",
"(MOVE TO BOTTOM?) frames[i].pack(side = tk.TOP, fill = \"both\", expand = True, padx",
"0, highlightthickness = 0, wrap = \"word\", width = 10, height = 5)",
"GO TO THE RIGHT else: frame = ttk.Frame(frameR, style=\"RoundedFrame\", padding=10) # APPEND EVERY",
"command = partial(functions.compile, texts , i), background = \"white\", borderwidth = 0, height",
"by side # SET FOCUS TO THE FIRST FRAME frames[0].focus_set() font_tuple = (\"Garamond\",",
"FRAME, WHERE TO HOST 3 TEXT WIDGETS EACH frameL = tk.Frame(root, bg=\"#BAD9D0\") #",
"BUTTON img = functions.image(3) # SETTING BUTTON IMAGES: SECONDARY BUTTONS img_cross = Image.open('cross1.png')",
"LIST TO ACCESS THEM LATER frames.append(frame) # CREATING THE TEXT WIDGETS (I.E. THE",
"i) elif i == 1: main_button = functions.create_buttons(frameL, functions.opensage, \"Sage\", i) elif i",
"TO SET A COMMAND FOR THE BUTTON USING THE INDEX (\"i\") AS ARGUMENT",
"frameR.pack(side=tk.LEFT, fill=\"both\", expand=True) # side=tk.LEFT places frames side by side # SET FOCUS",
"Purpose: # This is a note-taking app, useful for people working on several",
"SETTING BUTTON IMAGES: MAIN BUTTON img = functions.image(3) # SETTING BUTTON IMAGES: SECONDARY",
"functions.create_buttons(frameR, functions.openacode, \"ACoDe\", i) elif i == 5: main_button = functions.create_buttons(frameR, functions.openmisc, \"MISC\",",
"BASE64-ENCODED GIF OF A ROUNDED-CORNER SQUARE WITH A BLACK BORDER borderImageData = functions.border_string()",
"image = img_photo_crs, background = \"white\", borderwidth = 0, height = 30, width",
"frameR = tk.Frame(root, bg=\"#BAD9D0\") # DECLARING LISTS TO POPULATE WITH OBJECTS THAT WILL",
"projects at # the same time and who want to be able to",
"LEFT if i <= 2: frame = ttk.Frame(frameL, style=\"RoundedFrame\", padding=10) # THE LAST",
"root.title(\"Elena's Notes\") #root.geometry('200x150') # this adjusts the size of the GUI to 200X150",
"this code, then I removed the function but left the button, # and",
"THE BUTTONS FOLLOWING THE GIVEN ORDER CHECKING THE LOOP INDEX if i ==",
"{\"sticky\": \"nsew\"})]) style.configure('TFrame', background= 'black') # CREATING 2 FRAMES, A LEFT AND A",
"expand = True, padx = 30) # ADDING THE BUTTONS INSIDE THE INPUT",
"the same data, in which case only the time of writing is #",
"black (no-selection color). # CALLING A FUNCTION TO USE A BASE64-ENCODED GIF OF",
"functions.create_buttons(frameL, functions.openJALL, \"JALL\", i) #Journal African Languages & Linguistics elif i == 3:",
"i) #Journal African Languages & Linguistics elif i == 3: main_button = functions.create_buttons(frameR,",
"name of the corresponding # project. If clicked, that button opens the .txt",
"tk.Frame(root, bg=\"#BAD9D0\") # cD4F1B2 is a light green color frameR = tk.Frame(root, bg=\"#BAD9D0\")",
"# Topicalization Study elif i == 4: main_button = functions.create_buttons(frameR, functions.openacode, \"ACoDe\", i)",
"using two base64-encoded gifs of a rounded-corner square, one is green (accent color),",
"frames side by side # SET FOCUS TO THE FIRST FRAME frames[0].focus_set() font_tuple",
"\"word\", width = 10, height = 5) text.pack(fill = \"both\", expand = True)",
"borderImage = tk.PhotoImage(\"borderImage\", data=borderImageData) focusBorderImage = tk.PhotoImage(\"focusBorderImage\", data=focusBorderImageData) style.element_create(\"RoundedFrame\", \"image\", borderImage, (\"focus\", focusBorderImage),",
".txt document associated with that # widget. # The red cross button clears",
"functions from functools import partial import pdb; #pdb.set_trace() ctypes.windll.shcore.SetProcessDpiAwareness(1) # this improves resolution",
"image = img_photo_chk, command = partial(functions.compile, texts , i), background = \"white\", borderwidth",
"elif i == 2: main_button = functions.create_buttons(frameL, functions.openJALL, \"JALL\", i) #Journal African Languages",
"== 5: main_button = functions.create_buttons(frameR, functions.openmisc, \"MISC\", i) main_button.config(image = img) main_button.pack(pady =",
"5 projects. # You write your notes on the desired text widget. Once",
"BASE64-ENCODED GIF OF A ROUNDED-CORNER SQUARE WITH A GREEN BORDER focusBorderImageData = functions.focusborder_string()",
"date and time of writing, unless there is already an entry # on",
"OBJECTS THAT WILL BE ACCESSED LATER USING THE INDEX (\"i\") frames = []",
"note-taking app, useful for people working on several projects at # the same",
"widget (note: I had that link to a function in # a previous",
"side by side frameR.pack(side=tk.LEFT, fill=\"both\", expand=True) # side=tk.LEFT places frames side by side",
"BUTTONS INSIDE THE INPUT FIELDS # PARTIAL (IN \"command\") ALLOW US TO SET",
"main_button.config(image = img) main_button.pack(pady = 5) # SHOWING THE FRAMES (MOVE TO BOTTOM?)",
"INDEX (\"i\") AS ARGUMENT button_check = tk.Button(frames[i], image = img_photo_chk, command = partial(functions.compile,",
"padding=10) # APPEND EVERY SINGLE FRAME TO THE LIST TO ACCESS THEM LATER",
"img_cross = Image.open('cross1.png') img_cross = img_cross.resize((30,30), Image.ANTIALIAS) img_photo_crs = ImageTk.PhotoImage(img_cross) img_check = Image.open('check1.png')",
"the same time and who want to be able to update multiple documents",
"widgets to change color if the cursor is over those widgets, # so",
"BUTTONS FOLLOWING THE GIVEN ORDER CHECKING THE LOOP INDEX if i == 0:",
"only the time of writing is # indicated. Above every widget there's a",
"functions.border_string() style = ttk.Style() borderImage = tk.PhotoImage(\"borderImage\", data=borderImageData) focusBorderImage = tk.PhotoImage(\"focusBorderImage\", data=focusBorderImageData) style.element_create(\"RoundedFrame\",",
"I removed the function but left the button, # and I still haven't",
"tk.RIGHT) root.configure(background=\"#BAD9D0\") #BAD9D0 #cfffff #D4F1B2 frameL.pack(side=tk.LEFT, fill=\"both\", expand=True) # side=tk.LEFT places frames side",
"time and from the same window. # # Structure: # There are six",
"in # a previous version of this code, then I removed the function",
"light green color frameR = tk.Frame(root, bg=\"#BAD9D0\") # DECLARING LISTS TO POPULATE WITH",
"INDEX if i == 0: main_button = functions.create_buttons(frameL, functions.openprobus, \"Probus\", i) elif i",
"THEM LATER frames.append(frame) # CREATING THE TEXT WIDGETS (I.E. THE INPUT FIELDS) text",
"ADDING THE BUTTONS INSIDE THE INPUT FIELDS # PARTIAL (IN \"command\") ALLOW US",
"places frames side by side frameR.pack(side=tk.LEFT, fill=\"both\", expand=True) # side=tk.LEFT places frames side",
"RIGHT FRAME, WHERE TO HOST 3 TEXT WIDGETS EACH frameL = tk.Frame(root, bg=\"#BAD9D0\")",
"\"both\", expand = True, padx = 30) # ADDING THE BUTTONS INSIDE THE",
"i == 5: main_button = functions.create_buttons(frameR, functions.openmisc, \"MISC\", i) main_button.config(image = img) main_button.pack(pady",
"main_button = functions.create_buttons(frameR, functions.openmisc, \"MISC\", i) main_button.config(image = img) main_button.pack(pady = 5) #",
"that is # not related to those 5 projects. # You write your",
"previous version of this code, then I removed the function but left the",
"with the same data, in which case only the time of writing is",
"If clicked, that button opens the .txt document associated with that # widget.",
"is green (accent color), # the other one is black (no-selection color). #",
"= tk.RIGHT) root.configure(background=\"#BAD9D0\") #BAD9D0 #cfffff #D4F1B2 frameL.pack(side=tk.LEFT, fill=\"both\", expand=True) # side=tk.LEFT places frames",
"tk.Button(frames[i], image = img_photo_chk, command = partial(functions.compile, texts , i), background = \"white\",",
"= ImageTk.PhotoImage(img_cross) img_check = Image.open('check1.png') img_check = img_check.resize((30,30), Image.ANTIALIAS) img_photo_chk = ImageTk.PhotoImage(img_check) for",
"main_button = functions.create_buttons(frameL, functions.openJALL, \"JALL\", i) #Journal African Languages & Linguistics elif i",
"on the desired text widget. Once you're done, you click on # the",
"and I still haven't gotten around to linking it again) # #################################################################################### import",
"the cursor is over those widgets, # so I am using two base64-encoded",
"ARGUMENT button_check = tk.Button(frames[i], image = img_photo_chk, command = partial(functions.compile, texts , i),",
"functions.openmisc, \"MISC\", i) main_button.config(image = img) main_button.pack(pady = 5) # SHOWING THE FRAMES",
"COMMAND FOR THE BUTTON USING THE INDEX (\"i\") AS ARGUMENT button_check = tk.Button(frames[i],",
"# cD4F1B2 is a light green color frameR = tk.Frame(root, bg=\"#BAD9D0\") # DECLARING",
"tk.LEFT) button_cross = tk.Button(frames[i], image = img_photo_crs, background = \"white\", borderwidth = 0,",
"with that # widget. # The red cross button clears the text widget",
"# Purpose: # This is a note-taking app, useful for people working on",
"FIELDS # PARTIAL (IN \"command\") ALLOW US TO SET A COMMAND FOR THE",
"projects, 1 # (\"Misc\", from \"Miscellaneous\"for taking impromptu notes on anything else that",
"This is a note-taking app, useful for people working on several projects at",
"i) # Topicalization Study elif i == 4: main_button = functions.create_buttons(frameR, functions.openacode, \"ACoDe\",",
"indicated. Above every widget there's a button with the name of the corresponding",
"removed the function but left the button, # and I still haven't gotten",
"IMAGES: SECONDARY BUTTONS img_cross = Image.open('cross1.png') img_cross = img_cross.resize((30,30), Image.ANTIALIAS) img_photo_crs = ImageTk.PhotoImage(img_cross)",
"BORDER borderImageData = functions.border_string() style = ttk.Style() borderImage = tk.PhotoImage(\"borderImage\", data=borderImageData) focusBorderImage =",
"TO THE RIGHT else: frame = ttk.Frame(frameR, style=\"RoundedFrame\", padding=10) # APPEND EVERY SINGLE",
"from the same window. # # Structure: # There are six text widgets",
"text = tk.Text(frames[i], borderwidth = 0, highlightthickness = 0, wrap = \"word\", width",
"= True, padx = 30) # ADDING THE BUTTONS INSIDE THE INPUT FIELDS",
"On the txt file, entries # appear together with the date and time",
"text widgets to change color if the cursor is over those widgets, #",
"functions.openacode, \"ACoDe\", i) elif i == 5: main_button = functions.create_buttons(frameR, functions.openmisc, \"MISC\", i)",
"project. If clicked, that button opens the .txt document associated with that #",
"= functions.create_buttons(frameL, functions.openJALL, \"JALL\", i) #Journal African Languages & Linguistics elif i ==",
"code, then I removed the function but left the button, # and I",
"opens the .txt document associated with that # widget. # The red cross",
"documents at the same # time and from the same window. # #",
"FOR THE BUTTON USING THE INDEX (\"i\") AS ARGUMENT button_check = tk.Button(frames[i], image",
"to 200X150 # I want the border of the text widgets to change",
"USE A BASE64-ENCODED GIF OF A ROUNDED-CORNER SQUARE WITH A BLACK BORDER borderImageData",
"= \"white\", borderwidth = 0, height = 30, width = 30) button_check.image =",
"= tk.PhotoImage(\"borderImage\", data=borderImageData) focusBorderImage = tk.PhotoImage(\"focusBorderImage\", data=focusBorderImageData) style.element_create(\"RoundedFrame\", \"image\", borderImage, (\"focus\", focusBorderImage), border=20,",
"clears the text widget (note: I had that link to a function in",
"file, entries # appear together with the date and time of writing, unless",
"FOLLOWING THE GIVEN ORDER CHECKING THE LOOP INDEX if i == 0: main_button",
"= [] # SETTING BUTTON IMAGES: MAIN BUTTON img = functions.image(3) # SETTING",
"of the GUI to 200X150 # I want the border of the text",
"the text widget for you. On the txt file, entries # appear together",
"with the date and time of writing, unless there is already an entry",
"expand=True) # side=tk.LEFT places frames side by side # SET FOCUS TO THE",
"= img_photo_chk, command = partial(functions.compile, texts , i), background = \"white\", borderwidth =",
"3 SUBFRAMES GO TO THE LEFT if i <= 2: frame = ttk.Frame(frameL,",
"main_button = functions.create_buttons(frameR, functions.openheaviness, \"Heavi\", i) # Topicalization Study elif i == 4:",
"ACCESSED LATER USING THE INDEX (\"i\") frames = [] texts = [] #",
"Languages & Linguistics elif i == 3: main_button = functions.create_buttons(frameR, functions.openheaviness, \"Heavi\", i)",
"\"both\", expand = True) text.bind(\"<FocusIn>\", lambda event: frames[i].state([\"focus\"])) text.bind(\"<FocusOut>\", lambda event: frames[i].state([\"!focus\"])) text.insert(\"end\",",
"= img_photo_crs button_cross.pack(side = tk.RIGHT) root.configure(background=\"#BAD9D0\") #BAD9D0 #cfffff #D4F1B2 frameL.pack(side=tk.LEFT, fill=\"both\", expand=True) #",
"import ctypes import functions from functools import partial import pdb; #pdb.set_trace() ctypes.windll.shcore.SetProcessDpiAwareness(1) #",
"file, and automatically clears the text widget for you. On the txt file,",
"style=\"RoundedFrame\", padding=10) # APPEND EVERY SINGLE FRAME TO THE LIST TO ACCESS THEM",
"borderwidth = 0, highlightthickness = 0, wrap = \"word\", width = 10, height",
"ttk.Frame(frameR, style=\"RoundedFrame\", padding=10) # APPEND EVERY SINGLE FRAME TO THE LIST TO ACCESS",
"= 30, width = 30) button_check.image = img_photo_chk button_check.pack(side = tk.LEFT) button_cross =",
"SECONDARY BUTTONS img_cross = Image.open('cross1.png') img_cross = img_cross.resize((30,30), Image.ANTIALIAS) img_photo_crs = ImageTk.PhotoImage(img_cross) img_check",
"functions.create_buttons(frameL, functions.opensage, \"Sage\", i) elif i == 2: main_button = functions.create_buttons(frameL, functions.openJALL, \"JALL\",",
"every widget there's a button with the name of the corresponding # project.",
"had that link to a function in # a previous version of this",
"= tk.Button(frames[i], image = img_photo_chk, command = partial(functions.compile, texts , i), background =",
"Above every widget there's a button with the name of the corresponding #",
"= 30, width = 30) button_cross.image = img_photo_crs button_cross.pack(side = tk.RIGHT) root.configure(background=\"#BAD9D0\") #BAD9D0",
"you. On the txt file, entries # appear together with the date and",
"widget. # The red cross button clears the text widget (note: I had",
"the button, # and I still haven't gotten around to linking it again)",
"A BASE64-ENCODED GIF OF A ROUNDED-CORNER SQUARE WITH A BLACK BORDER borderImageData =",
"GO TO THE LEFT if i <= 2: frame = ttk.Frame(frameL, style=\"RoundedFrame\", padding=10)",
"INPUT FIELDS # PARTIAL (IN \"command\") ALLOW US TO SET A COMMAND FOR",
"the size of the GUI to 200X150 # I want the border of",
"tick button, which saves what you've written in a corresponding .txt # file,",
"taking impromptu notes on anything else that is # not related to those",
"width = 30) button_check.image = img_photo_chk button_check.pack(side = tk.LEFT) button_cross = tk.Button(frames[i], image",
"OF A ROUNDED-CORNER SQUARE WITH A BLACK BORDER borderImageData = functions.border_string() style =",
"30) button_check.image = img_photo_chk button_check.pack(side = tk.LEFT) button_cross = tk.Button(frames[i], image = img_photo_crs,",
"0, wrap = \"word\", width = 10, height = 5) text.pack(fill = \"both\",",
"i == 4: main_button = functions.create_buttons(frameR, functions.openacode, \"ACoDe\", i) elif i == 5:",
"improves resolution of GUI root = tk.Tk() root.title(\"Elena's Notes\") #root.geometry('200x150') # this adjusts",
"ImageTk.PhotoImage(img_cross) img_check = Image.open('check1.png') img_check = img_check.resize((30,30), Image.ANTIALIAS) img_photo_chk = ImageTk.PhotoImage(img_check) for i",
"and who want to be able to update multiple documents at the same",
"of the text widgets to change color if the cursor is over those",
"focusBorderImageData = functions.focusborder_string() # CALLING A FUNCTION TO USE A BASE64-ENCODED GIF OF",
"frames[i].state([\"!focus\"])) text.insert(\"end\", \"\") texts.append(text) # CREATING THE BUTTONS FOLLOWING THE GIVEN ORDER CHECKING",
"that txt file with the same data, in which case only the time",
"else: frame = ttk.Frame(frameR, style=\"RoundedFrame\", padding=10) # APPEND EVERY SINGLE FRAME TO THE",
"functions.openJALL, \"JALL\", i) #Journal African Languages & Linguistics elif i == 3: main_button",
"FRAMES (MOVE TO BOTTOM?) frames[i].pack(side = tk.TOP, fill = \"both\", expand = True,",
"# ADDING THE BUTTONS INSIDE THE INPUT FIELDS # PARTIAL (IN \"command\") ALLOW",
"which saves what you've written in a corresponding .txt # file, and automatically",
"text widget. Once you're done, you click on # the green tick button,",
"text.insert(\"end\", \"\") texts.append(text) # CREATING THE BUTTONS FOLLOWING THE GIVEN ORDER CHECKING THE",
"2022 # # Purpose: # This is a note-taking app, useful for people",
"button_check = tk.Button(frames[i], image = img_photo_chk, command = partial(functions.compile, texts , i), background",
"img_photo_chk, command = partial(functions.compile, texts , i), background = \"white\", borderwidth = 0,",
"WIDGETS (I.E. THE INPUT FIELDS) text = tk.Text(frames[i], borderwidth = 0, highlightthickness =",
"frame = ttk.Frame(frameR, style=\"RoundedFrame\", padding=10) # APPEND EVERY SINGLE FRAME TO THE LIST",
"by side frameR.pack(side=tk.LEFT, fill=\"both\", expand=True) # side=tk.LEFT places frames side by side #",
"= \"both\", expand = True, padx = 30) # ADDING THE BUTTONS INSIDE",
"borderImage, (\"focus\", focusBorderImage), border=20, sticky=\"nsew\") style.layout(\"RoundedFrame\", [(\"RoundedFrame\", {\"sticky\": \"nsew\"})]) style.configure('TFrame', background= 'black') #",
"# this adjusts the size of the GUI to 200X150 # I want",
"you're done, you click on # the green tick button, which saves what",
"BUTTONS img_cross = Image.open('cross1.png') img_cross = img_cross.resize((30,30), Image.ANTIALIAS) img_photo_crs = ImageTk.PhotoImage(img_cross) img_check =",
"img_photo_chk = ImageTk.PhotoImage(img_check) for i in range(6): # THE FIRST 3 SUBFRAMES GO",
"WITH A BLACK BORDER borderImageData = functions.border_string() style = ttk.Style() borderImage = tk.PhotoImage(\"borderImage\",",
"color frameR = tk.Frame(root, bg=\"#BAD9D0\") # DECLARING LISTS TO POPULATE WITH OBJECTS THAT",
"width = 10, height = 5) text.pack(fill = \"both\", expand = True) text.bind(\"<FocusIn>\",",
"TO USE A BASE64-ENCODED GIF OF A ROUNDED-CORNER SQUARE WITH A GREEN BORDER",
"focusBorderImage = tk.PhotoImage(\"focusBorderImage\", data=focusBorderImageData) style.element_create(\"RoundedFrame\", \"image\", borderImage, (\"focus\", focusBorderImage), border=20, sticky=\"nsew\") style.layout(\"RoundedFrame\", [(\"RoundedFrame\",",
"who want to be able to update multiple documents at the same #",
"document associated with that # widget. # The red cross button clears the",
"color), # the other one is black (no-selection color). # CALLING A FUNCTION",
"writing, unless there is already an entry # on that txt file with",
"together with the date and time of writing, unless there is already an",
"is a light green color frameR = tk.Frame(root, bg=\"#BAD9D0\") # DECLARING LISTS TO",
"desired text widget. Once you're done, you click on # the green tick",
"30, width = 30) button_cross.image = img_photo_crs button_cross.pack(side = tk.RIGHT) root.configure(background=\"#BAD9D0\") #BAD9D0 #cfffff",
"CALLING A FUNCTION TO USE A BASE64-ENCODED GIF OF A ROUNDED-CORNER SQUARE WITH",
"background = \"white\", borderwidth = 0, height = 30, width = 30) button_cross.image",
"sticky=\"nsew\") style.layout(\"RoundedFrame\", [(\"RoundedFrame\", {\"sticky\": \"nsew\"})]) style.configure('TFrame', background= 'black') # CREATING 2 FRAMES, A",
"[] texts = [] # SETTING BUTTON IMAGES: MAIN BUTTON img = functions.image(3)",
"ctypes import functions from functools import partial import pdb; #pdb.set_trace() ctypes.windll.shcore.SetProcessDpiAwareness(1) # this",
"the text widgets to change color if the cursor is over those widgets,",
"entries # appear together with the date and time of writing, unless there",
"tk.Button(frames[i], image = img_photo_crs, background = \"white\", borderwidth = 0, height = 30,",
".txt # file, and automatically clears the text widget for you. On the",
"the green tick button, which saves what you've written in a corresponding .txt",
"background= 'black') # CREATING 2 FRAMES, A LEFT AND A RIGHT FRAME, WHERE",
"an entry # on that txt file with the same data, in which",
"# not related to those 5 projects. # You write your notes on",
"5 corresponding to 5 different projects, 1 # (\"Misc\", from \"Miscellaneous\"for taking impromptu",
"button opens the .txt document associated with that # widget. # The red",
"main_button.pack(pady = 5) # SHOWING THE FRAMES (MOVE TO BOTTOM?) frames[i].pack(side = tk.TOP,",
"<filename>empty7v2.0.py #################################################################################### # Version: January 2022 # # Purpose: # This is a",
"is # not related to those 5 projects. # You write your notes",
"THE BUTTONS INSIDE THE INPUT FIELDS # PARTIAL (IN \"command\") ALLOW US TO",
"THE INPUT FIELDS # PARTIAL (IN \"command\") ALLOW US TO SET A COMMAND",
"CREATING THE BUTTONS FOLLOWING THE GIVEN ORDER CHECKING THE LOOP INDEX if i",
"Image.ANTIALIAS) img_photo_crs = ImageTk.PhotoImage(img_cross) img_check = Image.open('check1.png') img_check = img_check.resize((30,30), Image.ANTIALIAS) img_photo_chk =",
"img_check.resize((30,30), Image.ANTIALIAS) img_photo_chk = ImageTk.PhotoImage(img_check) for i in range(6): # THE FIRST 3",
"i) elif i == 5: main_button = functions.create_buttons(frameR, functions.openmisc, \"MISC\", i) main_button.config(image =",
"# PARTIAL (IN \"command\") ALLOW US TO SET A COMMAND FOR THE BUTTON",
"= tk.Button(frames[i], image = img_photo_crs, background = \"white\", borderwidth = 0, height =",
"THE LIST TO ACCESS THEM LATER frames.append(frame) # CREATING THE TEXT WIDGETS (I.E.",
"your notes on the desired text widget. Once you're done, you click on",
"functions.opensage, \"Sage\", i) elif i == 2: main_button = functions.create_buttons(frameL, functions.openJALL, \"JALL\", i)",
"projects. # You write your notes on the desired text widget. Once you're",
"ORDER CHECKING THE LOOP INDEX if i == 0: main_button = functions.create_buttons(frameL, functions.openprobus,",
"so I am using two base64-encoded gifs of a rounded-corner square, one is",
"to a function in # a previous version of this code, then I",
"FIELDS) text = tk.Text(frames[i], borderwidth = 0, highlightthickness = 0, wrap = \"word\",",
"left the button, # and I still haven't gotten around to linking it",
"# so I am using two base64-encoded gifs of a rounded-corner square, one",
"functions.create_buttons(frameR, functions.openmisc, \"MISC\", i) main_button.config(image = img) main_button.pack(pady = 5) # SHOWING THE",
"if i == 0: main_button = functions.create_buttons(frameL, functions.openprobus, \"Probus\", i) elif i ==",
"function but left the button, # and I still haven't gotten around to",
"not related to those 5 projects. # You write your notes on the",
"tk from tkinter import ttk from PIL import ImageTk, Image from tkinter import",
"time of writing, unless there is already an entry # on that txt",
"borderImageData = functions.border_string() style = ttk.Style() borderImage = tk.PhotoImage(\"borderImage\", data=borderImageData) focusBorderImage = tk.PhotoImage(\"focusBorderImage\",",
"for i in range(6): # THE FIRST 3 SUBFRAMES GO TO THE LEFT",
"ImageTk.PhotoImage(img_check) for i in range(6): # THE FIRST 3 SUBFRAMES GO TO THE",
"img) main_button.pack(pady = 5) # SHOWING THE FRAMES (MOVE TO BOTTOM?) frames[i].pack(side =",
"which case only the time of writing is # indicated. Above every widget",
"clicked, that button opens the .txt document associated with that # widget. #",
"5: main_button = functions.create_buttons(frameR, functions.openmisc, \"MISC\", i) main_button.config(image = img) main_button.pack(pady = 5)",
"A ROUNDED-CORNER SQUARE WITH A BLACK BORDER borderImageData = functions.border_string() style = ttk.Style()",
"import os import ctypes import functions from functools import partial import pdb; #pdb.set_trace()",
"# widget. # The red cross button clears the text widget (note: I",
"[(\"RoundedFrame\", {\"sticky\": \"nsew\"})]) style.configure('TFrame', background= 'black') # CREATING 2 FRAMES, A LEFT AND",
"#D4F1B2 frameL.pack(side=tk.LEFT, fill=\"both\", expand=True) # side=tk.LEFT places frames side by side frameR.pack(side=tk.LEFT, fill=\"both\",",
"CHECKING THE LOOP INDEX if i == 0: main_button = functions.create_buttons(frameL, functions.openprobus, \"Probus\",",
"BUTTON IMAGES: MAIN BUTTON img = functions.image(3) # SETTING BUTTON IMAGES: SECONDARY BUTTONS",
"highlightthickness = 0, wrap = \"word\", width = 10, height = 5) text.pack(fill",
"around to linking it again) # #################################################################################### import tkinter as tk from tkinter",
"LATER USING THE INDEX (\"i\") frames = [] texts = [] # SETTING",
"A BASE64-ENCODED GIF OF A ROUNDED-CORNER SQUARE WITH A GREEN BORDER focusBorderImageData =",
"= tk.Frame(root, bg=\"#BAD9D0\") # cD4F1B2 is a light green color frameR = tk.Frame(root,",
"= functions.image(3) # SETTING BUTTON IMAGES: SECONDARY BUTTONS img_cross = Image.open('cross1.png') img_cross =",
"5) # SHOWING THE FRAMES (MOVE TO BOTTOM?) frames[i].pack(side = tk.TOP, fill =",
"txt file, entries # appear together with the date and time of writing,",
"Linguistics elif i == 3: main_button = functions.create_buttons(frameR, functions.openheaviness, \"Heavi\", i) # Topicalization",
"padding=10) # THE LAST 3 SUBFRAMES GO TO THE RIGHT else: frame =",
"ttk.Frame(frameL, style=\"RoundedFrame\", padding=10) # THE LAST 3 SUBFRAMES GO TO THE RIGHT else:",
"GUI root = tk.Tk() root.title(\"Elena's Notes\") #root.geometry('200x150') # this adjusts the size of",
"BUTTON USING THE INDEX (\"i\") AS ARGUMENT button_check = tk.Button(frames[i], image = img_photo_chk,",
"and time of writing, unless there is already an entry # on that",
"text.bind(\"<FocusOut>\", lambda event: frames[i].state([\"!focus\"])) text.insert(\"end\", \"\") texts.append(text) # CREATING THE BUTTONS FOLLOWING THE",
"a function in # a previous version of this code, then I removed",
"style=\"RoundedFrame\", padding=10) # THE LAST 3 SUBFRAMES GO TO THE RIGHT else: frame",
"width = 30) button_cross.image = img_photo_crs button_cross.pack(side = tk.RIGHT) root.configure(background=\"#BAD9D0\") #BAD9D0 #cfffff #D4F1B2",
"TEXT WIDGETS (I.E. THE INPUT FIELDS) text = tk.Text(frames[i], borderwidth = 0, highlightthickness",
"focusBorderImage), border=20, sticky=\"nsew\") style.layout(\"RoundedFrame\", [(\"RoundedFrame\", {\"sticky\": \"nsew\"})]) style.configure('TFrame', background= 'black') # CREATING 2",
"# appear together with the date and time of writing, unless there is",
"# time and from the same window. # # Structure: # There are",
"that # widget. # The red cross button clears the text widget (note:",
"LAST 3 SUBFRAMES GO TO THE RIGHT else: frame = ttk.Frame(frameR, style=\"RoundedFrame\", padding=10)",
"# project. If clicked, that button opens the .txt document associated with that",
"saves what you've written in a corresponding .txt # file, and automatically clears",
"is # indicated. Above every widget there's a button with the name of",
"tkinter as tk from tkinter import ttk from PIL import ImageTk, Image from",
"img = functions.image(3) # SETTING BUTTON IMAGES: SECONDARY BUTTONS img_cross = Image.open('cross1.png') img_cross",
"= \"both\", expand = True) text.bind(\"<FocusIn>\", lambda event: frames[i].state([\"focus\"])) text.bind(\"<FocusOut>\", lambda event: frames[i].state([\"!focus\"]))",
"# CREATING THE BUTTONS FOLLOWING THE GIVEN ORDER CHECKING THE LOOP INDEX if",
"widget. Once you're done, you click on # the green tick button, which",
"WITH OBJECTS THAT WILL BE ACCESSED LATER USING THE INDEX (\"i\") frames =",
"The red cross button clears the text widget (note: I had that link",
"OF A ROUNDED-CORNER SQUARE WITH A GREEN BORDER focusBorderImageData = functions.focusborder_string() # CALLING",
"entry # on that txt file with the same data, in which case",
"# file, and automatically clears the text widget for you. On the txt",
"TEXT WIDGETS EACH frameL = tk.Frame(root, bg=\"#BAD9D0\") # cD4F1B2 is a light green",
"INSIDE THE INPUT FIELDS # PARTIAL (IN \"command\") ALLOW US TO SET A",
"= 0, height = 30, width = 30) button_check.image = img_photo_chk button_check.pack(side =",
"THE LOOP INDEX if i == 0: main_button = functions.create_buttons(frameL, functions.openprobus, \"Probus\", i)",
"(\"Misc\", from \"Miscellaneous\"for taking impromptu notes on anything else that is # not",
"style.layout(\"RoundedFrame\", [(\"RoundedFrame\", {\"sticky\": \"nsew\"})]) style.configure('TFrame', background= 'black') # CREATING 2 FRAMES, A LEFT",
"# This is a note-taking app, useful for people working on several projects",
"of GUI root = tk.Tk() root.title(\"Elena's Notes\") #root.geometry('200x150') # this adjusts the size",
"(\"i\") frames = [] texts = [] # SETTING BUTTON IMAGES: MAIN BUTTON",
"10, height = 5) text.pack(fill = \"both\", expand = True) text.bind(\"<FocusIn>\", lambda event:",
"functions.openheaviness, \"Heavi\", i) # Topicalization Study elif i == 4: main_button = functions.create_buttons(frameR,",
"ROUNDED-CORNER SQUARE WITH A GREEN BORDER focusBorderImageData = functions.focusborder_string() # CALLING A FUNCTION",
"== 3: main_button = functions.create_buttons(frameR, functions.openheaviness, \"Heavi\", i) # Topicalization Study elif i",
"in range(6): # THE FIRST 3 SUBFRAMES GO TO THE LEFT if i",
"= 30) # ADDING THE BUTTONS INSIDE THE INPUT FIELDS # PARTIAL (IN",
"\"Miscellaneous\"for taking impromptu notes on anything else that is # not related to",
"img_check = Image.open('check1.png') img_check = img_check.resize((30,30), Image.ANTIALIAS) img_photo_chk = ImageTk.PhotoImage(img_check) for i in",
"img_photo_crs, background = \"white\", borderwidth = 0, height = 30, width = 30)",
"# (\"Misc\", from \"Miscellaneous\"for taking impromptu notes on anything else that is #",
"window. # # Structure: # There are six text widgets in total: 5",
"two base64-encoded gifs of a rounded-corner square, one is green (accent color), #",
"= tk.Tk() root.title(\"Elena's Notes\") #root.geometry('200x150') # this adjusts the size of the GUI",
"i in range(6): # THE FIRST 3 SUBFRAMES GO TO THE LEFT if",
"INDEX (\"i\") frames = [] texts = [] # SETTING BUTTON IMAGES: MAIN",
"# CREATING THE TEXT WIDGETS (I.E. THE INPUT FIELDS) text = tk.Text(frames[i], borderwidth",
"200X150 # I want the border of the text widgets to change color",
"and from the same window. # # Structure: # There are six text",
"color if the cursor is over those widgets, # so I am using",
"Study elif i == 4: main_button = functions.create_buttons(frameR, functions.openacode, \"ACoDe\", i) elif i",
"<= 2: frame = ttk.Frame(frameL, style=\"RoundedFrame\", padding=10) # THE LAST 3 SUBFRAMES GO",
"= 30) button_check.image = img_photo_chk button_check.pack(side = tk.LEFT) button_cross = tk.Button(frames[i], image =",
"ALLOW US TO SET A COMMAND FOR THE BUTTON USING THE INDEX (\"i\")",
"places frames side by side # SET FOCUS TO THE FIRST FRAME frames[0].focus_set()",
"the GUI to 200X150 # I want the border of the text widgets",
"\"command\") ALLOW US TO SET A COMMAND FOR THE BUTTON USING THE INDEX",
"(\"i\") AS ARGUMENT button_check = tk.Button(frames[i], image = img_photo_chk, command = partial(functions.compile, texts",
"height = 5) text.pack(fill = \"both\", expand = True) text.bind(\"<FocusIn>\", lambda event: frames[i].state([\"focus\"]))",
"5) text.pack(fill = \"both\", expand = True) text.bind(\"<FocusIn>\", lambda event: frames[i].state([\"focus\"])) text.bind(\"<FocusOut>\", lambda",
"txt file with the same data, in which case only the time of",
"texts.append(text) # CREATING THE BUTTONS FOLLOWING THE GIVEN ORDER CHECKING THE LOOP INDEX",
"FRAMES, A LEFT AND A RIGHT FRAME, WHERE TO HOST 3 TEXT WIDGETS",
"else that is # not related to those 5 projects. # You write",
"I still haven't gotten around to linking it again) # #################################################################################### import tkinter",
"POPULATE WITH OBJECTS THAT WILL BE ACCESSED LATER USING THE INDEX (\"i\") frames",
"then I removed the function but left the button, # and I still",
"i == 3: main_button = functions.create_buttons(frameR, functions.openheaviness, \"Heavi\", i) # Topicalization Study elif",
"functions.create_buttons(frameR, functions.openheaviness, \"Heavi\", i) # Topicalization Study elif i == 4: main_button =",
"click on # the green tick button, which saves what you've written in",
"of the corresponding # project. If clicked, that button opens the .txt document",
"SUBFRAMES GO TO THE LEFT if i <= 2: frame = ttk.Frame(frameL, style=\"RoundedFrame\",",
"linking it again) # #################################################################################### import tkinter as tk from tkinter import ttk",
"\"MISC\", i) main_button.config(image = img) main_button.pack(pady = 5) # SHOWING THE FRAMES (MOVE",
"gotten around to linking it again) # #################################################################################### import tkinter as tk from",
"you click on # the green tick button, which saves what you've written",
"this adjusts the size of the GUI to 200X150 # I want the",
"function in # a previous version of this code, then I removed the",
"the same window. # # Structure: # There are six text widgets in",
"at # the same time and who want to be able to update",
"border of the text widgets to change color if the cursor is over",
"that link to a function in # a previous version of this code,",
"of writing, unless there is already an entry # on that txt file",
"green color frameR = tk.Frame(root, bg=\"#BAD9D0\") # DECLARING LISTS TO POPULATE WITH OBJECTS",
"written in a corresponding .txt # file, and automatically clears the text widget",
"functions.focusborder_string() # CALLING A FUNCTION TO USE A BASE64-ENCODED GIF OF A ROUNDED-CORNER",
"img_cross.resize((30,30), Image.ANTIALIAS) img_photo_crs = ImageTk.PhotoImage(img_cross) img_check = Image.open('check1.png') img_check = img_check.resize((30,30), Image.ANTIALIAS) img_photo_chk",
"functions.image(3) # SETTING BUTTON IMAGES: SECONDARY BUTTONS img_cross = Image.open('cross1.png') img_cross = img_cross.resize((30,30),",
"tk.PhotoImage(\"focusBorderImage\", data=focusBorderImageData) style.element_create(\"RoundedFrame\", \"image\", borderImage, (\"focus\", focusBorderImage), border=20, sticky=\"nsew\") style.layout(\"RoundedFrame\", [(\"RoundedFrame\", {\"sticky\": \"nsew\"})])",
"change color if the cursor is over those widgets, # so I am",
"base64-encoded gifs of a rounded-corner square, one is green (accent color), # the",
"the desired text widget. Once you're done, you click on # the green",
"to 5 different projects, 1 # (\"Misc\", from \"Miscellaneous\"for taking impromptu notes on",
"the txt file, entries # appear together with the date and time of",
"GIF OF A ROUNDED-CORNER SQUARE WITH A GREEN BORDER focusBorderImageData = functions.focusborder_string() #",
"frame = ttk.Frame(frameL, style=\"RoundedFrame\", padding=10) # THE LAST 3 SUBFRAMES GO TO THE",
"it again) # #################################################################################### import tkinter as tk from tkinter import ttk from",
"I am using two base64-encoded gifs of a rounded-corner square, one is green",
"tk.Frame(root, bg=\"#BAD9D0\") # DECLARING LISTS TO POPULATE WITH OBJECTS THAT WILL BE ACCESSED",
"SETTING BUTTON IMAGES: SECONDARY BUTTONS img_cross = Image.open('cross1.png') img_cross = img_cross.resize((30,30), Image.ANTIALIAS) img_photo_crs",
"root = tk.Tk() root.title(\"Elena's Notes\") #root.geometry('200x150') # this adjusts the size of the",
"same data, in which case only the time of writing is # indicated.",
"(\"focus\", focusBorderImage), border=20, sticky=\"nsew\") style.layout(\"RoundedFrame\", [(\"RoundedFrame\", {\"sticky\": \"nsew\"})]) style.configure('TFrame', background= 'black') # CREATING",
"height = 30, width = 30) button_check.image = img_photo_chk button_check.pack(side = tk.LEFT) button_cross",
"= 30) button_cross.image = img_photo_crs button_cross.pack(side = tk.RIGHT) root.configure(background=\"#BAD9D0\") #BAD9D0 #cfffff #D4F1B2 frameL.pack(side=tk.LEFT,",
"on several projects at # the same time and who want to be",
"event: frames[i].state([\"focus\"])) text.bind(\"<FocusOut>\", lambda event: frames[i].state([\"!focus\"])) text.insert(\"end\", \"\") texts.append(text) # CREATING THE BUTTONS",
"main_button = functions.create_buttons(frameR, functions.openacode, \"ACoDe\", i) elif i == 5: main_button = functions.create_buttons(frameR,",
"0: main_button = functions.create_buttons(frameL, functions.openprobus, \"Probus\", i) elif i == 1: main_button =",
"widgets, # so I am using two base64-encoded gifs of a rounded-corner square,",
"USE A BASE64-ENCODED GIF OF A ROUNDED-CORNER SQUARE WITH A GREEN BORDER focusBorderImageData",
"THE FIRST 3 SUBFRAMES GO TO THE LEFT if i <= 2: frame",
"\"white\", borderwidth = 0, height = 30, width = 30) button_cross.image = img_photo_crs",
"data=focusBorderImageData) style.element_create(\"RoundedFrame\", \"image\", borderImage, (\"focus\", focusBorderImage), border=20, sticky=\"nsew\") style.layout(\"RoundedFrame\", [(\"RoundedFrame\", {\"sticky\": \"nsew\"})]) style.configure('TFrame',",
"\"ACoDe\", i) elif i == 5: main_button = functions.create_buttons(frameR, functions.openmisc, \"MISC\", i) main_button.config(image",
"notes on the desired text widget. Once you're done, you click on #",
"THE LAST 3 SUBFRAMES GO TO THE RIGHT else: frame = ttk.Frame(frameR, style=\"RoundedFrame\",",
"[] # SETTING BUTTON IMAGES: MAIN BUTTON img = functions.image(3) # SETTING BUTTON",
"want the border of the text widgets to change color if the cursor",
"# # Purpose: # This is a note-taking app, useful for people working",
"2: frame = ttk.Frame(frameL, style=\"RoundedFrame\", padding=10) # THE LAST 3 SUBFRAMES GO TO",
"EVERY SINGLE FRAME TO THE LIST TO ACCESS THEM LATER frames.append(frame) # CREATING",
"text.bind(\"<FocusIn>\", lambda event: frames[i].state([\"focus\"])) text.bind(\"<FocusOut>\", lambda event: frames[i].state([\"!focus\"])) text.insert(\"end\", \"\") texts.append(text) # CREATING",
"\"Probus\", i) elif i == 1: main_button = functions.create_buttons(frameL, functions.opensage, \"Sage\", i) elif",
"appear together with the date and time of writing, unless there is already",
"import partial import pdb; #pdb.set_trace() ctypes.windll.shcore.SetProcessDpiAwareness(1) # this improves resolution of GUI root",
"functions.create_buttons(frameL, functions.openprobus, \"Probus\", i) elif i == 1: main_button = functions.create_buttons(frameL, functions.opensage, \"Sage\",",
"in which case only the time of writing is # indicated. Above every",
"of this code, then I removed the function but left the button, #",
"CREATING 2 FRAMES, A LEFT AND A RIGHT FRAME, WHERE TO HOST 3",
"those 5 projects. # You write your notes on the desired text widget.",
"import pdb; #pdb.set_trace() ctypes.windll.shcore.SetProcessDpiAwareness(1) # this improves resolution of GUI root = tk.Tk()",
"BLACK BORDER borderImageData = functions.border_string() style = ttk.Style() borderImage = tk.PhotoImage(\"borderImage\", data=borderImageData) focusBorderImage",
"A RIGHT FRAME, WHERE TO HOST 3 TEXT WIDGETS EACH frameL = tk.Frame(root,",
"IMAGES: MAIN BUTTON img = functions.image(3) # SETTING BUTTON IMAGES: SECONDARY BUTTONS img_cross",
"LATER frames.append(frame) # CREATING THE TEXT WIDGETS (I.E. THE INPUT FIELDS) text =",
"for people working on several projects at # the same time and who",
"from \"Miscellaneous\"for taking impromptu notes on anything else that is # not related",
"the time of writing is # indicated. Above every widget there's a button",
"style.configure('TFrame', background= 'black') # CREATING 2 FRAMES, A LEFT AND A RIGHT FRAME,",
"lambda event: frames[i].state([\"focus\"])) text.bind(\"<FocusOut>\", lambda event: frames[i].state([\"!focus\"])) text.insert(\"end\", \"\") texts.append(text) # CREATING THE",
"to be able to update multiple documents at the same # time and",
"at the same # time and from the same window. # # Structure:",
"data=borderImageData) focusBorderImage = tk.PhotoImage(\"focusBorderImage\", data=focusBorderImageData) style.element_create(\"RoundedFrame\", \"image\", borderImage, (\"focus\", focusBorderImage), border=20, sticky=\"nsew\") style.layout(\"RoundedFrame\",",
"AND A RIGHT FRAME, WHERE TO HOST 3 TEXT WIDGETS EACH frameL =",
"You write your notes on the desired text widget. Once you're done, you",
"# APPEND EVERY SINGLE FRAME TO THE LIST TO ACCESS THEM LATER frames.append(frame)",
"filedialog import os import ctypes import functions from functools import partial import pdb;",
"pdb; #pdb.set_trace() ctypes.windll.shcore.SetProcessDpiAwareness(1) # this improves resolution of GUI root = tk.Tk() root.title(\"Elena's",
"# #################################################################################### import tkinter as tk from tkinter import ttk from PIL import",
"3 SUBFRAMES GO TO THE RIGHT else: frame = ttk.Frame(frameR, style=\"RoundedFrame\", padding=10) #",
"main_button = functions.create_buttons(frameL, functions.openprobus, \"Probus\", i) elif i == 1: main_button = functions.create_buttons(frameL,",
"a corresponding .txt # file, and automatically clears the text widget for you.",
"borderwidth = 0, height = 30, width = 30) button_cross.image = img_photo_crs button_cross.pack(side",
"a previous version of this code, then I removed the function but left",
"write your notes on the desired text widget. Once you're done, you click",
"= [] texts = [] # SETTING BUTTON IMAGES: MAIN BUTTON img =",
"app, useful for people working on several projects at # the same time",
"from functools import partial import pdb; #pdb.set_trace() ctypes.windll.shcore.SetProcessDpiAwareness(1) # this improves resolution of",
"TO THE LIST TO ACCESS THEM LATER frames.append(frame) # CREATING THE TEXT WIDGETS",
"= ttk.Frame(frameR, style=\"RoundedFrame\", padding=10) # APPEND EVERY SINGLE FRAME TO THE LIST TO",
"= 10, height = 5) text.pack(fill = \"both\", expand = True) text.bind(\"<FocusIn>\", lambda",
"# indicated. Above every widget there's a button with the name of the",
"frameL.pack(side=tk.LEFT, fill=\"both\", expand=True) # side=tk.LEFT places frames side by side frameR.pack(side=tk.LEFT, fill=\"both\", expand=True)",
"0, height = 30, width = 30) button_check.image = img_photo_chk button_check.pack(side = tk.LEFT)",
"the .txt document associated with that # widget. # The red cross button",
"# this improves resolution of GUI root = tk.Tk() root.title(\"Elena's Notes\") #root.geometry('200x150') #",
"WITH A GREEN BORDER focusBorderImageData = functions.focusborder_string() # CALLING A FUNCTION TO USE",
"the text widget (note: I had that link to a function in #",
"3: main_button = functions.create_buttons(frameR, functions.openheaviness, \"Heavi\", i) # Topicalization Study elif i ==",
"cross button clears the text widget (note: I had that link to a",
"# on that txt file with the same data, in which case only",
"of a rounded-corner square, one is green (accent color), # the other one",
"as tk from tkinter import ttk from PIL import ImageTk, Image from tkinter",
"# the other one is black (no-selection color). # CALLING A FUNCTION TO",
"same # time and from the same window. # # Structure: # There",
"Structure: # There are six text widgets in total: 5 corresponding to 5",
"= tk.Text(frames[i], borderwidth = 0, highlightthickness = 0, wrap = \"word\", width =",
"January 2022 # # Purpose: # This is a note-taking app, useful for",
"side=tk.LEFT places frames side by side # SET FOCUS TO THE FIRST FRAME",
"RIGHT else: frame = ttk.Frame(frameR, style=\"RoundedFrame\", padding=10) # APPEND EVERY SINGLE FRAME TO",
"if the cursor is over those widgets, # so I am using two",
"BUTTON IMAGES: SECONDARY BUTTONS img_cross = Image.open('cross1.png') img_cross = img_cross.resize((30,30), Image.ANTIALIAS) img_photo_crs =",
"i == 0: main_button = functions.create_buttons(frameL, functions.openprobus, \"Probus\", i) elif i == 1:",
"# SET FOCUS TO THE FIRST FRAME frames[0].focus_set() font_tuple = (\"Garamond\", 14) root.mainloop()",
"again) # #################################################################################### import tkinter as tk from tkinter import ttk from PIL",
"a note-taking app, useful for people working on several projects at # the",
"green tick button, which saves what you've written in a corresponding .txt #",
"borderwidth = 0, height = 30, width = 30) button_check.image = img_photo_chk button_check.pack(side",
"\"nsew\"})]) style.configure('TFrame', background= 'black') # CREATING 2 FRAMES, A LEFT AND A RIGHT",
"same time and who want to be able to update multiple documents at",
"a button with the name of the corresponding # project. If clicked, that",
"# You write your notes on the desired text widget. Once you're done,",
"# DECLARING LISTS TO POPULATE WITH OBJECTS THAT WILL BE ACCESSED LATER USING",
"main_button = functions.create_buttons(frameL, functions.opensage, \"Sage\", i) elif i == 2: main_button = functions.create_buttons(frameL,",
"= img_cross.resize((30,30), Image.ANTIALIAS) img_photo_crs = ImageTk.PhotoImage(img_cross) img_check = Image.open('check1.png') img_check = img_check.resize((30,30), Image.ANTIALIAS)",
"notes on anything else that is # not related to those 5 projects.",
"30) button_cross.image = img_photo_crs button_cross.pack(side = tk.RIGHT) root.configure(background=\"#BAD9D0\") #BAD9D0 #cfffff #D4F1B2 frameL.pack(side=tk.LEFT, fill=\"both\",",
"GIVEN ORDER CHECKING THE LOOP INDEX if i == 0: main_button = functions.create_buttons(frameL,",
"expand=True) # side=tk.LEFT places frames side by side frameR.pack(side=tk.LEFT, fill=\"both\", expand=True) # side=tk.LEFT",
"already an entry # on that txt file with the same data, in",
"cD4F1B2 is a light green color frameR = tk.Frame(root, bg=\"#BAD9D0\") # DECLARING LISTS",
"THE INDEX (\"i\") frames = [] texts = [] # SETTING BUTTON IMAGES:",
"= \"white\", borderwidth = 0, height = 30, width = 30) button_cross.image =",
"to those 5 projects. # You write your notes on the desired text",
"in total: 5 corresponding to 5 different projects, 1 # (\"Misc\", from \"Miscellaneous\"for",
"from tkinter import ttk from PIL import ImageTk, Image from tkinter import filedialog",
"i == 1: main_button = functions.create_buttons(frameL, functions.opensage, \"Sage\", i) elif i == 2:",
"SQUARE WITH A GREEN BORDER focusBorderImageData = functions.focusborder_string() # CALLING A FUNCTION TO",
"functions.openprobus, \"Probus\", i) elif i == 1: main_button = functions.create_buttons(frameL, functions.opensage, \"Sage\", i)",
"\"\") texts.append(text) # CREATING THE BUTTONS FOLLOWING THE GIVEN ORDER CHECKING THE LOOP",
"different projects, 1 # (\"Misc\", from \"Miscellaneous\"for taking impromptu notes on anything else",
"expand = True) text.bind(\"<FocusIn>\", lambda event: frames[i].state([\"focus\"])) text.bind(\"<FocusOut>\", lambda event: frames[i].state([\"!focus\"])) text.insert(\"end\", \"\")",
"tk.TOP, fill = \"both\", expand = True, padx = 30) # ADDING THE",
"= functions.create_buttons(frameL, functions.openprobus, \"Probus\", i) elif i == 1: main_button = functions.create_buttons(frameL, functions.opensage,",
"A BLACK BORDER borderImageData = functions.border_string() style = ttk.Style() borderImage = tk.PhotoImage(\"borderImage\", data=borderImageData)",
"a rounded-corner square, one is green (accent color), # the other one is",
"# side=tk.LEFT places frames side by side frameR.pack(side=tk.LEFT, fill=\"both\", expand=True) # side=tk.LEFT places",
"= ttk.Frame(frameL, style=\"RoundedFrame\", padding=10) # THE LAST 3 SUBFRAMES GO TO THE RIGHT",
"frames[i].pack(side = tk.TOP, fill = \"both\", expand = True, padx = 30) #",
"to change color if the cursor is over those widgets, # so I",
"(note: I had that link to a function in # a previous version",
"# Version: January 2022 # # Purpose: # This is a note-taking app,",
"text widgets in total: 5 corresponding to 5 different projects, 1 # (\"Misc\",",
"= tk.Frame(root, bg=\"#BAD9D0\") # DECLARING LISTS TO POPULATE WITH OBJECTS THAT WILL BE",
"HOST 3 TEXT WIDGETS EACH frameL = tk.Frame(root, bg=\"#BAD9D0\") # cD4F1B2 is a",
"APPEND EVERY SINGLE FRAME TO THE LIST TO ACCESS THEM LATER frames.append(frame) #",
"that button opens the .txt document associated with that # widget. # The",
"(IN \"command\") ALLOW US TO SET A COMMAND FOR THE BUTTON USING THE",
"resolution of GUI root = tk.Tk() root.title(\"Elena's Notes\") #root.geometry('200x150') # this adjusts the",
"Image.ANTIALIAS) img_photo_chk = ImageTk.PhotoImage(img_check) for i in range(6): # THE FIRST 3 SUBFRAMES",
"to update multiple documents at the same # time and from the same",
"tkinter import ttk from PIL import ImageTk, Image from tkinter import filedialog import",
"Once you're done, you click on # the green tick button, which saves",
"link to a function in # a previous version of this code, then",
"FUNCTION TO USE A BASE64-ENCODED GIF OF A ROUNDED-CORNER SQUARE WITH A BLACK",
"img_photo_crs = ImageTk.PhotoImage(img_cross) img_check = Image.open('check1.png') img_check = img_check.resize((30,30), Image.ANTIALIAS) img_photo_chk = ImageTk.PhotoImage(img_check)",
"THE RIGHT else: frame = ttk.Frame(frameR, style=\"RoundedFrame\", padding=10) # APPEND EVERY SINGLE FRAME",
"the other one is black (no-selection color). # CALLING A FUNCTION TO USE",
"INPUT FIELDS) text = tk.Text(frames[i], borderwidth = 0, highlightthickness = 0, wrap =",
"corresponding to 5 different projects, 1 # (\"Misc\", from \"Miscellaneous\"for taking impromptu notes",
"True) text.bind(\"<FocusIn>\", lambda event: frames[i].state([\"focus\"])) text.bind(\"<FocusOut>\", lambda event: frames[i].state([\"!focus\"])) text.insert(\"end\", \"\") texts.append(text) #",
"== 2: main_button = functions.create_buttons(frameL, functions.openJALL, \"JALL\", i) #Journal African Languages & Linguistics",
"partial import pdb; #pdb.set_trace() ctypes.windll.shcore.SetProcessDpiAwareness(1) # this improves resolution of GUI root =",
"= ImageTk.PhotoImage(img_check) for i in range(6): # THE FIRST 3 SUBFRAMES GO TO",
"frames.append(frame) # CREATING THE TEXT WIDGETS (I.E. THE INPUT FIELDS) text = tk.Text(frames[i],",
"side by side # SET FOCUS TO THE FIRST FRAME frames[0].focus_set() font_tuple =",
"A GREEN BORDER focusBorderImageData = functions.focusborder_string() # CALLING A FUNCTION TO USE A",
"time of writing is # indicated. Above every widget there's a button with",
"= \"word\", width = 10, height = 5) text.pack(fill = \"both\", expand =",
"import tkinter as tk from tkinter import ttk from PIL import ImageTk, Image",
"#pdb.set_trace() ctypes.windll.shcore.SetProcessDpiAwareness(1) # this improves resolution of GUI root = tk.Tk() root.title(\"Elena's Notes\")",
"= 0, highlightthickness = 0, wrap = \"word\", width = 10, height =",
"you've written in a corresponding .txt # file, and automatically clears the text",
"THE GIVEN ORDER CHECKING THE LOOP INDEX if i == 0: main_button =",
"ACCESS THEM LATER frames.append(frame) # CREATING THE TEXT WIDGETS (I.E. THE INPUT FIELDS)",
"== 0: main_button = functions.create_buttons(frameL, functions.openprobus, \"Probus\", i) elif i == 1: main_button",
"\"Heavi\", i) # Topicalization Study elif i == 4: main_button = functions.create_buttons(frameR, functions.openacode,",
"square, one is green (accent color), # the other one is black (no-selection",
"elif i == 3: main_button = functions.create_buttons(frameR, functions.openheaviness, \"Heavi\", i) # Topicalization Study",
"SQUARE WITH A BLACK BORDER borderImageData = functions.border_string() style = ttk.Style() borderImage =",
"THE INPUT FIELDS) text = tk.Text(frames[i], borderwidth = 0, highlightthickness = 0, wrap",
"color). # CALLING A FUNCTION TO USE A BASE64-ENCODED GIF OF A ROUNDED-CORNER",
"#cfffff #D4F1B2 frameL.pack(side=tk.LEFT, fill=\"both\", expand=True) # side=tk.LEFT places frames side by side frameR.pack(side=tk.LEFT,",
"other one is black (no-selection color). # CALLING A FUNCTION TO USE A",
"i == 2: main_button = functions.create_buttons(frameL, functions.openJALL, \"JALL\", i) #Journal African Languages &",
"# CREATING 2 FRAMES, A LEFT AND A RIGHT FRAME, WHERE TO HOST",
"= tk.PhotoImage(\"focusBorderImage\", data=focusBorderImageData) style.element_create(\"RoundedFrame\", \"image\", borderImage, (\"focus\", focusBorderImage), border=20, sticky=\"nsew\") style.layout(\"RoundedFrame\", [(\"RoundedFrame\", {\"sticky\":",
"# side=tk.LEFT places frames side by side # SET FOCUS TO THE FIRST",
"is over those widgets, # so I am using two base64-encoded gifs of",
"useful for people working on several projects at # the same time and",
"am using two base64-encoded gifs of a rounded-corner square, one is green (accent",
"clears the text widget for you. On the txt file, entries # appear",
"LOOP INDEX if i == 0: main_button = functions.create_buttons(frameL, functions.openprobus, \"Probus\", i) elif",
"data, in which case only the time of writing is # indicated. Above",
"related to those 5 projects. # You write your notes on the desired",
"PIL import ImageTk, Image from tkinter import filedialog import os import ctypes import",
"A FUNCTION TO USE A BASE64-ENCODED GIF OF A ROUNDED-CORNER SQUARE WITH A",
"associated with that # widget. # The red cross button clears the text",
"== 1: main_button = functions.create_buttons(frameL, functions.opensage, \"Sage\", i) elif i == 2: main_button",
"# There are six text widgets in total: 5 corresponding to 5 different",
"corresponding .txt # file, and automatically clears the text widget for you. On",
"30) # ADDING THE BUTTONS INSIDE THE INPUT FIELDS # PARTIAL (IN \"command\")",
"\"image\", borderImage, (\"focus\", focusBorderImage), border=20, sticky=\"nsew\") style.layout(\"RoundedFrame\", [(\"RoundedFrame\", {\"sticky\": \"nsew\"})]) style.configure('TFrame', background= 'black')",
"# I want the border of the text widgets to change color if",
"bg=\"#BAD9D0\") # DECLARING LISTS TO POPULATE WITH OBJECTS THAT WILL BE ACCESSED LATER",
"= 5) # SHOWING THE FRAMES (MOVE TO BOTTOM?) frames[i].pack(side = tk.TOP, fill",
"a light green color frameR = tk.Frame(root, bg=\"#BAD9D0\") # DECLARING LISTS TO POPULATE",
"button_cross.image = img_photo_crs button_cross.pack(side = tk.RIGHT) root.configure(background=\"#BAD9D0\") #BAD9D0 #cfffff #D4F1B2 frameL.pack(side=tk.LEFT, fill=\"both\", expand=True)",
"There are six text widgets in total: 5 corresponding to 5 different projects,",
"# Structure: # There are six text widgets in total: 5 corresponding to",
"CREATING THE TEXT WIDGETS (I.E. THE INPUT FIELDS) text = tk.Text(frames[i], borderwidth =",
"frames[i].state([\"focus\"])) text.bind(\"<FocusOut>\", lambda event: frames[i].state([\"!focus\"])) text.insert(\"end\", \"\") texts.append(text) # CREATING THE BUTTONS FOLLOWING",
"MAIN BUTTON img = functions.image(3) # SETTING BUTTON IMAGES: SECONDARY BUTTONS img_cross =",
"= partial(functions.compile, texts , i), background = \"white\", borderwidth = 0, height =",
"update multiple documents at the same # time and from the same window.",
"there is already an entry # on that txt file with the same",
"widget for you. On the txt file, entries # appear together with the",
"= img) main_button.pack(pady = 5) # SHOWING THE FRAMES (MOVE TO BOTTOM?) frames[i].pack(side",
"able to update multiple documents at the same # time and from the",
"A COMMAND FOR THE BUTTON USING THE INDEX (\"i\") AS ARGUMENT button_check =",
"import ttk from PIL import ImageTk, Image from tkinter import filedialog import os",
"partial(functions.compile, texts , i), background = \"white\", borderwidth = 0, height = 30,",
"frames side by side frameR.pack(side=tk.LEFT, fill=\"both\", expand=True) # side=tk.LEFT places frames side by",
"WHERE TO HOST 3 TEXT WIDGETS EACH frameL = tk.Frame(root, bg=\"#BAD9D0\") # cD4F1B2",
"EACH frameL = tk.Frame(root, bg=\"#BAD9D0\") # cD4F1B2 is a light green color frameR",
"= functions.focusborder_string() # CALLING A FUNCTION TO USE A BASE64-ENCODED GIF OF A",
"fill=\"both\", expand=True) # side=tk.LEFT places frames side by side # SET FOCUS TO",
"the same # time and from the same window. # # Structure: #",
"functools import partial import pdb; #pdb.set_trace() ctypes.windll.shcore.SetProcessDpiAwareness(1) # this improves resolution of GUI",
"True, padx = 30) # ADDING THE BUTTONS INSIDE THE INPUT FIELDS #",
"1: main_button = functions.create_buttons(frameL, functions.opensage, \"Sage\", i) elif i == 2: main_button =",
"on anything else that is # not related to those 5 projects. #",
"tk.Text(frames[i], borderwidth = 0, highlightthickness = 0, wrap = \"word\", width = 10,",
"ttk from PIL import ImageTk, Image from tkinter import filedialog import os import",
"LEFT AND A RIGHT FRAME, WHERE TO HOST 3 TEXT WIDGETS EACH frameL",
"ImageTk, Image from tkinter import filedialog import os import ctypes import functions from",
"side frameR.pack(side=tk.LEFT, fill=\"both\", expand=True) # side=tk.LEFT places frames side by side # SET",
"# SETTING BUTTON IMAGES: SECONDARY BUTTONS img_cross = Image.open('cross1.png') img_cross = img_cross.resize((30,30), Image.ANTIALIAS)",
"# SHOWING THE FRAMES (MOVE TO BOTTOM?) frames[i].pack(side = tk.TOP, fill = \"both\",",
"automatically clears the text widget for you. On the txt file, entries #",
"gifs of a rounded-corner square, one is green (accent color), # the other",
"= True) text.bind(\"<FocusIn>\", lambda event: frames[i].state([\"focus\"])) text.bind(\"<FocusOut>\", lambda event: frames[i].state([\"!focus\"])) text.insert(\"end\", \"\") texts.append(text)",
"= functions.create_buttons(frameR, functions.openheaviness, \"Heavi\", i) # Topicalization Study elif i == 4: main_button",
"TO POPULATE WITH OBJECTS THAT WILL BE ACCESSED LATER USING THE INDEX (\"i\")",
"THE TEXT WIDGETS (I.E. THE INPUT FIELDS) text = tk.Text(frames[i], borderwidth = 0,",
"\"JALL\", i) #Journal African Languages & Linguistics elif i == 3: main_button =",
"GUI to 200X150 # I want the border of the text widgets to",
"side=tk.LEFT places frames side by side frameR.pack(side=tk.LEFT, fill=\"both\", expand=True) # side=tk.LEFT places frames",
"elif i == 1: main_button = functions.create_buttons(frameL, functions.opensage, \"Sage\", i) elif i ==",
"there's a button with the name of the corresponding # project. If clicked,",
"BORDER focusBorderImageData = functions.focusborder_string() # CALLING A FUNCTION TO USE A BASE64-ENCODED GIF",
"TO THE LEFT if i <= 2: frame = ttk.Frame(frameL, style=\"RoundedFrame\", padding=10) #",
"= Image.open('cross1.png') img_cross = img_cross.resize((30,30), Image.ANTIALIAS) img_photo_crs = ImageTk.PhotoImage(img_cross) img_check = Image.open('check1.png') img_check",
"THE INDEX (\"i\") AS ARGUMENT button_check = tk.Button(frames[i], image = img_photo_chk, command =",
"height = 30, width = 30) button_cross.image = img_photo_crs button_cross.pack(side = tk.RIGHT) root.configure(background=\"#BAD9D0\")",
"event: frames[i].state([\"!focus\"])) text.insert(\"end\", \"\") texts.append(text) # CREATING THE BUTTONS FOLLOWING THE GIVEN ORDER",
"i), background = \"white\", borderwidth = 0, height = 30, width = 30)",
"I want the border of the text widgets to change color if the",
"impromptu notes on anything else that is # not related to those 5",
"img_photo_chk button_check.pack(side = tk.LEFT) button_cross = tk.Button(frames[i], image = img_photo_crs, background = \"white\",",
"rounded-corner square, one is green (accent color), # the other one is black",
"frames = [] texts = [] # SETTING BUTTON IMAGES: MAIN BUTTON img",
"button_cross = tk.Button(frames[i], image = img_photo_crs, background = \"white\", borderwidth = 0, height",
"# # Structure: # There are six text widgets in total: 5 corresponding",
"= Image.open('check1.png') img_check = img_check.resize((30,30), Image.ANTIALIAS) img_photo_chk = ImageTk.PhotoImage(img_check) for i in range(6):",
"one is green (accent color), # the other one is black (no-selection color).",
"button with the name of the corresponding # project. If clicked, that button",
"bg=\"#BAD9D0\") # cD4F1B2 is a light green color frameR = tk.Frame(root, bg=\"#BAD9D0\") #",
"(accent color), # the other one is black (no-selection color). # CALLING A",
"border=20, sticky=\"nsew\") style.layout(\"RoundedFrame\", [(\"RoundedFrame\", {\"sticky\": \"nsew\"})]) style.configure('TFrame', background= 'black') # CREATING 2 FRAMES,",
"is already an entry # on that txt file with the same data,",
"THE FRAMES (MOVE TO BOTTOM?) frames[i].pack(side = tk.TOP, fill = \"both\", expand =",
"same window. # # Structure: # There are six text widgets in total:",
"button_cross.pack(side = tk.RIGHT) root.configure(background=\"#BAD9D0\") #BAD9D0 #cfffff #D4F1B2 frameL.pack(side=tk.LEFT, fill=\"both\", expand=True) # side=tk.LEFT places",
"import functions from functools import partial import pdb; #pdb.set_trace() ctypes.windll.shcore.SetProcessDpiAwareness(1) # this improves",
"are six text widgets in total: 5 corresponding to 5 different projects, 1",
"text widget for you. On the txt file, entries # appear together with",
", i), background = \"white\", borderwidth = 0, height = 30, width =",
"the date and time of writing, unless there is already an entry #",
"# The red cross button clears the text widget (note: I had that",
"USING THE INDEX (\"i\") frames = [] texts = [] # SETTING BUTTON",
"# a previous version of this code, then I removed the function but",
"US TO SET A COMMAND FOR THE BUTTON USING THE INDEX (\"i\") AS",
"# CALLING A FUNCTION TO USE A BASE64-ENCODED GIF OF A ROUNDED-CORNER SQUARE",
"done, you click on # the green tick button, which saves what you've",
"LISTS TO POPULATE WITH OBJECTS THAT WILL BE ACCESSED LATER USING THE INDEX",
"BE ACCESSED LATER USING THE INDEX (\"i\") frames = [] texts = []",
"USING THE INDEX (\"i\") AS ARGUMENT button_check = tk.Button(frames[i], image = img_photo_chk, command",
"& Linguistics elif i == 3: main_button = functions.create_buttons(frameR, functions.openheaviness, \"Heavi\", i) #",
"be able to update multiple documents at the same # time and from",
"button_check.image = img_photo_chk button_check.pack(side = tk.LEFT) button_cross = tk.Button(frames[i], image = img_photo_crs, background",
"texts , i), background = \"white\", borderwidth = 0, height = 30, width",
"on that txt file with the same data, in which case only the",
"os import ctypes import functions from functools import partial import pdb; #pdb.set_trace() ctypes.windll.shcore.SetProcessDpiAwareness(1)",
"this improves resolution of GUI root = tk.Tk() root.title(\"Elena's Notes\") #root.geometry('200x150') # this",
"frameL = tk.Frame(root, bg=\"#BAD9D0\") # cD4F1B2 is a light green color frameR =",
"BOTTOM?) frames[i].pack(side = tk.TOP, fill = \"both\", expand = True, padx = 30)",
"= img_photo_chk button_check.pack(side = tk.LEFT) button_cross = tk.Button(frames[i], image = img_photo_crs, background =",
"A ROUNDED-CORNER SQUARE WITH A GREEN BORDER focusBorderImageData = functions.focusborder_string() # CALLING A",
"corresponding # project. If clicked, that button opens the .txt document associated with",
"SUBFRAMES GO TO THE RIGHT else: frame = ttk.Frame(frameR, style=\"RoundedFrame\", padding=10) # APPEND",
"(I.E. THE INPUT FIELDS) text = tk.Text(frames[i], borderwidth = 0, highlightthickness = 0,",
"img_photo_crs button_cross.pack(side = tk.RIGHT) root.configure(background=\"#BAD9D0\") #BAD9D0 #cfffff #D4F1B2 frameL.pack(side=tk.LEFT, fill=\"both\", expand=True) # side=tk.LEFT",
"widgets in total: 5 corresponding to 5 different projects, 1 # (\"Misc\", from",
"wrap = \"word\", width = 10, height = 5) text.pack(fill = \"both\", expand",
"AS ARGUMENT button_check = tk.Button(frames[i], image = img_photo_chk, command = partial(functions.compile, texts ,",
"# SETTING BUTTON IMAGES: MAIN BUTTON img = functions.image(3) # SETTING BUTTON IMAGES:",
"text.pack(fill = \"both\", expand = True) text.bind(\"<FocusIn>\", lambda event: frames[i].state([\"focus\"])) text.bind(\"<FocusOut>\", lambda event:",
"FUNCTION TO USE A BASE64-ENCODED GIF OF A ROUNDED-CORNER SQUARE WITH A GREEN",
"style = ttk.Style() borderImage = tk.PhotoImage(\"borderImage\", data=borderImageData) focusBorderImage = tk.PhotoImage(\"focusBorderImage\", data=focusBorderImageData) style.element_create(\"RoundedFrame\", \"image\",",
"\"white\", borderwidth = 0, height = 30, width = 30) button_check.image = img_photo_chk",
"cursor is over those widgets, # so I am using two base64-encoded gifs",
"'black') # CREATING 2 FRAMES, A LEFT AND A RIGHT FRAME, WHERE TO",
"3 TEXT WIDGETS EACH frameL = tk.Frame(root, bg=\"#BAD9D0\") # cD4F1B2 is a light",
"Version: January 2022 # # Purpose: # This is a note-taking app, useful",
"= 0, height = 30, width = 30) button_cross.image = img_photo_crs button_cross.pack(side =",
"time and who want to be able to update multiple documents at the",
"from tkinter import filedialog import os import ctypes import functions from functools import",
"several projects at # the same time and who want to be able",
"from PIL import ImageTk, Image from tkinter import filedialog import os import ctypes",
"the border of the text widgets to change color if the cursor is",
"#Journal African Languages & Linguistics elif i == 3: main_button = functions.create_buttons(frameR, functions.openheaviness,",
"0, height = 30, width = 30) button_cross.image = img_photo_crs button_cross.pack(side = tk.RIGHT)",
"= functions.create_buttons(frameR, functions.openacode, \"ACoDe\", i) elif i == 5: main_button = functions.create_buttons(frameR, functions.openmisc,",
"background = \"white\", borderwidth = 0, height = 30, width = 30) button_check.image",
"Image from tkinter import filedialog import os import ctypes import functions from functools",
"size of the GUI to 200X150 # I want the border of the",
"= tk.LEFT) button_cross = tk.Button(frames[i], image = img_photo_crs, background = \"white\", borderwidth =",
"side # SET FOCUS TO THE FIRST FRAME frames[0].focus_set() font_tuple = (\"Garamond\", 14)",
"SINGLE FRAME TO THE LIST TO ACCESS THEM LATER frames.append(frame) # CREATING THE",
"button, which saves what you've written in a corresponding .txt # file, and",
"button_check.pack(side = tk.LEFT) button_cross = tk.Button(frames[i], image = img_photo_crs, background = \"white\", borderwidth",
"DECLARING LISTS TO POPULATE WITH OBJECTS THAT WILL BE ACCESSED LATER USING THE",
"widget there's a button with the name of the corresponding # project. If",
"\"Sage\", i) elif i == 2: main_button = functions.create_buttons(frameL, functions.openJALL, \"JALL\", i) #Journal",
"= 5) text.pack(fill = \"both\", expand = True) text.bind(\"<FocusIn>\", lambda event: frames[i].state([\"focus\"])) text.bind(\"<FocusOut>\",",
"in a corresponding .txt # file, and automatically clears the text widget for",
"#BAD9D0 #cfffff #D4F1B2 frameL.pack(side=tk.LEFT, fill=\"both\", expand=True) # side=tk.LEFT places frames side by side",
"writing is # indicated. Above every widget there's a button with the name",
"= ttk.Style() borderImage = tk.PhotoImage(\"borderImage\", data=borderImageData) focusBorderImage = tk.PhotoImage(\"focusBorderImage\", data=focusBorderImageData) style.element_create(\"RoundedFrame\", \"image\", borderImage,",
"= img_photo_crs, background = \"white\", borderwidth = 0, height = 30, width =",
"== 4: main_button = functions.create_buttons(frameR, functions.openacode, \"ACoDe\", i) elif i == 5: main_button",
"TO USE A BASE64-ENCODED GIF OF A ROUNDED-CORNER SQUARE WITH A BLACK BORDER",
"# and I still haven't gotten around to linking it again) # ####################################################################################",
"i <= 2: frame = ttk.Frame(frameL, style=\"RoundedFrame\", padding=10) # THE LAST 3 SUBFRAMES",
"i) main_button.config(image = img) main_button.pack(pady = 5) # SHOWING THE FRAMES (MOVE TO",
"ctypes.windll.shcore.SetProcessDpiAwareness(1) # this improves resolution of GUI root = tk.Tk() root.title(\"Elena's Notes\") #root.geometry('200x150')",
"working on several projects at # the same time and who want to",
"= functions.border_string() style = ttk.Style() borderImage = tk.PhotoImage(\"borderImage\", data=borderImageData) focusBorderImage = tk.PhotoImage(\"focusBorderImage\", data=focusBorderImageData)",
"anything else that is # not related to those 5 projects. # You",
"#################################################################################### import tkinter as tk from tkinter import ttk from PIL import ImageTk,",
"# THE LAST 3 SUBFRAMES GO TO THE RIGHT else: frame = ttk.Frame(frameR,",
"elif i == 4: main_button = functions.create_buttons(frameR, functions.openacode, \"ACoDe\", i) elif i ==",
"import ImageTk, Image from tkinter import filedialog import os import ctypes import functions",
"A LEFT AND A RIGHT FRAME, WHERE TO HOST 3 TEXT WIDGETS EACH",
"haven't gotten around to linking it again) # #################################################################################### import tkinter as tk",
"4: main_button = functions.create_buttons(frameR, functions.openacode, \"ACoDe\", i) elif i == 5: main_button =",
"# the green tick button, which saves what you've written in a corresponding",
"with the name of the corresponding # project. If clicked, that button opens",
"#root.geometry('200x150') # this adjusts the size of the GUI to 200X150 # I",
"total: 5 corresponding to 5 different projects, 1 # (\"Misc\", from \"Miscellaneous\"for taking",
"FIRST 3 SUBFRAMES GO TO THE LEFT if i <= 2: frame =",
"= tk.TOP, fill = \"both\", expand = True, padx = 30) # ADDING",
"tk.Tk() root.title(\"Elena's Notes\") #root.geometry('200x150') # this adjusts the size of the GUI to",
"the corresponding # project. If clicked, that button opens the .txt document associated",
"for you. On the txt file, entries # appear together with the date",
"what you've written in a corresponding .txt # file, and automatically clears the",
"GIF OF A ROUNDED-CORNER SQUARE WITH A BLACK BORDER borderImageData = functions.border_string() style",
"THAT WILL BE ACCESSED LATER USING THE INDEX (\"i\") frames = [] texts",
"GREEN BORDER focusBorderImageData = functions.focusborder_string() # CALLING A FUNCTION TO USE A BASE64-ENCODED",
"elif i == 5: main_button = functions.create_buttons(frameR, functions.openmisc, \"MISC\", i) main_button.config(image = img)",
"Image.open('check1.png') img_check = img_check.resize((30,30), Image.ANTIALIAS) img_photo_chk = ImageTk.PhotoImage(img_check) for i in range(6): #",
"six text widgets in total: 5 corresponding to 5 different projects, 1 #",
"tkinter import filedialog import os import ctypes import functions from functools import partial",
"on # the green tick button, which saves what you've written in a",
"green (accent color), # the other one is black (no-selection color). # CALLING",
"is a note-taking app, useful for people working on several projects at #",
"people working on several projects at # the same time and who want",
"to linking it again) # #################################################################################### import tkinter as tk from tkinter import",
"# the same time and who want to be able to update multiple",
"# THE FIRST 3 SUBFRAMES GO TO THE LEFT if i <= 2:",
"#################################################################################### # Version: January 2022 # # Purpose: # This is a note-taking",
"case only the time of writing is # indicated. Above every widget there's",
"red cross button clears the text widget (note: I had that link to",
"Notes\") #root.geometry('200x150') # this adjusts the size of the GUI to 200X150 #",
"Image.open('cross1.png') img_cross = img_cross.resize((30,30), Image.ANTIALIAS) img_photo_crs = ImageTk.PhotoImage(img_cross) img_check = Image.open('check1.png') img_check =",
"still haven't gotten around to linking it again) # #################################################################################### import tkinter as",
"adjusts the size of the GUI to 200X150 # I want the border",
"= functions.create_buttons(frameL, functions.opensage, \"Sage\", i) elif i == 2: main_button = functions.create_buttons(frameL, functions.openJALL,",
"ttk.Style() borderImage = tk.PhotoImage(\"borderImage\", data=borderImageData) focusBorderImage = tk.PhotoImage(\"focusBorderImage\", data=focusBorderImageData) style.element_create(\"RoundedFrame\", \"image\", borderImage, (\"focus\",",
"padx = 30) # ADDING THE BUTTONS INSIDE THE INPUT FIELDS # PARTIAL",
"WILL BE ACCESSED LATER USING THE INDEX (\"i\") frames = [] texts =",
"30, width = 30) button_check.image = img_photo_chk button_check.pack(side = tk.LEFT) button_cross = tk.Button(frames[i],",
"multiple documents at the same # time and from the same window. #",
"SHOWING THE FRAMES (MOVE TO BOTTOM?) frames[i].pack(side = tk.TOP, fill = \"both\", expand",
"of writing is # indicated. Above every widget there's a button with the",
"I had that link to a function in # a previous version of",
"TO BOTTOM?) frames[i].pack(side = tk.TOP, fill = \"both\", expand = True, padx =",
"the function but left the button, # and I still haven't gotten around",
"Topicalization Study elif i == 4: main_button = functions.create_buttons(frameR, functions.openacode, \"ACoDe\", i) elif",
"texts = [] # SETTING BUTTON IMAGES: MAIN BUTTON img = functions.image(3) #",
"TO HOST 3 TEXT WIDGETS EACH frameL = tk.Frame(root, bg=\"#BAD9D0\") # cD4F1B2 is",
"2: main_button = functions.create_buttons(frameL, functions.openJALL, \"JALL\", i) #Journal African Languages & Linguistics elif",
"= img_check.resize((30,30), Image.ANTIALIAS) img_photo_chk = ImageTk.PhotoImage(img_check) for i in range(6): # THE FIRST"
] |
[
"def run(self, opt, data_loader, writer, epoch=0): total_losses = self.loss_tuple(0, 0, 0, 0) data_length",
"stat(model=self.seg_net, input_size=(3, 256, 256)) self.sparse_l1 = torch.nn.SmoothL1Loss(reduction='none') self.l1 = torch.nn.SmoothL1Loss() self.l2 = torch.nn.MSELoss()",
"batch['num_points'] = batch['num_points'].long() num = batch['num_points'].view(batch_size, 1) batch['yx_loc'] = batch['yx_loc'].long() sub = 0",
"target=foreground) total_loss += background_loss mse = self.criterion_mse(output=output[1], batch=batch) losses = self.loss_tuple(total_loss=total_loss, NOC_loss=noc_loss, background_loss=background_loss,",
"__call__(self, tensor): \"\"\" Args: tensor (Tensor): Tensor image of size (C, H, W)",
"np.savetxt(write_file, concatenated_gt, fmt=' '.join(['%0.8f'] * 3 + ['%d'] * 3)) def validate(self, test_loader,",
"== 0: print(\"Epoch: {} | Iteration: {} | Train Loss: {}\".format(epoch, niter, losses.total_loss.item()))",
"sample=batch['noc_image'], niter=niter) return True class UnNormalize(object): def __init__(self, mean, std): self.mean = mean",
":num[idx, 0], :] noc_points = torch.transpose(noc_points, 0, 1) sub += self.l1(output[idx, :, batch['yx_loc'][idx,",
"tensor class TrainNOCs: def __init__(self, save_dir='Trial', mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), num_downs=5,",
"'.join(['%0.8f'] * 3 + ['%d'] * 3)) with open(os.path.join(ply_dir, 'Ground_truth_{}.ply'.format(idx + pdx)), 'w')",
"name=\"Train Total\", niter=niter, foreground=self.foreground) # batch['image'] = self.un_norm(batch['image']) # visualize(writer=writer.train, batch=batch, output=(output, loss),",
"self.un_norm(batch['image']) # visualize(writer=writer.train, batch=batch, output=(output, loss), # name=\"Train\", niter=niter) # Last Iteration if",
"utils.common import * def visualize(batch, output, writer, name, niter, foreground=False, test=False): output_image =",
"256)) self.sparse_l1 = torch.nn.SmoothL1Loss(reduction='none') self.l1 = torch.nn.SmoothL1Loss() self.l2 = torch.nn.MSELoss() self.bce = torch.nn.BCEWithLogitsLoss()",
"forward_sparse(self, batch): total_loss = 0 output = self.seg_net(batch['image']) # if 'mask_image' in batch.keys():",
"= batch['noc_points'][idx, :num[idx, 0], :] noc_points = torch.transpose(noc_points, 0, 1) sub += self.l2(output[idx,",
"batch['yx_loc'][pdx, :num[pdx, 0], 0], batch['yx_loc'][pdx, :num[pdx, 0], 1]] noc_gt = batch['noc_points'][pdx, :num[pdx, 0]].cpu().numpy()",
"# batch['image'] = self.un_norm(batch['image']) batch['image'] = batch['image'] * 2 - 1 test_writer.add_scalar('PSNR', total_losses.NOC_mse,",
"output=(output, self.loss_tuple(0, 0, 0, 0)), name=\"Validation\", niter=niter, foreground=self.foreground, test=True) def run(self, opt, data_loader,",
"# use_dropout=False, norm_layer=torch.nn.BatchNorm2d, # last_layer=nn.ReLU()) self.foreground = True else: self.foreground = None print(\"Error!",
"'Output_{}.ply'.format(idx + pdx)), 'w') as write_file: write_file.write(start) np.savetxt(write_file, concatenated_out, fmt=' '.join(['%0.8f'] * 3",
"= batch['num_points'].shape[0] batch['num_points'] = batch['num_points'].long() num = batch['num_points'].view(batch_size, 1) batch['yx_loc'] = batch['yx_loc'].long() sub",
"niter=niter, foreground=self.foreground, test=True) def run(self, opt, data_loader, writer, epoch=0): total_losses = self.loss_tuple(0, 0,",
"batch): output, losses = self.forward(batch=batch) # output = self.seg_net(batch['image']) # # # if",
"pdx in range(batch_size): image = batch['image'][pdx, :, batch['yx_loc'][pdx, :num[pdx, 0], 0], batch['yx_loc'][pdx, :num[pdx,",
"PLY if write_ply: self.write_noc_ply(output=output, batch=batch, idx=idx, ply_dir=ply_dir) for jdx, val in enumerate(losses): if",
"for idx, batch in enumerate(data_loader.train): for keys in batch: batch[keys] = batch[keys].float().cuda() #",
"1, niter=niter) final_noc = output_image * (torch.softmax(output[0][0], 1)[:, 1:2, :, :] > 0.5).float()",
"batch['num_points'].view(batch_size, 1) batch['yx_loc'] = batch['yx_loc'].long() sub = 0 for idx in range(batch_size): if",
"for jdx, val in enumerate(losses): if jdx is 3: total_losses[jdx] += 10 *",
"total_losses[jdx] += losses[jdx].item() # total_loss += loss.item() niter = idx + (epoch *",
"self.mean = mean self.std = std self.loss_tuple = recordclass('losses', ('total_loss', 'NOC_loss', 'background_loss', 'NOC_mse'))",
"if checkpoint is not None: checkpoint = torch.load(checkpoint) self.seg_net.load_state_dict(checkpoint['model']) self.optimizer.load_state_dict(checkpoint['optimizer']) self.save_path = os.path.join(\"../saves\",",
"'save_{}.pth'.format(niter))) # visualize(writer=writer.train, batch=batch, output=(output, total_losses), # name=\"Train Total\", niter=(epoch + 1) *",
"Total\", niter=(epoch + 1) * data_length) # self.test(test_loader=data_loader.test, test_writer=writer.test, niter=(epoch + 1) *",
"- 1): # print(len(test_loader)) for jdx, val in enumerate(total_losses): total_losses[jdx] /= len(test_loader) print(\"Validation",
"niter=niter, foreground=self.foreground) def test(self, test_loader, niter, test_writer): with torch.no_grad(): self.seg_net.eval() for idx, batch",
"- 1 test_writer.add_scalar('PSNR', total_losses.NOC_mse, niter) visualize(writer=test_writer, batch=batch, output=(output, total_losses), name=\"Validation\", niter=niter, foreground=self.foreground) def",
"name=\"{}/Output_Foreground\".format(name), sample=((torch.softmax(foreground, 1)[:, 1:2, :, :] > 0.5).long() * 2) - 1, niter=niter)",
"+ ['%d'] * 3)) def validate(self, test_loader, niter, test_writer, write_ply=False, ply_dir=''): total_losses =",
"enumerate(test_loader): for keys in batch: batch[keys] = batch[keys].float().cuda() output = self.seg_net(batch['image']) batch['image'] =",
"noc_loss = self.criterion_l1_sparse(output=output[1], batch=batch) total_loss += noc_loss * 70 # print(torch.max(((1 - batch['background'][:,",
"in enumerate(data_loader.train): for keys in batch: batch[keys] = batch[keys].float().cuda() # batch['image'] = batch['image']",
"losses), name=\"Train Total\", niter=niter, foreground=self.foreground) # batch['image'] = self.un_norm(batch['image']) # visualize(writer=writer.train, batch=batch, output=(output,",
"= idx + (epoch * data_length) if idx % opt.log_iter == 0: print(\"Epoch:",
"/ (num_points * 3) batch['num_points'] = batch['num_points'].long() num = batch['num_points'].view(batch_size, 1) batch['yx_loc'] =",
"os.mkdir(self.save_path) self.batch_size = batch_size self.mean = mean self.std = std self.loss_tuple = recordclass('losses',",
"> 0.5).long() * 2) - 1, niter=niter) final_noc = output_image * (torch.softmax(output[0][0], 1)[:,",
"uchar green property uchar blue end_header\\n''' self.un_norm = UnNormalize(mean=self.mean, std=self.std) def criterion_mse(self, output,",
"batch[keys].float().cuda() output, losses = self.forward(batch=batch) # View NOC as PLY if write_ply: self.write_noc_ply(output=output,",
"= ResNet2HeadGenerator(out_channels=3, last_layer=nn.ReLU()) if model_type == 'res_unet': self.seg_net = ResUnet2HeadGenerator(output_nc=3, last_layer=nn.ReLU()) # self.seg_net",
"foreground[:, 0, :, :] = batch['background'][:, 0, :, :] background_loss = self.bce(input=output[0], target=foreground)",
"batch_size = batch['num_points'].shape[0] batch['num_points'] = batch['num_points'].long() num = batch['num_points'].view(batch_size, 1) batch['yx_loc'] = batch['yx_loc'].long()",
"# num_points[num_points == 0] = 1 # sub = torch.abs(output - target) #",
"import * from utils.common import * def visualize(batch, output, writer, name, niter, foreground=False,",
"(Tensor): Tensor image of size (C, H, W) to be normalized. Returns: Tensor:",
"torch.transpose(noc_points, 0, 1) sub += self.l1(output[idx, :, batch['yx_loc'][idx, :num[idx, 0], 0], batch['yx_loc'][idx, :num[idx,",
"= self.forward(batch=batch) # View NOC as PLY if write_ply: self.write_noc_ply(output=output, batch=batch, idx=idx, ply_dir=ply_dir)",
"jdx, val in enumerate(total_losses): total_losses[jdx] /= data_length print(\"Epoch: {} | Final Iteration: {}",
"fmt=' '.join(['%0.8f'] * 3 + ['%d'] * 3)) with open(os.path.join(ply_dir, 'Ground_truth_{}.ply'.format(idx + pdx)),",
"self.seg_net.cuda() self.sparse_l1.cuda() self.l1.cuda() self.bce.cuda() self.seg_net.train() self.criterion_selection = None self.lr = lr self.optimizer =",
"log10(1 / losses[jdx].item()) else: total_losses[jdx] += losses[jdx].item() # total_losses.total_loss += losses.total_loss.item() if idx",
"0]].cpu().numpy() image = image.cpu().numpy().T image = image[:, [2, 1, 0]] * 255 output_arr",
"10 # loss = self.l1(masked_output, batch['noc_image']) background_target = torch.zeros_like(output) background_loss = self.l1(output *",
"# visualize(writer=writer.train, batch=batch, output=(output, loss), # name=\"Train\", niter=niter) # Last Iteration if idx",
"2) - 1, niter=niter) final_noc = output_image * (torch.softmax(output[0][0], 1)[:, 1:2, :, :]",
"= batch[keys].float().cuda() output = self.seg_net(batch['image']) batch['image'] = batch['image'] * 2 - 1 visualize(writer=test_writer,",
"idx, batch in enumerate(test_loader): for keys in batch: batch[keys] = batch[keys].float().cuda() output, losses",
"output=(output, losses), name=\"Train Total\", niter=niter, foreground=self.foreground) # batch['image'] = self.un_norm(batch['image']) # visualize(writer=writer.train, batch=batch,",
"2) - 1, niter=niter) writer.add_scalar('L1-Loss', output[1].total_loss, niter) writer.add_scalar('NOC-Loss', output[1].NOC_loss, niter) writer.add_scalar('Background-Loss', output[1].background_loss, niter)",
"1, niter=niter) write_image(writer, name=\"{}/Input\".format(name), sample=batch['image'], niter=niter) if not test: write_image(writer, name=\"{}/Ground Truth NOC\".format(name),",
"torch.sum(sub, dim=(1, 2, 3)) # sub_batch = sub_batch / (num_points * 3) batch['num_points']",
"Total\", niter=niter, foreground=self.foreground) # batch['image'] = self.un_norm(batch['image']) # visualize(writer=writer.train, batch=batch, output=(output, loss), #",
"losses[jdx].item()) else: total_losses[jdx] += losses[jdx].item() # total_losses.total_loss += losses.total_loss.item() if idx == (len(test_loader)",
"as write_file: write_file.write(start) np.savetxt(write_file, concatenated_gt, fmt=' '.join(['%0.8f'] * 3 + ['%d'] * 3))",
"ResUnet2HeadGenerator(output_nc=3, last_layer=nn.ReLU()) # self.seg_net = Unet2HeadGenerator(input_nc=3, output_nc=3, num_downs=num_downs, # use_dropout=False, norm_layer=torch.nn.BatchNorm2d, # last_layer=nn.ReLU())",
"-> t.sub_(m).div_(s) return tensor class TrainNOCs: def __init__(self, save_dir='Trial', mean=(0.5, 0.5, 0.5), std=(0.5,",
"for idx, batch in enumerate(test_loader): for keys in batch: batch[keys] = batch[keys].float().cuda() output",
"batch['noc_points'][idx, :num[idx, 0], :] noc_points = torch.transpose(noc_points, 0, 1) sub += self.l2(output[idx, :,",
"# # if 'mask_image' in batch.keys(): # masked_output = output * batch['mask_image'] #",
"0], batch['yx_loc'][pdx, :num[pdx, 0], 1]] noc_gt = batch['noc_points'][pdx, :num[pdx, 0]].cpu().numpy() image = image.cpu().numpy().T",
"self.un_norm = UnNormalize(mean=self.mean, std=self.std) def criterion_mse(self, output, batch): batch_size = batch['num_points'].shape[0] batch['num_points'] =",
"pdx)), image.astype('uint8')) with open(os.path.join(ply_dir, 'Output_{}.ply'.format(idx + pdx)), 'w') as write_file: write_file.write(start) np.savetxt(write_file, concatenated_out,",
"True else: self.foreground = None print(\"Error! Unknown number of heads!\") exit(256) print(\"Using model",
"opt, data_loader, writer, epoch=0): total_losses = self.loss_tuple(0, 0, 0, 0) data_length = len(data_loader.train)",
"# name=\"Train Total\", niter=(epoch + 1) * data_length) # self.test(test_loader=data_loader.test, test_writer=writer.test, niter=(epoch +",
"(1 - batch['background'][:, 0:2, :, :]).float() foreground[:, 0, :, :] = batch['background'][:, 0,",
"np.concatenate((noc_gt, image), axis=1) image = batch['image'][pdx, :, :, :].cpu().numpy() image = image.transpose(1, 2,",
"batch[keys] = batch[keys].float().cuda() output, losses = self.forward(batch=batch) # View NOC as PLY if",
"self.sparse_l1(output, target) # sub_batch = torch.sum(sub, dim=(1, 2, 3)) # sub_batch = sub_batch",
"batch): batch_size = batch['num_points'].shape[0] # num_points[num_points == 0] = 1 # sub =",
"1) for pdx in range(batch_size): image = batch['image'][pdx, :, batch['yx_loc'][pdx, :num[pdx, 0], 0],",
"0) if write_ply: if not os.path.exists(ply_dir): os.mkdir(ply_dir) with torch.no_grad(): self.seg_net.eval() for idx, batch",
"name=\"Validation\", niter=niter, foreground=self.foreground) def test(self, test_loader, niter, test_writer): with torch.no_grad(): self.seg_net.eval() for idx,",
"output[0][1] foreground = output[0][0] write_image(writer, name=\"{}/Ground Truth Foreground\".format(name), sample=((1 - batch['background']).long() * 2",
"Args: tensor (Tensor): Tensor image of size (C, H, W) to be normalized.",
"= torch.nn.BCEWithLogitsLoss() self.seg_net.cuda() self.sparse_l1.cuda() self.l1.cuda() self.bce.cuda() self.seg_net.train() self.criterion_selection = None self.lr = lr",
"self.l1(output[idx, :, batch['yx_loc'][idx, :num[idx, 0], 0], batch['yx_loc'][idx, :num[idx, 0], 1]], noc_points) return sub",
"total_loss = 0 output = self.seg_net(batch['image']) # if 'mask_image' in batch.keys(): # masked_output",
"background_loss=background_loss, NOC_mse=mse) return output, losses def forward_2_heads(self, batch): total_loss = 0 output =",
"self.optimizer.zero_grad() losses.total_loss.backward() self.optimizer.step() return output, losses def write_noc_ply(self, output, batch, idx, ply_dir): batch_size",
"for param_group in self.optimizer.param_groups: param_group['lr'] = self.lr for idx, batch in enumerate(data_loader.train): for",
"__init__(self, save_dir='Trial', mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), num_downs=5, lr=2e-4, betas=(0.5, 0.999), batch_size=8,",
"* (batch['mask_image'] > 0).float() batch['num_points'] = batch['num_points'].long() num = batch['num_points'].view(batch_size, 1) for pdx",
"self.loss_tuple(0, 0, 0, 0) data_length = len(data_loader.train) self.seg_net.train() if epoch > 0 and",
"print(\"Validation loss: {}\".format(total_losses.total_loss)) # batch['image'] = self.un_norm(batch['image']) batch['image'] = batch['image'] * 2 -",
"* 255 output_arr = output_arr.cpu().numpy().T start = self.ply_start.format(num[pdx, 0].item()) concatenated_out = np.concatenate((output_arr, image),",
"Truth NOC\".format(name), sample=batch['noc_image'], niter=niter) return True class UnNormalize(object): def __init__(self, mean, std): self.mean",
"= self.seg_net(batch['image']) # masked_output = output[1] * (batch['mask_image'] > 0).float() noc_loss = self.criterion_l1_sparse(output=output[1],",
"name=\"{}/Ground Truth NOC\".format(name), sample=batch['noc_image'], niter=niter) return True class UnNormalize(object): def __init__(self, mean, std):",
"idx, batch in enumerate(test_loader): for keys in batch: batch[keys] = batch[keys].float().cuda() output =",
"self.loss_tuple(0, 0, 0, 0)), name=\"Validation\", niter=niter, foreground=self.foreground, test=True) def run(self, opt, data_loader, writer,",
"self.foreground = False elif output_heads == 'two': self.forward = self.forward_2_heads self.seg_net = ResNet2HeadGenerator(out_channels=3,",
"self.optimizer.state_dict()}, os.path.join(self.save_path, 'save_{}.pth'.format(niter))) # visualize(writer=writer.train, batch=batch, output=(output, total_losses), # name=\"Train Total\", niter=(epoch +",
"output_nc=3, num_downs=num_downs, # use_dropout=False, norm_layer=torch.nn.BatchNorm2d, # last_layer=nn.ReLU()) self.foreground = True else: self.foreground =",
"# last_layer=nn.LeakyReLU(0.2)) self.foreground = False elif output_heads == 'two': self.forward = self.forward_2_heads self.seg_net",
"torch.nn.SmoothL1Loss(reduction='none') self.l1 = torch.nn.SmoothL1Loss() self.l2 = torch.nn.MSELoss() self.bce = torch.nn.BCEWithLogitsLoss() self.seg_net.cuda() self.sparse_l1.cuda() self.l1.cuda()",
"sub += self.l2(output[idx, :, batch['yx_loc'][idx, :num[idx, 0], 0], batch['yx_loc'][idx, :num[idx, 0], 1]], noc_points)",
"output[1].NOC_loss, niter) writer.add_scalar('Background-Loss', output[1].background_loss, niter) write_image(writer, name=\"{}/Output_NOC\".format(name), sample=(output_image * 2) - 1, niter=niter)",
"batch.keys(): # masked_output = output * batch['mask_image'] # # loss = self.criterion_l1(output=masked_output, batch=batch)",
"std=self.std) def criterion_mse(self, output, batch): batch_size = batch['num_points'].shape[0] batch['num_points'] = batch['num_points'].long() num =",
"not test: write_image(writer, name=\"{}/Ground Truth NOC\".format(name), sample=batch['noc_image'], niter=niter) return True class UnNormalize(object): def",
"def __call__(self, tensor): \"\"\" Args: tensor (Tensor): Tensor image of size (C, H,",
"Tensor: Normalized image. \"\"\" for t, m, s in zip(tensor, self.mean, self.std): t.mul_(s).add_(m)",
"0], 0], batch['yx_loc'][idx, :num[idx, 0], 1]], noc_points) return sub / batch_size def criterion_l1_sparse(self,",
"t.mul_(s).add_(m) # The normalize code -> t.sub_(m).div_(s) return tensor class TrainNOCs: def __init__(self,",
"* data_length) # self.test(test_loader=data_loader.test, test_writer=writer.test, niter=(epoch + 1) * data_length) self.validate(test_loader=data_loader.validate, test_writer=writer.validate, niter=(epoch",
"= torch.nn.SmoothL1Loss(reduction='none') self.l1 = torch.nn.SmoothL1Loss() self.l2 = torch.nn.MSELoss() self.bce = torch.nn.BCEWithLogitsLoss() self.seg_net.cuda() self.sparse_l1.cuda()",
"- 1, niter=niter) writer.add_scalar('L1-Loss', output[1].total_loss, niter) writer.add_scalar('NOC-Loss', output[1].NOC_loss, niter) writer.add_scalar('Background-Loss', output[1].background_loss, niter) write_image(writer,",
"# self.seg_net.apply(init_weights) # stat(model=self.seg_net, input_size=(3, 256, 256)) self.sparse_l1 = torch.nn.SmoothL1Loss(reduction='none') self.l1 = torch.nn.SmoothL1Loss()",
"- target) # sub = self.sparse_l1(output, target) # sub_batch = torch.sum(sub, dim=(1, 2,",
"output, losses = self.train(batch=batch) # print(batch['num_points'], torch.sum(batch['num_points'])) for jdx, val in enumerate(losses): if",
"checkpoint is not None: checkpoint = torch.load(checkpoint) self.seg_net.load_state_dict(checkpoint['model']) self.optimizer.load_state_dict(checkpoint['optimizer']) self.save_path = os.path.join(\"../saves\", save_dir)",
"(batch['mask_image'] > 0).float() batch['num_points'] = batch['num_points'].long() num = batch['num_points'].view(batch_size, 1) for pdx in",
"data_length + 1) print(\"*\" * 100) if __name__ == \"__main__\": noc_class = TrainNOCs()",
"niter = idx + (epoch * data_length) if idx % opt.log_iter == 0:",
"/= data_length print(\"Epoch: {} | Final Iteration: {} | Train Loss: {}\".format(epoch, niter,",
"cv2 from recordclass import recordclass from torchstat import stat from math import log10",
"self.foreground: out_arr = output[1] else: out_arr = output output_arr = out_arr[pdx, :, batch['yx_loc'][pdx,",
"Train NOC class \"\"\" import os import cv2 from recordclass import recordclass from",
"self.loss_tuple(0, 0, 0, 0) if write_ply: if not os.path.exists(ply_dir): os.mkdir(ply_dir) with torch.no_grad(): self.seg_net.eval()",
"* 2 - 1 visualize(writer=test_writer, batch=batch, output=(output, self.loss_tuple(0, 0, 0, 0)), name=\"Validation\", niter=niter,",
"/= len(test_loader) print(\"Validation loss: {}\".format(total_losses.total_loss)) # batch['image'] = self.un_norm(batch['image']) batch['image'] = batch['image'] *",
"batch): total_loss = 0 output = self.seg_net(batch['image']) # masked_output = output[1] * (batch['mask_image']",
"background_loss = self.l1(output * batch['background'], background_target) total_loss += background_loss mse = self.criterion_mse(output=output, batch=batch)",
"from math import log10 from models.networks import * from utils.common import * def",
"# self.seg_net = Unet2HeadGenerator(input_nc=3, output_nc=3, num_downs=num_downs, # use_dropout=False, norm_layer=torch.nn.BatchNorm2d, # last_layer=nn.ReLU()) self.foreground =",
"= False elif output_heads == 'two': self.forward = self.forward_2_heads self.seg_net = ResNet2HeadGenerator(out_channels=3, last_layer=nn.ReLU())",
"0], batch['yx_loc'][idx, :num[idx, 0], 1]], noc_points) return sub / batch_size def criterion_l1_sparse(self, output,",
"3) batch['num_points'] = batch['num_points'].long() num = batch['num_points'].view(batch_size, 1) batch['yx_loc'] = batch['yx_loc'].long() sub =",
"batch['noc_image']) / ( # torch.sum(batch['num_points']) + 1 * (torch.sum(batch['num_points'] == 0).float())) # self.optimizer.zero_grad()",
":] > 0.5).long() * 2) - 1, niter=niter) final_noc = output_image * (torch.softmax(output[0][0],",
"test=False): output_image = output[0] if foreground: output_image = output[0][1] foreground = output[0][0] write_image(writer,",
"= torch.zeros_like(output) background_loss = self.l1(output * batch['background'], background_target) total_loss += background_loss mse =",
"batch=batch, output=(output, loss), # name=\"Train\", niter=niter) # Last Iteration if idx == (data_length",
"uchar red property uchar green property uchar blue end_header\\n''' self.un_norm = UnNormalize(mean=self.mean, std=self.std)",
"0.5).float() write_image(writer, name=\"{}/Output_Final_NOC\".format(name), sample=(final_noc * 2) - 1, niter=niter) writer.add_scalar('L1-Loss', output[1].total_loss, niter) writer.add_scalar('NOC-Loss',",
"in enumerate(test_loader): for keys in batch: batch[keys] = batch[keys].float().cuda() output = self.seg_net(batch['image']) batch['image']",
"= 0 for idx in range(batch_size): if num[idx, 0] == 0: batch_size -=",
"if self.foreground: out_arr = output[1] else: out_arr = output output_arr = out_arr[pdx, :,",
"sample=((torch.softmax(foreground, 1)[:, 1:2, :, :] > 0.5).long() * 2) - 1, niter=niter) final_noc",
"class UnNormalize(object): def __init__(self, mean, std): self.mean = mean self.std = std def",
"std self.loss_tuple = recordclass('losses', ('total_loss', 'NOC_loss', 'background_loss', 'NOC_mse')) self.ply_start = '''ply format ascii",
"= self.seg_net(batch['image']) # if 'mask_image' in batch.keys(): # masked_output = output * (batch['mask_image']",
"torchstat import stat from math import log10 from models.networks import * from utils.common",
"image = image.cpu().numpy().T image = image[:, [2, 1, 0]] * 255 output_arr =",
"== 0: self.lr *= 0.9 for param_group in self.optimizer.param_groups: param_group['lr'] = self.lr for",
"= os.path.join(\"../saves\", save_dir) if not os.path.exists(self.save_path): os.mkdir(self.save_path) self.batch_size = batch_size self.mean = mean",
"self.seg_net.apply(init_weights) # stat(model=self.seg_net, input_size=(3, 256, 256)) self.sparse_l1 = torch.nn.SmoothL1Loss(reduction='none') self.l1 = torch.nn.SmoothL1Loss() self.l2",
"target) # sub_batch = torch.sum(sub, dim=(1, 2, 3)) # sub_batch = sub_batch /",
"batch['yx_loc'][pdx, :num[pdx, 0], 1]] if self.foreground: out_arr = output[1] else: out_arr = output",
"total_loss += loss.item() niter = idx + (epoch * data_length) if idx %",
"float x property float y property float z property uchar red property uchar",
"exit(256) print(\"Using model {}.\".format(self.seg_net.__class__.__name__)) # self.seg_net.apply(init_weights) # stat(model=self.seg_net, input_size=(3, 256, 256)) self.sparse_l1 =",
"cv2.imwrite(os.path.join(ply_dir, 'Output_{}.png'.format(idx + pdx)), image.astype('uint8')) with open(os.path.join(ply_dir, 'Output_{}.ply'.format(idx + pdx)), 'w') as write_file:",
"enumerate(total_losses): total_losses[jdx] /= data_length print(\"Epoch: {} | Final Iteration: {} | Train Loss:",
"idx, ply_dir): batch_size = batch['num_points'].shape[0] idx = idx * self.batch_size # masked_output =",
"batch['noc_points'][pdx, :num[pdx, 0]].cpu().numpy() image = image.cpu().numpy().T image = image[:, [2, 1, 0]] *",
"1)[:, 1:2, :, :] > 0.5).float() write_image(writer, name=\"{}/Output_Final_NOC\".format(name), sample=(final_noc * 2) - 1,",
"x property float y property float z property uchar red property uchar green",
"'Output_{}.png'.format(idx + pdx)), image.astype('uint8')) with open(os.path.join(ply_dir, 'Output_{}.ply'.format(idx + pdx)), 'w') as write_file: write_file.write(start)",
"0.5, 0.5), std=(0.5, 0.5, 0.5), num_downs=5, lr=2e-4, betas=(0.5, 0.999), batch_size=8, checkpoint=None, model_type='res', output_heads='two'):",
"self.sparse_l1 = torch.nn.SmoothL1Loss(reduction='none') self.l1 = torch.nn.SmoothL1Loss() self.l2 = torch.nn.MSELoss() self.bce = torch.nn.BCEWithLogitsLoss() self.seg_net.cuda()",
"* batch['mask_image'] # # loss = self.criterion_l1(output=masked_output, batch=batch) # l1_loss = self.loss_l1(masked_output, batch['noc_image'])",
"concatenated_out, fmt=' '.join(['%0.8f'] * 3 + ['%d'] * 3)) with open(os.path.join(ply_dir, 'Ground_truth_{}.ply'.format(idx +",
"sub = self.sparse_l1(output, target) # sub_batch = torch.sum(sub, dim=(1, 2, 3)) # sub_batch",
"self.seg_net = ResUnet2HeadGenerator(output_nc=3, last_layer=nn.ReLU()) # self.seg_net = Unet2HeadGenerator(input_nc=3, output_nc=3, num_downs=num_downs, # use_dropout=False, norm_layer=torch.nn.BatchNorm2d,",
"0) * 255 cv2.imwrite(os.path.join(ply_dir, 'Output_{}.png'.format(idx + pdx)), image.astype('uint8')) with open(os.path.join(ply_dir, 'Output_{}.ply'.format(idx + pdx)),",
"batch=batch, output=(output, total_losses), name=\"Validation\", niter=niter, foreground=self.foreground) def test(self, test_loader, niter, test_writer): with torch.no_grad():",
"(batch['mask_image'] > 0).float() noc_loss = self.criterion_l1_sparse(output=output, batch=batch) total_loss += noc_loss * 10 #",
"+ pdx)), image.astype('uint8')) with open(os.path.join(ply_dir, 'Output_{}.ply'.format(idx + pdx)), 'w') as write_file: write_file.write(start) np.savetxt(write_file,",
"# stat(model=self.seg_net, input_size=(3, 256, 256)) self.sparse_l1 = torch.nn.SmoothL1Loss(reduction='none') self.l1 = torch.nn.SmoothL1Loss() self.l2 =",
"test_writer=writer.validate, niter=(epoch + 1) * data_length + 1) print(\"*\" * 100) if __name__",
"total_loss += noc_loss * 10 # loss = self.l1(masked_output, batch['noc_image']) background_target = torch.zeros_like(output)",
"self.mean = mean self.std = std def __call__(self, tensor): \"\"\" Args: tensor (Tensor):",
"# masked_output = output[1] * (batch['mask_image'] > 0).float() batch['num_points'] = batch['num_points'].long() num =",
"torch.no_grad(): self.seg_net.eval() for idx, batch in enumerate(test_loader): for keys in batch: batch[keys] =",
"= batch['num_points'].long() num = batch['num_points'].view(batch_size, 1) batch['yx_loc'] = batch['yx_loc'].long() sub = 0 for",
"idx=idx, ply_dir=ply_dir) for jdx, val in enumerate(losses): if jdx is 3: total_losses[jdx] +=",
"+= noc_loss * 10 # loss = self.l1(masked_output, batch['noc_image']) background_target = torch.zeros_like(output) background_loss",
"idx = idx * self.batch_size # masked_output = output[1] * (batch['mask_image'] > 0).float()",
"masked_output = output[1] * (batch['mask_image'] > 0).float() batch['num_points'] = batch['num_points'].long() num = batch['num_points'].view(batch_size,",
"0], batch['yx_loc'][pdx, :num[pdx, 0], 1]] if self.foreground: out_arr = output[1] else: out_arr =",
"if not os.path.exists(ply_dir): os.mkdir(ply_dir) with torch.no_grad(): self.seg_net.eval() for idx, batch in enumerate(test_loader): for",
"idx + (epoch * data_length) if idx % opt.log_iter == 0: print(\"Epoch: {}",
"write_ply: if not os.path.exists(ply_dir): os.mkdir(ply_dir) with torch.no_grad(): self.seg_net.eval() for idx, batch in enumerate(test_loader):",
"test(self, test_loader, niter, test_writer): with torch.no_grad(): self.seg_net.eval() for idx, batch in enumerate(test_loader): for",
"# print(torch.max(((1 - batch['background'][:, 0:1, :, :]) > 0).float())) foreground = (1 -",
"write_ply=False, ply_dir=''): total_losses = self.loss_tuple(0, 0, 0, 0) if write_ply: if not os.path.exists(ply_dir):",
"in enumerate(total_losses): total_losses[jdx] /= len(test_loader) print(\"Validation loss: {}\".format(total_losses.total_loss)) # batch['image'] = self.un_norm(batch['image']) batch['image']",
"2 - 1 visualize(writer=writer.train, batch=batch, output=(output, losses), name=\"Train Total\", niter=niter, foreground=self.foreground) # batch['image']",
"NOC_loss=noc_loss, background_loss=background_loss, NOC_mse=mse) return output, losses def forward_2_heads(self, batch): total_loss = 0 output",
"1]], noc_points) return sub / batch_size def forward_sparse(self, batch): total_loss = 0 output",
"print(torch.max(((1 - batch['background'][:, 0:1, :, :]) > 0).float())) foreground = (1 - batch['background'][:,",
"image.cpu().numpy().T image = image[:, [2, 1, 0]] * 255 output_arr = output_arr.cpu().numpy().T start",
"foreground = output[0][0] write_image(writer, name=\"{}/Ground Truth Foreground\".format(name), sample=((1 - batch['background']).long() * 2 -",
":num[idx, 0], :] noc_points = torch.transpose(noc_points, 0, 1) sub += self.l2(output[idx, :, batch['yx_loc'][idx,",
"start = self.ply_start.format(num[pdx, 0].item()) concatenated_out = np.concatenate((output_arr, image), axis=1) concatenated_gt = np.concatenate((noc_gt, image),",
"losses = self.forward(batch=batch) # View NOC as PLY if write_ply: self.write_noc_ply(output=output, batch=batch, idx=idx,",
"0 and epoch % 15 == 0: self.lr *= 0.9 for param_group in",
"torch.sum(batch['num_points'])) for jdx, val in enumerate(losses): if jdx is 3: total_losses[jdx] += 10",
"batch=batch, output=(output, total_losses), # name=\"Train Total\", niter=(epoch + 1) * data_length) # self.test(test_loader=data_loader.test,",
"from torchstat import stat from math import log10 from models.networks import * from",
"- 1, niter=niter) final_noc = output_image * (torch.softmax(output[0][0], 1)[:, 1:2, :, :] >",
"> 0).float())) foreground = (1 - batch['background'][:, 0:2, :, :]).float() foreground[:, 0, :,",
"= (1 - batch['background'][:, 0:2, :, :]).float() foreground[:, 0, :, :] = batch['background'][:,",
"0, 0) data_length = len(data_loader.train) self.seg_net.train() if epoch > 0 and epoch %",
"log10 from models.networks import * from utils.common import * def visualize(batch, output, writer,",
"View NOC as PLY if write_ply: self.write_noc_ply(output=output, batch=batch, idx=idx, ply_dir=ply_dir) for jdx, val",
"(C, H, W) to be normalized. Returns: Tensor: Normalized image. \"\"\" for t,",
"> 0).float() noc_loss = self.criterion_l1_sparse(output=output[1], batch=batch) total_loss += noc_loss * 70 # print(torch.max(((1",
"* from utils.common import * def visualize(batch, output, writer, name, niter, foreground=False, test=False):",
"Foreground\".format(name), sample=((1 - batch['background']).long() * 2 - 1), niter=niter) write_image(writer, name=\"{}/Output_Foreground\".format(name), sample=((torch.softmax(foreground, 1)[:,",
"last_layer=nn.ReLU()) # self.seg_net = UnetGenerator(input_nc=3, output_nc=3, num_downs=num_downs, # use_dropout=False, norm_layer=torch.nn.BatchNorm2d, # last_layer=nn.LeakyReLU(0.2)) self.foreground",
"noc_loss = self.criterion_l1_sparse(output=output, batch=batch) total_loss += noc_loss * 10 # loss = self.l1(masked_output,",
"output, batch, idx, ply_dir): batch_size = batch['num_points'].shape[0] idx = idx * self.batch_size #",
"self.seg_net(batch['image']) # # # if 'mask_image' in batch.keys(): # masked_output = output *",
"+= losses[jdx].item() # total_losses.total_loss += losses.total_loss.item() if idx == (len(test_loader) - 1): #",
"/ ( # torch.sum(batch['num_points']) + 1 * (torch.sum(batch['num_points'] == 0).float())) # self.optimizer.zero_grad() losses.total_loss.backward()",
"validate(self, test_loader, niter, test_writer, write_ply=False, ply_dir=''): total_losses = self.loss_tuple(0, 0, 0, 0) if",
":num[pdx, 0], 1]] noc_gt = batch['noc_points'][pdx, :num[pdx, 0]].cpu().numpy() image = image.cpu().numpy().T image =",
"sub_batch / (num_points * 3) batch['num_points'] = batch['num_points'].long() num = batch['num_points'].view(batch_size, 1) batch['yx_loc']",
"256, 256)) self.sparse_l1 = torch.nn.SmoothL1Loss(reduction='none') self.l1 = torch.nn.SmoothL1Loss() self.l2 = torch.nn.MSELoss() self.bce =",
"= batch['background'][:, 0, :, :] background_loss = self.bce(input=output[0], target=foreground) total_loss += background_loss mse",
"name, niter, foreground=False, test=False): output_image = output[0] if foreground: output_image = output[0][1] foreground",
"= self.criterion_l1_sparse(output=output[1], batch=batch) total_loss += noc_loss * 70 # print(torch.max(((1 - batch['background'][:, 0:1,",
"batch['image'] = self.un_norm(batch['image']) # visualize(writer=writer.train, batch=batch, output=(output, loss), # name=\"Train\", niter=niter) # Last",
"val in enumerate(total_losses): total_losses[jdx] /= data_length print(\"Epoch: {} | Final Iteration: {} |",
"1:2, :, :] > 0.5).float() write_image(writer, name=\"{}/Output_Final_NOC\".format(name), sample=(final_noc * 2) - 1, niter=niter)",
"1 visualize(writer=writer.train, batch=batch, output=(output, losses), name=\"Train Total\", niter=niter, foreground=self.foreground) # batch['image'] = self.un_norm(batch['image'])",
"output, batch): batch_size = batch['num_points'].shape[0] batch['num_points'] = batch['num_points'].long() num = batch['num_points'].view(batch_size, 1) batch['yx_loc']",
"import recordclass from torchstat import stat from math import log10 from models.networks import",
"= 1 # sub = torch.abs(output - target) # sub = self.sparse_l1(output, target)",
"= self.ply_start.format(num[pdx, 0].item()) concatenated_out = np.concatenate((output_arr, image), axis=1) concatenated_gt = np.concatenate((noc_gt, image), axis=1)",
"(torch.softmax(output[0][0], 1)[:, 1:2, :, :] > 0.5).float() write_image(writer, name=\"{}/Output_Final_NOC\".format(name), sample=(final_noc * 2) -",
"fmt=' '.join(['%0.8f'] * 3 + ['%d'] * 3)) def validate(self, test_loader, niter, test_writer,",
"(len(test_loader) - 1): # print(len(test_loader)) for jdx, val in enumerate(total_losses): total_losses[jdx] /= len(test_loader)",
"losses.total_loss.item() if idx == (len(test_loader) - 1): # print(len(test_loader)) for jdx, val in",
"jdx is 3: total_losses[jdx] += 10 * log10(1 / losses[jdx].item()) else: total_losses[jdx] +=",
"keys in batch: batch[keys] = batch[keys].float().cuda() output = self.seg_net(batch['image']) batch['image'] = batch['image'] *",
":, batch['yx_loc'][pdx, :num[pdx, 0], 0], batch['yx_loc'][pdx, :num[pdx, 0], 1]] if self.foreground: out_arr =",
"return tensor class TrainNOCs: def __init__(self, save_dir='Trial', mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5),",
"+ ['%d'] * 3)) with open(os.path.join(ply_dir, 'Ground_truth_{}.ply'.format(idx + pdx)), 'w') as write_file: write_file.write(start)",
"axis=1) concatenated_gt = np.concatenate((noc_gt, image), axis=1) image = batch['image'][pdx, :, :, :].cpu().numpy() image",
"+ pdx)), 'w') as write_file: write_file.write(start) np.savetxt(write_file, concatenated_gt, fmt=' '.join(['%0.8f'] * 3 +",
"- batch['background']).long() * 2 - 1), niter=niter) write_image(writer, name=\"{}/Output_Foreground\".format(name), sample=((torch.softmax(foreground, 1)[:, 1:2, :,",
"- 1): for jdx, val in enumerate(total_losses): total_losses[jdx] /= data_length print(\"Epoch: {} |",
"mean self.std = std def __call__(self, tensor): \"\"\" Args: tensor (Tensor): Tensor image",
"batch_size def forward_sparse(self, batch): total_loss = 0 output = self.seg_net(batch['image']) # if 'mask_image'",
"*= 0.9 for param_group in self.optimizer.param_groups: param_group['lr'] = self.lr for idx, batch in",
"output_image = output[0] if foreground: output_image = output[0][1] foreground = output[0][0] write_image(writer, name=\"{}/Ground",
"+= background_loss mse = self.criterion_mse(output=output, batch=batch) losses = self.loss_tuple(total_loss=total_loss, NOC_loss=noc_loss, background_loss=background_loss, NOC_mse=mse) return",
"Normalized image. \"\"\" for t, m, s in zip(tensor, self.mean, self.std): t.mul_(s).add_(m) #",
"batch['background'][:, 0:1, :, :]) > 0).float())) foreground = (1 - batch['background'][:, 0:2, :,",
"batch['image'] * 2 - 1 test_writer.add_scalar('PSNR', total_losses.NOC_mse, niter) visualize(writer=test_writer, batch=batch, output=(output, total_losses), name=\"Validation\",",
"# sub = self.sparse_l1(output, target) # sub_batch = torch.sum(sub, dim=(1, 2, 3)) #",
":, :] = batch['background'][:, 0, :, :] background_loss = self.bce(input=output[0], target=foreground) total_loss +=",
"print(batch['num_points'], torch.sum(batch['num_points'])) for jdx, val in enumerate(losses): if jdx is 3: total_losses[jdx] +=",
"output_arr = out_arr[pdx, :, batch['yx_loc'][pdx, :num[pdx, 0], 0], batch['yx_loc'][pdx, :num[pdx, 0], 1]] noc_gt",
"for idx, batch in enumerate(test_loader): for keys in batch: batch[keys] = batch[keys].float().cuda() output,",
"0]] * 255 output_arr = output_arr.cpu().numpy().T start = self.ply_start.format(num[pdx, 0].item()) concatenated_out = np.concatenate((output_arr,",
"batch in enumerate(data_loader.train): for keys in batch: batch[keys] = batch[keys].float().cuda() # batch['image'] =",
"write_image(writer, name=\"{}/Ground Truth NOC\".format(name), sample=batch['noc_image'], niter=niter) return True class UnNormalize(object): def __init__(self, mean,",
"1) * data_length + 1) print(\"*\" * 100) if __name__ == \"__main__\": noc_class",
"2) - 1, niter=niter) write_image(writer, name=\"{}/Input\".format(name), sample=batch['image'], niter=niter) if not test: write_image(writer, name=\"{}/Ground",
"self.batch_size = batch_size self.mean = mean self.std = std self.loss_tuple = recordclass('losses', ('total_loss',",
"self.bce = torch.nn.BCEWithLogitsLoss() self.seg_net.cuda() self.sparse_l1.cuda() self.l1.cuda() self.bce.cuda() self.seg_net.train() self.criterion_selection = None self.lr =",
"param_group['lr'] = self.lr for idx, batch in enumerate(data_loader.train): for keys in batch: batch[keys]",
"total_loss = 0 output = self.seg_net(batch['image']) # masked_output = output[1] * (batch['mask_image'] >",
"total_losses[jdx] /= data_length print(\"Epoch: {} | Final Iteration: {} | Train Loss: {}\".format(epoch,",
"self.seg_net.load_state_dict(checkpoint['model']) self.optimizer.load_state_dict(checkpoint['optimizer']) self.save_path = os.path.join(\"../saves\", save_dir) if not os.path.exists(self.save_path): os.mkdir(self.save_path) self.batch_size = batch_size",
"self.seg_net.train() if epoch > 0 and epoch % 15 == 0: self.lr *=",
"data_length) # self.test(test_loader=data_loader.test, test_writer=writer.test, niter=(epoch + 1) * data_length) self.validate(test_loader=data_loader.validate, test_writer=writer.validate, niter=(epoch +",
"betas=(0.5, 0.999), batch_size=8, checkpoint=None, model_type='res', output_heads='two'): if output_heads == 'one': self.forward = self.forward_sparse",
"* 3) batch['num_points'] = batch['num_points'].long() num = batch['num_points'].view(batch_size, 1) batch['yx_loc'] = batch['yx_loc'].long() sub",
"write_image(writer, name=\"{}/Output_Foreground\".format(name), sample=((torch.softmax(foreground, 1)[:, 1:2, :, :] > 0.5).long() * 2) - 1,",
"torch.optim.SGD(params=self.seg_net.parameters(), lr=lr, momentum=0.5) if checkpoint is not None: checkpoint = torch.load(checkpoint) self.seg_net.load_state_dict(checkpoint['model']) self.optimizer.load_state_dict(checkpoint['optimizer'])",
"self.ply_start.format(num[pdx, 0].item()) concatenated_out = np.concatenate((output_arr, image), axis=1) concatenated_gt = np.concatenate((noc_gt, image), axis=1) image",
"+ pdx)), 'w') as write_file: write_file.write(start) np.savetxt(write_file, concatenated_out, fmt=' '.join(['%0.8f'] * 3 +",
"* 2 - 1 visualize(writer=writer.train, batch=batch, output=(output, losses), name=\"Train Total\", niter=niter, foreground=self.foreground) #",
":] noc_points = torch.transpose(noc_points, 0, 1) sub += self.l2(output[idx, :, batch['yx_loc'][idx, :num[idx, 0],",
"num_points[num_points == 0] = 1 # sub = torch.abs(output - target) # sub",
"'mask_image' in batch.keys(): # masked_output = output * (batch['mask_image'] > 0).float() noc_loss =",
"= batch['yx_loc'].long() sub = 0 for idx in range(batch_size): if num[idx, 0] ==",
"model_type == 'res_unet': self.seg_net = ResUnetGenerator(output_nc=3, last_layer=nn.ReLU()) # self.seg_net = UnetGenerator(input_nc=3, output_nc=3, num_downs=num_downs,",
"= lr self.optimizer = torch.optim.Adam(params=self.seg_net.parameters(), lr=lr, betas=betas) # self.optimizer = torch.optim.SGD(params=self.seg_net.parameters(), lr=lr, momentum=0.5)",
"= output[1] else: out_arr = output output_arr = out_arr[pdx, :, batch['yx_loc'][pdx, :num[pdx, 0],",
"batch: batch[keys] = batch[keys].float().cuda() output, losses = self.forward(batch=batch) # View NOC as PLY",
"* 3 + ['%d'] * 3)) def validate(self, test_loader, niter, test_writer, write_ply=False, ply_dir=''):",
"# print(batch['num_points'], torch.sum(batch['num_points'])) for jdx, val in enumerate(losses): if jdx is 3: total_losses[jdx]",
"self.test(test_loader=data_loader.test, test_writer=writer.test, niter=(epoch + 1) * data_length) self.validate(test_loader=data_loader.validate, test_writer=writer.validate, niter=(epoch + 1) *",
"-= 1 continue noc_points = batch['noc_points'][idx, :num[idx, 0], :] noc_points = torch.transpose(noc_points, 0,",
"write_file: write_file.write(start) np.savetxt(write_file, concatenated_out, fmt=' '.join(['%0.8f'] * 3 + ['%d'] * 3)) with",
"as PLY if write_ply: self.write_noc_ply(output=output, batch=batch, idx=idx, ply_dir=ply_dir) for jdx, val in enumerate(losses):",
"test_writer): with torch.no_grad(): self.seg_net.eval() for idx, batch in enumerate(test_loader): for keys in batch:",
"= torch.load(checkpoint) self.seg_net.load_state_dict(checkpoint['model']) self.optimizer.load_state_dict(checkpoint['optimizer']) self.save_path = os.path.join(\"../saves\", save_dir) if not os.path.exists(self.save_path): os.mkdir(self.save_path) self.batch_size",
"if idx == (data_length - 1): for jdx, val in enumerate(total_losses): total_losses[jdx] /=",
"* data_length + 1) print(\"*\" * 100) if __name__ == \"__main__\": noc_class =",
"self.mean, self.std): t.mul_(s).add_(m) # The normalize code -> t.sub_(m).div_(s) return tensor class TrainNOCs:",
"output_nc=3, num_downs=num_downs, # use_dropout=False, norm_layer=torch.nn.BatchNorm2d, # last_layer=nn.LeakyReLU(0.2)) self.foreground = False elif output_heads ==",
"Last Iteration if idx == (data_length - 1): for jdx, val in enumerate(total_losses):",
"== (len(test_loader) - 1): # print(len(test_loader)) for jdx, val in enumerate(total_losses): total_losses[jdx] /=",
"batch[keys].float().cuda() output = self.seg_net(batch['image']) batch['image'] = batch['image'] * 2 - 1 visualize(writer=test_writer, batch=batch,",
"epoch, 'model': self.seg_net.state_dict(), 'optimizer': self.optimizer.state_dict()}, os.path.join(self.save_path, 'save_{}.pth'.format(niter))) # visualize(writer=writer.train, batch=batch, output=(output, total_losses), #",
"self.lr = lr self.optimizer = torch.optim.Adam(params=self.seg_net.parameters(), lr=lr, betas=betas) # self.optimizer = torch.optim.SGD(params=self.seg_net.parameters(), lr=lr,",
"os.path.join(self.save_path, 'save_{}.pth'.format(niter))) # visualize(writer=writer.train, batch=batch, output=(output, total_losses), # name=\"Train Total\", niter=(epoch + 1)",
":num[idx, 0], 1]], noc_points) return sub / batch_size def forward_sparse(self, batch): total_loss =",
"TrainNOCs: def __init__(self, save_dir='Trial', mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), num_downs=5, lr=2e-4, betas=(0.5,",
"total_losses[jdx] += 10 * log10(1 / losses[jdx].item()) else: total_losses[jdx] += losses[jdx].item() # total_losses.total_loss",
"write_file.write(start) np.savetxt(write_file, concatenated_gt, fmt=' '.join(['%0.8f'] * 3 + ['%d'] * 3)) def validate(self,",
"1) * data_length) self.validate(test_loader=data_loader.validate, test_writer=writer.validate, niter=(epoch + 1) * data_length + 1) print(\"*\"",
":] background_loss = self.bce(input=output[0], target=foreground) total_loss += background_loss mse = self.criterion_mse(output=output[1], batch=batch) losses",
"1]], noc_points) return sub / batch_size def criterion_l1_sparse(self, output, batch): batch_size = batch['num_points'].shape[0]",
"= self.seg_net(batch['image']) batch['image'] = batch['image'] * 2 - 1 visualize(writer=test_writer, batch=batch, output=(output, self.loss_tuple(0,",
"= self.sparse_l1(output, target) # sub_batch = torch.sum(sub, dim=(1, 2, 3)) # sub_batch =",
":]).float() foreground[:, 0, :, :] = batch['background'][:, 0, :, :] background_loss = self.bce(input=output[0],",
"= batch['image'][pdx, :, :, :].cpu().numpy() image = image.transpose(1, 2, 0) * 255 cv2.imwrite(os.path.join(ply_dir,",
"batch=batch) losses = self.loss_tuple(total_loss=total_loss, NOC_loss=noc_loss, background_loss=background_loss, NOC_mse=mse) return output, losses def forward_2_heads(self, batch):",
"return output, losses def forward_2_heads(self, batch): total_loss = 0 output = self.seg_net(batch['image']) #",
"batch=batch) total_loss += noc_loss * 10 # loss = self.l1(masked_output, batch['noc_image']) background_target =",
"total_losses = self.loss_tuple(0, 0, 0, 0) if write_ply: if not os.path.exists(ply_dir): os.mkdir(ply_dir) with",
"name=\"Train Total\", niter=(epoch + 1) * data_length) # self.test(test_loader=data_loader.test, test_writer=writer.test, niter=(epoch + 1)",
"# masked_output = output * batch['mask_image'] # # loss = self.criterion_l1(output=masked_output, batch=batch) #",
"name=\"{}/Ground Truth Foreground\".format(name), sample=((1 - batch['background']).long() * 2 - 1), niter=niter) write_image(writer, name=\"{}/Output_Foreground\".format(name),",
"heads!\") exit(256) print(\"Using model {}.\".format(self.seg_net.__class__.__name__)) # self.seg_net.apply(init_weights) # stat(model=self.seg_net, input_size=(3, 256, 256)) self.sparse_l1",
"0).float())) foreground = (1 - batch['background'][:, 0:2, :, :]).float() foreground[:, 0, :, :]",
"= batch['image'] * 2 - 1 output, losses = self.train(batch=batch) # print(batch['num_points'], torch.sum(batch['num_points']))",
"visualize(batch, output, writer, name, niter, foreground=False, test=False): output_image = output[0] if foreground: output_image",
"in self.optimizer.param_groups: param_group['lr'] = self.lr for idx, batch in enumerate(data_loader.train): for keys in",
"if idx == (len(test_loader) - 1): # print(len(test_loader)) for jdx, val in enumerate(total_losses):",
"print(\"Epoch: {} | Iteration: {} | Train Loss: {}\".format(epoch, niter, losses.total_loss.item())) batch['image'] =",
"# torch.sum(batch['num_points']) + 1 * (torch.sum(batch['num_points'] == 0).float())) # self.optimizer.zero_grad() losses.total_loss.backward() self.optimizer.step() return",
"== 0).float())) # self.optimizer.zero_grad() losses.total_loss.backward() self.optimizer.step() return output, losses def write_noc_ply(self, output, batch,",
"batch['image'] * 2 - 1 visualize(writer=test_writer, batch=batch, output=(output, self.loss_tuple(0, 0, 0, 0)), name=\"Validation\",",
"0, :, :] = batch['background'][:, 0, :, :] background_loss = self.bce(input=output[0], target=foreground) total_loss",
"output_arr.cpu().numpy().T start = self.ply_start.format(num[pdx, 0].item()) concatenated_out = np.concatenate((output_arr, image), axis=1) concatenated_gt = np.concatenate((noc_gt,",
"batch['image'] = batch['image'] * 2 - 1 output, losses = self.train(batch=batch) # print(batch['num_points'],",
"{} | Train Loss: {}\".format(epoch, niter, losses.total_loss.item())) batch['image'] = batch['image'] * 2 -",
"* data_length) self.validate(test_loader=data_loader.validate, test_writer=writer.validate, niter=(epoch + 1) * data_length + 1) print(\"*\" *",
"self.optimizer.step() return output, losses def write_noc_ply(self, output, batch, idx, ply_dir): batch_size = batch['num_points'].shape[0]",
"0], 0], batch['yx_loc'][pdx, :num[pdx, 0], 1]] noc_gt = batch['noc_points'][pdx, :num[pdx, 0]].cpu().numpy() image =",
"sub / batch_size def criterion_l1_sparse(self, output, batch): batch_size = batch['num_points'].shape[0] # num_points[num_points ==",
"\"\"\" Train NOC class \"\"\" import os import cv2 from recordclass import recordclass",
"1:2, :, :] > 0.5).long() * 2) - 1, niter=niter) final_noc = output_image",
"losses = self.loss_tuple(total_loss=total_loss, NOC_loss=noc_loss, background_loss=background_loss, NOC_mse=mse) return output, losses def train(self, batch): output,",
"image = image[:, [2, 1, 0]] * 255 output_arr = output_arr.cpu().numpy().T start =",
"not os.path.exists(ply_dir): os.mkdir(ply_dir) with torch.no_grad(): self.seg_net.eval() for idx, batch in enumerate(test_loader): for keys",
"batch in enumerate(test_loader): for keys in batch: batch[keys] = batch[keys].float().cuda() output, losses =",
"1): # print(len(test_loader)) for jdx, val in enumerate(total_losses): total_losses[jdx] /= len(test_loader) print(\"Validation loss:",
"| Train Loss: {}\".format(epoch, niter, losses.total_loss.item())) batch['image'] = batch['image'] * 2 - 1",
"= output[0][0] write_image(writer, name=\"{}/Ground Truth Foreground\".format(name), sample=((1 - batch['background']).long() * 2 - 1),",
"None: checkpoint = torch.load(checkpoint) self.seg_net.load_state_dict(checkpoint['model']) self.optimizer.load_state_dict(checkpoint['optimizer']) self.save_path = os.path.join(\"../saves\", save_dir) if not os.path.exists(self.save_path):",
"batch=batch) total_loss += noc_loss * 70 # print(torch.max(((1 - batch['background'][:, 0:1, :, :])",
"0) data_length = len(data_loader.train) self.seg_net.train() if epoch > 0 and epoch % 15",
"output * (batch['mask_image'] > 0).float() noc_loss = self.criterion_l1_sparse(output=output, batch=batch) total_loss += noc_loss *",
"= image.transpose(1, 2, 0) * 255 cv2.imwrite(os.path.join(ply_dir, 'Output_{}.png'.format(idx + pdx)), image.astype('uint8')) with open(os.path.join(ply_dir,",
"niter, test_writer, write_ply=False, ply_dir=''): total_losses = self.loss_tuple(0, 0, 0, 0) if write_ply: if",
"{} property float x property float y property float z property uchar red",
"batch[keys] = batch[keys].float().cuda() output = self.seg_net(batch['image']) batch['image'] = batch['image'] * 2 - 1",
"+ 1) * data_length) # self.test(test_loader=data_loader.test, test_writer=writer.test, niter=(epoch + 1) * data_length) self.validate(test_loader=data_loader.validate,",
"* batch['background'], background_target) total_loss += background_loss mse = self.criterion_mse(output=output, batch=batch) losses = self.loss_tuple(total_loss=total_loss,",
"self.un_norm(batch['image']) batch['image'] = batch['image'] * 2 - 1 test_writer.add_scalar('PSNR', total_losses.NOC_mse, niter) visualize(writer=test_writer, batch=batch,",
"noc_points) return sub / batch_size def forward_sparse(self, batch): total_loss = 0 output =",
"1)[:, 1:2, :, :] > 0.5).long() * 2) - 1, niter=niter) final_noc =",
"# total_loss += loss.item() niter = idx + (epoch * data_length) if idx",
"as write_file: write_file.write(start) np.savetxt(write_file, concatenated_out, fmt=' '.join(['%0.8f'] * 3 + ['%d'] * 3))",
"niter=(epoch + 1) * data_length + 1) print(\"*\" * 100) if __name__ ==",
"output=(output, total_losses), # name=\"Train Total\", niter=(epoch + 1) * data_length) # self.test(test_loader=data_loader.test, test_writer=writer.test,",
"= self.loss_tuple(0, 0, 0, 0) data_length = len(data_loader.train) self.seg_net.train() if epoch > 0",
"sample=(output_image * 2) - 1, niter=niter) write_image(writer, name=\"{}/Input\".format(name), sample=batch['image'], niter=niter) if not test:",
"foreground=self.foreground) def test(self, test_loader, niter, test_writer): with torch.no_grad(): self.seg_net.eval() for idx, batch in",
"models.networks import * from utils.common import * def visualize(batch, output, writer, name, niter,",
"self.criterion_l1(output=masked_output, batch=batch) # l1_loss = self.loss_l1(masked_output, batch['noc_image']) / ( # torch.sum(batch['num_points']) + 1",
"Loss: {}\".format(epoch, niter, losses.total_loss.item())) batch['image'] = batch['image'] * 2 - 1 visualize(writer=writer.train, batch=batch,",
"np.concatenate((output_arr, image), axis=1) concatenated_gt = np.concatenate((noc_gt, image), axis=1) image = batch['image'][pdx, :, :,",
"= np.concatenate((output_arr, image), axis=1) concatenated_gt = np.concatenate((noc_gt, image), axis=1) image = batch['image'][pdx, :,",
"= ResUnetGenerator(output_nc=3, last_layer=nn.ReLU()) # self.seg_net = UnetGenerator(input_nc=3, output_nc=3, num_downs=num_downs, # use_dropout=False, norm_layer=torch.nn.BatchNorm2d, #",
"sub = torch.abs(output - target) # sub = self.sparse_l1(output, target) # sub_batch =",
"masked_output = output * batch['mask_image'] # # loss = self.criterion_l1(output=masked_output, batch=batch) # l1_loss",
"self.seg_net.eval() for idx, batch in enumerate(test_loader): for keys in batch: batch[keys] = batch[keys].float().cuda()",
"{}\".format(total_losses.total_loss)) # batch['image'] = self.un_norm(batch['image']) batch['image'] = batch['image'] * 2 - 1 test_writer.add_scalar('PSNR',",
"name=\"{}/Input\".format(name), sample=batch['image'], niter=niter) if not test: write_image(writer, name=\"{}/Ground Truth NOC\".format(name), sample=batch['noc_image'], niter=niter) return",
"= batch[keys].float().cuda() # batch['image'] = batch['image'] * 2 - 1 output, losses =",
"self.loss_l1(masked_output, batch['noc_image']) / ( # torch.sum(batch['num_points']) + 1 * (torch.sum(batch['num_points'] == 0).float())) #",
"* 2) - 1, niter=niter) writer.add_scalar('L1-Loss', output[1].total_loss, niter) writer.add_scalar('NOC-Loss', output[1].NOC_loss, niter) writer.add_scalar('Background-Loss', output[1].background_loss,",
"losses = self.loss_tuple(total_loss=total_loss, NOC_loss=noc_loss, background_loss=background_loss, NOC_mse=mse) return output, losses def forward_2_heads(self, batch): total_loss",
"batch: batch[keys] = batch[keys].float().cuda() output = self.seg_net(batch['image']) batch['image'] = batch['image'] * 2 -",
"batch in enumerate(test_loader): for keys in batch: batch[keys] = batch[keys].float().cuda() output = self.seg_net(batch['image'])",
"= self.forward_sparse self.seg_net = ResNetGenerator(out_channels=3, last_layer=nn.ReLU()) if model_type == 'res_unet': self.seg_net = ResUnetGenerator(output_nc=3,",
"# visualize(writer=writer.train, batch=batch, output=(output, total_losses), # name=\"Train Total\", niter=(epoch + 1) * data_length)",
"* 70 # print(torch.max(((1 - batch['background'][:, 0:1, :, :]) > 0).float())) foreground =",
"in enumerate(total_losses): total_losses[jdx] /= data_length print(\"Epoch: {} | Final Iteration: {} | Train",
"ascii 1.0 element vertex {} property float x property float y property float",
"end_header\\n''' self.un_norm = UnNormalize(mean=self.mean, std=self.std) def criterion_mse(self, output, batch): batch_size = batch['num_points'].shape[0] batch['num_points']",
"model {}.\".format(self.seg_net.__class__.__name__)) # self.seg_net.apply(init_weights) # stat(model=self.seg_net, input_size=(3, 256, 256)) self.sparse_l1 = torch.nn.SmoothL1Loss(reduction='none') self.l1",
"output[1] * (batch['mask_image'] > 0).float() batch['num_points'] = batch['num_points'].long() num = batch['num_points'].view(batch_size, 1) for",
"enumerate(total_losses): total_losses[jdx] /= len(test_loader) print(\"Validation loss: {}\".format(total_losses.total_loss)) # batch['image'] = self.un_norm(batch['image']) batch['image'] =",
"last_layer=nn.LeakyReLU(0.2)) self.foreground = False elif output_heads == 'two': self.forward = self.forward_2_heads self.seg_net =",
"torch.optim.Adam(params=self.seg_net.parameters(), lr=lr, betas=betas) # self.optimizer = torch.optim.SGD(params=self.seg_net.parameters(), lr=lr, momentum=0.5) if checkpoint is not",
"test_writer.add_scalar('PSNR', total_losses.NOC_mse, niter) visualize(writer=test_writer, batch=batch, output=(output, total_losses), name=\"Validation\", niter=niter, foreground=self.foreground) def test(self, test_loader,",
"sample=(final_noc * 2) - 1, niter=niter) writer.add_scalar('L1-Loss', output[1].total_loss, niter) writer.add_scalar('NOC-Loss', output[1].NOC_loss, niter) writer.add_scalar('Background-Loss',",
"writer, epoch=0): total_losses = self.loss_tuple(0, 0, 0, 0) data_length = len(data_loader.train) self.seg_net.train() if",
"'background_loss', 'NOC_mse')) self.ply_start = '''ply format ascii 1.0 element vertex {} property float",
"name=\"{}/Output_NOC\".format(name), sample=(output_image * 2) - 1, niter=niter) write_image(writer, name=\"{}/Input\".format(name), sample=batch['image'], niter=niter) if not",
"0, 1) sub += self.l1(output[idx, :, batch['yx_loc'][idx, :num[idx, 0], 0], batch['yx_loc'][idx, :num[idx, 0],",
"+= losses[jdx].item() # total_loss += loss.item() niter = idx + (epoch * data_length)",
"# l1_loss = self.loss_l1(masked_output, batch['noc_image']) / ( # torch.sum(batch['num_points']) + 1 * (torch.sum(batch['num_points']",
"batch['mask_image'] # # loss = self.criterion_l1(output=masked_output, batch=batch) # l1_loss = self.loss_l1(masked_output, batch['noc_image']) /",
"self.l1(output * batch['background'], background_target) total_loss += background_loss mse = self.criterion_mse(output=output, batch=batch) losses =",
"print(\"Using model {}.\".format(self.seg_net.__class__.__name__)) # self.seg_net.apply(init_weights) # stat(model=self.seg_net, input_size=(3, 256, 256)) self.sparse_l1 = torch.nn.SmoothL1Loss(reduction='none')",
"= self.l1(masked_output, batch['noc_image']) background_target = torch.zeros_like(output) background_loss = self.l1(output * batch['background'], background_target) total_loss",
"= mean self.std = std def __call__(self, tensor): \"\"\" Args: tensor (Tensor): Tensor",
"of size (C, H, W) to be normalized. Returns: Tensor: Normalized image. \"\"\"",
"elif output_heads == 'two': self.forward = self.forward_2_heads self.seg_net = ResNet2HeadGenerator(out_channels=3, last_layer=nn.ReLU()) if model_type",
"float z property uchar red property uchar green property uchar blue end_header\\n''' self.un_norm",
"0], 0], batch['yx_loc'][idx, :num[idx, 0], 1]], noc_points) return sub / batch_size def forward_sparse(self,",
"* 255 cv2.imwrite(os.path.join(ply_dir, 'Output_{}.png'.format(idx + pdx)), image.astype('uint8')) with open(os.path.join(ply_dir, 'Output_{}.ply'.format(idx + pdx)), 'w')",
"3 + ['%d'] * 3)) def validate(self, test_loader, niter, test_writer, write_ply=False, ply_dir=''): total_losses",
"Iteration: {} | Train Loss: {}\".format(epoch, niter, total_losses.total_loss)) batch['image'] = batch['image'] * 2",
"'res_unet': self.seg_net = ResUnetGenerator(output_nc=3, last_layer=nn.ReLU()) # self.seg_net = UnetGenerator(input_nc=3, output_nc=3, num_downs=num_downs, # use_dropout=False,",
"0], 1]], noc_points) return sub / batch_size def forward_sparse(self, batch): total_loss = 0",
"'w') as write_file: write_file.write(start) np.savetxt(write_file, concatenated_gt, fmt=' '.join(['%0.8f'] * 3 + ['%d'] *",
"2 - 1), niter=niter) write_image(writer, name=\"{}/Output_Foreground\".format(name), sample=((torch.softmax(foreground, 1)[:, 1:2, :, :] > 0.5).long()",
":, :] > 0.5).long() * 2) - 1, niter=niter) final_noc = output_image *",
"self.std): t.mul_(s).add_(m) # The normalize code -> t.sub_(m).div_(s) return tensor class TrainNOCs: def",
"betas=betas) # self.optimizer = torch.optim.SGD(params=self.seg_net.parameters(), lr=lr, momentum=0.5) if checkpoint is not None: checkpoint",
"output = self.seg_net(batch['image']) # masked_output = output[1] * (batch['mask_image'] > 0).float() noc_loss =",
"batch['image'] = batch['image'] * 2 - 1 visualize(writer=test_writer, batch=batch, output=(output, self.loss_tuple(0, 0, 0,",
"ply_dir=ply_dir) for jdx, val in enumerate(losses): if jdx is 3: total_losses[jdx] += 10",
"batch['num_points'].shape[0] batch['num_points'] = batch['num_points'].long() num = batch['num_points'].view(batch_size, 1) batch['yx_loc'] = batch['yx_loc'].long() sub =",
"= batch['num_points'].shape[0] # num_points[num_points == 0] = 1 # sub = torch.abs(output -",
"batch: batch[keys] = batch[keys].float().cuda() # batch['image'] = batch['image'] * 2 - 1 output,",
"# masked_output = output[1] * (batch['mask_image'] > 0).float() noc_loss = self.criterion_l1_sparse(output=output[1], batch=batch) total_loss",
"1, 0]] * 255 output_arr = output_arr.cpu().numpy().T start = self.ply_start.format(num[pdx, 0].item()) concatenated_out =",
"batch_size = batch['num_points'].shape[0] idx = idx * self.batch_size # masked_output = output[1] *",
"Returns: Tensor: Normalized image. \"\"\" for t, m, s in zip(tensor, self.mean, self.std):",
"self.seg_net.train() self.criterion_selection = None self.lr = lr self.optimizer = torch.optim.Adam(params=self.seg_net.parameters(), lr=lr, betas=betas) #",
"if write_ply: self.write_noc_ply(output=output, batch=batch, idx=idx, ply_dir=ply_dir) for jdx, val in enumerate(losses): if jdx",
"if idx % opt.log_iter == 0: print(\"Epoch: {} | Iteration: {} | Train",
"in range(batch_size): if num[idx, 0] == 0: batch_size -= 1 continue noc_points =",
"number of heads!\") exit(256) print(\"Using model {}.\".format(self.seg_net.__class__.__name__)) # self.seg_net.apply(init_weights) # stat(model=self.seg_net, input_size=(3, 256,",
"0], :] noc_points = torch.transpose(noc_points, 0, 1) sub += self.l2(output[idx, :, batch['yx_loc'][idx, :num[idx,",
"checkpoint=None, model_type='res', output_heads='two'): if output_heads == 'one': self.forward = self.forward_sparse self.seg_net = ResNetGenerator(out_channels=3,",
"== 0] = 1 # sub = torch.abs(output - target) # sub =",
"'mask_image' in batch.keys(): # masked_output = output * batch['mask_image'] # # loss =",
"enumerate(test_loader): for keys in batch: batch[keys] = batch[keys].float().cuda() output, losses = self.forward(batch=batch) #",
"write_ply: self.write_noc_ply(output=output, batch=batch, idx=idx, ply_dir=ply_dir) for jdx, val in enumerate(losses): if jdx is",
"(data_length - 1): for jdx, val in enumerate(total_losses): total_losses[jdx] /= data_length print(\"Epoch: {}",
"output[1].total_loss, niter) writer.add_scalar('NOC-Loss', output[1].NOC_loss, niter) writer.add_scalar('Background-Loss', output[1].background_loss, niter) write_image(writer, name=\"{}/Output_NOC\".format(name), sample=(output_image * 2)",
"0], 1]] noc_gt = batch['noc_points'][pdx, :num[pdx, 0]].cpu().numpy() image = image.cpu().numpy().T image = image[:,",
"log10(1 / losses[jdx].item()) else: total_losses[jdx] += losses[jdx].item() # total_loss += loss.item() niter =",
"= self.train(batch=batch) # print(batch['num_points'], torch.sum(batch['num_points'])) for jdx, val in enumerate(losses): if jdx is",
"batch.keys(): # masked_output = output * (batch['mask_image'] > 0).float() noc_loss = self.criterion_l1_sparse(output=output, batch=batch)",
"0.5).long() * 2) - 1, niter=niter) final_noc = output_image * (torch.softmax(output[0][0], 1)[:, 1:2,",
"batch['yx_loc'] = batch['yx_loc'].long() sub = 0 for idx in range(batch_size): if num[idx, 0]",
"niter) writer.add_scalar('Background-Loss', output[1].background_loss, niter) write_image(writer, name=\"{}/Output_NOC\".format(name), sample=(output_image * 2) - 1, niter=niter) write_image(writer,",
"output = self.seg_net(batch['image']) # if 'mask_image' in batch.keys(): # masked_output = output *",
"background_target) total_loss += background_loss mse = self.criterion_mse(output=output, batch=batch) losses = self.loss_tuple(total_loss=total_loss, NOC_loss=noc_loss, background_loss=background_loss,",
"batch_size def criterion_l1_sparse(self, output, batch): batch_size = batch['num_points'].shape[0] # num_points[num_points == 0] =",
"out_arr = output[1] else: out_arr = output output_arr = out_arr[pdx, :, batch['yx_loc'][pdx, :num[pdx,",
"niter=niter) write_image(writer, name=\"{}/Input\".format(name), sample=batch['image'], niter=niter) if not test: write_image(writer, name=\"{}/Ground Truth NOC\".format(name), sample=batch['noc_image'],",
"H, W) to be normalized. Returns: Tensor: Normalized image. \"\"\" for t, m,",
"z property uchar red property uchar green property uchar blue end_header\\n''' self.un_norm =",
"# # loss = self.criterion_l1(output=masked_output, batch=batch) # l1_loss = self.loss_l1(masked_output, batch['noc_image']) / (",
"uchar blue end_header\\n''' self.un_norm = UnNormalize(mean=self.mean, std=self.std) def criterion_mse(self, output, batch): batch_size =",
"losses.total_loss.backward() self.optimizer.step() return output, losses def write_noc_ply(self, output, batch, idx, ply_dir): batch_size =",
"- 1 writer.train.add_scalar('PSNR', total_losses.NOC_mse, niter) torch.save({'epoch': epoch, 'model': self.seg_net.state_dict(), 'optimizer': self.optimizer.state_dict()}, os.path.join(self.save_path, 'save_{}.pth'.format(niter)))",
"image.transpose(1, 2, 0) * 255 cv2.imwrite(os.path.join(ply_dir, 'Output_{}.png'.format(idx + pdx)), image.astype('uint8')) with open(os.path.join(ply_dir, 'Output_{}.ply'.format(idx",
"concatenated_gt, fmt=' '.join(['%0.8f'] * 3 + ['%d'] * 3)) def validate(self, test_loader, niter,",
"masked_output = output * (batch['mask_image'] > 0).float() noc_loss = self.criterion_l1_sparse(output=output, batch=batch) total_loss +=",
"0).float() noc_loss = self.criterion_l1_sparse(output=output, batch=batch) total_loss += noc_loss * 10 # loss =",
"num_downs=num_downs, # use_dropout=False, norm_layer=torch.nn.BatchNorm2d, # last_layer=nn.LeakyReLU(0.2)) self.foreground = False elif output_heads == 'two':",
"output_heads == 'two': self.forward = self.forward_2_heads self.seg_net = ResNet2HeadGenerator(out_channels=3, last_layer=nn.ReLU()) if model_type ==",
"loss = self.l1(masked_output, batch['noc_image']) background_target = torch.zeros_like(output) background_loss = self.l1(output * batch['background'], background_target)",
"return output, losses def write_noc_ply(self, output, batch, idx, ply_dir): batch_size = batch['num_points'].shape[0] idx",
"Truth Foreground\".format(name), sample=((1 - batch['background']).long() * 2 - 1), niter=niter) write_image(writer, name=\"{}/Output_Foreground\".format(name), sample=((torch.softmax(foreground,",
"= 0 output = self.seg_net(batch['image']) # masked_output = output[1] * (batch['mask_image'] > 0).float()",
"['%d'] * 3)) with open(os.path.join(ply_dir, 'Ground_truth_{}.ply'.format(idx + pdx)), 'w') as write_file: write_file.write(start) np.savetxt(write_file,",
"batch['image'] = self.un_norm(batch['image']) batch['image'] = batch['image'] * 2 - 1 test_writer.add_scalar('PSNR', total_losses.NOC_mse, niter)",
"if num[idx, 0] == 0: batch_size -= 1 continue noc_points = batch['noc_points'][idx, :num[idx,",
"batch['noc_image']) background_target = torch.zeros_like(output) background_loss = self.l1(output * batch['background'], background_target) total_loss += background_loss",
"0 for idx in range(batch_size): if num[idx, 0] == 0: batch_size -= 1",
"\"\"\" import os import cv2 from recordclass import recordclass from torchstat import stat",
"test: write_image(writer, name=\"{}/Ground Truth NOC\".format(name), sample=batch['noc_image'], niter=niter) return True class UnNormalize(object): def __init__(self,",
"output, batch): batch_size = batch['num_points'].shape[0] # num_points[num_points == 0] = 1 # sub",
"def forward_2_heads(self, batch): total_loss = 0 output = self.seg_net(batch['image']) # masked_output = output[1]",
"foreground = (1 - batch['background'][:, 0:2, :, :]).float() foreground[:, 0, :, :] =",
"self.loss_tuple(total_loss=total_loss, NOC_loss=noc_loss, background_loss=background_loss, NOC_mse=mse) return output, losses def train(self, batch): output, losses =",
"+= losses.total_loss.item() if idx == (len(test_loader) - 1): # print(len(test_loader)) for jdx, val",
"= len(data_loader.train) self.seg_net.train() if epoch > 0 and epoch % 15 == 0:",
"idx * self.batch_size # masked_output = output[1] * (batch['mask_image'] > 0).float() batch['num_points'] =",
"self.loss_tuple(total_loss=total_loss, NOC_loss=noc_loss, background_loss=background_loss, NOC_mse=mse) return output, losses def forward_2_heads(self, batch): total_loss = 0",
"loss), # name=\"Train\", niter=niter) # Last Iteration if idx == (data_length - 1):",
"output_image * (torch.softmax(output[0][0], 1)[:, 1:2, :, :] > 0.5).float() write_image(writer, name=\"{}/Output_Final_NOC\".format(name), sample=(final_noc *",
"for t, m, s in zip(tensor, self.mean, self.std): t.mul_(s).add_(m) # The normalize code",
"in batch.keys(): # masked_output = output * batch['mask_image'] # # loss = self.criterion_l1(output=masked_output,",
"batch=batch, output=(output, self.loss_tuple(0, 0, 0, 0)), name=\"Validation\", niter=niter, foreground=self.foreground, test=True) def run(self, opt,",
"1) batch['yx_loc'] = batch['yx_loc'].long() sub = 0 for idx in range(batch_size): if num[idx,",
"num = batch['num_points'].view(batch_size, 1) for pdx in range(batch_size): image = batch['image'][pdx, :, batch['yx_loc'][pdx,",
"mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), num_downs=5, lr=2e-4, betas=(0.5, 0.999), batch_size=8, checkpoint=None, model_type='res',",
"Unknown number of heads!\") exit(256) print(\"Using model {}.\".format(self.seg_net.__class__.__name__)) # self.seg_net.apply(init_weights) # stat(model=self.seg_net, input_size=(3,",
"if model_type == 'res_unet': self.seg_net = ResUnet2HeadGenerator(output_nc=3, last_layer=nn.ReLU()) # self.seg_net = Unet2HeadGenerator(input_nc=3, output_nc=3,",
"self.optimizer = torch.optim.SGD(params=self.seg_net.parameters(), lr=lr, momentum=0.5) if checkpoint is not None: checkpoint = torch.load(checkpoint)",
"0], batch['yx_loc'][idx, :num[idx, 0], 1]], noc_points) return sub / batch_size def forward_sparse(self, batch):",
"with open(os.path.join(ply_dir, 'Output_{}.ply'.format(idx + pdx)), 'w') as write_file: write_file.write(start) np.savetxt(write_file, concatenated_out, fmt=' '.join(['%0.8f']",
"is not None: checkpoint = torch.load(checkpoint) self.seg_net.load_state_dict(checkpoint['model']) self.optimizer.load_state_dict(checkpoint['optimizer']) self.save_path = os.path.join(\"../saves\", save_dir) if",
"# if 'mask_image' in batch.keys(): # masked_output = output * batch['mask_image'] # #",
"opt.log_iter == 0: print(\"Epoch: {} | Iteration: {} | Train Loss: {}\".format(epoch, niter,",
"epoch=0): total_losses = self.loss_tuple(0, 0, 0, 0) data_length = len(data_loader.train) self.seg_net.train() if epoch",
"'two': self.forward = self.forward_2_heads self.seg_net = ResNet2HeadGenerator(out_channels=3, last_layer=nn.ReLU()) if model_type == 'res_unet': self.seg_net",
"not os.path.exists(self.save_path): os.mkdir(self.save_path) self.batch_size = batch_size self.mean = mean self.std = std self.loss_tuple",
"0.9 for param_group in self.optimizer.param_groups: param_group['lr'] = self.lr for idx, batch in enumerate(data_loader.train):",
"= torch.transpose(noc_points, 0, 1) sub += self.l1(output[idx, :, batch['yx_loc'][idx, :num[idx, 0], 0], batch['yx_loc'][idx,",
"> 0).float() batch['num_points'] = batch['num_points'].long() num = batch['num_points'].view(batch_size, 1) for pdx in range(batch_size):",
"1]] if self.foreground: out_arr = output[1] else: out_arr = output output_arr = out_arr[pdx,",
"idx == (len(test_loader) - 1): # print(len(test_loader)) for jdx, val in enumerate(total_losses): total_losses[jdx]",
"niter) writer.add_scalar('NOC-Loss', output[1].NOC_loss, niter) writer.add_scalar('Background-Loss', output[1].background_loss, niter) write_image(writer, name=\"{}/Output_NOC\".format(name), sample=(output_image * 2) -",
"use_dropout=False, norm_layer=torch.nn.BatchNorm2d, # last_layer=nn.ReLU()) self.foreground = True else: self.foreground = None print(\"Error! Unknown",
"== 'res_unet': self.seg_net = ResUnetGenerator(output_nc=3, last_layer=nn.ReLU()) # self.seg_net = UnetGenerator(input_nc=3, output_nc=3, num_downs=num_downs, #",
"self.sparse_l1.cuda() self.l1.cuda() self.bce.cuda() self.seg_net.train() self.criterion_selection = None self.lr = lr self.optimizer = torch.optim.Adam(params=self.seg_net.parameters(),",
"batch_size -= 1 continue noc_points = batch['noc_points'][idx, :num[idx, 0], :] noc_points = torch.transpose(noc_points,",
"0.5), num_downs=5, lr=2e-4, betas=(0.5, 0.999), batch_size=8, checkpoint=None, model_type='res', output_heads='two'): if output_heads == 'one':",
"None print(\"Error! Unknown number of heads!\") exit(256) print(\"Using model {}.\".format(self.seg_net.__class__.__name__)) # self.seg_net.apply(init_weights) #",
"noc_loss * 10 # loss = self.l1(masked_output, batch['noc_image']) background_target = torch.zeros_like(output) background_loss =",
"['%d'] * 3)) def validate(self, test_loader, niter, test_writer, write_ply=False, ply_dir=''): total_losses = self.loss_tuple(0,",
"sub / batch_size def forward_sparse(self, batch): total_loss = 0 output = self.seg_net(batch['image']) #",
"0, 0, 0) if write_ply: if not os.path.exists(ply_dir): os.mkdir(ply_dir) with torch.no_grad(): self.seg_net.eval() for",
"ResNetGenerator(out_channels=3, last_layer=nn.ReLU()) if model_type == 'res_unet': self.seg_net = ResUnetGenerator(output_nc=3, last_layer=nn.ReLU()) # self.seg_net =",
"visualize(writer=writer.train, batch=batch, output=(output, loss), # name=\"Train\", niter=niter) # Last Iteration if idx ==",
"'res_unet': self.seg_net = ResUnet2HeadGenerator(output_nc=3, last_layer=nn.ReLU()) # self.seg_net = Unet2HeadGenerator(input_nc=3, output_nc=3, num_downs=num_downs, # use_dropout=False,",
"lr=2e-4, betas=(0.5, 0.999), batch_size=8, checkpoint=None, model_type='res', output_heads='two'): if output_heads == 'one': self.forward =",
"(torch.sum(batch['num_points'] == 0).float())) # self.optimizer.zero_grad() losses.total_loss.backward() self.optimizer.step() return output, losses def write_noc_ply(self, output,",
"format ascii 1.0 element vertex {} property float x property float y property",
"sub = 0 for idx in range(batch_size): if num[idx, 0] == 0: batch_size",
"# batch['image'] = batch['image'] * 2 - 1 output, losses = self.train(batch=batch) #",
"losses[jdx].item() # total_losses.total_loss += losses.total_loss.item() if idx == (len(test_loader) - 1): # print(len(test_loader))",
"write_image(writer, name=\"{}/Ground Truth Foreground\".format(name), sample=((1 - batch['background']).long() * 2 - 1), niter=niter) write_image(writer,",
"train(self, batch): output, losses = self.forward(batch=batch) # output = self.seg_net(batch['image']) # # #",
":num[pdx, 0], 0], batch['yx_loc'][pdx, :num[pdx, 0], 1]] if self.foreground: out_arr = output[1] else:",
"= idx * self.batch_size # masked_output = output[1] * (batch['mask_image'] > 0).float() batch['num_points']",
"1 output, losses = self.train(batch=batch) # print(batch['num_points'], torch.sum(batch['num_points'])) for jdx, val in enumerate(losses):",
"torch.sum(batch['num_points']) + 1 * (torch.sum(batch['num_points'] == 0).float())) # self.optimizer.zero_grad() losses.total_loss.backward() self.optimizer.step() return output,",
"'''ply format ascii 1.0 element vertex {} property float x property float y",
"be normalized. Returns: Tensor: Normalized image. \"\"\" for t, m, s in zip(tensor,",
"tensor (Tensor): Tensor image of size (C, H, W) to be normalized. Returns:",
"= batch['num_points'].view(batch_size, 1) batch['yx_loc'] = batch['yx_loc'].long() sub = 0 for idx in range(batch_size):",
"mse = self.criterion_mse(output=output, batch=batch) losses = self.loss_tuple(total_loss=total_loss, NOC_loss=noc_loss, background_loss=background_loss, NOC_mse=mse) return output, losses",
"0] = 1 # sub = torch.abs(output - target) # sub = self.sparse_l1(output,",
"output[1] else: out_arr = output output_arr = out_arr[pdx, :, batch['yx_loc'][pdx, :num[pdx, 0], 0],",
"self.write_noc_ply(output=output, batch=batch, idx=idx, ply_dir=ply_dir) for jdx, val in enumerate(losses): if jdx is 3:",
"loss: {}\".format(total_losses.total_loss)) # batch['image'] = self.un_norm(batch['image']) batch['image'] = batch['image'] * 2 - 1",
"+= background_loss mse = self.criterion_mse(output=output[1], batch=batch) losses = self.loss_tuple(total_loss=total_loss, NOC_loss=noc_loss, background_loss=background_loss, NOC_mse=mse) return",
"NOC class \"\"\" import os import cv2 from recordclass import recordclass from torchstat",
"test_loader, niter, test_writer): with torch.no_grad(): self.seg_net.eval() for idx, batch in enumerate(test_loader): for keys",
"Loss: {}\".format(epoch, niter, total_losses.total_loss)) batch['image'] = batch['image'] * 2 - 1 writer.train.add_scalar('PSNR', total_losses.NOC_mse,",
"l1_loss = self.loss_l1(masked_output, batch['noc_image']) / ( # torch.sum(batch['num_points']) + 1 * (torch.sum(batch['num_points'] ==",
"= None self.lr = lr self.optimizer = torch.optim.Adam(params=self.seg_net.parameters(), lr=lr, betas=betas) # self.optimizer =",
"total_loss += background_loss mse = self.criterion_mse(output=output, batch=batch) losses = self.loss_tuple(total_loss=total_loss, NOC_loss=noc_loss, background_loss=background_loss, NOC_mse=mse)",
"1): for jdx, val in enumerate(total_losses): total_losses[jdx] /= data_length print(\"Epoch: {} | Final",
"- 1 visualize(writer=test_writer, batch=batch, output=(output, self.loss_tuple(0, 0, 0, 0)), name=\"Validation\", niter=niter, foreground=self.foreground, test=True)",
"mean, std): self.mean = mean self.std = std def __call__(self, tensor): \"\"\" Args:",
"if foreground: output_image = output[0][1] foreground = output[0][0] write_image(writer, name=\"{}/Ground Truth Foreground\".format(name), sample=((1",
"output=(output, total_losses), name=\"Validation\", niter=niter, foreground=self.foreground) def test(self, test_loader, niter, test_writer): with torch.no_grad(): self.seg_net.eval()",
"niter=niter) write_image(writer, name=\"{}/Output_Foreground\".format(name), sample=((torch.softmax(foreground, 1)[:, 1:2, :, :] > 0.5).long() * 2) -",
"self.loss_tuple = recordclass('losses', ('total_loss', 'NOC_loss', 'background_loss', 'NOC_mse')) self.ply_start = '''ply format ascii 1.0",
"background_loss mse = self.criterion_mse(output=output, batch=batch) losses = self.loss_tuple(total_loss=total_loss, NOC_loss=noc_loss, background_loss=background_loss, NOC_mse=mse) return output,",
":].cpu().numpy() image = image.transpose(1, 2, 0) * 255 cv2.imwrite(os.path.join(ply_dir, 'Output_{}.png'.format(idx + pdx)), image.astype('uint8'))",
"+ (epoch * data_length) if idx % opt.log_iter == 0: print(\"Epoch: {} |",
"self.validate(test_loader=data_loader.validate, test_writer=writer.validate, niter=(epoch + 1) * data_length + 1) print(\"*\" * 100) if",
"os.path.exists(self.save_path): os.mkdir(self.save_path) self.batch_size = batch_size self.mean = mean self.std = std self.loss_tuple =",
"# The normalize code -> t.sub_(m).div_(s) return tensor class TrainNOCs: def __init__(self, save_dir='Trial',",
"( # torch.sum(batch['num_points']) + 1 * (torch.sum(batch['num_points'] == 0).float())) # self.optimizer.zero_grad() losses.total_loss.backward() self.optimizer.step()",
"out_arr = output output_arr = out_arr[pdx, :, batch['yx_loc'][pdx, :num[pdx, 0], 0], batch['yx_loc'][pdx, :num[pdx,",
"'optimizer': self.optimizer.state_dict()}, os.path.join(self.save_path, 'save_{}.pth'.format(niter))) # visualize(writer=writer.train, batch=batch, output=(output, total_losses), # name=\"Train Total\", niter=(epoch",
"2, 0) * 255 cv2.imwrite(os.path.join(ply_dir, 'Output_{}.png'.format(idx + pdx)), image.astype('uint8')) with open(os.path.join(ply_dir, 'Output_{}.ply'.format(idx +",
"0.999), batch_size=8, checkpoint=None, model_type='res', output_heads='two'): if output_heads == 'one': self.forward = self.forward_sparse self.seg_net",
"0:2, :, :]).float() foreground[:, 0, :, :] = batch['background'][:, 0, :, :] background_loss",
"self.l1 = torch.nn.SmoothL1Loss() self.l2 = torch.nn.MSELoss() self.bce = torch.nn.BCEWithLogitsLoss() self.seg_net.cuda() self.sparse_l1.cuda() self.l1.cuda() self.bce.cuda()",
"Iteration: {} | Train Loss: {}\".format(epoch, niter, losses.total_loss.item())) batch['image'] = batch['image'] * 2",
"= self.forward_2_heads self.seg_net = ResNet2HeadGenerator(out_channels=3, last_layer=nn.ReLU()) if model_type == 'res_unet': self.seg_net = ResUnet2HeadGenerator(output_nc=3,",
"3)) # sub_batch = sub_batch / (num_points * 3) batch['num_points'] = batch['num_points'].long() num",
"self.forward = self.forward_2_heads self.seg_net = ResNet2HeadGenerator(out_channels=3, last_layer=nn.ReLU()) if model_type == 'res_unet': self.seg_net =",
"writer.add_scalar('NOC-Loss', output[1].NOC_loss, niter) writer.add_scalar('Background-Loss', output[1].background_loss, niter) write_image(writer, name=\"{}/Output_NOC\".format(name), sample=(output_image * 2) - 1,",
"image = batch['image'][pdx, :, batch['yx_loc'][pdx, :num[pdx, 0], 0], batch['yx_loc'][pdx, :num[pdx, 0], 1]] if",
"+= 10 * log10(1 / losses[jdx].item()) else: total_losses[jdx] += losses[jdx].item() # total_losses.total_loss +=",
"def criterion_mse(self, output, batch): batch_size = batch['num_points'].shape[0] batch['num_points'] = batch['num_points'].long() num = batch['num_points'].view(batch_size,",
"+ 1) * data_length + 1) print(\"*\" * 100) if __name__ == \"__main__\":",
"in batch: batch[keys] = batch[keys].float().cuda() output, losses = self.forward(batch=batch) # View NOC as",
"normalized. Returns: Tensor: Normalized image. \"\"\" for t, m, s in zip(tensor, self.mean,",
"open(os.path.join(ply_dir, 'Ground_truth_{}.ply'.format(idx + pdx)), 'w') as write_file: write_file.write(start) np.savetxt(write_file, concatenated_gt, fmt=' '.join(['%0.8f'] *",
"batch['image'] * 2 - 1 visualize(writer=writer.train, batch=batch, output=(output, losses), name=\"Train Total\", niter=niter, foreground=self.foreground)",
"import * def visualize(batch, output, writer, name, niter, foreground=False, test=False): output_image = output[0]",
"{} | Final Iteration: {} | Train Loss: {}\".format(epoch, niter, total_losses.total_loss)) batch['image'] =",
"'w') as write_file: write_file.write(start) np.savetxt(write_file, concatenated_out, fmt=' '.join(['%0.8f'] * 3 + ['%d'] *",
"self.seg_net.state_dict(), 'optimizer': self.optimizer.state_dict()}, os.path.join(self.save_path, 'save_{}.pth'.format(niter))) # visualize(writer=writer.train, batch=batch, output=(output, total_losses), # name=\"Train Total\",",
"red property uchar green property uchar blue end_header\\n''' self.un_norm = UnNormalize(mean=self.mean, std=self.std) def",
"batch['yx_loc'][pdx, :num[pdx, 0], 1]] noc_gt = batch['noc_points'][pdx, :num[pdx, 0]].cpu().numpy() image = image.cpu().numpy().T image",
"property uchar blue end_header\\n''' self.un_norm = UnNormalize(mean=self.mean, std=self.std) def criterion_mse(self, output, batch): batch_size",
"normalize code -> t.sub_(m).div_(s) return tensor class TrainNOCs: def __init__(self, save_dir='Trial', mean=(0.5, 0.5,",
"0], 1]], noc_points) return sub / batch_size def criterion_l1_sparse(self, output, batch): batch_size =",
"* (torch.softmax(output[0][0], 1)[:, 1:2, :, :] > 0.5).float() write_image(writer, name=\"{}/Output_Final_NOC\".format(name), sample=(final_noc * 2)",
"niter=niter) if not test: write_image(writer, name=\"{}/Ground Truth NOC\".format(name), sample=batch['noc_image'], niter=niter) return True class",
"def forward_sparse(self, batch): total_loss = 0 output = self.seg_net(batch['image']) # if 'mask_image' in",
":, :]) > 0).float())) foreground = (1 - batch['background'][:, 0:2, :, :]).float() foreground[:,",
"import os import cv2 from recordclass import recordclass from torchstat import stat from",
"name=\"Train\", niter=niter) # Last Iteration if idx == (data_length - 1): for jdx,",
"= output[0] if foreground: output_image = output[0][1] foreground = output[0][0] write_image(writer, name=\"{}/Ground Truth",
"1) sub += self.l2(output[idx, :, batch['yx_loc'][idx, :num[idx, 0], 0], batch['yx_loc'][idx, :num[idx, 0], 1]],",
"lr=lr, momentum=0.5) if checkpoint is not None: checkpoint = torch.load(checkpoint) self.seg_net.load_state_dict(checkpoint['model']) self.optimizer.load_state_dict(checkpoint['optimizer']) self.save_path",
"0 output = self.seg_net(batch['image']) # if 'mask_image' in batch.keys(): # masked_output = output",
"def validate(self, test_loader, niter, test_writer, write_ply=False, ply_dir=''): total_losses = self.loss_tuple(0, 0, 0, 0)",
"last_layer=nn.ReLU()) self.foreground = True else: self.foreground = None print(\"Error! Unknown number of heads!\")",
"# total_losses.total_loss += losses.total_loss.item() if idx == (len(test_loader) - 1): # print(len(test_loader)) for",
"= output[1] * (batch['mask_image'] > 0).float() batch['num_points'] = batch['num_points'].long() num = batch['num_points'].view(batch_size, 1)",
"0], :] noc_points = torch.transpose(noc_points, 0, 1) sub += self.l1(output[idx, :, batch['yx_loc'][idx, :num[idx,",
"len(test_loader) print(\"Validation loss: {}\".format(total_losses.total_loss)) # batch['image'] = self.un_norm(batch['image']) batch['image'] = batch['image'] * 2",
"losses[jdx].item()) else: total_losses[jdx] += losses[jdx].item() # total_loss += loss.item() niter = idx +",
"for jdx, val in enumerate(total_losses): total_losses[jdx] /= data_length print(\"Epoch: {} | Final Iteration:",
"niter, total_losses.total_loss)) batch['image'] = batch['image'] * 2 - 1 writer.train.add_scalar('PSNR', total_losses.NOC_mse, niter) torch.save({'epoch':",
"self.seg_net = Unet2HeadGenerator(input_nc=3, output_nc=3, num_downs=num_downs, # use_dropout=False, norm_layer=torch.nn.BatchNorm2d, # last_layer=nn.ReLU()) self.foreground = True",
"in enumerate(test_loader): for keys in batch: batch[keys] = batch[keys].float().cuda() output, losses = self.forward(batch=batch)",
"ply_dir=''): total_losses = self.loss_tuple(0, 0, 0, 0) if write_ply: if not os.path.exists(ply_dir): os.mkdir(ply_dir)",
"noc_points = batch['noc_points'][idx, :num[idx, 0], :] noc_points = torch.transpose(noc_points, 0, 1) sub +=",
"(epoch * data_length) if idx % opt.log_iter == 0: print(\"Epoch: {} | Iteration:",
"noc_points = torch.transpose(noc_points, 0, 1) sub += self.l1(output[idx, :, batch['yx_loc'][idx, :num[idx, 0], 0],",
"torch.load(checkpoint) self.seg_net.load_state_dict(checkpoint['model']) self.optimizer.load_state_dict(checkpoint['optimizer']) self.save_path = os.path.join(\"../saves\", save_dir) if not os.path.exists(self.save_path): os.mkdir(self.save_path) self.batch_size =",
"property uchar red property uchar green property uchar blue end_header\\n''' self.un_norm = UnNormalize(mean=self.mean,",
"use_dropout=False, norm_layer=torch.nn.BatchNorm2d, # last_layer=nn.LeakyReLU(0.2)) self.foreground = False elif output_heads == 'two': self.forward =",
"= mean self.std = std self.loss_tuple = recordclass('losses', ('total_loss', 'NOC_loss', 'background_loss', 'NOC_mse')) self.ply_start",
"0:1, :, :]) > 0).float())) foreground = (1 - batch['background'][:, 0:2, :, :]).float()",
"test_writer, write_ply=False, ply_dir=''): total_losses = self.loss_tuple(0, 0, 0, 0) if write_ply: if not",
"else: out_arr = output output_arr = out_arr[pdx, :, batch['yx_loc'][pdx, :num[pdx, 0], 0], batch['yx_loc'][pdx,",
"total_losses.total_loss += losses.total_loss.item() if idx == (len(test_loader) - 1): # print(len(test_loader)) for jdx,",
"self.l1.cuda() self.bce.cuda() self.seg_net.train() self.criterion_selection = None self.lr = lr self.optimizer = torch.optim.Adam(params=self.seg_net.parameters(), lr=lr,",
"return sub / batch_size def forward_sparse(self, batch): total_loss = 0 output = self.seg_net(batch['image'])",
"= out_arr[pdx, :, batch['yx_loc'][pdx, :num[pdx, 0], 0], batch['yx_loc'][pdx, :num[pdx, 0], 1]] noc_gt =",
"1 test_writer.add_scalar('PSNR', total_losses.NOC_mse, niter) visualize(writer=test_writer, batch=batch, output=(output, total_losses), name=\"Validation\", niter=niter, foreground=self.foreground) def test(self,",
"losses[jdx].item() # total_loss += loss.item() niter = idx + (epoch * data_length) if",
"os.path.join(\"../saves\", save_dir) if not os.path.exists(self.save_path): os.mkdir(self.save_path) self.batch_size = batch_size self.mean = mean self.std",
"image of size (C, H, W) to be normalized. Returns: Tensor: Normalized image.",
"background_loss mse = self.criterion_mse(output=output[1], batch=batch) losses = self.loss_tuple(total_loss=total_loss, NOC_loss=noc_loss, background_loss=background_loss, NOC_mse=mse) return output,",
"total_losses.NOC_mse, niter) visualize(writer=test_writer, batch=batch, output=(output, total_losses), name=\"Validation\", niter=niter, foreground=self.foreground) def test(self, test_loader, niter,",
"image.astype('uint8')) with open(os.path.join(ply_dir, 'Output_{}.ply'.format(idx + pdx)), 'w') as write_file: write_file.write(start) np.savetxt(write_file, concatenated_out, fmt='",
"0, 0, 0)), name=\"Validation\", niter=niter, foreground=self.foreground, test=True) def run(self, opt, data_loader, writer, epoch=0):",
"= self.un_norm(batch['image']) # visualize(writer=writer.train, batch=batch, output=(output, loss), # name=\"Train\", niter=niter) # Last Iteration",
"self.foreground = None print(\"Error! Unknown number of heads!\") exit(256) print(\"Using model {}.\".format(self.seg_net.__class__.__name__)) #",
"UnNormalize(object): def __init__(self, mean, std): self.mean = mean self.std = std def __call__(self,",
"green property uchar blue end_header\\n''' self.un_norm = UnNormalize(mean=self.mean, std=self.std) def criterion_mse(self, output, batch):",
"is 3: total_losses[jdx] += 10 * log10(1 / losses[jdx].item()) else: total_losses[jdx] += losses[jdx].item()",
"= ResUnet2HeadGenerator(output_nc=3, last_layer=nn.ReLU()) # self.seg_net = Unet2HeadGenerator(input_nc=3, output_nc=3, num_downs=num_downs, # use_dropout=False, norm_layer=torch.nn.BatchNorm2d, #",
"* (batch['mask_image'] > 0).float() noc_loss = self.criterion_l1_sparse(output=output[1], batch=batch) total_loss += noc_loss * 70",
"= self.criterion_l1(output=masked_output, batch=batch) # l1_loss = self.loss_l1(masked_output, batch['noc_image']) / ( # torch.sum(batch['num_points']) +",
"0], 1]] if self.foreground: out_arr = output[1] else: out_arr = output output_arr =",
"/ batch_size def forward_sparse(self, batch): total_loss = 0 output = self.seg_net(batch['image']) # if",
"__init__(self, mean, std): self.mean = mean self.std = std def __call__(self, tensor): \"\"\"",
"niter) write_image(writer, name=\"{}/Output_NOC\".format(name), sample=(output_image * 2) - 1, niter=niter) write_image(writer, name=\"{}/Input\".format(name), sample=batch['image'], niter=niter)",
":] > 0.5).float() write_image(writer, name=\"{}/Output_Final_NOC\".format(name), sample=(final_noc * 2) - 1, niter=niter) writer.add_scalar('L1-Loss', output[1].total_loss,",
"niter=niter) final_noc = output_image * (torch.softmax(output[0][0], 1)[:, 1:2, :, :] > 0.5).float() write_image(writer,",
":num[idx, 0], 1]], noc_points) return sub / batch_size def criterion_l1_sparse(self, output, batch): batch_size",
"1) sub += self.l1(output[idx, :, batch['yx_loc'][idx, :num[idx, 0], 0], batch['yx_loc'][idx, :num[idx, 0], 1]],",
"batch): total_loss = 0 output = self.seg_net(batch['image']) # if 'mask_image' in batch.keys(): #",
"2 - 1 output, losses = self.train(batch=batch) # print(batch['num_points'], torch.sum(batch['num_points'])) for jdx, val",
"momentum=0.5) if checkpoint is not None: checkpoint = torch.load(checkpoint) self.seg_net.load_state_dict(checkpoint['model']) self.optimizer.load_state_dict(checkpoint['optimizer']) self.save_path =",
"print(\"Epoch: {} | Final Iteration: {} | Train Loss: {}\".format(epoch, niter, total_losses.total_loss)) batch['image']",
"UnNormalize(mean=self.mean, std=self.std) def criterion_mse(self, output, batch): batch_size = batch['num_points'].shape[0] batch['num_points'] = batch['num_points'].long() num",
"idx in range(batch_size): if num[idx, 0] == 0: batch_size -= 1 continue noc_points",
"output[1] * (batch['mask_image'] > 0).float() noc_loss = self.criterion_l1_sparse(output=output[1], batch=batch) total_loss += noc_loss *",
":, :] background_loss = self.bce(input=output[0], target=foreground) total_loss += background_loss mse = self.criterion_mse(output=output[1], batch=batch)",
"self.criterion_mse(output=output[1], batch=batch) losses = self.loss_tuple(total_loss=total_loss, NOC_loss=noc_loss, background_loss=background_loss, NOC_mse=mse) return output, losses def train(self,",
"- batch['background'][:, 0:1, :, :]) > 0).float())) foreground = (1 - batch['background'][:, 0:2,",
"'Ground_truth_{}.ply'.format(idx + pdx)), 'w') as write_file: write_file.write(start) np.savetxt(write_file, concatenated_gt, fmt=' '.join(['%0.8f'] * 3",
"# loss = self.criterion_l1(output=masked_output, batch=batch) # l1_loss = self.loss_l1(masked_output, batch['noc_image']) / ( #",
":, batch['yx_loc'][idx, :num[idx, 0], 0], batch['yx_loc'][idx, :num[idx, 0], 1]], noc_points) return sub /",
"* def visualize(batch, output, writer, name, niter, foreground=False, test=False): output_image = output[0] if",
"output = self.seg_net(batch['image']) # # # if 'mask_image' in batch.keys(): # masked_output =",
"# masked_output = output * (batch['mask_image'] > 0).float() noc_loss = self.criterion_l1_sparse(output=output, batch=batch) total_loss",
"/ losses[jdx].item()) else: total_losses[jdx] += losses[jdx].item() # total_losses.total_loss += losses.total_loss.item() if idx ==",
"def __init__(self, mean, std): self.mean = mean self.std = std def __call__(self, tensor):",
"+= self.l2(output[idx, :, batch['yx_loc'][idx, :num[idx, 0], 0], batch['yx_loc'][idx, :num[idx, 0], 1]], noc_points) return",
"{} | Train Loss: {}\".format(epoch, niter, total_losses.total_loss)) batch['image'] = batch['image'] * 2 -",
"output output_arr = out_arr[pdx, :, batch['yx_loc'][pdx, :num[pdx, 0], 0], batch['yx_loc'][pdx, :num[pdx, 0], 1]]",
"name=\"Validation\", niter=niter, foreground=self.foreground, test=True) def run(self, opt, data_loader, writer, epoch=0): total_losses = self.loss_tuple(0,",
"- 1), niter=niter) write_image(writer, name=\"{}/Output_Foreground\".format(name), sample=((torch.softmax(foreground, 1)[:, 1:2, :, :] > 0.5).long() *",
"niter, test_writer): with torch.no_grad(): self.seg_net.eval() for idx, batch in enumerate(test_loader): for keys in",
"data_length print(\"Epoch: {} | Final Iteration: {} | Train Loss: {}\".format(epoch, niter, total_losses.total_loss))",
"data_length) if idx % opt.log_iter == 0: print(\"Epoch: {} | Iteration: {} |",
"= torch.abs(output - target) # sub = self.sparse_l1(output, target) # sub_batch = torch.sum(sub,",
"= torch.sum(sub, dim=(1, 2, 3)) # sub_batch = sub_batch / (num_points * 3)",
"out_arr[pdx, :, batch['yx_loc'][pdx, :num[pdx, 0], 0], batch['yx_loc'][pdx, :num[pdx, 0], 1]] noc_gt = batch['noc_points'][pdx,",
"= output_arr.cpu().numpy().T start = self.ply_start.format(num[pdx, 0].item()) concatenated_out = np.concatenate((output_arr, image), axis=1) concatenated_gt =",
"niter) visualize(writer=test_writer, batch=batch, output=(output, total_losses), name=\"Validation\", niter=niter, foreground=self.foreground) def test(self, test_loader, niter, test_writer):",
"15 == 0: self.lr *= 0.9 for param_group in self.optimizer.param_groups: param_group['lr'] = self.lr",
"self.seg_net(batch['image']) # masked_output = output[1] * (batch['mask_image'] > 0).float() noc_loss = self.criterion_l1_sparse(output=output[1], batch=batch)",
"+= 10 * log10(1 / losses[jdx].item()) else: total_losses[jdx] += losses[jdx].item() # total_loss +=",
"property float x property float y property float z property uchar red property",
"# sub_batch = torch.sum(sub, dim=(1, 2, 3)) # sub_batch = sub_batch / (num_points",
"0], 0], batch['yx_loc'][pdx, :num[pdx, 0], 1]] if self.foreground: out_arr = output[1] else: out_arr",
"= output_image * (torch.softmax(output[0][0], 1)[:, 1:2, :, :] > 0.5).float() write_image(writer, name=\"{}/Output_Final_NOC\".format(name), sample=(final_noc",
"1.0 element vertex {} property float x property float y property float z",
"if model_type == 'res_unet': self.seg_net = ResUnetGenerator(output_nc=3, last_layer=nn.ReLU()) # self.seg_net = UnetGenerator(input_nc=3, output_nc=3,",
"output[0] if foreground: output_image = output[0][1] foreground = output[0][0] write_image(writer, name=\"{}/Ground Truth Foreground\".format(name),",
":, batch['yx_loc'][pdx, :num[pdx, 0], 0], batch['yx_loc'][pdx, :num[pdx, 0], 1]] noc_gt = batch['noc_points'][pdx, :num[pdx,",
"* self.batch_size # masked_output = output[1] * (batch['mask_image'] > 0).float() batch['num_points'] = batch['num_points'].long()",
"and epoch % 15 == 0: self.lr *= 0.9 for param_group in self.optimizer.param_groups:",
"lr self.optimizer = torch.optim.Adam(params=self.seg_net.parameters(), lr=lr, betas=betas) # self.optimizer = torch.optim.SGD(params=self.seg_net.parameters(), lr=lr, momentum=0.5) if",
"# sub = torch.abs(output - target) # sub = self.sparse_l1(output, target) # sub_batch",
"torch.abs(output - target) # sub = self.sparse_l1(output, target) # sub_batch = torch.sum(sub, dim=(1,",
"+ 1 * (torch.sum(batch['num_points'] == 0).float())) # self.optimizer.zero_grad() losses.total_loss.backward() self.optimizer.step() return output, losses",
"property uchar green property uchar blue end_header\\n''' self.un_norm = UnNormalize(mean=self.mean, std=self.std) def criterion_mse(self,",
"| Train Loss: {}\".format(epoch, niter, total_losses.total_loss)) batch['image'] = batch['image'] * 2 - 1",
"total_loss += background_loss mse = self.criterion_mse(output=output[1], batch=batch) losses = self.loss_tuple(total_loss=total_loss, NOC_loss=noc_loss, background_loss=background_loss, NOC_mse=mse)",
"= batch['num_points'].long() num = batch['num_points'].view(batch_size, 1) for pdx in range(batch_size): image = batch['image'][pdx,",
"batch['image'] * 2 - 1 output, losses = self.train(batch=batch) # print(batch['num_points'], torch.sum(batch['num_points'])) for",
"2 - 1 visualize(writer=test_writer, batch=batch, output=(output, self.loss_tuple(0, 0, 0, 0)), name=\"Validation\", niter=niter, foreground=self.foreground,",
"{}\".format(epoch, niter, losses.total_loss.item())) batch['image'] = batch['image'] * 2 - 1 visualize(writer=writer.train, batch=batch, output=(output,",
"0, 1) sub += self.l2(output[idx, :, batch['yx_loc'][idx, :num[idx, 0], 0], batch['yx_loc'][idx, :num[idx, 0],",
"1) * data_length) # self.test(test_loader=data_loader.test, test_writer=writer.test, niter=(epoch + 1) * data_length) self.validate(test_loader=data_loader.validate, test_writer=writer.validate,",
"2, 3)) # sub_batch = sub_batch / (num_points * 3) batch['num_points'] = batch['num_points'].long()",
"0).float() batch['num_points'] = batch['num_points'].long() num = batch['num_points'].view(batch_size, 1) for pdx in range(batch_size): image",
"ResUnetGenerator(output_nc=3, last_layer=nn.ReLU()) # self.seg_net = UnetGenerator(input_nc=3, output_nc=3, num_downs=num_downs, # use_dropout=False, norm_layer=torch.nn.BatchNorm2d, # last_layer=nn.LeakyReLU(0.2))",
"self.forward(batch=batch) # View NOC as PLY if write_ply: self.write_noc_ply(output=output, batch=batch, idx=idx, ply_dir=ply_dir) for",
"1, niter=niter) writer.add_scalar('L1-Loss', output[1].total_loss, niter) writer.add_scalar('NOC-Loss', output[1].NOC_loss, niter) writer.add_scalar('Background-Loss', output[1].background_loss, niter) write_image(writer, name=\"{}/Output_NOC\".format(name),",
"std): self.mean = mean self.std = std def __call__(self, tensor): \"\"\" Args: tensor",
"+= self.l1(output[idx, :, batch['yx_loc'][idx, :num[idx, 0], 0], batch['yx_loc'][idx, :num[idx, 0], 1]], noc_points) return",
"= ResNetGenerator(out_channels=3, last_layer=nn.ReLU()) if model_type == 'res_unet': self.seg_net = ResUnetGenerator(output_nc=3, last_layer=nn.ReLU()) # self.seg_net",
"0 output = self.seg_net(batch['image']) # masked_output = output[1] * (batch['mask_image'] > 0).float() noc_loss",
"image = batch['image'][pdx, :, :, :].cpu().numpy() image = image.transpose(1, 2, 0) * 255",
"0)), name=\"Validation\", niter=niter, foreground=self.foreground, test=True) def run(self, opt, data_loader, writer, epoch=0): total_losses =",
"param_group in self.optimizer.param_groups: param_group['lr'] = self.lr for idx, batch in enumerate(data_loader.train): for keys",
"UnetGenerator(input_nc=3, output_nc=3, num_downs=num_downs, # use_dropout=False, norm_layer=torch.nn.BatchNorm2d, # last_layer=nn.LeakyReLU(0.2)) self.foreground = False elif output_heads",
"import log10 from models.networks import * from utils.common import * def visualize(batch, output,",
"The normalize code -> t.sub_(m).div_(s) return tensor class TrainNOCs: def __init__(self, save_dir='Trial', mean=(0.5,",
"self.ply_start = '''ply format ascii 1.0 element vertex {} property float x property",
"/ batch_size def criterion_l1_sparse(self, output, batch): batch_size = batch['num_points'].shape[0] # num_points[num_points == 0]",
"test_writer=writer.test, niter=(epoch + 1) * data_length) self.validate(test_loader=data_loader.validate, test_writer=writer.validate, niter=(epoch + 1) * data_length",
"3)) with open(os.path.join(ply_dir, 'Ground_truth_{}.ply'.format(idx + pdx)), 'w') as write_file: write_file.write(start) np.savetxt(write_file, concatenated_gt, fmt='",
"batch['image'] = batch['image'] * 2 - 1 visualize(writer=writer.train, batch=batch, output=(output, losses), name=\"Train Total\",",
"batch=batch) # l1_loss = self.loss_l1(masked_output, batch['noc_image']) / ( # torch.sum(batch['num_points']) + 1 *",
"loss.item() niter = idx + (epoch * data_length) if idx % opt.log_iter ==",
"with torch.no_grad(): self.seg_net.eval() for idx, batch in enumerate(test_loader): for keys in batch: batch[keys]",
"1 continue noc_points = batch['noc_points'][idx, :num[idx, 0], :] noc_points = torch.transpose(noc_points, 0, 1)",
"batch['num_points'].shape[0] # num_points[num_points == 0] = 1 # sub = torch.abs(output - target)",
"recordclass from torchstat import stat from math import log10 from models.networks import *",
"if 'mask_image' in batch.keys(): # masked_output = output * batch['mask_image'] # # loss",
":]) > 0).float())) foreground = (1 - batch['background'][:, 0:2, :, :]).float() foreground[:, 0,",
"self.l1(masked_output, batch['noc_image']) background_target = torch.zeros_like(output) background_loss = self.l1(output * batch['background'], background_target) total_loss +=",
"batch['image'] = batch['image'] * 2 - 1 test_writer.add_scalar('PSNR', total_losses.NOC_mse, niter) visualize(writer=test_writer, batch=batch, output=(output,",
"batch['background'][:, 0, :, :] background_loss = self.bce(input=output[0], target=foreground) total_loss += background_loss mse =",
"batch['image'][pdx, :, :, :].cpu().numpy() image = image.transpose(1, 2, 0) * 255 cv2.imwrite(os.path.join(ply_dir, 'Output_{}.png'.format(idx",
"self.bce.cuda() self.seg_net.train() self.criterion_selection = None self.lr = lr self.optimizer = torch.optim.Adam(params=self.seg_net.parameters(), lr=lr, betas=betas)",
"niter, foreground=False, test=False): output_image = output[0] if foreground: output_image = output[0][1] foreground =",
"std=(0.5, 0.5, 0.5), num_downs=5, lr=2e-4, betas=(0.5, 0.999), batch_size=8, checkpoint=None, model_type='res', output_heads='two'): if output_heads",
"jdx, val in enumerate(total_losses): total_losses[jdx] /= len(test_loader) print(\"Validation loss: {}\".format(total_losses.total_loss)) # batch['image'] =",
"= torch.transpose(noc_points, 0, 1) sub += self.l2(output[idx, :, batch['yx_loc'][idx, :num[idx, 0], 0], batch['yx_loc'][idx,",
"0).float() noc_loss = self.criterion_l1_sparse(output=output[1], batch=batch) total_loss += noc_loss * 70 # print(torch.max(((1 -",
"else: self.foreground = None print(\"Error! Unknown number of heads!\") exit(256) print(\"Using model {}.\".format(self.seg_net.__class__.__name__))",
"axis=1) image = batch['image'][pdx, :, :, :].cpu().numpy() image = image.transpose(1, 2, 0) *",
"% opt.log_iter == 0: print(\"Epoch: {} | Iteration: {} | Train Loss: {}\".format(epoch,",
"* 2 - 1 writer.train.add_scalar('PSNR', total_losses.NOC_mse, niter) torch.save({'epoch': epoch, 'model': self.seg_net.state_dict(), 'optimizer': self.optimizer.state_dict()},",
"= True else: self.foreground = None print(\"Error! Unknown number of heads!\") exit(256) print(\"Using",
"(batch['mask_image'] > 0).float() noc_loss = self.criterion_l1_sparse(output=output[1], batch=batch) total_loss += noc_loss * 70 #",
"batch=batch, idx=idx, ply_dir=ply_dir) for jdx, val in enumerate(losses): if jdx is 3: total_losses[jdx]",
"* 2) - 1, niter=niter) write_image(writer, name=\"{}/Input\".format(name), sample=batch['image'], niter=niter) if not test: write_image(writer,",
"= self.loss_l1(masked_output, batch['noc_image']) / ( # torch.sum(batch['num_points']) + 1 * (torch.sum(batch['num_points'] == 0).float()))",
"def test(self, test_loader, niter, test_writer): with torch.no_grad(): self.seg_net.eval() for idx, batch in enumerate(test_loader):",
"for idx in range(batch_size): if num[idx, 0] == 0: batch_size -= 1 continue",
"== 'one': self.forward = self.forward_sparse self.seg_net = ResNetGenerator(out_channels=3, last_layer=nn.ReLU()) if model_type == 'res_unet':",
"writer.train.add_scalar('PSNR', total_losses.NOC_mse, niter) torch.save({'epoch': epoch, 'model': self.seg_net.state_dict(), 'optimizer': self.optimizer.state_dict()}, os.path.join(self.save_path, 'save_{}.pth'.format(niter))) # visualize(writer=writer.train,",
"noc_points = torch.transpose(noc_points, 0, 1) sub += self.l2(output[idx, :, batch['yx_loc'][idx, :num[idx, 0], 0],",
"mse = self.criterion_mse(output=output[1], batch=batch) losses = self.loss_tuple(total_loss=total_loss, NOC_loss=noc_loss, background_loss=background_loss, NOC_mse=mse) return output, losses",
"t.sub_(m).div_(s) return tensor class TrainNOCs: def __init__(self, save_dir='Trial', mean=(0.5, 0.5, 0.5), std=(0.5, 0.5,",
":num[pdx, 0], 0], batch['yx_loc'][pdx, :num[pdx, 0], 1]] noc_gt = batch['noc_points'][pdx, :num[pdx, 0]].cpu().numpy() image",
"idx, batch in enumerate(data_loader.train): for keys in batch: batch[keys] = batch[keys].float().cuda() # batch['image']",
"num_downs=5, lr=2e-4, betas=(0.5, 0.999), batch_size=8, checkpoint=None, model_type='res', output_heads='two'): if output_heads == 'one': self.forward",
"write_file: write_file.write(start) np.savetxt(write_file, concatenated_gt, fmt=' '.join(['%0.8f'] * 3 + ['%d'] * 3)) def",
"in enumerate(losses): if jdx is 3: total_losses[jdx] += 10 * log10(1 / losses[jdx].item())",
"= batch['image'] * 2 - 1 test_writer.add_scalar('PSNR', total_losses.NOC_mse, niter) visualize(writer=test_writer, batch=batch, output=(output, total_losses),",
"1 * (torch.sum(batch['num_points'] == 0).float())) # self.optimizer.zero_grad() losses.total_loss.backward() self.optimizer.step() return output, losses def",
"total_losses[jdx] += 10 * log10(1 / losses[jdx].item()) else: total_losses[jdx] += losses[jdx].item() # total_loss",
"write_file.write(start) np.savetxt(write_file, concatenated_out, fmt=' '.join(['%0.8f'] * 3 + ['%d'] * 3)) with open(os.path.join(ply_dir,",
"background_target = torch.zeros_like(output) background_loss = self.l1(output * batch['background'], background_target) total_loss += background_loss mse",
"0.5), std=(0.5, 0.5, 0.5), num_downs=5, lr=2e-4, betas=(0.5, 0.999), batch_size=8, checkpoint=None, model_type='res', output_heads='two'): if",
"criterion_l1_sparse(self, output, batch): batch_size = batch['num_points'].shape[0] # num_points[num_points == 0] = 1 #",
"losses = self.forward(batch=batch) # output = self.seg_net(batch['image']) # # # if 'mask_image' in",
"\"\"\" for t, m, s in zip(tensor, self.mean, self.std): t.mul_(s).add_(m) # The normalize",
"> 0).float() noc_loss = self.criterion_l1_sparse(output=output, batch=batch) total_loss += noc_loss * 10 # loss",
"noc_loss * 70 # print(torch.max(((1 - batch['background'][:, 0:1, :, :]) > 0).float())) foreground",
"= batch['num_points'].view(batch_size, 1) for pdx in range(batch_size): image = batch['image'][pdx, :, batch['yx_loc'][pdx, :num[pdx,",
"image[:, [2, 1, 0]] * 255 output_arr = output_arr.cpu().numpy().T start = self.ply_start.format(num[pdx, 0].item())",
"output[1].background_loss, niter) write_image(writer, name=\"{}/Output_NOC\".format(name), sample=(output_image * 2) - 1, niter=niter) write_image(writer, name=\"{}/Input\".format(name), sample=batch['image'],",
"batch[keys] = batch[keys].float().cuda() # batch['image'] = batch['image'] * 2 - 1 output, losses",
"Train Loss: {}\".format(epoch, niter, total_losses.total_loss)) batch['image'] = batch['image'] * 2 - 1 writer.train.add_scalar('PSNR',",
"from models.networks import * from utils.common import * def visualize(batch, output, writer, name,",
"NOC\".format(name), sample=batch['noc_image'], niter=niter) return True class UnNormalize(object): def __init__(self, mean, std): self.mean =",
"/ losses[jdx].item()) else: total_losses[jdx] += losses[jdx].item() # total_loss += loss.item() niter = idx",
"= UnNormalize(mean=self.mean, std=self.std) def criterion_mse(self, output, batch): batch_size = batch['num_points'].shape[0] batch['num_points'] = batch['num_points'].long()",
"self.forward(batch=batch) # output = self.seg_net(batch['image']) # # # if 'mask_image' in batch.keys(): #",
"# Last Iteration if idx == (data_length - 1): for jdx, val in",
"self.criterion_l1_sparse(output=output, batch=batch) total_loss += noc_loss * 10 # loss = self.l1(masked_output, batch['noc_image']) background_target",
"vertex {} property float x property float y property float z property uchar",
"output, losses = self.forward(batch=batch) # output = self.seg_net(batch['image']) # # # if 'mask_image'",
"input_size=(3, 256, 256)) self.sparse_l1 = torch.nn.SmoothL1Loss(reduction='none') self.l1 = torch.nn.SmoothL1Loss() self.l2 = torch.nn.MSELoss() self.bce",
"float y property float z property uchar red property uchar green property uchar",
"self.seg_net = ResUnetGenerator(output_nc=3, last_layer=nn.ReLU()) # self.seg_net = UnetGenerator(input_nc=3, output_nc=3, num_downs=num_downs, # use_dropout=False, norm_layer=torch.nn.BatchNorm2d,",
"output=(output, loss), # name=\"Train\", niter=niter) # Last Iteration if idx == (data_length -",
"niter, losses.total_loss.item())) batch['image'] = batch['image'] * 2 - 1 visualize(writer=writer.train, batch=batch, output=(output, losses),",
"= sub_batch / (num_points * 3) batch['num_points'] = batch['num_points'].long() num = batch['num_points'].view(batch_size, 1)",
"# sub_batch = sub_batch / (num_points * 3) batch['num_points'] = batch['num_points'].long() num =",
"'model': self.seg_net.state_dict(), 'optimizer': self.optimizer.state_dict()}, os.path.join(self.save_path, 'save_{}.pth'.format(niter))) # visualize(writer=writer.train, batch=batch, output=(output, total_losses), # name=\"Train",
"\"\"\" Args: tensor (Tensor): Tensor image of size (C, H, W) to be",
"batch): batch_size = batch['num_points'].shape[0] batch['num_points'] = batch['num_points'].long() num = batch['num_points'].view(batch_size, 1) batch['yx_loc'] =",
"self.std = std def __call__(self, tensor): \"\"\" Args: tensor (Tensor): Tensor image of",
"if not os.path.exists(self.save_path): os.mkdir(self.save_path) self.batch_size = batch_size self.mean = mean self.std = std",
"recordclass('losses', ('total_loss', 'NOC_loss', 'background_loss', 'NOC_mse')) self.ply_start = '''ply format ascii 1.0 element vertex",
"losses.total_loss.item())) batch['image'] = batch['image'] * 2 - 1 visualize(writer=writer.train, batch=batch, output=(output, losses), name=\"Train",
"{}\".format(epoch, niter, total_losses.total_loss)) batch['image'] = batch['image'] * 2 - 1 writer.train.add_scalar('PSNR', total_losses.NOC_mse, niter)",
"* log10(1 / losses[jdx].item()) else: total_losses[jdx] += losses[jdx].item() # total_loss += loss.item() niter",
"idx == (data_length - 1): for jdx, val in enumerate(total_losses): total_losses[jdx] /= data_length",
"batch['noc_points'][idx, :num[idx, 0], :] noc_points = torch.transpose(noc_points, 0, 1) sub += self.l1(output[idx, :,",
"range(batch_size): if num[idx, 0] == 0: batch_size -= 1 continue noc_points = batch['noc_points'][idx,",
"niter=niter) return True class UnNormalize(object): def __init__(self, mean, std): self.mean = mean self.std",
"batch['background'][:, 0:2, :, :]).float() foreground[:, 0, :, :] = batch['background'][:, 0, :, :]",
"keys in batch: batch[keys] = batch[keys].float().cuda() output, losses = self.forward(batch=batch) # View NOC",
"with open(os.path.join(ply_dir, 'Ground_truth_{}.ply'.format(idx + pdx)), 'w') as write_file: write_file.write(start) np.savetxt(write_file, concatenated_gt, fmt=' '.join(['%0.8f']",
"- 1 output, losses = self.train(batch=batch) # print(batch['num_points'], torch.sum(batch['num_points'])) for jdx, val in",
"batch=batch, output=(output, losses), name=\"Train Total\", niter=niter, foreground=self.foreground) # batch['image'] = self.un_norm(batch['image']) # visualize(writer=writer.train,",
"self.bce(input=output[0], target=foreground) total_loss += background_loss mse = self.criterion_mse(output=output[1], batch=batch) losses = self.loss_tuple(total_loss=total_loss, NOC_loss=noc_loss,",
"open(os.path.join(ply_dir, 'Output_{}.ply'.format(idx + pdx)), 'w') as write_file: write_file.write(start) np.savetxt(write_file, concatenated_out, fmt=' '.join(['%0.8f'] *",
"# self.seg_net = UnetGenerator(input_nc=3, output_nc=3, num_downs=num_downs, # use_dropout=False, norm_layer=torch.nn.BatchNorm2d, # last_layer=nn.LeakyReLU(0.2)) self.foreground =",
"NOC_loss=noc_loss, background_loss=background_loss, NOC_mse=mse) return output, losses def train(self, batch): output, losses = self.forward(batch=batch)",
"batch_size=8, checkpoint=None, model_type='res', output_heads='two'): if output_heads == 'one': self.forward = self.forward_sparse self.seg_net =",
"if epoch > 0 and epoch % 15 == 0: self.lr *= 0.9",
"| Iteration: {} | Train Loss: {}\".format(epoch, niter, losses.total_loss.item())) batch['image'] = batch['image'] *",
"self.optimizer = torch.optim.Adam(params=self.seg_net.parameters(), lr=lr, betas=betas) # self.optimizer = torch.optim.SGD(params=self.seg_net.parameters(), lr=lr, momentum=0.5) if checkpoint",
"% 15 == 0: self.lr *= 0.9 for param_group in self.optimizer.param_groups: param_group['lr'] =",
"visualize(writer=writer.train, batch=batch, output=(output, losses), name=\"Train Total\", niter=niter, foreground=self.foreground) # batch['image'] = self.un_norm(batch['image']) #",
"test=True) def run(self, opt, data_loader, writer, epoch=0): total_losses = self.loss_tuple(0, 0, 0, 0)",
"writer.add_scalar('L1-Loss', output[1].total_loss, niter) writer.add_scalar('NOC-Loss', output[1].NOC_loss, niter) writer.add_scalar('Background-Loss', output[1].background_loss, niter) write_image(writer, name=\"{}/Output_NOC\".format(name), sample=(output_image *",
"checkpoint = torch.load(checkpoint) self.seg_net.load_state_dict(checkpoint['model']) self.optimizer.load_state_dict(checkpoint['optimizer']) self.save_path = os.path.join(\"../saves\", save_dir) if not os.path.exists(self.save_path): os.mkdir(self.save_path)",
"num[idx, 0] == 0: batch_size -= 1 continue noc_points = batch['noc_points'][idx, :num[idx, 0],",
"= self.bce(input=output[0], target=foreground) total_loss += background_loss mse = self.criterion_mse(output=output[1], batch=batch) losses = self.loss_tuple(total_loss=total_loss,",
":] noc_points = torch.transpose(noc_points, 0, 1) sub += self.l1(output[idx, :, batch['yx_loc'][idx, :num[idx, 0],",
"self.l2 = torch.nn.MSELoss() self.bce = torch.nn.BCEWithLogitsLoss() self.seg_net.cuda() self.sparse_l1.cuda() self.l1.cuda() self.bce.cuda() self.seg_net.train() self.criterion_selection =",
"m, s in zip(tensor, self.mean, self.std): t.mul_(s).add_(m) # The normalize code -> t.sub_(m).div_(s)",
"= torch.nn.SmoothL1Loss() self.l2 = torch.nn.MSELoss() self.bce = torch.nn.BCEWithLogitsLoss() self.seg_net.cuda() self.sparse_l1.cuda() self.l1.cuda() self.bce.cuda() self.seg_net.train()",
"self.seg_net(batch['image']) batch['image'] = batch['image'] * 2 - 1 visualize(writer=test_writer, batch=batch, output=(output, self.loss_tuple(0, 0,",
"niter=niter) # Last Iteration if idx == (data_length - 1): for jdx, val",
"1 # sub = torch.abs(output - target) # sub = self.sparse_l1(output, target) #",
"class TrainNOCs: def __init__(self, save_dir='Trial', mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), num_downs=5, lr=2e-4,",
"total_losses.NOC_mse, niter) torch.save({'epoch': epoch, 'model': self.seg_net.state_dict(), 'optimizer': self.optimizer.state_dict()}, os.path.join(self.save_path, 'save_{}.pth'.format(niter))) # visualize(writer=writer.train, batch=batch,",
"== 'res_unet': self.seg_net = ResUnet2HeadGenerator(output_nc=3, last_layer=nn.ReLU()) # self.seg_net = Unet2HeadGenerator(input_nc=3, output_nc=3, num_downs=num_downs, #",
"test_loader, niter, test_writer, write_ply=False, ply_dir=''): total_losses = self.loss_tuple(0, 0, 0, 0) if write_ply:",
"# self.test(test_loader=data_loader.test, test_writer=writer.test, niter=(epoch + 1) * data_length) self.validate(test_loader=data_loader.validate, test_writer=writer.validate, niter=(epoch + 1)",
"total_losses[jdx] /= len(test_loader) print(\"Validation loss: {}\".format(total_losses.total_loss)) # batch['image'] = self.un_norm(batch['image']) batch['image'] = batch['image']",
"output, writer, name, niter, foreground=False, test=False): output_image = output[0] if foreground: output_image =",
"= output[1] * (batch['mask_image'] > 0).float() noc_loss = self.criterion_l1_sparse(output=output[1], batch=batch) total_loss += noc_loss",
"batch['yx_loc'][pdx, :num[pdx, 0], 0], batch['yx_loc'][pdx, :num[pdx, 0], 1]] if self.foreground: out_arr = output[1]",
"concatenated_out = np.concatenate((output_arr, image), axis=1) concatenated_gt = np.concatenate((noc_gt, image), axis=1) image = batch['image'][pdx,",
"sample=((1 - batch['background']).long() * 2 - 1), niter=niter) write_image(writer, name=\"{}/Output_Foreground\".format(name), sample=((torch.softmax(foreground, 1)[:, 1:2,",
"def visualize(batch, output, writer, name, niter, foreground=False, test=False): output_image = output[0] if foreground:",
"+= noc_loss * 70 # print(torch.max(((1 - batch['background'][:, 0:1, :, :]) > 0).float()))",
":num[pdx, 0], 1]] if self.foreground: out_arr = output[1] else: out_arr = output output_arr",
"self.forward_sparse self.seg_net = ResNetGenerator(out_channels=3, last_layer=nn.ReLU()) if model_type == 'res_unet': self.seg_net = ResUnetGenerator(output_nc=3, last_layer=nn.ReLU())",
"foreground: output_image = output[0][1] foreground = output[0][0] write_image(writer, name=\"{}/Ground Truth Foreground\".format(name), sample=((1 -",
"range(batch_size): image = batch['image'][pdx, :, batch['yx_loc'][pdx, :num[pdx, 0], 0], batch['yx_loc'][pdx, :num[pdx, 0], 1]]",
"tensor): \"\"\" Args: tensor (Tensor): Tensor image of size (C, H, W) to",
"writer.add_scalar('Background-Loss', output[1].background_loss, niter) write_image(writer, name=\"{}/Output_NOC\".format(name), sample=(output_image * 2) - 1, niter=niter) write_image(writer, name=\"{}/Input\".format(name),",
"= recordclass('losses', ('total_loss', 'NOC_loss', 'background_loss', 'NOC_mse')) self.ply_start = '''ply format ascii 1.0 element",
"zip(tensor, self.mean, self.std): t.mul_(s).add_(m) # The normalize code -> t.sub_(m).div_(s) return tensor class",
"batch_size = batch['num_points'].shape[0] # num_points[num_points == 0] = 1 # sub = torch.abs(output",
"1]] noc_gt = batch['noc_points'][pdx, :num[pdx, 0]].cpu().numpy() image = image.cpu().numpy().T image = image[:, [2,",
"[2, 1, 0]] * 255 output_arr = output_arr.cpu().numpy().T start = self.ply_start.format(num[pdx, 0].item()) concatenated_out",
"= batch['num_points'].shape[0] idx = idx * self.batch_size # masked_output = output[1] * (batch['mask_image']",
"foreground=False, test=False): output_image = output[0] if foreground: output_image = output[0][1] foreground = output[0][0]",
"= torch.optim.Adam(params=self.seg_net.parameters(), lr=lr, betas=betas) # self.optimizer = torch.optim.SGD(params=self.seg_net.parameters(), lr=lr, momentum=0.5) if checkpoint is",
"self.seg_net = UnetGenerator(input_nc=3, output_nc=3, num_downs=num_downs, # use_dropout=False, norm_layer=torch.nn.BatchNorm2d, # last_layer=nn.LeakyReLU(0.2)) self.foreground = False",
"batch['background']).long() * 2 - 1), niter=niter) write_image(writer, name=\"{}/Output_Foreground\".format(name), sample=((torch.softmax(foreground, 1)[:, 1:2, :, :]",
"# # # if 'mask_image' in batch.keys(): # masked_output = output * batch['mask_image']",
"return output, losses def train(self, batch): output, losses = self.forward(batch=batch) # output =",
"visualize(writer=test_writer, batch=batch, output=(output, self.loss_tuple(0, 0, 0, 0)), name=\"Validation\", niter=niter, foreground=self.foreground, test=True) def run(self,",
"batch['image'] = batch['image'] * 2 - 1 writer.train.add_scalar('PSNR', total_losses.NOC_mse, niter) torch.save({'epoch': epoch, 'model':",
"foreground=self.foreground) # batch['image'] = self.un_norm(batch['image']) # visualize(writer=writer.train, batch=batch, output=(output, loss), # name=\"Train\", niter=niter)",
"write_image(writer, name=\"{}/Input\".format(name), sample=batch['image'], niter=niter) if not test: write_image(writer, name=\"{}/Ground Truth NOC\".format(name), sample=batch['noc_image'], niter=niter)",
"std def __call__(self, tensor): \"\"\" Args: tensor (Tensor): Tensor image of size (C,",
"- 1, niter=niter) write_image(writer, name=\"{}/Input\".format(name), sample=batch['image'], niter=niter) if not test: write_image(writer, name=\"{}/Ground Truth",
"last_layer=nn.ReLU()) if model_type == 'res_unet': self.seg_net = ResUnet2HeadGenerator(output_nc=3, last_layer=nn.ReLU()) # self.seg_net = Unet2HeadGenerator(input_nc=3,",
"if 'mask_image' in batch.keys(): # masked_output = output * (batch['mask_image'] > 0).float() noc_loss",
"property float y property float z property uchar red property uchar green property",
"lr=lr, betas=betas) # self.optimizer = torch.optim.SGD(params=self.seg_net.parameters(), lr=lr, momentum=0.5) if checkpoint is not None:",
"os.path.exists(ply_dir): os.mkdir(ply_dir) with torch.no_grad(): self.seg_net.eval() for idx, batch in enumerate(test_loader): for keys in",
"- batch['background'][:, 0:2, :, :]).float() foreground[:, 0, :, :] = batch['background'][:, 0, :,",
"niter=(epoch + 1) * data_length) # self.test(test_loader=data_loader.test, test_writer=writer.test, niter=(epoch + 1) * data_length)",
"model_type='res', output_heads='two'): if output_heads == 'one': self.forward = self.forward_sparse self.seg_net = ResNetGenerator(out_channels=3, last_layer=nn.ReLU())",
"batch['yx_loc'][idx, :num[idx, 0], 0], batch['yx_loc'][idx, :num[idx, 0], 1]], noc_points) return sub / batch_size",
"batch['num_points'].shape[0] idx = idx * self.batch_size # masked_output = output[1] * (batch['mask_image'] >",
"= output * (batch['mask_image'] > 0).float() noc_loss = self.criterion_l1_sparse(output=output, batch=batch) total_loss += noc_loss",
":num[pdx, 0]].cpu().numpy() image = image.cpu().numpy().T image = image[:, [2, 1, 0]] * 255",
"image), axis=1) image = batch['image'][pdx, :, :, :].cpu().numpy() image = image.transpose(1, 2, 0)",
"= self.un_norm(batch['image']) batch['image'] = batch['image'] * 2 - 1 test_writer.add_scalar('PSNR', total_losses.NOC_mse, niter) visualize(writer=test_writer,",
"NOC_mse=mse) return output, losses def train(self, batch): output, losses = self.forward(batch=batch) # output",
"3: total_losses[jdx] += 10 * log10(1 / losses[jdx].item()) else: total_losses[jdx] += losses[jdx].item() #",
"0, 0)), name=\"Validation\", niter=niter, foreground=self.foreground, test=True) def run(self, opt, data_loader, writer, epoch=0): total_losses",
"# loss = self.l1(masked_output, batch['noc_image']) background_target = torch.zeros_like(output) background_loss = self.l1(output * batch['background'],",
"from recordclass import recordclass from torchstat import stat from math import log10 from",
"1), niter=niter) write_image(writer, name=\"{}/Output_Foreground\".format(name), sample=((torch.softmax(foreground, 1)[:, 1:2, :, :] > 0.5).long() * 2)",
"# if 'mask_image' in batch.keys(): # masked_output = output * (batch['mask_image'] > 0).float()",
"torch.zeros_like(output) background_loss = self.l1(output * batch['background'], background_target) total_loss += background_loss mse = self.criterion_mse(output=output,",
"batch, idx, ply_dir): batch_size = batch['num_points'].shape[0] idx = idx * self.batch_size # masked_output",
"batch['background'], background_target) total_loss += background_loss mse = self.criterion_mse(output=output, batch=batch) losses = self.loss_tuple(total_loss=total_loss, NOC_loss=noc_loss,",
"def train(self, batch): output, losses = self.forward(batch=batch) # output = self.seg_net(batch['image']) # #",
"loss = self.criterion_l1(output=masked_output, batch=batch) # l1_loss = self.loss_l1(masked_output, batch['noc_image']) / ( # torch.sum(batch['num_points'])",
"Train Loss: {}\".format(epoch, niter, losses.total_loss.item())) batch['image'] = batch['image'] * 2 - 1 visualize(writer=writer.train,",
"batch_size self.mean = mean self.std = std self.loss_tuple = recordclass('losses', ('total_loss', 'NOC_loss', 'background_loss',",
"'one': self.forward = self.forward_sparse self.seg_net = ResNetGenerator(out_channels=3, last_layer=nn.ReLU()) if model_type == 'res_unet': self.seg_net",
"def criterion_l1_sparse(self, output, batch): batch_size = batch['num_points'].shape[0] # num_points[num_points == 0] = 1",
"= output output_arr = out_arr[pdx, :, batch['yx_loc'][pdx, :num[pdx, 0], 0], batch['yx_loc'][pdx, :num[pdx, 0],",
":, :].cpu().numpy() image = image.transpose(1, 2, 0) * 255 cv2.imwrite(os.path.join(ply_dir, 'Output_{}.png'.format(idx + pdx)),",
"= np.concatenate((noc_gt, image), axis=1) image = batch['image'][pdx, :, :, :].cpu().numpy() image = image.transpose(1,",
"return True class UnNormalize(object): def __init__(self, mean, std): self.mean = mean self.std =",
"| Final Iteration: {} | Train Loss: {}\".format(epoch, niter, total_losses.total_loss)) batch['image'] = batch['image']",
"element vertex {} property float x property float y property float z property",
"output, losses def train(self, batch): output, losses = self.forward(batch=batch) # output = self.seg_net(batch['image'])",
"if write_ply: if not os.path.exists(ply_dir): os.mkdir(ply_dir) with torch.no_grad(): self.seg_net.eval() for idx, batch in",
"0, :, :] background_loss = self.bce(input=output[0], target=foreground) total_loss += background_loss mse = self.criterion_mse(output=output[1],",
"total_loss += noc_loss * 70 # print(torch.max(((1 - batch['background'][:, 0:1, :, :]) >",
"else: total_losses[jdx] += losses[jdx].item() # total_losses.total_loss += losses.total_loss.item() if idx == (len(test_loader) -",
"val in enumerate(total_losses): total_losses[jdx] /= len(test_loader) print(\"Validation loss: {}\".format(total_losses.total_loss)) # batch['image'] = self.un_norm(batch['image'])",
"keys in batch: batch[keys] = batch[keys].float().cuda() # batch['image'] = batch['image'] * 2 -",
"if jdx is 3: total_losses[jdx] += 10 * log10(1 / losses[jdx].item()) else: total_losses[jdx]",
"# use_dropout=False, norm_layer=torch.nn.BatchNorm2d, # last_layer=nn.LeakyReLU(0.2)) self.foreground = False elif output_heads == 'two': self.forward",
"# print(len(test_loader)) for jdx, val in enumerate(total_losses): total_losses[jdx] /= len(test_loader) print(\"Validation loss: {}\".format(total_losses.total_loss))",
"stat from math import log10 from models.networks import * from utils.common import *",
"pdx)), 'w') as write_file: write_file.write(start) np.savetxt(write_file, concatenated_out, fmt=' '.join(['%0.8f'] * 3 + ['%d']",
"name=\"{}/Output_Final_NOC\".format(name), sample=(final_noc * 2) - 1, niter=niter) writer.add_scalar('L1-Loss', output[1].total_loss, niter) writer.add_scalar('NOC-Loss', output[1].NOC_loss, niter)",
"output, losses = self.forward(batch=batch) # View NOC as PLY if write_ply: self.write_noc_ply(output=output, batch=batch,",
"# View NOC as PLY if write_ply: self.write_noc_ply(output=output, batch=batch, idx=idx, ply_dir=ply_dir) for jdx,",
"= batch['image'] * 2 - 1 visualize(writer=writer.train, batch=batch, output=(output, losses), name=\"Train Total\", niter=niter,",
"{} | Iteration: {} | Train Loss: {}\".format(epoch, niter, losses.total_loss.item())) batch['image'] = batch['image']",
"= self.lr for idx, batch in enumerate(data_loader.train): for keys in batch: batch[keys] =",
"= batch['noc_points'][pdx, :num[pdx, 0]].cpu().numpy() image = image.cpu().numpy().T image = image[:, [2, 1, 0]]",
"from utils.common import * def visualize(batch, output, writer, name, niter, foreground=False, test=False): output_image",
"# self.optimizer = torch.optim.SGD(params=self.seg_net.parameters(), lr=lr, momentum=0.5) if checkpoint is not None: checkpoint =",
"NOC as PLY if write_ply: self.write_noc_ply(output=output, batch=batch, idx=idx, ply_dir=ply_dir) for jdx, val in",
"Final Iteration: {} | Train Loss: {}\".format(epoch, niter, total_losses.total_loss)) batch['image'] = batch['image'] *",
"for keys in batch: batch[keys] = batch[keys].float().cuda() output, losses = self.forward(batch=batch) # View",
"# output = self.seg_net(batch['image']) # # # if 'mask_image' in batch.keys(): # masked_output",
"norm_layer=torch.nn.BatchNorm2d, # last_layer=nn.ReLU()) self.foreground = True else: self.foreground = None print(\"Error! Unknown number",
"('total_loss', 'NOC_loss', 'background_loss', 'NOC_mse')) self.ply_start = '''ply format ascii 1.0 element vertex {}",
"ResNet2HeadGenerator(out_channels=3, last_layer=nn.ReLU()) if model_type == 'res_unet': self.seg_net = ResUnet2HeadGenerator(output_nc=3, last_layer=nn.ReLU()) # self.seg_net =",
"property float z property uchar red property uchar green property uchar blue end_header\\n'''",
"in batch.keys(): # masked_output = output * (batch['mask_image'] > 0).float() noc_loss = self.criterion_l1_sparse(output=output,",
"model_type == 'res_unet': self.seg_net = ResUnet2HeadGenerator(output_nc=3, last_layer=nn.ReLU()) # self.seg_net = Unet2HeadGenerator(input_nc=3, output_nc=3, num_downs=num_downs,",
":, :, :].cpu().numpy() image = image.transpose(1, 2, 0) * 255 cv2.imwrite(os.path.join(ply_dir, 'Output_{}.png'.format(idx +",
"epoch % 15 == 0: self.lr *= 0.9 for param_group in self.optimizer.param_groups: param_group['lr']",
"== 0: batch_size -= 1 continue noc_points = batch['noc_points'][idx, :num[idx, 0], :] noc_points",
"self.std = std self.loss_tuple = recordclass('losses', ('total_loss', 'NOC_loss', 'background_loss', 'NOC_mse')) self.ply_start = '''ply",
"= self.forward(batch=batch) # output = self.seg_net(batch['image']) # # # if 'mask_image' in batch.keys():",
"total_losses = self.loss_tuple(0, 0, 0, 0) data_length = len(data_loader.train) self.seg_net.train() if epoch >",
"epoch > 0 and epoch % 15 == 0: self.lr *= 0.9 for",
"visualize(writer=writer.train, batch=batch, output=(output, total_losses), # name=\"Train Total\", niter=(epoch + 1) * data_length) #",
"* 2 - 1 test_writer.add_scalar('PSNR', total_losses.NOC_mse, niter) visualize(writer=test_writer, batch=batch, output=(output, total_losses), name=\"Validation\", niter=niter,",
"losses def forward_2_heads(self, batch): total_loss = 0 output = self.seg_net(batch['image']) # masked_output =",
"image = image.transpose(1, 2, 0) * 255 cv2.imwrite(os.path.join(ply_dir, 'Output_{}.png'.format(idx + pdx)), image.astype('uint8')) with",
"Tensor image of size (C, H, W) to be normalized. Returns: Tensor: Normalized",
"for jdx, val in enumerate(total_losses): total_losses[jdx] /= len(test_loader) print(\"Validation loss: {}\".format(total_losses.total_loss)) # batch['image']",
"output = self.seg_net(batch['image']) batch['image'] = batch['image'] * 2 - 1 visualize(writer=test_writer, batch=batch, output=(output,",
"* 2) - 1, niter=niter) final_noc = output_image * (torch.softmax(output[0][0], 1)[:, 1:2, :,",
"Iteration if idx == (data_length - 1): for jdx, val in enumerate(total_losses): total_losses[jdx]",
":, :] > 0.5).float() write_image(writer, name=\"{}/Output_Final_NOC\".format(name), sample=(final_noc * 2) - 1, niter=niter) writer.add_scalar('L1-Loss',",
"final_noc = output_image * (torch.softmax(output[0][0], 1)[:, 1:2, :, :] > 0.5).float() write_image(writer, name=\"{}/Output_Final_NOC\".format(name),",
"image), axis=1) concatenated_gt = np.concatenate((noc_gt, image), axis=1) image = batch['image'][pdx, :, :, :].cpu().numpy()",
"= image.cpu().numpy().T image = image[:, [2, 1, 0]] * 255 output_arr = output_arr.cpu().numpy().T",
"self.train(batch=batch) # print(batch['num_points'], torch.sum(batch['num_points'])) for jdx, val in enumerate(losses): if jdx is 3:",
"output_heads == 'one': self.forward = self.forward_sparse self.seg_net = ResNetGenerator(out_channels=3, last_layer=nn.ReLU()) if model_type ==",
"losses def train(self, batch): output, losses = self.forward(batch=batch) # output = self.seg_net(batch['image']) #",
"for keys in batch: batch[keys] = batch[keys].float().cuda() output = self.seg_net(batch['image']) batch['image'] = batch['image']",
"foreground=self.foreground, test=True) def run(self, opt, data_loader, writer, epoch=0): total_losses = self.loss_tuple(0, 0, 0,",
"= '''ply format ascii 1.0 element vertex {} property float x property float",
"of heads!\") exit(256) print(\"Using model {}.\".format(self.seg_net.__class__.__name__)) # self.seg_net.apply(init_weights) # stat(model=self.seg_net, input_size=(3, 256, 256))",
"data_length = len(data_loader.train) self.seg_net.train() if epoch > 0 and epoch % 15 ==",
"self.lr for idx, batch in enumerate(data_loader.train): for keys in batch: batch[keys] = batch[keys].float().cuda()",
"in batch: batch[keys] = batch[keys].float().cuda() output = self.seg_net(batch['image']) batch['image'] = batch['image'] * 2",
":num[idx, 0], 0], batch['yx_loc'][idx, :num[idx, 0], 1]], noc_points) return sub / batch_size def",
"== (data_length - 1): for jdx, val in enumerate(total_losses): total_losses[jdx] /= data_length print(\"Epoch:",
"data_length) self.validate(test_loader=data_loader.validate, test_writer=writer.validate, niter=(epoch + 1) * data_length + 1) print(\"*\" * 100)",
"batch['num_points'].long() num = batch['num_points'].view(batch_size, 1) for pdx in range(batch_size): image = batch['image'][pdx, :,",
"10 * log10(1 / losses[jdx].item()) else: total_losses[jdx] += losses[jdx].item() # total_losses.total_loss += losses.total_loss.item()",
"<reponame>ArvindSoma/HumanEstimation \"\"\" Train NOC class \"\"\" import os import cv2 from recordclass import",
"1 writer.train.add_scalar('PSNR', total_losses.NOC_mse, niter) torch.save({'epoch': epoch, 'model': self.seg_net.state_dict(), 'optimizer': self.optimizer.state_dict()}, os.path.join(self.save_path, 'save_{}.pth'.format(niter))) #",
"self.seg_net = ResNetGenerator(out_channels=3, last_layer=nn.ReLU()) if model_type == 'res_unet': self.seg_net = ResUnetGenerator(output_nc=3, last_layer=nn.ReLU()) #",
"batch['yx_loc'].long() sub = 0 for idx in range(batch_size): if num[idx, 0] == 0:",
"Unet2HeadGenerator(input_nc=3, output_nc=3, num_downs=num_downs, # use_dropout=False, norm_layer=torch.nn.BatchNorm2d, # last_layer=nn.ReLU()) self.foreground = True else: self.foreground",
"* 2 - 1 output, losses = self.train(batch=batch) # print(batch['num_points'], torch.sum(batch['num_points'])) for jdx,",
"total_losses), # name=\"Train Total\", niter=(epoch + 1) * data_length) # self.test(test_loader=data_loader.test, test_writer=writer.test, niter=(epoch",
"= batch['image'] * 2 - 1 visualize(writer=test_writer, batch=batch, output=(output, self.loss_tuple(0, 0, 0, 0)),",
"= None print(\"Error! Unknown number of heads!\") exit(256) print(\"Using model {}.\".format(self.seg_net.__class__.__name__)) # self.seg_net.apply(init_weights)",
"self.seg_net(batch['image']) # if 'mask_image' in batch.keys(): # masked_output = output * (batch['mask_image'] >",
"pdx)), 'w') as write_file: write_file.write(start) np.savetxt(write_file, concatenated_gt, fmt=' '.join(['%0.8f'] * 3 + ['%d']",
"return sub / batch_size def criterion_l1_sparse(self, output, batch): batch_size = batch['num_points'].shape[0] # num_points[num_points",
"None self.lr = lr self.optimizer = torch.optim.Adam(params=self.seg_net.parameters(), lr=lr, betas=betas) # self.optimizer = torch.optim.SGD(params=self.seg_net.parameters(),",
"mean self.std = std self.loss_tuple = recordclass('losses', ('total_loss', 'NOC_loss', 'background_loss', 'NOC_mse')) self.ply_start =",
"torch.nn.BCEWithLogitsLoss() self.seg_net.cuda() self.sparse_l1.cuda() self.l1.cuda() self.bce.cuda() self.seg_net.train() self.criterion_selection = None self.lr = lr self.optimizer",
"= self.criterion_mse(output=output[1], batch=batch) losses = self.loss_tuple(total_loss=total_loss, NOC_loss=noc_loss, background_loss=background_loss, NOC_mse=mse) return output, losses def",
"output_heads='two'): if output_heads == 'one': self.forward = self.forward_sparse self.seg_net = ResNetGenerator(out_channels=3, last_layer=nn.ReLU()) if",
"background_loss = self.bce(input=output[0], target=foreground) total_loss += background_loss mse = self.criterion_mse(output=output[1], batch=batch) losses =",
"sub_batch = sub_batch / (num_points * 3) batch['num_points'] = batch['num_points'].long() num = batch['num_points'].view(batch_size,",
"= output[0][1] foreground = output[0][0] write_image(writer, name=\"{}/Ground Truth Foreground\".format(name), sample=((1 - batch['background']).long() *",
"> 0 and epoch % 15 == 0: self.lr *= 0.9 for param_group",
"= std def __call__(self, tensor): \"\"\" Args: tensor (Tensor): Tensor image of size",
"blue end_header\\n''' self.un_norm = UnNormalize(mean=self.mean, std=self.std) def criterion_mse(self, output, batch): batch_size = batch['num_points'].shape[0]",
":] = batch['background'][:, 0, :, :] background_loss = self.bce(input=output[0], target=foreground) total_loss += background_loss",
"output * batch['mask_image'] # # loss = self.criterion_l1(output=masked_output, batch=batch) # l1_loss = self.loss_l1(masked_output,",
"0: self.lr *= 0.9 for param_group in self.optimizer.param_groups: param_group['lr'] = self.lr for idx,",
"os import cv2 from recordclass import recordclass from torchstat import stat from math",
"self.forward_2_heads self.seg_net = ResNet2HeadGenerator(out_channels=3, last_layer=nn.ReLU()) if model_type == 'res_unet': self.seg_net = ResUnet2HeadGenerator(output_nc=3, last_layer=nn.ReLU())",
"False elif output_heads == 'two': self.forward = self.forward_2_heads self.seg_net = ResNet2HeadGenerator(out_channels=3, last_layer=nn.ReLU()) if",
"= batch_size self.mean = mean self.std = std self.loss_tuple = recordclass('losses', ('total_loss', 'NOC_loss',",
"NOC_mse=mse) return output, losses def forward_2_heads(self, batch): total_loss = 0 output = self.seg_net(batch['image'])",
"70 # print(torch.max(((1 - batch['background'][:, 0:1, :, :]) > 0).float())) foreground = (1",
"niter=niter, foreground=self.foreground) # batch['image'] = self.un_norm(batch['image']) # visualize(writer=writer.train, batch=batch, output=(output, loss), # name=\"Train\",",
"= batch['image'][pdx, :, batch['yx_loc'][pdx, :num[pdx, 0], 0], batch['yx_loc'][pdx, :num[pdx, 0], 1]] if self.foreground:",
"= self.criterion_mse(output=output, batch=batch) losses = self.loss_tuple(total_loss=total_loss, NOC_loss=noc_loss, background_loss=background_loss, NOC_mse=mse) return output, losses def",
"print(\"Error! Unknown number of heads!\") exit(256) print(\"Using model {}.\".format(self.seg_net.__class__.__name__)) # self.seg_net.apply(init_weights) # stat(model=self.seg_net,",
"not None: checkpoint = torch.load(checkpoint) self.seg_net.load_state_dict(checkpoint['model']) self.optimizer.load_state_dict(checkpoint['optimizer']) self.save_path = os.path.join(\"../saves\", save_dir) if not",
"batch=batch) losses = self.loss_tuple(total_loss=total_loss, NOC_loss=noc_loss, background_loss=background_loss, NOC_mse=mse) return output, losses def train(self, batch):",
"t, m, s in zip(tensor, self.mean, self.std): t.mul_(s).add_(m) # The normalize code ->",
"torch.nn.MSELoss() self.bce = torch.nn.BCEWithLogitsLoss() self.seg_net.cuda() self.sparse_l1.cuda() self.l1.cuda() self.bce.cuda() self.seg_net.train() self.criterion_selection = None self.lr",
"0, 0, 0) data_length = len(data_loader.train) self.seg_net.train() if epoch > 0 and epoch",
"sub += self.l1(output[idx, :, batch['yx_loc'][idx, :num[idx, 0], 0], batch['yx_loc'][idx, :num[idx, 0], 1]], noc_points)",
"import stat from math import log10 from models.networks import * from utils.common import",
"True class UnNormalize(object): def __init__(self, mean, std): self.mean = mean self.std = std",
"norm_layer=torch.nn.BatchNorm2d, # last_layer=nn.LeakyReLU(0.2)) self.foreground = False elif output_heads == 'two': self.forward = self.forward_2_heads",
"0).float())) # self.optimizer.zero_grad() losses.total_loss.backward() self.optimizer.step() return output, losses def write_noc_ply(self, output, batch, idx,",
"output, losses def write_noc_ply(self, output, batch, idx, ply_dir): batch_size = batch['num_points'].shape[0] idx =",
"(num_points * 3) batch['num_points'] = batch['num_points'].long() num = batch['num_points'].view(batch_size, 1) batch['yx_loc'] = batch['yx_loc'].long()",
"code -> t.sub_(m).div_(s) return tensor class TrainNOCs: def __init__(self, save_dir='Trial', mean=(0.5, 0.5, 0.5),",
"write_image(writer, name=\"{}/Output_Final_NOC\".format(name), sample=(final_noc * 2) - 1, niter=niter) writer.add_scalar('L1-Loss', output[1].total_loss, niter) writer.add_scalar('NOC-Loss', output[1].NOC_loss,",
"val in enumerate(losses): if jdx is 3: total_losses[jdx] += 10 * log10(1 /",
"else: total_losses[jdx] += losses[jdx].item() # total_loss += loss.item() niter = idx + (epoch",
"* (batch['mask_image'] > 0).float() noc_loss = self.criterion_l1_sparse(output=output, batch=batch) total_loss += noc_loss * 10",
"masked_output = output[1] * (batch['mask_image'] > 0).float() noc_loss = self.criterion_l1_sparse(output=output[1], batch=batch) total_loss +=",
"output, losses def forward_2_heads(self, batch): total_loss = 0 output = self.seg_net(batch['image']) # masked_output",
"* 10 # loss = self.l1(masked_output, batch['noc_image']) background_target = torch.zeros_like(output) background_loss = self.l1(output",
"= self.l1(output * batch['background'], background_target) total_loss += background_loss mse = self.criterion_mse(output=output, batch=batch) losses",
"3 + ['%d'] * 3)) with open(os.path.join(ply_dir, 'Ground_truth_{}.ply'.format(idx + pdx)), 'w') as write_file:",
"= batch['image'] * 2 - 1 writer.train.add_scalar('PSNR', total_losses.NOC_mse, niter) torch.save({'epoch': epoch, 'model': self.seg_net.state_dict(),",
"criterion_mse(self, output, batch): batch_size = batch['num_points'].shape[0] batch['num_points'] = batch['num_points'].long() num = batch['num_points'].view(batch_size, 1)",
"math import log10 from models.networks import * from utils.common import * def visualize(batch,",
"# self.optimizer.zero_grad() losses.total_loss.backward() self.optimizer.step() return output, losses def write_noc_ply(self, output, batch, idx, ply_dir):",
"niter) torch.save({'epoch': epoch, 'model': self.seg_net.state_dict(), 'optimizer': self.optimizer.state_dict()}, os.path.join(self.save_path, 'save_{}.pth'.format(niter))) # visualize(writer=writer.train, batch=batch, output=(output,",
"if not test: write_image(writer, name=\"{}/Ground Truth NOC\".format(name), sample=batch['noc_image'], niter=niter) return True class UnNormalize(object):",
"background_loss=background_loss, NOC_mse=mse) return output, losses def train(self, batch): output, losses = self.forward(batch=batch) #",
"niter=niter) writer.add_scalar('L1-Loss', output[1].total_loss, niter) writer.add_scalar('NOC-Loss', output[1].NOC_loss, niter) writer.add_scalar('Background-Loss', output[1].background_loss, niter) write_image(writer, name=\"{}/Output_NOC\".format(name), sample=(output_image",
"run(self, opt, data_loader, writer, epoch=0): total_losses = self.loss_tuple(0, 0, 0, 0) data_length =",
"continue noc_points = batch['noc_points'][idx, :num[idx, 0], :] noc_points = torch.transpose(noc_points, 0, 1) sub",
"noc_points) return sub / batch_size def criterion_l1_sparse(self, output, batch): batch_size = batch['num_points'].shape[0] #",
"= output * batch['mask_image'] # # loss = self.criterion_l1(output=masked_output, batch=batch) # l1_loss =",
"W) to be normalized. Returns: Tensor: Normalized image. \"\"\" for t, m, s",
"self.l2(output[idx, :, batch['yx_loc'][idx, :num[idx, 0], 0], batch['yx_loc'][idx, :num[idx, 0], 1]], noc_points) return sub",
"self.seg_net = ResNet2HeadGenerator(out_channels=3, last_layer=nn.ReLU()) if model_type == 'res_unet': self.seg_net = ResUnet2HeadGenerator(output_nc=3, last_layer=nn.ReLU()) #",
"print(len(test_loader)) for jdx, val in enumerate(total_losses): total_losses[jdx] /= len(test_loader) print(\"Validation loss: {}\".format(total_losses.total_loss)) #",
"concatenated_gt = np.concatenate((noc_gt, image), axis=1) image = batch['image'][pdx, :, :, :].cpu().numpy() image =",
"idx % opt.log_iter == 0: print(\"Epoch: {} | Iteration: {} | Train Loss:",
"= torch.optim.SGD(params=self.seg_net.parameters(), lr=lr, momentum=0.5) if checkpoint is not None: checkpoint = torch.load(checkpoint) self.seg_net.load_state_dict(checkpoint['model'])",
"jdx, val in enumerate(losses): if jdx is 3: total_losses[jdx] += 10 * log10(1",
"{}.\".format(self.seg_net.__class__.__name__)) # self.seg_net.apply(init_weights) # stat(model=self.seg_net, input_size=(3, 256, 256)) self.sparse_l1 = torch.nn.SmoothL1Loss(reduction='none') self.l1 =",
"s in zip(tensor, self.mean, self.std): t.mul_(s).add_(m) # The normalize code -> t.sub_(m).div_(s) return",
"= self.loss_tuple(total_loss=total_loss, NOC_loss=noc_loss, background_loss=background_loss, NOC_mse=mse) return output, losses def train(self, batch): output, losses",
"self.criterion_l1_sparse(output=output[1], batch=batch) total_loss += noc_loss * 70 # print(torch.max(((1 - batch['background'][:, 0:1, :,",
"= UnetGenerator(input_nc=3, output_nc=3, num_downs=num_downs, # use_dropout=False, norm_layer=torch.nn.BatchNorm2d, # last_layer=nn.LeakyReLU(0.2)) self.foreground = False elif",
"batch['num_points'].long() num = batch['num_points'].view(batch_size, 1) batch['yx_loc'] = batch['yx_loc'].long() sub = 0 for idx",
"output[0][0] write_image(writer, name=\"{}/Ground Truth Foreground\".format(name), sample=((1 - batch['background']).long() * 2 - 1), niter=niter)",
"def write_noc_ply(self, output, batch, idx, ply_dir): batch_size = batch['num_points'].shape[0] idx = idx *",
"np.savetxt(write_file, concatenated_out, fmt=' '.join(['%0.8f'] * 3 + ['%d'] * 3)) with open(os.path.join(ply_dir, 'Ground_truth_{}.ply'.format(idx",
"output_arr = output_arr.cpu().numpy().T start = self.ply_start.format(num[pdx, 0].item()) concatenated_out = np.concatenate((output_arr, image), axis=1) concatenated_gt",
"data_loader, writer, epoch=0): total_losses = self.loss_tuple(0, 0, 0, 0) data_length = len(data_loader.train) self.seg_net.train()",
"= torch.nn.MSELoss() self.bce = torch.nn.BCEWithLogitsLoss() self.seg_net.cuda() self.sparse_l1.cuda() self.l1.cuda() self.bce.cuda() self.seg_net.train() self.criterion_selection = None",
"sample=batch['image'], niter=niter) if not test: write_image(writer, name=\"{}/Ground Truth NOC\".format(name), sample=batch['noc_image'], niter=niter) return True",
"for pdx in range(batch_size): image = batch['image'][pdx, :, batch['yx_loc'][pdx, :num[pdx, 0], 0], batch['yx_loc'][pdx,",
"# batch['image'] = self.un_norm(batch['image']) # visualize(writer=writer.train, batch=batch, output=(output, loss), # name=\"Train\", niter=niter) #",
"* (torch.sum(batch['num_points'] == 0).float())) # self.optimizer.zero_grad() losses.total_loss.backward() self.optimizer.step() return output, losses def write_noc_ply(self,",
"niter=(epoch + 1) * data_length) self.validate(test_loader=data_loader.validate, test_writer=writer.validate, niter=(epoch + 1) * data_length +",
"y property float z property uchar red property uchar green property uchar blue",
"self.foreground = True else: self.foreground = None print(\"Error! Unknown number of heads!\") exit(256)",
"0: batch_size -= 1 continue noc_points = batch['noc_points'][idx, :num[idx, 0], :] noc_points =",
"if output_heads == 'one': self.forward = self.forward_sparse self.seg_net = ResNetGenerator(out_channels=3, last_layer=nn.ReLU()) if model_type",
"self.optimizer.load_state_dict(checkpoint['optimizer']) self.save_path = os.path.join(\"../saves\", save_dir) if not os.path.exists(self.save_path): os.mkdir(self.save_path) self.batch_size = batch_size self.mean",
":, :]).float() foreground[:, 0, :, :] = batch['background'][:, 0, :, :] background_loss =",
"255 output_arr = output_arr.cpu().numpy().T start = self.ply_start.format(num[pdx, 0].item()) concatenated_out = np.concatenate((output_arr, image), axis=1)",
"in range(batch_size): image = batch['image'][pdx, :, batch['yx_loc'][pdx, :num[pdx, 0], 0], batch['yx_loc'][pdx, :num[pdx, 0],",
"in zip(tensor, self.mean, self.std): t.mul_(s).add_(m) # The normalize code -> t.sub_(m).div_(s) return tensor",
"'.join(['%0.8f'] * 3 + ['%d'] * 3)) def validate(self, test_loader, niter, test_writer, write_ply=False,",
"save_dir='Trial', mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), num_downs=5, lr=2e-4, betas=(0.5, 0.999), batch_size=8, checkpoint=None,",
"output_image = output[0][1] foreground = output[0][0] write_image(writer, name=\"{}/Ground Truth Foreground\".format(name), sample=((1 - batch['background']).long()",
"* 3)) with open(os.path.join(ply_dir, 'Ground_truth_{}.ply'.format(idx + pdx)), 'w') as write_file: write_file.write(start) np.savetxt(write_file, concatenated_gt,",
"torch.save({'epoch': epoch, 'model': self.seg_net.state_dict(), 'optimizer': self.optimizer.state_dict()}, os.path.join(self.save_path, 'save_{}.pth'.format(niter))) # visualize(writer=writer.train, batch=batch, output=(output, total_losses),",
"write_image(writer, name=\"{}/Output_NOC\".format(name), sample=(output_image * 2) - 1, niter=niter) write_image(writer, name=\"{}/Input\".format(name), sample=batch['image'], niter=niter) if",
"batch['yx_loc'][idx, :num[idx, 0], 1]], noc_points) return sub / batch_size def forward_sparse(self, batch): total_loss",
"batch['image'][pdx, :, batch['yx_loc'][pdx, :num[pdx, 0], 0], batch['yx_loc'][pdx, :num[pdx, 0], 1]] if self.foreground: out_arr",
"self.forward = self.forward_sparse self.seg_net = ResNetGenerator(out_channels=3, last_layer=nn.ReLU()) if model_type == 'res_unet': self.seg_net =",
"= Unet2HeadGenerator(input_nc=3, output_nc=3, num_downs=num_downs, # use_dropout=False, norm_layer=torch.nn.BatchNorm2d, # last_layer=nn.ReLU()) self.foreground = True else:",
"self.criterion_selection = None self.lr = lr self.optimizer = torch.optim.Adam(params=self.seg_net.parameters(), lr=lr, betas=betas) # self.optimizer",
"losses def write_noc_ply(self, output, batch, idx, ply_dir): batch_size = batch['num_points'].shape[0] idx = idx",
"last_layer=nn.ReLU()) # self.seg_net = Unet2HeadGenerator(input_nc=3, output_nc=3, num_downs=num_downs, # use_dropout=False, norm_layer=torch.nn.BatchNorm2d, # last_layer=nn.ReLU()) self.foreground",
"sub_batch = torch.sum(sub, dim=(1, 2, 3)) # sub_batch = sub_batch / (num_points *",
"torch.transpose(noc_points, 0, 1) sub += self.l2(output[idx, :, batch['yx_loc'][idx, :num[idx, 0], 0], batch['yx_loc'][idx, :num[idx,",
"import cv2 from recordclass import recordclass from torchstat import stat from math import",
"last_layer=nn.ReLU()) if model_type == 'res_unet': self.seg_net = ResUnetGenerator(output_nc=3, last_layer=nn.ReLU()) # self.seg_net = UnetGenerator(input_nc=3,",
"write_noc_ply(self, output, batch, idx, ply_dir): batch_size = batch['num_points'].shape[0] idx = idx * self.batch_size",
"noc_gt = batch['noc_points'][pdx, :num[pdx, 0]].cpu().numpy() image = image.cpu().numpy().T image = image[:, [2, 1,",
"visualize(writer=test_writer, batch=batch, output=(output, total_losses), name=\"Validation\", niter=niter, foreground=self.foreground) def test(self, test_loader, niter, test_writer): with",
"recordclass import recordclass from torchstat import stat from math import log10 from models.networks",
"torch.nn.SmoothL1Loss() self.l2 = torch.nn.MSELoss() self.bce = torch.nn.BCEWithLogitsLoss() self.seg_net.cuda() self.sparse_l1.cuda() self.l1.cuda() self.bce.cuda() self.seg_net.train() self.criterion_selection",
"0].item()) concatenated_out = np.concatenate((output_arr, image), axis=1) concatenated_gt = np.concatenate((noc_gt, image), axis=1) image =",
"enumerate(data_loader.train): for keys in batch: batch[keys] = batch[keys].float().cuda() # batch['image'] = batch['image'] *",
"'NOC_loss', 'background_loss', 'NOC_mse')) self.ply_start = '''ply format ascii 1.0 element vertex {} property",
"num_downs=num_downs, # use_dropout=False, norm_layer=torch.nn.BatchNorm2d, # last_layer=nn.ReLU()) self.foreground = True else: self.foreground = None",
"* log10(1 / losses[jdx].item()) else: total_losses[jdx] += losses[jdx].item() # total_losses.total_loss += losses.total_loss.item() if",
"size (C, H, W) to be normalized. Returns: Tensor: Normalized image. \"\"\" for",
"0, 0) if write_ply: if not os.path.exists(ply_dir): os.mkdir(ply_dir) with torch.no_grad(): self.seg_net.eval() for idx,",
"enumerate(losses): if jdx is 3: total_losses[jdx] += 10 * log10(1 / losses[jdx].item()) else:",
"len(data_loader.train) self.seg_net.train() if epoch > 0 and epoch % 15 == 0: self.lr",
"255 cv2.imwrite(os.path.join(ply_dir, 'Output_{}.png'.format(idx + pdx)), image.astype('uint8')) with open(os.path.join(ply_dir, 'Output_{}.ply'.format(idx + pdx)), 'w') as",
"for keys in batch: batch[keys] = batch[keys].float().cuda() # batch['image'] = batch['image'] * 2",
"dim=(1, 2, 3)) # sub_batch = sub_batch / (num_points * 3) batch['num_points'] =",
"= self.loss_tuple(0, 0, 0, 0) if write_ply: if not os.path.exists(ply_dir): os.mkdir(ply_dir) with torch.no_grad():",
"= self.criterion_l1_sparse(output=output, batch=batch) total_loss += noc_loss * 10 # loss = self.l1(masked_output, batch['noc_image'])",
"num = batch['num_points'].view(batch_size, 1) batch['yx_loc'] = batch['yx_loc'].long() sub = 0 for idx in",
"self.save_path = os.path.join(\"../saves\", save_dir) if not os.path.exists(self.save_path): os.mkdir(self.save_path) self.batch_size = batch_size self.mean =",
"ply_dir): batch_size = batch['num_points'].shape[0] idx = idx * self.batch_size # masked_output = output[1]",
"* 3 + ['%d'] * 3)) with open(os.path.join(ply_dir, 'Ground_truth_{}.ply'.format(idx + pdx)), 'w') as",
"image. \"\"\" for t, m, s in zip(tensor, self.mean, self.std): t.mul_(s).add_(m) # The",
"to be normalized. Returns: Tensor: Normalized image. \"\"\" for t, m, s in",
"forward_2_heads(self, batch): total_loss = 0 output = self.seg_net(batch['image']) # masked_output = output[1] *",
"batch['num_points'].view(batch_size, 1) for pdx in range(batch_size): image = batch['image'][pdx, :, batch['yx_loc'][pdx, :num[pdx, 0],",
"2 - 1 test_writer.add_scalar('PSNR', total_losses.NOC_mse, niter) visualize(writer=test_writer, batch=batch, output=(output, total_losses), name=\"Validation\", niter=niter, foreground=self.foreground)",
"0.5, 0.5), num_downs=5, lr=2e-4, betas=(0.5, 0.999), batch_size=8, checkpoint=None, model_type='res', output_heads='two'): if output_heads ==",
"total_losses), name=\"Validation\", niter=niter, foreground=self.foreground) def test(self, test_loader, niter, test_writer): with torch.no_grad(): self.seg_net.eval() for",
"+= loss.item() niter = idx + (epoch * data_length) if idx % opt.log_iter",
"> 0.5).float() write_image(writer, name=\"{}/Output_Final_NOC\".format(name), sample=(final_noc * 2) - 1, niter=niter) writer.add_scalar('L1-Loss', output[1].total_loss, niter)",
"total_losses[jdx] += losses[jdx].item() # total_losses.total_loss += losses.total_loss.item() if idx == (len(test_loader) - 1):",
"= batch['noc_points'][idx, :num[idx, 0], :] noc_points = torch.transpose(noc_points, 0, 1) sub += self.l1(output[idx,",
"# last_layer=nn.ReLU()) self.foreground = True else: self.foreground = None print(\"Error! Unknown number of",
"target) # sub = self.sparse_l1(output, target) # sub_batch = torch.sum(sub, dim=(1, 2, 3))",
"save_dir) if not os.path.exists(self.save_path): os.mkdir(self.save_path) self.batch_size = batch_size self.mean = mean self.std =",
"= std self.loss_tuple = recordclass('losses', ('total_loss', 'NOC_loss', 'background_loss', 'NOC_mse')) self.ply_start = '''ply format",
"self.batch_size # masked_output = output[1] * (batch['mask_image'] > 0).float() batch['num_points'] = batch['num_points'].long() num",
"'NOC_mse')) self.ply_start = '''ply format ascii 1.0 element vertex {} property float x",
"losses = self.train(batch=batch) # print(batch['num_points'], torch.sum(batch['num_points'])) for jdx, val in enumerate(losses): if jdx",
"# name=\"Train\", niter=niter) # Last Iteration if idx == (data_length - 1): for",
"* 3)) def validate(self, test_loader, niter, test_writer, write_ply=False, ply_dir=''): total_losses = self.loss_tuple(0, 0,",
"= 0 output = self.seg_net(batch['image']) # if 'mask_image' in batch.keys(): # masked_output =",
"* data_length) if idx % opt.log_iter == 0: print(\"Epoch: {} | Iteration: {}",
"2 - 1 writer.train.add_scalar('PSNR', total_losses.NOC_mse, niter) torch.save({'epoch': epoch, 'model': self.seg_net.state_dict(), 'optimizer': self.optimizer.state_dict()}, os.path.join(self.save_path,",
"= self.seg_net(batch['image']) # # # if 'mask_image' in batch.keys(): # masked_output = output",
"= image[:, [2, 1, 0]] * 255 output_arr = output_arr.cpu().numpy().T start = self.ply_start.format(num[pdx,",
"os.mkdir(ply_dir) with torch.no_grad(): self.seg_net.eval() for idx, batch in enumerate(test_loader): for keys in batch:",
"1 visualize(writer=test_writer, batch=batch, output=(output, self.loss_tuple(0, 0, 0, 0)), name=\"Validation\", niter=niter, foreground=self.foreground, test=True) def",
"0] == 0: batch_size -= 1 continue noc_points = batch['noc_points'][idx, :num[idx, 0], :]",
"batch['image'] * 2 - 1 writer.train.add_scalar('PSNR', total_losses.NOC_mse, niter) torch.save({'epoch': epoch, 'model': self.seg_net.state_dict(), 'optimizer':",
"batch['yx_loc'][idx, :num[idx, 0], 1]], noc_points) return sub / batch_size def criterion_l1_sparse(self, output, batch):",
"class \"\"\" import os import cv2 from recordclass import recordclass from torchstat import",
"batch['num_points'] = batch['num_points'].long() num = batch['num_points'].view(batch_size, 1) for pdx in range(batch_size): image =",
"total_losses.total_loss)) batch['image'] = batch['image'] * 2 - 1 writer.train.add_scalar('PSNR', total_losses.NOC_mse, niter) torch.save({'epoch': epoch,",
"10 * log10(1 / losses[jdx].item()) else: total_losses[jdx] += losses[jdx].item() # total_loss += loss.item()",
"== 'two': self.forward = self.forward_2_heads self.seg_net = ResNet2HeadGenerator(out_channels=3, last_layer=nn.ReLU()) if model_type == 'res_unet':",
"self.criterion_mse(output=output, batch=batch) losses = self.loss_tuple(total_loss=total_loss, NOC_loss=noc_loss, background_loss=background_loss, NOC_mse=mse) return output, losses def forward_2_heads(self,",
"def __init__(self, save_dir='Trial', mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), num_downs=5, lr=2e-4, betas=(0.5, 0.999),",
"writer, name, niter, foreground=False, test=False): output_image = output[0] if foreground: output_image = output[0][1]",
"= self.loss_tuple(total_loss=total_loss, NOC_loss=noc_loss, background_loss=background_loss, NOC_mse=mse) return output, losses def forward_2_heads(self, batch): total_loss =",
"* 2 - 1), niter=niter) write_image(writer, name=\"{}/Output_Foreground\".format(name), sample=((torch.softmax(foreground, 1)[:, 1:2, :, :] >",
"self.lr *= 0.9 for param_group in self.optimizer.param_groups: param_group['lr'] = self.lr for idx, batch",
"self.optimizer.param_groups: param_group['lr'] = self.lr for idx, batch in enumerate(data_loader.train): for keys in batch:",
"batch[keys].float().cuda() # batch['image'] = batch['image'] * 2 - 1 output, losses = self.train(batch=batch)",
"in batch: batch[keys] = batch[keys].float().cuda() # batch['image'] = batch['image'] * 2 - 1",
"0: print(\"Epoch: {} | Iteration: {} | Train Loss: {}\".format(epoch, niter, losses.total_loss.item())) batch['image']",
"- 1 visualize(writer=writer.train, batch=batch, output=(output, losses), name=\"Train Total\", niter=niter, foreground=self.foreground) # batch['image'] =",
"3)) def validate(self, test_loader, niter, test_writer, write_ply=False, ply_dir=''): total_losses = self.loss_tuple(0, 0, 0,",
"+ 1) * data_length) self.validate(test_loader=data_loader.validate, test_writer=writer.validate, niter=(epoch + 1) * data_length + 1)",
"= batch[keys].float().cuda() output, losses = self.forward(batch=batch) # View NOC as PLY if write_ply:"
] |
[
"<gh_stars>0 from .ngram import ngram from .lda import lda from .tfidf import tfidf"
] |
[
"import logging import os from typing import Literal, Union from ghaudit.cli import cli",
"root = logging.getLogger() root.setLevel(LOGLEVEL) root.addHandler(handler) else: logging.basicConfig(level=LOGLEVEL, format=LOG_FORMAT, style=STYLE) # pylint: disable=no-value-for-parameter cli()",
"typing import Literal, Union from ghaudit.cli import cli LOGFILE = os.environ.get(\"LOGFILE\") LOGLEVEL =",
"from ghaudit.cli import cli LOGFILE = os.environ.get(\"LOGFILE\") LOGLEVEL = os.environ.get(\"LOGLEVEL\", \"ERROR\") # pylint:",
"\"ERROR\") # pylint: disable=line-too-long LOG_FORMAT = \"{asctime} {levelname:8s} ghaudit <{filename}:{lineno} {module}.{funcName}> {message}\" #",
"def main() -> None: if LOGFILE: handler = logging.FileHandler(LOGFILE) formatter = logging.Formatter(LOG_FORMAT, style=STYLE)",
"None: if LOGFILE: handler = logging.FileHandler(LOGFILE) formatter = logging.Formatter(LOG_FORMAT, style=STYLE) handler.setFormatter(formatter) root =",
"import Literal, Union from ghaudit.cli import cli LOGFILE = os.environ.get(\"LOGFILE\") LOGLEVEL = os.environ.get(\"LOGLEVEL\",",
"= logging.getLogger() root.setLevel(LOGLEVEL) root.addHandler(handler) else: logging.basicConfig(level=LOGLEVEL, format=LOG_FORMAT, style=STYLE) # pylint: disable=no-value-for-parameter cli() if",
"logging import os from typing import Literal, Union from ghaudit.cli import cli LOGFILE",
"= \"{\" # type: Union[Literal[\"%\"], Literal[\"{\"], Literal[\"$\"]] def main() -> None: if LOGFILE:",
"import os from typing import Literal, Union from ghaudit.cli import cli LOGFILE =",
"from typing import Literal, Union from ghaudit.cli import cli LOGFILE = os.environ.get(\"LOGFILE\") LOGLEVEL",
"Union[Literal[\"%\"], Literal[\"{\"], Literal[\"$\"]] def main() -> None: if LOGFILE: handler = logging.FileHandler(LOGFILE) formatter",
"cli LOGFILE = os.environ.get(\"LOGFILE\") LOGLEVEL = os.environ.get(\"LOGLEVEL\", \"ERROR\") # pylint: disable=line-too-long LOG_FORMAT =",
"LOGFILE = os.environ.get(\"LOGFILE\") LOGLEVEL = os.environ.get(\"LOGLEVEL\", \"ERROR\") # pylint: disable=line-too-long LOG_FORMAT = \"{asctime}",
"logging.getLogger() root.setLevel(LOGLEVEL) root.addHandler(handler) else: logging.basicConfig(level=LOGLEVEL, format=LOG_FORMAT, style=STYLE) # pylint: disable=no-value-for-parameter cli() if __name__",
"{module}.{funcName}> {message}\" # noqa: E501 STYLE = \"{\" # type: Union[Literal[\"%\"], Literal[\"{\"], Literal[\"$\"]]",
"\"{\" # type: Union[Literal[\"%\"], Literal[\"{\"], Literal[\"$\"]] def main() -> None: if LOGFILE: handler",
"Literal, Union from ghaudit.cli import cli LOGFILE = os.environ.get(\"LOGFILE\") LOGLEVEL = os.environ.get(\"LOGLEVEL\", \"ERROR\")",
"LOGLEVEL = os.environ.get(\"LOGLEVEL\", \"ERROR\") # pylint: disable=line-too-long LOG_FORMAT = \"{asctime} {levelname:8s} ghaudit <{filename}:{lineno}",
"\"{asctime} {levelname:8s} ghaudit <{filename}:{lineno} {module}.{funcName}> {message}\" # noqa: E501 STYLE = \"{\" #",
"logging.FileHandler(LOGFILE) formatter = logging.Formatter(LOG_FORMAT, style=STYLE) handler.setFormatter(formatter) root = logging.getLogger() root.setLevel(LOGLEVEL) root.addHandler(handler) else: logging.basicConfig(level=LOGLEVEL,",
"E501 STYLE = \"{\" # type: Union[Literal[\"%\"], Literal[\"{\"], Literal[\"$\"]] def main() -> None:",
"handler.setFormatter(formatter) root = logging.getLogger() root.setLevel(LOGLEVEL) root.addHandler(handler) else: logging.basicConfig(level=LOGLEVEL, format=LOG_FORMAT, style=STYLE) # pylint: disable=no-value-for-parameter",
"disable=line-too-long LOG_FORMAT = \"{asctime} {levelname:8s} ghaudit <{filename}:{lineno} {module}.{funcName}> {message}\" # noqa: E501 STYLE",
"os.environ.get(\"LOGFILE\") LOGLEVEL = os.environ.get(\"LOGLEVEL\", \"ERROR\") # pylint: disable=line-too-long LOG_FORMAT = \"{asctime} {levelname:8s} ghaudit",
"{message}\" # noqa: E501 STYLE = \"{\" # type: Union[Literal[\"%\"], Literal[\"{\"], Literal[\"$\"]] def",
"Literal[\"{\"], Literal[\"$\"]] def main() -> None: if LOGFILE: handler = logging.FileHandler(LOGFILE) formatter =",
"os.environ.get(\"LOGLEVEL\", \"ERROR\") # pylint: disable=line-too-long LOG_FORMAT = \"{asctime} {levelname:8s} ghaudit <{filename}:{lineno} {module}.{funcName}> {message}\"",
"style=STYLE) handler.setFormatter(formatter) root = logging.getLogger() root.setLevel(LOGLEVEL) root.addHandler(handler) else: logging.basicConfig(level=LOGLEVEL, format=LOG_FORMAT, style=STYLE) # pylint:",
"-> None: if LOGFILE: handler = logging.FileHandler(LOGFILE) formatter = logging.Formatter(LOG_FORMAT, style=STYLE) handler.setFormatter(formatter) root",
"type: Union[Literal[\"%\"], Literal[\"{\"], Literal[\"$\"]] def main() -> None: if LOGFILE: handler = logging.FileHandler(LOGFILE)",
"LOG_FORMAT = \"{asctime} {levelname:8s} ghaudit <{filename}:{lineno} {module}.{funcName}> {message}\" # noqa: E501 STYLE =",
"else: logging.basicConfig(level=LOGLEVEL, format=LOG_FORMAT, style=STYLE) # pylint: disable=no-value-for-parameter cli() if __name__ == \"__main__\": main()",
"Literal[\"$\"]] def main() -> None: if LOGFILE: handler = logging.FileHandler(LOGFILE) formatter = logging.Formatter(LOG_FORMAT,",
"= os.environ.get(\"LOGFILE\") LOGLEVEL = os.environ.get(\"LOGLEVEL\", \"ERROR\") # pylint: disable=line-too-long LOG_FORMAT = \"{asctime} {levelname:8s}",
"STYLE = \"{\" # type: Union[Literal[\"%\"], Literal[\"{\"], Literal[\"$\"]] def main() -> None: if",
"= logging.Formatter(LOG_FORMAT, style=STYLE) handler.setFormatter(formatter) root = logging.getLogger() root.setLevel(LOGLEVEL) root.addHandler(handler) else: logging.basicConfig(level=LOGLEVEL, format=LOG_FORMAT, style=STYLE)",
"# pylint: disable=line-too-long LOG_FORMAT = \"{asctime} {levelname:8s} ghaudit <{filename}:{lineno} {module}.{funcName}> {message}\" # noqa:",
"# type: Union[Literal[\"%\"], Literal[\"{\"], Literal[\"$\"]] def main() -> None: if LOGFILE: handler =",
"logging.Formatter(LOG_FORMAT, style=STYLE) handler.setFormatter(formatter) root = logging.getLogger() root.setLevel(LOGLEVEL) root.addHandler(handler) else: logging.basicConfig(level=LOGLEVEL, format=LOG_FORMAT, style=STYLE) #",
"= os.environ.get(\"LOGLEVEL\", \"ERROR\") # pylint: disable=line-too-long LOG_FORMAT = \"{asctime} {levelname:8s} ghaudit <{filename}:{lineno} {module}.{funcName}>",
"= \"{asctime} {levelname:8s} ghaudit <{filename}:{lineno} {module}.{funcName}> {message}\" # noqa: E501 STYLE = \"{\"",
"handler = logging.FileHandler(LOGFILE) formatter = logging.Formatter(LOG_FORMAT, style=STYLE) handler.setFormatter(formatter) root = logging.getLogger() root.setLevel(LOGLEVEL) root.addHandler(handler)",
"Union from ghaudit.cli import cli LOGFILE = os.environ.get(\"LOGFILE\") LOGLEVEL = os.environ.get(\"LOGLEVEL\", \"ERROR\") #",
"noqa: E501 STYLE = \"{\" # type: Union[Literal[\"%\"], Literal[\"{\"], Literal[\"$\"]] def main() ->",
"# noqa: E501 STYLE = \"{\" # type: Union[Literal[\"%\"], Literal[\"{\"], Literal[\"$\"]] def main()",
"ghaudit.cli import cli LOGFILE = os.environ.get(\"LOGFILE\") LOGLEVEL = os.environ.get(\"LOGLEVEL\", \"ERROR\") # pylint: disable=line-too-long",
"ghaudit <{filename}:{lineno} {module}.{funcName}> {message}\" # noqa: E501 STYLE = \"{\" # type: Union[Literal[\"%\"],",
"main() -> None: if LOGFILE: handler = logging.FileHandler(LOGFILE) formatter = logging.Formatter(LOG_FORMAT, style=STYLE) handler.setFormatter(formatter)",
"{levelname:8s} ghaudit <{filename}:{lineno} {module}.{funcName}> {message}\" # noqa: E501 STYLE = \"{\" # type:",
"formatter = logging.Formatter(LOG_FORMAT, style=STYLE) handler.setFormatter(formatter) root = logging.getLogger() root.setLevel(LOGLEVEL) root.addHandler(handler) else: logging.basicConfig(level=LOGLEVEL, format=LOG_FORMAT,",
"os from typing import Literal, Union from ghaudit.cli import cli LOGFILE = os.environ.get(\"LOGFILE\")",
"root.setLevel(LOGLEVEL) root.addHandler(handler) else: logging.basicConfig(level=LOGLEVEL, format=LOG_FORMAT, style=STYLE) # pylint: disable=no-value-for-parameter cli() if __name__ ==",
"LOGFILE: handler = logging.FileHandler(LOGFILE) formatter = logging.Formatter(LOG_FORMAT, style=STYLE) handler.setFormatter(formatter) root = logging.getLogger() root.setLevel(LOGLEVEL)",
"root.addHandler(handler) else: logging.basicConfig(level=LOGLEVEL, format=LOG_FORMAT, style=STYLE) # pylint: disable=no-value-for-parameter cli() if __name__ == \"__main__\":",
"import cli LOGFILE = os.environ.get(\"LOGFILE\") LOGLEVEL = os.environ.get(\"LOGLEVEL\", \"ERROR\") # pylint: disable=line-too-long LOG_FORMAT",
"pylint: disable=line-too-long LOG_FORMAT = \"{asctime} {levelname:8s} ghaudit <{filename}:{lineno} {module}.{funcName}> {message}\" # noqa: E501",
"<{filename}:{lineno} {module}.{funcName}> {message}\" # noqa: E501 STYLE = \"{\" # type: Union[Literal[\"%\"], Literal[\"{\"],",
"if LOGFILE: handler = logging.FileHandler(LOGFILE) formatter = logging.Formatter(LOG_FORMAT, style=STYLE) handler.setFormatter(formatter) root = logging.getLogger()",
"= logging.FileHandler(LOGFILE) formatter = logging.Formatter(LOG_FORMAT, style=STYLE) handler.setFormatter(formatter) root = logging.getLogger() root.setLevel(LOGLEVEL) root.addHandler(handler) else:"
] |
[
"for i in range(int(Nx/J)): coupling[i*J:(i+1)*J,i*J:(i+1)*J] = np.ones((J,J)) return mesh,coupling # need to implement",
"np.linspace(0,L-h,Nx) mesh = Mesh(1,topology,geometry) return mesh def make_lattice1d_coupled(Nx,L,J): mesh = make_lattice1d(Nx,L) coupling =",
"Mesh(1,topology,geometry) return mesh def make_lattice1d_coupled(Nx,L,J): mesh = make_lattice1d(Nx,L) coupling = np.zeros((Nx,Nx)) for i",
"Nvoxels pairs (volume,x,(y,(z))) def get_coarseMesh_voxel(voxel,coupling): # returns the coarse mesh voxel associated with",
"make_lattice2d(Nx,Ny,Lx,Ly): topology = np.zeros((Nx*Ny,Nx*Ny)) d1 = np.ones(Nx-1) d2 = np.ones(Nx*Ny-Ny) for i in",
"the coarse mesh voxel to by the smallest # index coupled to voxel",
"geometry = np.zeros((Nx,2)) h = L/Nx geometry[:,0] = h*np.ones(Nx) geometry[:,1] = np.linspace(0,L-h,Nx) mesh",
"np.ones(Nx*Ny-Ny) for i in range(Ny): topology[i*Ny:(i+1)*Ny,i*Ny:(i+1)*Ny] = np.diag(d1,1)+np.diag(d1,-1) topology = topology + np.diag(d2,Nx)+np.diag(d2,-Nx)",
"hx = Nx/Lx hy = Ny/Ly #geometry[:,0] = h*np.ones(Nx) #geometry[:,1] = linspace(0,L-h,Nx) mesh",
"according to coupling i = 0 while coupling[voxel,i]<1: i = i+1 return i",
"geometry[:,0] = h*np.ones(Nx) geometry[:,1] = np.linspace(0,L-h,Nx) mesh = Mesh(1,topology,geometry) return mesh def make_lattice1d_coupled(Nx,L,J):",
"about the spatial domain \"\"\" def __init__(self,dimension,topology,geometry): self.Nvoxels = len(topology) self.dimension = dimension",
"to coupling i = 0 while coupling[voxel,i]<1: i = i+1 return i def",
"voxel to by the smallest # index coupled to voxel according to coupling",
"returns the coarse mesh voxel associated with # voxel by the coupling #",
"diagonal, 1 elsewhere # only really works for regular grids self.geometry = geometry",
"np.ones(Nx-1) d2 = np.ones(Nx*Ny-Ny) for i in range(Ny): topology[i*Ny:(i+1)*Ny,i*Ny:(i+1)*Ny] = np.diag(d1,1)+np.diag(d1,-1) topology =",
"d1 = np.ones(Nx-1) d2 = np.ones(Nx*Ny-Ny) for i in range(Ny): topology[i*Ny:(i+1)*Ny,i*Ny:(i+1)*Ny] = np.diag(d1,1)+np.diag(d1,-1)",
"= np.diag(d1,1)+np.diag(d1,-1) topology = topology + np.diag(d2,Nx)+np.diag(d2,-Nx) geometry = np.zeros((Nx*Ny,2)) hx = Nx/Lx",
"along main diagonal, 1 elsewhere # only really works for regular grids self.geometry",
"for i in range(Ny): topology[i*Ny:(i+1)*Ny,i*Ny:(i+1)*Ny] = np.diag(d1,1)+np.diag(d1,-1) topology = topology + np.diag(d2,Nx)+np.diag(d2,-Nx) geometry",
"np.zeros((Nx,Nx)) d = np.ones(Nx-1) topology = np.diag(d,1)+np.diag(d,-1) geometry = np.zeros((Nx,2)) h = L/Nx",
"= make_lattice1d(Nx,L) coupling = np.zeros((Nx,Nx)) for i in range(int(Nx/J)): coupling[i*J:(i+1)*J,i*J:(i+1)*J] = np.ones((J,J)) return",
"self.topology = topology # adjaceny matrix (numpy array), 0 along main diagonal, 1",
"in range(Ny): topology[i*Ny:(i+1)*Ny,i*Ny:(i+1)*Ny] = np.diag(d1,1)+np.diag(d1,-1) topology = topology + np.diag(d2,Nx)+np.diag(d2,-Nx) geometry = np.zeros((Nx*Ny,2))",
"all the information about the spatial domain \"\"\" def __init__(self,dimension,topology,geometry): self.Nvoxels = len(topology)",
"by the coupling # by convention I take the coarse mesh voxel to",
"np.diag(d2,Nx)+np.diag(d2,-Nx) geometry = np.zeros((Nx*Ny,2)) hx = Nx/Lx hy = Ny/Ly #geometry[:,0] = h*np.ones(Nx)",
"\"\"\" Contains all the information about the spatial domain \"\"\" def __init__(self,dimension,topology,geometry): self.Nvoxels",
"by the smallest # index coupled to voxel according to coupling i =",
"np.zeros((Nx,2)) h = L/Nx geometry[:,0] = h*np.ones(Nx) geometry[:,1] = np.linspace(0,L-h,Nx) mesh = Mesh(1,topology,geometry)",
"np.zeros((Nx*Ny,Nx*Ny)) d1 = np.ones(Nx-1) d2 = np.ones(Nx*Ny-Ny) for i in range(Ny): topology[i*Ny:(i+1)*Ny,i*Ny:(i+1)*Ny] =",
"topology[i*Ny:(i+1)*Ny,i*Ny:(i+1)*Ny] = np.diag(d1,1)+np.diag(d1,-1) topology = topology + np.diag(d2,Nx)+np.diag(d2,-Nx) geometry = np.zeros((Nx*Ny,2)) hx =",
"range(int(Nx/J)): coupling[i*J:(i+1)*J,i*J:(i+1)*J] = np.ones((J,J)) return mesh,coupling # need to implement def make_lattice2d(Nx,Ny,Lx,Ly): topology",
"spatial domain \"\"\" def __init__(self,dimension,topology,geometry): self.Nvoxels = len(topology) self.dimension = dimension self.topology =",
"i def make_lattice1d(Nx,L): # generates uniform 1d lattice on [0,L] topology = np.zeros((Nx,Nx))",
"# generates uniform 1d lattice on [0,L] topology = np.zeros((Nx,Nx)) d = np.ones(Nx-1)",
"# voxel by the coupling # by convention I take the coarse mesh",
"to by the smallest # index coupled to voxel according to coupling i",
"as np class Mesh: \"\"\" Contains all the information about the spatial domain",
"works for regular grids self.geometry = geometry # numpy array of Nvoxels pairs",
"= 0 while coupling[voxel,i]<1: i = i+1 return i def make_lattice1d(Nx,L): # generates",
"np.zeros((Nx,Nx)) for i in range(int(Nx/J)): coupling[i*J:(i+1)*J,i*J:(i+1)*J] = np.ones((J,J)) return mesh,coupling # need to",
"i in range(int(Nx/J)): coupling[i*J:(i+1)*J,i*J:(i+1)*J] = np.ones((J,J)) return mesh,coupling # need to implement def",
"np.diag(d1,1)+np.diag(d1,-1) topology = topology + np.diag(d2,Nx)+np.diag(d2,-Nx) geometry = np.zeros((Nx*Ny,2)) hx = Nx/Lx hy",
"d = np.ones(Nx-1) topology = np.diag(d,1)+np.diag(d,-1) geometry = np.zeros((Nx,2)) h = L/Nx geometry[:,0]",
"return mesh,coupling # need to implement def make_lattice2d(Nx,Ny,Lx,Ly): topology = np.zeros((Nx*Ny,Nx*Ny)) d1 =",
"the spatial domain \"\"\" def __init__(self,dimension,topology,geometry): self.Nvoxels = len(topology) self.dimension = dimension self.topology",
"h*np.ones(Nx) #geometry[:,1] = linspace(0,L-h,Nx) mesh = Mesh(1,topology,geometry) return mesh def make_lattice3d(Nx,Ny): return None",
"make_lattice1d(Nx,L): # generates uniform 1d lattice on [0,L] topology = np.zeros((Nx,Nx)) d =",
"Mesh: \"\"\" Contains all the information about the spatial domain \"\"\" def __init__(self,dimension,topology,geometry):",
"# by convention I take the coarse mesh voxel to by the smallest",
"Contains all the information about the spatial domain \"\"\" def __init__(self,dimension,topology,geometry): self.Nvoxels =",
"I take the coarse mesh voxel to by the smallest # index coupled",
"# index coupled to voxel according to coupling i = 0 while coupling[voxel,i]<1:",
"take the coarse mesh voxel to by the smallest # index coupled to",
"= np.zeros((Nx,Nx)) for i in range(int(Nx/J)): coupling[i*J:(i+1)*J,i*J:(i+1)*J] = np.ones((J,J)) return mesh,coupling # need",
"= dimension self.topology = topology # adjaceny matrix (numpy array), 0 along main",
"0 along main diagonal, 1 elsewhere # only really works for regular grids",
"= np.ones((J,J)) return mesh,coupling # need to implement def make_lattice2d(Nx,Ny,Lx,Ly): topology = np.zeros((Nx*Ny,Nx*Ny))",
"regular grids self.geometry = geometry # numpy array of Nvoxels pairs (volume,x,(y,(z))) def",
"= i+1 return i def make_lattice1d(Nx,L): # generates uniform 1d lattice on [0,L]",
"make_lattice1d_coupled(Nx,L,J): mesh = make_lattice1d(Nx,L) coupling = np.zeros((Nx,Nx)) for i in range(int(Nx/J)): coupling[i*J:(i+1)*J,i*J:(i+1)*J] =",
"topology = np.diag(d,1)+np.diag(d,-1) geometry = np.zeros((Nx,2)) h = L/Nx geometry[:,0] = h*np.ones(Nx) geometry[:,1]",
"Nx/Lx hy = Ny/Ly #geometry[:,0] = h*np.ones(Nx) #geometry[:,1] = linspace(0,L-h,Nx) mesh = Mesh(1,topology,geometry)",
"on [0,L] topology = np.zeros((Nx,Nx)) d = np.ones(Nx-1) topology = np.diag(d,1)+np.diag(d,-1) geometry =",
"coarse mesh voxel to by the smallest # index coupled to voxel according",
"1 elsewhere # only really works for regular grids self.geometry = geometry #",
"topology = np.zeros((Nx,Nx)) d = np.ones(Nx-1) topology = np.diag(d,1)+np.diag(d,-1) geometry = np.zeros((Nx,2)) h",
"np.ones((J,J)) return mesh,coupling # need to implement def make_lattice2d(Nx,Ny,Lx,Ly): topology = np.zeros((Nx*Ny,Nx*Ny)) d1",
"matrix (numpy array), 0 along main diagonal, 1 elsewhere # only really works",
"geometry # numpy array of Nvoxels pairs (volume,x,(y,(z))) def get_coarseMesh_voxel(voxel,coupling): # returns the",
"need to implement def make_lattice2d(Nx,Ny,Lx,Ly): topology = np.zeros((Nx*Ny,Nx*Ny)) d1 = np.ones(Nx-1) d2 =",
"def __init__(self,dimension,topology,geometry): self.Nvoxels = len(topology) self.dimension = dimension self.topology = topology # adjaceny",
"to voxel according to coupling i = 0 while coupling[voxel,i]<1: i = i+1",
"= L/Nx geometry[:,0] = h*np.ones(Nx) geometry[:,1] = np.linspace(0,L-h,Nx) mesh = Mesh(1,topology,geometry) return mesh",
"pairs (volume,x,(y,(z))) def get_coarseMesh_voxel(voxel,coupling): # returns the coarse mesh voxel associated with #",
"array of Nvoxels pairs (volume,x,(y,(z))) def get_coarseMesh_voxel(voxel,coupling): # returns the coarse mesh voxel",
"voxel by the coupling # by convention I take the coarse mesh voxel",
"topology = topology + np.diag(d2,Nx)+np.diag(d2,-Nx) geometry = np.zeros((Nx*Ny,2)) hx = Nx/Lx hy =",
"# need to implement def make_lattice2d(Nx,Ny,Lx,Ly): topology = np.zeros((Nx*Ny,Nx*Ny)) d1 = np.ones(Nx-1) d2",
"i in range(Ny): topology[i*Ny:(i+1)*Ny,i*Ny:(i+1)*Ny] = np.diag(d1,1)+np.diag(d1,-1) topology = topology + np.diag(d2,Nx)+np.diag(d2,-Nx) geometry =",
"h = L/Nx geometry[:,0] = h*np.ones(Nx) geometry[:,1] = np.linspace(0,L-h,Nx) mesh = Mesh(1,topology,geometry) return",
"hy = Ny/Ly #geometry[:,0] = h*np.ones(Nx) #geometry[:,1] = linspace(0,L-h,Nx) mesh = Mesh(1,topology,geometry) return",
"i+1 return i def make_lattice1d(Nx,L): # generates uniform 1d lattice on [0,L] topology",
"= np.ones(Nx-1) topology = np.diag(d,1)+np.diag(d,-1) geometry = np.zeros((Nx,2)) h = L/Nx geometry[:,0] =",
"mesh,coupling # need to implement def make_lattice2d(Nx,Ny,Lx,Ly): topology = np.zeros((Nx*Ny,Nx*Ny)) d1 = np.ones(Nx-1)",
"np class Mesh: \"\"\" Contains all the information about the spatial domain \"\"\"",
"topology # adjaceny matrix (numpy array), 0 along main diagonal, 1 elsewhere #",
"with # voxel by the coupling # by convention I take the coarse",
"1d lattice on [0,L] topology = np.zeros((Nx,Nx)) d = np.ones(Nx-1) topology = np.diag(d,1)+np.diag(d,-1)",
"geometry = np.zeros((Nx*Ny,2)) hx = Nx/Lx hy = Ny/Ly #geometry[:,0] = h*np.ones(Nx) #geometry[:,1]",
"= h*np.ones(Nx) #geometry[:,1] = linspace(0,L-h,Nx) mesh = Mesh(1,topology,geometry) return mesh def make_lattice3d(Nx,Ny): return",
"for regular grids self.geometry = geometry # numpy array of Nvoxels pairs (volume,x,(y,(z)))",
"voxel associated with # voxel by the coupling # by convention I take",
"while coupling[voxel,i]<1: i = i+1 return i def make_lattice1d(Nx,L): # generates uniform 1d",
"import numpy as np class Mesh: \"\"\" Contains all the information about the",
"the coarse mesh voxel associated with # voxel by the coupling # by",
"= np.zeros((Nx,2)) h = L/Nx geometry[:,0] = h*np.ones(Nx) geometry[:,1] = np.linspace(0,L-h,Nx) mesh =",
"topology + np.diag(d2,Nx)+np.diag(d2,-Nx) geometry = np.zeros((Nx*Ny,2)) hx = Nx/Lx hy = Ny/Ly #geometry[:,0]",
"really works for regular grids self.geometry = geometry # numpy array of Nvoxels",
"= h*np.ones(Nx) geometry[:,1] = np.linspace(0,L-h,Nx) mesh = Mesh(1,topology,geometry) return mesh def make_lattice1d_coupled(Nx,L,J): mesh",
"= len(topology) self.dimension = dimension self.topology = topology # adjaceny matrix (numpy array),",
"lattice on [0,L] topology = np.zeros((Nx,Nx)) d = np.ones(Nx-1) topology = np.diag(d,1)+np.diag(d,-1) geometry",
"coupling[i*J:(i+1)*J,i*J:(i+1)*J] = np.ones((J,J)) return mesh,coupling # need to implement def make_lattice2d(Nx,Ny,Lx,Ly): topology =",
"= Nx/Lx hy = Ny/Ly #geometry[:,0] = h*np.ones(Nx) #geometry[:,1] = linspace(0,L-h,Nx) mesh =",
"0 while coupling[voxel,i]<1: i = i+1 return i def make_lattice1d(Nx,L): # generates uniform",
"generates uniform 1d lattice on [0,L] topology = np.zeros((Nx,Nx)) d = np.ones(Nx-1) topology",
"self.dimension = dimension self.topology = topology # adjaceny matrix (numpy array), 0 along",
"# adjaceny matrix (numpy array), 0 along main diagonal, 1 elsewhere # only",
"the smallest # index coupled to voxel according to coupling i = 0",
"[0,L] topology = np.zeros((Nx,Nx)) d = np.ones(Nx-1) topology = np.diag(d,1)+np.diag(d,-1) geometry = np.zeros((Nx,2))",
"np.diag(d,1)+np.diag(d,-1) geometry = np.zeros((Nx,2)) h = L/Nx geometry[:,0] = h*np.ones(Nx) geometry[:,1] = np.linspace(0,L-h,Nx)",
"= np.linspace(0,L-h,Nx) mesh = Mesh(1,topology,geometry) return mesh def make_lattice1d_coupled(Nx,L,J): mesh = make_lattice1d(Nx,L) coupling",
"i = i+1 return i def make_lattice1d(Nx,L): # generates uniform 1d lattice on",
"coupling[voxel,i]<1: i = i+1 return i def make_lattice1d(Nx,L): # generates uniform 1d lattice",
"convention I take the coarse mesh voxel to by the smallest # index",
"def get_coarseMesh_voxel(voxel,coupling): # returns the coarse mesh voxel associated with # voxel by",
"= np.zeros((Nx*Ny,Nx*Ny)) d1 = np.ones(Nx-1) d2 = np.ones(Nx*Ny-Ny) for i in range(Ny): topology[i*Ny:(i+1)*Ny,i*Ny:(i+1)*Ny]",
"array), 0 along main diagonal, 1 elsewhere # only really works for regular",
"np.ones(Nx-1) topology = np.diag(d,1)+np.diag(d,-1) geometry = np.zeros((Nx,2)) h = L/Nx geometry[:,0] = h*np.ones(Nx)",
"domain \"\"\" def __init__(self,dimension,topology,geometry): self.Nvoxels = len(topology) self.dimension = dimension self.topology = topology",
"\"\"\" def __init__(self,dimension,topology,geometry): self.Nvoxels = len(topology) self.dimension = dimension self.topology = topology #",
"def make_lattice1d(Nx,L): # generates uniform 1d lattice on [0,L] topology = np.zeros((Nx,Nx)) d",
"voxel according to coupling i = 0 while coupling[voxel,i]<1: i = i+1 return",
"mesh def make_lattice1d_coupled(Nx,L,J): mesh = make_lattice1d(Nx,L) coupling = np.zeros((Nx,Nx)) for i in range(int(Nx/J)):",
"information about the spatial domain \"\"\" def __init__(self,dimension,topology,geometry): self.Nvoxels = len(topology) self.dimension =",
"elsewhere # only really works for regular grids self.geometry = geometry # numpy",
"make_lattice1d(Nx,L) coupling = np.zeros((Nx,Nx)) for i in range(int(Nx/J)): coupling[i*J:(i+1)*J,i*J:(i+1)*J] = np.ones((J,J)) return mesh,coupling",
"d2 = np.ones(Nx*Ny-Ny) for i in range(Ny): topology[i*Ny:(i+1)*Ny,i*Ny:(i+1)*Ny] = np.diag(d1,1)+np.diag(d1,-1) topology = topology",
"def make_lattice2d(Nx,Ny,Lx,Ly): topology = np.zeros((Nx*Ny,Nx*Ny)) d1 = np.ones(Nx-1) d2 = np.ones(Nx*Ny-Ny) for i",
"coarse mesh voxel associated with # voxel by the coupling # by convention",
"numpy array of Nvoxels pairs (volume,x,(y,(z))) def get_coarseMesh_voxel(voxel,coupling): # returns the coarse mesh",
"get_coarseMesh_voxel(voxel,coupling): # returns the coarse mesh voxel associated with # voxel by the",
"to implement def make_lattice2d(Nx,Ny,Lx,Ly): topology = np.zeros((Nx*Ny,Nx*Ny)) d1 = np.ones(Nx-1) d2 = np.ones(Nx*Ny-Ny)",
"= Mesh(1,topology,geometry) return mesh def make_lattice1d_coupled(Nx,L,J): mesh = make_lattice1d(Nx,L) coupling = np.zeros((Nx,Nx)) for",
"grids self.geometry = geometry # numpy array of Nvoxels pairs (volume,x,(y,(z))) def get_coarseMesh_voxel(voxel,coupling):",
"coupling # by convention I take the coarse mesh voxel to by the",
"by convention I take the coarse mesh voxel to by the smallest #",
"in range(int(Nx/J)): coupling[i*J:(i+1)*J,i*J:(i+1)*J] = np.ones((J,J)) return mesh,coupling # need to implement def make_lattice2d(Nx,Ny,Lx,Ly):",
"uniform 1d lattice on [0,L] topology = np.zeros((Nx,Nx)) d = np.ones(Nx-1) topology =",
"(volume,x,(y,(z))) def get_coarseMesh_voxel(voxel,coupling): # returns the coarse mesh voxel associated with # voxel",
"topology = np.zeros((Nx*Ny,Nx*Ny)) d1 = np.ones(Nx-1) d2 = np.ones(Nx*Ny-Ny) for i in range(Ny):",
"= np.zeros((Nx*Ny,2)) hx = Nx/Lx hy = Ny/Ly #geometry[:,0] = h*np.ones(Nx) #geometry[:,1] =",
"dimension self.topology = topology # adjaceny matrix (numpy array), 0 along main diagonal,",
"= np.ones(Nx-1) d2 = np.ones(Nx*Ny-Ny) for i in range(Ny): topology[i*Ny:(i+1)*Ny,i*Ny:(i+1)*Ny] = np.diag(d1,1)+np.diag(d1,-1) topology",
"= topology # adjaceny matrix (numpy array), 0 along main diagonal, 1 elsewhere",
"of Nvoxels pairs (volume,x,(y,(z))) def get_coarseMesh_voxel(voxel,coupling): # returns the coarse mesh voxel associated",
"Ny/Ly #geometry[:,0] = h*np.ones(Nx) #geometry[:,1] = linspace(0,L-h,Nx) mesh = Mesh(1,topology,geometry) return mesh def",
"L/Nx geometry[:,0] = h*np.ones(Nx) geometry[:,1] = np.linspace(0,L-h,Nx) mesh = Mesh(1,topology,geometry) return mesh def",
"= np.ones(Nx*Ny-Ny) for i in range(Ny): topology[i*Ny:(i+1)*Ny,i*Ny:(i+1)*Ny] = np.diag(d1,1)+np.diag(d1,-1) topology = topology +",
"coupled to voxel according to coupling i = 0 while coupling[voxel,i]<1: i =",
"mesh = Mesh(1,topology,geometry) return mesh def make_lattice1d_coupled(Nx,L,J): mesh = make_lattice1d(Nx,L) coupling = np.zeros((Nx,Nx))",
"mesh voxel associated with # voxel by the coupling # by convention I",
"h*np.ones(Nx) geometry[:,1] = np.linspace(0,L-h,Nx) mesh = Mesh(1,topology,geometry) return mesh def make_lattice1d_coupled(Nx,L,J): mesh =",
"len(topology) self.dimension = dimension self.topology = topology # adjaceny matrix (numpy array), 0",
"associated with # voxel by the coupling # by convention I take the",
"coupling i = 0 while coupling[voxel,i]<1: i = i+1 return i def make_lattice1d(Nx,L):",
"mesh = make_lattice1d(Nx,L) coupling = np.zeros((Nx,Nx)) for i in range(int(Nx/J)): coupling[i*J:(i+1)*J,i*J:(i+1)*J] = np.ones((J,J))",
"index coupled to voxel according to coupling i = 0 while coupling[voxel,i]<1: i",
"(numpy array), 0 along main diagonal, 1 elsewhere # only really works for",
"self.geometry = geometry # numpy array of Nvoxels pairs (volume,x,(y,(z))) def get_coarseMesh_voxel(voxel,coupling): #",
"class Mesh: \"\"\" Contains all the information about the spatial domain \"\"\" def",
"return i def make_lattice1d(Nx,L): # generates uniform 1d lattice on [0,L] topology =",
"def make_lattice1d_coupled(Nx,L,J): mesh = make_lattice1d(Nx,L) coupling = np.zeros((Nx,Nx)) for i in range(int(Nx/J)): coupling[i*J:(i+1)*J,i*J:(i+1)*J]",
"#geometry[:,0] = h*np.ones(Nx) #geometry[:,1] = linspace(0,L-h,Nx) mesh = Mesh(1,topology,geometry) return mesh def make_lattice3d(Nx,Ny):",
"numpy as np class Mesh: \"\"\" Contains all the information about the spatial",
"# only really works for regular grids self.geometry = geometry # numpy array",
"= geometry # numpy array of Nvoxels pairs (volume,x,(y,(z))) def get_coarseMesh_voxel(voxel,coupling): # returns",
"geometry[:,1] = np.linspace(0,L-h,Nx) mesh = Mesh(1,topology,geometry) return mesh def make_lattice1d_coupled(Nx,L,J): mesh = make_lattice1d(Nx,L)",
"implement def make_lattice2d(Nx,Ny,Lx,Ly): topology = np.zeros((Nx*Ny,Nx*Ny)) d1 = np.ones(Nx-1) d2 = np.ones(Nx*Ny-Ny) for",
"main diagonal, 1 elsewhere # only really works for regular grids self.geometry =",
"= np.diag(d,1)+np.diag(d,-1) geometry = np.zeros((Nx,2)) h = L/Nx geometry[:,0] = h*np.ones(Nx) geometry[:,1] =",
"range(Ny): topology[i*Ny:(i+1)*Ny,i*Ny:(i+1)*Ny] = np.diag(d1,1)+np.diag(d1,-1) topology = topology + np.diag(d2,Nx)+np.diag(d2,-Nx) geometry = np.zeros((Nx*Ny,2)) hx",
"return mesh def make_lattice1d_coupled(Nx,L,J): mesh = make_lattice1d(Nx,L) coupling = np.zeros((Nx,Nx)) for i in",
"= np.zeros((Nx,Nx)) d = np.ones(Nx-1) topology = np.diag(d,1)+np.diag(d,-1) geometry = np.zeros((Nx,2)) h =",
"np.zeros((Nx*Ny,2)) hx = Nx/Lx hy = Ny/Ly #geometry[:,0] = h*np.ones(Nx) #geometry[:,1] = linspace(0,L-h,Nx)",
"smallest # index coupled to voxel according to coupling i = 0 while",
"= Ny/Ly #geometry[:,0] = h*np.ones(Nx) #geometry[:,1] = linspace(0,L-h,Nx) mesh = Mesh(1,topology,geometry) return mesh",
"only really works for regular grids self.geometry = geometry # numpy array of",
"self.Nvoxels = len(topology) self.dimension = dimension self.topology = topology # adjaceny matrix (numpy",
"adjaceny matrix (numpy array), 0 along main diagonal, 1 elsewhere # only really",
"__init__(self,dimension,topology,geometry): self.Nvoxels = len(topology) self.dimension = dimension self.topology = topology # adjaceny matrix",
"# numpy array of Nvoxels pairs (volume,x,(y,(z))) def get_coarseMesh_voxel(voxel,coupling): # returns the coarse",
"# returns the coarse mesh voxel associated with # voxel by the coupling",
"the coupling # by convention I take the coarse mesh voxel to by",
"coupling = np.zeros((Nx,Nx)) for i in range(int(Nx/J)): coupling[i*J:(i+1)*J,i*J:(i+1)*J] = np.ones((J,J)) return mesh,coupling #",
"the information about the spatial domain \"\"\" def __init__(self,dimension,topology,geometry): self.Nvoxels = len(topology) self.dimension",
"+ np.diag(d2,Nx)+np.diag(d2,-Nx) geometry = np.zeros((Nx*Ny,2)) hx = Nx/Lx hy = Ny/Ly #geometry[:,0] =",
"i = 0 while coupling[voxel,i]<1: i = i+1 return i def make_lattice1d(Nx,L): #",
"= topology + np.diag(d2,Nx)+np.diag(d2,-Nx) geometry = np.zeros((Nx*Ny,2)) hx = Nx/Lx hy = Ny/Ly",
"mesh voxel to by the smallest # index coupled to voxel according to"
] |
[
"os, subprocess from shelljob import proc application = Flask(__name__) @application.route('/provision', methods=['POST', 'GET']) def",
"= str(request.form['username']) usr_pass = str(request.form['password']) if usr_name == 'admin' and usr_pass == '<PASSWORD>':",
"\\ format(contrail_package_version,contrail_package_build,base_image,contrail_package_release,target_node_ip), shell=True)).splitlines(): yield line + '\\n' os.remove(\"testbed.py\") return Response( generate(), mimetype= 'text/html'",
"== 'admin' and usr_pass == '<PASSWORD>': return render_template('provision.html') else: return render_template('login-fail.html') @application.route('/') def",
"= str(request.form['build']) testbed_file = request.files['testbed-file'].read() localfile = open(\"testbed.py\", \"w\") localfile.write(testbed_file) localfile.close() if request.form[\"commit\"]",
"shell=True)).splitlines(): yield line + '\\n' os.remove(\"testbed.py\") return Response( generate(), mimetype= 'text/html' ) @application.route('/login',",
"render_template('login-fail.html') @application.route('/') def main(): return render_template('login.html') if __name__ == \"__main__\": application.run(debug=True, host='0.0.0.0', port=9000)",
"from flask import Flask, flash, redirect, render_template, request, session, abort, Response import os,",
"return Response( generate(), mimetype= 'text/html' ) @application.route('/login', methods=['POST', 'GET']) def login(): usr_name =",
"'<PASSWORD>': return render_template('provision.html') else: return render_template('login-fail.html') @application.route('/') def main(): return render_template('login.html') if __name__",
"localfile = open(\"testbed.py\", \"w\") localfile.write(testbed_file) localfile.close() if request.form[\"commit\"] == \"Provision\": def generate(): for",
"\\ ssh root@{4} truncate -s 0 /etc/apt/sources.list && \\ scp testbed.py root@{4}:~/ &&",
"@application.route('/login', methods=['POST', 'GET']) def login(): usr_name = str(request.form['username']) usr_pass = str(request.form['password']) if usr_name",
"= str(request.form['target-password']) base_image = str(request.form['image']) contrail_package_version = str(request.form['package']).split('contrail-')[1] contrail_package_release = str(request.form['release']) contrail_package_build =",
"'\\n' os.remove(\"testbed.py\") return Response( generate(), mimetype= 'text/html' ) @application.route('/login', methods=['POST', 'GET']) def login():",
"= str(request.form['target-ip']) target_node_password = str(request.form['target-password']) base_image = str(request.form['image']) contrail_package_version = str(request.form['package']).split('contrail-')[1] contrail_package_release =",
"target_node_password = str(request.form['target-password']) base_image = str(request.form['image']) contrail_package_version = str(request.form['package']).split('contrail-')[1] contrail_package_release = str(request.form['release']) contrail_package_build",
"'GET']) def login(): usr_name = str(request.form['username']) usr_pass = str(request.form['password']) if usr_name == 'admin'",
"usr_name = str(request.form['username']) usr_pass = str(request.form['password']) if usr_name == 'admin' and usr_pass ==",
"for line in (subprocess.check_output(\"ssh root@{4} wget http://10.84.5.120/github-build/R{0}/{1}/{2}/{3}/artifacts/contrail-cloud-docker_4.0.0.0-{1}-{3}.tgz && \\ ssh root@{4} wget http://10.84.5.120/github-build/R{0}/{1}/{2}/{3}/artifacts/contrail-server-manager-installer_4.0.0.0-{1}~{3}_all.deb",
"str(request.form['target-password']) base_image = str(request.form['image']) contrail_package_version = str(request.form['package']).split('contrail-')[1] contrail_package_release = str(request.form['release']) contrail_package_build = str(request.form['build'])",
"ssh root@{4} wget http://10.84.5.120/github-build/R{0}/{1}/{2}/{3}/artifacts/contrail-server-manager-installer_4.0.0.0-{1}~{3}_all.deb && \\ ssh root@{4} truncate -s 0 /etc/apt/sources.list &&",
"request, session, abort, Response import os, subprocess from shelljob import proc application =",
"\"w\") localfile.write(testbed_file) localfile.close() if request.form[\"commit\"] == \"Provision\": def generate(): for line in (subprocess.check_output(\"ssh",
"methods=['POST', 'GET']) def login(): usr_name = str(request.form['username']) usr_pass = str(request.form['password']) if usr_name ==",
"provision(): target_node_ip = str(request.form['target-ip']) target_node_password = str(request.form['target-password']) base_image = str(request.form['image']) contrail_package_version = str(request.form['package']).split('contrail-')[1]",
"def provision(): target_node_ip = str(request.form['target-ip']) target_node_password = str(request.form['target-password']) base_image = str(request.form['image']) contrail_package_version =",
"= str(request.form['package']).split('contrail-')[1] contrail_package_release = str(request.form['release']) contrail_package_build = str(request.form['build']) testbed_file = request.files['testbed-file'].read() localfile =",
"Response( generate(), mimetype= 'text/html' ) @application.route('/login', methods=['POST', 'GET']) def login(): usr_name = str(request.form['username'])",
"str(request.form['username']) usr_pass = str(request.form['password']) if usr_name == 'admin' and usr_pass == '<PASSWORD>': return",
"application = Flask(__name__) @application.route('/provision', methods=['POST', 'GET']) def provision(): target_node_ip = str(request.form['target-ip']) target_node_password =",
"= request.files['testbed-file'].read() localfile = open(\"testbed.py\", \"w\") localfile.write(testbed_file) localfile.close() if request.form[\"commit\"] == \"Provision\": def",
"flash, redirect, render_template, request, session, abort, Response import os, subprocess from shelljob import",
"'text/html' ) @application.route('/login', methods=['POST', 'GET']) def login(): usr_name = str(request.form['username']) usr_pass = str(request.form['password'])",
"http://10.84.5.120/github-build/R{0}/{1}/{2}/{3}/artifacts/contrail-server-manager-installer_4.0.0.0-{1}~{3}_all.deb && \\ ssh root@{4} truncate -s 0 /etc/apt/sources.list && \\ scp testbed.py",
"proc application = Flask(__name__) @application.route('/provision', methods=['POST', 'GET']) def provision(): target_node_ip = str(request.form['target-ip']) target_node_password",
"(subprocess.check_output(\"ssh root@{4} wget http://10.84.5.120/github-build/R{0}/{1}/{2}/{3}/artifacts/contrail-cloud-docker_4.0.0.0-{1}-{3}.tgz && \\ ssh root@{4} wget http://10.84.5.120/github-build/R{0}/{1}/{2}/{3}/artifacts/contrail-server-manager-installer_4.0.0.0-{1}~{3}_all.deb && \\ ssh",
"-s 0 /etc/apt/sources.list && \\ scp testbed.py root@{4}:~/ && \\ ssh root@{4} dpkg",
"open(\"testbed.py\", \"w\") localfile.write(testbed_file) localfile.close() if request.form[\"commit\"] == \"Provision\": def generate(): for line in",
"== '<PASSWORD>': return render_template('provision.html') else: return render_template('login-fail.html') @application.route('/') def main(): return render_template('login.html') if",
"def generate(): for line in (subprocess.check_output(\"ssh root@{4} wget http://10.84.5.120/github-build/R{0}/{1}/{2}/{3}/artifacts/contrail-cloud-docker_4.0.0.0-{1}-{3}.tgz && \\ ssh root@{4}",
"= str(request.form['image']) contrail_package_version = str(request.form['package']).split('contrail-')[1] contrail_package_release = str(request.form['release']) contrail_package_build = str(request.form['build']) testbed_file =",
"os.remove(\"testbed.py\") return Response( generate(), mimetype= 'text/html' ) @application.route('/login', methods=['POST', 'GET']) def login(): usr_name",
"\"Provision\": def generate(): for line in (subprocess.check_output(\"ssh root@{4} wget http://10.84.5.120/github-build/R{0}/{1}/{2}/{3}/artifacts/contrail-cloud-docker_4.0.0.0-{1}-{3}.tgz && \\ ssh",
"str(request.form['target-ip']) target_node_password = str(request.form['target-password']) base_image = str(request.form['image']) contrail_package_version = str(request.form['package']).split('contrail-')[1] contrail_package_release = str(request.form['release'])",
"mimetype= 'text/html' ) @application.route('/login', methods=['POST', 'GET']) def login(): usr_name = str(request.form['username']) usr_pass =",
"redirect, render_template, request, session, abort, Response import os, subprocess from shelljob import proc",
"'admin' and usr_pass == '<PASSWORD>': return render_template('provision.html') else: return render_template('login-fail.html') @application.route('/') def main():",
"str(request.form['password']) if usr_name == 'admin' and usr_pass == '<PASSWORD>': return render_template('provision.html') else: return",
"if usr_name == 'admin' and usr_pass == '<PASSWORD>': return render_template('provision.html') else: return render_template('login-fail.html')",
"\\ scp testbed.py root@{4}:~/ && \\ ssh root@{4} dpkg -i contrail-server-manager*deb\". \\ format(contrail_package_version,contrail_package_build,base_image,contrail_package_release,target_node_ip),",
"root@{4} wget http://10.84.5.120/github-build/R{0}/{1}/{2}/{3}/artifacts/contrail-cloud-docker_4.0.0.0-{1}-{3}.tgz && \\ ssh root@{4} wget http://10.84.5.120/github-build/R{0}/{1}/{2}/{3}/artifacts/contrail-server-manager-installer_4.0.0.0-{1}~{3}_all.deb && \\ ssh root@{4}",
"Flask, flash, redirect, render_template, request, session, abort, Response import os, subprocess from shelljob",
"str(request.form['image']) contrail_package_version = str(request.form['package']).split('contrail-')[1] contrail_package_release = str(request.form['release']) contrail_package_build = str(request.form['build']) testbed_file = request.files['testbed-file'].read()",
"Response import os, subprocess from shelljob import proc application = Flask(__name__) @application.route('/provision', methods=['POST',",
"format(contrail_package_version,contrail_package_build,base_image,contrail_package_release,target_node_ip), shell=True)).splitlines(): yield line + '\\n' os.remove(\"testbed.py\") return Response( generate(), mimetype= 'text/html' )",
"= str(request.form['release']) contrail_package_build = str(request.form['build']) testbed_file = request.files['testbed-file'].read() localfile = open(\"testbed.py\", \"w\") localfile.write(testbed_file)",
"contrail_package_build = str(request.form['build']) testbed_file = request.files['testbed-file'].read() localfile = open(\"testbed.py\", \"w\") localfile.write(testbed_file) localfile.close() if",
"session, abort, Response import os, subprocess from shelljob import proc application = Flask(__name__)",
"line in (subprocess.check_output(\"ssh root@{4} wget http://10.84.5.120/github-build/R{0}/{1}/{2}/{3}/artifacts/contrail-cloud-docker_4.0.0.0-{1}-{3}.tgz && \\ ssh root@{4} wget http://10.84.5.120/github-build/R{0}/{1}/{2}/{3}/artifacts/contrail-server-manager-installer_4.0.0.0-{1}~{3}_all.deb &&",
"Flask(__name__) @application.route('/provision', methods=['POST', 'GET']) def provision(): target_node_ip = str(request.form['target-ip']) target_node_password = str(request.form['target-password']) base_image",
"root@{4} truncate -s 0 /etc/apt/sources.list && \\ scp testbed.py root@{4}:~/ && \\ ssh",
"in (subprocess.check_output(\"ssh root@{4} wget http://10.84.5.120/github-build/R{0}/{1}/{2}/{3}/artifacts/contrail-cloud-docker_4.0.0.0-{1}-{3}.tgz && \\ ssh root@{4} wget http://10.84.5.120/github-build/R{0}/{1}/{2}/{3}/artifacts/contrail-server-manager-installer_4.0.0.0-{1}~{3}_all.deb && \\",
"return render_template('provision.html') else: return render_template('login-fail.html') @application.route('/') def main(): return render_template('login.html') if __name__ ==",
"request.files['testbed-file'].read() localfile = open(\"testbed.py\", \"w\") localfile.write(testbed_file) localfile.close() if request.form[\"commit\"] == \"Provision\": def generate():",
"contrail_package_release = str(request.form['release']) contrail_package_build = str(request.form['build']) testbed_file = request.files['testbed-file'].read() localfile = open(\"testbed.py\", \"w\")",
"&& \\ ssh root@{4} truncate -s 0 /etc/apt/sources.list && \\ scp testbed.py root@{4}:~/",
"localfile.close() if request.form[\"commit\"] == \"Provision\": def generate(): for line in (subprocess.check_output(\"ssh root@{4} wget",
"-i contrail-server-manager*deb\". \\ format(contrail_package_version,contrail_package_build,base_image,contrail_package_release,target_node_ip), shell=True)).splitlines(): yield line + '\\n' os.remove(\"testbed.py\") return Response( generate(),",
"root@{4} wget http://10.84.5.120/github-build/R{0}/{1}/{2}/{3}/artifacts/contrail-server-manager-installer_4.0.0.0-{1}~{3}_all.deb && \\ ssh root@{4} truncate -s 0 /etc/apt/sources.list && \\",
"def login(): usr_name = str(request.form['username']) usr_pass = str(request.form['password']) if usr_name == 'admin' and",
"flask import Flask, flash, redirect, render_template, request, session, abort, Response import os, subprocess",
"return render_template('login-fail.html') @application.route('/') def main(): return render_template('login.html') if __name__ == \"__main__\": application.run(debug=True, host='0.0.0.0',",
"base_image = str(request.form['image']) contrail_package_version = str(request.form['package']).split('contrail-')[1] contrail_package_release = str(request.form['release']) contrail_package_build = str(request.form['build']) testbed_file",
"== \"Provision\": def generate(): for line in (subprocess.check_output(\"ssh root@{4} wget http://10.84.5.120/github-build/R{0}/{1}/{2}/{3}/artifacts/contrail-cloud-docker_4.0.0.0-{1}-{3}.tgz && \\",
"ssh root@{4} truncate -s 0 /etc/apt/sources.list && \\ scp testbed.py root@{4}:~/ && \\",
"= open(\"testbed.py\", \"w\") localfile.write(testbed_file) localfile.close() if request.form[\"commit\"] == \"Provision\": def generate(): for line",
"if request.form[\"commit\"] == \"Provision\": def generate(): for line in (subprocess.check_output(\"ssh root@{4} wget http://10.84.5.120/github-build/R{0}/{1}/{2}/{3}/artifacts/contrail-cloud-docker_4.0.0.0-{1}-{3}.tgz",
"import proc application = Flask(__name__) @application.route('/provision', methods=['POST', 'GET']) def provision(): target_node_ip = str(request.form['target-ip'])",
"render_template('provision.html') else: return render_template('login-fail.html') @application.route('/') def main(): return render_template('login.html') if __name__ == \"__main__\":",
"usr_pass = str(request.form['password']) if usr_name == 'admin' and usr_pass == '<PASSWORD>': return render_template('provision.html')",
"wget http://10.84.5.120/github-build/R{0}/{1}/{2}/{3}/artifacts/contrail-server-manager-installer_4.0.0.0-{1}~{3}_all.deb && \\ ssh root@{4} truncate -s 0 /etc/apt/sources.list && \\ scp",
"line + '\\n' os.remove(\"testbed.py\") return Response( generate(), mimetype= 'text/html' ) @application.route('/login', methods=['POST', 'GET'])",
"generate(): for line in (subprocess.check_output(\"ssh root@{4} wget http://10.84.5.120/github-build/R{0}/{1}/{2}/{3}/artifacts/contrail-cloud-docker_4.0.0.0-{1}-{3}.tgz && \\ ssh root@{4} wget",
"str(request.form['build']) testbed_file = request.files['testbed-file'].read() localfile = open(\"testbed.py\", \"w\") localfile.write(testbed_file) localfile.close() if request.form[\"commit\"] ==",
"root@{4}:~/ && \\ ssh root@{4} dpkg -i contrail-server-manager*deb\". \\ format(contrail_package_version,contrail_package_build,base_image,contrail_package_release,target_node_ip), shell=True)).splitlines(): yield line",
"from shelljob import proc application = Flask(__name__) @application.route('/provision', methods=['POST', 'GET']) def provision(): target_node_ip",
"import Flask, flash, redirect, render_template, request, session, abort, Response import os, subprocess from",
"0 /etc/apt/sources.list && \\ scp testbed.py root@{4}:~/ && \\ ssh root@{4} dpkg -i",
"login(): usr_name = str(request.form['username']) usr_pass = str(request.form['password']) if usr_name == 'admin' and usr_pass",
"localfile.write(testbed_file) localfile.close() if request.form[\"commit\"] == \"Provision\": def generate(): for line in (subprocess.check_output(\"ssh root@{4}",
"testbed_file = request.files['testbed-file'].read() localfile = open(\"testbed.py\", \"w\") localfile.write(testbed_file) localfile.close() if request.form[\"commit\"] == \"Provision\":",
"abort, Response import os, subprocess from shelljob import proc application = Flask(__name__) @application.route('/provision',",
"\\ ssh root@{4} dpkg -i contrail-server-manager*deb\". \\ format(contrail_package_version,contrail_package_build,base_image,contrail_package_release,target_node_ip), shell=True)).splitlines(): yield line + '\\n'",
"usr_pass == '<PASSWORD>': return render_template('provision.html') else: return render_template('login-fail.html') @application.route('/') def main(): return render_template('login.html')",
"yield line + '\\n' os.remove(\"testbed.py\") return Response( generate(), mimetype= 'text/html' ) @application.route('/login', methods=['POST',",
"ssh root@{4} dpkg -i contrail-server-manager*deb\". \\ format(contrail_package_version,contrail_package_build,base_image,contrail_package_release,target_node_ip), shell=True)).splitlines(): yield line + '\\n' os.remove(\"testbed.py\")",
") @application.route('/login', methods=['POST', 'GET']) def login(): usr_name = str(request.form['username']) usr_pass = str(request.form['password']) if",
"&& \\ ssh root@{4} dpkg -i contrail-server-manager*deb\". \\ format(contrail_package_version,contrail_package_build,base_image,contrail_package_release,target_node_ip), shell=True)).splitlines(): yield line +",
"/etc/apt/sources.list && \\ scp testbed.py root@{4}:~/ && \\ ssh root@{4} dpkg -i contrail-server-manager*deb\".",
"testbed.py root@{4}:~/ && \\ ssh root@{4} dpkg -i contrail-server-manager*deb\". \\ format(contrail_package_version,contrail_package_build,base_image,contrail_package_release,target_node_ip), shell=True)).splitlines(): yield",
"else: return render_template('login-fail.html') @application.route('/') def main(): return render_template('login.html') if __name__ == \"__main__\": application.run(debug=True,",
"str(request.form['release']) contrail_package_build = str(request.form['build']) testbed_file = request.files['testbed-file'].read() localfile = open(\"testbed.py\", \"w\") localfile.write(testbed_file) localfile.close()",
"methods=['POST', 'GET']) def provision(): target_node_ip = str(request.form['target-ip']) target_node_password = str(request.form['target-password']) base_image = str(request.form['image'])",
"request.form[\"commit\"] == \"Provision\": def generate(): for line in (subprocess.check_output(\"ssh root@{4} wget http://10.84.5.120/github-build/R{0}/{1}/{2}/{3}/artifacts/contrail-cloud-docker_4.0.0.0-{1}-{3}.tgz &&",
"scp testbed.py root@{4}:~/ && \\ ssh root@{4} dpkg -i contrail-server-manager*deb\". \\ format(contrail_package_version,contrail_package_build,base_image,contrail_package_release,target_node_ip), shell=True)).splitlines():",
"<reponame>savithruml/contrail-provisioning-tool from flask import Flask, flash, redirect, render_template, request, session, abort, Response import",
"contrail-server-manager*deb\". \\ format(contrail_package_version,contrail_package_build,base_image,contrail_package_release,target_node_ip), shell=True)).splitlines(): yield line + '\\n' os.remove(\"testbed.py\") return Response( generate(), mimetype=",
"and usr_pass == '<PASSWORD>': return render_template('provision.html') else: return render_template('login-fail.html') @application.route('/') def main(): return",
"import os, subprocess from shelljob import proc application = Flask(__name__) @application.route('/provision', methods=['POST', 'GET'])",
"generate(), mimetype= 'text/html' ) @application.route('/login', methods=['POST', 'GET']) def login(): usr_name = str(request.form['username']) usr_pass",
"subprocess from shelljob import proc application = Flask(__name__) @application.route('/provision', methods=['POST', 'GET']) def provision():",
"+ '\\n' os.remove(\"testbed.py\") return Response( generate(), mimetype= 'text/html' ) @application.route('/login', methods=['POST', 'GET']) def",
"dpkg -i contrail-server-manager*deb\". \\ format(contrail_package_version,contrail_package_build,base_image,contrail_package_release,target_node_ip), shell=True)).splitlines(): yield line + '\\n' os.remove(\"testbed.py\") return Response(",
"http://10.84.5.120/github-build/R{0}/{1}/{2}/{3}/artifacts/contrail-cloud-docker_4.0.0.0-{1}-{3}.tgz && \\ ssh root@{4} wget http://10.84.5.120/github-build/R{0}/{1}/{2}/{3}/artifacts/contrail-server-manager-installer_4.0.0.0-{1}~{3}_all.deb && \\ ssh root@{4} truncate -s",
"= str(request.form['password']) if usr_name == 'admin' and usr_pass == '<PASSWORD>': return render_template('provision.html') else:",
"str(request.form['package']).split('contrail-')[1] contrail_package_release = str(request.form['release']) contrail_package_build = str(request.form['build']) testbed_file = request.files['testbed-file'].read() localfile = open(\"testbed.py\",",
"render_template, request, session, abort, Response import os, subprocess from shelljob import proc application",
"= Flask(__name__) @application.route('/provision', methods=['POST', 'GET']) def provision(): target_node_ip = str(request.form['target-ip']) target_node_password = str(request.form['target-password'])",
"shelljob import proc application = Flask(__name__) @application.route('/provision', methods=['POST', 'GET']) def provision(): target_node_ip =",
"contrail_package_version = str(request.form['package']).split('contrail-')[1] contrail_package_release = str(request.form['release']) contrail_package_build = str(request.form['build']) testbed_file = request.files['testbed-file'].read() localfile",
"wget http://10.84.5.120/github-build/R{0}/{1}/{2}/{3}/artifacts/contrail-cloud-docker_4.0.0.0-{1}-{3}.tgz && \\ ssh root@{4} wget http://10.84.5.120/github-build/R{0}/{1}/{2}/{3}/artifacts/contrail-server-manager-installer_4.0.0.0-{1}~{3}_all.deb && \\ ssh root@{4} truncate",
"\\ ssh root@{4} wget http://10.84.5.120/github-build/R{0}/{1}/{2}/{3}/artifacts/contrail-server-manager-installer_4.0.0.0-{1}~{3}_all.deb && \\ ssh root@{4} truncate -s 0 /etc/apt/sources.list",
"truncate -s 0 /etc/apt/sources.list && \\ scp testbed.py root@{4}:~/ && \\ ssh root@{4}",
"@application.route('/provision', methods=['POST', 'GET']) def provision(): target_node_ip = str(request.form['target-ip']) target_node_password = str(request.form['target-password']) base_image =",
"usr_name == 'admin' and usr_pass == '<PASSWORD>': return render_template('provision.html') else: return render_template('login-fail.html') @application.route('/')",
"target_node_ip = str(request.form['target-ip']) target_node_password = str(request.form['target-password']) base_image = str(request.form['image']) contrail_package_version = str(request.form['package']).split('contrail-')[1] contrail_package_release",
"&& \\ scp testbed.py root@{4}:~/ && \\ ssh root@{4} dpkg -i contrail-server-manager*deb\". \\",
"'GET']) def provision(): target_node_ip = str(request.form['target-ip']) target_node_password = str(request.form['target-password']) base_image = str(request.form['image']) contrail_package_version",
"root@{4} dpkg -i contrail-server-manager*deb\". \\ format(contrail_package_version,contrail_package_build,base_image,contrail_package_release,target_node_ip), shell=True)).splitlines(): yield line + '\\n' os.remove(\"testbed.py\") return",
"&& \\ ssh root@{4} wget http://10.84.5.120/github-build/R{0}/{1}/{2}/{3}/artifacts/contrail-server-manager-installer_4.0.0.0-{1}~{3}_all.deb && \\ ssh root@{4} truncate -s 0"
] |
[
"self.basics) return self.finishWalk() def test_walk_leaf(self): oid = OID(\".1.3.6.1.4.2.1.1\") result = Result() self.session.walk([oid], set_result,",
"version = \"2c\" class TestOID(unittest.TestCase): def test_oid_name(self): oid = OID(\"1.3.6.1.2.1.1.1.0\") self.assertEquals(oid, OID(\"SNMPv2-MIB::sysDescr.0\")) self.assertEquals(oid,",
"\"%d-%d-%d,%d\" % (now[0], now[1], now[2], now[3]) result = self.session.sget([OID(\".1.3.6.1.2.1.25.1.2.0\")]) self.assert_(result) value = result[0][1].split(':',",
"Result() self.session.walk([oid], set_result, result, strict=True) self.session.wait() self.assertEquals(result.value, []) return self.finishStrictWalk() def test_sysDescr(self): result",
"snapy.netsnmp import Session, SnmpError, SnmpTimeout, OID class Result(object): \"\"\"Container for async results\"\"\" value",
"for x,v in self.basics]) self.assertEquals(result, self.basics) return self.finishGet() def test_get_small(self): result = Result()",
"= value class TestSessionV1(TestCase): version = \"1\" bulk = False basics = [",
"= result[0][1].split(':', 1)[0] self.assertEquals(value, now) return self.finishGet() class TestSessionV2cBulk(TestSessionV2c): bulk = True class",
"= [ (OID(\".1.3.6.1.4.2.1.1\"), 1), (OID(\".1.3.6.1.4.2.1.2\"), -1), (OID(\".1.3.6.1.4.2.1.3\"), 1), (OID(\".1.3.6.1.4.2.1.4\"), \"test value\"), ] def",
"version=self.version, community=\"public\", peername=address, _use_bulk=self.bulk) self.session.open() def tearDownSession(self): self.session.close() def test_sget(self): result = self.session.sget([x",
"= \"%d-%d-%d,%d\" % (now[0], now[1], now[2], now[3]) result = self.session.sget([OID(\".1.3.6.1.2.1.25.1.2.0\")]) self.assert_(result) value =",
"test_get(self): result = Result() self.session.get([\".1.3.6.1.4.2.1.1\"], set_result, result) self.session.wait() assert isinstance(result.value, SnmpTimeout) def tearDown(self):",
"not zero padded # so we must format the date manually, whee... now",
"the Free Software Foundation. # # This program is distributed in the hope",
"avoid a race condition. # And one more quirk, these dates are not",
"PARTICULAR PURPOSE. See the # GNU General Public License for more details. import",
"test_sysDescr(self): result = self.session.sget([OID(\"SNMPv2-MIB::sysDescr.0\")]) self.assert_(result) self.assertIsInstance(result[0][1], str) self.assert_(len(result[0][1]) > 0) return self.finishGet() class",
"= dict(result.value) for oid in oids: assert oid in result assert result[oid] ==",
"= Result() self.session.get([x for x,v in self.basics], set_result, result) self.session.wait() self.assertEquals(result.value, self.basics) return",
"self.assertEquals(result.value, self.basics) return self.finishGet() def test_get_big(self): oids = [] for i in xrange(1,",
"result, strict=True) self.session.wait() self.assertEquals(result.value, []) return self.finishStrictWalk() def test_sysDescr(self): result = self.session.sget([OID(\"SNMPv2-MIB::sysDescr.0\")]) self.assert_(result)",
"TestTimeoutsV1(unittest.TestCase): version = \"1\" def setUp(self): self.session = Session( version=self.version, community=\"public\", peername=\"udp:127.0.0.1:9\", retries=0,",
"version = \"1\" bulk = False basics = [ (OID(\".1.3.6.1.4.2.1.1\"), 1), (OID(\".1.3.6.1.4.2.1.2\"), -1),",
"ITA Software, Inc. # # This program is free software; you can redistribute",
"set_result, result) self.session.wait() self.assertEquals(result.value, self.basics) return self.finishWalk() def test_walk_leaf(self): oid = OID(\".1.3.6.1.4.2.1.1\") result",
"without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR",
"free software; you can redistribute it and/or # modify it under the terms",
"self.finishWalk() def test_walk_leaf(self): oid = OID(\".1.3.6.1.4.2.1.1\") result = Result() self.session.walk([oid], set_result, result) self.session.wait()",
"self.session.open() def tearDownSession(self): self.session.close() def test_sget(self): result = self.session.sget([x for x,v in self.basics])",
"= False basics = [ (OID(\".1.3.6.1.4.2.1.1\"), 1), (OID(\".1.3.6.1.4.2.1.2\"), -1), (OID(\".1.3.6.1.4.2.1.3\"), 1), (OID(\".1.3.6.1.4.2.1.4\"), \"test",
"self.session.walk([\".1.3.6.1.4.2.1\"], set_result, result) self.session.wait() self.assertEquals(result.value, self.basics) return self.finishWalk() def test_walk_leaf(self): oid = OID(\".1.3.6.1.4.2.1.1\")",
"self.session.sget([OID(\".1.3.6.1.2.1.25.1.2.0\")]) self.assert_(result) value = result[0][1].split(':', 1)[0] self.assertEquals(value, now) return self.finishGet() class TestSessionV2cBulk(TestSessionV2c): bulk",
"# GNU General Public License for more details. import time from twisted.trial import",
"General Public License for more details. import time from twisted.trial import unittest from",
"in result assert result[oid] == \"data data data data\" return self.finishGet() def test_walk_tree(self):",
"set_result, result) self.session.wait() self.assertEquals(result.value, [(oid, 1)]) return self.finishGet() def test_walk_strict(self): oid = OID(\".1.3.6.1.4.2.1.1\")",
"Public License # version 2 as published by the Free Software Foundation. #",
"now[2], now[3]) result = self.session.sget([OID(\".1.3.6.1.2.1.25.1.2.0\")]) self.assert_(result) value = result[0][1].split(':', 1)[0] self.assertEquals(value, now) return",
"peername=\"udp:127.0.0.1:9\", retries=0, timeout=0.1) self.session.open() def test_sget(self): self.assertRaises(SnmpError, self.session.sget, [\".1.3.6.1.4.2.1.1\"]) def test_get(self): result =",
"i in xrange(1, 100): oids.append(OID((1,3,6,1,4,2,4,i))) result = Result() self.session.get(oids, set_result, result) self.session.wait() result",
"oids = [] for i in xrange(1, 100): oids.append(OID((1,3,6,1,4,2,4,i))) result = Result() self.session.get(oids,",
"_use_bulk=self.bulk) self.session.open() def tearDownSession(self): self.session.close() def test_sget(self): result = self.session.sget([x for x,v in",
"self.assertIsInstance(result[0][1], str) self.assert_(len(result[0][1]) > 0) return self.finishGet() class TestSessionV2c(TestSessionV1): version = \"2c\" def",
"Foundation. # # This program is distributed in the hope that it will",
"bulk = True class TestTimeoutsV1(unittest.TestCase): version = \"1\" def setUp(self): self.session = Session(",
"(OID(\".1.3.6.1.4.2.1.3\"), 1), (OID(\".1.3.6.1.4.2.1.4\"), \"test value\"), ] def setUpSession(self, address): self.session = Session( version=self.version,",
"WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A",
"(now[0], now[1], now[2], now[3]) result = self.session.sget([OID(\".1.3.6.1.2.1.25.1.2.0\")]) self.assert_(result) value = result[0][1].split(':', 1)[0] self.assertEquals(value,",
"setUpSession(self, address): self.session = Session( version=self.version, community=\"public\", peername=address, _use_bulk=self.bulk) self.session.open() def tearDownSession(self): self.session.close()",
"that it will be useful, # but WITHOUT ANY WARRANTY; without even the",
"def test_get_small(self): result = Result() self.session.get([x for x,v in self.basics], set_result, result) self.session.wait()",
"result = Result() self.session.get(oids, set_result, result) self.session.wait() result = dict(result.value) for oid in",
"test_walk_leaf(self): oid = OID(\".1.3.6.1.4.2.1.1\") result = Result() self.session.walk([oid], set_result, result) self.session.wait() self.assertEquals(result.value, [(oid,",
"assert result[oid] == \"data data data data\" return self.finishGet() def test_walk_tree(self): result =",
"def test_sysDescr(self): result = self.session.sget([OID(\"SNMPv2-MIB::sysDescr.0\")]) self.assert_(result) self.assertIsInstance(result[0][1], str) self.assert_(len(result[0][1]) > 0) return self.finishGet()",
"result) self.session.wait() result = dict(result.value) for oid in oids: assert oid in result",
"TestSessionV2c(TestSessionV1): version = \"2c\" def test_hrSystemDate(self): # This is a special string that",
"of the GNU General Public License # version 2 as published by the",
"= Result() self.session.walk([\".1.3.6.1.4.2.1\"], set_result, result) self.session.wait() self.assertEquals(result.value, self.basics) return self.finishWalk() def test_walk_leaf(self): oid",
"import unittest from snapy.netsnmp.unittests import TestCase from snapy.netsnmp import Session, SnmpError, SnmpTimeout, OID",
"TestCase from snapy.netsnmp import Session, SnmpError, SnmpTimeout, OID class Result(object): \"\"\"Container for async",
"self.assertRaises(SnmpError, self.session.sget, [\".1.3.6.1.4.2.1.1\"]) def test_get(self): result = Result() self.session.get([\".1.3.6.1.4.2.1.1\"], set_result, result) self.session.wait() assert",
"gets formatted using the # MIB's DISPLAY-HINT value. Also, strip off everything #",
"program is free software; you can redistribute it and/or # modify it under",
"more quirk, these dates are not zero padded # so we must format",
"xrange(1, 100): oids.append(OID((1,3,6,1,4,2,4,i))) result = Result() self.session.get(oids, set_result, result) self.session.wait() result = dict(result.value)",
"General Public License # version 2 as published by the Free Software Foundation.",
"implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the",
"self.assertEquals(result.value, []) return self.finishStrictWalk() def test_sysDescr(self): result = self.session.sget([OID(\"SNMPv2-MIB::sysDescr.0\")]) self.assert_(result) self.assertIsInstance(result[0][1], str) self.assert_(len(result[0][1])",
"it and/or # modify it under the terms of the GNU General Public",
"return self.finishGet() def test_walk_tree(self): result = Result() self.session.walk([\".1.3.6.1.4.2.1\"], set_result, result) self.session.wait() self.assertEquals(result.value, self.basics)",
"import Session, SnmpError, SnmpTimeout, OID class Result(object): \"\"\"Container for async results\"\"\" value =",
"1), (OID(\".1.3.6.1.4.2.1.2\"), -1), (OID(\".1.3.6.1.4.2.1.3\"), 1), (OID(\".1.3.6.1.4.2.1.4\"), \"test value\"), ] def setUpSession(self, address): self.session",
"self.session = Session( version=self.version, community=\"public\", peername=\"udp:127.0.0.1:9\", retries=0, timeout=0.1) self.session.open() def test_sget(self): self.assertRaises(SnmpError, self.session.sget,",
"OID class Result(object): \"\"\"Container for async results\"\"\" value = None def set_result(value, result):",
"the hope that it will be useful, # but WITHOUT ANY WARRANTY; without",
"def test_get(self): result = Result() self.session.get([\".1.3.6.1.4.2.1.1\"], set_result, result) self.session.wait() assert isinstance(result.value, SnmpTimeout) def",
"Result(object): \"\"\"Container for async results\"\"\" value = None def set_result(value, result): result.value =",
"(OID(\".1.3.6.1.4.2.1.2\"), -1), (OID(\".1.3.6.1.4.2.1.3\"), 1), (OID(\".1.3.6.1.4.2.1.4\"), \"test value\"), ] def setUpSession(self, address): self.session =",
"self.session.sget([x for x,v in self.basics]) self.assertEquals(result, self.basics) return self.finishGet() def test_get_small(self): result =",
"now = time.localtime() now = \"%d-%d-%d,%d\" % (now[0], now[1], now[2], now[3]) result =",
"\"data data data data\" return self.finishGet() def test_walk_tree(self): result = Result() self.session.walk([\".1.3.6.1.4.2.1\"], set_result,",
"self.session.close() def test_sget(self): result = self.session.sget([x for x,v in self.basics]) self.assertEquals(result, self.basics) return",
"Result() self.session.get(oids, set_result, result) self.session.wait() result = dict(result.value) for oid in oids: assert",
"the # GNU General Public License for more details. import time from twisted.trial",
"the # MIB's DISPLAY-HINT value. Also, strip off everything # other than the",
"self.session.sget([OID(\"SNMPv2-MIB::sysDescr.0\")]) self.assert_(result) self.assertIsInstance(result[0][1], str) self.assert_(len(result[0][1]) > 0) return self.finishGet() class TestSessionV2c(TestSessionV1): version =",
"self.finishGet() def test_walk_strict(self): oid = OID(\".1.3.6.1.4.2.1.1\") result = Result() self.session.walk([oid], set_result, result, strict=True)",
"class TestSessionV2c(TestSessionV1): version = \"2c\" def test_hrSystemDate(self): # This is a special string",
"test_get_big(self): oids = [] for i in xrange(1, 100): oids.append(OID((1,3,6,1,4,2,4,i))) result = Result()",
"return self.finishGet() def test_get_small(self): result = Result() self.session.get([x for x,v in self.basics], set_result,",
"Also, strip off everything # other than the date and hour to avoid",
"formatted using the # MIB's DISPLAY-HINT value. Also, strip off everything # other",
"assert oid in result assert result[oid] == \"data data data data\" return self.finishGet()",
"= self.session.sget([OID(\"SNMPv2-MIB::sysDescr.0\")]) self.assert_(result) self.assertIsInstance(result[0][1], str) self.assert_(len(result[0][1]) > 0) return self.finishGet() class TestSessionV2c(TestSessionV1): version",
"oid in result assert result[oid] == \"data data data data\" return self.finishGet() def",
"See the # GNU General Public License for more details. import time from",
"import TestCase from snapy.netsnmp import Session, SnmpError, SnmpTimeout, OID class Result(object): \"\"\"Container for",
"A PARTICULAR PURPOSE. See the # GNU General Public License for more details.",
"result) self.session.wait() self.assertEquals(result.value, self.basics) return self.finishGet() def test_get_big(self): oids = [] for i",
"TestSessionV2cBulk(TestSessionV2c): bulk = True class TestTimeoutsV1(unittest.TestCase): version = \"1\" def setUp(self): self.session =",
"isinstance(result.value, SnmpTimeout) def tearDown(self): self.session.close() class TestTimeoutsV2c(TestTimeoutsV1): version = \"2c\" class TestOID(unittest.TestCase): def",
"x,v in self.basics]) self.assertEquals(result, self.basics) return self.finishGet() def test_get_small(self): result = Result() self.session.get([x",
"= Result() self.session.walk([oid], set_result, result) self.session.wait() self.assertEquals(result.value, [(oid, 1)]) return self.finishGet() def test_walk_strict(self):",
"the GNU General Public License # version 2 as published by the Free",
"self.basics) return self.finishGet() def test_get_big(self): oids = [] for i in xrange(1, 100):",
"results\"\"\" value = None def set_result(value, result): result.value = value class TestSessionV1(TestCase): version",
"software; you can redistribute it and/or # modify it under the terms of",
"by the Free Software Foundation. # # This program is distributed in the",
"manually, whee... now = time.localtime() now = \"%d-%d-%d,%d\" % (now[0], now[1], now[2], now[3])",
"strict=True) self.session.wait() self.assertEquals(result.value, []) return self.finishStrictWalk() def test_sysDescr(self): result = self.session.sget([OID(\"SNMPv2-MIB::sysDescr.0\")]) self.assert_(result) self.assertIsInstance(result[0][1],",
"= self.session.sget([OID(\".1.3.6.1.2.1.25.1.2.0\")]) self.assert_(result) value = result[0][1].split(':', 1)[0] self.assertEquals(value, now) return self.finishGet() class TestSessionV2cBulk(TestSessionV2c):",
"result = Result() self.session.walk([oid], set_result, result) self.session.wait() self.assertEquals(result.value, [(oid, 1)]) return self.finishGet() def",
"= Result() self.session.walk([oid], set_result, result, strict=True) self.session.wait() self.assertEquals(result.value, []) return self.finishStrictWalk() def test_sysDescr(self):",
"\"1\" def setUp(self): self.session = Session( version=self.version, community=\"public\", peername=\"udp:127.0.0.1:9\", retries=0, timeout=0.1) self.session.open() def",
"class TestSessionV2cBulk(TestSessionV2c): bulk = True class TestTimeoutsV1(unittest.TestCase): version = \"1\" def setUp(self): self.session",
"result) self.session.wait() self.assertEquals(result.value, [(oid, 1)]) return self.finishGet() def test_walk_strict(self): oid = OID(\".1.3.6.1.4.2.1.1\") result",
"= Session( version=self.version, community=\"public\", peername=\"udp:127.0.0.1:9\", retries=0, timeout=0.1) self.session.open() def test_sget(self): self.assertRaises(SnmpError, self.session.sget, [\".1.3.6.1.4.2.1.1\"])",
"Session, SnmpError, SnmpTimeout, OID class Result(object): \"\"\"Container for async results\"\"\" value = None",
"off everything # other than the date and hour to avoid a race",
"def tearDownSession(self): self.session.close() def test_sget(self): result = self.session.sget([x for x,v in self.basics]) self.assertEquals(result,",
"# # This program is free software; you can redistribute it and/or #",
"# modify it under the terms of the GNU General Public License #",
"from snapy.netsnmp.unittests import TestCase from snapy.netsnmp import Session, SnmpError, SnmpTimeout, OID class Result(object):",
"GNU General Public License # version 2 as published by the Free Software",
"# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General",
"snapy - a python snmp library # # Copyright (C) 2009 ITA Software,",
"self.session.wait() self.assertEquals(result.value, []) return self.finishStrictWalk() def test_sysDescr(self): result = self.session.sget([OID(\"SNMPv2-MIB::sysDescr.0\")]) self.assert_(result) self.assertIsInstance(result[0][1], str)",
"SnmpTimeout, OID class Result(object): \"\"\"Container for async results\"\"\" value = None def set_result(value,",
"% (now[0], now[1], now[2], now[3]) result = self.session.sget([OID(\".1.3.6.1.2.1.25.1.2.0\")]) self.assert_(result) value = result[0][1].split(':', 1)[0]",
"def test_sget(self): result = self.session.sget([x for x,v in self.basics]) self.assertEquals(result, self.basics) return self.finishGet()",
"# MIB's DISPLAY-HINT value. Also, strip off everything # other than the date",
"result[0][1].split(':', 1)[0] self.assertEquals(value, now) return self.finishGet() class TestSessionV2cBulk(TestSessionV2c): bulk = True class TestTimeoutsV1(unittest.TestCase):",
"a special string that gets formatted using the # MIB's DISPLAY-HINT value. Also,",
"def test_sget(self): self.assertRaises(SnmpError, self.session.sget, [\".1.3.6.1.4.2.1.1\"]) def test_get(self): result = Result() self.session.get([\".1.3.6.1.4.2.1.1\"], set_result, result)",
"self.session.wait() assert isinstance(result.value, SnmpTimeout) def tearDown(self): self.session.close() class TestTimeoutsV2c(TestTimeoutsV1): version = \"2c\" class",
"assert isinstance(result.value, SnmpTimeout) def tearDown(self): self.session.close() class TestTimeoutsV2c(TestTimeoutsV1): version = \"2c\" class TestOID(unittest.TestCase):",
"self.assertEquals(value, now) return self.finishGet() class TestSessionV2cBulk(TestSessionV2c): bulk = True class TestTimeoutsV1(unittest.TestCase): version =",
"= time.localtime() now = \"%d-%d-%d,%d\" % (now[0], now[1], now[2], now[3]) result = self.session.sget([OID(\".1.3.6.1.2.1.25.1.2.0\")])",
"= OID(\".1.3.6.1.4.2.1.1\") result = Result() self.session.walk([oid], set_result, result, strict=True) self.session.wait() self.assertEquals(result.value, []) return",
"and/or # modify it under the terms of the GNU General Public License",
"other than the date and hour to avoid a race condition. # And",
"self.session.sget, [\".1.3.6.1.4.2.1.1\"]) def test_get(self): result = Result() self.session.get([\".1.3.6.1.4.2.1.1\"], set_result, result) self.session.wait() assert isinstance(result.value,",
"now) return self.finishGet() class TestSessionV2cBulk(TestSessionV2c): bulk = True class TestTimeoutsV1(unittest.TestCase): version = \"1\"",
"self.session.wait() self.assertEquals(result.value, [(oid, 1)]) return self.finishGet() def test_walk_strict(self): oid = OID(\".1.3.6.1.4.2.1.1\") result =",
"== \"data data data data\" return self.finishGet() def test_walk_tree(self): result = Result() self.session.walk([\".1.3.6.1.4.2.1\"],",
"-1), (OID(\".1.3.6.1.4.2.1.3\"), 1), (OID(\".1.3.6.1.4.2.1.4\"), \"test value\"), ] def setUpSession(self, address): self.session = Session(",
"warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #",
"Result() self.session.walk([\".1.3.6.1.4.2.1\"], set_result, result) self.session.wait() self.assertEquals(result.value, self.basics) return self.finishWalk() def test_walk_leaf(self): oid =",
"(C) 2009 ITA Software, Inc. # # This program is free software; you",
"Result() self.session.walk([oid], set_result, result) self.session.wait() self.assertEquals(result.value, [(oid, 1)]) return self.finishGet() def test_walk_strict(self): oid",
"padded # so we must format the date manually, whee... now = time.localtime()",
"License for more details. import time from twisted.trial import unittest from snapy.netsnmp.unittests import",
"return self.finishGet() class TestSessionV2c(TestSessionV1): version = \"2c\" def test_hrSystemDate(self): # This is a",
"This is a special string that gets formatted using the # MIB's DISPLAY-HINT",
"hour to avoid a race condition. # And one more quirk, these dates",
"retries=0, timeout=0.1) self.session.open() def test_sget(self): self.assertRaises(SnmpError, self.session.sget, [\".1.3.6.1.4.2.1.1\"]) def test_get(self): result = Result()",
"# version 2 as published by the Free Software Foundation. # # This",
"OID(\".1.3.6.1.4.2.1.1\") result = Result() self.session.walk([oid], set_result, result) self.session.wait() self.assertEquals(result.value, [(oid, 1)]) return self.finishGet()",
"value = None def set_result(value, result): result.value = value class TestSessionV1(TestCase): version =",
"string that gets formatted using the # MIB's DISPLAY-HINT value. Also, strip off",
"self.finishGet() def test_get_small(self): result = Result() self.session.get([x for x,v in self.basics], set_result, result)",
"oids: assert oid in result assert result[oid] == \"data data data data\" return",
"= OID(\".1.3.6.1.4.2.1.1\") result = Result() self.session.walk([oid], set_result, result) self.session.wait() self.assertEquals(result.value, [(oid, 1)]) return",
"return self.finishGet() def test_get_big(self): oids = [] for i in xrange(1, 100): oids.append(OID((1,3,6,1,4,2,4,i)))",
"must format the date manually, whee... now = time.localtime() now = \"%d-%d-%d,%d\" %",
"and hour to avoid a race condition. # And one more quirk, these",
"tearDown(self): self.session.close() class TestTimeoutsV2c(TestTimeoutsV1): version = \"2c\" class TestOID(unittest.TestCase): def test_oid_name(self): oid =",
"self.session.wait() self.assertEquals(result.value, self.basics) return self.finishWalk() def test_walk_leaf(self): oid = OID(\".1.3.6.1.4.2.1.1\") result = Result()",
"\"test value\"), ] def setUpSession(self, address): self.session = Session( version=self.version, community=\"public\", peername=address, _use_bulk=self.bulk)",
"set_result, result) self.session.wait() assert isinstance(result.value, SnmpTimeout) def tearDown(self): self.session.close() class TestTimeoutsV2c(TestTimeoutsV1): version =",
"zero padded # so we must format the date manually, whee... now =",
"version=self.version, community=\"public\", peername=\"udp:127.0.0.1:9\", retries=0, timeout=0.1) self.session.open() def test_sget(self): self.assertRaises(SnmpError, self.session.sget, [\".1.3.6.1.4.2.1.1\"]) def test_get(self):",
"- a python snmp library # # Copyright (C) 2009 ITA Software, Inc.",
"now = \"%d-%d-%d,%d\" % (now[0], now[1], now[2], now[3]) result = self.session.sget([OID(\".1.3.6.1.2.1.25.1.2.0\")]) self.assert_(result) value",
"\"\"\"Container for async results\"\"\" value = None def set_result(value, result): result.value = value",
"result = Result() self.session.get([x for x,v in self.basics], set_result, result) self.session.wait() self.assertEquals(result.value, self.basics)",
"it will be useful, # but WITHOUT ANY WARRANTY; without even the implied",
"for i in xrange(1, 100): oids.append(OID((1,3,6,1,4,2,4,i))) result = Result() self.session.get(oids, set_result, result) self.session.wait()",
"set_result, result) self.session.wait() result = dict(result.value) for oid in oids: assert oid in",
"one more quirk, these dates are not zero padded # so we must",
"result = Result() self.session.get([\".1.3.6.1.4.2.1.1\"], set_result, result) self.session.wait() assert isinstance(result.value, SnmpTimeout) def tearDown(self): self.session.close()",
"for x,v in self.basics], set_result, result) self.session.wait() self.assertEquals(result.value, self.basics) return self.finishGet() def test_get_big(self):",
"Result() self.session.get([x for x,v in self.basics], set_result, result) self.session.wait() self.assertEquals(result.value, self.basics) return self.finishGet()",
"peername=address, _use_bulk=self.bulk) self.session.open() def tearDownSession(self): self.session.close() def test_sget(self): result = self.session.sget([x for x,v",
"format the date manually, whee... now = time.localtime() now = \"%d-%d-%d,%d\" % (now[0],",
"(OID(\".1.3.6.1.4.2.1.1\"), 1), (OID(\".1.3.6.1.4.2.1.2\"), -1), (OID(\".1.3.6.1.4.2.1.3\"), 1), (OID(\".1.3.6.1.4.2.1.4\"), \"test value\"), ] def setUpSession(self, address):",
"the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See",
"result = dict(result.value) for oid in oids: assert oid in result assert result[oid]",
"quirk, these dates are not zero padded # so we must format the",
"set_result, result) self.session.wait() self.assertEquals(result.value, self.basics) return self.finishGet() def test_get_big(self): oids = [] for",
"terms of the GNU General Public License # version 2 as published by",
"self.finishGet() def test_get_big(self): oids = [] for i in xrange(1, 100): oids.append(OID((1,3,6,1,4,2,4,i))) result",
"dict(result.value) for oid in oids: assert oid in result assert result[oid] == \"data",
"we must format the date manually, whee... now = time.localtime() now = \"%d-%d-%d,%d\"",
"result.value = value class TestSessionV1(TestCase): version = \"1\" bulk = False basics =",
"more details. import time from twisted.trial import unittest from snapy.netsnmp.unittests import TestCase from",
"(OID(\".1.3.6.1.4.2.1.4\"), \"test value\"), ] def setUpSession(self, address): self.session = Session( version=self.version, community=\"public\", peername=address,",
"the date and hour to avoid a race condition. # And one more",
"\"1\" bulk = False basics = [ (OID(\".1.3.6.1.4.2.1.1\"), 1), (OID(\".1.3.6.1.4.2.1.2\"), -1), (OID(\".1.3.6.1.4.2.1.3\"), 1),",
"or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License",
"it under the terms of the GNU General Public License # version 2",
"= [] for i in xrange(1, 100): oids.append(OID((1,3,6,1,4,2,4,i))) result = Result() self.session.get(oids, set_result,",
"in self.basics], set_result, result) self.session.wait() self.assertEquals(result.value, self.basics) return self.finishGet() def test_get_big(self): oids =",
"version 2 as published by the Free Software Foundation. # # This program",
"self.finishGet() class TestSessionV2c(TestSessionV1): version = \"2c\" def test_hrSystemDate(self): # This is a special",
"value\"), ] def setUpSession(self, address): self.session = Session( version=self.version, community=\"public\", peername=address, _use_bulk=self.bulk) self.session.open()",
"test_hrSystemDate(self): # This is a special string that gets formatted using the #",
"the terms of the GNU General Public License # version 2 as published",
"of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU",
"everything # other than the date and hour to avoid a race condition.",
"using the # MIB's DISPLAY-HINT value. Also, strip off everything # other than",
"# # Copyright (C) 2009 ITA Software, Inc. # # This program is",
"self.session.get([\".1.3.6.1.4.2.1.1\"], set_result, result) self.session.wait() assert isinstance(result.value, SnmpTimeout) def tearDown(self): self.session.close() class TestTimeoutsV2c(TestTimeoutsV1): version",
"self.assertEquals(result.value, [(oid, 1)]) return self.finishGet() def test_walk_strict(self): oid = OID(\".1.3.6.1.4.2.1.1\") result = Result()",
"program is distributed in the hope that it will be useful, # but",
"1)[0] self.assertEquals(value, now) return self.finishGet() class TestSessionV2cBulk(TestSessionV2c): bulk = True class TestTimeoutsV1(unittest.TestCase): version",
"distributed in the hope that it will be useful, # but WITHOUT ANY",
"oids.append(OID((1,3,6,1,4,2,4,i))) result = Result() self.session.get(oids, set_result, result) self.session.wait() result = dict(result.value) for oid",
"details. import time from twisted.trial import unittest from snapy.netsnmp.unittests import TestCase from snapy.netsnmp",
"# This is a special string that gets formatted using the # MIB's",
"return self.finishWalk() def test_walk_leaf(self): oid = OID(\".1.3.6.1.4.2.1.1\") result = Result() self.session.walk([oid], set_result, result)",
"test_walk_tree(self): result = Result() self.session.walk([\".1.3.6.1.4.2.1\"], set_result, result) self.session.wait() self.assertEquals(result.value, self.basics) return self.finishWalk() def",
"self.assert_(result) value = result[0][1].split(':', 1)[0] self.assertEquals(value, now) return self.finishGet() class TestSessionV2cBulk(TestSessionV2c): bulk =",
"= \"2c\" def test_hrSystemDate(self): # This is a special string that gets formatted",
"return self.finishGet() def test_walk_strict(self): oid = OID(\".1.3.6.1.4.2.1.1\") result = Result() self.session.walk([oid], set_result, result,",
"special string that gets formatted using the # MIB's DISPLAY-HINT value. Also, strip",
"result): result.value = value class TestSessionV1(TestCase): version = \"1\" bulk = False basics",
"date and hour to avoid a race condition. # And one more quirk,",
"community=\"public\", peername=address, _use_bulk=self.bulk) self.session.open() def tearDownSession(self): self.session.close() def test_sget(self): result = self.session.sget([x for",
"from snapy.netsnmp import Session, SnmpError, SnmpTimeout, OID class Result(object): \"\"\"Container for async results\"\"\"",
"Free Software Foundation. # # This program is distributed in the hope that",
"def test_walk_strict(self): oid = OID(\".1.3.6.1.4.2.1.1\") result = Result() self.session.walk([oid], set_result, result, strict=True) self.session.wait()",
"under the terms of the GNU General Public License # version 2 as",
"1)]) return self.finishGet() def test_walk_strict(self): oid = OID(\".1.3.6.1.4.2.1.1\") result = Result() self.session.walk([oid], set_result,",
"This program is free software; you can redistribute it and/or # modify it",
"strip off everything # other than the date and hour to avoid a",
"these dates are not zero padded # so we must format the date",
"condition. # And one more quirk, these dates are not zero padded #",
"self.session.get(oids, set_result, result) self.session.wait() result = dict(result.value) for oid in oids: assert oid",
"1), (OID(\".1.3.6.1.4.2.1.4\"), \"test value\"), ] def setUpSession(self, address): self.session = Session( version=self.version, community=\"public\",",
"SnmpError, SnmpTimeout, OID class Result(object): \"\"\"Container for async results\"\"\" value = None def",
"async results\"\"\" value = None def set_result(value, result): result.value = value class TestSessionV1(TestCase):",
"a python snmp library # # Copyright (C) 2009 ITA Software, Inc. #",
"than the date and hour to avoid a race condition. # And one",
"= \"1\" bulk = False basics = [ (OID(\".1.3.6.1.4.2.1.1\"), 1), (OID(\".1.3.6.1.4.2.1.2\"), -1), (OID(\".1.3.6.1.4.2.1.3\"),",
"hope that it will be useful, # but WITHOUT ANY WARRANTY; without even",
"self.session.wait() result = dict(result.value) for oid in oids: assert oid in result assert",
"def test_hrSystemDate(self): # This is a special string that gets formatted using the",
"basics = [ (OID(\".1.3.6.1.4.2.1.1\"), 1), (OID(\".1.3.6.1.4.2.1.2\"), -1), (OID(\".1.3.6.1.4.2.1.3\"), 1), (OID(\".1.3.6.1.4.2.1.4\"), \"test value\"), ]",
"the date manually, whee... now = time.localtime() now = \"%d-%d-%d,%d\" % (now[0], now[1],",
"[]) return self.finishStrictWalk() def test_sysDescr(self): result = self.session.sget([OID(\"SNMPv2-MIB::sysDescr.0\")]) self.assert_(result) self.assertIsInstance(result[0][1], str) self.assert_(len(result[0][1]) >",
"set_result, result, strict=True) self.session.wait() self.assertEquals(result.value, []) return self.finishStrictWalk() def test_sysDescr(self): result = self.session.sget([OID(\"SNMPv2-MIB::sysDescr.0\")])",
"\"2c\" def test_hrSystemDate(self): # This is a special string that gets formatted using",
"= None def set_result(value, result): result.value = value class TestSessionV1(TestCase): version = \"1\"",
"True class TestTimeoutsV1(unittest.TestCase): version = \"1\" def setUp(self): self.session = Session( version=self.version, community=\"public\",",
"for async results\"\"\" value = None def set_result(value, result): result.value = value class",
"twisted.trial import unittest from snapy.netsnmp.unittests import TestCase from snapy.netsnmp import Session, SnmpError, SnmpTimeout,",
"This program is distributed in the hope that it will be useful, #",
"test_sget(self): result = self.session.sget([x for x,v in self.basics]) self.assertEquals(result, self.basics) return self.finishGet() def",
"library # # Copyright (C) 2009 ITA Software, Inc. # # This program",
"useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of #",
"time.localtime() now = \"%d-%d-%d,%d\" % (now[0], now[1], now[2], now[3]) result = self.session.sget([OID(\".1.3.6.1.2.1.25.1.2.0\")]) self.assert_(result)",
"class TestSessionV1(TestCase): version = \"1\" bulk = False basics = [ (OID(\".1.3.6.1.4.2.1.1\"), 1),",
"And one more quirk, these dates are not zero padded # so we",
"= \"2c\" class TestOID(unittest.TestCase): def test_oid_name(self): oid = OID(\"1.3.6.1.2.1.1.1.0\") self.assertEquals(oid, OID(\"SNMPv2-MIB::sysDescr.0\")) self.assertEquals(oid, OID(\"sysDescr.0\"))",
"self.session.get([x for x,v in self.basics], set_result, result) self.session.wait() self.assertEquals(result.value, self.basics) return self.finishGet() def",
"that gets formatted using the # MIB's DISPLAY-HINT value. Also, strip off everything",
"even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.",
"result) self.session.wait() self.assertEquals(result.value, self.basics) return self.finishWalk() def test_walk_leaf(self): oid = OID(\".1.3.6.1.4.2.1.1\") result =",
"= \"1\" def setUp(self): self.session = Session( version=self.version, community=\"public\", peername=\"udp:127.0.0.1:9\", retries=0, timeout=0.1) self.session.open()",
"= Result() self.session.get(oids, set_result, result) self.session.wait() result = dict(result.value) for oid in oids:",
"oid = OID(\".1.3.6.1.4.2.1.1\") result = Result() self.session.walk([oid], set_result, result, strict=True) self.session.wait() self.assertEquals(result.value, [])",
"self.session.walk([oid], set_result, result, strict=True) self.session.wait() self.assertEquals(result.value, []) return self.finishStrictWalk() def test_sysDescr(self): result =",
"result assert result[oid] == \"data data data data\" return self.finishGet() def test_walk_tree(self): result",
"data data data\" return self.finishGet() def test_walk_tree(self): result = Result() self.session.walk([\".1.3.6.1.4.2.1\"], set_result, result)",
"# # This program is distributed in the hope that it will be",
"License # version 2 as published by the Free Software Foundation. # #",
"[(oid, 1)]) return self.finishGet() def test_walk_strict(self): oid = OID(\".1.3.6.1.4.2.1.1\") result = Result() self.session.walk([oid],",
"def test_walk_tree(self): result = Result() self.session.walk([\".1.3.6.1.4.2.1\"], set_result, result) self.session.wait() self.assertEquals(result.value, self.basics) return self.finishWalk()",
"self.assert_(result) self.assertIsInstance(result[0][1], str) self.assert_(len(result[0][1]) > 0) return self.finishGet() class TestSessionV2c(TestSessionV1): version = \"2c\"",
"be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of",
"False basics = [ (OID(\".1.3.6.1.4.2.1.1\"), 1), (OID(\".1.3.6.1.4.2.1.2\"), -1), (OID(\".1.3.6.1.4.2.1.3\"), 1), (OID(\".1.3.6.1.4.2.1.4\"), \"test value\"),",
"race condition. # And one more quirk, these dates are not zero padded",
"can redistribute it and/or # modify it under the terms of the GNU",
"100): oids.append(OID((1,3,6,1,4,2,4,i))) result = Result() self.session.get(oids, set_result, result) self.session.wait() result = dict(result.value) for",
"in self.basics]) self.assertEquals(result, self.basics) return self.finishGet() def test_get_small(self): result = Result() self.session.get([x for",
"Inc. # # This program is free software; you can redistribute it and/or",
"is distributed in the hope that it will be useful, # but WITHOUT",
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public",
"None def set_result(value, result): result.value = value class TestSessionV1(TestCase): version = \"1\" bulk",
"Session( version=self.version, community=\"public\", peername=address, _use_bulk=self.bulk) self.session.open() def tearDownSession(self): self.session.close() def test_sget(self): result =",
"in the hope that it will be useful, # but WITHOUT ANY WARRANTY;",
"value = result[0][1].split(':', 1)[0] self.assertEquals(value, now) return self.finishGet() class TestSessionV2cBulk(TestSessionV2c): bulk = True",
"Copyright (C) 2009 ITA Software, Inc. # # This program is free software;",
"FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for",
"# Copyright (C) 2009 ITA Software, Inc. # # This program is free",
"Public License for more details. import time from twisted.trial import unittest from snapy.netsnmp.unittests",
"set_result(value, result): result.value = value class TestSessionV1(TestCase): version = \"1\" bulk = False",
"for more details. import time from twisted.trial import unittest from snapy.netsnmp.unittests import TestCase",
"Software, Inc. # # This program is free software; you can redistribute it",
"community=\"public\", peername=\"udp:127.0.0.1:9\", retries=0, timeout=0.1) self.session.open() def test_sget(self): self.assertRaises(SnmpError, self.session.sget, [\".1.3.6.1.4.2.1.1\"]) def test_get(self): result",
"TestSessionV1(TestCase): version = \"1\" bulk = False basics = [ (OID(\".1.3.6.1.4.2.1.1\"), 1), (OID(\".1.3.6.1.4.2.1.2\"),",
"def tearDown(self): self.session.close() class TestTimeoutsV2c(TestTimeoutsV1): version = \"2c\" class TestOID(unittest.TestCase): def test_oid_name(self): oid",
"self.session.close() class TestTimeoutsV2c(TestTimeoutsV1): version = \"2c\" class TestOID(unittest.TestCase): def test_oid_name(self): oid = OID(\"1.3.6.1.2.1.1.1.0\")",
"2 as published by the Free Software Foundation. # # This program is",
"result) self.session.wait() assert isinstance(result.value, SnmpTimeout) def tearDown(self): self.session.close() class TestTimeoutsV2c(TestTimeoutsV1): version = \"2c\"",
"self.session.walk([oid], set_result, result) self.session.wait() self.assertEquals(result.value, [(oid, 1)]) return self.finishGet() def test_walk_strict(self): oid =",
"a race condition. # And one more quirk, these dates are not zero",
"return self.finishGet() class TestSessionV2cBulk(TestSessionV2c): bulk = True class TestTimeoutsV1(unittest.TestCase): version = \"1\" def",
"DISPLAY-HINT value. Also, strip off everything # other than the date and hour",
"self.session.wait() self.assertEquals(result.value, self.basics) return self.finishGet() def test_get_big(self): oids = [] for i in",
"def setUp(self): self.session = Session( version=self.version, community=\"public\", peername=\"udp:127.0.0.1:9\", retries=0, timeout=0.1) self.session.open() def test_sget(self):",
"[] for i in xrange(1, 100): oids.append(OID((1,3,6,1,4,2,4,i))) result = Result() self.session.get(oids, set_result, result)",
"Result() self.session.get([\".1.3.6.1.4.2.1.1\"], set_result, result) self.session.wait() assert isinstance(result.value, SnmpTimeout) def tearDown(self): self.session.close() class TestTimeoutsV2c(TestTimeoutsV1):",
"time from twisted.trial import unittest from snapy.netsnmp.unittests import TestCase from snapy.netsnmp import Session,",
"# This program is free software; you can redistribute it and/or # modify",
"are not zero padded # so we must format the date manually, whee...",
"# And one more quirk, these dates are not zero padded # so",
"] def setUpSession(self, address): self.session = Session( version=self.version, community=\"public\", peername=address, _use_bulk=self.bulk) self.session.open() def",
"version = \"1\" def setUp(self): self.session = Session( version=self.version, community=\"public\", peername=\"udp:127.0.0.1:9\", retries=0, timeout=0.1)",
"from twisted.trial import unittest from snapy.netsnmp.unittests import TestCase from snapy.netsnmp import Session, SnmpError,",
"= self.session.sget([x for x,v in self.basics]) self.assertEquals(result, self.basics) return self.finishGet() def test_get_small(self): result",
"test_walk_strict(self): oid = OID(\".1.3.6.1.4.2.1.1\") result = Result() self.session.walk([oid], set_result, result, strict=True) self.session.wait() self.assertEquals(result.value,",
"as published by the Free Software Foundation. # # This program is distributed",
"MIB's DISPLAY-HINT value. Also, strip off everything # other than the date and",
"redistribute it and/or # modify it under the terms of the GNU General",
"now[1], now[2], now[3]) result = self.session.sget([OID(\".1.3.6.1.2.1.25.1.2.0\")]) self.assert_(result) value = result[0][1].split(':', 1)[0] self.assertEquals(value, now)",
"# This program is distributed in the hope that it will be useful,",
"self.assertEquals(result, self.basics) return self.finishGet() def test_get_small(self): result = Result() self.session.get([x for x,v in",
"but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or",
"now[3]) result = self.session.sget([OID(\".1.3.6.1.2.1.25.1.2.0\")]) self.assert_(result) value = result[0][1].split(':', 1)[0] self.assertEquals(value, now) return self.finishGet()",
"= Session( version=self.version, community=\"public\", peername=address, _use_bulk=self.bulk) self.session.open() def tearDownSession(self): self.session.close() def test_sget(self): result",
"[\".1.3.6.1.4.2.1.1\"]) def test_get(self): result = Result() self.session.get([\".1.3.6.1.4.2.1.1\"], set_result, result) self.session.wait() assert isinstance(result.value, SnmpTimeout)",
"oid = OID(\".1.3.6.1.4.2.1.1\") result = Result() self.session.walk([oid], set_result, result) self.session.wait() self.assertEquals(result.value, [(oid, 1)])",
"value. Also, strip off everything # other than the date and hour to",
"oid in oids: assert oid in result assert result[oid] == \"data data data",
"whee... now = time.localtime() now = \"%d-%d-%d,%d\" % (now[0], now[1], now[2], now[3]) result",
"[ (OID(\".1.3.6.1.4.2.1.1\"), 1), (OID(\".1.3.6.1.4.2.1.2\"), -1), (OID(\".1.3.6.1.4.2.1.3\"), 1), (OID(\".1.3.6.1.4.2.1.4\"), \"test value\"), ] def setUpSession(self,",
"result[oid] == \"data data data data\" return self.finishGet() def test_walk_tree(self): result = Result()",
"Session( version=self.version, community=\"public\", peername=\"udp:127.0.0.1:9\", retries=0, timeout=0.1) self.session.open() def test_sget(self): self.assertRaises(SnmpError, self.session.sget, [\".1.3.6.1.4.2.1.1\"]) def",
"result = Result() self.session.walk([oid], set_result, result, strict=True) self.session.wait() self.assertEquals(result.value, []) return self.finishStrictWalk() def",
"import time from twisted.trial import unittest from snapy.netsnmp.unittests import TestCase from snapy.netsnmp import",
"class TestTimeoutsV2c(TestTimeoutsV1): version = \"2c\" class TestOID(unittest.TestCase): def test_oid_name(self): oid = OID(\"1.3.6.1.2.1.1.1.0\") self.assertEquals(oid,",
"bulk = False basics = [ (OID(\".1.3.6.1.4.2.1.1\"), 1), (OID(\".1.3.6.1.4.2.1.2\"), -1), (OID(\".1.3.6.1.4.2.1.3\"), 1), (OID(\".1.3.6.1.4.2.1.4\"),",
"x,v in self.basics], set_result, result) self.session.wait() self.assertEquals(result.value, self.basics) return self.finishGet() def test_get_big(self): oids",
"data data\" return self.finishGet() def test_walk_tree(self): result = Result() self.session.walk([\".1.3.6.1.4.2.1\"], set_result, result) self.session.wait()",
"# snapy - a python snmp library # # Copyright (C) 2009 ITA",
"published by the Free Software Foundation. # # This program is distributed in",
"# so we must format the date manually, whee... now = time.localtime() now",
"self.session = Session( version=self.version, community=\"public\", peername=address, _use_bulk=self.bulk) self.session.open() def tearDownSession(self): self.session.close() def test_sget(self):",
"def set_result(value, result): result.value = value class TestSessionV1(TestCase): version = \"1\" bulk =",
"self.session.open() def test_sget(self): self.assertRaises(SnmpError, self.session.sget, [\".1.3.6.1.4.2.1.1\"]) def test_get(self): result = Result() self.session.get([\".1.3.6.1.4.2.1.1\"], set_result,",
"unittest from snapy.netsnmp.unittests import TestCase from snapy.netsnmp import Session, SnmpError, SnmpTimeout, OID class",
"is free software; you can redistribute it and/or # modify it under the",
"result = Result() self.session.walk([\".1.3.6.1.4.2.1\"], set_result, result) self.session.wait() self.assertEquals(result.value, self.basics) return self.finishWalk() def test_walk_leaf(self):",
"self.assertEquals(result.value, self.basics) return self.finishWalk() def test_walk_leaf(self): oid = OID(\".1.3.6.1.4.2.1.1\") result = Result() self.session.walk([oid],",
"= Result() self.session.get([\".1.3.6.1.4.2.1.1\"], set_result, result) self.session.wait() assert isinstance(result.value, SnmpTimeout) def tearDown(self): self.session.close() class",
"return self.finishStrictWalk() def test_sysDescr(self): result = self.session.sget([OID(\"SNMPv2-MIB::sysDescr.0\")]) self.assert_(result) self.assertIsInstance(result[0][1], str) self.assert_(len(result[0][1]) > 0)",
"snmp library # # Copyright (C) 2009 ITA Software, Inc. # # This",
"in xrange(1, 100): oids.append(OID((1,3,6,1,4,2,4,i))) result = Result() self.session.get(oids, set_result, result) self.session.wait() result =",
"= True class TestTimeoutsV1(unittest.TestCase): version = \"1\" def setUp(self): self.session = Session( version=self.version,",
"self.basics], set_result, result) self.session.wait() self.assertEquals(result.value, self.basics) return self.finishGet() def test_get_big(self): oids = []",
"self.basics) return self.finishGet() def test_get_small(self): result = Result() self.session.get([x for x,v in self.basics],",
"result = self.session.sget([OID(\"SNMPv2-MIB::sysDescr.0\")]) self.assert_(result) self.assertIsInstance(result[0][1], str) self.assert_(len(result[0][1]) > 0) return self.finishGet() class TestSessionV2c(TestSessionV1):",
"python snmp library # # Copyright (C) 2009 ITA Software, Inc. # #",
"str) self.assert_(len(result[0][1]) > 0) return self.finishGet() class TestSessionV2c(TestSessionV1): version = \"2c\" def test_hrSystemDate(self):",
"test_sget(self): self.assertRaises(SnmpError, self.session.sget, [\".1.3.6.1.4.2.1.1\"]) def test_get(self): result = Result() self.session.get([\".1.3.6.1.4.2.1.1\"], set_result, result) self.session.wait()",
"ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR",
"you can redistribute it and/or # modify it under the terms of the",
"date manually, whee... now = time.localtime() now = \"%d-%d-%d,%d\" % (now[0], now[1], now[2],",
"self.finishGet() def test_walk_tree(self): result = Result() self.session.walk([\".1.3.6.1.4.2.1\"], set_result, result) self.session.wait() self.assertEquals(result.value, self.basics) return",
"tearDownSession(self): self.session.close() def test_sget(self): result = self.session.sget([x for x,v in self.basics]) self.assertEquals(result, self.basics)",
"self.finishStrictWalk() def test_sysDescr(self): result = self.session.sget([OID(\"SNMPv2-MIB::sysDescr.0\")]) self.assert_(result) self.assertIsInstance(result[0][1], str) self.assert_(len(result[0][1]) > 0) return",
"self.basics]) self.assertEquals(result, self.basics) return self.finishGet() def test_get_small(self): result = Result() self.session.get([x for x,v",
"setUp(self): self.session = Session( version=self.version, community=\"public\", peername=\"udp:127.0.0.1:9\", retries=0, timeout=0.1) self.session.open() def test_sget(self): self.assertRaises(SnmpError,",
"WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS",
"timeout=0.1) self.session.open() def test_sget(self): self.assertRaises(SnmpError, self.session.sget, [\".1.3.6.1.4.2.1.1\"]) def test_get(self): result = Result() self.session.get([\".1.3.6.1.4.2.1.1\"],",
"GNU General Public License for more details. import time from twisted.trial import unittest",
"result = self.session.sget([OID(\".1.3.6.1.2.1.25.1.2.0\")]) self.assert_(result) value = result[0][1].split(':', 1)[0] self.assertEquals(value, now) return self.finishGet() class",
"> 0) return self.finishGet() class TestSessionV2c(TestSessionV1): version = \"2c\" def test_hrSystemDate(self): # This",
"FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more",
"dates are not zero padded # so we must format the date manually,",
"version = \"2c\" def test_hrSystemDate(self): # This is a special string that gets",
"test_get_small(self): result = Result() self.session.get([x for x,v in self.basics], set_result, result) self.session.wait() self.assertEquals(result.value,",
"value class TestSessionV1(TestCase): version = \"1\" bulk = False basics = [ (OID(\".1.3.6.1.4.2.1.1\"),",
"address): self.session = Session( version=self.version, community=\"public\", peername=address, _use_bulk=self.bulk) self.session.open() def tearDownSession(self): self.session.close() def",
"PURPOSE. See the # GNU General Public License for more details. import time",
"def setUpSession(self, address): self.session = Session( version=self.version, community=\"public\", peername=address, _use_bulk=self.bulk) self.session.open() def tearDownSession(self):",
"data\" return self.finishGet() def test_walk_tree(self): result = Result() self.session.walk([\".1.3.6.1.4.2.1\"], set_result, result) self.session.wait() self.assertEquals(result.value,",
"modify it under the terms of the GNU General Public License # version",
"def test_walk_leaf(self): oid = OID(\".1.3.6.1.4.2.1.1\") result = Result() self.session.walk([oid], set_result, result) self.session.wait() self.assertEquals(result.value,",
"0) return self.finishGet() class TestSessionV2c(TestSessionV1): version = \"2c\" def test_hrSystemDate(self): # This is",
"snapy.netsnmp.unittests import TestCase from snapy.netsnmp import Session, SnmpError, SnmpTimeout, OID class Result(object): \"\"\"Container",
"2009 ITA Software, Inc. # # This program is free software; you can",
"def test_get_big(self): oids = [] for i in xrange(1, 100): oids.append(OID((1,3,6,1,4,2,4,i))) result =",
"in oids: assert oid in result assert result[oid] == \"data data data data\"",
"self.finishGet() class TestSessionV2cBulk(TestSessionV2c): bulk = True class TestTimeoutsV1(unittest.TestCase): version = \"1\" def setUp(self):",
"for oid in oids: assert oid in result assert result[oid] == \"data data",
"is a special string that gets formatted using the # MIB's DISPLAY-HINT value.",
"# other than the date and hour to avoid a race condition. #",
"self.assert_(len(result[0][1]) > 0) return self.finishGet() class TestSessionV2c(TestSessionV1): version = \"2c\" def test_hrSystemDate(self): #",
"to avoid a race condition. # And one more quirk, these dates are",
"SnmpTimeout) def tearDown(self): self.session.close() class TestTimeoutsV2c(TestTimeoutsV1): version = \"2c\" class TestOID(unittest.TestCase): def test_oid_name(self):",
"OID(\".1.3.6.1.4.2.1.1\") result = Result() self.session.walk([oid], set_result, result, strict=True) self.session.wait() self.assertEquals(result.value, []) return self.finishStrictWalk()",
"will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty",
"class Result(object): \"\"\"Container for async results\"\"\" value = None def set_result(value, result): result.value",
"TestTimeoutsV2c(TestTimeoutsV1): version = \"2c\" class TestOID(unittest.TestCase): def test_oid_name(self): oid = OID(\"1.3.6.1.2.1.1.1.0\") self.assertEquals(oid, OID(\"SNMPv2-MIB::sysDescr.0\"))",
"so we must format the date manually, whee... now = time.localtime() now =",
"Software Foundation. # # This program is distributed in the hope that it",
"# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY",
"result = self.session.sget([x for x,v in self.basics]) self.assertEquals(result, self.basics) return self.finishGet() def test_get_small(self):",
"class TestTimeoutsV1(unittest.TestCase): version = \"1\" def setUp(self): self.session = Session( version=self.version, community=\"public\", peername=\"udp:127.0.0.1:9\","
] |
[
"if color is None: return self._decode_pixel(self._block(x, y, x, y)) if 0 <= x",
"data = pixel * _BUFFER_SIZE for _ in range(chunks): self.write(None, data) self.write(None, pixel",
"\"https://github.com/adafruit/Adafruit_CircuitPython_RGB_Display.git\" # This is the size of the buffer to be used for",
"the specified color.\"\"\" self.fill_rectangle(0, 0, self.width, self.height, color) def hline(self, x, y, width,",
"0 # pylint: disable=invalid-name _INIT = () _ENCODE_PIXEL = \">H\" _ENCODE_POS = \">HH\"",
"#pylint: disable-msg=too-many-arguments def __init__(self, spi, dc, cs, rst=None, width=1, height=1, baudrate=12000000, polarity=0, phase=0,",
">> 3 class DummyPin: \"\"\"Can be used in place of a ``DigitalInOut()`` when",
"width = min(self.width - x, max(1, width)) height = min(self.height - y, max(1,",
"def direction(self): \"\"\"Dummy direction DigitalInOut property\"\"\" pass @direction.setter def direction(self, val): pass @property",
"TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.",
"y_offset # pylint: disable=invalid-name super().__init__(width, height) #pylint: enable-msg=too-many-arguments def reset(self): \"\"\"Reset the device\"\"\"",
"& 0xFF #print([hex(x) for x in pixels]) self._block(0, 0, self.width-1, self.height - 1,",
"platform.python_implementation(): # check for FT232H special case try: import os if os.environ['BLINKA_FT232H']: #",
"Library image. The image should be in 1 bit mode and a size",
"90, 180, 270): raise ValueError('Rotation must be 0/90/180/270') if rotation != 0: img",
"position.\"\"\" if color is None: return self._decode_pixel(self._block(x, y, x, y)) if 0 <=",
"EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,",
"Industries # # Permission is hereby granted, free of charge, to any person",
"baudrate=12000000, polarity=0, phase=0, *, x_offset=0, y_offset=0): self.spi_device = spi_device.SPIDevice(spi, cs, baudrate=baudrate, polarity=polarity, phase=phase)",
"set smaller MCU friendly size _BUFFER_SIZE = 256 def color565(r, g=0, b=0): \"\"\"Convert",
"RGB or RGBA') if rotation not in (0, 90, 180, 270): raise ValueError('Rotation",
"imwidth, imheight = img.size if imwidth != self.width or imheight != self.height: raise",
"the Software without restriction, including without limitation the rights # to use, copy,",
"- y, max(1, height)) self._block(x, y, x + width - 1, y +",
"ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN",
"specified color.\"\"\" self.fill_rectangle(0, 0, self.width, self.height, color) def hline(self, x, y, width, color):",
"with self.spi_device as spi: spi.write(data) def read(self, command=None, count=0): \"\"\"SPI read from device",
"fill_rectangle(self, x, y, width, height, color): \"\"\"Draw a rectangle at specified position with",
"class DummyPin: \"\"\"Can be used in place of a ``DigitalInOut()`` when you don't",
"x in pixels]) self._block(0, 0, self.width-1, self.height - 1, pixels) #pylint: disable-msg=too-many-arguments def",
"person obtaining a copy # of this software and associated documentation files (the",
"payload from pyftdi.spi import SpiController _BUFFER_SIZE = SpiController.PAYLOAD_MAX_LENGTH // 2 # max bytes",
"def _encode_pos(self, x, y): \"\"\"Encode a postion into bytes.\"\"\" return struct.pack(self._ENCODE_POS, x, y)",
"at specified position with specified width and height, and fill it with the",
"min(self.height - 1, max(0, y)) width = min(self.width - x, max(1, width)) height",
"y, x + width - 1, y + height - 1, b'') chunks,",
"x + width - 1, y + height - 1, b'') chunks, rest",
"x, y, height, color): \"\"\"Draw a vertical line.\"\"\" self.fill_rectangle(x, y, 1, height, color)",
"__init__(self, spi, dc, cs, rst=None, width=1, height=1, baudrate=12000000, polarity=0, phase=0, *, x_offset=0, y_offset=0):",
"self.rst: self.rst.switch_to_output(value=0) self.reset() self._X_START = x_offset # pylint: disable=invalid-name self._Y_START = y_offset #",
"None: return self._decode_pixel(self._block(x, y, x, y)) if 0 <= x < self.width and",
"double loop is slow, for y in range(self.height): # but these displays are",
"time.sleep(0.050) # 50 milliseconds # pylint: disable=no-member def write(self, command=None, data=None): \"\"\"SPI write",
"don't want to skip it.\"\"\" def deinit(self): \"\"\"Dummy DigitalInOut deinit\"\"\" pass def switch_to_output(self,",
"chunks, rest = divmod(width * height, _BUFFER_SIZE) pixel = self._encode_pixel(color) if chunks: data",
"A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR",
"SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #",
"fill(self, color=0): \"\"\"Fill the whole display with the specified color.\"\"\" self.fill_rectangle(0, 0, self.width,",
"= () _ENCODE_PIXEL = \">H\" _ENCODE_POS = \">HH\" _DECODE_PIXEL = \">BBB\" def __init__(self,",
"should be in 1 bit mode and a size equal to the display",
"# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies",
"1, y + height - 1, b'') chunks, rest = divmod(width * height,",
"not in (0, 90, 180, 270): raise ValueError('Rotation must be 0/90/180/270') if rotation",
"above copyright notice and this permission notice shall be included in # all",
"& 0xf8) << 8 | (g & 0xfc) << 3 | b >>",
"| (g & 0xfc) << 3 | b >> 3 class DummyPin: \"\"\"Can",
"x)) y = min(self.height - 1, max(0, y)) width = min(self.width - x,",
"and blue values (0-255) into a 16-bit 565 encoding. As a convenience this",
"adafruit_rgb_display package namespace.\"\"\" try: r, g, b = r # see if the",
"large as possible import platform if \"CPython\" in platform.python_implementation(): # check for FT232H",
"optional command\"\"\" data = bytearray(count) self.dc_pin.value = 0 with self.spi_device as spi: if",
"self.width or imheight != self.height: raise ValueError('Image must be same dimensions as display",
"* size) self.write(self._RAM_WRITE, data) return None #pylint: enable-msg=invalid-name,too-many-arguments def _encode_pos(self, x, y): \"\"\"Encode",
"is None: return self._decode_pixel(self._block(x, y, x, y)) if 0 <= x < self.width",
"_ENCODE_POS = \">HH\" _DECODE_PIXEL = \">BBB\" def __init__(self, width, height): self.width = width",
"see if the first var is a tuple/list except TypeError: pass return (r",
"the pixels for x in range(self.width): # yes this double loop is slow,",
"is hereby granted, free of charge, to any person obtaining a copy #",
"y, width, height, color): \"\"\"Draw a rectangle at specified position with specified width",
"50 milliseconds self.rst.value = 1 time.sleep(0.050) # 50 milliseconds # pylint: disable=no-member def",
"1 time.sleep(0.050) # 50 milliseconds # pylint: disable=no-member def write(self, command=None, data=None): \"\"\"SPI",
"__version__ = \"0.0.0-auto.0\" __repo__ = \"https://github.com/adafruit/Adafruit_CircuitPython_RGB_Display.git\" # This is the size of the",
"persons to whom the Software is # furnished to do so, subject to",
"pull(self): \"\"\"Dummy pull DigitalInOut property\"\"\" pass @pull.setter def pull(self, val): pass class Display:",
"as display ({0}x{1}).' \\ .format(self.width, self.height)) pixels = bytearray(self.width * self.height * 2)",
"conditions: # # The above copyright notice and this permission notice shall be",
"INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A",
"# pylint: disable=invalid-name _Y_START = 0 # pylint: disable=invalid-name _INIT = () _ENCODE_PIXEL",
"x, y, width, color): \"\"\"Draw a horizontal line.\"\"\" self.fill_rectangle(x, y, width, 1, color)",
"# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE",
"spi: spi.write(bytearray([command])) if data is not None: self.dc_pin.value = 1 with self.spi_device as",
"OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,",
"# we are limited by pyftdi's max SPI payload from pyftdi.spi import SpiController",
"given position.\"\"\" if color is None: return self._decode_pixel(self._block(x, y, x, y)) if 0",
"documentation files (the \"Software\"), to deal # in the Software without restriction, including",
"MCU friendly size _BUFFER_SIZE = 256 def color565(r, g=0, b=0): \"\"\"Convert red, green",
"these displays are small! pix = color565(img.getpixel((x, y))) pixels[2*(y * self.width + x)]",
"+ x) + 1] = pix & 0xFF #print([hex(x) for x in pixels])",
"as spi: spi.write(data) def read(self, command=None, count=0): \"\"\"SPI read from device with optional",
"= min(self.width - 1, max(0, x)) y = min(self.height - 1, max(0, y))",
"x_offset # pylint: disable=invalid-name self._Y_START = y_offset # pylint: disable=invalid-name super().__init__(width, height) #pylint:",
"the first var is a tuple/list except TypeError: pass return (r & 0xf8)",
"to permit persons to whom the Software is # furnished to do so,",
"ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT,",
"or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS",
"1, max(0, y)) width = min(self.width - x, max(1, width)) height = min(self.height",
"\"\"\"Draw a vertical line.\"\"\" self.fill_rectangle(x, y, 1, height, color) class DisplaySPI(Display): \"\"\"Base class",
"self.rst.value = 1 time.sleep(0.050) # 50 milliseconds # pylint: disable=no-member def write(self, command=None,",
"value(self, val): pass @property def direction(self): \"\"\"Dummy direction DigitalInOut property\"\"\" pass @direction.setter def",
"import struct except ImportError: import ustruct as struct import adafruit_bus_device.spi_device as spi_device __version__",
"try to set as large as possible import platform if \"CPython\" in platform.python_implementation():",
"command=None, count=0): \"\"\"SPI read from device with optional command\"\"\" data = bytearray(count) self.dc_pin.value",
"number of pixels wide :param height: number of pixels high \"\"\" _PAGE_SET =",
"def hline(self, x, y, width, color): \"\"\"Draw a horizontal line.\"\"\" self.fill_rectangle(x, y, width,",
"except KeyError: # otherwise set it to blit the whole thing _BUFFER_SIZE =",
"notice and this permission notice shall be included in # all copies or",
"of charge, to any person obtaining a copy # of this software and",
"disable=invalid-name _Y_START = 0 # pylint: disable=invalid-name _INIT = () _ENCODE_PIXEL = \">H\"",
"you don't want to skip it.\"\"\" def deinit(self): \"\"\"Dummy DigitalInOut deinit\"\"\" pass def",
"self._block(x, y, x + width - 1, y + height - 1, b'')",
"friendly size _BUFFER_SIZE = 256 def color565(r, g=0, b=0): \"\"\"Convert red, green and",
"& 0xfc) << 3 | b >> 3 class DummyPin: \"\"\"Can be used",
"not img.mode in ('RGB', 'RGBA'): raise ValueError('Image must be in mode RGB or",
"self.width + x)] = pix >> 8 pixels[2*(y * self.width + x) +",
"namespace.\"\"\" try: r, g, b = r # see if the first var",
"height): self.width = width self.height = height self.init() def init(self): \"\"\"Run the initialization",
"y, height, color): \"\"\"Draw a vertical line.\"\"\" self.fill_rectangle(x, y, 1, height, color) class",
"into bytes.\"\"\" return struct.pack(self._ENCODE_POS, x, y) def _encode_pixel(self, color): \"\"\"Encode a pixel color",
"as spi_device __version__ = \"0.0.0-auto.0\" __repo__ = \"https://github.com/adafruit/Adafruit_CircuitPython_RGB_Display.git\" # This is the size",
"= \"0.0.0-auto.0\" __repo__ = \"https://github.com/adafruit/Adafruit_CircuitPython_RGB_Display.git\" # This is the size of the buffer",
"def __init__(self, width, height): self.width = width self.height = height self.init() def init(self):",
"and this permission notice shall be included in # all copies or substantial",
"= x_offset # pylint: disable=invalid-name self._Y_START = y_offset # pylint: disable=invalid-name super().__init__(width, height)",
"for _ in range(chunks): self.write(None, data) self.write(None, pixel * rest) #pylint: enable-msg=too-many-arguments def",
"3 class DummyPin: \"\"\"Can be used in place of a ``DigitalInOut()`` when you",
":param width: number of pixels wide :param height: number of pixels high \"\"\"",
"*args, **kwargs): \"\"\"Dummy switch_to_input method\"\"\" pass @property def value(self): \"\"\"Dummy value DigitalInOut property\"\"\"",
"def color565(r, g=0, b=0): \"\"\"Convert red, green and blue values (0-255) into a",
"so, subject to the following conditions: # # The above copyright notice and",
"< self.height: self._block(x, y, x, y, self._encode_pixel(color)) return None def image(self, img, rotation=0):",
"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION",
"y = min(self.height - 1, max(0, y)) width = min(self.width - x, max(1,",
"color565(r, g=0, b=0): \"\"\"Convert red, green and blue values (0-255) into a 16-bit",
"method\"\"\" pass @property def value(self): \"\"\"Dummy value DigitalInOut property\"\"\" pass @value.setter def value(self,",
"class Display: #pylint: disable-msg=no-member \"\"\"Base class for all RGB display devices :param width:",
">> 8 pixels[2*(y * self.width + x) + 1] = pix & 0xFF",
"y, max(1, height)) self._block(x, y, x + width - 1, y + height",
"height) #pylint: enable-msg=too-many-arguments def reset(self): \"\"\"Reset the device\"\"\" self.rst.value = 0 time.sleep(0.050) #",
"0 <= y < self.height: self._block(x, y, x, y, self._encode_pixel(color)) return None def",
"bytes into a pixel color.\"\"\" return color565(*struct.unpack(self._DECODE_PIXEL, data)) def pixel(self, x, y, color=None):",
"= None _RAM_WRITE = None _RAM_READ = None _X_START = 0 # pylint:",
"self.height, color) def hline(self, x, y, width, color): \"\"\"Draw a horizontal line.\"\"\" self.fill_rectangle(x,",
"raise ValueError('Image must be same dimensions as display ({0}x{1}).' \\ .format(self.width, self.height)) pixels",
"spi, dc, cs, rst=None, width=1, height=1, baudrate=12000000, polarity=0, phase=0, *, x_offset=0, y_offset=0): self.spi_device",
"os if os.environ['BLINKA_FT232H']: # we are limited by pyftdi's max SPI payload from",
"copy # of this software and associated documentation files (the \"Software\"), to deal",
"pixels) #pylint: disable-msg=too-many-arguments def fill_rectangle(self, x, y, width, height, color): \"\"\"Draw a rectangle",
"= 1 time.sleep(0.050) # 50 milliseconds # pylint: disable=no-member def write(self, command=None, data=None):",
"``DigitalInOut()`` when you don't want to skip it.\"\"\" def deinit(self): \"\"\"Dummy DigitalInOut deinit\"\"\"",
"pass @property def pull(self): \"\"\"Dummy pull DigitalInOut property\"\"\" pass @pull.setter def pull(self, val):",
"_PAGE_SET = None _COLUMN_SET = None _RAM_WRITE = None _RAM_READ = None _X_START",
"min(self.width - 1, max(0, x)) y = min(self.height - 1, max(0, y)) width",
"bytes per pixel except KeyError: # otherwise set it to blit the whole",
"\"\"\"Draw a rectangle at specified position with specified width and height, and fill",
"max(1, height)) self._block(x, y, x + width - 1, y + height -",
"to the following conditions: # # The above copyright notice and this permission",
"included in # all copies or substantial portions of the Software. # #",
"self._decode_pixel(self._block(x, y, x, y)) if 0 <= x < self.width and 0 <=",
"# pylint: disable=invalid-name super().__init__(width, height) #pylint: enable-msg=too-many-arguments def reset(self): \"\"\"Reset the device\"\"\" self.rst.value",
"must be same dimensions as display ({0}x{1}).' \\ .format(self.width, self.height)) pixels = bytearray(self.width",
"__init__(self, width, height): self.width = width self.height = height self.init() def init(self): \"\"\"Run",
"spi: spi.write(data) def read(self, command=None, count=0): \"\"\"SPI read from device with optional command\"\"\"",
"divmod(width * height, _BUFFER_SIZE) pixel = self._encode_pixel(color) if chunks: data = pixel *",
"spi.write(data) def read(self, command=None, count=0): \"\"\"SPI read from device with optional command\"\"\" data",
"or write a block of data.\"\"\" self.write(self._COLUMN_SET, self._encode_pos(x0 + self._X_START, x1 + self._X_START))",
"is also available in the parent adafruit_rgb_display package namespace.\"\"\" try: r, g, b",
"the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF",
"if os.environ['BLINKA_FT232H']: # we are limited by pyftdi's max SPI payload from pyftdi.spi",
"y, width, color): \"\"\"Draw a horizontal line.\"\"\" self.fill_rectangle(x, y, width, 1, color) def",
"rst=None, width=1, height=1, baudrate=12000000, polarity=0, phase=0, *, x_offset=0, y_offset=0): self.spi_device = spi_device.SPIDevice(spi, cs,",
"enable-msg=too-many-arguments def reset(self): \"\"\"Reset the device\"\"\" self.rst.value = 0 time.sleep(0.050) # 50 milliseconds",
"blit the whole thing _BUFFER_SIZE = 320 * 240 else: # in case",
"and associated documentation files (the \"Software\"), to deal # in the Software without",
"yes this double loop is slow, for y in range(self.height): # but these",
"565 encoding. As a convenience this is also available in the parent adafruit_rgb_display",
"* (y1 - y0 + 1) * size) self.write(self._RAM_WRITE, data) return None #pylint:",
"pix >> 8 pixels[2*(y * self.width + x) + 1] = pix &",
"(g & 0xfc) << 3 | b >> 3 class DummyPin: \"\"\"Can be",
"init(self): \"\"\"Run the initialization commands.\"\"\" for command, data in self._INIT: self.write(command, data) #pylint:",
"of pixels wide :param height: number of pixels high \"\"\" _PAGE_SET = None",
"possible import platform if \"CPython\" in platform.python_implementation(): # check for FT232H special case",
"= pixel * _BUFFER_SIZE for _ in range(chunks): self.write(None, data) self.write(None, pixel *",
"is not None: self.dc_pin.value = 0 with self.spi_device as spi: spi.write(bytearray([command])) if data",
"x1 + self._X_START)) self.write(self._PAGE_SET, self._encode_pos(y0 + self._Y_START, y1 + self._Y_START)) if data is",
"self._encode_pos(x0 + self._X_START, x1 + self._X_START)) self.write(self._PAGE_SET, self._encode_pos(y0 + self._Y_START, y1 + self._Y_START))",
"TypeError: pass return (r & 0xf8) << 8 | (g & 0xfc) <<",
"y, 1, height, color) class DisplaySPI(Display): \"\"\"Base class for SPI type devices\"\"\" #pylint:",
"chunks: data = pixel * _BUFFER_SIZE for _ in range(chunks): self.write(None, data) self.write(None,",
"and fill it with the specified color.\"\"\" x = min(self.width - 1, max(0,",
"self.width + x) + 1] = pix & 0xFF #print([hex(x) for x in",
"SPI payload from pyftdi.spi import SpiController _BUFFER_SIZE = SpiController.PAYLOAD_MAX_LENGTH // 2 # max",
"a tuple/list except TypeError: pass return (r & 0xf8) << 8 | (g",
"If we're on CPython, try to set as large as possible import platform",
"g=0, b=0): \"\"\"Convert red, green and blue values (0-255) into a 16-bit 565",
"of pixels high \"\"\" _PAGE_SET = None _COLUMN_SET = None _RAM_WRITE = None",
"!= self.width or imheight != self.height: raise ValueError('Image must be same dimensions as",
"color): \"\"\"Encode a pixel color into bytes.\"\"\" return struct.pack(self._ENCODE_PIXEL, color) def _decode_pixel(self, data):",
"({0}x{1}).' \\ .format(self.width, self.height)) pixels = bytearray(self.width * self.height * 2) # Iterate",
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #",
"in the parent adafruit_rgb_display package namespace.\"\"\" try: r, g, b = r #",
"fill it with the specified color.\"\"\" x = min(self.width - 1, max(0, x))",
"SpiController.PAYLOAD_MAX_LENGTH // 2 # max bytes / bytes per pixel except KeyError: #",
"= spi_device.SPIDevice(spi, cs, baudrate=baudrate, polarity=polarity, phase=phase) self.dc_pin = dc self.rst = rst self.dc_pin.switch_to_output(value=0)",
"# 50 milliseconds # pylint: disable=no-member def write(self, command=None, data=None): \"\"\"SPI write to",
"a given position.\"\"\" if color is None: return self._decode_pixel(self._block(x, y, x, y)) if",
"KeyError: # otherwise set it to blit the whole thing _BUFFER_SIZE = 320",
"BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN",
"return None #pylint: enable-msg=invalid-name,too-many-arguments def _encode_pos(self, x, y): \"\"\"Encode a postion into bytes.\"\"\"",
"sublicense, and/or sell # copies of the Software, and to permit persons to",
"Software is # furnished to do so, subject to the following conditions: #",
"operations, in 16-bit # units. try: # If we're on CPython, try to",
"!= self.height: raise ValueError('Image must be same dimensions as display ({0}x{1}).' \\ .format(self.width,",
"2) # Iterate through the pixels for x in range(self.width): # yes this",
"# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR",
"rotation=0): \"\"\"Set buffer to value of Python Imaging Library image. The image should",
"0xf8) << 8 | (g & 0xfc) << 3 | b >> 3",
"g, b = r # see if the first var is a tuple/list",
"CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT",
"place of a ``DigitalInOut()`` when you don't want to skip it.\"\"\" def deinit(self):",
"image(self, img, rotation=0): \"\"\"Set buffer to value of Python Imaging Library image. The",
"Author(s): <NAME>, <NAME> \"\"\" import time try: import struct except ImportError: import ustruct",
"OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE",
"polarity=polarity, phase=phase) self.dc_pin = dc self.rst = rst self.dc_pin.switch_to_output(value=0) if self.rst: self.rst.switch_to_output(value=0) self.reset()",
"if not img.mode in ('RGB', 'RGBA'): raise ValueError('Image must be in mode RGB",
"be in 1 bit mode and a size equal to the display size.\"\"\"",
"data) self.write(None, pixel * rest) #pylint: enable-msg=too-many-arguments def fill(self, color=0): \"\"\"Fill the whole",
"OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. \"\"\" `adafruit_rgb_display.rgb` ====================================================",
"import os if os.environ['BLINKA_FT232H']: # we are limited by pyftdi's max SPI payload",
"with the specified color.\"\"\" x = min(self.width - 1, max(0, x)) y =",
"THE USE OR OTHER DEALINGS IN # THE SOFTWARE. \"\"\" `adafruit_rgb_display.rgb` ==================================================== Base",
"def pull(self, val): pass class Display: #pylint: disable-msg=no-member \"\"\"Base class for all RGB",
"#pylint: enable-msg=too-many-arguments def fill(self, color=0): \"\"\"Fill the whole display with the specified color.\"\"\"",
"<NAME> and Adafruit Industries # # Permission is hereby granted, free of charge,",
"image. The image should be in 1 bit mode and a size equal",
"polarity=0, phase=0, *, x_offset=0, y_offset=0): self.spi_device = spi_device.SPIDevice(spi, cs, baudrate=baudrate, polarity=polarity, phase=phase) self.dc_pin",
"pyftdi.spi import SpiController _BUFFER_SIZE = SpiController.PAYLOAD_MAX_LENGTH // 2 # max bytes / bytes",
"into a 16-bit 565 encoding. As a convenience this is also available in",
"data\"\"\" if command is not None: self.dc_pin.value = 0 with self.spi_device as spi:",
"height, _BUFFER_SIZE) pixel = self._encode_pixel(color) if chunks: data = pixel * _BUFFER_SIZE for",
"whole thing _BUFFER_SIZE = 320 * 240 else: # in case CircuitPython ever",
"DigitalInOut property\"\"\" pass @value.setter def value(self, val): pass @property def direction(self): \"\"\"Dummy direction",
"with the specified color.\"\"\" self.fill_rectangle(0, 0, self.width, self.height, color) def hline(self, x, y,",
"a pixel at a given position.\"\"\" if color is None: return self._decode_pixel(self._block(x, y,",
"pixels wide :param height: number of pixels high \"\"\" _PAGE_SET = None _COLUMN_SET",
":param height: number of pixels high \"\"\" _PAGE_SET = None _COLUMN_SET = None",
"ImportError: # Otherwise set smaller MCU friendly size _BUFFER_SIZE = 256 def color565(r,",
"*args, **kwargs): \"\"\"Dummy switch_to_output method\"\"\" pass def switch_to_input(self, *args, **kwargs): \"\"\"Dummy switch_to_input method\"\"\"",
"= bytearray(self.width * self.height * 2) # Iterate through the pixels for x",
"through the pixels for x in range(self.width): # yes this double loop is",
"read from device with optional command\"\"\" data = bytearray(count) self.dc_pin.value = 0 with",
"def _encode_pixel(self, color): \"\"\"Encode a pixel color into bytes.\"\"\" return struct.pack(self._ENCODE_PIXEL, color) def",
"= pix & 0xFF #print([hex(x) for x in pixels]) self._block(0, 0, self.width-1, self.height",
"of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY",
"# pylint: disable=invalid-name self._Y_START = y_offset # pylint: disable=invalid-name super().__init__(width, height) #pylint: enable-msg=too-many-arguments",
"a pixel color.\"\"\" return color565(*struct.unpack(self._DECODE_PIXEL, data)) def pixel(self, x, y, color=None): \"\"\"Read or",
"# copies of the Software, and to permit persons to whom the Software",
"pixel * _BUFFER_SIZE for _ in range(chunks): self.write(None, data) self.write(None, pixel * rest)",
"1 bit mode and a size equal to the display size.\"\"\" if not",
"max(1, width)) height = min(self.height - y, max(1, height)) self._block(x, y, x +",
"DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR",
"RGBA') if rotation not in (0, 90, 180, 270): raise ValueError('Rotation must be",
"return (r & 0xf8) << 8 | (g & 0xfc) << 3 |",
"x, y) def _encode_pixel(self, color): \"\"\"Encode a pixel color into bytes.\"\"\" return struct.pack(self._ENCODE_PIXEL,",
"in ('RGB', 'RGBA'): raise ValueError('Image must be in mode RGB or RGBA') if",
"slow, for y in range(self.height): # but these displays are small! pix =",
"_block(self, x0, y0, x1, y1, data=None): \"\"\"Read or write a block of data.\"\"\"",
"package namespace.\"\"\" try: r, g, b = r # see if the first",
"0: img = img.rotate(rotation, expand=True) imwidth, imheight = img.size if imwidth != self.width",
"width)) height = min(self.height - y, max(1, height)) self._block(x, y, x + width",
"SPI type devices\"\"\" #pylint: disable-msg=too-many-arguments def __init__(self, spi, dc, cs, rst=None, width=1, height=1,",
"x, y, color=None): \"\"\"Read or write a pixel at a given position.\"\"\" if",
"self._encode_pixel(color)) return None def image(self, img, rotation=0): \"\"\"Set buffer to value of Python",
"for all RGB display devices :param width: number of pixels wide :param height:",
"height self.init() def init(self): \"\"\"Run the initialization commands.\"\"\" for command, data in self._INIT:",
"THE SOFTWARE. \"\"\" `adafruit_rgb_display.rgb` ==================================================== Base class for all RGB Display devices *",
"def init(self): \"\"\"Run the initialization commands.\"\"\" for command, data in self._INIT: self.write(command, data)",
"self.width and 0 <= y < self.height: self._block(x, y, x, y, self._encode_pixel(color)) return",
"this permission notice shall be included in # all copies or substantial portions",
"_COLUMN_SET = None _RAM_WRITE = None _RAM_READ = None _X_START = 0 #",
"expand=True) imwidth, imheight = img.size if imwidth != self.width or imheight != self.height:",
"import platform if \"CPython\" in platform.python_implementation(): # check for FT232H special case try:",
"width: number of pixels wide :param height: number of pixels high \"\"\" _PAGE_SET",
"self.height: self._block(x, y, x, y, self._encode_pixel(color)) return None def image(self, img, rotation=0): \"\"\"Set",
"height = min(self.height - y, max(1, height)) self._block(x, y, x + width -",
"spi_device.SPIDevice(spi, cs, baudrate=baudrate, polarity=polarity, phase=phase) self.dc_pin = dc self.rst = rst self.dc_pin.switch_to_output(value=0) if",
"milliseconds # pylint: disable=no-member def write(self, command=None, data=None): \"\"\"SPI write to the device:",
"in range(self.width): # yes this double loop is slow, for y in range(self.height):",
"**kwargs): \"\"\"Dummy switch_to_output method\"\"\" pass def switch_to_input(self, *args, **kwargs): \"\"\"Dummy switch_to_input method\"\"\" pass",
"used in place of a ``DigitalInOut()`` when you don't want to skip it.\"\"\"",
"def pull(self): \"\"\"Dummy pull DigitalInOut property\"\"\" pass @pull.setter def pull(self, val): pass class",
"= self._encode_pixel(color) if chunks: data = pixel * _BUFFER_SIZE for _ in range(chunks):",
"(0, 90, 180, 270): raise ValueError('Rotation must be 0/90/180/270') if rotation != 0:",
"with self.spi_device as spi: spi.write(bytearray([command])) if data is not None: self.dc_pin.value = 1",
"+ 1) * size) self.write(self._RAM_WRITE, data) return None #pylint: enable-msg=invalid-name,too-many-arguments def _encode_pos(self, x,",
"_RAM_READ = None _X_START = 0 # pylint: disable=invalid-name _Y_START = 0 #",
"'RGBA'): raise ValueError('Image must be in mode RGB or RGBA') if rotation not",
"in range(self.height): # but these displays are small! pix = color565(img.getpixel((x, y))) pixels[2*(y",
"NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE",
"the parent adafruit_rgb_display package namespace.\"\"\" try: r, g, b = r # see",
"display ({0}x{1}).' \\ .format(self.width, self.height)) pixels = bytearray(self.width * self.height * 2) #",
"software and associated documentation files (the \"Software\"), to deal # in the Software",
"case try: import os if os.environ['BLINKA_FT232H']: # we are limited by pyftdi's max",
"0 # pylint: disable=invalid-name _Y_START = 0 # pylint: disable=invalid-name _INIT = ()",
"1) * (y1 - y0 + 1) * size) self.write(self._RAM_WRITE, data) return None",
"WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT",
"small! pix = color565(img.getpixel((x, y))) pixels[2*(y * self.width + x)] = pix >>",
"y, color=None): \"\"\"Read or write a pixel at a given position.\"\"\" if color",
"OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN",
"x, y, self._encode_pixel(color)) return None def image(self, img, rotation=0): \"\"\"Set buffer to value",
"\"\"\"Set buffer to value of Python Imaging Library image. The image should be",
"be used in place of a ``DigitalInOut()`` when you don't want to skip",
"with self.spi_device as spi: if command is not None: spi.write(bytearray([command])) if count: spi.readinto(data)",
"value DigitalInOut property\"\"\" pass @value.setter def value(self, val): pass @property def direction(self): \"\"\"Dummy",
"None _COLUMN_SET = None _RAM_WRITE = None _RAM_READ = None _X_START = 0",
"r # see if the first var is a tuple/list except TypeError: pass",
"pass def switch_to_input(self, *args, **kwargs): \"\"\"Dummy switch_to_input method\"\"\" pass @property def value(self): \"\"\"Dummy",
"color.\"\"\" x = min(self.width - 1, max(0, x)) y = min(self.height - 1,",
"# The MIT License (MIT) # # Copyright (c) 2017 <NAME> and Adafruit",
"in pixels]) self._block(0, 0, self.width-1, self.height - 1, pixels) #pylint: disable-msg=too-many-arguments def fill_rectangle(self,",
"and to permit persons to whom the Software is # furnished to do",
"use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the",
"0, self.width, self.height, color) def hline(self, x, y, width, color): \"\"\"Draw a horizontal",
"the following conditions: # # The above copyright notice and this permission notice",
"in self._INIT: self.write(command, data) #pylint: disable-msg=invalid-name,too-many-arguments def _block(self, x0, y0, x1, y1, data=None):",
"self.height: raise ValueError('Image must be same dimensions as display ({0}x{1}).' \\ .format(self.width, self.height))",
"check for FT232H special case try: import os if os.environ['BLINKA_FT232H']: # we are",
"LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND",
"OTHER DEALINGS IN # THE SOFTWARE. \"\"\" `adafruit_rgb_display.rgb` ==================================================== Base class for all",
"SOFTWARE. \"\"\" `adafruit_rgb_display.rgb` ==================================================== Base class for all RGB Display devices * Author(s):",
"# furnished to do so, subject to the following conditions: # # The",
"DigitalInOut deinit\"\"\" pass def switch_to_output(self, *args, **kwargs): \"\"\"Dummy switch_to_output method\"\"\" pass def switch_to_input(self,",
"the Software, and to permit persons to whom the Software is # furnished",
"if 0 <= x < self.width and 0 <= y < self.height: self._block(x,",
"rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #",
"but these displays are small! pix = color565(img.getpixel((x, y))) pixels[2*(y * self.width +",
"size _BUFFER_SIZE = 256 def color565(r, g=0, b=0): \"\"\"Convert red, green and blue",
"\"\"\"Dummy switch_to_output method\"\"\" pass def switch_to_input(self, *args, **kwargs): \"\"\"Dummy switch_to_input method\"\"\" pass @property",
"self.dc_pin.value = 0 with self.spi_device as spi: if command is not None: spi.write(bytearray([command]))",
"encoding. As a convenience this is also available in the parent adafruit_rgb_display package",
"<NAME> \"\"\" import time try: import struct except ImportError: import ustruct as struct",
"+ 1) * (y1 - y0 + 1) * size) self.write(self._RAM_WRITE, data) return",
"_decode_pixel(self, data): \"\"\"Decode bytes into a pixel color.\"\"\" return color565(*struct.unpack(self._DECODE_PIXEL, data)) def pixel(self,",
"FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF",
"self._encode_pixel(color) if chunks: data = pixel * _BUFFER_SIZE for _ in range(chunks): self.write(None,",
"_encode_pixel(self, color): \"\"\"Encode a pixel color into bytes.\"\"\" return struct.pack(self._ENCODE_PIXEL, color) def _decode_pixel(self,",
"self.dc_pin.value = 0 with self.spi_device as spi: spi.write(bytearray([command])) if data is not None:",
"(x1 - x0 + 1) * (y1 - y0 + 1) * size)",
"except ImportError: import ustruct as struct import adafruit_bus_device.spi_device as spi_device __version__ = \"0.0.0-auto.0\"",
"values (0-255) into a 16-bit 565 encoding. As a convenience this is also",
"must be 0/90/180/270') if rotation != 0: img = img.rotate(rotation, expand=True) imwidth, imheight",
"merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to",
"+ 1] = pix & 0xFF #print([hex(x) for x in pixels]) self._block(0, 0,",
"color=0): \"\"\"Fill the whole display with the specified color.\"\"\" self.fill_rectangle(0, 0, self.width, self.height,",
"None: self.dc_pin.value = 1 with self.spi_device as spi: spi.write(data) def read(self, command=None, count=0):",
"OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING",
"self.dc_pin = dc self.rst = rst self.dc_pin.switch_to_output(value=0) if self.rst: self.rst.switch_to_output(value=0) self.reset() self._X_START =",
"imheight != self.height: raise ValueError('Image must be same dimensions as display ({0}x{1}).' \\",
"- 1, y + height - 1, b'') chunks, rest = divmod(width *",
"ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE",
"max SPI payload from pyftdi.spi import SpiController _BUFFER_SIZE = SpiController.PAYLOAD_MAX_LENGTH // 2 #",
"imheight = img.size if imwidth != self.width or imheight != self.height: raise ValueError('Image",
"height: number of pixels high \"\"\" _PAGE_SET = None _COLUMN_SET = None _RAM_WRITE",
"in # all copies or substantial portions of the Software. # # THE",
"disable=invalid-name _INIT = () _ENCODE_PIXEL = \">H\" _ENCODE_POS = \">HH\" _DECODE_PIXEL = \">BBB\"",
"to do so, subject to the following conditions: # # The above copyright",
"command\"\"\" data = bytearray(count) self.dc_pin.value = 0 with self.spi_device as spi: if command",
"def reset(self): \"\"\"Reset the device\"\"\" self.rst.value = 0 time.sleep(0.050) # 50 milliseconds self.rst.value",
"_BUFFER_SIZE) pixel = self._encode_pixel(color) if chunks: data = pixel * _BUFFER_SIZE for _",
"dc, cs, rst=None, width=1, height=1, baudrate=12000000, polarity=0, phase=0, *, x_offset=0, y_offset=0): self.spi_device =",
"= \"https://github.com/adafruit/Adafruit_CircuitPython_RGB_Display.git\" # This is the size of the buffer to be used",
"\"\"\" _PAGE_SET = None _COLUMN_SET = None _RAM_WRITE = None _RAM_READ = None",
"<< 3 | b >> 3 class DummyPin: \"\"\"Can be used in place",
"def deinit(self): \"\"\"Dummy DigitalInOut deinit\"\"\" pass def switch_to_output(self, *args, **kwargs): \"\"\"Dummy switch_to_output method\"\"\"",
"size = struct.calcsize(self._DECODE_PIXEL) return self.read(self._RAM_READ, (x1 - x0 + 1) * (y1 -",
"color into bytes.\"\"\" return struct.pack(self._ENCODE_PIXEL, color) def _decode_pixel(self, data): \"\"\"Decode bytes into a",
"Display: #pylint: disable-msg=no-member \"\"\"Base class for all RGB display devices :param width: number",
"= struct.calcsize(self._DECODE_PIXEL) return self.read(self._RAM_READ, (x1 - x0 + 1) * (y1 - y0",
"= pix >> 8 pixels[2*(y * self.width + x) + 1] = pix",
"this double loop is slow, for y in range(self.height): # but these displays",
"spi_device __version__ = \"0.0.0-auto.0\" __repo__ = \"https://github.com/adafruit/Adafruit_CircuitPython_RGB_Display.git\" # This is the size of",
"img = img.rotate(rotation, expand=True) imwidth, imheight = img.size if imwidth != self.width or",
"y))) pixels[2*(y * self.width + x)] = pix >> 8 pixels[2*(y * self.width",
"\"\"\"Fill the whole display with the specified color.\"\"\" self.fill_rectangle(0, 0, self.width, self.height, color)",
"want to skip it.\"\"\" def deinit(self): \"\"\"Dummy DigitalInOut deinit\"\"\" pass def switch_to_output(self, *args,",
"def value(self): \"\"\"Dummy value DigitalInOut property\"\"\" pass @value.setter def value(self, val): pass @property",
"pass @direction.setter def direction(self, val): pass @property def pull(self): \"\"\"Dummy pull DigitalInOut property\"\"\"",
"a postion into bytes.\"\"\" return struct.pack(self._ENCODE_POS, x, y) def _encode_pixel(self, color): \"\"\"Encode a",
"The image should be in 1 bit mode and a size equal to",
"max(0, y)) width = min(self.width - x, max(1, width)) height = min(self.height -",
"convenience this is also available in the parent adafruit_rgb_display package namespace.\"\"\" try: r,",
"None _RAM_WRITE = None _RAM_READ = None _X_START = 0 # pylint: disable=invalid-name",
"value(self): \"\"\"Dummy value DigitalInOut property\"\"\" pass @value.setter def value(self, val): pass @property def",
"x)] = pix >> 8 pixels[2*(y * self.width + x) + 1] =",
"_BUFFER_SIZE = 320 * 240 else: # in case CircuitPython ever implements platform",
"it.\"\"\" def deinit(self): \"\"\"Dummy DigitalInOut deinit\"\"\" pass def switch_to_output(self, *args, **kwargs): \"\"\"Dummy switch_to_output",
"in platform.python_implementation(): # check for FT232H special case try: import os if os.environ['BLINKA_FT232H']:",
"_Y_START = 0 # pylint: disable=invalid-name _INIT = () _ENCODE_PIXEL = \">H\" _ENCODE_POS",
"in 16-bit # units. try: # If we're on CPython, try to set",
"a horizontal line.\"\"\" self.fill_rectangle(x, y, width, 1, color) def vline(self, x, y, height,",
"device with optional command\"\"\" data = bytearray(count) self.dc_pin.value = 0 with self.spi_device as",
"whom the Software is # furnished to do so, subject to the following",
"device\"\"\" self.rst.value = 0 time.sleep(0.050) # 50 milliseconds self.rst.value = 1 time.sleep(0.050) #",
"IN # THE SOFTWARE. \"\"\" `adafruit_rgb_display.rgb` ==================================================== Base class for all RGB Display",
"CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH",
"milliseconds self.rst.value = 1 time.sleep(0.050) # 50 milliseconds # pylint: disable=no-member def write(self,",
"super().__init__(width, height) #pylint: enable-msg=too-many-arguments def reset(self): \"\"\"Reset the device\"\"\" self.rst.value = 0 time.sleep(0.050)",
"# This is the size of the buffer to be used for fill",
"if chunks: data = pixel * _BUFFER_SIZE for _ in range(chunks): self.write(None, data)",
"pylint: disable=no-member def write(self, command=None, data=None): \"\"\"SPI write to the device: commands and",
"in 1 bit mode and a size equal to the display size.\"\"\" if",
"smaller MCU friendly size _BUFFER_SIZE = 256 def color565(r, g=0, b=0): \"\"\"Convert red,",
"be in mode RGB or RGBA') if rotation not in (0, 90, 180,",
"self.write(None, pixel * rest) #pylint: enable-msg=too-many-arguments def fill(self, color=0): \"\"\"Fill the whole display",
"color.\"\"\" return color565(*struct.unpack(self._DECODE_PIXEL, data)) def pixel(self, x, y, color=None): \"\"\"Read or write a",
"y)) width = min(self.width - x, max(1, width)) height = min(self.height - y,",
"self.dc_pin.value = 1 with self.spi_device as spi: spi.write(data) def read(self, command=None, count=0): \"\"\"SPI",
"free of charge, to any person obtaining a copy # of this software",
"y0 + 1) * size) self.write(self._RAM_WRITE, data) return None #pylint: enable-msg=invalid-name,too-many-arguments def _encode_pos(self,",
"= img.rotate(rotation, expand=True) imwidth, imheight = img.size if imwidth != self.width or imheight",
"def fill_rectangle(self, x, y, width, height, color): \"\"\"Draw a rectangle at specified position",
"= dc self.rst = rst self.dc_pin.switch_to_output(value=0) if self.rst: self.rst.switch_to_output(value=0) self.reset() self._X_START = x_offset",
"if rotation not in (0, 90, 180, 270): raise ValueError('Rotation must be 0/90/180/270')",
"256 except ImportError: # Otherwise set smaller MCU friendly size _BUFFER_SIZE = 256",
"with optional command\"\"\" data = bytearray(count) self.dc_pin.value = 0 with self.spi_device as spi:",
"is None: size = struct.calcsize(self._DECODE_PIXEL) return self.read(self._RAM_READ, (x1 - x0 + 1) *",
"320 * 240 else: # in case CircuitPython ever implements platform _BUFFER_SIZE =",
"PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT",
"__repo__ = \"https://github.com/adafruit/Adafruit_CircuitPython_RGB_Display.git\" # This is the size of the buffer to be",
"y in range(self.height): # but these displays are small! pix = color565(img.getpixel((x, y)))",
"copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software,",
"disable-msg=no-member \"\"\"Base class for all RGB display devices :param width: number of pixels",
"specified position with specified width and height, and fill it with the specified",
"pylint: disable=invalid-name super().__init__(width, height) #pylint: enable-msg=too-many-arguments def reset(self): \"\"\"Reset the device\"\"\" self.rst.value =",
"commands and data\"\"\" if command is not None: self.dc_pin.value = 0 with self.spi_device",
"pass @value.setter def value(self, val): pass @property def direction(self): \"\"\"Dummy direction DigitalInOut property\"\"\"",
"equal to the display size.\"\"\" if not img.mode in ('RGB', 'RGBA'): raise ValueError('Image",
"horizontal line.\"\"\" self.fill_rectangle(x, y, width, 1, color) def vline(self, x, y, height, color):",
"rotation != 0: img = img.rotate(rotation, expand=True) imwidth, imheight = img.size if imwidth",
"8 | (g & 0xfc) << 3 | b >> 3 class DummyPin:",
"ImportError: import ustruct as struct import adafruit_bus_device.spi_device as spi_device __version__ = \"0.0.0-auto.0\" __repo__",
"without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense,",
"color is None: return self._decode_pixel(self._block(x, y, x, y)) if 0 <= x <",
"is # furnished to do so, subject to the following conditions: # #",
"to set as large as possible import platform if \"CPython\" in platform.python_implementation(): #",
"Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY",
"None #pylint: enable-msg=invalid-name,too-many-arguments def _encode_pos(self, x, y): \"\"\"Encode a postion into bytes.\"\"\" return",
"size equal to the display size.\"\"\" if not img.mode in ('RGB', 'RGBA'): raise",
"y_offset=0): self.spi_device = spi_device.SPIDevice(spi, cs, baudrate=baudrate, polarity=polarity, phase=phase) self.dc_pin = dc self.rst =",
"def write(self, command=None, data=None): \"\"\"SPI write to the device: commands and data\"\"\" if",
"size) self.write(self._RAM_WRITE, data) return None #pylint: enable-msg=invalid-name,too-many-arguments def _encode_pos(self, x, y): \"\"\"Encode a",
"\"\"\"SPI write to the device: commands and data\"\"\" if command is not None:",
"disable=no-member def write(self, command=None, data=None): \"\"\"SPI write to the device: commands and data\"\"\"",
"wide :param height: number of pixels high \"\"\" _PAGE_SET = None _COLUMN_SET =",
"As a convenience this is also available in the parent adafruit_rgb_display package namespace.\"\"\"",
"it to blit the whole thing _BUFFER_SIZE = 320 * 240 else: #",
"to deal # in the Software without restriction, including without limitation the rights",
"# but these displays are small! pix = color565(img.getpixel((x, y))) pixels[2*(y * self.width",
"self.write(None, data) self.write(None, pixel * rest) #pylint: enable-msg=too-many-arguments def fill(self, color=0): \"\"\"Fill the",
"to any person obtaining a copy # of this software and associated documentation",
"number of pixels high \"\"\" _PAGE_SET = None _COLUMN_SET = None _RAM_WRITE =",
"width self.height = height self.init() def init(self): \"\"\"Run the initialization commands.\"\"\" for command,",
"ValueError('Rotation must be 0/90/180/270') if rotation != 0: img = img.rotate(rotation, expand=True) imwidth,",
"* height, _BUFFER_SIZE) pixel = self._encode_pixel(color) if chunks: data = pixel * _BUFFER_SIZE",
"This is the size of the buffer to be used for fill operations,",
"x = min(self.width - 1, max(0, x)) y = min(self.height - 1, max(0,",
"switch_to_output method\"\"\" pass def switch_to_input(self, *args, **kwargs): \"\"\"Dummy switch_to_input method\"\"\" pass @property def",
"self._INIT: self.write(command, data) #pylint: disable-msg=invalid-name,too-many-arguments def _block(self, x0, y0, x1, y1, data=None): \"\"\"Read",
"to the display size.\"\"\" if not img.mode in ('RGB', 'RGBA'): raise ValueError('Image must",
"units. try: # If we're on CPython, try to set as large as",
"+ self._X_START)) self.write(self._PAGE_SET, self._encode_pos(y0 + self._Y_START, y1 + self._Y_START)) if data is None:",
"by pyftdi's max SPI payload from pyftdi.spi import SpiController _BUFFER_SIZE = SpiController.PAYLOAD_MAX_LENGTH //",
"`adafruit_rgb_display.rgb` ==================================================== Base class for all RGB Display devices * Author(s): <NAME>, <NAME>",
"max(0, x)) y = min(self.height - 1, max(0, y)) width = min(self.width -",
"permission notice shall be included in # all copies or substantial portions of",
"None: size = struct.calcsize(self._DECODE_PIXEL) return self.read(self._RAM_READ, (x1 - x0 + 1) * (y1",
"be used for fill operations, in 16-bit # units. try: # If we're",
"value of Python Imaging Library image. The image should be in 1 bit",
"OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #",
"case CircuitPython ever implements platform _BUFFER_SIZE = 256 except ImportError: # Otherwise set",
"# max bytes / bytes per pixel except KeyError: # otherwise set it",
"\">BBB\" def __init__(self, width, height): self.width = width self.height = height self.init() def",
"y, self._encode_pixel(color)) return None def image(self, img, rotation=0): \"\"\"Set buffer to value of",
"x, y, width, height, color): \"\"\"Draw a rectangle at specified position with specified",
"- 1, b'') chunks, rest = divmod(width * height, _BUFFER_SIZE) pixel = self._encode_pixel(color)",
"self.init() def init(self): \"\"\"Run the initialization commands.\"\"\" for command, data in self._INIT: self.write(command,",
"@pull.setter def pull(self, val): pass class Display: #pylint: disable-msg=no-member \"\"\"Base class for all",
"* self.height * 2) # Iterate through the pixels for x in range(self.width):",
"= 256 except ImportError: # Otherwise set smaller MCU friendly size _BUFFER_SIZE =",
"THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN",
"adafruit_bus_device.spi_device as spi_device __version__ = \"0.0.0-auto.0\" __repo__ = \"https://github.com/adafruit/Adafruit_CircuitPython_RGB_Display.git\" # This is the",
"DummyPin: \"\"\"Can be used in place of a ``DigitalInOut()`` when you don't want",
"for x in pixels]) self._block(0, 0, self.width-1, self.height - 1, pixels) #pylint: disable-msg=too-many-arguments",
"#pylint: disable-msg=too-many-arguments def fill_rectangle(self, x, y, width, height, color): \"\"\"Draw a rectangle at",
"height)) self._block(x, y, x + width - 1, y + height - 1,",
"@property def value(self): \"\"\"Dummy value DigitalInOut property\"\"\" pass @value.setter def value(self, val): pass",
"also available in the parent adafruit_rgb_display package namespace.\"\"\" try: r, g, b =",
"loop is slow, for y in range(self.height): # but these displays are small!",
"OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE",
"a convenience this is also available in the parent adafruit_rgb_display package namespace.\"\"\" try:",
"#pylint: disable-msg=no-member \"\"\"Base class for all RGB display devices :param width: number of",
"* _BUFFER_SIZE for _ in range(chunks): self.write(None, data) self.write(None, pixel * rest) #pylint:",
"high \"\"\" _PAGE_SET = None _COLUMN_SET = None _RAM_WRITE = None _RAM_READ =",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #",
"SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES",
"pixels[2*(y * self.width + x)] = pix >> 8 pixels[2*(y * self.width +",
"self.height)) pixels = bytearray(self.width * self.height * 2) # Iterate through the pixels",
"# pylint: disable=invalid-name _INIT = () _ENCODE_PIXEL = \">H\" _ENCODE_POS = \">HH\" _DECODE_PIXEL",
"DigitalInOut property\"\"\" pass @direction.setter def direction(self, val): pass @property def pull(self): \"\"\"Dummy pull",
"self.write(self._PAGE_SET, self._encode_pos(y0 + self._Y_START, y1 + self._Y_START)) if data is None: size =",
"if \"CPython\" in platform.python_implementation(): # check for FT232H special case try: import os",
"@property def direction(self): \"\"\"Dummy direction DigitalInOut property\"\"\" pass @direction.setter def direction(self, val): pass",
"self.rst.switch_to_output(value=0) self.reset() self._X_START = x_offset # pylint: disable=invalid-name self._Y_START = y_offset # pylint:",
"Software, and to permit persons to whom the Software is # furnished to",
"1] = pix & 0xFF #print([hex(x) for x in pixels]) self._block(0, 0, self.width-1,",
"from pyftdi.spi import SpiController _BUFFER_SIZE = SpiController.PAYLOAD_MAX_LENGTH // 2 # max bytes /",
"pixels high \"\"\" _PAGE_SET = None _COLUMN_SET = None _RAM_WRITE = None _RAM_READ",
"\">H\" _ENCODE_POS = \">HH\" _DECODE_PIXEL = \">BBB\" def __init__(self, width, height): self.width =",
"/ bytes per pixel except KeyError: # otherwise set it to blit the",
"width, 1, color) def vline(self, x, y, height, color): \"\"\"Draw a vertical line.\"\"\"",
"val): pass @property def direction(self): \"\"\"Dummy direction DigitalInOut property\"\"\" pass @direction.setter def direction(self,",
"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE.",
"if command is not None: self.dc_pin.value = 0 with self.spi_device as spi: spi.write(bytearray([command]))",
"self.write(self._COLUMN_SET, self._encode_pos(x0 + self._X_START, x1 + self._X_START)) self.write(self._PAGE_SET, self._encode_pos(y0 + self._Y_START, y1 +",
"displays are small! pix = color565(img.getpixel((x, y))) pixels[2*(y * self.width + x)] =",
"* self.width + x) + 1] = pix & 0xFF #print([hex(x) for x",
"this software and associated documentation files (the \"Software\"), to deal # in the",
"in mode RGB or RGBA') if rotation not in (0, 90, 180, 270):",
"platform if \"CPython\" in platform.python_implementation(): # check for FT232H special case try: import",
"= None _COLUMN_SET = None _RAM_WRITE = None _RAM_READ = None _X_START =",
"==================================================== Base class for all RGB Display devices * Author(s): <NAME>, <NAME> \"\"\"",
"direction(self): \"\"\"Dummy direction DigitalInOut property\"\"\" pass @direction.setter def direction(self, val): pass @property def",
"- x0 + 1) * (y1 - y0 + 1) * size) self.write(self._RAM_WRITE,",
"pass @property def value(self): \"\"\"Dummy value DigitalInOut property\"\"\" pass @value.setter def value(self, val):",
"pix & 0xFF #print([hex(x) for x in pixels]) self._block(0, 0, self.width-1, self.height -",
"rst self.dc_pin.switch_to_output(value=0) if self.rst: self.rst.switch_to_output(value=0) self.reset() self._X_START = x_offset # pylint: disable=invalid-name self._Y_START",
"() _ENCODE_PIXEL = \">H\" _ENCODE_POS = \">HH\" _DECODE_PIXEL = \">BBB\" def __init__(self, width,",
"0xFF #print([hex(x) for x in pixels]) self._block(0, 0, self.width-1, self.height - 1, pixels)",
"x in range(self.width): # yes this double loop is slow, for y in",
"- 1, max(0, x)) y = min(self.height - 1, max(0, y)) width =",
"2017 <NAME> and Adafruit Industries # # Permission is hereby granted, free of",
"pull(self, val): pass class Display: #pylint: disable-msg=no-member \"\"\"Base class for all RGB display",
"shall be included in # all copies or substantial portions of the Software.",
"OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY,",
"display devices :param width: number of pixels wide :param height: number of pixels",
"block of data.\"\"\" self.write(self._COLUMN_SET, self._encode_pos(x0 + self._X_START, x1 + self._X_START)) self.write(self._PAGE_SET, self._encode_pos(y0 +",
"pull DigitalInOut property\"\"\" pass @pull.setter def pull(self, val): pass class Display: #pylint: disable-msg=no-member",
"granted, free of charge, to any person obtaining a copy # of this",
"pixel = self._encode_pixel(color) if chunks: data = pixel * _BUFFER_SIZE for _ in",
"all RGB display devices :param width: number of pixels wide :param height: number",
"commands.\"\"\" for command, data in self._INIT: self.write(command, data) #pylint: disable-msg=invalid-name,too-many-arguments def _block(self, x0,",
"x) + 1] = pix & 0xFF #print([hex(x) for x in pixels]) self._block(0,",
"50 milliseconds # pylint: disable=no-member def write(self, command=None, data=None): \"\"\"SPI write to the",
"to be used for fill operations, in 16-bit # units. try: # If",
"first var is a tuple/list except TypeError: pass return (r & 0xf8) <<",
"except ImportError: # Otherwise set smaller MCU friendly size _BUFFER_SIZE = 256 def",
"@direction.setter def direction(self, val): pass @property def pull(self): \"\"\"Dummy pull DigitalInOut property\"\"\" pass",
"\"\"\"Run the initialization commands.\"\"\" for command, data in self._INIT: self.write(command, data) #pylint: disable-msg=invalid-name,too-many-arguments",
"data is None: size = struct.calcsize(self._DECODE_PIXEL) return self.read(self._RAM_READ, (x1 - x0 + 1)",
"specified color.\"\"\" x = min(self.width - 1, max(0, x)) y = min(self.height -",
"bytearray(self.width * self.height * 2) # Iterate through the pixels for x in",
"def switch_to_input(self, *args, **kwargs): \"\"\"Dummy switch_to_input method\"\"\" pass @property def value(self): \"\"\"Dummy value",
"y < self.height: self._block(x, y, x, y, self._encode_pixel(color)) return None def image(self, img,",
"#pylint: enable-msg=too-many-arguments def reset(self): \"\"\"Reset the device\"\"\" self.rst.value = 0 time.sleep(0.050) # 50",
"the specified color.\"\"\" x = min(self.width - 1, max(0, x)) y = min(self.height",
"if data is None: size = struct.calcsize(self._DECODE_PIXEL) return self.read(self._RAM_READ, (x1 - x0 +",
"- x, max(1, width)) height = min(self.height - y, max(1, height)) self._block(x, y,",
"furnished to do so, subject to the following conditions: # # The above",
"width - 1, y + height - 1, b'') chunks, rest = divmod(width",
"modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and",
"(MIT) # # Copyright (c) 2017 <NAME> and Adafruit Industries # # Permission",
"ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES",
"line.\"\"\" self.fill_rectangle(x, y, 1, height, color) class DisplaySPI(Display): \"\"\"Base class for SPI type",
"\"\"\"SPI read from device with optional command\"\"\" data = bytearray(count) self.dc_pin.value = 0",
"# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
"def pixel(self, x, y, color=None): \"\"\"Read or write a pixel at a given",
"# Permission is hereby granted, free of charge, to any person obtaining a",
"buffer to be used for fill operations, in 16-bit # units. try: #",
"IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF",
"img.size if imwidth != self.width or imheight != self.height: raise ValueError('Image must be",
"min(self.height - y, max(1, height)) self._block(x, y, x + width - 1, y",
"when you don't want to skip it.\"\"\" def deinit(self): \"\"\"Dummy DigitalInOut deinit\"\"\" pass",
"it with the specified color.\"\"\" x = min(self.width - 1, max(0, x)) y",
"if data is not None: self.dc_pin.value = 1 with self.spi_device as spi: spi.write(data)",
"direction DigitalInOut property\"\"\" pass @direction.setter def direction(self, val): pass @property def pull(self): \"\"\"Dummy",
"self.read(self._RAM_READ, (x1 - x0 + 1) * (y1 - y0 + 1) *",
"# units. try: # If we're on CPython, try to set as large",
"publish, distribute, sublicense, and/or sell # copies of the Software, and to permit",
"0xfc) << 3 | b >> 3 class DummyPin: \"\"\"Can be used in",
"with specified width and height, and fill it with the specified color.\"\"\" x",
"class DisplaySPI(Display): \"\"\"Base class for SPI type devices\"\"\" #pylint: disable-msg=too-many-arguments def __init__(self, spi,",
"per pixel except KeyError: # otherwise set it to blit the whole thing",
"\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT",
"0 with self.spi_device as spi: if command is not None: spi.write(bytearray([command])) if count:",
"otherwise set it to blit the whole thing _BUFFER_SIZE = 320 * 240",
"the whole display with the specified color.\"\"\" self.fill_rectangle(0, 0, self.width, self.height, color) def",
"try: import os if os.environ['BLINKA_FT232H']: # we are limited by pyftdi's max SPI",
"pixels for x in range(self.width): # yes this double loop is slow, for",
"red, green and blue values (0-255) into a 16-bit 565 encoding. As a",
"= 320 * 240 else: # in case CircuitPython ever implements platform _BUFFER_SIZE",
"width, height, color): \"\"\"Draw a rectangle at specified position with specified width and",
"= width self.height = height self.init() def init(self): \"\"\"Run the initialization commands.\"\"\" for",
"= \">HH\" _DECODE_PIXEL = \">BBB\" def __init__(self, width, height): self.width = width self.height",
"be included in # all copies or substantial portions of the Software. #",
"pylint: disable=invalid-name self._Y_START = y_offset # pylint: disable=invalid-name super().__init__(width, height) #pylint: enable-msg=too-many-arguments def",
"specified width and height, and fill it with the specified color.\"\"\" x =",
"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION",
"# Otherwise set smaller MCU friendly size _BUFFER_SIZE = 256 def color565(r, g=0,",
"= None _RAM_READ = None _X_START = 0 # pylint: disable=invalid-name _Y_START =",
"without restriction, including without limitation the rights # to use, copy, modify, merge,",
"240 else: # in case CircuitPython ever implements platform _BUFFER_SIZE = 256 except",
"a 16-bit 565 encoding. As a convenience this is also available in the",
"\"\"\"Convert red, green and blue values (0-255) into a 16-bit 565 encoding. As",
"enable-msg=invalid-name,too-many-arguments def _encode_pos(self, x, y): \"\"\"Encode a postion into bytes.\"\"\" return struct.pack(self._ENCODE_POS, x,",
"or RGBA') if rotation not in (0, 90, 180, 270): raise ValueError('Rotation must",
"self.height - 1, pixels) #pylint: disable-msg=too-many-arguments def fill_rectangle(self, x, y, width, height, color):",
"**kwargs): \"\"\"Dummy switch_to_input method\"\"\" pass @property def value(self): \"\"\"Dummy value DigitalInOut property\"\"\" pass",
"x, max(1, width)) height = min(self.height - y, max(1, height)) self._block(x, y, x",
"mode RGB or RGBA') if rotation not in (0, 90, 180, 270): raise",
"is not None: self.dc_pin.value = 1 with self.spi_device as spi: spi.write(data) def read(self,",
"spi.write(bytearray([command])) if data is not None: self.dc_pin.value = 1 with self.spi_device as spi:",
"class for SPI type devices\"\"\" #pylint: disable-msg=too-many-arguments def __init__(self, spi, dc, cs, rst=None,",
"the buffer to be used for fill operations, in 16-bit # units. try:",
"USE OR OTHER DEALINGS IN # THE SOFTWARE. \"\"\" `adafruit_rgb_display.rgb` ==================================================== Base class",
"1, color) def vline(self, x, y, height, color): \"\"\"Draw a vertical line.\"\"\" self.fill_rectangle(x,",
"for SPI type devices\"\"\" #pylint: disable-msg=too-many-arguments def __init__(self, spi, dc, cs, rst=None, width=1,",
"as spi: spi.write(bytearray([command])) if data is not None: self.dc_pin.value = 1 with self.spi_device",
"+ self._X_START, x1 + self._X_START)) self.write(self._PAGE_SET, self._encode_pos(y0 + self._Y_START, y1 + self._Y_START)) if",
"class for all RGB Display devices * Author(s): <NAME>, <NAME> \"\"\" import time",
"# Iterate through the pixels for x in range(self.width): # yes this double",
"# in case CircuitPython ever implements platform _BUFFER_SIZE = 256 except ImportError: #",
"return struct.pack(self._ENCODE_PIXEL, color) def _decode_pixel(self, data): \"\"\"Decode bytes into a pixel color.\"\"\" return",
"range(chunks): self.write(None, data) self.write(None, pixel * rest) #pylint: enable-msg=too-many-arguments def fill(self, color=0): \"\"\"Fill",
"import ustruct as struct import adafruit_bus_device.spi_device as spi_device __version__ = \"0.0.0-auto.0\" __repo__ =",
"self.dc_pin.switch_to_output(value=0) if self.rst: self.rst.switch_to_output(value=0) self.reset() self._X_START = x_offset # pylint: disable=invalid-name self._Y_START =",
"available in the parent adafruit_rgb_display package namespace.\"\"\" try: r, g, b = r",
"_BUFFER_SIZE = SpiController.PAYLOAD_MAX_LENGTH // 2 # max bytes / bytes per pixel except",
"if the first var is a tuple/list except TypeError: pass return (r &",
"x0 + 1) * (y1 - y0 + 1) * size) self.write(self._RAM_WRITE, data)",
"in the Software without restriction, including without limitation the rights # to use,",
"a pixel color into bytes.\"\"\" return struct.pack(self._ENCODE_PIXEL, color) def _decode_pixel(self, data): \"\"\"Decode bytes",
"_BUFFER_SIZE for _ in range(chunks): self.write(None, data) self.write(None, pixel * rest) #pylint: enable-msg=too-many-arguments",
"height, color): \"\"\"Draw a vertical line.\"\"\" self.fill_rectangle(x, y, 1, height, color) class DisplaySPI(Display):",
"3 | b >> 3 class DummyPin: \"\"\"Can be used in place of",
"time try: import struct except ImportError: import ustruct as struct import adafruit_bus_device.spi_device as",
"a vertical line.\"\"\" self.fill_rectangle(x, y, 1, height, color) class DisplaySPI(Display): \"\"\"Base class for",
"reset(self): \"\"\"Reset the device\"\"\" self.rst.value = 0 time.sleep(0.050) # 50 milliseconds self.rst.value =",
"pass return (r & 0xf8) << 8 | (g & 0xfc) << 3",
"\"\"\"Draw a horizontal line.\"\"\" self.fill_rectangle(x, y, width, 1, color) def vline(self, x, y,",
"command=None, data=None): \"\"\"SPI write to the device: commands and data\"\"\" if command is",
"if self.rst: self.rst.switch_to_output(value=0) self.reset() self._X_START = x_offset # pylint: disable=invalid-name self._Y_START = y_offset",
"PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS",
"postion into bytes.\"\"\" return struct.pack(self._ENCODE_POS, x, y) def _encode_pixel(self, color): \"\"\"Encode a pixel",
"OR OTHER DEALINGS IN # THE SOFTWARE. \"\"\" `adafruit_rgb_display.rgb` ==================================================== Base class for",
"#print([hex(x) for x in pixels]) self._block(0, 0, self.width-1, self.height - 1, pixels) #pylint:",
"import SpiController _BUFFER_SIZE = SpiController.PAYLOAD_MAX_LENGTH // 2 # max bytes / bytes per",
"= \">H\" _ENCODE_POS = \">HH\" _DECODE_PIXEL = \">BBB\" def __init__(self, width, height): self.width",
"copies of the Software, and to permit persons to whom the Software is",
"color.\"\"\" self.fill_rectangle(0, 0, self.width, self.height, color) def hline(self, x, y, width, color): \"\"\"Draw",
"1, max(0, x)) y = min(self.height - 1, max(0, y)) width = min(self.width",
"deinit(self): \"\"\"Dummy DigitalInOut deinit\"\"\" pass def switch_to_output(self, *args, **kwargs): \"\"\"Dummy switch_to_output method\"\"\" pass",
"for FT232H special case try: import os if os.environ['BLINKA_FT232H']: # we are limited",
"= SpiController.PAYLOAD_MAX_LENGTH // 2 # max bytes / bytes per pixel except KeyError:",
"def _decode_pixel(self, data): \"\"\"Decode bytes into a pixel color.\"\"\" return color565(*struct.unpack(self._DECODE_PIXEL, data)) def",
"as spi: if command is not None: spi.write(bytearray([command])) if count: spi.readinto(data) return data",
"self.rst.value = 0 time.sleep(0.050) # 50 milliseconds self.rst.value = 1 time.sleep(0.050) # 50",
"range(self.height): # but these displays are small! pix = color565(img.getpixel((x, y))) pixels[2*(y *",
"color565(*struct.unpack(self._DECODE_PIXEL, data)) def pixel(self, x, y, color=None): \"\"\"Read or write a pixel at",
"AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR",
"max bytes / bytes per pixel except KeyError: # otherwise set it to",
"the whole thing _BUFFER_SIZE = 320 * 240 else: # in case CircuitPython",
"<< 8 | (g & 0xfc) << 3 | b >> 3 class",
"data in self._INIT: self.write(command, data) #pylint: disable-msg=invalid-name,too-many-arguments def _block(self, x0, y0, x1, y1,",
"(y1 - y0 + 1) * size) self.write(self._RAM_WRITE, data) return None #pylint: enable-msg=invalid-name,too-many-arguments",
"= bytearray(count) self.dc_pin.value = 0 with self.spi_device as spi: if command is not",
"devices\"\"\" #pylint: disable-msg=too-many-arguments def __init__(self, spi, dc, cs, rst=None, width=1, height=1, baudrate=12000000, polarity=0,",
"self._Y_START, y1 + self._Y_START)) if data is None: size = struct.calcsize(self._DECODE_PIXEL) return self.read(self._RAM_READ,",
"DigitalInOut property\"\"\" pass @pull.setter def pull(self, val): pass class Display: #pylint: disable-msg=no-member \"\"\"Base",
"dc self.rst = rst self.dc_pin.switch_to_output(value=0) if self.rst: self.rst.switch_to_output(value=0) self.reset() self._X_START = x_offset #",
"self.fill_rectangle(x, y, width, 1, color) def vline(self, x, y, height, color): \"\"\"Draw a",
"of data.\"\"\" self.write(self._COLUMN_SET, self._encode_pos(x0 + self._X_START, x1 + self._X_START)) self.write(self._PAGE_SET, self._encode_pos(y0 + self._Y_START,",
"\">HH\" _DECODE_PIXEL = \">BBB\" def __init__(self, width, height): self.width = width self.height =",
"used for fill operations, in 16-bit # units. try: # If we're on",
"size.\"\"\" if not img.mode in ('RGB', 'RGBA'): raise ValueError('Image must be in mode",
"180, 270): raise ValueError('Rotation must be 0/90/180/270') if rotation != 0: img =",
"obtaining a copy # of this software and associated documentation files (the \"Software\"),",
"NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE",
"must be in mode RGB or RGBA') if rotation not in (0, 90,",
"MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL",
"DEALINGS IN # THE SOFTWARE. \"\"\" `adafruit_rgb_display.rgb` ==================================================== Base class for all RGB",
"y, width, 1, color) def vline(self, x, y, height, color): \"\"\"Draw a vertical",
"def fill(self, color=0): \"\"\"Fill the whole display with the specified color.\"\"\" self.fill_rectangle(0, 0,",
"ever implements platform _BUFFER_SIZE = 256 except ImportError: # Otherwise set smaller MCU",
"the size of the buffer to be used for fill operations, in 16-bit",
"struct.calcsize(self._DECODE_PIXEL) return self.read(self._RAM_READ, (x1 - x0 + 1) * (y1 - y0 +",
"270): raise ValueError('Rotation must be 0/90/180/270') if rotation != 0: img = img.rotate(rotation,",
"y + height - 1, b'') chunks, rest = divmod(width * height, _BUFFER_SIZE)",
"* Author(s): <NAME>, <NAME> \"\"\" import time try: import struct except ImportError: import",
"<NAME>, <NAME> \"\"\" import time try: import struct except ImportError: import ustruct as",
"pixels = bytearray(self.width * self.height * 2) # Iterate through the pixels for",
"self._encode_pos(y0 + self._Y_START, y1 + self._Y_START)) if data is None: size = struct.calcsize(self._DECODE_PIXEL)",
"and/or sell # copies of the Software, and to permit persons to whom",
"range(self.width): # yes this double loop is slow, for y in range(self.height): #",
"self.reset() self._X_START = x_offset # pylint: disable=invalid-name self._Y_START = y_offset # pylint: disable=invalid-name",
"pixels]) self._block(0, 0, self.width-1, self.height - 1, pixels) #pylint: disable-msg=too-many-arguments def fill_rectangle(self, x,",
"in place of a ``DigitalInOut()`` when you don't want to skip it.\"\"\" def",
"def value(self, val): pass @property def direction(self): \"\"\"Dummy direction DigitalInOut property\"\"\" pass @direction.setter",
"\"\"\" import time try: import struct except ImportError: import ustruct as struct import",
"1) * size) self.write(self._RAM_WRITE, data) return None #pylint: enable-msg=invalid-name,too-many-arguments def _encode_pos(self, x, y):",
"_ENCODE_PIXEL = \">H\" _ENCODE_POS = \">HH\" _DECODE_PIXEL = \">BBB\" def __init__(self, width, height):",
"switch_to_output(self, *args, **kwargs): \"\"\"Dummy switch_to_output method\"\"\" pass def switch_to_input(self, *args, **kwargs): \"\"\"Dummy switch_to_input",
"# in the Software without restriction, including without limitation the rights # to",
"self._Y_START = y_offset # pylint: disable=invalid-name super().__init__(width, height) #pylint: enable-msg=too-many-arguments def reset(self): \"\"\"Reset",
"display size.\"\"\" if not img.mode in ('RGB', 'RGBA'): raise ValueError('Image must be in",
"display with the specified color.\"\"\" self.fill_rectangle(0, 0, self.width, self.height, color) def hline(self, x,",
"_BUFFER_SIZE = 256 except ImportError: # Otherwise set smaller MCU friendly size _BUFFER_SIZE",
"rest) #pylint: enable-msg=too-many-arguments def fill(self, color=0): \"\"\"Fill the whole display with the specified",
"bytes.\"\"\" return struct.pack(self._ENCODE_POS, x, y) def _encode_pixel(self, color): \"\"\"Encode a pixel color into",
"write to the device: commands and data\"\"\" if command is not None: self.dc_pin.value",
"for all RGB Display devices * Author(s): <NAME>, <NAME> \"\"\" import time try:",
"_INIT = () _ENCODE_PIXEL = \">H\" _ENCODE_POS = \">HH\" _DECODE_PIXEL = \">BBB\" def",
"pixel * rest) #pylint: enable-msg=too-many-arguments def fill(self, color=0): \"\"\"Fill the whole display with",
"data=None): \"\"\"Read or write a block of data.\"\"\" self.write(self._COLUMN_SET, self._encode_pos(x0 + self._X_START, x1",
"* self.width + x)] = pix >> 8 pixels[2*(y * self.width + x)",
"vline(self, x, y, height, color): \"\"\"Draw a vertical line.\"\"\" self.fill_rectangle(x, y, 1, height,",
"disable-msg=invalid-name,too-many-arguments def _block(self, x0, y0, x1, y1, data=None): \"\"\"Read or write a block",
"bytes / bytes per pixel except KeyError: # otherwise set it to blit",
"1, height, color) class DisplaySPI(Display): \"\"\"Base class for SPI type devices\"\"\" #pylint: disable-msg=too-many-arguments",
"TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE",
"else: # in case CircuitPython ever implements platform _BUFFER_SIZE = 256 except ImportError:",
"x, y)) if 0 <= x < self.width and 0 <= y <",
"= 256 def color565(r, g=0, b=0): \"\"\"Convert red, green and blue values (0-255)",
"bytes.\"\"\" return struct.pack(self._ENCODE_PIXEL, color) def _decode_pixel(self, data): \"\"\"Decode bytes into a pixel color.\"\"\"",
"read(self, command=None, count=0): \"\"\"SPI read from device with optional command\"\"\" data = bytearray(count)",
"* 240 else: # in case CircuitPython ever implements platform _BUFFER_SIZE = 256",
"\\ .format(self.width, self.height)) pixels = bytearray(self.width * self.height * 2) # Iterate through",
"IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #",
"Imaging Library image. The image should be in 1 bit mode and a",
"# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS",
"or write a pixel at a given position.\"\"\" if color is None: return",
"or imheight != self.height: raise ValueError('Image must be same dimensions as display ({0}x{1}).'",
"self._block(x, y, x, y, self._encode_pixel(color)) return None def image(self, img, rotation=0): \"\"\"Set buffer",
"os.environ['BLINKA_FT232H']: # we are limited by pyftdi's max SPI payload from pyftdi.spi import",
"#pylint: enable-msg=invalid-name,too-many-arguments def _encode_pos(self, x, y): \"\"\"Encode a postion into bytes.\"\"\" return struct.pack(self._ENCODE_POS,",
"def _block(self, x0, y0, x1, y1, data=None): \"\"\"Read or write a block of",
"struct.pack(self._ENCODE_POS, x, y) def _encode_pixel(self, color): \"\"\"Encode a pixel color into bytes.\"\"\" return",
"= min(self.width - x, max(1, width)) height = min(self.height - y, max(1, height))",
"thing _BUFFER_SIZE = 320 * 240 else: # in case CircuitPython ever implements",
"and 0 <= y < self.height: self._block(x, y, x, y, self._encode_pixel(color)) return None",
"1, b'') chunks, rest = divmod(width * height, _BUFFER_SIZE) pixel = self._encode_pixel(color) if",
"device: commands and data\"\"\" if command is not None: self.dc_pin.value = 0 with",
"any person obtaining a copy # of this software and associated documentation files",
"height, color): \"\"\"Draw a rectangle at specified position with specified width and height,",
"import time try: import struct except ImportError: import ustruct as struct import adafruit_bus_device.spi_device",
"self._X_START, x1 + self._X_START)) self.write(self._PAGE_SET, self._encode_pos(y0 + self._Y_START, y1 + self._Y_START)) if data",
"# # The above copyright notice and this permission notice shall be included",
"\"0.0.0-auto.0\" __repo__ = \"https://github.com/adafruit/Adafruit_CircuitPython_RGB_Display.git\" # This is the size of the buffer to",
"_X_START = 0 # pylint: disable=invalid-name _Y_START = 0 # pylint: disable=invalid-name _INIT",
"self._block(0, 0, self.width-1, self.height - 1, pixels) #pylint: disable-msg=too-many-arguments def fill_rectangle(self, x, y,",
"type devices\"\"\" #pylint: disable-msg=too-many-arguments def __init__(self, spi, dc, cs, rst=None, width=1, height=1, baudrate=12000000,",
"b >> 3 class DummyPin: \"\"\"Can be used in place of a ``DigitalInOut()``",
"height=1, baudrate=12000000, polarity=0, phase=0, *, x_offset=0, y_offset=0): self.spi_device = spi_device.SPIDevice(spi, cs, baudrate=baudrate, polarity=polarity,",
"\"Software\"), to deal # in the Software without restriction, including without limitation the",
"!= 0: img = img.rotate(rotation, expand=True) imwidth, imheight = img.size if imwidth !=",
"width=1, height=1, baudrate=12000000, polarity=0, phase=0, *, x_offset=0, y_offset=0): self.spi_device = spi_device.SPIDevice(spi, cs, baudrate=baudrate,",
"import adafruit_bus_device.spi_device as spi_device __version__ = \"0.0.0-auto.0\" __repo__ = \"https://github.com/adafruit/Adafruit_CircuitPython_RGB_Display.git\" # This is",
"data) #pylint: disable-msg=invalid-name,too-many-arguments def _block(self, x0, y0, x1, y1, data=None): \"\"\"Read or write",
"\"\"\"Decode bytes into a pixel color.\"\"\" return color565(*struct.unpack(self._DECODE_PIXEL, data)) def pixel(self, x, y,",
"raise ValueError('Image must be in mode RGB or RGBA') if rotation not in",
"try: r, g, b = r # see if the first var is",
"count=0): \"\"\"SPI read from device with optional command\"\"\" data = bytearray(count) self.dc_pin.value =",
"ValueError('Image must be same dimensions as display ({0}x{1}).' \\ .format(self.width, self.height)) pixels =",
"copyright notice and this permission notice shall be included in # all copies",
"are limited by pyftdi's max SPI payload from pyftdi.spi import SpiController _BUFFER_SIZE =",
"write(self, command=None, data=None): \"\"\"SPI write to the device: commands and data\"\"\" if command",
"AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE",
"IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED,",
"self.write(command, data) #pylint: disable-msg=invalid-name,too-many-arguments def _block(self, x0, y0, x1, y1, data=None): \"\"\"Read or",
"Copyright (c) 2017 <NAME> and Adafruit Industries # # Permission is hereby granted,",
"a copy # of this software and associated documentation files (the \"Software\"), to",
"deal # in the Software without restriction, including without limitation the rights #",
"# If we're on CPython, try to set as large as possible import",
"0 <= x < self.width and 0 <= y < self.height: self._block(x, y,",
"enable-msg=too-many-arguments def fill(self, color=0): \"\"\"Fill the whole display with the specified color.\"\"\" self.fill_rectangle(0,",
"self._X_START = x_offset # pylint: disable=invalid-name self._Y_START = y_offset # pylint: disable=invalid-name super().__init__(width,",
"self.fill_rectangle(0, 0, self.width, self.height, color) def hline(self, x, y, width, color): \"\"\"Draw a",
"cs, baudrate=baudrate, polarity=polarity, phase=phase) self.dc_pin = dc self.rst = rst self.dc_pin.switch_to_output(value=0) if self.rst:",
"val): pass @property def pull(self): \"\"\"Dummy pull DigitalInOut property\"\"\" pass @pull.setter def pull(self,",
"self._X_START)) self.write(self._PAGE_SET, self._encode_pos(y0 + self._Y_START, y1 + self._Y_START)) if data is None: size",
"color) class DisplaySPI(Display): \"\"\"Base class for SPI type devices\"\"\" #pylint: disable-msg=too-many-arguments def __init__(self,",
"the device\"\"\" self.rst.value = 0 time.sleep(0.050) # 50 milliseconds self.rst.value = 1 time.sleep(0.050)",
"CPython, try to set as large as possible import platform if \"CPython\" in",
"width, height): self.width = width self.height = height self.init() def init(self): \"\"\"Run the",
"position with specified width and height, and fill it with the specified color.\"\"\"",
"def read(self, command=None, count=0): \"\"\"SPI read from device with optional command\"\"\" data =",
"same dimensions as display ({0}x{1}).' \\ .format(self.width, self.height)) pixels = bytearray(self.width * self.height",
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #",
"deinit\"\"\" pass def switch_to_output(self, *args, **kwargs): \"\"\"Dummy switch_to_output method\"\"\" pass def switch_to_input(self, *args,",
"(the \"Software\"), to deal # in the Software without restriction, including without limitation",
"= 0 with self.spi_device as spi: spi.write(bytearray([command])) if data is not None: self.dc_pin.value",
"@value.setter def value(self, val): pass @property def direction(self): \"\"\"Dummy direction DigitalInOut property\"\"\" pass",
"IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR",
"= color565(img.getpixel((x, y))) pixels[2*(y * self.width + x)] = pix >> 8 pixels[2*(y",
"to blit the whole thing _BUFFER_SIZE = 320 * 240 else: # in",
"+ x)] = pix >> 8 pixels[2*(y * self.width + x) + 1]",
"Display devices * Author(s): <NAME>, <NAME> \"\"\" import time try: import struct except",
"data=None): \"\"\"SPI write to the device: commands and data\"\"\" if command is not",
"distribute, sublicense, and/or sell # copies of the Software, and to permit persons",
"x, y): \"\"\"Encode a postion into bytes.\"\"\" return struct.pack(self._ENCODE_POS, x, y) def _encode_pixel(self,",
"fill operations, in 16-bit # units. try: # If we're on CPython, try",
"color=None): \"\"\"Read or write a pixel at a given position.\"\"\" if color is",
"self.rst = rst self.dc_pin.switch_to_output(value=0) if self.rst: self.rst.switch_to_output(value=0) self.reset() self._X_START = x_offset # pylint:",
"charge, to any person obtaining a copy # of this software and associated",
"img, rotation=0): \"\"\"Set buffer to value of Python Imaging Library image. The image",
"r, g, b = r # see if the first var is a",
"*, x_offset=0, y_offset=0): self.spi_device = spi_device.SPIDevice(spi, cs, baudrate=baudrate, polarity=polarity, phase=phase) self.dc_pin = dc",
"WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO",
"platform _BUFFER_SIZE = 256 except ImportError: # Otherwise set smaller MCU friendly size",
"pixels[2*(y * self.width + x) + 1] = pix & 0xFF #print([hex(x) for",
"phase=phase) self.dc_pin = dc self.rst = rst self.dc_pin.switch_to_output(value=0) if self.rst: self.rst.switch_to_output(value=0) self.reset() self._X_START",
"= min(self.height - y, max(1, height)) self._block(x, y, x + width - 1,",
"this is also available in the parent adafruit_rgb_display package namespace.\"\"\" try: r, g,",
"rectangle at specified position with specified width and height, and fill it with",
"into bytes.\"\"\" return struct.pack(self._ENCODE_PIXEL, color) def _decode_pixel(self, data): \"\"\"Decode bytes into a pixel",
"a size equal to the display size.\"\"\" if not img.mode in ('RGB', 'RGBA'):",
"\"\"\"Read or write a block of data.\"\"\" self.write(self._COLUMN_SET, self._encode_pos(x0 + self._X_START, x1 +",
"if imwidth != self.width or imheight != self.height: raise ValueError('Image must be same",
"direction(self, val): pass @property def pull(self): \"\"\"Dummy pull DigitalInOut property\"\"\" pass @pull.setter def",
"hline(self, x, y, width, color): \"\"\"Draw a horizontal line.\"\"\" self.fill_rectangle(x, y, width, 1,",
"self.spi_device as spi: spi.write(bytearray([command])) if data is not None: self.dc_pin.value = 1 with",
"y1 + self._Y_START)) if data is None: size = struct.calcsize(self._DECODE_PIXEL) return self.read(self._RAM_READ, (x1",
"y) def _encode_pixel(self, color): \"\"\"Encode a pixel color into bytes.\"\"\" return struct.pack(self._ENCODE_PIXEL, color)",
"+ width - 1, y + height - 1, b'') chunks, rest =",
"WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO",
"of Python Imaging Library image. The image should be in 1 bit mode",
"rest = divmod(width * height, _BUFFER_SIZE) pixel = self._encode_pixel(color) if chunks: data =",
"color): \"\"\"Draw a horizontal line.\"\"\" self.fill_rectangle(x, y, width, 1, color) def vline(self, x,",
"property\"\"\" pass @direction.setter def direction(self, val): pass @property def pull(self): \"\"\"Dummy pull DigitalInOut",
"and data\"\"\" if command is not None: self.dc_pin.value = 0 with self.spi_device as",
"self.width = width self.height = height self.init() def init(self): \"\"\"Run the initialization commands.\"\"\"",
"WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED",
"KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF",
"Iterate through the pixels for x in range(self.width): # yes this double loop",
"to whom the Software is # furnished to do so, subject to the",
"The MIT License (MIT) # # Copyright (c) 2017 <NAME> and Adafruit Industries",
"limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or",
"Base class for all RGB Display devices * Author(s): <NAME>, <NAME> \"\"\" import",
"16-bit # units. try: # If we're on CPython, try to set as",
"tuple/list except TypeError: pass return (r & 0xf8) << 8 | (g &",
"as possible import platform if \"CPython\" in platform.python_implementation(): # check for FT232H special",
"and height, and fill it with the specified color.\"\"\" x = min(self.width -",
"struct import adafruit_bus_device.spi_device as spi_device __version__ = \"0.0.0-auto.0\" __repo__ = \"https://github.com/adafruit/Adafruit_CircuitPython_RGB_Display.git\" # This",
"COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER",
"THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. \"\"\"",
"RGB display devices :param width: number of pixels wide :param height: number of",
"return color565(*struct.unpack(self._DECODE_PIXEL, data)) def pixel(self, x, y, color=None): \"\"\"Read or write a pixel",
"= divmod(width * height, _BUFFER_SIZE) pixel = self._encode_pixel(color) if chunks: data = pixel",
"skip it.\"\"\" def deinit(self): \"\"\"Dummy DigitalInOut deinit\"\"\" pass def switch_to_output(self, *args, **kwargs): \"\"\"Dummy",
"disable=invalid-name self._Y_START = y_offset # pylint: disable=invalid-name super().__init__(width, height) #pylint: enable-msg=too-many-arguments def reset(self):",
"2 # max bytes / bytes per pixel except KeyError: # otherwise set",
"RGB Display devices * Author(s): <NAME>, <NAME> \"\"\" import time try: import struct",
"data.\"\"\" self.write(self._COLUMN_SET, self._encode_pos(x0 + self._X_START, x1 + self._X_START)) self.write(self._PAGE_SET, self._encode_pos(y0 + self._Y_START, y1",
"y)) if 0 <= x < self.width and 0 <= y < self.height:",
"rotation not in (0, 90, 180, 270): raise ValueError('Rotation must be 0/90/180/270') if",
"def vline(self, x, y, height, color): \"\"\"Draw a vertical line.\"\"\" self.fill_rectangle(x, y, 1,",
"and a size equal to the display size.\"\"\" if not img.mode in ('RGB',",
"switch_to_input method\"\"\" pass @property def value(self): \"\"\"Dummy value DigitalInOut property\"\"\" pass @value.setter def",
"be same dimensions as display ({0}x{1}).' \\ .format(self.width, self.height)) pixels = bytearray(self.width *",
"pass class Display: #pylint: disable-msg=no-member \"\"\"Base class for all RGB display devices :param",
"copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED",
"<= y < self.height: self._block(x, y, x, y, self._encode_pixel(color)) return None def image(self,",
"self.width, self.height, color) def hline(self, x, y, width, color): \"\"\"Draw a horizontal line.\"\"\"",
"Otherwise set smaller MCU friendly size _BUFFER_SIZE = 256 def color565(r, g=0, b=0):",
"property\"\"\" pass @pull.setter def pull(self, val): pass class Display: #pylint: disable-msg=no-member \"\"\"Base class",
"pass @property def direction(self): \"\"\"Dummy direction DigitalInOut property\"\"\" pass @direction.setter def direction(self, val):",
"None def image(self, img, rotation=0): \"\"\"Set buffer to value of Python Imaging Library",
"val): pass class Display: #pylint: disable-msg=no-member \"\"\"Base class for all RGB display devices",
"color) def hline(self, x, y, width, color): \"\"\"Draw a horizontal line.\"\"\" self.fill_rectangle(x, y,",
"data): \"\"\"Decode bytes into a pixel color.\"\"\" return color565(*struct.unpack(self._DECODE_PIXEL, data)) def pixel(self, x,",
"portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT",
"the display size.\"\"\" if not img.mode in ('RGB', 'RGBA'): raise ValueError('Image must be",
"height - 1, b'') chunks, rest = divmod(width * height, _BUFFER_SIZE) pixel =",
"do so, subject to the following conditions: # # The above copyright notice",
"image should be in 1 bit mode and a size equal to the",
"None: self.dc_pin.value = 0 with self.spi_device as spi: spi.write(bytearray([command])) if data is not",
"is a tuple/list except TypeError: pass return (r & 0xf8) << 8 |",
"def switch_to_output(self, *args, **kwargs): \"\"\"Dummy switch_to_output method\"\"\" pass def switch_to_input(self, *args, **kwargs): \"\"\"Dummy",
"in range(chunks): self.write(None, data) self.write(None, pixel * rest) #pylint: enable-msg=too-many-arguments def fill(self, color=0):",
"8 pixels[2*(y * self.width + x) + 1] = pix & 0xFF #print([hex(x)",
"to the device: commands and data\"\"\" if command is not None: self.dc_pin.value =",
"switch_to_input(self, *args, **kwargs): \"\"\"Dummy switch_to_input method\"\"\" pass @property def value(self): \"\"\"Dummy value DigitalInOut",
"x < self.width and 0 <= y < self.height: self._block(x, y, x, y,",
"THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR",
"data)) def pixel(self, x, y, color=None): \"\"\"Read or write a pixel at a",
"Adafruit Industries # # Permission is hereby granted, free of charge, to any",
"disable-msg=too-many-arguments def __init__(self, spi, dc, cs, rst=None, width=1, height=1, baudrate=12000000, polarity=0, phase=0, *,",
"blue values (0-255) into a 16-bit 565 encoding. As a convenience this is",
"_ in range(chunks): self.write(None, data) self.write(None, pixel * rest) #pylint: enable-msg=too-many-arguments def fill(self,",
"color) def _decode_pixel(self, data): \"\"\"Decode bytes into a pixel color.\"\"\" return color565(*struct.unpack(self._DECODE_PIXEL, data))",
"to value of Python Imaging Library image. The image should be in 1",
"disable=invalid-name super().__init__(width, height) #pylint: enable-msg=too-many-arguments def reset(self): \"\"\"Reset the device\"\"\" self.rst.value = 0",
"permit persons to whom the Software is # furnished to do so, subject",
"pixel except KeyError: # otherwise set it to blit the whole thing _BUFFER_SIZE",
"we are limited by pyftdi's max SPI payload from pyftdi.spi import SpiController _BUFFER_SIZE",
"pixel(self, x, y, color=None): \"\"\"Read or write a pixel at a given position.\"\"\"",
"- 1, pixels) #pylint: disable-msg=too-many-arguments def fill_rectangle(self, x, y, width, height, color): \"\"\"Draw",
"width and height, and fill it with the specified color.\"\"\" x = min(self.width",
"Permission is hereby granted, free of charge, to any person obtaining a copy",
"pixel color.\"\"\" return color565(*struct.unpack(self._DECODE_PIXEL, data)) def pixel(self, x, y, color=None): \"\"\"Read or write",
"\"\"\"Dummy DigitalInOut deinit\"\"\" pass def switch_to_output(self, *args, **kwargs): \"\"\"Dummy switch_to_output method\"\"\" pass def",
"@property def pull(self): \"\"\"Dummy pull DigitalInOut property\"\"\" pass @pull.setter def pull(self, val): pass",
"+ self._Y_START)) if data is None: size = struct.calcsize(self._DECODE_PIXEL) return self.read(self._RAM_READ, (x1 -",
"\"\"\"Reset the device\"\"\" self.rst.value = 0 time.sleep(0.050) # 50 milliseconds self.rst.value = 1",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR",
"0 time.sleep(0.050) # 50 milliseconds self.rst.value = 1 time.sleep(0.050) # 50 milliseconds #",
"raise ValueError('Rotation must be 0/90/180/270') if rotation != 0: img = img.rotate(rotation, expand=True)",
"set it to blit the whole thing _BUFFER_SIZE = 320 * 240 else:",
"IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT",
"| b >> 3 class DummyPin: \"\"\"Can be used in place of a",
"EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,",
"Software without restriction, including without limitation the rights # to use, copy, modify,",
"= 0 # pylint: disable=invalid-name _Y_START = 0 # pylint: disable=invalid-name _INIT =",
"= height self.init() def init(self): \"\"\"Run the initialization commands.\"\"\" for command, data in",
"* 2) # Iterate through the pixels for x in range(self.width): # yes",
"self.spi_device = spi_device.SPIDevice(spi, cs, baudrate=baudrate, polarity=polarity, phase=phase) self.dc_pin = dc self.rst = rst",
"y, x, y, self._encode_pixel(color)) return None def image(self, img, rotation=0): \"\"\"Set buffer to",
"time.sleep(0.050) # 50 milliseconds self.rst.value = 1 time.sleep(0.050) # 50 milliseconds # pylint:",
"the device: commands and data\"\"\" if command is not None: self.dc_pin.value = 0",
"ValueError('Image must be in mode RGB or RGBA') if rotation not in (0,",
"we're on CPython, try to set as large as possible import platform if",
"buffer to value of Python Imaging Library image. The image should be in",
"\"\"\"Dummy switch_to_input method\"\"\" pass @property def value(self): \"\"\"Dummy value DigitalInOut property\"\"\" pass @value.setter",
"self.spi_device as spi: spi.write(data) def read(self, command=None, count=0): \"\"\"SPI read from device with",
"pyftdi's max SPI payload from pyftdi.spi import SpiController _BUFFER_SIZE = SpiController.PAYLOAD_MAX_LENGTH // 2",
"DisplaySPI(Display): \"\"\"Base class for SPI type devices\"\"\" #pylint: disable-msg=too-many-arguments def __init__(self, spi, dc,",
"not None: self.dc_pin.value = 1 with self.spi_device as spi: spi.write(data) def read(self, command=None,",
"is slow, for y in range(self.height): # but these displays are small! pix",
"self.height * 2) # Iterate through the pixels for x in range(self.width): #",
"size of the buffer to be used for fill operations, in 16-bit #",
"# The above copyright notice and this permission notice shall be included in",
"in case CircuitPython ever implements platform _BUFFER_SIZE = 256 except ImportError: # Otherwise",
"whole display with the specified color.\"\"\" self.fill_rectangle(0, 0, self.width, self.height, color) def hline(self,",
"= 0 time.sleep(0.050) # 50 milliseconds self.rst.value = 1 time.sleep(0.050) # 50 milliseconds",
"# of this software and associated documentation files (the \"Software\"), to deal #",
"SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. \"\"\" `adafruit_rgb_display.rgb`",
"OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR",
"phase=0, *, x_offset=0, y_offset=0): self.spi_device = spi_device.SPIDevice(spi, cs, baudrate=baudrate, polarity=polarity, phase=phase) self.dc_pin =",
"data) return None #pylint: enable-msg=invalid-name,too-many-arguments def _encode_pos(self, x, y): \"\"\"Encode a postion into",
"= None _X_START = 0 # pylint: disable=invalid-name _Y_START = 0 # pylint:",
"CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE",
".format(self.width, self.height)) pixels = bytearray(self.width * self.height * 2) # Iterate through the",
"command, data in self._INIT: self.write(command, data) #pylint: disable-msg=invalid-name,too-many-arguments def _block(self, x0, y0, x1,",
"sell # copies of the Software, and to permit persons to whom the",
"\"\"\"Dummy pull DigitalInOut property\"\"\" pass @pull.setter def pull(self, val): pass class Display: #pylint:",
"substantial portions of the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\",",
"FT232H special case try: import os if os.environ['BLINKA_FT232H']: # we are limited by",
"pix = color565(img.getpixel((x, y))) pixels[2*(y * self.width + x)] = pix >> 8",
"line.\"\"\" self.fill_rectangle(x, y, width, 1, color) def vline(self, x, y, height, color): \"\"\"Draw",
"\"\"\"Dummy value DigitalInOut property\"\"\" pass @value.setter def value(self, val): pass @property def direction(self):",
"1, pixels) #pylint: disable-msg=too-many-arguments def fill_rectangle(self, x, y, width, height, color): \"\"\"Draw a",
"for x in range(self.width): # yes this double loop is slow, for y",
"except TypeError: pass return (r & 0xf8) << 8 | (g & 0xfc)",
"set as large as possible import platform if \"CPython\" in platform.python_implementation(): # check",
"# all copies or substantial portions of the Software. # # THE SOFTWARE",
"self.write(self._RAM_WRITE, data) return None #pylint: enable-msg=invalid-name,too-many-arguments def _encode_pos(self, x, y): \"\"\"Encode a postion",
"x0, y0, x1, y1, data=None): \"\"\"Read or write a block of data.\"\"\" self.write(self._COLUMN_SET,",
"<= x < self.width and 0 <= y < self.height: self._block(x, y, x,",
"imwidth != self.width or imheight != self.height: raise ValueError('Image must be same dimensions",
"self.height = height self.init() def init(self): \"\"\"Run the initialization commands.\"\"\" for command, data",
"into a pixel color.\"\"\" return color565(*struct.unpack(self._DECODE_PIXEL, data)) def pixel(self, x, y, color=None): \"\"\"Read",
"pass @pull.setter def pull(self, val): pass class Display: #pylint: disable-msg=no-member \"\"\"Base class for",
"restriction, including without limitation the rights # to use, copy, modify, merge, publish,",
"at a given position.\"\"\" if color is None: return self._decode_pixel(self._block(x, y, x, y))",
"return struct.pack(self._ENCODE_POS, x, y) def _encode_pixel(self, color): \"\"\"Encode a pixel color into bytes.\"\"\"",
"FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS",
"# # Permission is hereby granted, free of charge, to any person obtaining",
"all copies or substantial portions of the Software. # # THE SOFTWARE IS",
"\"CPython\" in platform.python_implementation(): # check for FT232H special case try: import os if",
"command is not None: self.dc_pin.value = 0 with self.spi_device as spi: spi.write(bytearray([command])) if",
"special case try: import os if os.environ['BLINKA_FT232H']: # we are limited by pyftdi's",
"color): \"\"\"Draw a rectangle at specified position with specified width and height, and",
"b = r # see if the first var is a tuple/list except",
"write a pixel at a given position.\"\"\" if color is None: return self._decode_pixel(self._block(x,",
"as struct import adafruit_bus_device.spi_device as spi_device __version__ = \"0.0.0-auto.0\" __repo__ = \"https://github.com/adafruit/Adafruit_CircuitPython_RGB_Display.git\" #",
"None _X_START = 0 # pylint: disable=invalid-name _Y_START = 0 # pylint: disable=invalid-name",
"on CPython, try to set as large as possible import platform if \"CPython\"",
"pixel at a given position.\"\"\" if color is None: return self._decode_pixel(self._block(x, y, x,",
"(0-255) into a 16-bit 565 encoding. As a convenience this is also available",
"BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR",
"License (MIT) # # Copyright (c) 2017 <NAME> and Adafruit Industries # #",
"width, color): \"\"\"Draw a horizontal line.\"\"\" self.fill_rectangle(x, y, width, 1, color) def vline(self,",
"not None: self.dc_pin.value = 0 with self.spi_device as spi: spi.write(bytearray([command])) if data is",
"color565(img.getpixel((x, y))) pixels[2*(y * self.width + x)] = pix >> 8 pixels[2*(y *",
"method\"\"\" pass def switch_to_input(self, *args, **kwargs): \"\"\"Dummy switch_to_input method\"\"\" pass @property def value(self):",
"ustruct as struct import adafruit_bus_device.spi_device as spi_device __version__ = \"0.0.0-auto.0\" __repo__ = \"https://github.com/adafruit/Adafruit_CircuitPython_RGB_Display.git\"",
"FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE",
"OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT",
"PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING",
"None _RAM_READ = None _X_START = 0 # pylint: disable=invalid-name _Y_START = 0",
"initialization commands.\"\"\" for command, data in self._INIT: self.write(command, data) #pylint: disable-msg=invalid-name,too-many-arguments def _block(self,",
"img.rotate(rotation, expand=True) imwidth, imheight = img.size if imwidth != self.width or imheight !=",
"for y in range(self.height): # but these displays are small! pix = color565(img.getpixel((x,",
"16-bit 565 encoding. As a convenience this is also available in the parent",
"files (the \"Software\"), to deal # in the Software without restriction, including without",
"# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS",
"\"\"\"Can be used in place of a ``DigitalInOut()`` when you don't want to",
"= r # see if the first var is a tuple/list except TypeError:",
"devices :param width: number of pixels wide :param height: number of pixels high",
"0/90/180/270') if rotation != 0: img = img.rotate(rotation, expand=True) imwidth, imheight = img.size",
"y): \"\"\"Encode a postion into bytes.\"\"\" return struct.pack(self._ENCODE_POS, x, y) def _encode_pixel(self, color):",
"try: # If we're on CPython, try to set as large as possible",
"\"\"\"Encode a pixel color into bytes.\"\"\" return struct.pack(self._ENCODE_PIXEL, color) def _decode_pixel(self, data): \"\"\"Decode",
"property\"\"\" pass @value.setter def value(self, val): pass @property def direction(self): \"\"\"Dummy direction DigitalInOut",
"is the size of the buffer to be used for fill operations, in",
"= \">BBB\" def __init__(self, width, height): self.width = width self.height = height self.init()",
"# otherwise set it to blit the whole thing _BUFFER_SIZE = 320 *",
"img.mode in ('RGB', 'RGBA'): raise ValueError('Image must be in mode RGB or RGBA')",
"+ self._Y_START, y1 + self._Y_START)) if data is None: size = struct.calcsize(self._DECODE_PIXEL) return",
"- y0 + 1) * size) self.write(self._RAM_WRITE, data) return None #pylint: enable-msg=invalid-name,too-many-arguments def",
"= 0 with self.spi_device as spi: if command is not None: spi.write(bytearray([command])) if",
"bit mode and a size equal to the display size.\"\"\" if not img.mode",
"implements platform _BUFFER_SIZE = 256 except ImportError: # Otherwise set smaller MCU friendly",
"b=0): \"\"\"Convert red, green and blue values (0-255) into a 16-bit 565 encoding.",
"the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell",
"= min(self.height - 1, max(0, y)) width = min(self.width - x, max(1, width))",
"_encode_pos(self, x, y): \"\"\"Encode a postion into bytes.\"\"\" return struct.pack(self._ENCODE_POS, x, y) def",
"# # Copyright (c) 2017 <NAME> and Adafruit Industries # # Permission is",
"data is not None: self.dc_pin.value = 1 with self.spi_device as spi: spi.write(data) def",
"following conditions: # # The above copyright notice and this permission notice shall",
"# 50 milliseconds self.rst.value = 1 time.sleep(0.050) # 50 milliseconds # pylint: disable=no-member",
"of the Software, and to permit persons to whom the Software is #",
"height, and fill it with the specified color.\"\"\" x = min(self.width - 1,",
"= 1 with self.spi_device as spi: spi.write(data) def read(self, command=None, count=0): \"\"\"SPI read",
"// 2 # max bytes / bytes per pixel except KeyError: # otherwise",
"self._Y_START)) if data is None: size = struct.calcsize(self._DECODE_PIXEL) return self.read(self._RAM_READ, (x1 - x0",
"vertical line.\"\"\" self.fill_rectangle(x, y, 1, height, color) class DisplaySPI(Display): \"\"\"Base class for SPI",
"\"\"\"Base class for all RGB display devices :param width: number of pixels wide",
"a rectangle at specified position with specified width and height, and fill it",
"for fill operations, in 16-bit # units. try: # If we're on CPython,",
"# see if the first var is a tuple/list except TypeError: pass return",
"a block of data.\"\"\" self.write(self._COLUMN_SET, self._encode_pos(x0 + self._X_START, x1 + self._X_START)) self.write(self._PAGE_SET, self._encode_pos(y0",
"\"\"\"Base class for SPI type devices\"\"\" #pylint: disable-msg=too-many-arguments def __init__(self, spi, dc, cs,",
"def __init__(self, spi, dc, cs, rst=None, width=1, height=1, baudrate=12000000, polarity=0, phase=0, *, x_offset=0,",
"return None def image(self, img, rotation=0): \"\"\"Set buffer to value of Python Imaging",
"\"\"\"Read or write a pixel at a given position.\"\"\" if color is None:",
"parent adafruit_rgb_display package namespace.\"\"\" try: r, g, b = r # see if",
"the initialization commands.\"\"\" for command, data in self._INIT: self.write(command, data) #pylint: disable-msg=invalid-name,too-many-arguments def",
"are small! pix = color565(img.getpixel((x, y))) pixels[2*(y * self.width + x)] = pix",
"The above copyright notice and this permission notice shall be included in #",
"and Adafruit Industries # # Permission is hereby granted, free of charge, to",
"var is a tuple/list except TypeError: pass return (r & 0xf8) << 8",
"pylint: disable=invalid-name _INIT = () _ENCODE_PIXEL = \">H\" _ENCODE_POS = \">HH\" _DECODE_PIXEL =",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR",
"\"\"\" `adafruit_rgb_display.rgb` ==================================================== Base class for all RGB Display devices * Author(s): <NAME>,",
"\"\"\"Encode a postion into bytes.\"\"\" return struct.pack(self._ENCODE_POS, x, y) def _encode_pixel(self, color): \"\"\"Encode",
"('RGB', 'RGBA'): raise ValueError('Image must be in mode RGB or RGBA') if rotation",
"height, color) class DisplaySPI(Display): \"\"\"Base class for SPI type devices\"\"\" #pylint: disable-msg=too-many-arguments def",
"return self._decode_pixel(self._block(x, y, x, y)) if 0 <= x < self.width and 0",
"- 1, max(0, y)) width = min(self.width - x, max(1, width)) height =",
"< self.width and 0 <= y < self.height: self._block(x, y, x, y, self._encode_pixel(color))",
"color): \"\"\"Draw a vertical line.\"\"\" self.fill_rectangle(x, y, 1, height, color) class DisplaySPI(Display): \"\"\"Base",
"_BUFFER_SIZE = 256 def color565(r, g=0, b=0): \"\"\"Convert red, green and blue values",
"for command, data in self._INIT: self.write(command, data) #pylint: disable-msg=invalid-name,too-many-arguments def _block(self, x0, y0,",
"def image(self, img, rotation=0): \"\"\"Set buffer to value of Python Imaging Library image.",
"try: import struct except ImportError: import ustruct as struct import adafruit_bus_device.spi_device as spi_device",
"green and blue values (0-255) into a 16-bit 565 encoding. As a convenience",
"a ``DigitalInOut()`` when you don't want to skip it.\"\"\" def deinit(self): \"\"\"Dummy DigitalInOut",
"1 with self.spi_device as spi: spi.write(data) def read(self, command=None, count=0): \"\"\"SPI read from",
"of a ``DigitalInOut()`` when you don't want to skip it.\"\"\" def deinit(self): \"\"\"Dummy",
"def direction(self, val): pass @property def pull(self): \"\"\"Dummy pull DigitalInOut property\"\"\" pass @pull.setter",
"256 def color565(r, g=0, b=0): \"\"\"Convert red, green and blue values (0-255) into",
"struct.pack(self._ENCODE_PIXEL, color) def _decode_pixel(self, data): \"\"\"Decode bytes into a pixel color.\"\"\" return color565(*struct.unpack(self._DECODE_PIXEL,",
"data = bytearray(count) self.dc_pin.value = 0 with self.spi_device as spi: if command is",
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER",
"baudrate=baudrate, polarity=polarity, phase=phase) self.dc_pin = dc self.rst = rst self.dc_pin.switch_to_output(value=0) if self.rst: self.rst.switch_to_output(value=0)",
"of the buffer to be used for fill operations, in 16-bit # units.",
"HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN",
"x_offset=0, y_offset=0): self.spi_device = spi_device.SPIDevice(spi, cs, baudrate=baudrate, polarity=polarity, phase=phase) self.dc_pin = dc self.rst",
"disable-msg=too-many-arguments def fill_rectangle(self, x, y, width, height, color): \"\"\"Draw a rectangle at specified",
"including without limitation the rights # to use, copy, modify, merge, publish, distribute,",
"= img.size if imwidth != self.width or imheight != self.height: raise ValueError('Image must",
"from device with optional command\"\"\" data = bytearray(count) self.dc_pin.value = 0 with self.spi_device",
"CircuitPython ever implements platform _BUFFER_SIZE = 256 except ImportError: # Otherwise set smaller",
"devices * Author(s): <NAME>, <NAME> \"\"\" import time try: import struct except ImportError:",
"= rst self.dc_pin.switch_to_output(value=0) if self.rst: self.rst.switch_to_output(value=0) self.reset() self._X_START = x_offset # pylint: disable=invalid-name",
"y, x, y)) if 0 <= x < self.width and 0 <= y",
"to skip it.\"\"\" def deinit(self): \"\"\"Dummy DigitalInOut deinit\"\"\" pass def switch_to_output(self, *args, **kwargs):",
"y1, data=None): \"\"\"Read or write a block of data.\"\"\" self.write(self._COLUMN_SET, self._encode_pos(x0 + self._X_START,",
"mode and a size equal to the display size.\"\"\" if not img.mode in",
"struct except ImportError: import ustruct as struct import adafruit_bus_device.spi_device as spi_device __version__ =",
"# THE SOFTWARE. \"\"\" `adafruit_rgb_display.rgb` ==================================================== Base class for all RGB Display devices",
"_RAM_WRITE = None _RAM_READ = None _X_START = 0 # pylint: disable=invalid-name _Y_START",
"in (0, 90, 180, 270): raise ValueError('Rotation must be 0/90/180/270') if rotation !=",
"be 0/90/180/270') if rotation != 0: img = img.rotate(rotation, expand=True) imwidth, imheight =",
"* rest) #pylint: enable-msg=too-many-arguments def fill(self, color=0): \"\"\"Fill the whole display with the",
"(c) 2017 <NAME> and Adafruit Industries # # Permission is hereby granted, free",
"all RGB Display devices * Author(s): <NAME>, <NAME> \"\"\" import time try: import",
"MIT License (MIT) # # Copyright (c) 2017 <NAME> and Adafruit Industries #",
"cs, rst=None, width=1, height=1, baudrate=12000000, polarity=0, phase=0, *, x_offset=0, y_offset=0): self.spi_device = spi_device.SPIDevice(spi,",
"0 with self.spi_device as spi: spi.write(bytearray([command])) if data is not None: self.dc_pin.value =",
"# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
"pixel color into bytes.\"\"\" return struct.pack(self._ENCODE_PIXEL, color) def _decode_pixel(self, data): \"\"\"Decode bytes into",
"+ height - 1, b'') chunks, rest = divmod(width * height, _BUFFER_SIZE) pixel",
"#pylint: disable-msg=invalid-name,too-many-arguments def _block(self, x0, y0, x1, y1, data=None): \"\"\"Read or write a",
"if rotation != 0: img = img.rotate(rotation, expand=True) imwidth, imheight = img.size if",
"associated documentation files (the \"Software\"), to deal # in the Software without restriction,",
"self.width-1, self.height - 1, pixels) #pylint: disable-msg=too-many-arguments def fill_rectangle(self, x, y, width, height,",
"class for all RGB display devices :param width: number of pixels wide :param",
"color) def vline(self, x, y, height, color): \"\"\"Draw a vertical line.\"\"\" self.fill_rectangle(x, y,",
"as large as possible import platform if \"CPython\" in platform.python_implementation(): # check for",
"hereby granted, free of charge, to any person obtaining a copy # of",
"of this software and associated documentation files (the \"Software\"), to deal # in",
"# yes this double loop is slow, for y in range(self.height): # but",
"OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS",
"Python Imaging Library image. The image should be in 1 bit mode and",
"self.spi_device as spi: if command is not None: spi.write(bytearray([command])) if count: spi.readinto(data) return",
"x1, y1, data=None): \"\"\"Read or write a block of data.\"\"\" self.write(self._COLUMN_SET, self._encode_pos(x0 +",
"b'') chunks, rest = divmod(width * height, _BUFFER_SIZE) pixel = self._encode_pixel(color) if chunks:",
"# # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
"= 0 # pylint: disable=invalid-name _INIT = () _ENCODE_PIXEL = \">H\" _ENCODE_POS =",
"(r & 0xf8) << 8 | (g & 0xfc) << 3 | b",
"pass def switch_to_output(self, *args, **kwargs): \"\"\"Dummy switch_to_output method\"\"\" pass def switch_to_input(self, *args, **kwargs):",
"pylint: disable=invalid-name _Y_START = 0 # pylint: disable=invalid-name _INIT = () _ENCODE_PIXEL =",
"write a block of data.\"\"\" self.write(self._COLUMN_SET, self._encode_pos(x0 + self._X_START, x1 + self._X_START)) self.write(self._PAGE_SET,",
"_DECODE_PIXEL = \">BBB\" def __init__(self, width, height): self.width = width self.height = height",
"notice shall be included in # all copies or substantial portions of the",
"dimensions as display ({0}x{1}).' \\ .format(self.width, self.height)) pixels = bytearray(self.width * self.height *",
"y0, x1, y1, data=None): \"\"\"Read or write a block of data.\"\"\" self.write(self._COLUMN_SET, self._encode_pos(x0",
"\"\"\"Dummy direction DigitalInOut property\"\"\" pass @direction.setter def direction(self, val): pass @property def pull(self):",
"# pylint: disable=no-member def write(self, command=None, data=None): \"\"\"SPI write to the device: commands",
"NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY",
"self.fill_rectangle(x, y, 1, height, color) class DisplaySPI(Display): \"\"\"Base class for SPI type devices\"\"\"",
"limited by pyftdi's max SPI payload from pyftdi.spi import SpiController _BUFFER_SIZE = SpiController.PAYLOAD_MAX_LENGTH",
"0, self.width-1, self.height - 1, pixels) #pylint: disable-msg=too-many-arguments def fill_rectangle(self, x, y, width,",
"# check for FT232H special case try: import os if os.environ['BLINKA_FT232H']: # we",
"min(self.width - x, max(1, width)) height = min(self.height - y, max(1, height)) self._block(x,",
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of",
"bytearray(count) self.dc_pin.value = 0 with self.spi_device as spi: if command is not None:",
"return self.read(self._RAM_READ, (x1 - x0 + 1) * (y1 - y0 + 1)",
"the Software is # furnished to do so, subject to the following conditions:",
"subject to the following conditions: # # The above copyright notice and this",
"# Copyright (c) 2017 <NAME> and Adafruit Industries # # Permission is hereby",
"= y_offset # pylint: disable=invalid-name super().__init__(width, height) #pylint: enable-msg=too-many-arguments def reset(self): \"\"\"Reset the",
"SpiController _BUFFER_SIZE = SpiController.PAYLOAD_MAX_LENGTH // 2 # max bytes / bytes per pixel"
] |
[
"calc_temps_start(start_date): tobs_stats = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\ filter(Measurement.date >= start_date).all() tobs_stats_all = [] for",
"a dictionary from the row data and append to a list of all_passengers",
"a list of all_passengers all_dates = [] for date, prcp in date_prcp: dict",
"dt.date(2017, 8, 18) - dt.timedelta(days=365) most_active = session.query(Measurement.date, Measurement.tobs).\\ filter(Measurement.station == 'USC00519281').\\ filter(Measurement.date",
"= {} dict[\"id\"] = id dict[\"station\"] = station dict[\"name\"] = name dict[\"latitude\"] =",
"filter(Measurement.date >= start_date).all() tobs_stats_all = [] for min, avg, max in tobs_stats: dict",
"{} dict[\"id\"] = id dict[\"station\"] = station dict[\"name\"] = name dict[\"latitude\"] = latitude",
"for date, prcp in date_prcp: dict = {} dict[\"date\"] = date dict[\"prcp\"] =",
"list of all_passengers all_dates = [] for date, prcp in date_prcp: dict =",
"f\"/api/v1.0/precipitation<br/>\" f\"/api/v1.0/stations<br/>\" f\"/api/v1.0/tobs<br/>\" f\"/api/v1.0/<start_date><br/>\" f\"/api/v1.0/<start_date>/<end_date><br/>\" ) @app.route(\"/api/v1.0/precipitation\") def precipitation(): session = Session(engine) first_date",
"{} dict[\"date\"] = date dict[\"prcp\"] = prcp all_dates.append(dict) return jsonify(all_dates) @app.route(\"/api/v1.0/stations\") def stations():",
"= dt.date(2017, 8, 18) - dt.timedelta(days=365) most_active = session.query(Measurement.date, Measurement.tobs).\\ filter(Measurement.station == 'USC00519281').\\",
"session.query(Measurement.date, Measurement.tobs).\\ filter(Measurement.station == 'USC00519281').\\ filter(Measurement.date > year_ago).all() most_active_tobs = [] for date,",
"Measurement = Base.classes.measurement Station = Base.classes.station app = Flask(__name__) @app.route(\"/\") def welcome(): \"\"\"List",
"= Session(engine) stations = session.query(Station.id, Station.station, Station.name, Station.latitude, Station.longitude, Station.elevation).all() all_stations = []",
"welcome(): \"\"\"List all available api routes.\"\"\" return ( f\"Available Routes:<br/>\" f\"/api/v1.0/precipitation<br/>\" f\"/api/v1.0/stations<br/>\" f\"/api/v1.0/tobs<br/>\"",
"= session.query(Measurement.date, func.max(Measurement.prcp)).group_by(Measurement.date).\\ filter(Measurement.date > year_ago) session.close() # Create a dictionary from the",
"for id, station, name, latitude, longitude, elevation in stations: dict = {} dict[\"id\"]",
"= avg dict['max'] = max tobs_stats_all.append(dict) return jsonify(tobs_stats_all) @app.route(\"/api/v1.0/<start_date>/<end_date>\") def calc_temps_start_end(start_date, end_date): tobs_stats",
"def welcome(): \"\"\"List all available api routes.\"\"\" return ( f\"Available Routes:<br/>\" f\"/api/v1.0/precipitation<br/>\" f\"/api/v1.0/stations<br/>\"",
"for min, avg, max in tobs_stats: dict = {} dict['min'] = min dict['avg']",
"= [] for id, station, name, latitude, longitude, elevation in stations: dict =",
"avg dict['max'] = max tobs_stats_all.append(dict) return jsonify(tobs_stats_all) @app.route(\"/api/v1.0/<start_date>/<end_date>\") def calc_temps_start_end(start_date, end_date): tobs_stats =",
"row data and append to a list of all_passengers all_dates = [] for",
"date, prcp in date_prcp: dict = {} dict[\"date\"] = date dict[\"prcp\"] = prcp",
"automap_base() Base.prepare(engine, reflect=True) Measurement = Base.classes.measurement Station = Base.classes.station app = Flask(__name__) @app.route(\"/\")",
"jsonify(most_active_tobs) @app.route(\"/api/v1.0/<start_date>\") def calc_temps_start(start_date): tobs_stats = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\ filter(Measurement.date >= start_date).all() tobs_stats_all",
"= elevation all_stations.append(dict) return jsonify(all_stations) @app.route(\"/api/v1.0/tobs\") def tobs(): session = Session(engine) year_ago =",
"precipitation(): session = Session(engine) first_date = session.query(Measurement.date).order_by(Measurement.date).first() last_date = session.query(Measurement.date).order_by(Measurement.date.desc()).first() year_ago = dt.date(2017,",
"'USC00519281').\\ filter(Measurement.date > year_ago).all() most_active_tobs = [] for date, tobs in most_active: dict",
"def precipitation(): session = Session(engine) first_date = session.query(Measurement.date).order_by(Measurement.date).first() last_date = session.query(Measurement.date).order_by(Measurement.date.desc()).first() year_ago =",
"func import datetime as dt from flask import Flask, jsonify engine = create_engine(\"sqlite:///Resources/hawaii.sqlite\")",
"last_date = session.query(Measurement.date).order_by(Measurement.date.desc()).first() year_ago = dt.date(2017, 8, 23) - dt.timedelta(days=365) date_prcp = session.query(Measurement.date,",
"in most_active: dict = {} dict['date'] = date dict['tobs'] = tobs most_active_tobs.append(dict) return",
"= min dict['avg'] = avg dict['max'] = max tobs_stats_all.append(dict) return jsonify(tobs_stats_all) @app.route(\"/api/v1.0/<start_date>/<end_date>\") def",
"f\"/api/v1.0/stations<br/>\" f\"/api/v1.0/tobs<br/>\" f\"/api/v1.0/<start_date><br/>\" f\"/api/v1.0/<start_date>/<end_date><br/>\" ) @app.route(\"/api/v1.0/precipitation\") def precipitation(): session = Session(engine) first_date =",
"end_date): tobs_stats = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\ filter(Measurement.date >= start_date).filter(Measurement.date <= end_date).all() tobs_stats_all =",
"Base.classes.measurement Station = Base.classes.station app = Flask(__name__) @app.route(\"/\") def welcome(): \"\"\"List all available",
"routes.\"\"\" return ( f\"Available Routes:<br/>\" f\"/api/v1.0/precipitation<br/>\" f\"/api/v1.0/stations<br/>\" f\"/api/v1.0/tobs<br/>\" f\"/api/v1.0/<start_date><br/>\" f\"/api/v1.0/<start_date>/<end_date><br/>\" ) @app.route(\"/api/v1.0/precipitation\") def",
"date dict[\"prcp\"] = prcp all_dates.append(dict) return jsonify(all_dates) @app.route(\"/api/v1.0/stations\") def stations(): session = Session(engine)",
"= session.query(Station.id, Station.station, Station.name, Station.latitude, Station.longitude, Station.elevation).all() all_stations = [] for id, station,",
"most_active: dict = {} dict['date'] = date dict['tobs'] = tobs most_active_tobs.append(dict) return jsonify(most_active_tobs)",
"Station.name, Station.latitude, Station.longitude, Station.elevation).all() all_stations = [] for id, station, name, latitude, longitude,",
"> year_ago).all() most_active_tobs = [] for date, tobs in most_active: dict = {}",
"func.max(Measurement.tobs)).\\ filter(Measurement.date >= start_date).filter(Measurement.date <= end_date).all() tobs_stats_all = [] for min, avg, max",
"import create_engine, func import datetime as dt from flask import Flask, jsonify engine",
"Session(engine) first_date = session.query(Measurement.date).order_by(Measurement.date).first() last_date = session.query(Measurement.date).order_by(Measurement.date.desc()).first() year_ago = dt.date(2017, 8, 23) -",
"= session.query(Measurement.date).order_by(Measurement.date).first() last_date = session.query(Measurement.date).order_by(Measurement.date.desc()).first() year_ago = dt.date(2017, 8, 23) - dt.timedelta(days=365) date_prcp",
"= [] for date, prcp in date_prcp: dict = {} dict[\"date\"] = date",
"= tobs most_active_tobs.append(dict) return jsonify(most_active_tobs) @app.route(\"/api/v1.0/<start_date>\") def calc_temps_start(start_date): tobs_stats = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\",
"tobs_stats = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\ filter(Measurement.date >= start_date).filter(Measurement.date <= end_date).all() tobs_stats_all = []",
"in tobs_stats: dict = {} dict['min'] = min dict['avg'] = avg dict['max'] =",
"jsonify(tobs_stats_all) @app.route(\"/api/v1.0/<start_date>/<end_date>\") def calc_temps_start_end(start_date, end_date): tobs_stats = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\ filter(Measurement.date >= start_date).filter(Measurement.date",
"= name dict[\"latitude\"] = latitude dict[\"longitude\"] = longitude dict[\"elevation\"] = elevation all_stations.append(dict) return",
"= Session(engine) first_date = session.query(Measurement.date).order_by(Measurement.date).first() last_date = session.query(Measurement.date).order_by(Measurement.date.desc()).first() year_ago = dt.date(2017, 8, 23)",
"23) - dt.timedelta(days=365) date_prcp = session.query(Measurement.date, func.max(Measurement.prcp)).group_by(Measurement.date).\\ filter(Measurement.date > year_ago) session.close() # Create",
"most_active_tobs = [] for date, tobs in most_active: dict = {} dict['date'] =",
"all_stations.append(dict) return jsonify(all_stations) @app.route(\"/api/v1.0/tobs\") def tobs(): session = Session(engine) year_ago = dt.date(2017, 8,",
"avg, max in tobs_stats: dict = {} dict['min'] = min dict['avg'] = avg",
"session.close() # Create a dictionary from the row data and append to a",
"== 'USC00519281').\\ filter(Measurement.date > year_ago).all() most_active_tobs = [] for date, tobs in most_active:",
"= date dict['tobs'] = tobs most_active_tobs.append(dict) return jsonify(most_active_tobs) @app.route(\"/api/v1.0/<start_date>\") def calc_temps_start(start_date): tobs_stats =",
"return jsonify(all_dates) @app.route(\"/api/v1.0/stations\") def stations(): session = Session(engine) stations = session.query(Station.id, Station.station, Station.name,",
"from the row data and append to a list of all_passengers all_dates =",
"def calc_temps_start(start_date): tobs_stats = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\ filter(Measurement.date >= start_date).all() tobs_stats_all = []",
"{} dict['date'] = date dict['tobs'] = tobs most_active_tobs.append(dict) return jsonify(most_active_tobs) @app.route(\"/api/v1.0/<start_date>\") def calc_temps_start(start_date):",
"[] for date, prcp in date_prcp: dict = {} dict[\"date\"] = date dict[\"prcp\"]",
"year_ago = dt.date(2017, 8, 23) - dt.timedelta(days=365) date_prcp = session.query(Measurement.date, func.max(Measurement.prcp)).group_by(Measurement.date).\\ filter(Measurement.date >",
"from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func",
"8, 18) - dt.timedelta(days=365) most_active = session.query(Measurement.date, Measurement.tobs).\\ filter(Measurement.station == 'USC00519281').\\ filter(Measurement.date >",
"filter(Measurement.date > year_ago).all() most_active_tobs = [] for date, tobs in most_active: dict =",
"Session from sqlalchemy import create_engine, func import datetime as dt from flask import",
"Create a dictionary from the row data and append to a list of",
"session.query(Measurement.date).order_by(Measurement.date).first() last_date = session.query(Measurement.date).order_by(Measurement.date.desc()).first() year_ago = dt.date(2017, 8, 23) - dt.timedelta(days=365) date_prcp =",
"= [] for date, tobs in most_active: dict = {} dict['date'] = date",
"app = Flask(__name__) @app.route(\"/\") def welcome(): \"\"\"List all available api routes.\"\"\" return (",
"create_engine(\"sqlite:///Resources/hawaii.sqlite\") Base = automap_base() Base.prepare(engine, reflect=True) Measurement = Base.classes.measurement Station = Base.classes.station app",
"date, tobs in most_active: dict = {} dict['date'] = date dict['tobs'] = tobs",
">= start_date).all() tobs_stats_all = [] for min, avg, max in tobs_stats: dict =",
"return jsonify(tobs_stats_all) @app.route(\"/api/v1.0/<start_date>/<end_date>\") def calc_temps_start_end(start_date, end_date): tobs_stats = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\ filter(Measurement.date >=",
"= min dict['avg'] = avg dict['max'] = max tobs_stats_all.append(dict) return jsonify(tobs_stats_all) if __name__",
"available api routes.\"\"\" return ( f\"Available Routes:<br/>\" f\"/api/v1.0/precipitation<br/>\" f\"/api/v1.0/stations<br/>\" f\"/api/v1.0/tobs<br/>\" f\"/api/v1.0/<start_date><br/>\" f\"/api/v1.0/<start_date>/<end_date><br/>\" )",
"year_ago) session.close() # Create a dictionary from the row data and append to",
"append to a list of all_passengers all_dates = [] for date, prcp in",
"> year_ago) session.close() # Create a dictionary from the row data and append",
"max in tobs_stats: dict = {} dict['min'] = min dict['avg'] = avg dict['max']",
"date_prcp: dict = {} dict[\"date\"] = date dict[\"prcp\"] = prcp all_dates.append(dict) return jsonify(all_dates)",
"automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func import datetime as",
"from sqlalchemy import create_engine, func import datetime as dt from flask import Flask,",
"filter(Measurement.date >= start_date).filter(Measurement.date <= end_date).all() tobs_stats_all = [] for min, avg, max in",
"= station dict[\"name\"] = name dict[\"latitude\"] = latitude dict[\"longitude\"] = longitude dict[\"elevation\"] =",
"dict = {} dict['min'] = min dict['avg'] = avg dict['max'] = max tobs_stats_all.append(dict)",
"dict[\"latitude\"] = latitude dict[\"longitude\"] = longitude dict[\"elevation\"] = elevation all_stations.append(dict) return jsonify(all_stations) @app.route(\"/api/v1.0/tobs\")",
") @app.route(\"/api/v1.0/precipitation\") def precipitation(): session = Session(engine) first_date = session.query(Measurement.date).order_by(Measurement.date).first() last_date = session.query(Measurement.date).order_by(Measurement.date.desc()).first()",
"session.query(Measurement.date, func.max(Measurement.prcp)).group_by(Measurement.date).\\ filter(Measurement.date > year_ago) session.close() # Create a dictionary from the row",
"session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\ filter(Measurement.date >= start_date).all() tobs_stats_all = [] for min, avg, max",
"engine = create_engine(\"sqlite:///Resources/hawaii.sqlite\") Base = automap_base() Base.prepare(engine, reflect=True) Measurement = Base.classes.measurement Station =",
"= automap_base() Base.prepare(engine, reflect=True) Measurement = Base.classes.measurement Station = Base.classes.station app = Flask(__name__)",
"tobs in most_active: dict = {} dict['date'] = date dict['tobs'] = tobs most_active_tobs.append(dict)",
"Base.classes.station app = Flask(__name__) @app.route(\"/\") def welcome(): \"\"\"List all available api routes.\"\"\" return",
"dict['avg'] = avg dict['max'] = max tobs_stats_all.append(dict) return jsonify(tobs_stats_all) if __name__ == '__main__':",
"= Flask(__name__) @app.route(\"/\") def welcome(): \"\"\"List all available api routes.\"\"\" return ( f\"Available",
"dt from flask import Flask, jsonify engine = create_engine(\"sqlite:///Resources/hawaii.sqlite\") Base = automap_base() Base.prepare(engine,",
"most_active_tobs.append(dict) return jsonify(most_active_tobs) @app.route(\"/api/v1.0/<start_date>\") def calc_temps_start(start_date): tobs_stats = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\ filter(Measurement.date >=",
"all_stations = [] for id, station, name, latitude, longitude, elevation in stations: dict",
"jsonify(all_dates) @app.route(\"/api/v1.0/stations\") def stations(): session = Session(engine) stations = session.query(Station.id, Station.station, Station.name, Station.latitude,",
"most_active = session.query(Measurement.date, Measurement.tobs).\\ filter(Measurement.station == 'USC00519281').\\ filter(Measurement.date > year_ago).all() most_active_tobs = []",
"@app.route(\"/\") def welcome(): \"\"\"List all available api routes.\"\"\" return ( f\"Available Routes:<br/>\" f\"/api/v1.0/precipitation<br/>\"",
"all_passengers all_dates = [] for date, prcp in date_prcp: dict = {} dict[\"date\"]",
"dict[\"name\"] = name dict[\"latitude\"] = latitude dict[\"longitude\"] = longitude dict[\"elevation\"] = elevation all_stations.append(dict)",
"def stations(): session = Session(engine) stations = session.query(Station.id, Station.station, Station.name, Station.latitude, Station.longitude, Station.elevation).all()",
"session = Session(engine) stations = session.query(Station.id, Station.station, Station.name, Station.latitude, Station.longitude, Station.elevation).all() all_stations =",
"dict = {} dict[\"date\"] = date dict[\"prcp\"] = prcp all_dates.append(dict) return jsonify(all_dates) @app.route(\"/api/v1.0/stations\")",
"jsonify(all_stations) @app.route(\"/api/v1.0/tobs\") def tobs(): session = Session(engine) year_ago = dt.date(2017, 8, 18) -",
"dict['date'] = date dict['tobs'] = tobs most_active_tobs.append(dict) return jsonify(most_active_tobs) @app.route(\"/api/v1.0/<start_date>\") def calc_temps_start(start_date): tobs_stats",
"def tobs(): session = Session(engine) year_ago = dt.date(2017, 8, 18) - dt.timedelta(days=365) most_active",
"start_date).all() tobs_stats_all = [] for min, avg, max in tobs_stats: dict = {}",
"= {} dict['min'] = min dict['avg'] = avg dict['max'] = max tobs_stats_all.append(dict) return",
"np import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy",
"@app.route(\"/api/v1.0/stations\") def stations(): session = Session(engine) stations = session.query(Station.id, Station.station, Station.name, Station.latitude, Station.longitude,",
"- dt.timedelta(days=365) date_prcp = session.query(Measurement.date, func.max(Measurement.prcp)).group_by(Measurement.date).\\ filter(Measurement.date > year_ago) session.close() # Create a",
"return jsonify(all_stations) @app.route(\"/api/v1.0/tobs\") def tobs(): session = Session(engine) year_ago = dt.date(2017, 8, 18)",
"= session.query(Measurement.date, Measurement.tobs).\\ filter(Measurement.station == 'USC00519281').\\ filter(Measurement.date > year_ago).all() most_active_tobs = [] for",
"f\"/api/v1.0/tobs<br/>\" f\"/api/v1.0/<start_date><br/>\" f\"/api/v1.0/<start_date>/<end_date><br/>\" ) @app.route(\"/api/v1.0/precipitation\") def precipitation(): session = Session(engine) first_date = session.query(Measurement.date).order_by(Measurement.date).first()",
"latitude, longitude, elevation in stations: dict = {} dict[\"id\"] = id dict[\"station\"] =",
"dt.date(2017, 8, 23) - dt.timedelta(days=365) date_prcp = session.query(Measurement.date, func.max(Measurement.prcp)).group_by(Measurement.date).\\ filter(Measurement.date > year_ago) session.close()",
"8, 23) - dt.timedelta(days=365) date_prcp = session.query(Measurement.date, func.max(Measurement.prcp)).group_by(Measurement.date).\\ filter(Measurement.date > year_ago) session.close() #",
"dt.timedelta(days=365) most_active = session.query(Measurement.date, Measurement.tobs).\\ filter(Measurement.station == 'USC00519281').\\ filter(Measurement.date > year_ago).all() most_active_tobs =",
"= max tobs_stats_all.append(dict) return jsonify(tobs_stats_all) @app.route(\"/api/v1.0/<start_date>/<end_date>\") def calc_temps_start_end(start_date, end_date): tobs_stats = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs),",
"tobs_stats_all.append(dict) return jsonify(tobs_stats_all) @app.route(\"/api/v1.0/<start_date>/<end_date>\") def calc_temps_start_end(start_date, end_date): tobs_stats = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\ filter(Measurement.date",
"to a list of all_passengers all_dates = [] for date, prcp in date_prcp:",
"calc_temps_start_end(start_date, end_date): tobs_stats = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\ filter(Measurement.date >= start_date).filter(Measurement.date <= end_date).all() tobs_stats_all",
"Session(engine) year_ago = dt.date(2017, 8, 18) - dt.timedelta(days=365) most_active = session.query(Measurement.date, Measurement.tobs).\\ filter(Measurement.station",
"func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\ filter(Measurement.date >= start_date).filter(Measurement.date <= end_date).all() tobs_stats_all = [] for min, avg,",
"name dict[\"latitude\"] = latitude dict[\"longitude\"] = longitude dict[\"elevation\"] = elevation all_stations.append(dict) return jsonify(all_stations)",
"year_ago = dt.date(2017, 8, 18) - dt.timedelta(days=365) most_active = session.query(Measurement.date, Measurement.tobs).\\ filter(Measurement.station ==",
"reflect=True) Measurement = Base.classes.measurement Station = Base.classes.station app = Flask(__name__) @app.route(\"/\") def welcome():",
"= avg dict['max'] = max tobs_stats_all.append(dict) return jsonify(tobs_stats_all) if __name__ == '__main__': app.run(debug=True)",
"= {} dict[\"date\"] = date dict[\"prcp\"] = prcp all_dates.append(dict) return jsonify(all_dates) @app.route(\"/api/v1.0/stations\") def",
"and append to a list of all_passengers all_dates = [] for date, prcp",
"Base = automap_base() Base.prepare(engine, reflect=True) Measurement = Base.classes.measurement Station = Base.classes.station app =",
"dict['max'] = max tobs_stats_all.append(dict) return jsonify(tobs_stats_all) @app.route(\"/api/v1.0/<start_date>/<end_date>\") def calc_temps_start_end(start_date, end_date): tobs_stats = session.query(func.min(Measurement.tobs),",
"of all_passengers all_dates = [] for date, prcp in date_prcp: dict = {}",
"# Create a dictionary from the row data and append to a list",
"Measurement.tobs).\\ filter(Measurement.station == 'USC00519281').\\ filter(Measurement.date > year_ago).all() most_active_tobs = [] for date, tobs",
"dictionary from the row data and append to a list of all_passengers all_dates",
"dict['tobs'] = tobs most_active_tobs.append(dict) return jsonify(most_active_tobs) @app.route(\"/api/v1.0/<start_date>\") def calc_temps_start(start_date): tobs_stats = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs),",
"return jsonify(most_active_tobs) @app.route(\"/api/v1.0/<start_date>\") def calc_temps_start(start_date): tobs_stats = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\ filter(Measurement.date >= start_date).all()",
"station, name, latitude, longitude, elevation in stations: dict = {} dict[\"id\"] = id",
"f\"Available Routes:<br/>\" f\"/api/v1.0/precipitation<br/>\" f\"/api/v1.0/stations<br/>\" f\"/api/v1.0/tobs<br/>\" f\"/api/v1.0/<start_date><br/>\" f\"/api/v1.0/<start_date>/<end_date><br/>\" ) @app.route(\"/api/v1.0/precipitation\") def precipitation(): session =",
"stations = session.query(Station.id, Station.station, Station.name, Station.latitude, Station.longitude, Station.elevation).all() all_stations = [] for id,",
"Station.station, Station.name, Station.latitude, Station.longitude, Station.elevation).all() all_stations = [] for id, station, name, latitude,",
"for date, tobs in most_active: dict = {} dict['date'] = date dict['tobs'] =",
"<= end_date).all() tobs_stats_all = [] for min, avg, max in tobs_stats: dict =",
"tobs(): session = Session(engine) year_ago = dt.date(2017, 8, 18) - dt.timedelta(days=365) most_active =",
"sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine,",
"import Session from sqlalchemy import create_engine, func import datetime as dt from flask",
"filter(Measurement.station == 'USC00519281').\\ filter(Measurement.date > year_ago).all() most_active_tobs = [] for date, tobs in",
"dict[\"prcp\"] = prcp all_dates.append(dict) return jsonify(all_dates) @app.route(\"/api/v1.0/stations\") def stations(): session = Session(engine) stations",
"= latitude dict[\"longitude\"] = longitude dict[\"elevation\"] = elevation all_stations.append(dict) return jsonify(all_stations) @app.route(\"/api/v1.0/tobs\") def",
"= session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\ filter(Measurement.date >= start_date).filter(Measurement.date <= end_date).all() tobs_stats_all = [] for",
"data and append to a list of all_passengers all_dates = [] for date,",
"tobs_stats = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\ filter(Measurement.date >= start_date).all() tobs_stats_all = [] for min,",
"min dict['avg'] = avg dict['max'] = max tobs_stats_all.append(dict) return jsonify(tobs_stats_all) if __name__ ==",
"= dt.date(2017, 8, 23) - dt.timedelta(days=365) date_prcp = session.query(Measurement.date, func.max(Measurement.prcp)).group_by(Measurement.date).\\ filter(Measurement.date > year_ago)",
"= session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\ filter(Measurement.date >= start_date).all() tobs_stats_all = [] for min, avg,",
"Station.elevation).all() all_stations = [] for id, station, name, latitude, longitude, elevation in stations:",
"= Session(engine) year_ago = dt.date(2017, 8, 18) - dt.timedelta(days=365) most_active = session.query(Measurement.date, Measurement.tobs).\\",
"stations(): session = Session(engine) stations = session.query(Station.id, Station.station, Station.name, Station.latitude, Station.longitude, Station.elevation).all() all_stations",
"all available api routes.\"\"\" return ( f\"Available Routes:<br/>\" f\"/api/v1.0/precipitation<br/>\" f\"/api/v1.0/stations<br/>\" f\"/api/v1.0/tobs<br/>\" f\"/api/v1.0/<start_date><br/>\" f\"/api/v1.0/<start_date>/<end_date><br/>\"",
"dict['min'] = min dict['avg'] = avg dict['max'] = max tobs_stats_all.append(dict) return jsonify(tobs_stats_all) if",
"Station = Base.classes.station app = Flask(__name__) @app.route(\"/\") def welcome(): \"\"\"List all available api",
"session = Session(engine) first_date = session.query(Measurement.date).order_by(Measurement.date).first() last_date = session.query(Measurement.date).order_by(Measurement.date.desc()).first() year_ago = dt.date(2017, 8,",
"latitude dict[\"longitude\"] = longitude dict[\"elevation\"] = elevation all_stations.append(dict) return jsonify(all_stations) @app.route(\"/api/v1.0/tobs\") def tobs():",
"[] for min, avg, max in tobs_stats: dict = {} dict['min'] = min",
"longitude dict[\"elevation\"] = elevation all_stations.append(dict) return jsonify(all_stations) @app.route(\"/api/v1.0/tobs\") def tobs(): session = Session(engine)",
"in date_prcp: dict = {} dict[\"date\"] = date dict[\"prcp\"] = prcp all_dates.append(dict) return",
"filter(Measurement.date > year_ago) session.close() # Create a dictionary from the row data and",
"[] for id, station, name, latitude, longitude, elevation in stations: dict = {}",
"session.query(Measurement.date).order_by(Measurement.date.desc()).first() year_ago = dt.date(2017, 8, 23) - dt.timedelta(days=365) date_prcp = session.query(Measurement.date, func.max(Measurement.prcp)).group_by(Measurement.date).\\ filter(Measurement.date",
"= session.query(Measurement.date).order_by(Measurement.date.desc()).first() year_ago = dt.date(2017, 8, 23) - dt.timedelta(days=365) date_prcp = session.query(Measurement.date, func.max(Measurement.prcp)).group_by(Measurement.date).\\",
"sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func import",
"import Flask, jsonify engine = create_engine(\"sqlite:///Resources/hawaii.sqlite\") Base = automap_base() Base.prepare(engine, reflect=True) Measurement =",
"= [] for min, avg, max in tobs_stats: dict = {} dict['min'] =",
"18) - dt.timedelta(days=365) most_active = session.query(Measurement.date, Measurement.tobs).\\ filter(Measurement.station == 'USC00519281').\\ filter(Measurement.date > year_ago).all()",
"func.max(Measurement.prcp)).group_by(Measurement.date).\\ filter(Measurement.date > year_ago) session.close() # Create a dictionary from the row data",
"date_prcp = session.query(Measurement.date, func.max(Measurement.prcp)).group_by(Measurement.date).\\ filter(Measurement.date > year_ago) session.close() # Create a dictionary from",
"as dt from flask import Flask, jsonify engine = create_engine(\"sqlite:///Resources/hawaii.sqlite\") Base = automap_base()",
"session.query(Station.id, Station.station, Station.name, Station.latitude, Station.longitude, Station.elevation).all() all_stations = [] for id, station, name,",
"[] for date, tobs in most_active: dict = {} dict['date'] = date dict['tobs']",
"jsonify engine = create_engine(\"sqlite:///Resources/hawaii.sqlite\") Base = automap_base() Base.prepare(engine, reflect=True) Measurement = Base.classes.measurement Station",
"end_date).all() tobs_stats_all = [] for min, avg, max in tobs_stats: dict = {}",
"( f\"Available Routes:<br/>\" f\"/api/v1.0/precipitation<br/>\" f\"/api/v1.0/stations<br/>\" f\"/api/v1.0/tobs<br/>\" f\"/api/v1.0/<start_date><br/>\" f\"/api/v1.0/<start_date>/<end_date><br/>\" ) @app.route(\"/api/v1.0/precipitation\") def precipitation(): session",
"Routes:<br/>\" f\"/api/v1.0/precipitation<br/>\" f\"/api/v1.0/stations<br/>\" f\"/api/v1.0/tobs<br/>\" f\"/api/v1.0/<start_date><br/>\" f\"/api/v1.0/<start_date>/<end_date><br/>\" ) @app.route(\"/api/v1.0/precipitation\") def precipitation(): session = Session(engine)",
"all_dates.append(dict) return jsonify(all_dates) @app.route(\"/api/v1.0/stations\") def stations(): session = Session(engine) stations = session.query(Station.id, Station.station,",
"start_date).filter(Measurement.date <= end_date).all() tobs_stats_all = [] for min, avg, max in tobs_stats: dict",
"create_engine, func import datetime as dt from flask import Flask, jsonify engine =",
"the row data and append to a list of all_passengers all_dates = []",
"dict[\"station\"] = station dict[\"name\"] = name dict[\"latitude\"] = latitude dict[\"longitude\"] = longitude dict[\"elevation\"]",
"dict[\"elevation\"] = elevation all_stations.append(dict) return jsonify(all_stations) @app.route(\"/api/v1.0/tobs\") def tobs(): session = Session(engine) year_ago",
"return ( f\"Available Routes:<br/>\" f\"/api/v1.0/precipitation<br/>\" f\"/api/v1.0/stations<br/>\" f\"/api/v1.0/tobs<br/>\" f\"/api/v1.0/<start_date><br/>\" f\"/api/v1.0/<start_date>/<end_date><br/>\" ) @app.route(\"/api/v1.0/precipitation\") def precipitation():",
"from flask import Flask, jsonify engine = create_engine(\"sqlite:///Resources/hawaii.sqlite\") Base = automap_base() Base.prepare(engine, reflect=True)",
"dict[\"date\"] = date dict[\"prcp\"] = prcp all_dates.append(dict) return jsonify(all_dates) @app.route(\"/api/v1.0/stations\") def stations(): session",
"tobs_stats_all = [] for min, avg, max in tobs_stats: dict = {} dict['min']",
"api routes.\"\"\" return ( f\"Available Routes:<br/>\" f\"/api/v1.0/precipitation<br/>\" f\"/api/v1.0/stations<br/>\" f\"/api/v1.0/tobs<br/>\" f\"/api/v1.0/<start_date><br/>\" f\"/api/v1.0/<start_date>/<end_date><br/>\" ) @app.route(\"/api/v1.0/precipitation\")",
"from sqlalchemy.orm import Session from sqlalchemy import create_engine, func import datetime as dt",
"@app.route(\"/api/v1.0/tobs\") def tobs(): session = Session(engine) year_ago = dt.date(2017, 8, 18) - dt.timedelta(days=365)",
"all_dates = [] for date, prcp in date_prcp: dict = {} dict[\"date\"] =",
"\"\"\"List all available api routes.\"\"\" return ( f\"Available Routes:<br/>\" f\"/api/v1.0/precipitation<br/>\" f\"/api/v1.0/stations<br/>\" f\"/api/v1.0/tobs<br/>\" f\"/api/v1.0/<start_date><br/>\"",
"Station.latitude, Station.longitude, Station.elevation).all() all_stations = [] for id, station, name, latitude, longitude, elevation",
"Station.longitude, Station.elevation).all() all_stations = [] for id, station, name, latitude, longitude, elevation in",
"dt.timedelta(days=365) date_prcp = session.query(Measurement.date, func.max(Measurement.prcp)).group_by(Measurement.date).\\ filter(Measurement.date > year_ago) session.close() # Create a dictionary",
"station dict[\"name\"] = name dict[\"latitude\"] = latitude dict[\"longitude\"] = longitude dict[\"elevation\"] = elevation",
"session = Session(engine) year_ago = dt.date(2017, 8, 18) - dt.timedelta(days=365) most_active = session.query(Measurement.date,",
"dict[\"longitude\"] = longitude dict[\"elevation\"] = elevation all_stations.append(dict) return jsonify(all_stations) @app.route(\"/api/v1.0/tobs\") def tobs(): session",
"datetime as dt from flask import Flask, jsonify engine = create_engine(\"sqlite:///Resources/hawaii.sqlite\") Base =",
"= create_engine(\"sqlite:///Resources/hawaii.sqlite\") Base = automap_base() Base.prepare(engine, reflect=True) Measurement = Base.classes.measurement Station = Base.classes.station",
"tobs most_active_tobs.append(dict) return jsonify(most_active_tobs) @app.route(\"/api/v1.0/<start_date>\") def calc_temps_start(start_date): tobs_stats = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\ filter(Measurement.date",
"first_date = session.query(Measurement.date).order_by(Measurement.date).first() last_date = session.query(Measurement.date).order_by(Measurement.date.desc()).first() year_ago = dt.date(2017, 8, 23) - dt.timedelta(days=365)",
"max tobs_stats_all.append(dict) return jsonify(tobs_stats_all) @app.route(\"/api/v1.0/<start_date>/<end_date>\") def calc_temps_start_end(start_date, end_date): tobs_stats = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\",
"sqlalchemy.orm import Session from sqlalchemy import create_engine, func import datetime as dt from",
"flask import Flask, jsonify engine = create_engine(\"sqlite:///Resources/hawaii.sqlite\") Base = automap_base() Base.prepare(engine, reflect=True) Measurement",
"= Base.classes.station app = Flask(__name__) @app.route(\"/\") def welcome(): \"\"\"List all available api routes.\"\"\"",
"import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func import datetime",
"import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import",
"numpy as np import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session",
"sqlalchemy import create_engine, func import datetime as dt from flask import Flask, jsonify",
"prcp in date_prcp: dict = {} dict[\"date\"] = date dict[\"prcp\"] = prcp all_dates.append(dict)",
"@app.route(\"/api/v1.0/precipitation\") def precipitation(): session = Session(engine) first_date = session.query(Measurement.date).order_by(Measurement.date).first() last_date = session.query(Measurement.date).order_by(Measurement.date.desc()).first() year_ago",
"= date dict[\"prcp\"] = prcp all_dates.append(dict) return jsonify(all_dates) @app.route(\"/api/v1.0/stations\") def stations(): session =",
"prcp all_dates.append(dict) return jsonify(all_dates) @app.route(\"/api/v1.0/stations\") def stations(): session = Session(engine) stations = session.query(Station.id,",
"id, station, name, latitude, longitude, elevation in stations: dict = {} dict[\"id\"] =",
"import datetime as dt from flask import Flask, jsonify engine = create_engine(\"sqlite:///Resources/hawaii.sqlite\") Base",
"stations: dict = {} dict[\"id\"] = id dict[\"station\"] = station dict[\"name\"] = name",
"dict[\"id\"] = id dict[\"station\"] = station dict[\"name\"] = name dict[\"latitude\"] = latitude dict[\"longitude\"]",
"func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\ filter(Measurement.date >= start_date).all() tobs_stats_all = [] for min, avg, max in",
"as np import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from",
"elevation all_stations.append(dict) return jsonify(all_stations) @app.route(\"/api/v1.0/tobs\") def tobs(): session = Session(engine) year_ago = dt.date(2017,",
"= {} dict['date'] = date dict['tobs'] = tobs most_active_tobs.append(dict) return jsonify(most_active_tobs) @app.route(\"/api/v1.0/<start_date>\") def",
"f\"/api/v1.0/<start_date>/<end_date><br/>\" ) @app.route(\"/api/v1.0/precipitation\") def precipitation(): session = Session(engine) first_date = session.query(Measurement.date).order_by(Measurement.date).first() last_date =",
"dict = {} dict['date'] = date dict['tobs'] = tobs most_active_tobs.append(dict) return jsonify(most_active_tobs) @app.route(\"/api/v1.0/<start_date>\")",
"min dict['avg'] = avg dict['max'] = max tobs_stats_all.append(dict) return jsonify(tobs_stats_all) @app.route(\"/api/v1.0/<start_date>/<end_date>\") def calc_temps_start_end(start_date,",
"in stations: dict = {} dict[\"id\"] = id dict[\"station\"] = station dict[\"name\"] =",
"session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\ filter(Measurement.date >= start_date).filter(Measurement.date <= end_date).all() tobs_stats_all = [] for min,",
"tobs_stats: dict = {} dict['min'] = min dict['avg'] = avg dict['max'] = max",
">= start_date).filter(Measurement.date <= end_date).all() tobs_stats_all = [] for min, avg, max in tobs_stats:",
"name, latitude, longitude, elevation in stations: dict = {} dict[\"id\"] = id dict[\"station\"]",
"= id dict[\"station\"] = station dict[\"name\"] = name dict[\"latitude\"] = latitude dict[\"longitude\"] =",
"dict = {} dict[\"id\"] = id dict[\"station\"] = station dict[\"name\"] = name dict[\"latitude\"]",
"Base.prepare(engine, reflect=True) Measurement = Base.classes.measurement Station = Base.classes.station app = Flask(__name__) @app.route(\"/\") def",
"dict['min'] = min dict['avg'] = avg dict['max'] = max tobs_stats_all.append(dict) return jsonify(tobs_stats_all) @app.route(\"/api/v1.0/<start_date>/<end_date>\")",
"min, avg, max in tobs_stats: dict = {} dict['min'] = min dict['avg'] =",
"Flask(__name__) @app.route(\"/\") def welcome(): \"\"\"List all available api routes.\"\"\" return ( f\"Available Routes:<br/>\"",
"Session(engine) stations = session.query(Station.id, Station.station, Station.name, Station.latitude, Station.longitude, Station.elevation).all() all_stations = [] for",
"@app.route(\"/api/v1.0/<start_date>\") def calc_temps_start(start_date): tobs_stats = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\ filter(Measurement.date >= start_date).all() tobs_stats_all =",
"dict['avg'] = avg dict['max'] = max tobs_stats_all.append(dict) return jsonify(tobs_stats_all) @app.route(\"/api/v1.0/<start_date>/<end_date>\") def calc_temps_start_end(start_date, end_date):",
"Flask, jsonify engine = create_engine(\"sqlite:///Resources/hawaii.sqlite\") Base = automap_base() Base.prepare(engine, reflect=True) Measurement = Base.classes.measurement",
"f\"/api/v1.0/<start_date><br/>\" f\"/api/v1.0/<start_date>/<end_date><br/>\" ) @app.route(\"/api/v1.0/precipitation\") def precipitation(): session = Session(engine) first_date = session.query(Measurement.date).order_by(Measurement.date).first() last_date",
"- dt.timedelta(days=365) most_active = session.query(Measurement.date, Measurement.tobs).\\ filter(Measurement.station == 'USC00519281').\\ filter(Measurement.date > year_ago).all() most_active_tobs",
"{} dict['min'] = min dict['avg'] = avg dict['max'] = max tobs_stats_all.append(dict) return jsonify(tobs_stats_all)",
"elevation in stations: dict = {} dict[\"id\"] = id dict[\"station\"] = station dict[\"name\"]",
"longitude, elevation in stations: dict = {} dict[\"id\"] = id dict[\"station\"] = station",
"@app.route(\"/api/v1.0/<start_date>/<end_date>\") def calc_temps_start_end(start_date, end_date): tobs_stats = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\ filter(Measurement.date >= start_date).filter(Measurement.date <=",
"year_ago).all() most_active_tobs = [] for date, tobs in most_active: dict = {} dict['date']",
"= Base.classes.measurement Station = Base.classes.station app = Flask(__name__) @app.route(\"/\") def welcome(): \"\"\"List all",
"func.max(Measurement.tobs)).\\ filter(Measurement.date >= start_date).all() tobs_stats_all = [] for min, avg, max in tobs_stats:",
"def calc_temps_start_end(start_date, end_date): tobs_stats = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\ filter(Measurement.date >= start_date).filter(Measurement.date <= end_date).all()",
"date dict['tobs'] = tobs most_active_tobs.append(dict) return jsonify(most_active_tobs) @app.route(\"/api/v1.0/<start_date>\") def calc_temps_start(start_date): tobs_stats = session.query(func.min(Measurement.tobs),",
"= prcp all_dates.append(dict) return jsonify(all_dates) @app.route(\"/api/v1.0/stations\") def stations(): session = Session(engine) stations =",
"id dict[\"station\"] = station dict[\"name\"] = name dict[\"latitude\"] = latitude dict[\"longitude\"] = longitude",
"= longitude dict[\"elevation\"] = elevation all_stations.append(dict) return jsonify(all_stations) @app.route(\"/api/v1.0/tobs\") def tobs(): session =",
"import numpy as np import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import"
] |
[
"# Needed to init the MazeSolver.ALGORITHMS list alg_gen, alg_sol, width, height = -1,",
"\") while solve_anim.lower() not in [\"y\", \"n\"]: solve_anim = input(\"Enable animation for solving?",
"the n° of the algorithm for the solving: \") print() while width not",
"= True if build_anim.lower() == \"y\" else False mt.Window.SOLVE_ANIMATION = True if solve_anim.lower()",
"in range(len(mt.MazeGenerator.ALGORITHMS)): print( f\"{vc.CMDColors.YELLOW} {i}: {list(mt.MazeGenerator.ALGORITHMS.keys())[i]} {vc.CMDColors.RESET}\" ) print() while alg_gen not in",
"width, height = -1, -1, -1, -1 build_anim, solve_anim = \"\", \"\" #",
"print() while alg_gen not in range(len(mt.MazeGenerator.ALGORITHMS)): alg_gen = ask_for_int(\"Input the n° of the",
"height = ask_for_int(\"Height of the maze: \") print() while build_anim.lower() not in [\"y\",",
"while build_anim.lower() not in [\"y\", \"n\"]: build_anim = input(\"Enable animation for building? (Y/N):",
"in range(len(mt.MazeSolver.ALGORITHMS)): print( f\"{vc.CMDColors.YELLOW} {i}: {list(mt.MazeSolver.ALGORITHMS.keys())[i]} {vc.CMDColors.RESET}\" ) print() while alg_sol not in",
"generation: \") print() for i in range(len(mt.MazeSolver.ALGORITHMS)): print( f\"{vc.CMDColors.YELLOW} {i}: {list(mt.MazeSolver.ALGORITHMS.keys())[i]} {vc.CMDColors.RESET}\" )",
"(Y/N): \") while solve_anim.lower() not in [\"y\", \"n\"]: solve_anim = input(\"Enable animation for",
"of the maze: \") while height not in range(1000): height = ask_for_int(\"Height of",
"for solving? (Y/N): \") print() # Setting animation properties for pygame window mt.Window.GENERATE_ANIMATION",
"mt.MazeGenerator(alg_gen) maze_solver = mt.MazeSolver(alg_sol) # Drawing print( vc.CMDColors.CYAN + \"Press \" + vc.CMDColors.FAIL",
"-1 build_anim, solve_anim = \"\", \"\" # Getting the user's inputs for i",
"= ask_for_int(\"Width of the maze: \") while height not in range(1000): height =",
"in range(1000): width = ask_for_int(\"Width of the maze: \") while height not in",
"alg_sol, width, height = -1, -1, -1, -1 build_anim, solve_anim = \"\", \"\"",
"maze.\\nPress \" + vc.CMDColors.FAIL + \"SPACE\" + vc.CMDColors.CYAN + \" again to solve",
"the user for an integer. \"\"\" while True: try: return int(input(sentence)) except ValueError:",
"pygame window # Initializing maze = m.Maze(width, height) maze_generator = mt.MazeGenerator(alg_gen) maze_solver =",
"+ vc.CMDColors.FAIL + \"SPACE\" + vc.CMDColors.CYAN + \" again to solve it.\\nPress \"",
"# Initializing maze = m.Maze(width, height) maze_generator = mt.MazeGenerator(alg_gen) maze_solver = mt.MazeSolver(alg_sol) #",
"the pygame window # Initializing maze = m.Maze(width, height) maze_generator = mt.MazeGenerator(alg_gen) maze_solver",
"\"Press \" + vc.CMDColors.FAIL + \"SPACE\" + vc.CMDColors.CYAN + \" to start building",
"vc.CMDColors.HEADER + \"CTRL+C\" + vc.CMDColors.CYAN + \" in the terminal to exit.\" +",
"+ \"CTRL+C\" + vc.CMDColors.CYAN + \" in the terminal to exit.\" + vc.CMDColors.RESET",
"mt.Window.GENERATE_ANIMATION = True if build_anim.lower() == \"y\" else False mt.Window.SOLVE_ANIMATION = True if",
"= ask_for_int(\"Input the n° of the algorithm for the solving: \") print() while",
"alg_gen = ask_for_int(\"Input the n° of the algorithm for the generation: \") print()",
"start building the maze.\\nPress \" + vc.CMDColors.FAIL + \"SPACE\" + vc.CMDColors.CYAN + \"",
"import maze.maze as m import maze.maze_tools as mt import visual.colors as vc from",
"exit.\" + vc.CMDColors.RESET ) # Starting the animations maze_drawer = mt.MazeDrawer(maze_generator, maze_solver, maze)",
"except ValueError: print(\"Invalid input. Please try again.\") def main(): # Intializing variables _",
"again.\") def main(): # Intializing variables _ = mt.MazeGenerator(0) # Needed to init",
"the solving: \") print() while width not in range(1000): width = ask_for_int(\"Width of",
"in range(1000): height = ask_for_int(\"Height of the maze: \") print() while build_anim.lower() not",
"Please try again.\") def main(): # Intializing variables _ = mt.MazeGenerator(0) # Needed",
"print() while build_anim.lower() not in [\"y\", \"n\"]: build_anim = input(\"Enable animation for building?",
"int: \"\"\" Ask the user for an integer. \"\"\" while True: try: return",
"vc.CMDColors.CYAN + \"Press \" + vc.CMDColors.FAIL + \"SPACE\" + vc.CMDColors.CYAN + \" to",
"algorithm for the solving: \") print() while width not in range(1000): width =",
"Drawing print( vc.CMDColors.CYAN + \"Press \" + vc.CMDColors.FAIL + \"SPACE\" + vc.CMDColors.CYAN +",
"animation for building? (Y/N): \") while solve_anim.lower() not in [\"y\", \"n\"]: solve_anim =",
"i in range(len(mt.MazeSolver.ALGORITHMS)): print( f\"{vc.CMDColors.YELLOW} {i}: {list(mt.MazeSolver.ALGORITHMS.keys())[i]} {vc.CMDColors.RESET}\" ) print() while alg_sol not",
"f\"{vc.CMDColors.YELLOW} {i}: {list(mt.MazeSolver.ALGORITHMS.keys())[i]} {vc.CMDColors.RESET}\" ) print() while alg_sol not in range(len(mt.MazeSolver.ALGORITHMS)): alg_sol =",
"if build_anim.lower() == \"y\" else False mt.Window.SOLVE_ANIMATION = True if solve_anim.lower() == \"y\"",
"init the MazeSolver.ALGORITHMS list alg_gen, alg_sol, width, height = -1, -1, -1, -1",
"mt.MazeGenerator(0) # Needed to init the MazeBuilder.ALGORITHMS list _ = mt.MazeSolver(0) # Needed",
"{vc.CMDColors.RESET}\" ) print() while alg_gen not in range(len(mt.MazeGenerator.ALGORITHMS)): alg_gen = ask_for_int(\"Input the n°",
"maze.maze as m import maze.maze_tools as mt import visual.colors as vc from abc",
"of the maze: \") print() while build_anim.lower() not in [\"y\", \"n\"]: build_anim =",
"Getting the user's inputs for i in range(len(mt.MazeGenerator.ALGORITHMS)): print( f\"{vc.CMDColors.YELLOW} {i}: {list(mt.MazeGenerator.ALGORITHMS.keys())[i]} {vc.CMDColors.RESET}\"",
"integer. \"\"\" while True: try: return int(input(sentence)) except ValueError: print(\"Invalid input. Please try",
"\") print() # Setting animation properties for pygame window mt.Window.GENERATE_ANIMATION = True if",
"\") print() while build_anim.lower() not in [\"y\", \"n\"]: build_anim = input(\"Enable animation for",
"alg_sol = ask_for_int(\"Input the n° of the algorithm for the solving: \") print()",
"build_anim.lower() not in [\"y\", \"n\"]: build_anim = input(\"Enable animation for building? (Y/N): \")",
"window # Initializing maze = m.Maze(width, height) maze_generator = mt.MazeGenerator(alg_gen) maze_solver = mt.MazeSolver(alg_sol)",
"# Drawing print( vc.CMDColors.CYAN + \"Press \" + vc.CMDColors.FAIL + \"SPACE\" + vc.CMDColors.CYAN",
"Needed to init the MazeSolver.ALGORITHMS list alg_gen, alg_sol, width, height = -1, -1,",
"{vc.CMDColors.RESET}\" ) print() while alg_sol not in range(len(mt.MazeSolver.ALGORITHMS)): alg_sol = ask_for_int(\"Input the n°",
"not in range(len(mt.MazeSolver.ALGORITHMS)): alg_sol = ask_for_int(\"Input the n° of the algorithm for the",
"-> int: \"\"\" Ask the user for an integer. \"\"\" while True: try:",
"solve_anim.lower() == \"y\" else False # Showing the maze on the pygame window",
"== \"y\" else False mt.Window.SOLVE_ANIMATION = True if solve_anim.lower() == \"y\" else False",
"the n° of the algorithm for the generation: \") print() for i in",
"False # Showing the maze on the pygame window # Initializing maze =",
"solving: \") print() while width not in range(1000): width = ask_for_int(\"Width of the",
"import abstractmethod def ask_for_int(sentence: str) -> int: \"\"\" Ask the user for an",
"range(1000): height = ask_for_int(\"Height of the maze: \") print() while build_anim.lower() not in",
"# Setting animation properties for pygame window mt.Window.GENERATE_ANIMATION = True if build_anim.lower() ==",
"print() for i in range(len(mt.MazeSolver.ALGORITHMS)): print( f\"{vc.CMDColors.YELLOW} {i}: {list(mt.MazeSolver.ALGORITHMS.keys())[i]} {vc.CMDColors.RESET}\" ) print() while",
"width = ask_for_int(\"Width of the maze: \") while height not in range(1000): height",
"\"y\" else False mt.Window.SOLVE_ANIMATION = True if solve_anim.lower() == \"y\" else False #",
"try: return int(input(sentence)) except ValueError: print(\"Invalid input. Please try again.\") def main(): #",
"solving? (Y/N): \") print() # Setting animation properties for pygame window mt.Window.GENERATE_ANIMATION =",
") print() while alg_sol not in range(len(mt.MazeSolver.ALGORITHMS)): alg_sol = ask_for_int(\"Input the n° of",
"to start building the maze.\\nPress \" + vc.CMDColors.FAIL + \"SPACE\" + vc.CMDColors.CYAN +",
"mt.MazeSolver(0) # Needed to init the MazeSolver.ALGORITHMS list alg_gen, alg_sol, width, height =",
"= -1, -1, -1, -1 build_anim, solve_anim = \"\", \"\" # Getting the",
"inputs for i in range(len(mt.MazeGenerator.ALGORITHMS)): print( f\"{vc.CMDColors.YELLOW} {i}: {list(mt.MazeGenerator.ALGORITHMS.keys())[i]} {vc.CMDColors.RESET}\" ) print() while",
"algorithm for the generation: \") print() for i in range(len(mt.MazeSolver.ALGORITHMS)): print( f\"{vc.CMDColors.YELLOW} {i}:",
"\") print() for i in range(len(mt.MazeSolver.ALGORITHMS)): print( f\"{vc.CMDColors.YELLOW} {i}: {list(mt.MazeSolver.ALGORITHMS.keys())[i]} {vc.CMDColors.RESET}\" ) print()",
"maze: \") print() while build_anim.lower() not in [\"y\", \"n\"]: build_anim = input(\"Enable animation",
"+ vc.CMDColors.CYAN + \" to start building the maze.\\nPress \" + vc.CMDColors.FAIL +",
"pygame window mt.Window.GENERATE_ANIMATION = True if build_anim.lower() == \"y\" else False mt.Window.SOLVE_ANIMATION =",
"in [\"y\", \"n\"]: build_anim = input(\"Enable animation for building? (Y/N): \") while solve_anim.lower()",
"ask_for_int(\"Input the n° of the algorithm for the solving: \") print() while width",
"mt.Window.SOLVE_ANIMATION = True if solve_anim.lower() == \"y\" else False # Showing the maze",
"properties for pygame window mt.Window.GENERATE_ANIMATION = True if build_anim.lower() == \"y\" else False",
"the MazeBuilder.ALGORITHMS list _ = mt.MazeSolver(0) # Needed to init the MazeSolver.ALGORITHMS list",
"Ask the user for an integer. \"\"\" while True: try: return int(input(sentence)) except",
"range(len(mt.MazeGenerator.ALGORITHMS)): alg_gen = ask_for_int(\"Input the n° of the algorithm for the generation: \")",
"range(len(mt.MazeSolver.ALGORITHMS)): print( f\"{vc.CMDColors.YELLOW} {i}: {list(mt.MazeSolver.ALGORITHMS.keys())[i]} {vc.CMDColors.RESET}\" ) print() while alg_sol not in range(len(mt.MazeSolver.ALGORITHMS)):",
"= mt.MazeGenerator(alg_gen) maze_solver = mt.MazeSolver(alg_sol) # Drawing print( vc.CMDColors.CYAN + \"Press \" +",
"-1, -1, -1 build_anim, solve_anim = \"\", \"\" # Getting the user's inputs",
"solve it.\\nPress \" + vc.CMDColors.HEADER + \"CTRL+C\" + vc.CMDColors.CYAN + \" in the",
"as vc from abc import abstractmethod def ask_for_int(sentence: str) -> int: \"\"\" Ask",
"str) -> int: \"\"\" Ask the user for an integer. \"\"\" while True:",
"<reponame>marcpinet/maze-generator-and-solver import maze.maze as m import maze.maze_tools as mt import visual.colors as vc",
"ask_for_int(sentence: str) -> int: \"\"\" Ask the user for an integer. \"\"\" while",
"for pygame window mt.Window.GENERATE_ANIMATION = True if build_anim.lower() == \"y\" else False mt.Window.SOLVE_ANIMATION",
"maze = m.Maze(width, height) maze_generator = mt.MazeGenerator(alg_gen) maze_solver = mt.MazeSolver(alg_sol) # Drawing print(",
"building the maze.\\nPress \" + vc.CMDColors.FAIL + \"SPACE\" + vc.CMDColors.CYAN + \" again",
"+ vc.CMDColors.CYAN + \" again to solve it.\\nPress \" + vc.CMDColors.HEADER + \"CTRL+C\"",
"\"CTRL+C\" + vc.CMDColors.CYAN + \" in the terminal to exit.\" + vc.CMDColors.RESET )",
"on the pygame window # Initializing maze = m.Maze(width, height) maze_generator = mt.MazeGenerator(alg_gen)",
"maze.maze_tools as mt import visual.colors as vc from abc import abstractmethod def ask_for_int(sentence:",
"print() while alg_sol not in range(len(mt.MazeSolver.ALGORITHMS)): alg_sol = ask_for_int(\"Input the n° of the",
"\"n\"]: solve_anim = input(\"Enable animation for solving? (Y/N): \") print() # Setting animation",
"Intializing variables _ = mt.MazeGenerator(0) # Needed to init the MazeBuilder.ALGORITHMS list _",
"build_anim, solve_anim = \"\", \"\" # Getting the user's inputs for i in",
"the generation: \") print() for i in range(len(mt.MazeSolver.ALGORITHMS)): print( f\"{vc.CMDColors.YELLOW} {i}: {list(mt.MazeSolver.ALGORITHMS.keys())[i]} {vc.CMDColors.RESET}\"",
"maze: \") while height not in range(1000): height = ask_for_int(\"Height of the maze:",
"= input(\"Enable animation for solving? (Y/N): \") print() # Setting animation properties for",
"input. Please try again.\") def main(): # Intializing variables _ = mt.MazeGenerator(0) #",
"return int(input(sentence)) except ValueError: print(\"Invalid input. Please try again.\") def main(): # Intializing",
"vc.CMDColors.CYAN + \" again to solve it.\\nPress \" + vc.CMDColors.HEADER + \"CTRL+C\" +",
"abc import abstractmethod def ask_for_int(sentence: str) -> int: \"\"\" Ask the user for",
"if solve_anim.lower() == \"y\" else False # Showing the maze on the pygame",
"alg_gen, alg_sol, width, height = -1, -1, -1, -1 build_anim, solve_anim = \"\",",
"print() # Setting animation properties for pygame window mt.Window.GENERATE_ANIMATION = True if build_anim.lower()",
"the maze on the pygame window # Initializing maze = m.Maze(width, height) maze_generator",
"vc.CMDColors.CYAN + \" to start building the maze.\\nPress \" + vc.CMDColors.FAIL + \"SPACE\"",
"MazeSolver.ALGORITHMS list alg_gen, alg_sol, width, height = -1, -1, -1, -1 build_anim, solve_anim",
"+ vc.CMDColors.FAIL + \"SPACE\" + vc.CMDColors.CYAN + \" to start building the maze.\\nPress",
"maze_solver = mt.MazeSolver(alg_sol) # Drawing print( vc.CMDColors.CYAN + \"Press \" + vc.CMDColors.FAIL +",
"print( f\"{vc.CMDColors.YELLOW} {i}: {list(mt.MazeGenerator.ALGORITHMS.keys())[i]} {vc.CMDColors.RESET}\" ) print() while alg_gen not in range(len(mt.MazeGenerator.ALGORITHMS)): alg_gen",
"alg_sol not in range(len(mt.MazeSolver.ALGORITHMS)): alg_sol = ask_for_int(\"Input the n° of the algorithm for",
"{list(mt.MazeSolver.ALGORITHMS.keys())[i]} {vc.CMDColors.RESET}\" ) print() while alg_sol not in range(len(mt.MazeSolver.ALGORITHMS)): alg_sol = ask_for_int(\"Input the",
"of the algorithm for the solving: \") print() while width not in range(1000):",
"the algorithm for the solving: \") print() while width not in range(1000): width",
"not in range(1000): width = ask_for_int(\"Width of the maze: \") while height not",
"while alg_gen not in range(len(mt.MazeGenerator.ALGORITHMS)): alg_gen = ask_for_int(\"Input the n° of the algorithm",
"width not in range(1000): width = ask_for_int(\"Width of the maze: \") while height",
"= mt.MazeGenerator(0) # Needed to init the MazeBuilder.ALGORITHMS list _ = mt.MazeSolver(0) #",
"solve_anim.lower() not in [\"y\", \"n\"]: solve_anim = input(\"Enable animation for solving? (Y/N): \")",
"+ \" to start building the maze.\\nPress \" + vc.CMDColors.FAIL + \"SPACE\" +",
"\" + vc.CMDColors.FAIL + \"SPACE\" + vc.CMDColors.CYAN + \" to start building the",
"{i}: {list(mt.MazeSolver.ALGORITHMS.keys())[i]} {vc.CMDColors.RESET}\" ) print() while alg_sol not in range(len(mt.MazeSolver.ALGORITHMS)): alg_sol = ask_for_int(\"Input",
"= ask_for_int(\"Height of the maze: \") print() while build_anim.lower() not in [\"y\", \"n\"]:",
"while width not in range(1000): width = ask_for_int(\"Width of the maze: \") while",
"build_anim.lower() == \"y\" else False mt.Window.SOLVE_ANIMATION = True if solve_anim.lower() == \"y\" else",
"\"SPACE\" + vc.CMDColors.CYAN + \" to start building the maze.\\nPress \" + vc.CMDColors.FAIL",
"in range(len(mt.MazeSolver.ALGORITHMS)): alg_sol = ask_for_int(\"Input the n° of the algorithm for the solving:",
"not in range(1000): height = ask_for_int(\"Height of the maze: \") print() while build_anim.lower()",
"vc from abc import abstractmethod def ask_for_int(sentence: str) -> int: \"\"\" Ask the",
"Initializing maze = m.Maze(width, height) maze_generator = mt.MazeGenerator(alg_gen) maze_solver = mt.MazeSolver(alg_sol) # Drawing",
"-1, -1, -1, -1 build_anim, solve_anim = \"\", \"\" # Getting the user's",
"vc.CMDColors.RESET ) # Starting the animations maze_drawer = mt.MazeDrawer(maze_generator, maze_solver, maze) maze_drawer.start() if",
"\"\"\" Ask the user for an integer. \"\"\" while True: try: return int(input(sentence))",
"\"n\"]: build_anim = input(\"Enable animation for building? (Y/N): \") while solve_anim.lower() not in",
"_ = mt.MazeGenerator(0) # Needed to init the MazeBuilder.ALGORITHMS list _ = mt.MazeSolver(0)",
"user for an integer. \"\"\" while True: try: return int(input(sentence)) except ValueError: print(\"Invalid",
"f\"{vc.CMDColors.YELLOW} {i}: {list(mt.MazeGenerator.ALGORITHMS.keys())[i]} {vc.CMDColors.RESET}\" ) print() while alg_gen not in range(len(mt.MazeGenerator.ALGORITHMS)): alg_gen =",
"= ask_for_int(\"Input the n° of the algorithm for the generation: \") print() for",
"solve_anim = input(\"Enable animation for solving? (Y/N): \") print() # Setting animation properties",
"+ vc.CMDColors.CYAN + \" in the terminal to exit.\" + vc.CMDColors.RESET ) #",
"from abc import abstractmethod def ask_for_int(sentence: str) -> int: \"\"\" Ask the user",
"= mt.MazeSolver(alg_sol) # Drawing print( vc.CMDColors.CYAN + \"Press \" + vc.CMDColors.FAIL + \"SPACE\"",
"\"y\" else False # Showing the maze on the pygame window # Initializing",
"not in [\"y\", \"n\"]: build_anim = input(\"Enable animation for building? (Y/N): \") while",
"in range(len(mt.MazeGenerator.ALGORITHMS)): alg_gen = ask_for_int(\"Input the n° of the algorithm for the generation:",
"True if build_anim.lower() == \"y\" else False mt.Window.SOLVE_ANIMATION = True if solve_anim.lower() ==",
"= True if solve_anim.lower() == \"y\" else False # Showing the maze on",
"animation for solving? (Y/N): \") print() # Setting animation properties for pygame window",
"maze_generator = mt.MazeGenerator(alg_gen) maze_solver = mt.MazeSolver(alg_sol) # Drawing print( vc.CMDColors.CYAN + \"Press \"",
"[\"y\", \"n\"]: solve_anim = input(\"Enable animation for solving? (Y/N): \") print() # Setting",
"+ \" again to solve it.\\nPress \" + vc.CMDColors.HEADER + \"CTRL+C\" + vc.CMDColors.CYAN",
"for building? (Y/N): \") while solve_anim.lower() not in [\"y\", \"n\"]: solve_anim = input(\"Enable",
"# Intializing variables _ = mt.MazeGenerator(0) # Needed to init the MazeBuilder.ALGORITHMS list",
"as m import maze.maze_tools as mt import visual.colors as vc from abc import",
"the MazeSolver.ALGORITHMS list alg_gen, alg_sol, width, height = -1, -1, -1, -1 build_anim,",
"for i in range(len(mt.MazeGenerator.ALGORITHMS)): print( f\"{vc.CMDColors.YELLOW} {i}: {list(mt.MazeGenerator.ALGORITHMS.keys())[i]} {vc.CMDColors.RESET}\" ) print() while alg_gen",
"alg_gen not in range(len(mt.MazeGenerator.ALGORITHMS)): alg_gen = ask_for_int(\"Input the n° of the algorithm for",
"for i in range(len(mt.MazeSolver.ALGORITHMS)): print( f\"{vc.CMDColors.YELLOW} {i}: {list(mt.MazeSolver.ALGORITHMS.keys())[i]} {vc.CMDColors.RESET}\" ) print() while alg_sol",
"building? (Y/N): \") while solve_anim.lower() not in [\"y\", \"n\"]: solve_anim = input(\"Enable animation",
"+ vc.CMDColors.HEADER + \"CTRL+C\" + vc.CMDColors.CYAN + \" in the terminal to exit.\"",
"Starting the animations maze_drawer = mt.MazeDrawer(maze_generator, maze_solver, maze) maze_drawer.start() if __name__ == \"__main__\":",
"print(\"Invalid input. Please try again.\") def main(): # Intializing variables _ = mt.MazeGenerator(0)",
"ValueError: print(\"Invalid input. Please try again.\") def main(): # Intializing variables _ =",
"{i}: {list(mt.MazeGenerator.ALGORITHMS.keys())[i]} {vc.CMDColors.RESET}\" ) print() while alg_gen not in range(len(mt.MazeGenerator.ALGORITHMS)): alg_gen = ask_for_int(\"Input",
") print() while alg_gen not in range(len(mt.MazeGenerator.ALGORITHMS)): alg_gen = ask_for_int(\"Input the n° of",
"vc.CMDColors.FAIL + \"SPACE\" + vc.CMDColors.CYAN + \" again to solve it.\\nPress \" +",
"the animations maze_drawer = mt.MazeDrawer(maze_generator, maze_solver, maze) maze_drawer.start() if __name__ == \"__main__\": main()",
"ask_for_int(\"Width of the maze: \") while height not in range(1000): height = ask_for_int(\"Height",
"+ \"SPACE\" + vc.CMDColors.CYAN + \" to start building the maze.\\nPress \" +",
"+ \"SPACE\" + vc.CMDColors.CYAN + \" again to solve it.\\nPress \" + vc.CMDColors.HEADER",
"the maze: \") print() while build_anim.lower() not in [\"y\", \"n\"]: build_anim = input(\"Enable",
"Needed to init the MazeBuilder.ALGORITHMS list _ = mt.MazeSolver(0) # Needed to init",
"height) maze_generator = mt.MazeGenerator(alg_gen) maze_solver = mt.MazeSolver(alg_sol) # Drawing print( vc.CMDColors.CYAN + \"Press",
"\") while height not in range(1000): height = ask_for_int(\"Height of the maze: \")",
"try again.\") def main(): # Intializing variables _ = mt.MazeGenerator(0) # Needed to",
"for the solving: \") print() while width not in range(1000): width = ask_for_int(\"Width",
"the maze: \") while height not in range(1000): height = ask_for_int(\"Height of the",
"while solve_anim.lower() not in [\"y\", \"n\"]: solve_anim = input(\"Enable animation for solving? (Y/N):",
"n° of the algorithm for the solving: \") print() while width not in",
"Showing the maze on the pygame window # Initializing maze = m.Maze(width, height)",
"vc.CMDColors.CYAN + \" in the terminal to exit.\" + vc.CMDColors.RESET ) # Starting",
"False mt.Window.SOLVE_ANIMATION = True if solve_anim.lower() == \"y\" else False # Showing the",
"\"SPACE\" + vc.CMDColors.CYAN + \" again to solve it.\\nPress \" + vc.CMDColors.HEADER +",
"def main(): # Intializing variables _ = mt.MazeGenerator(0) # Needed to init the",
"= mt.MazeSolver(0) # Needed to init the MazeSolver.ALGORITHMS list alg_gen, alg_sol, width, height",
"variables _ = mt.MazeGenerator(0) # Needed to init the MazeBuilder.ALGORITHMS list _ =",
"height not in range(1000): height = ask_for_int(\"Height of the maze: \") print() while",
"to init the MazeBuilder.ALGORITHMS list _ = mt.MazeSolver(0) # Needed to init the",
"to init the MazeSolver.ALGORITHMS list alg_gen, alg_sol, width, height = -1, -1, -1,",
"m.Maze(width, height) maze_generator = mt.MazeGenerator(alg_gen) maze_solver = mt.MazeSolver(alg_sol) # Drawing print( vc.CMDColors.CYAN +",
"\"\" # Getting the user's inputs for i in range(len(mt.MazeGenerator.ALGORITHMS)): print( f\"{vc.CMDColors.YELLOW} {i}:",
"import visual.colors as vc from abc import abstractmethod def ask_for_int(sentence: str) -> int:",
"# Showing the maze on the pygame window # Initializing maze = m.Maze(width,",
"as mt import visual.colors as vc from abc import abstractmethod def ask_for_int(sentence: str)",
"to solve it.\\nPress \" + vc.CMDColors.HEADER + \"CTRL+C\" + vc.CMDColors.CYAN + \" in",
"else False mt.Window.SOLVE_ANIMATION = True if solve_anim.lower() == \"y\" else False # Showing",
"_ = mt.MazeSolver(0) # Needed to init the MazeSolver.ALGORITHMS list alg_gen, alg_sol, width,",
"user's inputs for i in range(len(mt.MazeGenerator.ALGORITHMS)): print( f\"{vc.CMDColors.YELLOW} {i}: {list(mt.MazeGenerator.ALGORITHMS.keys())[i]} {vc.CMDColors.RESET}\" ) print()",
"mt import visual.colors as vc from abc import abstractmethod def ask_for_int(sentence: str) ->",
"solve_anim = \"\", \"\" # Getting the user's inputs for i in range(len(mt.MazeGenerator.ALGORITHMS)):",
"+ vc.CMDColors.RESET ) # Starting the animations maze_drawer = mt.MazeDrawer(maze_generator, maze_solver, maze) maze_drawer.start()",
") # Starting the animations maze_drawer = mt.MazeDrawer(maze_generator, maze_solver, maze) maze_drawer.start() if __name__",
"def ask_for_int(sentence: str) -> int: \"\"\" Ask the user for an integer. \"\"\"",
"\"\"\" while True: try: return int(input(sentence)) except ValueError: print(\"Invalid input. Please try again.\")",
"main(): # Intializing variables _ = mt.MazeGenerator(0) # Needed to init the MazeBuilder.ALGORITHMS",
"== \"y\" else False # Showing the maze on the pygame window #",
"the maze.\\nPress \" + vc.CMDColors.FAIL + \"SPACE\" + vc.CMDColors.CYAN + \" again to",
"# Needed to init the MazeBuilder.ALGORITHMS list _ = mt.MazeSolver(0) # Needed to",
"build_anim = input(\"Enable animation for building? (Y/N): \") while solve_anim.lower() not in [\"y\",",
"ask_for_int(\"Height of the maze: \") print() while build_anim.lower() not in [\"y\", \"n\"]: build_anim",
"else False # Showing the maze on the pygame window # Initializing maze",
"print( f\"{vc.CMDColors.YELLOW} {i}: {list(mt.MazeSolver.ALGORITHMS.keys())[i]} {vc.CMDColors.RESET}\" ) print() while alg_sol not in range(len(mt.MazeSolver.ALGORITHMS)): alg_sol",
"window mt.Window.GENERATE_ANIMATION = True if build_anim.lower() == \"y\" else False mt.Window.SOLVE_ANIMATION = True",
"height = -1, -1, -1, -1 build_anim, solve_anim = \"\", \"\" # Getting",
"[\"y\", \"n\"]: build_anim = input(\"Enable animation for building? (Y/N): \") while solve_anim.lower() not",
"input(\"Enable animation for solving? (Y/N): \") print() # Setting animation properties for pygame",
"animation properties for pygame window mt.Window.GENERATE_ANIMATION = True if build_anim.lower() == \"y\" else",
"list _ = mt.MazeSolver(0) # Needed to init the MazeSolver.ALGORITHMS list alg_gen, alg_sol,",
"= input(\"Enable animation for building? (Y/N): \") while solve_anim.lower() not in [\"y\", \"n\"]:",
"the user's inputs for i in range(len(mt.MazeGenerator.ALGORITHMS)): print( f\"{vc.CMDColors.YELLOW} {i}: {list(mt.MazeGenerator.ALGORITHMS.keys())[i]} {vc.CMDColors.RESET}\" )",
"vc.CMDColors.FAIL + \"SPACE\" + vc.CMDColors.CYAN + \" to start building the maze.\\nPress \"",
"+ \" in the terminal to exit.\" + vc.CMDColors.RESET ) # Starting the",
"print( vc.CMDColors.CYAN + \"Press \" + vc.CMDColors.FAIL + \"SPACE\" + vc.CMDColors.CYAN + \"",
"\" in the terminal to exit.\" + vc.CMDColors.RESET ) # Starting the animations",
"m import maze.maze_tools as mt import visual.colors as vc from abc import abstractmethod",
"for an integer. \"\"\" while True: try: return int(input(sentence)) except ValueError: print(\"Invalid input.",
"i in range(len(mt.MazeGenerator.ALGORITHMS)): print( f\"{vc.CMDColors.YELLOW} {i}: {list(mt.MazeGenerator.ALGORITHMS.keys())[i]} {vc.CMDColors.RESET}\" ) print() while alg_gen not",
"the algorithm for the generation: \") print() for i in range(len(mt.MazeSolver.ALGORITHMS)): print( f\"{vc.CMDColors.YELLOW}",
"ask_for_int(\"Input the n° of the algorithm for the generation: \") print() for i",
"in the terminal to exit.\" + vc.CMDColors.RESET ) # Starting the animations maze_drawer",
"# Starting the animations maze_drawer = mt.MazeDrawer(maze_generator, maze_solver, maze) maze_drawer.start() if __name__ ==",
"while height not in range(1000): height = ask_for_int(\"Height of the maze: \") print()",
"True if solve_anim.lower() == \"y\" else False # Showing the maze on the",
"= \"\", \"\" # Getting the user's inputs for i in range(len(mt.MazeGenerator.ALGORITHMS)): print(",
"while alg_sol not in range(len(mt.MazeSolver.ALGORITHMS)): alg_sol = ask_for_int(\"Input the n° of the algorithm",
"in [\"y\", \"n\"]: solve_anim = input(\"Enable animation for solving? (Y/N): \") print() #",
"terminal to exit.\" + vc.CMDColors.RESET ) # Starting the animations maze_drawer = mt.MazeDrawer(maze_generator,",
"not in [\"y\", \"n\"]: solve_anim = input(\"Enable animation for solving? (Y/N): \") print()",
"= m.Maze(width, height) maze_generator = mt.MazeGenerator(alg_gen) maze_solver = mt.MazeSolver(alg_sol) # Drawing print( vc.CMDColors.CYAN",
"of the algorithm for the generation: \") print() for i in range(len(mt.MazeSolver.ALGORITHMS)): print(",
"an integer. \"\"\" while True: try: return int(input(sentence)) except ValueError: print(\"Invalid input. Please",
"\"\", \"\" # Getting the user's inputs for i in range(len(mt.MazeGenerator.ALGORITHMS)): print( f\"{vc.CMDColors.YELLOW}",
"{list(mt.MazeGenerator.ALGORITHMS.keys())[i]} {vc.CMDColors.RESET}\" ) print() while alg_gen not in range(len(mt.MazeGenerator.ALGORITHMS)): alg_gen = ask_for_int(\"Input the",
"\" again to solve it.\\nPress \" + vc.CMDColors.HEADER + \"CTRL+C\" + vc.CMDColors.CYAN +",
"import maze.maze_tools as mt import visual.colors as vc from abc import abstractmethod def",
"int(input(sentence)) except ValueError: print(\"Invalid input. Please try again.\") def main(): # Intializing variables",
"range(len(mt.MazeGenerator.ALGORITHMS)): print( f\"{vc.CMDColors.YELLOW} {i}: {list(mt.MazeGenerator.ALGORITHMS.keys())[i]} {vc.CMDColors.RESET}\" ) print() while alg_gen not in range(len(mt.MazeGenerator.ALGORITHMS)):",
"print() while width not in range(1000): width = ask_for_int(\"Width of the maze: \")",
"visual.colors as vc from abc import abstractmethod def ask_for_int(sentence: str) -> int: \"\"\"",
"to exit.\" + vc.CMDColors.RESET ) # Starting the animations maze_drawer = mt.MazeDrawer(maze_generator, maze_solver,",
"(Y/N): \") print() # Setting animation properties for pygame window mt.Window.GENERATE_ANIMATION = True",
"range(1000): width = ask_for_int(\"Width of the maze: \") while height not in range(1000):",
"-1, -1 build_anim, solve_anim = \"\", \"\" # Getting the user's inputs for",
"n° of the algorithm for the generation: \") print() for i in range(len(mt.MazeSolver.ALGORITHMS)):",
"init the MazeBuilder.ALGORITHMS list _ = mt.MazeSolver(0) # Needed to init the MazeSolver.ALGORITHMS",
"input(\"Enable animation for building? (Y/N): \") while solve_anim.lower() not in [\"y\", \"n\"]: solve_anim",
"again to solve it.\\nPress \" + vc.CMDColors.HEADER + \"CTRL+C\" + vc.CMDColors.CYAN + \"",
"\" + vc.CMDColors.HEADER + \"CTRL+C\" + vc.CMDColors.CYAN + \" in the terminal to",
"it.\\nPress \" + vc.CMDColors.HEADER + \"CTRL+C\" + vc.CMDColors.CYAN + \" in the terminal",
"range(len(mt.MazeSolver.ALGORITHMS)): alg_sol = ask_for_int(\"Input the n° of the algorithm for the solving: \")",
"not in range(len(mt.MazeGenerator.ALGORITHMS)): alg_gen = ask_for_int(\"Input the n° of the algorithm for the",
"+ \"Press \" + vc.CMDColors.FAIL + \"SPACE\" + vc.CMDColors.CYAN + \" to start",
"\") print() while width not in range(1000): width = ask_for_int(\"Width of the maze:",
"list alg_gen, alg_sol, width, height = -1, -1, -1, -1 build_anim, solve_anim =",
"\" + vc.CMDColors.FAIL + \"SPACE\" + vc.CMDColors.CYAN + \" again to solve it.\\nPress",
"# Getting the user's inputs for i in range(len(mt.MazeGenerator.ALGORITHMS)): print( f\"{vc.CMDColors.YELLOW} {i}: {list(mt.MazeGenerator.ALGORITHMS.keys())[i]}",
"Setting animation properties for pygame window mt.Window.GENERATE_ANIMATION = True if build_anim.lower() == \"y\"",
"True: try: return int(input(sentence)) except ValueError: print(\"Invalid input. Please try again.\") def main():",
"for the generation: \") print() for i in range(len(mt.MazeSolver.ALGORITHMS)): print( f\"{vc.CMDColors.YELLOW} {i}: {list(mt.MazeSolver.ALGORITHMS.keys())[i]}",
"mt.MazeSolver(alg_sol) # Drawing print( vc.CMDColors.CYAN + \"Press \" + vc.CMDColors.FAIL + \"SPACE\" +",
"abstractmethod def ask_for_int(sentence: str) -> int: \"\"\" Ask the user for an integer.",
"MazeBuilder.ALGORITHMS list _ = mt.MazeSolver(0) # Needed to init the MazeSolver.ALGORITHMS list alg_gen,",
"the terminal to exit.\" + vc.CMDColors.RESET ) # Starting the animations maze_drawer =",
"\" to start building the maze.\\nPress \" + vc.CMDColors.FAIL + \"SPACE\" + vc.CMDColors.CYAN",
"while True: try: return int(input(sentence)) except ValueError: print(\"Invalid input. Please try again.\") def",
"maze on the pygame window # Initializing maze = m.Maze(width, height) maze_generator ="
] |
[
"requests import json from datetime import datetime def get_all_products(): url = \"https://api.fmarket.vn/res/products/filter\" data",
"import json from datetime import datetime def get_all_products(): url = \"https://api.fmarket.vn/res/products/filter\" data =",
"datetime import datetime def get_all_products(): url = \"https://api.fmarket.vn/res/products/filter\" data = {\"types\":[\"NEW_FUND\",\"TRADING_FUND\"],\"issuerIds\":[],\"page\":1,\"pageSize\":1000,\"fundAssetTypes\":[],\"bondRemainPeriods\":[],\"searchField\":\"\"} headers =",
"= {\"Content-Type\": \"application/json; charset=utf-8\"} x = requests.post(url, json=data, headers=headers) return json.loads(x.text) def get_history(product_id):",
"toDate} headers = {\"Content-Type\": \"application/json; charset=utf-8\"} x = requests.post(url, json=data, headers=headers) return json.loads(x.text)",
"= \"https://api.fmarket.vn/res/products/filter\" data = {\"types\":[\"NEW_FUND\",\"TRADING_FUND\"],\"issuerIds\":[],\"page\":1,\"pageSize\":1000,\"fundAssetTypes\":[],\"bondRemainPeriods\":[],\"searchField\":\"\"} headers = {\"Content-Type\": \"application/json; charset=utf-8\"} x = requests.post(url,",
"<gh_stars>0 import requests import json from datetime import datetime def get_all_products(): url =",
"= {\"isAllData\":1,\"productId\":product_id,\"fromDate\": None, \"toDate\": toDate} headers = {\"Content-Type\": \"application/json; charset=utf-8\"} x = requests.post(url,",
"\"https://api.fmarket.vn/res/product/get-nav-history\" toDate = datetime.now().strftime(\"%Y%m%d\") data = {\"isAllData\":1,\"productId\":product_id,\"fromDate\": None, \"toDate\": toDate} headers = {\"Content-Type\":",
"x = requests.post(url, json=data, headers=headers) return json.loads(x.text) def get_history(product_id): url = \"https://api.fmarket.vn/res/product/get-nav-history\" toDate",
"datetime def get_all_products(): url = \"https://api.fmarket.vn/res/products/filter\" data = {\"types\":[\"NEW_FUND\",\"TRADING_FUND\"],\"issuerIds\":[],\"page\":1,\"pageSize\":1000,\"fundAssetTypes\":[],\"bondRemainPeriods\":[],\"searchField\":\"\"} headers = {\"Content-Type\": \"application/json;",
"get_history(product_id): url = \"https://api.fmarket.vn/res/product/get-nav-history\" toDate = datetime.now().strftime(\"%Y%m%d\") data = {\"isAllData\":1,\"productId\":product_id,\"fromDate\": None, \"toDate\": toDate}",
"url = \"https://api.fmarket.vn/res/products/filter\" data = {\"types\":[\"NEW_FUND\",\"TRADING_FUND\"],\"issuerIds\":[],\"page\":1,\"pageSize\":1000,\"fundAssetTypes\":[],\"bondRemainPeriods\":[],\"searchField\":\"\"} headers = {\"Content-Type\": \"application/json; charset=utf-8\"} x =",
"from datetime import datetime def get_all_products(): url = \"https://api.fmarket.vn/res/products/filter\" data = {\"types\":[\"NEW_FUND\",\"TRADING_FUND\"],\"issuerIds\":[],\"page\":1,\"pageSize\":1000,\"fundAssetTypes\":[],\"bondRemainPeriods\":[],\"searchField\":\"\"} headers",
"get_all_products(): url = \"https://api.fmarket.vn/res/products/filter\" data = {\"types\":[\"NEW_FUND\",\"TRADING_FUND\"],\"issuerIds\":[],\"page\":1,\"pageSize\":1000,\"fundAssetTypes\":[],\"bondRemainPeriods\":[],\"searchField\":\"\"} headers = {\"Content-Type\": \"application/json; charset=utf-8\"} x",
"return json.loads(x.text) def get_history(product_id): url = \"https://api.fmarket.vn/res/product/get-nav-history\" toDate = datetime.now().strftime(\"%Y%m%d\") data = {\"isAllData\":1,\"productId\":product_id,\"fromDate\":",
"def get_history(product_id): url = \"https://api.fmarket.vn/res/product/get-nav-history\" toDate = datetime.now().strftime(\"%Y%m%d\") data = {\"isAllData\":1,\"productId\":product_id,\"fromDate\": None, \"toDate\":",
"import datetime def get_all_products(): url = \"https://api.fmarket.vn/res/products/filter\" data = {\"types\":[\"NEW_FUND\",\"TRADING_FUND\"],\"issuerIds\":[],\"page\":1,\"pageSize\":1000,\"fundAssetTypes\":[],\"bondRemainPeriods\":[],\"searchField\":\"\"} headers = {\"Content-Type\":",
"= requests.post(url, json=data, headers=headers) return json.loads(x.text) def get_history(product_id): url = \"https://api.fmarket.vn/res/product/get-nav-history\" toDate =",
"headers=headers) return json.loads(x.text) def get_history(product_id): url = \"https://api.fmarket.vn/res/product/get-nav-history\" toDate = datetime.now().strftime(\"%Y%m%d\") data =",
"= \"https://api.fmarket.vn/res/product/get-nav-history\" toDate = datetime.now().strftime(\"%Y%m%d\") data = {\"isAllData\":1,\"productId\":product_id,\"fromDate\": None, \"toDate\": toDate} headers =",
"{\"types\":[\"NEW_FUND\",\"TRADING_FUND\"],\"issuerIds\":[],\"page\":1,\"pageSize\":1000,\"fundAssetTypes\":[],\"bondRemainPeriods\":[],\"searchField\":\"\"} headers = {\"Content-Type\": \"application/json; charset=utf-8\"} x = requests.post(url, json=data, headers=headers) return json.loads(x.text)",
"url = \"https://api.fmarket.vn/res/product/get-nav-history\" toDate = datetime.now().strftime(\"%Y%m%d\") data = {\"isAllData\":1,\"productId\":product_id,\"fromDate\": None, \"toDate\": toDate} headers",
"\"https://api.fmarket.vn/res/products/filter\" data = {\"types\":[\"NEW_FUND\",\"TRADING_FUND\"],\"issuerIds\":[],\"page\":1,\"pageSize\":1000,\"fundAssetTypes\":[],\"bondRemainPeriods\":[],\"searchField\":\"\"} headers = {\"Content-Type\": \"application/json; charset=utf-8\"} x = requests.post(url, json=data,",
"json=data, headers=headers) return json.loads(x.text) def get_history(product_id): url = \"https://api.fmarket.vn/res/product/get-nav-history\" toDate = datetime.now().strftime(\"%Y%m%d\") data",
"data = {\"types\":[\"NEW_FUND\",\"TRADING_FUND\"],\"issuerIds\":[],\"page\":1,\"pageSize\":1000,\"fundAssetTypes\":[],\"bondRemainPeriods\":[],\"searchField\":\"\"} headers = {\"Content-Type\": \"application/json; charset=utf-8\"} x = requests.post(url, json=data, headers=headers)",
"data = {\"isAllData\":1,\"productId\":product_id,\"fromDate\": None, \"toDate\": toDate} headers = {\"Content-Type\": \"application/json; charset=utf-8\"} x =",
"headers = {\"Content-Type\": \"application/json; charset=utf-8\"} x = requests.post(url, json=data, headers=headers) return json.loads(x.text) def",
"\"toDate\": toDate} headers = {\"Content-Type\": \"application/json; charset=utf-8\"} x = requests.post(url, json=data, headers=headers) return",
"\"application/json; charset=utf-8\"} x = requests.post(url, json=data, headers=headers) return json.loads(x.text) def get_history(product_id): url =",
"{\"Content-Type\": \"application/json; charset=utf-8\"} x = requests.post(url, json=data, headers=headers) return json.loads(x.text) def get_history(product_id): url",
"{\"isAllData\":1,\"productId\":product_id,\"fromDate\": None, \"toDate\": toDate} headers = {\"Content-Type\": \"application/json; charset=utf-8\"} x = requests.post(url, json=data,",
"= {\"types\":[\"NEW_FUND\",\"TRADING_FUND\"],\"issuerIds\":[],\"page\":1,\"pageSize\":1000,\"fundAssetTypes\":[],\"bondRemainPeriods\":[],\"searchField\":\"\"} headers = {\"Content-Type\": \"application/json; charset=utf-8\"} x = requests.post(url, json=data, headers=headers) return",
"json from datetime import datetime def get_all_products(): url = \"https://api.fmarket.vn/res/products/filter\" data = {\"types\":[\"NEW_FUND\",\"TRADING_FUND\"],\"issuerIds\":[],\"page\":1,\"pageSize\":1000,\"fundAssetTypes\":[],\"bondRemainPeriods\":[],\"searchField\":\"\"}",
"charset=utf-8\"} x = requests.post(url, json=data, headers=headers) return json.loads(x.text) def get_history(product_id): url = \"https://api.fmarket.vn/res/product/get-nav-history\"",
"requests.post(url, json=data, headers=headers) return json.loads(x.text) def get_history(product_id): url = \"https://api.fmarket.vn/res/product/get-nav-history\" toDate = datetime.now().strftime(\"%Y%m%d\")",
"def get_all_products(): url = \"https://api.fmarket.vn/res/products/filter\" data = {\"types\":[\"NEW_FUND\",\"TRADING_FUND\"],\"issuerIds\":[],\"page\":1,\"pageSize\":1000,\"fundAssetTypes\":[],\"bondRemainPeriods\":[],\"searchField\":\"\"} headers = {\"Content-Type\": \"application/json; charset=utf-8\"}",
"= datetime.now().strftime(\"%Y%m%d\") data = {\"isAllData\":1,\"productId\":product_id,\"fromDate\": None, \"toDate\": toDate} headers = {\"Content-Type\": \"application/json; charset=utf-8\"}",
"datetime.now().strftime(\"%Y%m%d\") data = {\"isAllData\":1,\"productId\":product_id,\"fromDate\": None, \"toDate\": toDate} headers = {\"Content-Type\": \"application/json; charset=utf-8\"} x",
"import requests import json from datetime import datetime def get_all_products(): url = \"https://api.fmarket.vn/res/products/filter\"",
"json.loads(x.text) def get_history(product_id): url = \"https://api.fmarket.vn/res/product/get-nav-history\" toDate = datetime.now().strftime(\"%Y%m%d\") data = {\"isAllData\":1,\"productId\":product_id,\"fromDate\": None,",
"None, \"toDate\": toDate} headers = {\"Content-Type\": \"application/json; charset=utf-8\"} x = requests.post(url, json=data, headers=headers)",
"toDate = datetime.now().strftime(\"%Y%m%d\") data = {\"isAllData\":1,\"productId\":product_id,\"fromDate\": None, \"toDate\": toDate} headers = {\"Content-Type\": \"application/json;"
] |
[
"@params(api='gl', prms=['index', 'v']) def glVertexAttrib1hvNV(index, v): pass @params(api='gl', prms=['index', 'x', 'y']) def glVertexAttrib2hNV(index,",
"ny, nz): pass @params(api='gl', prms=['v']) def glNormal3hvNV(v): pass @params(api='gl', prms=['red', 'green', 'blue']) def",
"@params(api='gl', prms=['target', 's']) def glMultiTexCoord1hNV(target, s): pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord1hvNV(target, v):",
"def glVertexAttrib3hvNV(index, v): pass @params(api='gl', prms=['index', 'x', 'y', 'z', 'w']) def glVertexAttrib4hNV(index, x,",
"'y', 'z', 'w']) def glVertex4hNV(x, y, z, w): pass @params(api='gl', prms=['v']) def glVertex4hvNV(v):",
"pass @params(api='gl', prms=['index', 'x']) def glVertexAttrib1hNV(index, x): pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib1hvNV(index,",
"@params(api='gl', prms=['index', 'x', 'y']) def glVertexAttrib2hNV(index, x, y): pass @params(api='gl', prms=['index', 'v']) def",
"'s', 't', 'r']) def glMultiTexCoord3hNV(target, s, t, r): pass @params(api='gl', prms=['target', 'v']) def",
"prms=['v']) def glTexCoord2hvNV(v): pass @params(api='gl', prms=['s', 't', 'r']) def glTexCoord3hNV(s, t, r): pass",
"glMultiTexCoord3hNV(target, s, t, r): pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord3hvNV(target, v): pass @params(api='gl',",
"@params(api='gl', prms=['target', 's', 't']) def glMultiTexCoord2hNV(target, s, t): pass @params(api='gl', prms=['target', 'v']) def",
"r): pass @params(api='gl', prms=['v']) def glTexCoord3hvNV(v): pass @params(api='gl', prms=['s', 't', 'r', 'q']) def",
"def glFogCoordhvNV(fog): pass @params(api='gl', prms=['red', 'green', 'blue']) def glSecondaryColor3hNV(red, green, blue): pass @params(api='gl',",
"glVertexAttribs2hvNV(index, n, v): pass @params(api='gl', prms=['index', 'n', 'v']) def glVertexAttribs3hvNV(index, n, v): pass",
"@params(api='gl', prms=['fog']) def glFogCoordhNV(fog): pass @params(api='gl', prms=['fog']) def glFogCoordhvNV(fog): pass @params(api='gl', prms=['red', 'green',",
"@params(api='gl', prms=['v']) def glVertex3hvNV(v): pass @params(api='gl', prms=['x', 'y', 'z', 'w']) def glVertex4hNV(x, y,",
"pass @params(api='gl', prms=['index', 'n', 'v']) def glVertexAttribs1hvNV(index, n, v): pass @params(api='gl', prms=['index', 'n',",
"z, w): pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib4hvNV(index, v): pass @params(api='gl', prms=['index', 'n',",
"'z']) def glVertex3hNV(x, y, z): pass @params(api='gl', prms=['v']) def glVertex3hvNV(v): pass @params(api='gl', prms=['x',",
"def glTexCoord4hvNV(v): pass @params(api='gl', prms=['target', 's']) def glMultiTexCoord1hNV(target, s): pass @params(api='gl', prms=['target', 'v'])",
"'r']) def glTexCoord3hNV(s, t, r): pass @params(api='gl', prms=['v']) def glTexCoord3hvNV(v): pass @params(api='gl', prms=['s',",
"def glTexCoord2hvNV(v): pass @params(api='gl', prms=['s', 't', 'r']) def glTexCoord3hNV(s, t, r): pass @params(api='gl',",
"'z']) def glVertexAttrib3hNV(index, x, y, z): pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib3hvNV(index, v):",
"'z', 'w']) def glVertex4hNV(x, y, z, w): pass @params(api='gl', prms=['v']) def glVertex4hvNV(v): pass",
"v): pass @params(api='gl', prms=['index', 'n', 'v']) def glVertexAttribs2hvNV(index, n, v): pass @params(api='gl', prms=['index',",
"glNormal3hvNV(v): pass @params(api='gl', prms=['red', 'green', 'blue']) def glColor3hNV(red, green, blue): pass @params(api='gl', prms=['v'])",
"s, t): pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord2hvNV(target, v): pass @params(api='gl', prms=['target', 's',",
"pass @params(api='gl', prms=['index', 'n', 'v']) def glVertexAttribs2hvNV(index, n, v): pass @params(api='gl', prms=['index', 'n',",
"n, v): pass @params(api='gl', prms=['index', 'n', 'v']) def glVertexAttribs2hvNV(index, n, v): pass @params(api='gl',",
"@params(api='gl', prms=['target', 'v']) def glMultiTexCoord2hvNV(target, v): pass @params(api='gl', prms=['target', 's', 't', 'r']) def",
"glColor3hNV(red, green, blue): pass @params(api='gl', prms=['v']) def glColor3hvNV(v): pass @params(api='gl', prms=['red', 'green', 'blue',",
"def glColor4hvNV(v): pass @params(api='gl', prms=['s']) def glTexCoord1hNV(s): pass @params(api='gl', prms=['v']) def glTexCoord1hvNV(v): pass",
"@params(api='gl', prms=['nx', 'ny', 'nz']) def glNormal3hNV(nx, ny, nz): pass @params(api='gl', prms=['v']) def glNormal3hvNV(v):",
"'n', 'v']) def glVertexAttribs3hvNV(index, n, v): pass @params(api='gl', prms=['index', 'n', 'v']) def glVertexAttribs4hvNV(index,",
"'nz']) def glNormal3hNV(nx, ny, nz): pass @params(api='gl', prms=['v']) def glNormal3hvNV(v): pass @params(api='gl', prms=['red',",
"def glVertex2hvNV(v): pass @params(api='gl', prms=['x', 'y', 'z']) def glVertex3hNV(x, y, z): pass @params(api='gl',",
"def glTexCoord3hNV(s, t, r): pass @params(api='gl', prms=['v']) def glTexCoord3hvNV(v): pass @params(api='gl', prms=['s', 't',",
"'v']) def glMultiTexCoord3hvNV(target, v): pass @params(api='gl', prms=['target', 's', 't', 'r', 'q']) def glMultiTexCoord4hNV(target,",
"prms=['v']) def glVertex2hvNV(v): pass @params(api='gl', prms=['x', 'y', 'z']) def glVertex3hNV(x, y, z): pass",
"glTexCoord2hvNV(v): pass @params(api='gl', prms=['s', 't', 'r']) def glTexCoord3hNV(s, t, r): pass @params(api='gl', prms=['v'])",
"'v']) def glVertexAttrib3hvNV(index, v): pass @params(api='gl', prms=['index', 'x', 'y', 'z', 'w']) def glVertexAttrib4hNV(index,",
"'y', 'z']) def glVertexAttrib3hNV(index, x, y, z): pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib3hvNV(index,",
"def glVertexAttrib1hvNV(index, v): pass @params(api='gl', prms=['index', 'x', 'y']) def glVertexAttrib2hNV(index, x, y): pass",
"prms=['target', 'v']) def glMultiTexCoord2hvNV(target, v): pass @params(api='gl', prms=['target', 's', 't', 'r']) def glMultiTexCoord3hNV(target,",
"prms=['target', 's']) def glMultiTexCoord1hNV(target, s): pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord1hvNV(target, v): pass",
"pass @params(api='gl', prms=['index', 'x', 'y', 'z', 'w']) def glVertexAttrib4hNV(index, x, y, z, w):",
"glVertex3hNV(x, y, z): pass @params(api='gl', prms=['v']) def glVertex3hvNV(v): pass @params(api='gl', prms=['x', 'y', 'z',",
"prms=['v']) def glColor3hvNV(v): pass @params(api='gl', prms=['red', 'green', 'blue', 'alpha']) def glColor4hNV(red, green, blue,",
"prms=['fog']) def glFogCoordhNV(fog): pass @params(api='gl', prms=['fog']) def glFogCoordhvNV(fog): pass @params(api='gl', prms=['red', 'green', 'blue'])",
"'v']) def glVertexAttrib4hvNV(index, v): pass @params(api='gl', prms=['index', 'n', 'v']) def glVertexAttribs1hvNV(index, n, v):",
"prms=['x', 'y']) def glVertex2hNV(x, y): pass @params(api='gl', prms=['v']) def glVertex2hvNV(v): pass @params(api='gl', prms=['x',",
"'r']) def glMultiTexCoord3hNV(target, s, t, r): pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord3hvNV(target, v):",
"'y']) def glVertexAttrib2hNV(index, x, y): pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib2hvNV(index, v): pass",
"y, z): pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib3hvNV(index, v): pass @params(api='gl', prms=['index', 'x',",
"def glVertexAttrib1hNV(index, x): pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib1hvNV(index, v): pass @params(api='gl', prms=['index',",
"pass @params(api='gl', prms=['s']) def glTexCoord1hNV(s): pass @params(api='gl', prms=['v']) def glTexCoord1hvNV(v): pass @params(api='gl', prms=['s',",
"glSecondaryColor3hNV(red, green, blue): pass @params(api='gl', prms=['v']) def glSecondaryColor3hvNV(v): pass @params(api='gl', prms=['weight']) def glVertexWeighthNV(weight):",
"green, blue): pass @params(api='gl', prms=['v']) def glSecondaryColor3hvNV(v): pass @params(api='gl', prms=['weight']) def glVertexWeighthNV(weight): pass",
"'v']) def glMultiTexCoord4hvNV(target, v): pass @params(api='gl', prms=['fog']) def glFogCoordhNV(fog): pass @params(api='gl', prms=['fog']) def",
"y, z, w): pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib4hvNV(index, v): pass @params(api='gl', prms=['index',",
"pass @params(api='gl', prms=['s', 't', 'r', 'q']) def glTexCoord4hNV(s, t, r, q): pass @params(api='gl',",
"def glVertex4hvNV(v): pass @params(api='gl', prms=['nx', 'ny', 'nz']) def glNormal3hNV(nx, ny, nz): pass @params(api='gl',",
"prms=['index', 'x']) def glVertexAttrib1hNV(index, x): pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib1hvNV(index, v): pass",
"prms=['index', 'v']) def glVertexAttrib3hvNV(index, v): pass @params(api='gl', prms=['index', 'x', 'y', 'z', 'w']) def",
"prms=['weight']) def glVertexWeighthvNV(weight): pass @params(api='gl', prms=['index', 'x']) def glVertexAttrib1hNV(index, x): pass @params(api='gl', prms=['index',",
"glVertex4hvNV(v): pass @params(api='gl', prms=['nx', 'ny', 'nz']) def glNormal3hNV(nx, ny, nz): pass @params(api='gl', prms=['v'])",
"def glMultiTexCoord1hvNV(target, v): pass @params(api='gl', prms=['target', 's', 't']) def glMultiTexCoord2hNV(target, s, t): pass",
"glMultiTexCoord4hNV(target, s, t, r, q): pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord4hvNV(target, v): pass",
"glMultiTexCoord2hvNV(target, v): pass @params(api='gl', prms=['target', 's', 't', 'r']) def glMultiTexCoord3hNV(target, s, t, r):",
"<gh_stars>0 from OpenGLCffi.GL import params @params(api='gl', prms=['x', 'y']) def glVertex2hNV(x, y): pass @params(api='gl',",
"pass @params(api='gl', prms=['v']) def glVertex2hvNV(v): pass @params(api='gl', prms=['x', 'y', 'z']) def glVertex3hNV(x, y,",
"'x', 'y']) def glVertexAttrib2hNV(index, x, y): pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib2hvNV(index, v):",
"pass @params(api='gl', prms=['s', 't']) def glTexCoord2hNV(s, t): pass @params(api='gl', prms=['v']) def glTexCoord2hvNV(v): pass",
"prms=['weight']) def glVertexWeighthNV(weight): pass @params(api='gl', prms=['weight']) def glVertexWeighthvNV(weight): pass @params(api='gl', prms=['index', 'x']) def",
"glVertexAttrib3hNV(index, x, y, z): pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib3hvNV(index, v): pass @params(api='gl',",
"prms=['target', 's', 't']) def glMultiTexCoord2hNV(target, s, t): pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord2hvNV(target,",
"'v']) def glVertexAttribs2hvNV(index, n, v): pass @params(api='gl', prms=['index', 'n', 'v']) def glVertexAttribs3hvNV(index, n,",
"def glMultiTexCoord2hvNV(target, v): pass @params(api='gl', prms=['target', 's', 't', 'r']) def glMultiTexCoord3hNV(target, s, t,",
"def glTexCoord4hNV(s, t, r, q): pass @params(api='gl', prms=['v']) def glTexCoord4hvNV(v): pass @params(api='gl', prms=['target',",
"import params @params(api='gl', prms=['x', 'y']) def glVertex2hNV(x, y): pass @params(api='gl', prms=['v']) def glVertex2hvNV(v):",
"glVertex2hNV(x, y): pass @params(api='gl', prms=['v']) def glVertex2hvNV(v): pass @params(api='gl', prms=['x', 'y', 'z']) def",
"pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord2hvNV(target, v): pass @params(api='gl', prms=['target', 's', 't', 'r'])",
"@params(api='gl', prms=['index', 'v']) def glVertexAttrib4hvNV(index, v): pass @params(api='gl', prms=['index', 'n', 'v']) def glVertexAttribs1hvNV(index,",
"def glNormal3hNV(nx, ny, nz): pass @params(api='gl', prms=['v']) def glNormal3hvNV(v): pass @params(api='gl', prms=['red', 'green',",
"glVertexAttrib2hvNV(index, v): pass @params(api='gl', prms=['index', 'x', 'y', 'z']) def glVertexAttrib3hNV(index, x, y, z):",
"def glVertex4hNV(x, y, z, w): pass @params(api='gl', prms=['v']) def glVertex4hvNV(v): pass @params(api='gl', prms=['nx',",
"'t']) def glMultiTexCoord2hNV(target, s, t): pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord2hvNV(target, v): pass",
"prms=['index', 'v']) def glVertexAttrib1hvNV(index, v): pass @params(api='gl', prms=['index', 'x', 'y']) def glVertexAttrib2hNV(index, x,",
"@params(api='gl', prms=['index', 'v']) def glVertexAttrib2hvNV(index, v): pass @params(api='gl', prms=['index', 'x', 'y', 'z']) def",
"@params(api='gl', prms=['weight']) def glVertexWeighthvNV(weight): pass @params(api='gl', prms=['index', 'x']) def glVertexAttrib1hNV(index, x): pass @params(api='gl',",
"'t']) def glTexCoord2hNV(s, t): pass @params(api='gl', prms=['v']) def glTexCoord2hvNV(v): pass @params(api='gl', prms=['s', 't',",
"prms=['v']) def glNormal3hvNV(v): pass @params(api='gl', prms=['red', 'green', 'blue']) def glColor3hNV(red, green, blue): pass",
"prms=['target', 'v']) def glMultiTexCoord1hvNV(target, v): pass @params(api='gl', prms=['target', 's', 't']) def glMultiTexCoord2hNV(target, s,",
"'y']) def glVertex2hNV(x, y): pass @params(api='gl', prms=['v']) def glVertex2hvNV(v): pass @params(api='gl', prms=['x', 'y',",
"pass @params(api='gl', prms=['v']) def glVertex3hvNV(v): pass @params(api='gl', prms=['x', 'y', 'z', 'w']) def glVertex4hNV(x,",
"def glVertex3hNV(x, y, z): pass @params(api='gl', prms=['v']) def glVertex3hvNV(v): pass @params(api='gl', prms=['x', 'y',",
"glMultiTexCoord4hvNV(target, v): pass @params(api='gl', prms=['fog']) def glFogCoordhNV(fog): pass @params(api='gl', prms=['fog']) def glFogCoordhvNV(fog): pass",
"'q']) def glTexCoord4hNV(s, t, r, q): pass @params(api='gl', prms=['v']) def glTexCoord4hvNV(v): pass @params(api='gl',",
"pass @params(api='gl', prms=['index', 'n', 'v']) def glVertexAttribs3hvNV(index, n, v): pass @params(api='gl', prms=['index', 'n',",
"prms=['s', 't', 'r', 'q']) def glTexCoord4hNV(s, t, r, q): pass @params(api='gl', prms=['v']) def",
"prms=['index', 'n', 'v']) def glVertexAttribs1hvNV(index, n, v): pass @params(api='gl', prms=['index', 'n', 'v']) def",
"pass @params(api='gl', prms=['fog']) def glFogCoordhNV(fog): pass @params(api='gl', prms=['fog']) def glFogCoordhvNV(fog): pass @params(api='gl', prms=['red',",
"@params(api='gl', prms=['s']) def glTexCoord1hNV(s): pass @params(api='gl', prms=['v']) def glTexCoord1hvNV(v): pass @params(api='gl', prms=['s', 't'])",
"'green', 'blue', 'alpha']) def glColor4hNV(red, green, blue, alpha): pass @params(api='gl', prms=['v']) def glColor4hvNV(v):",
"@params(api='gl', prms=['x', 'y']) def glVertex2hNV(x, y): pass @params(api='gl', prms=['v']) def glVertex2hvNV(v): pass @params(api='gl',",
"'y', 'z']) def glVertex3hNV(x, y, z): pass @params(api='gl', prms=['v']) def glVertex3hvNV(v): pass @params(api='gl',",
"r, q): pass @params(api='gl', prms=['v']) def glTexCoord4hvNV(v): pass @params(api='gl', prms=['target', 's']) def glMultiTexCoord1hNV(target,",
"r, q): pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord4hvNV(target, v): pass @params(api='gl', prms=['fog']) def",
"prms=['v']) def glTexCoord4hvNV(v): pass @params(api='gl', prms=['target', 's']) def glMultiTexCoord1hNV(target, s): pass @params(api='gl', prms=['target',",
"@params(api='gl', prms=['weight']) def glVertexWeighthNV(weight): pass @params(api='gl', prms=['weight']) def glVertexWeighthvNV(weight): pass @params(api='gl', prms=['index', 'x'])",
"def glTexCoord2hNV(s, t): pass @params(api='gl', prms=['v']) def glTexCoord2hvNV(v): pass @params(api='gl', prms=['s', 't', 'r'])",
"'r', 'q']) def glMultiTexCoord4hNV(target, s, t, r, q): pass @params(api='gl', prms=['target', 'v']) def",
"def glVertexAttrib4hNV(index, x, y, z, w): pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib4hvNV(index, v):",
"glMultiTexCoord2hNV(target, s, t): pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord2hvNV(target, v): pass @params(api='gl', prms=['target',",
"pass @params(api='gl', prms=['v']) def glColor3hvNV(v): pass @params(api='gl', prms=['red', 'green', 'blue', 'alpha']) def glColor4hNV(red,",
"y, z): pass @params(api='gl', prms=['v']) def glVertex3hvNV(v): pass @params(api='gl', prms=['x', 'y', 'z', 'w'])",
"prms=['red', 'green', 'blue', 'alpha']) def glColor4hNV(red, green, blue, alpha): pass @params(api='gl', prms=['v']) def",
"from OpenGLCffi.GL import params @params(api='gl', prms=['x', 'y']) def glVertex2hNV(x, y): pass @params(api='gl', prms=['v'])",
"w): pass @params(api='gl', prms=['v']) def glVertex4hvNV(v): pass @params(api='gl', prms=['nx', 'ny', 'nz']) def glNormal3hNV(nx,",
"s): pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord1hvNV(target, v): pass @params(api='gl', prms=['target', 's', 't'])",
"prms=['index', 'n', 'v']) def glVertexAttribs3hvNV(index, n, v): pass @params(api='gl', prms=['index', 'n', 'v']) def",
"prms=['s']) def glTexCoord1hNV(s): pass @params(api='gl', prms=['v']) def glTexCoord1hvNV(v): pass @params(api='gl', prms=['s', 't']) def",
"'q']) def glMultiTexCoord4hNV(target, s, t, r, q): pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord4hvNV(target,",
"prms=['v']) def glVertex4hvNV(v): pass @params(api='gl', prms=['nx', 'ny', 'nz']) def glNormal3hNV(nx, ny, nz): pass",
"glTexCoord4hvNV(v): pass @params(api='gl', prms=['target', 's']) def glMultiTexCoord1hNV(target, s): pass @params(api='gl', prms=['target', 'v']) def",
"z, w): pass @params(api='gl', prms=['v']) def glVertex4hvNV(v): pass @params(api='gl', prms=['nx', 'ny', 'nz']) def",
"glVertexAttrib2hNV(index, x, y): pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib2hvNV(index, v): pass @params(api='gl', prms=['index',",
"pass @params(api='gl', prms=['weight']) def glVertexWeighthNV(weight): pass @params(api='gl', prms=['weight']) def glVertexWeighthvNV(weight): pass @params(api='gl', prms=['index',",
"green, blue): pass @params(api='gl', prms=['v']) def glColor3hvNV(v): pass @params(api='gl', prms=['red', 'green', 'blue', 'alpha'])",
"x): pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib1hvNV(index, v): pass @params(api='gl', prms=['index', 'x', 'y'])",
"@params(api='gl', prms=['index', 'v']) def glVertexAttrib3hvNV(index, v): pass @params(api='gl', prms=['index', 'x', 'y', 'z', 'w'])",
"prms=['index', 'x', 'y']) def glVertexAttrib2hNV(index, x, y): pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib2hvNV(index,",
"@params(api='gl', prms=['target', 'v']) def glMultiTexCoord1hvNV(target, v): pass @params(api='gl', prms=['target', 's', 't']) def glMultiTexCoord2hNV(target,",
"prms=['red', 'green', 'blue']) def glColor3hNV(red, green, blue): pass @params(api='gl', prms=['v']) def glColor3hvNV(v): pass",
"@params(api='gl', prms=['target', 's', 't', 'r', 'q']) def glMultiTexCoord4hNV(target, s, t, r, q): pass",
"glVertex2hvNV(v): pass @params(api='gl', prms=['x', 'y', 'z']) def glVertex3hNV(x, y, z): pass @params(api='gl', prms=['v'])",
"def glTexCoord1hvNV(v): pass @params(api='gl', prms=['s', 't']) def glTexCoord2hNV(s, t): pass @params(api='gl', prms=['v']) def",
"'z', 'w']) def glVertexAttrib4hNV(index, x, y, z, w): pass @params(api='gl', prms=['index', 'v']) def",
"'v']) def glVertexAttribs1hvNV(index, n, v): pass @params(api='gl', prms=['index', 'n', 'v']) def glVertexAttribs2hvNV(index, n,",
"'green', 'blue']) def glColor3hNV(red, green, blue): pass @params(api='gl', prms=['v']) def glColor3hvNV(v): pass @params(api='gl',",
"pass @params(api='gl', prms=['red', 'green', 'blue', 'alpha']) def glColor4hNV(red, green, blue, alpha): pass @params(api='gl',",
"glColor4hvNV(v): pass @params(api='gl', prms=['s']) def glTexCoord1hNV(s): pass @params(api='gl', prms=['v']) def glTexCoord1hvNV(v): pass @params(api='gl',",
"'x', 'y', 'z', 'w']) def glVertexAttrib4hNV(index, x, y, z, w): pass @params(api='gl', prms=['index',",
"'w']) def glVertexAttrib4hNV(index, x, y, z, w): pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib4hvNV(index,",
"'ny', 'nz']) def glNormal3hNV(nx, ny, nz): pass @params(api='gl', prms=['v']) def glNormal3hvNV(v): pass @params(api='gl',",
"prms=['index', 'x', 'y', 'z', 'w']) def glVertexAttrib4hNV(index, x, y, z, w): pass @params(api='gl',",
"pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord3hvNV(target, v): pass @params(api='gl', prms=['target', 's', 't', 'r',",
"'green', 'blue']) def glSecondaryColor3hNV(red, green, blue): pass @params(api='gl', prms=['v']) def glSecondaryColor3hvNV(v): pass @params(api='gl',",
"pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib3hvNV(index, v): pass @params(api='gl', prms=['index', 'x', 'y', 'z',",
"'t', 'r']) def glMultiTexCoord3hNV(target, s, t, r): pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord3hvNV(target,",
"v): pass @params(api='gl', prms=['index', 'x', 'y']) def glVertexAttrib2hNV(index, x, y): pass @params(api='gl', prms=['index',",
"@params(api='gl', prms=['red', 'green', 'blue']) def glSecondaryColor3hNV(red, green, blue): pass @params(api='gl', prms=['v']) def glSecondaryColor3hvNV(v):",
"prms=['index', 'x', 'y', 'z']) def glVertexAttrib3hNV(index, x, y, z): pass @params(api='gl', prms=['index', 'v'])",
"y): pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib2hvNV(index, v): pass @params(api='gl', prms=['index', 'x', 'y',",
"prms=['target', 's', 't', 'r', 'q']) def glMultiTexCoord4hNV(target, s, t, r, q): pass @params(api='gl',",
"def glFogCoordhNV(fog): pass @params(api='gl', prms=['fog']) def glFogCoordhvNV(fog): pass @params(api='gl', prms=['red', 'green', 'blue']) def",
"q): pass @params(api='gl', prms=['v']) def glTexCoord4hvNV(v): pass @params(api='gl', prms=['target', 's']) def glMultiTexCoord1hNV(target, s):",
"def glColor4hNV(red, green, blue, alpha): pass @params(api='gl', prms=['v']) def glColor4hvNV(v): pass @params(api='gl', prms=['s'])",
"glVertex4hNV(x, y, z, w): pass @params(api='gl', prms=['v']) def glVertex4hvNV(v): pass @params(api='gl', prms=['nx', 'ny',",
"'v']) def glMultiTexCoord2hvNV(target, v): pass @params(api='gl', prms=['target', 's', 't', 'r']) def glMultiTexCoord3hNV(target, s,",
"def glColor3hvNV(v): pass @params(api='gl', prms=['red', 'green', 'blue', 'alpha']) def glColor4hNV(red, green, blue, alpha):",
"pass @params(api='gl', prms=['v']) def glSecondaryColor3hvNV(v): pass @params(api='gl', prms=['weight']) def glVertexWeighthNV(weight): pass @params(api='gl', prms=['weight'])",
"prms=['index', 'v']) def glVertexAttrib2hvNV(index, v): pass @params(api='gl', prms=['index', 'x', 'y', 'z']) def glVertexAttrib3hNV(index,",
"@params(api='gl', prms=['x', 'y', 'z', 'w']) def glVertex4hNV(x, y, z, w): pass @params(api='gl', prms=['v'])",
"'blue']) def glColor3hNV(red, green, blue): pass @params(api='gl', prms=['v']) def glColor3hvNV(v): pass @params(api='gl', prms=['red',",
"glVertexAttrib4hvNV(index, v): pass @params(api='gl', prms=['index', 'n', 'v']) def glVertexAttribs1hvNV(index, n, v): pass @params(api='gl',",
"glMultiTexCoord1hNV(target, s): pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord1hvNV(target, v): pass @params(api='gl', prms=['target', 's',",
"prms=['nx', 'ny', 'nz']) def glNormal3hNV(nx, ny, nz): pass @params(api='gl', prms=['v']) def glNormal3hvNV(v): pass",
"r): pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord3hvNV(target, v): pass @params(api='gl', prms=['target', 's', 't',",
"glFogCoordhvNV(fog): pass @params(api='gl', prms=['red', 'green', 'blue']) def glSecondaryColor3hNV(red, green, blue): pass @params(api='gl', prms=['v'])",
"@params(api='gl', prms=['target', 's', 't', 'r']) def glMultiTexCoord3hNV(target, s, t, r): pass @params(api='gl', prms=['target',",
"v): pass @params(api='gl', prms=['target', 's', 't', 'r']) def glMultiTexCoord3hNV(target, s, t, r): pass",
"glVertexAttrib3hvNV(index, v): pass @params(api='gl', prms=['index', 'x', 'y', 'z', 'w']) def glVertexAttrib4hNV(index, x, y,",
"x, y, z): pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib3hvNV(index, v): pass @params(api='gl', prms=['index',",
"@params(api='gl', prms=['v']) def glVertex2hvNV(v): pass @params(api='gl', prms=['x', 'y', 'z']) def glVertex3hNV(x, y, z):",
"@params(api='gl', prms=['red', 'green', 'blue', 'alpha']) def glColor4hNV(red, green, blue, alpha): pass @params(api='gl', prms=['v'])",
"'s']) def glMultiTexCoord1hNV(target, s): pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord1hvNV(target, v): pass @params(api='gl',",
"pass @params(api='gl', prms=['weight']) def glVertexWeighthvNV(weight): pass @params(api='gl', prms=['index', 'x']) def glVertexAttrib1hNV(index, x): pass",
"pass @params(api='gl', prms=['index', 'x', 'y', 'z']) def glVertexAttrib3hNV(index, x, y, z): pass @params(api='gl',",
"n, v): pass @params(api='gl', prms=['index', 'n', 'v']) def glVertexAttribs3hvNV(index, n, v): pass @params(api='gl',",
"def glVertex2hNV(x, y): pass @params(api='gl', prms=['v']) def glVertex2hvNV(v): pass @params(api='gl', prms=['x', 'y', 'z'])",
"def glVertexAttrib2hNV(index, x, y): pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib2hvNV(index, v): pass @params(api='gl',",
"def glVertexAttrib2hvNV(index, v): pass @params(api='gl', prms=['index', 'x', 'y', 'z']) def glVertexAttrib3hNV(index, x, y,",
"prms=['x', 'y', 'z', 'w']) def glVertex4hNV(x, y, z, w): pass @params(api='gl', prms=['v']) def",
"prms=['index', 'v']) def glVertexAttrib4hvNV(index, v): pass @params(api='gl', prms=['index', 'n', 'v']) def glVertexAttribs1hvNV(index, n,",
"@params(api='gl', prms=['index', 'n', 'v']) def glVertexAttribs3hvNV(index, n, v): pass @params(api='gl', prms=['index', 'n', 'v'])",
"'n', 'v']) def glVertexAttribs1hvNV(index, n, v): pass @params(api='gl', prms=['index', 'n', 'v']) def glVertexAttribs2hvNV(index,",
"nz): pass @params(api='gl', prms=['v']) def glNormal3hvNV(v): pass @params(api='gl', prms=['red', 'green', 'blue']) def glColor3hNV(red,",
"q): pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord4hvNV(target, v): pass @params(api='gl', prms=['fog']) def glFogCoordhNV(fog):",
"'t', 'r', 'q']) def glMultiTexCoord4hNV(target, s, t, r, q): pass @params(api='gl', prms=['target', 'v'])",
"pass @params(api='gl', prms=['target', 's', 't']) def glMultiTexCoord2hNV(target, s, t): pass @params(api='gl', prms=['target', 'v'])",
"v): pass @params(api='gl', prms=['fog']) def glFogCoordhNV(fog): pass @params(api='gl', prms=['fog']) def glFogCoordhvNV(fog): pass @params(api='gl',",
"'r', 'q']) def glTexCoord4hNV(s, t, r, q): pass @params(api='gl', prms=['v']) def glTexCoord4hvNV(v): pass",
"v): pass @params(api='gl', prms=['index', 'x', 'y', 'z', 'w']) def glVertexAttrib4hNV(index, x, y, z,",
"def glTexCoord1hNV(s): pass @params(api='gl', prms=['v']) def glTexCoord1hvNV(v): pass @params(api='gl', prms=['s', 't']) def glTexCoord2hNV(s,",
"@params(api='gl', prms=['s', 't', 'r', 'q']) def glTexCoord4hNV(s, t, r, q): pass @params(api='gl', prms=['v'])",
"'w']) def glVertex4hNV(x, y, z, w): pass @params(api='gl', prms=['v']) def glVertex4hvNV(v): pass @params(api='gl',",
"s, t, r, q): pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord4hvNV(target, v): pass @params(api='gl',",
"glFogCoordhNV(fog): pass @params(api='gl', prms=['fog']) def glFogCoordhvNV(fog): pass @params(api='gl', prms=['red', 'green', 'blue']) def glSecondaryColor3hNV(red,",
"prms=['target', 'v']) def glMultiTexCoord3hvNV(target, v): pass @params(api='gl', prms=['target', 's', 't', 'r', 'q']) def",
"y): pass @params(api='gl', prms=['v']) def glVertex2hvNV(v): pass @params(api='gl', prms=['x', 'y', 'z']) def glVertex3hNV(x,",
"@params(api='gl', prms=['target', 'v']) def glMultiTexCoord3hvNV(target, v): pass @params(api='gl', prms=['target', 's', 't', 'r', 'q'])",
"glTexCoord1hNV(s): pass @params(api='gl', prms=['v']) def glTexCoord1hvNV(v): pass @params(api='gl', prms=['s', 't']) def glTexCoord2hNV(s, t):",
"prms=['v']) def glVertex3hvNV(v): pass @params(api='gl', prms=['x', 'y', 'z', 'w']) def glVertex4hNV(x, y, z,",
"prms=['fog']) def glFogCoordhvNV(fog): pass @params(api='gl', prms=['red', 'green', 'blue']) def glSecondaryColor3hNV(red, green, blue): pass",
"def glVertex3hvNV(v): pass @params(api='gl', prms=['x', 'y', 'z', 'w']) def glVertex4hNV(x, y, z, w):",
"def glTexCoord3hvNV(v): pass @params(api='gl', prms=['s', 't', 'r', 'q']) def glTexCoord4hNV(s, t, r, q):",
"def glNormal3hvNV(v): pass @params(api='gl', prms=['red', 'green', 'blue']) def glColor3hNV(red, green, blue): pass @params(api='gl',",
"@params(api='gl', prms=['s', 't']) def glTexCoord2hNV(s, t): pass @params(api='gl', prms=['v']) def glTexCoord2hvNV(v): pass @params(api='gl',",
"v): pass @params(api='gl', prms=['index', 'n', 'v']) def glVertexAttribs3hvNV(index, n, v): pass @params(api='gl', prms=['index',",
"pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib4hvNV(index, v): pass @params(api='gl', prms=['index', 'n', 'v']) def",
"pass @params(api='gl', prms=['v']) def glVertex4hvNV(v): pass @params(api='gl', prms=['nx', 'ny', 'nz']) def glNormal3hNV(nx, ny,",
"glVertexWeighthvNV(weight): pass @params(api='gl', prms=['index', 'x']) def glVertexAttrib1hNV(index, x): pass @params(api='gl', prms=['index', 'v']) def",
"'x']) def glVertexAttrib1hNV(index, x): pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib1hvNV(index, v): pass @params(api='gl',",
"@params(api='gl', prms=['target', 'v']) def glMultiTexCoord4hvNV(target, v): pass @params(api='gl', prms=['fog']) def glFogCoordhNV(fog): pass @params(api='gl',",
"glSecondaryColor3hvNV(v): pass @params(api='gl', prms=['weight']) def glVertexWeighthNV(weight): pass @params(api='gl', prms=['weight']) def glVertexWeighthvNV(weight): pass @params(api='gl',",
"pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib2hvNV(index, v): pass @params(api='gl', prms=['index', 'x', 'y', 'z'])",
"s, t, r): pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord3hvNV(target, v): pass @params(api='gl', prms=['target',",
"def glMultiTexCoord1hNV(target, s): pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord1hvNV(target, v): pass @params(api='gl', prms=['target',",
"t, r, q): pass @params(api='gl', prms=['v']) def glTexCoord4hvNV(v): pass @params(api='gl', prms=['target', 's']) def",
"glTexCoord3hNV(s, t, r): pass @params(api='gl', prms=['v']) def glTexCoord3hvNV(v): pass @params(api='gl', prms=['s', 't', 'r',",
"glMultiTexCoord1hvNV(target, v): pass @params(api='gl', prms=['target', 's', 't']) def glMultiTexCoord2hNV(target, s, t): pass @params(api='gl',",
"@params(api='gl', prms=['index', 'x', 'y', 'z']) def glVertexAttrib3hNV(index, x, y, z): pass @params(api='gl', prms=['index',",
"pass @params(api='gl', prms=['fog']) def glFogCoordhvNV(fog): pass @params(api='gl', prms=['red', 'green', 'blue']) def glSecondaryColor3hNV(red, green,",
"z): pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib3hvNV(index, v): pass @params(api='gl', prms=['index', 'x', 'y',",
"glVertexAttribs1hvNV(index, n, v): pass @params(api='gl', prms=['index', 'n', 'v']) def glVertexAttribs2hvNV(index, n, v): pass",
"pass @params(api='gl', prms=['x', 'y', 'z']) def glVertex3hNV(x, y, z): pass @params(api='gl', prms=['v']) def",
"glColor4hNV(red, green, blue, alpha): pass @params(api='gl', prms=['v']) def glColor4hvNV(v): pass @params(api='gl', prms=['s']) def",
"OpenGLCffi.GL import params @params(api='gl', prms=['x', 'y']) def glVertex2hNV(x, y): pass @params(api='gl', prms=['v']) def",
"def glMultiTexCoord3hNV(target, s, t, r): pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord3hvNV(target, v): pass",
"'v']) def glVertexAttrib2hvNV(index, v): pass @params(api='gl', prms=['index', 'x', 'y', 'z']) def glVertexAttrib3hNV(index, x,",
"pass @params(api='gl', prms=['v']) def glTexCoord2hvNV(v): pass @params(api='gl', prms=['s', 't', 'r']) def glTexCoord3hNV(s, t,",
"pass @params(api='gl', prms=['red', 'green', 'blue']) def glSecondaryColor3hNV(red, green, blue): pass @params(api='gl', prms=['v']) def",
"glVertexAttribs3hvNV(index, n, v): pass @params(api='gl', prms=['index', 'n', 'v']) def glVertexAttribs4hvNV(index, n, v): pass",
"pass @params(api='gl', prms=['v']) def glNormal3hvNV(v): pass @params(api='gl', prms=['red', 'green', 'blue']) def glColor3hNV(red, green,",
"prms=['s', 't', 'r']) def glTexCoord3hNV(s, t, r): pass @params(api='gl', prms=['v']) def glTexCoord3hvNV(v): pass",
"glTexCoord2hNV(s, t): pass @params(api='gl', prms=['v']) def glTexCoord2hvNV(v): pass @params(api='gl', prms=['s', 't', 'r']) def",
"x, y, z, w): pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib4hvNV(index, v): pass @params(api='gl',",
"def glMultiTexCoord3hvNV(target, v): pass @params(api='gl', prms=['target', 's', 't', 'r', 'q']) def glMultiTexCoord4hNV(target, s,",
"@params(api='gl', prms=['v']) def glNormal3hvNV(v): pass @params(api='gl', prms=['red', 'green', 'blue']) def glColor3hNV(red, green, blue):",
"def glMultiTexCoord4hNV(target, s, t, r, q): pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord4hvNV(target, v):",
"@params(api='gl', prms=['v']) def glSecondaryColor3hvNV(v): pass @params(api='gl', prms=['weight']) def glVertexWeighthNV(weight): pass @params(api='gl', prms=['weight']) def",
"y, z, w): pass @params(api='gl', prms=['v']) def glVertex4hvNV(v): pass @params(api='gl', prms=['nx', 'ny', 'nz'])",
"pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord1hvNV(target, v): pass @params(api='gl', prms=['target', 's', 't']) def",
"glTexCoord4hNV(s, t, r, q): pass @params(api='gl', prms=['v']) def glTexCoord4hvNV(v): pass @params(api='gl', prms=['target', 's'])",
"def glVertexAttribs1hvNV(index, n, v): pass @params(api='gl', prms=['index', 'n', 'v']) def glVertexAttribs2hvNV(index, n, v):",
"v): pass @params(api='gl', prms=['index', 'x', 'y', 'z']) def glVertexAttrib3hNV(index, x, y, z): pass",
"prms=['v']) def glTexCoord1hvNV(v): pass @params(api='gl', prms=['s', 't']) def glTexCoord2hNV(s, t): pass @params(api='gl', prms=['v'])",
"'s', 't']) def glMultiTexCoord2hNV(target, s, t): pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord2hvNV(target, v):",
"def glColor3hNV(red, green, blue): pass @params(api='gl', prms=['v']) def glColor3hvNV(v): pass @params(api='gl', prms=['red', 'green',",
"@params(api='gl', prms=['v']) def glTexCoord2hvNV(v): pass @params(api='gl', prms=['s', 't', 'r']) def glTexCoord3hNV(s, t, r):",
"alpha): pass @params(api='gl', prms=['v']) def glColor4hvNV(v): pass @params(api='gl', prms=['s']) def glTexCoord1hNV(s): pass @params(api='gl',",
"pass @params(api='gl', prms=['index', 'x', 'y']) def glVertexAttrib2hNV(index, x, y): pass @params(api='gl', prms=['index', 'v'])",
"'n', 'v']) def glVertexAttribs2hvNV(index, n, v): pass @params(api='gl', prms=['index', 'n', 'v']) def glVertexAttribs3hvNV(index,",
"def glVertexAttribs3hvNV(index, n, v): pass @params(api='gl', prms=['index', 'n', 'v']) def glVertexAttribs4hvNV(index, n, v):",
"'blue']) def glSecondaryColor3hNV(red, green, blue): pass @params(api='gl', prms=['v']) def glSecondaryColor3hvNV(v): pass @params(api='gl', prms=['weight'])",
"@params(api='gl', prms=['v']) def glColor3hvNV(v): pass @params(api='gl', prms=['red', 'green', 'blue', 'alpha']) def glColor4hNV(red, green,",
"pass @params(api='gl', prms=['target', 's']) def glMultiTexCoord1hNV(target, s): pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord1hvNV(target,",
"v): pass @params(api='gl', prms=['index', 'n', 'v']) def glVertexAttribs1hvNV(index, n, v): pass @params(api='gl', prms=['index',",
"@params(api='gl', prms=['x', 'y', 'z']) def glVertex3hNV(x, y, z): pass @params(api='gl', prms=['v']) def glVertex3hvNV(v):",
"v): pass @params(api='gl', prms=['target', 's', 't', 'r', 'q']) def glMultiTexCoord4hNV(target, s, t, r,",
"pass @params(api='gl', prms=['s', 't', 'r']) def glTexCoord3hNV(s, t, r): pass @params(api='gl', prms=['v']) def",
"'t', 'r', 'q']) def glTexCoord4hNV(s, t, r, q): pass @params(api='gl', prms=['v']) def glTexCoord4hvNV(v):",
"glVertexAttrib4hNV(index, x, y, z, w): pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib4hvNV(index, v): pass",
"glVertexWeighthNV(weight): pass @params(api='gl', prms=['weight']) def glVertexWeighthvNV(weight): pass @params(api='gl', prms=['index', 'x']) def glVertexAttrib1hNV(index, x):",
"pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib1hvNV(index, v): pass @params(api='gl', prms=['index', 'x', 'y']) def",
"v): pass @params(api='gl', prms=['target', 's', 't']) def glMultiTexCoord2hNV(target, s, t): pass @params(api='gl', prms=['target',",
"pass @params(api='gl', prms=['red', 'green', 'blue']) def glColor3hNV(red, green, blue): pass @params(api='gl', prms=['v']) def",
"pass @params(api='gl', prms=['target', 's', 't', 'r', 'q']) def glMultiTexCoord4hNV(target, s, t, r, q):",
"blue): pass @params(api='gl', prms=['v']) def glColor3hvNV(v): pass @params(api='gl', prms=['red', 'green', 'blue', 'alpha']) def",
"glTexCoord1hvNV(v): pass @params(api='gl', prms=['s', 't']) def glTexCoord2hNV(s, t): pass @params(api='gl', prms=['v']) def glTexCoord2hvNV(v):",
"def glSecondaryColor3hNV(red, green, blue): pass @params(api='gl', prms=['v']) def glSecondaryColor3hvNV(v): pass @params(api='gl', prms=['weight']) def",
"@params(api='gl', prms=['index', 'x', 'y', 'z', 'w']) def glVertexAttrib4hNV(index, x, y, z, w): pass",
"glColor3hvNV(v): pass @params(api='gl', prms=['red', 'green', 'blue', 'alpha']) def glColor4hNV(red, green, blue, alpha): pass",
"pass @params(api='gl', prms=['x', 'y', 'z', 'w']) def glVertex4hNV(x, y, z, w): pass @params(api='gl',",
"prms=['v']) def glSecondaryColor3hvNV(v): pass @params(api='gl', prms=['weight']) def glVertexWeighthNV(weight): pass @params(api='gl', prms=['weight']) def glVertexWeighthvNV(weight):",
"@params(api='gl', prms=['v']) def glColor4hvNV(v): pass @params(api='gl', prms=['s']) def glTexCoord1hNV(s): pass @params(api='gl', prms=['v']) def",
"t): pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord2hvNV(target, v): pass @params(api='gl', prms=['target', 's', 't',",
"@params(api='gl', prms=['v']) def glVertex4hvNV(v): pass @params(api='gl', prms=['nx', 'ny', 'nz']) def glNormal3hNV(nx, ny, nz):",
"'v']) def glVertexAttrib1hvNV(index, v): pass @params(api='gl', prms=['index', 'x', 'y']) def glVertexAttrib2hNV(index, x, y):",
"t, r, q): pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord4hvNV(target, v): pass @params(api='gl', prms=['fog'])",
"@params(api='gl', prms=['s', 't', 'r']) def glTexCoord3hNV(s, t, r): pass @params(api='gl', prms=['v']) def glTexCoord3hvNV(v):",
"prms=['v']) def glColor4hvNV(v): pass @params(api='gl', prms=['s']) def glTexCoord1hNV(s): pass @params(api='gl', prms=['v']) def glTexCoord1hvNV(v):",
"glVertexAttrib1hvNV(index, v): pass @params(api='gl', prms=['index', 'x', 'y']) def glVertexAttrib2hNV(index, x, y): pass @params(api='gl',",
"glVertex3hvNV(v): pass @params(api='gl', prms=['x', 'y', 'z', 'w']) def glVertex4hNV(x, y, z, w): pass",
"'t', 'r']) def glTexCoord3hNV(s, t, r): pass @params(api='gl', prms=['v']) def glTexCoord3hvNV(v): pass @params(api='gl',",
"glTexCoord3hvNV(v): pass @params(api='gl', prms=['s', 't', 'r', 'q']) def glTexCoord4hNV(s, t, r, q): pass",
"green, blue, alpha): pass @params(api='gl', prms=['v']) def glColor4hvNV(v): pass @params(api='gl', prms=['s']) def glTexCoord1hNV(s):",
"t, r): pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord3hvNV(target, v): pass @params(api='gl', prms=['target', 's',",
"@params(api='gl', prms=['index', 'n', 'v']) def glVertexAttribs1hvNV(index, n, v): pass @params(api='gl', prms=['index', 'n', 'v'])",
"def glVertexAttribs2hvNV(index, n, v): pass @params(api='gl', prms=['index', 'n', 'v']) def glVertexAttribs3hvNV(index, n, v):",
"prms=['red', 'green', 'blue']) def glSecondaryColor3hNV(red, green, blue): pass @params(api='gl', prms=['v']) def glSecondaryColor3hvNV(v): pass",
"prms=['index', 'n', 'v']) def glVertexAttribs2hvNV(index, n, v): pass @params(api='gl', prms=['index', 'n', 'v']) def",
"z): pass @params(api='gl', prms=['v']) def glVertex3hvNV(v): pass @params(api='gl', prms=['x', 'y', 'z', 'w']) def",
"pass @params(api='gl', prms=['nx', 'ny', 'nz']) def glNormal3hNV(nx, ny, nz): pass @params(api='gl', prms=['v']) def",
"'x', 'y', 'z']) def glVertexAttrib3hNV(index, x, y, z): pass @params(api='gl', prms=['index', 'v']) def",
"@params(api='gl', prms=['red', 'green', 'blue']) def glColor3hNV(red, green, blue): pass @params(api='gl', prms=['v']) def glColor3hvNV(v):",
"'v']) def glMultiTexCoord1hvNV(target, v): pass @params(api='gl', prms=['target', 's', 't']) def glMultiTexCoord2hNV(target, s, t):",
"def glVertexAttrib3hNV(index, x, y, z): pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib3hvNV(index, v): pass",
"prms=['target', 'v']) def glMultiTexCoord4hvNV(target, v): pass @params(api='gl', prms=['fog']) def glFogCoordhNV(fog): pass @params(api='gl', prms=['fog'])",
"prms=['x', 'y', 'z']) def glVertex3hNV(x, y, z): pass @params(api='gl', prms=['v']) def glVertex3hvNV(v): pass",
"t): pass @params(api='gl', prms=['v']) def glTexCoord2hvNV(v): pass @params(api='gl', prms=['s', 't', 'r']) def glTexCoord3hNV(s,",
"pass @params(api='gl', prms=['v']) def glTexCoord4hvNV(v): pass @params(api='gl', prms=['target', 's']) def glMultiTexCoord1hNV(target, s): pass",
"prms=['s', 't']) def glTexCoord2hNV(s, t): pass @params(api='gl', prms=['v']) def glTexCoord2hvNV(v): pass @params(api='gl', prms=['s',",
"def glMultiTexCoord4hvNV(target, v): pass @params(api='gl', prms=['fog']) def glFogCoordhNV(fog): pass @params(api='gl', prms=['fog']) def glFogCoordhvNV(fog):",
"prms=['v']) def glTexCoord3hvNV(v): pass @params(api='gl', prms=['s', 't', 'r', 'q']) def glTexCoord4hNV(s, t, r,",
"pass @params(api='gl', prms=['target', 's', 't', 'r']) def glMultiTexCoord3hNV(target, s, t, r): pass @params(api='gl',",
"'y', 'z', 'w']) def glVertexAttrib4hNV(index, x, y, z, w): pass @params(api='gl', prms=['index', 'v'])",
"@params(api='gl', prms=['v']) def glTexCoord3hvNV(v): pass @params(api='gl', prms=['s', 't', 'r', 'q']) def glTexCoord4hNV(s, t,",
"def glVertexWeighthNV(weight): pass @params(api='gl', prms=['weight']) def glVertexWeighthvNV(weight): pass @params(api='gl', prms=['index', 'x']) def glVertexAttrib1hNV(index,",
"w): pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib4hvNV(index, v): pass @params(api='gl', prms=['index', 'n', 'v'])",
"'v']) def glVertexAttribs3hvNV(index, n, v): pass @params(api='gl', prms=['index', 'n', 'v']) def glVertexAttribs4hvNV(index, n,",
"glNormal3hNV(nx, ny, nz): pass @params(api='gl', prms=['v']) def glNormal3hvNV(v): pass @params(api='gl', prms=['red', 'green', 'blue'])",
"blue): pass @params(api='gl', prms=['v']) def glSecondaryColor3hvNV(v): pass @params(api='gl', prms=['weight']) def glVertexWeighthNV(weight): pass @params(api='gl',",
"pass @params(api='gl', prms=['v']) def glTexCoord3hvNV(v): pass @params(api='gl', prms=['s', 't', 'r', 'q']) def glTexCoord4hNV(s,",
"'blue', 'alpha']) def glColor4hNV(red, green, blue, alpha): pass @params(api='gl', prms=['v']) def glColor4hvNV(v): pass",
"pass @params(api='gl', prms=['v']) def glColor4hvNV(v): pass @params(api='gl', prms=['s']) def glTexCoord1hNV(s): pass @params(api='gl', prms=['v'])",
"@params(api='gl', prms=['v']) def glTexCoord4hvNV(v): pass @params(api='gl', prms=['target', 's']) def glMultiTexCoord1hNV(target, s): pass @params(api='gl',",
"pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord4hvNV(target, v): pass @params(api='gl', prms=['fog']) def glFogCoordhNV(fog): pass",
"blue, alpha): pass @params(api='gl', prms=['v']) def glColor4hvNV(v): pass @params(api='gl', prms=['s']) def glTexCoord1hNV(s): pass",
"@params(api='gl', prms=['v']) def glTexCoord1hvNV(v): pass @params(api='gl', prms=['s', 't']) def glTexCoord2hNV(s, t): pass @params(api='gl',",
"params @params(api='gl', prms=['x', 'y']) def glVertex2hNV(x, y): pass @params(api='gl', prms=['v']) def glVertex2hvNV(v): pass",
"glVertexAttrib1hNV(index, x): pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib1hvNV(index, v): pass @params(api='gl', prms=['index', 'x',",
"@params(api='gl', prms=['index', 'x']) def glVertexAttrib1hNV(index, x): pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib1hvNV(index, v):",
"glMultiTexCoord3hvNV(target, v): pass @params(api='gl', prms=['target', 's', 't', 'r', 'q']) def glMultiTexCoord4hNV(target, s, t,",
"def glVertexAttrib4hvNV(index, v): pass @params(api='gl', prms=['index', 'n', 'v']) def glVertexAttribs1hvNV(index, n, v): pass",
"'alpha']) def glColor4hNV(red, green, blue, alpha): pass @params(api='gl', prms=['v']) def glColor4hvNV(v): pass @params(api='gl',",
"pass @params(api='gl', prms=['v']) def glTexCoord1hvNV(v): pass @params(api='gl', prms=['s', 't']) def glTexCoord2hNV(s, t): pass",
"@params(api='gl', prms=['fog']) def glFogCoordhvNV(fog): pass @params(api='gl', prms=['red', 'green', 'blue']) def glSecondaryColor3hNV(red, green, blue):",
"def glMultiTexCoord2hNV(target, s, t): pass @params(api='gl', prms=['target', 'v']) def glMultiTexCoord2hvNV(target, v): pass @params(api='gl',",
"@params(api='gl', prms=['index', 'n', 'v']) def glVertexAttribs2hvNV(index, n, v): pass @params(api='gl', prms=['index', 'n', 'v'])",
"'s', 't', 'r', 'q']) def glMultiTexCoord4hNV(target, s, t, r, q): pass @params(api='gl', prms=['target',",
"x, y): pass @params(api='gl', prms=['index', 'v']) def glVertexAttrib2hvNV(index, v): pass @params(api='gl', prms=['index', 'x',",
"prms=['target', 's', 't', 'r']) def glMultiTexCoord3hNV(target, s, t, r): pass @params(api='gl', prms=['target', 'v'])",
"def glSecondaryColor3hvNV(v): pass @params(api='gl', prms=['weight']) def glVertexWeighthNV(weight): pass @params(api='gl', prms=['weight']) def glVertexWeighthvNV(weight): pass",
"t, r): pass @params(api='gl', prms=['v']) def glTexCoord3hvNV(v): pass @params(api='gl', prms=['s', 't', 'r', 'q'])",
"def glVertexWeighthvNV(weight): pass @params(api='gl', prms=['index', 'x']) def glVertexAttrib1hNV(index, x): pass @params(api='gl', prms=['index', 'v'])"
] |
[
"from sklearn.model_selection import train_test_split # Import train_test_split function from sklearn import metrics #Import",
"y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1) # 70% training and 30% test",
"= File(file) name_of_image = \"Tree_of_\"+str(os.path.splitext(uploaded_file.name)[0]) + \".png\" name = fs.save(name_of_image, django_file) print(path_to_generated_image) context['image_name']",
"Import Decision Tree Classifier from sklearn.model_selection import train_test_split # Import train_test_split function from",
"os.path.abspath(os.path.join(os.getcwd(), os.pardir))+\"\\\\mining-assignment-master\\\\\"+ image_url file = open(path_to_generated_image , \"rb\") django_file = File(file) name_of_image =",
"django.shortcuts import render, redirect from django.views.generic import TemplateView, ListView, CreateView from django.core.files.storage import",
"CreateView from django.core.files.storage import FileSystemStorage from django.urls import reverse_lazy from django.core.files import File",
"= pydotplus.graph_from_dot_data(dot_data.getvalue()) graph.write_png(image_url) imge = Image(graph.create_png()) fs = FileSystemStorage() upload_file_name = uploaded_file path_to_generated_image",
"\".png\" dataset_cols_name = [] pima = pd.read_csv(uploaded_file , header=0) dataset_cols_name = pima.columns.values.tolist() transet_cols_name",
"pd.read_csv(uploaded_file , header=0) dataset_cols_name = pima.columns.values.tolist() transet_cols_name = dataset_cols_name[:len(dataset_cols_name)-1] transet_cols_name.append(\"decisionCol\") pima.columns = transet_cols_name",
"= [] pima = pd.read_csv(uploaded_file , header=0) dataset_cols_name = pima.columns.values.tolist() transet_cols_name = dataset_cols_name[:len(dataset_cols_name)-1]",
"os.pardir)) class Home(TemplateView): template_name = 'home.html' def upload(request): context = {} upload_file_name =",
"sklearn.model_selection import train_test_split # Import train_test_split function from sklearn import metrics #Import scikit-learn",
"File(file) name_of_image = \"Tree_of_\"+str(os.path.splitext(uploaded_file.name)[0]) + \".png\" name = fs.save(name_of_image, django_file) print(path_to_generated_image) context['image_name'] =",
"# Import train_test_split function from sklearn import metrics #Import scikit-learn metrics module for",
"metrics #Import scikit-learn metrics module for accuracy calculation from sklearn.tree import export_graphviz from",
"Decision Tree Classifer clf = clf.fit(X_train,y_train) #Predict the response for test dataset y_pred",
"print(\"Accuracy:\",metrics.accuracy_score(y_test, y_pred)) dot_data = StringIO() export_graphviz(clf, out_file=dot_data, filled=True, rounded=True, special_characters=True,feature_names = feature_cols,class_names=['0','1']) graph",
"= request.FILES['document'] image_url = \"Tree_of_\"+str(os.path.splitext(uploaded_file.name)[0]) + \".png\" dataset_cols_name = [] pima = pd.read_csv(uploaded_file",
"scikit-learn metrics module for accuracy calculation from sklearn.tree import export_graphviz from six import",
"metrics module for accuracy calculation from sklearn.tree import export_graphviz from six import StringIO",
"= pima[feature_cols] # Features y = pima.decisionCol # Target variable # Split dataset",
"# 70% training and 30% test # Create Decision Tree classifer object clf",
"= clf.predict(X_test) # Model Accuracy, how often is the classifier correct? print(\"Accuracy:\",metrics.accuracy_score(y_test, y_pred))",
"the classifier correct? print(\"Accuracy:\",metrics.accuracy_score(y_test, y_pred)) dot_data = StringIO() export_graphviz(clf, out_file=dot_data, filled=True, rounded=True, special_characters=True,feature_names",
"feature_cols,class_names=['0','1']) graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) graph.write_png(image_url) imge = Image(graph.create_png()) fs = FileSystemStorage() upload_file_name =",
"open(path_to_generated_image , \"rb\") django_file = File(file) name_of_image = \"Tree_of_\"+str(os.path.splitext(uploaded_file.name)[0]) + \".png\" name =",
"the response for test dataset y_pred = clf.predict(X_test) # Model Accuracy, how often",
"rounded=True, special_characters=True,feature_names = feature_cols,class_names=['0','1']) graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) graph.write_png(image_url) imge = Image(graph.create_png()) fs =",
"django.urls import reverse_lazy from django.core.files import File from .forms import BookForm from .models",
"import Image import os import pydotplus BASE_DIR = os.path.abspath(os.path.join(os.getcwd(), os.pardir)) class Home(TemplateView): template_name",
"# Target variable # Split dataset into training set and test set X_train,",
"test_size=0.3, random_state=1) # 70% training and 30% test # Create Decision Tree classifer",
"Tree Classifer clf = clf.fit(X_train,y_train) #Predict the response for test dataset y_pred =",
"# Load libraries import pandas as pd from sklearn.tree import DecisionTreeClassifier # Import",
"pandas as pd from sklearn.tree import DecisionTreeClassifier # Import Decision Tree Classifier from",
"DecisionTreeClassifier() # Train Decision Tree Classifer clf = clf.fit(X_train,y_train) #Predict the response for",
"= train_test_split(X, y, test_size=0.3, random_state=1) # 70% training and 30% test # Create",
"= dataset_cols_name[:len(dataset_cols_name)-1] transet_cols_name.append(\"decisionCol\") pima.columns = transet_cols_name #split dataset in features and target variable",
"upload(request): context = {} upload_file_name = \"\" image_url = \"\" if request.method ==",
"and test set X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1) #",
"in features and target variable feature_cols = transet_cols_name[:len(transet_cols_name)-1] X = pima[feature_cols] # Features",
"file = open(path_to_generated_image , \"rb\") django_file = File(file) name_of_image = \"Tree_of_\"+str(os.path.splitext(uploaded_file.name)[0]) + \".png\"",
"sklearn import metrics #Import scikit-learn metrics module for accuracy calculation from sklearn.tree import",
"y_pred = clf.predict(X_test) # Model Accuracy, how often is the classifier correct? print(\"Accuracy:\",metrics.accuracy_score(y_test,",
"FileSystemStorage from django.urls import reverse_lazy from django.core.files import File from .forms import BookForm",
"Image(graph.create_png()) fs = FileSystemStorage() upload_file_name = uploaded_file path_to_generated_image = os.path.abspath(os.path.join(os.getcwd(), os.pardir))+\"\\\\mining-assignment-master\\\\\"+ image_url file",
"accuracy calculation from sklearn.tree import export_graphviz from six import StringIO from IPython.display import",
"from django.urls import reverse_lazy from django.core.files import File from .forms import BookForm from",
"import FileSystemStorage from django.urls import reverse_lazy from django.core.files import File from .forms import",
"for test dataset y_pred = clf.predict(X_test) # Model Accuracy, how often is the",
", header=0) dataset_cols_name = pima.columns.values.tolist() transet_cols_name = dataset_cols_name[:len(dataset_cols_name)-1] transet_cols_name.append(\"decisionCol\") pima.columns = transet_cols_name #split",
"dataset_cols_name = [] pima = pd.read_csv(uploaded_file , header=0) dataset_cols_name = pima.columns.values.tolist() transet_cols_name =",
"six import StringIO from IPython.display import Image import os import pydotplus BASE_DIR =",
"os.path.abspath(os.path.join(os.getcwd(), os.pardir)) class Home(TemplateView): template_name = 'home.html' def upload(request): context = {} upload_file_name",
"= transet_cols_name #split dataset in features and target variable feature_cols = transet_cols_name[:len(transet_cols_name)-1] X",
"= \"\" image_url = \"\" if request.method == 'POST': uploaded_file = request.FILES['document'] image_url",
"from sklearn.tree import DecisionTreeClassifier # Import Decision Tree Classifier from sklearn.model_selection import train_test_split",
"Accuracy, how often is the classifier correct? print(\"Accuracy:\",metrics.accuracy_score(y_test, y_pred)) dot_data = StringIO() export_graphviz(clf,",
"Features y = pima.decisionCol # Target variable # Split dataset into training set",
"if request.method == 'POST': uploaded_file = request.FILES['document'] image_url = \"Tree_of_\"+str(os.path.splitext(uploaded_file.name)[0]) + \".png\" dataset_cols_name",
"feature_cols = transet_cols_name[:len(transet_cols_name)-1] X = pima[feature_cols] # Features y = pima.decisionCol # Target",
"= StringIO() export_graphviz(clf, out_file=dot_data, filled=True, rounded=True, special_characters=True,feature_names = feature_cols,class_names=['0','1']) graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) graph.write_png(image_url)",
"Tree Classifier from sklearn.model_selection import train_test_split # Import train_test_split function from sklearn import",
"import StringIO from IPython.display import Image import os import pydotplus BASE_DIR = os.path.abspath(os.path.join(os.getcwd(),",
", \"rb\") django_file = File(file) name_of_image = \"Tree_of_\"+str(os.path.splitext(uploaded_file.name)[0]) + \".png\" name = fs.save(name_of_image,",
"correct? print(\"Accuracy:\",metrics.accuracy_score(y_test, y_pred)) dot_data = StringIO() export_graphviz(clf, out_file=dot_data, filled=True, rounded=True, special_characters=True,feature_names = feature_cols,class_names=['0','1'])",
"StringIO() export_graphviz(clf, out_file=dot_data, filled=True, rounded=True, special_characters=True,feature_names = feature_cols,class_names=['0','1']) graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) graph.write_png(image_url) imge",
"= \"Tree_of_\"+str(os.path.splitext(uploaded_file.name)[0]) + \".png\" name = fs.save(name_of_image, django_file) print(path_to_generated_image) context['image_name'] = name_of_image return",
"X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1) # 70% training and 30%",
"dot_data = StringIO() export_graphviz(clf, out_file=dot_data, filled=True, rounded=True, special_characters=True,feature_names = feature_cols,class_names=['0','1']) graph = pydotplus.graph_from_dot_data(dot_data.getvalue())",
"test # Create Decision Tree classifer object clf = DecisionTreeClassifier() # Train Decision",
"y, test_size=0.3, random_state=1) # 70% training and 30% test # Create Decision Tree",
"Import train_test_split function from sklearn import metrics #Import scikit-learn metrics module for accuracy",
"dataset_cols_name = pima.columns.values.tolist() transet_cols_name = dataset_cols_name[:len(dataset_cols_name)-1] transet_cols_name.append(\"decisionCol\") pima.columns = transet_cols_name #split dataset in",
"File from .forms import BookForm from .models import Book # Load libraries import",
"transet_cols_name[:len(transet_cols_name)-1] X = pima[feature_cols] # Features y = pima.decisionCol # Target variable #",
"= {} upload_file_name = \"\" image_url = \"\" if request.method == 'POST': uploaded_file",
"object clf = DecisionTreeClassifier() # Train Decision Tree Classifer clf = clf.fit(X_train,y_train) #Predict",
"redirect from django.views.generic import TemplateView, ListView, CreateView from django.core.files.storage import FileSystemStorage from django.urls",
"special_characters=True,feature_names = feature_cols,class_names=['0','1']) graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) graph.write_png(image_url) imge = Image(graph.create_png()) fs = FileSystemStorage()",
"into training set and test set X_train, X_test, y_train, y_test = train_test_split(X, y,",
"#split dataset in features and target variable feature_cols = transet_cols_name[:len(transet_cols_name)-1] X = pima[feature_cols]",
"import train_test_split # Import train_test_split function from sklearn import metrics #Import scikit-learn metrics",
"classifier correct? print(\"Accuracy:\",metrics.accuracy_score(y_test, y_pred)) dot_data = StringIO() export_graphviz(clf, out_file=dot_data, filled=True, rounded=True, special_characters=True,feature_names =",
"test dataset y_pred = clf.predict(X_test) # Model Accuracy, how often is the classifier",
"70% training and 30% test # Create Decision Tree classifer object clf =",
"= \"Tree_of_\"+str(os.path.splitext(uploaded_file.name)[0]) + \".png\" dataset_cols_name = [] pima = pd.read_csv(uploaded_file , header=0) dataset_cols_name",
"# Import Decision Tree Classifier from sklearn.model_selection import train_test_split # Import train_test_split function",
"X = pima[feature_cols] # Features y = pima.decisionCol # Target variable # Split",
"from IPython.display import Image import os import pydotplus BASE_DIR = os.path.abspath(os.path.join(os.getcwd(), os.pardir)) class",
"variable # Split dataset into training set and test set X_train, X_test, y_train,",
"pima.columns.values.tolist() transet_cols_name = dataset_cols_name[:len(dataset_cols_name)-1] transet_cols_name.append(\"decisionCol\") pima.columns = transet_cols_name #split dataset in features and",
"upload_file_name = uploaded_file path_to_generated_image = os.path.abspath(os.path.join(os.getcwd(), os.pardir))+\"\\\\mining-assignment-master\\\\\"+ image_url file = open(path_to_generated_image , \"rb\")",
"\"Tree_of_\"+str(os.path.splitext(uploaded_file.name)[0]) + \".png\" name = fs.save(name_of_image, django_file) print(path_to_generated_image) context['image_name'] = name_of_image return render(request,",
"= uploaded_file path_to_generated_image = os.path.abspath(os.path.join(os.getcwd(), os.pardir))+\"\\\\mining-assignment-master\\\\\"+ image_url file = open(path_to_generated_image , \"rb\") django_file",
"transet_cols_name #split dataset in features and target variable feature_cols = transet_cols_name[:len(transet_cols_name)-1] X =",
"calculation from sklearn.tree import export_graphviz from six import StringIO from IPython.display import Image",
"#Predict the response for test dataset y_pred = clf.predict(X_test) # Model Accuracy, how",
"BASE_DIR = os.path.abspath(os.path.join(os.getcwd(), os.pardir)) class Home(TemplateView): template_name = 'home.html' def upload(request): context =",
"= 'home.html' def upload(request): context = {} upload_file_name = \"\" image_url = \"\"",
"Classifier from sklearn.model_selection import train_test_split # Import train_test_split function from sklearn import metrics",
"from .models import Book # Load libraries import pandas as pd from sklearn.tree",
"as pd from sklearn.tree import DecisionTreeClassifier # Import Decision Tree Classifier from sklearn.model_selection",
"Home(TemplateView): template_name = 'home.html' def upload(request): context = {} upload_file_name = \"\" image_url",
"export_graphviz from six import StringIO from IPython.display import Image import os import pydotplus",
"TemplateView, ListView, CreateView from django.core.files.storage import FileSystemStorage from django.urls import reverse_lazy from django.core.files",
"Split dataset into training set and test set X_train, X_test, y_train, y_test =",
"import metrics #Import scikit-learn metrics module for accuracy calculation from sklearn.tree import export_graphviz",
"IPython.display import Image import os import pydotplus BASE_DIR = os.path.abspath(os.path.join(os.getcwd(), os.pardir)) class Home(TemplateView):",
"imge = Image(graph.create_png()) fs = FileSystemStorage() upload_file_name = uploaded_file path_to_generated_image = os.path.abspath(os.path.join(os.getcwd(), os.pardir))+\"\\\\mining-assignment-master\\\\\"+",
"from django.views.generic import TemplateView, ListView, CreateView from django.core.files.storage import FileSystemStorage from django.urls import",
"\"\" image_url = \"\" if request.method == 'POST': uploaded_file = request.FILES['document'] image_url =",
"test set X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1) # 70%",
"30% test # Create Decision Tree classifer object clf = DecisionTreeClassifier() # Train",
".models import Book # Load libraries import pandas as pd from sklearn.tree import",
"clf = DecisionTreeClassifier() # Train Decision Tree Classifer clf = clf.fit(X_train,y_train) #Predict the",
"from django.core.files import File from .forms import BookForm from .models import Book #",
"often is the classifier correct? print(\"Accuracy:\",metrics.accuracy_score(y_test, y_pred)) dot_data = StringIO() export_graphviz(clf, out_file=dot_data, filled=True,",
"render, redirect from django.views.generic import TemplateView, ListView, CreateView from django.core.files.storage import FileSystemStorage from",
"is the classifier correct? print(\"Accuracy:\",metrics.accuracy_score(y_test, y_pred)) dot_data = StringIO() export_graphviz(clf, out_file=dot_data, filled=True, rounded=True,",
"django_file = File(file) name_of_image = \"Tree_of_\"+str(os.path.splitext(uploaded_file.name)[0]) + \".png\" name = fs.save(name_of_image, django_file) print(path_to_generated_image)",
"features and target variable feature_cols = transet_cols_name[:len(transet_cols_name)-1] X = pima[feature_cols] # Features y",
"pima.columns = transet_cols_name #split dataset in features and target variable feature_cols = transet_cols_name[:len(transet_cols_name)-1]",
"django.core.files import File from .forms import BookForm from .models import Book # Load",
"and target variable feature_cols = transet_cols_name[:len(transet_cols_name)-1] X = pima[feature_cols] # Features y =",
"target variable feature_cols = transet_cols_name[:len(transet_cols_name)-1] X = pima[feature_cols] # Features y = pima.decisionCol",
"sklearn.tree import export_graphviz from six import StringIO from IPython.display import Image import os",
"dataset_cols_name[:len(dataset_cols_name)-1] transet_cols_name.append(\"decisionCol\") pima.columns = transet_cols_name #split dataset in features and target variable feature_cols",
"def upload(request): context = {} upload_file_name = \"\" image_url = \"\" if request.method",
".forms import BookForm from .models import Book # Load libraries import pandas as",
"pydotplus BASE_DIR = os.path.abspath(os.path.join(os.getcwd(), os.pardir)) class Home(TemplateView): template_name = 'home.html' def upload(request): context",
"= \"\" if request.method == 'POST': uploaded_file = request.FILES['document'] image_url = \"Tree_of_\"+str(os.path.splitext(uploaded_file.name)[0]) +",
"from django.shortcuts import render, redirect from django.views.generic import TemplateView, ListView, CreateView from django.core.files.storage",
"set and test set X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)",
"Book # Load libraries import pandas as pd from sklearn.tree import DecisionTreeClassifier #",
"Tree classifer object clf = DecisionTreeClassifier() # Train Decision Tree Classifer clf =",
"import render, redirect from django.views.generic import TemplateView, ListView, CreateView from django.core.files.storage import FileSystemStorage",
"graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) graph.write_png(image_url) imge = Image(graph.create_png()) fs = FileSystemStorage() upload_file_name = uploaded_file",
"os import pydotplus BASE_DIR = os.path.abspath(os.path.join(os.getcwd(), os.pardir)) class Home(TemplateView): template_name = 'home.html' def",
"pd from sklearn.tree import DecisionTreeClassifier # Import Decision Tree Classifier from sklearn.model_selection import",
"and 30% test # Create Decision Tree classifer object clf = DecisionTreeClassifier() #",
"BookForm from .models import Book # Load libraries import pandas as pd from",
"= pima.columns.values.tolist() transet_cols_name = dataset_cols_name[:len(dataset_cols_name)-1] transet_cols_name.append(\"decisionCol\") pima.columns = transet_cols_name #split dataset in features",
"= pima.decisionCol # Target variable # Split dataset into training set and test",
"= clf.fit(X_train,y_train) #Predict the response for test dataset y_pred = clf.predict(X_test) # Model",
"{} upload_file_name = \"\" image_url = \"\" if request.method == 'POST': uploaded_file =",
"# Create Decision Tree classifer object clf = DecisionTreeClassifier() # Train Decision Tree",
"random_state=1) # 70% training and 30% test # Create Decision Tree classifer object",
"path_to_generated_image = os.path.abspath(os.path.join(os.getcwd(), os.pardir))+\"\\\\mining-assignment-master\\\\\"+ image_url file = open(path_to_generated_image , \"rb\") django_file = File(file)",
"request.FILES['document'] image_url = \"Tree_of_\"+str(os.path.splitext(uploaded_file.name)[0]) + \".png\" dataset_cols_name = [] pima = pd.read_csv(uploaded_file ,",
"= transet_cols_name[:len(transet_cols_name)-1] X = pima[feature_cols] # Features y = pima.decisionCol # Target variable",
"'POST': uploaded_file = request.FILES['document'] image_url = \"Tree_of_\"+str(os.path.splitext(uploaded_file.name)[0]) + \".png\" dataset_cols_name = [] pima",
"graph.write_png(image_url) imge = Image(graph.create_png()) fs = FileSystemStorage() upload_file_name = uploaded_file path_to_generated_image = os.path.abspath(os.path.join(os.getcwd(),",
"import BookForm from .models import Book # Load libraries import pandas as pd",
"module for accuracy calculation from sklearn.tree import export_graphviz from six import StringIO from",
"classifer object clf = DecisionTreeClassifier() # Train Decision Tree Classifer clf = clf.fit(X_train,y_train)",
"# Features y = pima.decisionCol # Target variable # Split dataset into training",
"train_test_split # Import train_test_split function from sklearn import metrics #Import scikit-learn metrics module",
"training set and test set X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,",
"how often is the classifier correct? print(\"Accuracy:\",metrics.accuracy_score(y_test, y_pred)) dot_data = StringIO() export_graphviz(clf, out_file=dot_data,",
"function from sklearn import metrics #Import scikit-learn metrics module for accuracy calculation from",
"dataset in features and target variable feature_cols = transet_cols_name[:len(transet_cols_name)-1] X = pima[feature_cols] #",
"[] pima = pd.read_csv(uploaded_file , header=0) dataset_cols_name = pima.columns.values.tolist() transet_cols_name = dataset_cols_name[:len(dataset_cols_name)-1] transet_cols_name.append(\"decisionCol\")",
"request.method == 'POST': uploaded_file = request.FILES['document'] image_url = \"Tree_of_\"+str(os.path.splitext(uploaded_file.name)[0]) + \".png\" dataset_cols_name =",
"from sklearn.tree import export_graphviz from six import StringIO from IPython.display import Image import",
"= pd.read_csv(uploaded_file , header=0) dataset_cols_name = pima.columns.values.tolist() transet_cols_name = dataset_cols_name[:len(dataset_cols_name)-1] transet_cols_name.append(\"decisionCol\") pima.columns =",
"Load libraries import pandas as pd from sklearn.tree import DecisionTreeClassifier # Import Decision",
"training and 30% test # Create Decision Tree classifer object clf = DecisionTreeClassifier()",
"response for test dataset y_pred = clf.predict(X_test) # Model Accuracy, how often is",
"clf.predict(X_test) # Model Accuracy, how often is the classifier correct? print(\"Accuracy:\",metrics.accuracy_score(y_test, y_pred)) dot_data",
"= FileSystemStorage() upload_file_name = uploaded_file path_to_generated_image = os.path.abspath(os.path.join(os.getcwd(), os.pardir))+\"\\\\mining-assignment-master\\\\\"+ image_url file = open(path_to_generated_image",
"\".png\" name = fs.save(name_of_image, django_file) print(path_to_generated_image) context['image_name'] = name_of_image return render(request, 'upload.html', context)",
"dataset into training set and test set X_train, X_test, y_train, y_test = train_test_split(X,",
"Decision Tree Classifier from sklearn.model_selection import train_test_split # Import train_test_split function from sklearn",
"DecisionTreeClassifier # Import Decision Tree Classifier from sklearn.model_selection import train_test_split # Import train_test_split",
"image_url file = open(path_to_generated_image , \"rb\") django_file = File(file) name_of_image = \"Tree_of_\"+str(os.path.splitext(uploaded_file.name)[0]) +",
"Decision Tree classifer object clf = DecisionTreeClassifier() # Train Decision Tree Classifer clf",
"+ \".png\" name = fs.save(name_of_image, django_file) print(path_to_generated_image) context['image_name'] = name_of_image return render(request, 'upload.html',",
"import DecisionTreeClassifier # Import Decision Tree Classifier from sklearn.model_selection import train_test_split # Import",
"= feature_cols,class_names=['0','1']) graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) graph.write_png(image_url) imge = Image(graph.create_png()) fs = FileSystemStorage() upload_file_name",
"image_url = \"\" if request.method == 'POST': uploaded_file = request.FILES['document'] image_url = \"Tree_of_\"+str(os.path.splitext(uploaded_file.name)[0])",
"y_test = train_test_split(X, y, test_size=0.3, random_state=1) # 70% training and 30% test #",
"os.pardir))+\"\\\\mining-assignment-master\\\\\"+ image_url file = open(path_to_generated_image , \"rb\") django_file = File(file) name_of_image = \"Tree_of_\"+str(os.path.splitext(uploaded_file.name)[0])",
"from six import StringIO from IPython.display import Image import os import pydotplus BASE_DIR",
"train_test_split(X, y, test_size=0.3, random_state=1) # 70% training and 30% test # Create Decision",
"transet_cols_name.append(\"decisionCol\") pima.columns = transet_cols_name #split dataset in features and target variable feature_cols =",
"\"\" if request.method == 'POST': uploaded_file = request.FILES['document'] image_url = \"Tree_of_\"+str(os.path.splitext(uploaded_file.name)[0]) + \".png\"",
"y_pred)) dot_data = StringIO() export_graphviz(clf, out_file=dot_data, filled=True, rounded=True, special_characters=True,feature_names = feature_cols,class_names=['0','1']) graph =",
"from .forms import BookForm from .models import Book # Load libraries import pandas",
"class Home(TemplateView): template_name = 'home.html' def upload(request): context = {} upload_file_name = \"\"",
"dataset y_pred = clf.predict(X_test) # Model Accuracy, how often is the classifier correct?",
"pima.decisionCol # Target variable # Split dataset into training set and test set",
"'home.html' def upload(request): context = {} upload_file_name = \"\" image_url = \"\" if",
"\"rb\") django_file = File(file) name_of_image = \"Tree_of_\"+str(os.path.splitext(uploaded_file.name)[0]) + \".png\" name = fs.save(name_of_image, django_file)",
"from sklearn import metrics #Import scikit-learn metrics module for accuracy calculation from sklearn.tree",
"name_of_image = \"Tree_of_\"+str(os.path.splitext(uploaded_file.name)[0]) + \".png\" name = fs.save(name_of_image, django_file) print(path_to_generated_image) context['image_name'] = name_of_image",
"Create Decision Tree classifer object clf = DecisionTreeClassifier() # Train Decision Tree Classifer",
"# Split dataset into training set and test set X_train, X_test, y_train, y_test",
"import reverse_lazy from django.core.files import File from .forms import BookForm from .models import",
"+ \".png\" dataset_cols_name = [] pima = pd.read_csv(uploaded_file , header=0) dataset_cols_name = pima.columns.values.tolist()",
"set X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1) # 70% training",
"y = pima.decisionCol # Target variable # Split dataset into training set and",
"export_graphviz(clf, out_file=dot_data, filled=True, rounded=True, special_characters=True,feature_names = feature_cols,class_names=['0','1']) graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) graph.write_png(image_url) imge =",
"\"Tree_of_\"+str(os.path.splitext(uploaded_file.name)[0]) + \".png\" dataset_cols_name = [] pima = pd.read_csv(uploaded_file , header=0) dataset_cols_name =",
"= open(path_to_generated_image , \"rb\") django_file = File(file) name_of_image = \"Tree_of_\"+str(os.path.splitext(uploaded_file.name)[0]) + \".png\" name",
"import Book # Load libraries import pandas as pd from sklearn.tree import DecisionTreeClassifier",
"Train Decision Tree Classifer clf = clf.fit(X_train,y_train) #Predict the response for test dataset",
"Image import os import pydotplus BASE_DIR = os.path.abspath(os.path.join(os.getcwd(), os.pardir)) class Home(TemplateView): template_name =",
"from django.core.files.storage import FileSystemStorage from django.urls import reverse_lazy from django.core.files import File from",
"django.core.files.storage import FileSystemStorage from django.urls import reverse_lazy from django.core.files import File from .forms",
"image_url = \"Tree_of_\"+str(os.path.splitext(uploaded_file.name)[0]) + \".png\" dataset_cols_name = [] pima = pd.read_csv(uploaded_file , header=0)",
"uploaded_file path_to_generated_image = os.path.abspath(os.path.join(os.getcwd(), os.pardir))+\"\\\\mining-assignment-master\\\\\"+ image_url file = open(path_to_generated_image , \"rb\") django_file =",
"FileSystemStorage() upload_file_name = uploaded_file path_to_generated_image = os.path.abspath(os.path.join(os.getcwd(), os.pardir))+\"\\\\mining-assignment-master\\\\\"+ image_url file = open(path_to_generated_image ,",
"train_test_split function from sklearn import metrics #Import scikit-learn metrics module for accuracy calculation",
"import os import pydotplus BASE_DIR = os.path.abspath(os.path.join(os.getcwd(), os.pardir)) class Home(TemplateView): template_name = 'home.html'",
"import export_graphviz from six import StringIO from IPython.display import Image import os import",
"== 'POST': uploaded_file = request.FILES['document'] image_url = \"Tree_of_\"+str(os.path.splitext(uploaded_file.name)[0]) + \".png\" dataset_cols_name = []",
"# Train Decision Tree Classifer clf = clf.fit(X_train,y_train) #Predict the response for test",
"import TemplateView, ListView, CreateView from django.core.files.storage import FileSystemStorage from django.urls import reverse_lazy from",
"uploaded_file = request.FILES['document'] image_url = \"Tree_of_\"+str(os.path.splitext(uploaded_file.name)[0]) + \".png\" dataset_cols_name = [] pima =",
"import pandas as pd from sklearn.tree import DecisionTreeClassifier # Import Decision Tree Classifier",
"fs = FileSystemStorage() upload_file_name = uploaded_file path_to_generated_image = os.path.abspath(os.path.join(os.getcwd(), os.pardir))+\"\\\\mining-assignment-master\\\\\"+ image_url file =",
"filled=True, rounded=True, special_characters=True,feature_names = feature_cols,class_names=['0','1']) graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) graph.write_png(image_url) imge = Image(graph.create_png()) fs",
"pima[feature_cols] # Features y = pima.decisionCol # Target variable # Split dataset into",
"clf = clf.fit(X_train,y_train) #Predict the response for test dataset y_pred = clf.predict(X_test) #",
"import pydotplus BASE_DIR = os.path.abspath(os.path.join(os.getcwd(), os.pardir)) class Home(TemplateView): template_name = 'home.html' def upload(request):",
"header=0) dataset_cols_name = pima.columns.values.tolist() transet_cols_name = dataset_cols_name[:len(dataset_cols_name)-1] transet_cols_name.append(\"decisionCol\") pima.columns = transet_cols_name #split dataset",
"ListView, CreateView from django.core.files.storage import FileSystemStorage from django.urls import reverse_lazy from django.core.files import",
"# Model Accuracy, how often is the classifier correct? print(\"Accuracy:\",metrics.accuracy_score(y_test, y_pred)) dot_data =",
"reverse_lazy from django.core.files import File from .forms import BookForm from .models import Book",
"template_name = 'home.html' def upload(request): context = {} upload_file_name = \"\" image_url =",
"Target variable # Split dataset into training set and test set X_train, X_test,",
"Model Accuracy, how often is the classifier correct? print(\"Accuracy:\",metrics.accuracy_score(y_test, y_pred)) dot_data = StringIO()",
"transet_cols_name = dataset_cols_name[:len(dataset_cols_name)-1] transet_cols_name.append(\"decisionCol\") pima.columns = transet_cols_name #split dataset in features and target",
"clf.fit(X_train,y_train) #Predict the response for test dataset y_pred = clf.predict(X_test) # Model Accuracy,",
"sklearn.tree import DecisionTreeClassifier # Import Decision Tree Classifier from sklearn.model_selection import train_test_split #",
"out_file=dot_data, filled=True, rounded=True, special_characters=True,feature_names = feature_cols,class_names=['0','1']) graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) graph.write_png(image_url) imge = Image(graph.create_png())",
"pydotplus.graph_from_dot_data(dot_data.getvalue()) graph.write_png(image_url) imge = Image(graph.create_png()) fs = FileSystemStorage() upload_file_name = uploaded_file path_to_generated_image =",
"for accuracy calculation from sklearn.tree import export_graphviz from six import StringIO from IPython.display",
"= os.path.abspath(os.path.join(os.getcwd(), os.pardir)) class Home(TemplateView): template_name = 'home.html' def upload(request): context = {}",
"django.views.generic import TemplateView, ListView, CreateView from django.core.files.storage import FileSystemStorage from django.urls import reverse_lazy",
"= os.path.abspath(os.path.join(os.getcwd(), os.pardir))+\"\\\\mining-assignment-master\\\\\"+ image_url file = open(path_to_generated_image , \"rb\") django_file = File(file) name_of_image",
"context = {} upload_file_name = \"\" image_url = \"\" if request.method == 'POST':",
"= DecisionTreeClassifier() # Train Decision Tree Classifer clf = clf.fit(X_train,y_train) #Predict the response",
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1) # 70% training and",
"libraries import pandas as pd from sklearn.tree import DecisionTreeClassifier # Import Decision Tree",
"variable feature_cols = transet_cols_name[:len(transet_cols_name)-1] X = pima[feature_cols] # Features y = pima.decisionCol #",
"= Image(graph.create_png()) fs = FileSystemStorage() upload_file_name = uploaded_file path_to_generated_image = os.path.abspath(os.path.join(os.getcwd(), os.pardir))+\"\\\\mining-assignment-master\\\\\"+ image_url",
"import File from .forms import BookForm from .models import Book # Load libraries",
"#Import scikit-learn metrics module for accuracy calculation from sklearn.tree import export_graphviz from six",
"Classifer clf = clf.fit(X_train,y_train) #Predict the response for test dataset y_pred = clf.predict(X_test)",
"upload_file_name = \"\" image_url = \"\" if request.method == 'POST': uploaded_file = request.FILES['document']",
"pima = pd.read_csv(uploaded_file , header=0) dataset_cols_name = pima.columns.values.tolist() transet_cols_name = dataset_cols_name[:len(dataset_cols_name)-1] transet_cols_name.append(\"decisionCol\") pima.columns",
"StringIO from IPython.display import Image import os import pydotplus BASE_DIR = os.path.abspath(os.path.join(os.getcwd(), os.pardir))"
] |
[
"as sp form = cgi.FieldStorage() user_name = form.getvalue('user_name') lv_size = form.getvalue('lv_size') print(user_name) print(lv_size)",
"= cgi.FieldStorage() user_name = form.getvalue('user_name') lv_size = form.getvalue('lv_size') print(user_name) print(lv_size) output=sp.getstatusoutput(\"sudo ansible-playbook ostaas.yml",
": print(\"<b> NFS-server succesfully created</b>\") client_mount=sp.getstatusoutput(\"sudo ansible-playbook ostaasclient.yml --extra-vars='user_name={u} lv_size={l}'\".format(u=user_name, l=lv_size)) if client_mount[0]",
"cloud storage..</b>\") else: print(\"Sorry, We're facing technical issue. please visit after some time\")",
"import subprocess as sp form = cgi.FieldStorage() user_name = form.getvalue('user_name') lv_size = form.getvalue('lv_size')",
"ansible-playbook ostaasclient.yml --extra-vars='user_name={u} lv_size={l}'\".format(u=user_name, l=lv_size)) if client_mount[0] == 0 : print(\"<b>Enjoy free cloud",
"--extra-vars='user_name={u} lv_size={l}'\".format(u=user_name, l=lv_size)) if output[0] == 0 : print(\"<b> NFS-server succesfully created</b>\") client_mount=sp.getstatusoutput(\"sudo",
"sp form = cgi.FieldStorage() user_name = form.getvalue('user_name') lv_size = form.getvalue('lv_size') print(user_name) print(lv_size) output=sp.getstatusoutput(\"sudo",
"free cloud storage..</b>\") else: print(\"Sorry, We're facing technical issue. please visit after some",
"created</b>\") client_mount=sp.getstatusoutput(\"sudo ansible-playbook ostaasclient.yml --extra-vars='user_name={u} lv_size={l}'\".format(u=user_name, l=lv_size)) if client_mount[0] == 0 : print(\"<b>Enjoy",
"= form.getvalue('user_name') lv_size = form.getvalue('lv_size') print(user_name) print(lv_size) output=sp.getstatusoutput(\"sudo ansible-playbook ostaas.yml --extra-vars='user_name={u} lv_size={l}'\".format(u=user_name, l=lv_size))",
"l=lv_size)) if client_mount[0] == 0 : print(\"<b>Enjoy free cloud storage..</b>\") else: print(\"Sorry, We're",
"print(user_name) print(lv_size) output=sp.getstatusoutput(\"sudo ansible-playbook ostaas.yml --extra-vars='user_name={u} lv_size={l}'\".format(u=user_name, l=lv_size)) if output[0] == 0 :",
"succesfully created</b>\") client_mount=sp.getstatusoutput(\"sudo ansible-playbook ostaasclient.yml --extra-vars='user_name={u} lv_size={l}'\".format(u=user_name, l=lv_size)) if client_mount[0] == 0 :",
"ansible-playbook ostaas.yml --extra-vars='user_name={u} lv_size={l}'\".format(u=user_name, l=lv_size)) if output[0] == 0 : print(\"<b> NFS-server succesfully",
"subprocess as sp form = cgi.FieldStorage() user_name = form.getvalue('user_name') lv_size = form.getvalue('lv_size') print(user_name)",
"import cgi import subprocess as sp form = cgi.FieldStorage() user_name = form.getvalue('user_name') lv_size",
"ostaas.yml --extra-vars='user_name={u} lv_size={l}'\".format(u=user_name, l=lv_size)) if output[0] == 0 : print(\"<b> NFS-server succesfully created</b>\")",
"0 : print(\"<b>Enjoy free cloud storage..</b>\") else: print(\"Sorry, We're facing technical issue. please",
"form = cgi.FieldStorage() user_name = form.getvalue('user_name') lv_size = form.getvalue('lv_size') print(user_name) print(lv_size) output=sp.getstatusoutput(\"sudo ansible-playbook",
"print(lv_size) output=sp.getstatusoutput(\"sudo ansible-playbook ostaas.yml --extra-vars='user_name={u} lv_size={l}'\".format(u=user_name, l=lv_size)) if output[0] == 0 : print(\"<b>",
"0 : print(\"<b> NFS-server succesfully created</b>\") client_mount=sp.getstatusoutput(\"sudo ansible-playbook ostaasclient.yml --extra-vars='user_name={u} lv_size={l}'\".format(u=user_name, l=lv_size)) if",
"ostaasclient.yml --extra-vars='user_name={u} lv_size={l}'\".format(u=user_name, l=lv_size)) if client_mount[0] == 0 : print(\"<b>Enjoy free cloud storage..</b>\")",
"print(\"content-type: text/html\") print(\"\") import cgi import subprocess as sp form = cgi.FieldStorage() user_name",
"user_name = form.getvalue('user_name') lv_size = form.getvalue('lv_size') print(user_name) print(lv_size) output=sp.getstatusoutput(\"sudo ansible-playbook ostaas.yml --extra-vars='user_name={u} lv_size={l}'\".format(u=user_name,",
"output[0] == 0 : print(\"<b> NFS-server succesfully created</b>\") client_mount=sp.getstatusoutput(\"sudo ansible-playbook ostaasclient.yml --extra-vars='user_name={u} lv_size={l}'\".format(u=user_name,",
"== 0 : print(\"<b> NFS-server succesfully created</b>\") client_mount=sp.getstatusoutput(\"sudo ansible-playbook ostaasclient.yml --extra-vars='user_name={u} lv_size={l}'\".format(u=user_name, l=lv_size))",
"print(\"<b>Enjoy free cloud storage..</b>\") else: print(\"Sorry, We're facing technical issue. please visit after",
"output=sp.getstatusoutput(\"sudo ansible-playbook ostaas.yml --extra-vars='user_name={u} lv_size={l}'\".format(u=user_name, l=lv_size)) if output[0] == 0 : print(\"<b> NFS-server",
"form.getvalue('user_name') lv_size = form.getvalue('lv_size') print(user_name) print(lv_size) output=sp.getstatusoutput(\"sudo ansible-playbook ostaas.yml --extra-vars='user_name={u} lv_size={l}'\".format(u=user_name, l=lv_size)) if",
"if client_mount[0] == 0 : print(\"<b>Enjoy free cloud storage..</b>\") else: print(\"Sorry, We're facing",
"client_mount[0] == 0 : print(\"<b>Enjoy free cloud storage..</b>\") else: print(\"Sorry, We're facing technical",
"#!/usr/bin/python36 print(\"content-type: text/html\") print(\"\") import cgi import subprocess as sp form = cgi.FieldStorage()",
": print(\"<b>Enjoy free cloud storage..</b>\") else: print(\"Sorry, We're facing technical issue. please visit",
"lv_size = form.getvalue('lv_size') print(user_name) print(lv_size) output=sp.getstatusoutput(\"sudo ansible-playbook ostaas.yml --extra-vars='user_name={u} lv_size={l}'\".format(u=user_name, l=lv_size)) if output[0]",
"lv_size={l}'\".format(u=user_name, l=lv_size)) if client_mount[0] == 0 : print(\"<b>Enjoy free cloud storage..</b>\") else: print(\"Sorry,",
"lv_size={l}'\".format(u=user_name, l=lv_size)) if output[0] == 0 : print(\"<b> NFS-server succesfully created</b>\") client_mount=sp.getstatusoutput(\"sudo ansible-playbook",
"l=lv_size)) if output[0] == 0 : print(\"<b> NFS-server succesfully created</b>\") client_mount=sp.getstatusoutput(\"sudo ansible-playbook ostaasclient.yml",
"cgi.FieldStorage() user_name = form.getvalue('user_name') lv_size = form.getvalue('lv_size') print(user_name) print(lv_size) output=sp.getstatusoutput(\"sudo ansible-playbook ostaas.yml --extra-vars='user_name={u}",
"print(\"\") import cgi import subprocess as sp form = cgi.FieldStorage() user_name = form.getvalue('user_name')",
"NFS-server succesfully created</b>\") client_mount=sp.getstatusoutput(\"sudo ansible-playbook ostaasclient.yml --extra-vars='user_name={u} lv_size={l}'\".format(u=user_name, l=lv_size)) if client_mount[0] == 0",
"== 0 : print(\"<b>Enjoy free cloud storage..</b>\") else: print(\"Sorry, We're facing technical issue.",
"text/html\") print(\"\") import cgi import subprocess as sp form = cgi.FieldStorage() user_name =",
"client_mount=sp.getstatusoutput(\"sudo ansible-playbook ostaasclient.yml --extra-vars='user_name={u} lv_size={l}'\".format(u=user_name, l=lv_size)) if client_mount[0] == 0 : print(\"<b>Enjoy free",
"print(\"<b> NFS-server succesfully created</b>\") client_mount=sp.getstatusoutput(\"sudo ansible-playbook ostaasclient.yml --extra-vars='user_name={u} lv_size={l}'\".format(u=user_name, l=lv_size)) if client_mount[0] ==",
"--extra-vars='user_name={u} lv_size={l}'\".format(u=user_name, l=lv_size)) if client_mount[0] == 0 : print(\"<b>Enjoy free cloud storage..</b>\") else:",
"if output[0] == 0 : print(\"<b> NFS-server succesfully created</b>\") client_mount=sp.getstatusoutput(\"sudo ansible-playbook ostaasclient.yml --extra-vars='user_name={u}",
"= form.getvalue('lv_size') print(user_name) print(lv_size) output=sp.getstatusoutput(\"sudo ansible-playbook ostaas.yml --extra-vars='user_name={u} lv_size={l}'\".format(u=user_name, l=lv_size)) if output[0] ==",
"cgi import subprocess as sp form = cgi.FieldStorage() user_name = form.getvalue('user_name') lv_size =",
"form.getvalue('lv_size') print(user_name) print(lv_size) output=sp.getstatusoutput(\"sudo ansible-playbook ostaas.yml --extra-vars='user_name={u} lv_size={l}'\".format(u=user_name, l=lv_size)) if output[0] == 0"
] |
[
"from django.urls import path from .views import DevelopmentLTIView app_name = \"development\" urlpatterns =",
"from .views import DevelopmentLTIView app_name = \"development\" urlpatterns = [ path(\"development/\", DevelopmentLTIView.as_view(), name=\"lti-development-view\"),",
"django.urls import path from .views import DevelopmentLTIView app_name = \"development\" urlpatterns = [",
"app URLs configuration.\"\"\" from django.urls import path from .views import DevelopmentLTIView app_name =",
"import path from .views import DevelopmentLTIView app_name = \"development\" urlpatterns = [ path(\"development/\",",
"<gh_stars>0 \"\"\"Marsha Development app URLs configuration.\"\"\" from django.urls import path from .views import",
"path from .views import DevelopmentLTIView app_name = \"development\" urlpatterns = [ path(\"development/\", DevelopmentLTIView.as_view(),",
"URLs configuration.\"\"\" from django.urls import path from .views import DevelopmentLTIView app_name = \"development\"",
"configuration.\"\"\" from django.urls import path from .views import DevelopmentLTIView app_name = \"development\" urlpatterns",
".views import DevelopmentLTIView app_name = \"development\" urlpatterns = [ path(\"development/\", DevelopmentLTIView.as_view(), name=\"lti-development-view\"), ]",
"Development app URLs configuration.\"\"\" from django.urls import path from .views import DevelopmentLTIView app_name",
"\"\"\"Marsha Development app URLs configuration.\"\"\" from django.urls import path from .views import DevelopmentLTIView"
] |
[
"to (or want to) train any layers of our pre-trained vgg model, so",
"### Total Loss def compute_loss(model, loss_weights, generated_output_activations, gram_style_features, content_features, num_content_layers, num_style_layers): generated_content_activations =",
"data vgg19 = VGG19(weights=None, include_top=False) # We don't need to (or want to)",
"style_score, content_score ############################################################################################################ ############################################################################################################ # CREATE STYLE TRANFER ############################################################################################################ ############################################################################################################ # Using Keras",
"+= 116.779 x[:, :, 2] += 123.68 x = x[:, :, ::-1] x",
"tensorflow as tf from tensorflow.python.keras.preprocessing import image as kp_image # Keras is only",
"return gram def get_style_loss(base_style, gram_target): height, width, channels = base_style.get_shape().as_list() gram_style = gram_matrix(base_style)",
"original paper, the initial stylized image is random matrix of same size as",
"paper, the initial stylized image is random matrix of same size as that",
"images are located content_path = 'content.jpg' style_path = 'style.jpg' # Save the result",
"generated_image = tf.Variable(generated_image, dtype=tf.float32) model_outputs = model(generated_image) # weightages of each content and",
"the weights again because tf.global_variables_initializer() resets the weights vgg19.load_weights(vgg_weights) # Put loss as",
"] return style_features, content_features ### Total Loss def compute_loss(model, loss_weights, generated_output_activations, gram_style_features, content_features,",
"import numpy as np ## ## ## # list of layers to be",
"false. vgg19.trainable = False style_model_outputs = [vgg19.get_layer(name).output for name in style_layers] content_model_outputs =",
"later images content image was used instead on random values for first stylized",
"loss_weights = (style_weight, content_weight) # Create our optimizer loss = compute_loss(model, loss_weights, model_outputs,",
"max-min value of VGG norm clipped = tf.clip_by_value(generated_image, min_vals, max_vals) # assign the",
"style_score, content_score = loss total_loss = total_loss.eval(session=sess) if total_loss < best_loss: # Update",
"[-1, channels]) n = tf.shape(a)[0] # get gram matrix gram = tf.matmul(a, a,",
"content and style images are located content_path = 'content.jpg' style_path = 'style.jpg' #",
"def compute_loss(model, loss_weights, generated_output_activations, gram_style_features, content_features, num_content_layers, num_style_layers): generated_content_activations = generated_output_activations[:num_content_layers] generated_style_activations =",
"in content_layers] model_outputs = content_model_outputs + style_model_outputs # Build model return Model(inputs =",
"model_outputs = content_model_outputs + style_model_outputs # Build model return Model(inputs = vgg19.input, outputs",
"from keras.applications.vgg19 import VGG19 from keras.models import Model from keras import backend as",
"to make it suitable to be used by VGG19 model out = tf.keras.applications.vgg19.preprocess_input(img)",
"123.68 x = x[:, :, ::-1] x = np.clip(x, 0, 255).astype('uint8') return x",
"and Style Loss content_layers = ['block3_conv3'] style_layers = ['block1_conv1','block2_conv2','block4_conv3'] num_content_layers = len(content_layers) num_style_layers",
"Create our optimizer loss = compute_loss(model, loss_weights, model_outputs, gram_style_features, content_features, num_content_layers, num_style_layers) opt",
"np ## ## ## # list of layers to be considered for calculation",
"############################################################################################################ # UTILS ############################################################################################################ ############################################################################################################ def load_img(path_to_img): max_dim = 512 img = Image.open(path_to_img)",
"= 0 content_score = 0 # Accumulate style losses from all layers #",
"content_score = 0 # Accumulate style losses from all layers # Here, we",
"# Get the style and content feature representations (from our specified intermediate layers)",
"= [ style_layer[0] for style_layer in style_outputs[num_content_layers:] ] content_features = [ content_layer[0] for",
"= content_model_outputs + style_model_outputs # Build model return Model(inputs = vgg19.input, outputs =",
"set it's trainable to false. vgg19.trainable = False style_model_outputs = [vgg19.get_layer(name).output for name",
"the training generated_image = tf.Variable(generated_image, dtype=tf.float32) model_outputs = model(generated_image) # weightages of each",
"# because it proved to help to stylize faster generated_image = load_img(content_path) #",
"= tf.matmul(a, a, transpose_a=True) return gram def get_style_loss(base_style, gram_target): height, width, channels =",
"transpose_a=True) return gram def get_style_loss(base_style, gram_target): height, width, channels = base_style.get_shape().as_list() gram_style =",
"calculation of Content and Style Loss content_layers = ['block3_conv3'] style_layers = ['block1_conv1','block2_conv2','block4_conv3'] num_content_layers",
"= tf.Variable(generated_image, dtype=tf.float32) model_outputs = model(generated_image) # weightages of each content and style",
"tf.matmul(a, a, transpose_a=True) return gram def get_style_loss(base_style, gram_target): height, width, channels = base_style.get_shape().as_list()",
"(i.e image with minimum loss) best_loss, best_img = float('inf'), None for i in",
"generated_output_activations[num_content_layers:] style_weight, content_weight = loss_weights style_score = 0 content_score = 0 # Accumulate",
"session which we created K.set_session(sess) model, vgg19 = get_model(content_layers,style_layers) # Get the style",
"all layers weight_per_content_layer = 1.0 / float(num_content_layers) for target_content, comb_content in zip(content_features, generated_content_activations):",
"max_dim/img_size img = img.resize((round(img.size[0]*scale), round(img.size[1]*scale)), Image.ANTIALIAS) img = kp_image.img_to_array(img) # We need to",
"content_layer[0] for content_layer in content_outputs[:num_content_layers] ] return style_features, content_features ### Total Loss def",
"x = np.clip(x, 0, 255).astype('uint8') return x ############################################################################################################ ############################################################################################################ # Loss Function ############################################################################################################",
"= np.array([103.939, 116.779, 123.68]) min_vals = -norm_means max_vals = 255 - norm_means #",
"a 2D array of Nc x (Nh*Nw) channels = int(input_tensor.shape[-1]) a = tf.reshape(input_tensor,",
"we equally weight each contribution of each loss layer weight_per_style_layer = 1.0 /",
"in style_layers] content_model_outputs = [vgg19.get_layer(name).output for name in content_layers] model_outputs = content_model_outputs +",
"content image was used instead on random values for first stylized image #",
"from keras import backend as K # pillow is used for loading and",
"for style_layer in style_outputs[num_content_layers:] ] content_features = [ content_layer[0] for content_layer in content_outputs[:num_content_layers]",
"Keras Load VGG19 model def get_model(content_layers,style_layers): # Load our model. We load pretrained",
"of Content and Style Loss content_layers = ['block3_conv3'] style_layers = ['block1_conv1','block2_conv2','block4_conv3'] num_content_layers =",
"weight_per_content_layer = 1.0 / float(num_content_layers) for target_content, comb_content in zip(content_features, generated_content_activations): temp =",
"def gram_matrix(input_tensor): # if input tensor is a 3D array of size Nh",
"close the TF session sess.close() return best_img, best_loss best, best_loss = run_style_transfer(content_path, style_path)",
"perform the inverse of the preprocessiing step x[:, :, 0] += 103.939 x[:,",
"from total loss. best_loss = total_loss # generated image is of shape (1,",
"pretrained VGG, trained on imagenet data vgg19 = VGG19(weights=None, include_top=False) # We don't",
"our case import numpy as np ## ## ## # list of layers",
"loss[0], var_list = [generated_image]) sess.run(tf.global_variables_initializer()) sess.run(generated_image.initializer) # loading the weights again because tf.global_variables_initializer()",
"through it def get_feature_representations(model, content_path, style_path, num_content_layers): # Load our images in content_image",
"Keras is only used to load VGG19 model as a high level API",
"style_layer in style_outputs[num_content_layers:] ] content_features = [ content_layer[0] for content_layer in content_outputs[:num_content_layers] ]",
"::-1] x = np.clip(x, 0, 255).astype('uint8') return x ############################################################################################################ ############################################################################################################ # Loss Function",
"= get_feature_representations(model, content_path, style_path, num_content_layers) gram_style_features = [gram_matrix(style_feature) for style_feature in style_features] #",
"size as that of content image # but in later images content image",
"for target_content, comb_content in zip(content_features, generated_content_activations): temp = get_content_loss(comb_content[0], target_content) content_score += weight_per_content_layer*",
"with minimum loss) best_loss, best_img = float('inf'), None for i in range(num_iterations): #",
"get_model(content_layers,style_layers) # Get the style and content feature representations (from our specified intermediate",
"located vgg_weights = \"vgg_weights/vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5\" ############################################################################################################ ############################################################################################################ # UTILS ############################################################################################################ ############################################################################################################ def load_img(path_to_img): max_dim",
"content_outputs[:num_content_layers] ] return style_features, content_features ### Total Loss def compute_loss(model, loss_weights, generated_output_activations, gram_style_features,",
"103.939 x[:, :, 1] += 116.779 x[:, :, 2] += 123.68 x =",
"2) return tf.reduce_mean(tf.square(gram_style - gram_target)) / (channels**2 * width * height) #(4.0 *",
"# Using Keras Load VGG19 model def get_model(content_layers,style_layers): # Load our model. We",
"channels = int(input_tensor.shape[-1]) a = tf.reshape(input_tensor, [-1, channels]) n = tf.shape(a)[0] # get",
"[ content_layer[0] for content_layer in content_outputs[:num_content_layers] ] return style_features, content_features ### Total Loss",
"content_path, style_path, num_content_layers) gram_style_features = [gram_matrix(style_feature) for style_feature in style_features] # VGG default",
"model_outputs = model(generated_image) # weightages of each content and style images i.e alpha",
"images i.e alpha & beta loss_weights = (style_weight, content_weight) # Create our optimizer",
"stays in the range of max-min value of VGG norm clipped = tf.clip_by_value(generated_image,",
"training generated_image = tf.Variable(generated_image, dtype=tf.float32) model_outputs = model(generated_image) # weightages of each content",
"API to TensorFlow from keras.applications.vgg19 import VGG19 from keras.models import Model from keras",
"num_style_layers = len(style_layers) # path where the content and style images are located",
"# CREATE STYLE TRANFER ############################################################################################################ ############################################################################################################ # Using Keras Load VGG19 model def",
"our model. We load pretrained VGG, trained on imagenet data vgg19 = VGG19(weights=None,",
"considered for calculation of Content and Style Loss content_layers = ['block3_conv3'] style_layers =",
"best image (i.e image with minimum loss) best_loss, best_img = float('inf'), None for",
"only used to load VGG19 model as a high level API to TensorFlow",
"style images i.e alpha & beta loss_weights = (style_weight, content_weight) # Create our",
"min_vals, max_vals) # assign the clipped value to the tensor stylized image generated_image.assign(clipped)",
"of each loss layer weight_per_style_layer = 1.0 / float(num_style_layers) for target_style, comb_style in",
"# Get total loss loss = style_weight*style_score + content_weight*content_score return loss, style_score, content_score",
"style_loss: ', s_loss,' content_loss: ', c_loss) # Save image after every 100 iterations",
"such that it has a batch dimension img = np.expand_dims(img, axis=0) # preprocess",
"## ## ## # list of layers to be considered for calculation of",
"We need to broadcast the image array such that it has a batch",
"has a batch dimension img = np.expand_dims(img, axis=0) # preprocess raw images to",
"content image # but in later images content image was used instead on",
"Nh x Nw X Nc # we reshape it to a 2D array",
"losses from all layers weight_per_content_layer = 1.0 / float(num_content_layers) for target_content, comb_content in",
"0] += 103.939 x[:, :, 1] += 116.779 x[:, :, 2] += 123.68",
"VGG19 from keras.models import Model from keras import backend as K # pillow",
"\"vgg_weights/vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5\" ############################################################################################################ ############################################################################################################ # UTILS ############################################################################################################ ############################################################################################################ def load_img(path_to_img): max_dim = 512 img",
"of max-min value of VGG norm clipped = tf.clip_by_value(generated_image, min_vals, max_vals) # assign",
"the preprocessiing step x[:, :, 0] += 103.939 x[:, :, 1] += 116.779",
"saving images from PIL import Image # numPy is used for manipulation of",
"style_features, content_features ### Total Loss def compute_loss(model, loss_weights, generated_output_activations, gram_style_features, content_features, num_content_layers, num_style_layers):",
"from tensorflow.python.keras.preprocessing import image as kp_image # Keras is only used to load",
"* (channels ** 2) * (width * height) ** 2) return tf.reduce_mean(tf.square(gram_style -",
"np.clip(x, 0, 255).astype('uint8') return x ############################################################################################################ ############################################################################################################ # Loss Function ############################################################################################################ ############################################################################################################ ###",
"model as a high level API to TensorFlow from keras.applications.vgg19 import VGG19 from",
"x ############################################################################################################ ############################################################################################################ # Loss Function ############################################################################################################ ############################################################################################################ ### Content Loss Function def",
"[ style_layer[0] for style_layer in style_outputs[num_content_layers:] ] content_features = [ content_layer[0] for content_layer",
"from all layers # Here, we equally weight each contribution of each loss",
"the TF session which we created K.set_session(sess) model, vgg19 = get_model(content_layers,style_layers) # Get",
"Build model return Model(inputs = vgg19.input, outputs = model_outputs), vgg19 def run_style_transfer(content_path, style_path,",
"content losses from all layers weight_per_content_layer = 1.0 / float(num_content_layers) for target_content, comb_content",
"content_layers] model_outputs = content_model_outputs + style_model_outputs # Build model return Model(inputs = vgg19.input,",
"image during the training generated_image = tf.Variable(generated_image, dtype=tf.float32) model_outputs = model(generated_image) # weightages",
"= loss_weights style_score = 0 content_score = 0 # Accumulate style losses from",
"of size Nh x Nw X Nc # we reshape it to a",
"our optimizer loss = compute_loss(model, loss_weights, model_outputs, gram_style_features, content_features, num_content_layers, num_style_layers) opt =",
"after every 100 iterations if (i+1)%100 == 0: output = Image.fromarray(best_img) output.save(str(i+1)+'-'+save_name) #",
"we reshape it to a 2D array of Nc x (Nh*Nw) channels =",
"content_path = 'content.jpg' style_path = 'style.jpg' # Save the result as save_name =",
"1.0 / float(num_content_layers) for target_content, comb_content in zip(content_features, generated_content_activations): temp = get_content_loss(comb_content[0], target_content)",
"def get_model(content_layers,style_layers): # Load our model. We load pretrained VGG, trained on imagenet",
"dtype=tf.float32) model_outputs = model(generated_image) # weightages of each content and style images i.e",
"max_vals = 255 - norm_means # In original paper, the initial stylized image",
"be considered for calculation of Content and Style Loss content_layers = ['block3_conv3'] style_layers",
"height, width, channels = base_style.get_shape().as_list() gram_style = gram_matrix(base_style) # Original eqn as a",
"gram_matrix(input_tensor): # if input tensor is a 3D array of size Nh x",
"loss = compute_loss(model, loss_weights, model_outputs, gram_style_features, content_features, num_content_layers, num_style_layers) opt = tf.train.AdamOptimizer(learning_rate=9, beta1=0.9,",
"float('inf'), None for i in range(num_iterations): # Do optimization sess.run(opt) # Make sure",
"from keras.models import Model from keras import backend as K # pillow is",
"outputs = model_outputs), vgg19 def run_style_transfer(content_path, style_path, num_iterations=200, content_weight=0.1, style_weight=0.9): # Create a",
":, 0] += 103.939 x[:, :, 1] += 116.779 x[:, :, 2] +=",
"we created K.set_session(sess) model, vgg19 = get_model(content_layers,style_layers) # Get the style and content",
"/ (channels**2 * width * height) #(4.0 * (channels ** 2) * (width",
"* height) ** 2) ### Use to pass content and style image through",
"was used instead on random values for first stylized image # because it",
"image was used instead on random values for first stylized image # because",
"generated_image = np.random.randint(0,255, size=generated_image.shape) # Create tensorflow variable to hold a stylized/generated image",
"img = np.expand_dims(img, axis=0) # preprocess raw images to make it suitable to",
"as infinity before training starts and Create a variable to hold best image",
"range of max-min value of VGG norm clipped = tf.clip_by_value(generated_image, min_vals, max_vals) #",
"Image.fromarray(best_img) output.save(str(i+1)+'-'+save_name) # after num_iterations iterations are completed, close the TF session sess.close()",
"width, channels = base_style.get_shape().as_list() gram_style = gram_matrix(base_style) # Original eqn as a constant",
"# We need to broadcast the image array such that it has a",
"[vgg19.get_layer(name).output for name in style_layers] content_model_outputs = [vgg19.get_layer(name).output for name in content_layers] model_outputs",
"= deprocess_img(temp_generated_image) s_loss = sess.run(style_score) c_loss = sess.run(content_score) # print best loss print('best:",
"gram_target)) / (channels**2 * width * height) #(4.0 * (channels ** 2) *",
"(channels ** 2) * (width * height) ** 2) ### Use to pass",
"= int(input_tensor.shape[-1]) a = tf.reshape(input_tensor, [-1, channels]) n = tf.shape(a)[0] # get gram",
"content feature representations (from our specified intermediate layers) style_features, content_features = get_feature_representations(model, content_path,",
"used for manipulation of array of object i.e Image in our case import",
"to (h, w, 3) temp_generated_image = sess.run(generated_image)[0] best_img = deprocess_img(temp_generated_image) s_loss = sess.run(style_score)",
"num_iterations iterations are completed, close the TF session sess.close() return best_img, best_loss best,",
"i.e alpha & beta loss_weights = (style_weight, content_weight) # Create our optimizer loss",
"3D array of size Nh x Nw X Nc # we reshape it",
"width * height) #(4.0 * (channels ** 2) * (width * height) **",
"default normalization norm_means = np.array([103.939, 116.779, 123.68]) min_vals = -norm_means max_vals = 255",
"style_model_outputs # Build model return Model(inputs = vgg19.input, outputs = model_outputs), vgg19 def",
"infinity before training starts and Create a variable to hold best image (i.e",
"Create a variable to hold best image (i.e image with minimum loss) best_loss,",
"load VGG19 model as a high level API to TensorFlow from keras.applications.vgg19 import",
"where Vgg19 model weight is located vgg_weights = \"vgg_weights/vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5\" ############################################################################################################ ############################################################################################################ # UTILS",
"# Here, we equally weight each contribution of each loss layer weight_per_style_layer =",
"tf.clip_by_value(generated_image, min_vals, max_vals) # assign the clipped value to the tensor stylized image",
"keras.models import Model from keras import backend as K # pillow is used",
"is random matrix of same size as that of content image # but",
"h, w, 3) convert it to (h, w, 3) temp_generated_image = sess.run(generated_image)[0] best_img",
"of object i.e Image in our case import numpy as np ## ##",
"temp # Get total loss loss = style_weight*style_score + content_weight*content_score return loss, style_score,",
"loss_weights style_score = 0 content_score = 0 # Accumulate style losses from all",
"and saving images from PIL import Image # numPy is used for manipulation",
"our images in content_image = load_img(content_path) style_image = load_img(style_path) # batch compute content",
"array such that it has a batch dimension img = np.expand_dims(img, axis=0) #",
"generated_content_activations = generated_output_activations[:num_content_layers] generated_style_activations = generated_output_activations[num_content_layers:] style_weight, content_weight = loss_weights style_score = 0",
"# Put loss as infinity before training starts and Create a variable to",
"features content_outputs = model(content_image) style_outputs = model(style_image) # Get the style and content",
"starts and Create a variable to hold best image (i.e image with minimum",
"# Load our images in content_image = load_img(content_path) style_image = load_img(style_path) # batch",
"axis=0) # preprocess raw images to make it suitable to be used by",
"(width * height) ** 2) ### Use to pass content and style image",
"total_loss < best_loss: # Update best loss and best image from total loss.",
"for target_style, comb_style in zip(gram_style_features, generated_style_activations): temp = get_style_loss(comb_style[0], target_style) style_score += weight_per_style_layer",
"############################################################################################################ ############################################################################################################ def load_img(path_to_img): max_dim = 512 img = Image.open(path_to_img) img_size = max(img.size)",
"style_score = 0 content_score = 0 # Accumulate style losses from all layers",
"if (i+1)%100 == 0: output = Image.fromarray(best_img) output.save(str(i+1)+'-'+save_name) # after num_iterations iterations are",
"in content_outputs[:num_content_layers] ] return style_features, content_features ### Total Loss def compute_loss(model, loss_weights, generated_output_activations,",
"# We don't need to (or want to) train any layers of our",
"STYLE TRANFER ############################################################################################################ ############################################################################################################ # Using Keras Load VGG19 model def get_model(content_layers,style_layers): #",
"that it has a batch dimension img = np.expand_dims(img, axis=0) # preprocess raw",
"loss, style_score, content_score ############################################################################################################ ############################################################################################################ # CREATE STYLE TRANFER ############################################################################################################ ############################################################################################################ # Using",
"# Open the Tuple of tensors total_loss, style_score, content_score = loss total_loss =",
"output = Image.fromarray(best_img) output.save(str(i+1)+'-'+save_name) # after num_iterations iterations are completed, close the TF",
"to be used by VGG19 model out = tf.keras.applications.vgg19.preprocess_input(img) return tf.convert_to_tensor(out) def deprocess_img(processed_img):",
"# Loss Function ############################################################################################################ ############################################################################################################ ### Content Loss Function def get_content_loss(content, target): return",
"sess.run(generated_image.initializer) # loading the weights again because tf.global_variables_initializer() resets the weights vgg19.load_weights(vgg_weights) #",
"# In original paper, the initial stylized image is random matrix of same",
"for name in style_layers] content_model_outputs = [vgg19.get_layer(name).output for name in content_layers] model_outputs =",
"the image array such that it has a batch dimension img = np.expand_dims(img,",
"model_outputs), vgg19 def run_style_transfer(content_path, style_path, num_iterations=200, content_weight=0.1, style_weight=0.9): # Create a tensorflow session",
",' style_loss: ', s_loss,' content_loss: ', c_loss) # Save image after every 100",
"the Tuple of tensors total_loss, style_score, content_score = loss total_loss = total_loss.eval(session=sess) if",
"each loss layer weight_per_style_layer = 1.0 / float(num_style_layers) for target_style, comb_style in zip(gram_style_features,",
"############################################################################################################ # Loss Function ############################################################################################################ ############################################################################################################ ### Content Loss Function def get_content_loss(content, target):",
"to stylize faster generated_image = load_img(content_path) # generated_image = np.random.randint(0,255, size=generated_image.shape) # Create",
"matrix of same size as that of content image # but in later",
"x Nw X Nc # we reshape it to a 2D array of",
"UTILS ############################################################################################################ ############################################################################################################ def load_img(path_to_img): max_dim = 512 img = Image.open(path_to_img) img_size =",
"to) train any layers of our pre-trained vgg model, so we set it's",
"style_outputs = model(style_image) # Get the style and content feature representations from our",
"num_iterations=200, content_weight=0.1, style_weight=0.9): # Create a tensorflow session sess = tf.Session() # Assign",
"(from our specified intermediate layers) style_features, content_features = get_feature_representations(model, content_path, style_path, num_content_layers) gram_style_features",
"0: output = Image.fromarray(best_img) output.save(str(i+1)+'-'+save_name) # after num_iterations iterations are completed, close the",
"tf.shape(a)[0] # get gram matrix gram = tf.matmul(a, a, transpose_a=True) return gram def",
"(channels**2 * width * height) #(4.0 * (channels ** 2) * (width *",
"initial stylized image is random matrix of same size as that of content",
"2D array of Nc x (Nh*Nw) channels = int(input_tensor.shape[-1]) a = tf.reshape(input_tensor, [-1,",
"out = tf.keras.applications.vgg19.preprocess_input(img) return tf.convert_to_tensor(out) def deprocess_img(processed_img): x = processed_img.copy() # perform the",
"Load our model. We load pretrained VGG, trained on imagenet data vgg19 =",
"loss total_loss = total_loss.eval(session=sess) if total_loss < best_loss: # Update best loss and",
"to be considered for calculation of Content and Style Loss content_layers = ['block3_conv3']",
"# after num_iterations iterations are completed, close the TF session sess.close() return best_img,",
"= np.expand_dims(img, axis=0) # preprocess raw images to make it suitable to be",
"Get the style and content feature representations (from our specified intermediate layers) style_features,",
"image through it def get_feature_representations(model, content_path, style_path, num_content_layers): # Load our images in",
"image array such that it has a batch dimension img = np.expand_dims(img, axis=0)",
"# Create our optimizer loss = compute_loss(model, loss_weights, model_outputs, gram_style_features, content_features, num_content_layers, num_style_layers)",
"num_content_layers): # Load our images in content_image = load_img(content_path) style_image = load_img(style_path) #",
"our specified intermediate layers) style_features, content_features = get_feature_representations(model, content_path, style_path, num_content_layers) gram_style_features =",
"broadcast the image array such that it has a batch dimension img =",
"load pretrained VGG, trained on imagenet data vgg19 = VGG19(weights=None, include_top=False) # We",
"i in range(num_iterations): # Do optimization sess.run(opt) # Make sure image values stays",
"make it suitable to be used by VGG19 model out = tf.keras.applications.vgg19.preprocess_input(img) return",
"a constant to divide i.e 1/(4. * (channels ** 2) * (width *",
"tf.train.AdamOptimizer(learning_rate=9, beta1=0.9, epsilon=1e-1).minimize( loss[0], var_list = [generated_image]) sess.run(tf.global_variables_initializer()) sess.run(generated_image.initializer) # loading the weights",
"loss = style_weight*style_score + content_weight*content_score return loss, style_score, content_score ############################################################################################################ ############################################################################################################ # CREATE",
"= 512 img = Image.open(path_to_img) img_size = max(img.size) scale = max_dim/img_size img =",
"as that of content image # but in later images content image was",
"Put loss as infinity before training starts and Create a variable to hold",
"best_img = float('inf'), None for i in range(num_iterations): # Do optimization sess.run(opt) #",
"total loss loss = style_weight*style_score + content_weight*content_score return loss, style_score, content_score ############################################################################################################ ############################################################################################################",
"- norm_means # In original paper, the initial stylized image is random matrix",
"', s_loss,' content_loss: ', c_loss) # Save image after every 100 iterations if",
"def deprocess_img(processed_img): x = processed_img.copy() # perform the inverse of the preprocessiing step",
"style_model_outputs = [vgg19.get_layer(name).output for name in style_layers] content_model_outputs = [vgg19.get_layer(name).output for name in",
"style images are located content_path = 'content.jpg' style_path = 'style.jpg' # Save the",
"# Do optimization sess.run(opt) # Make sure image values stays in the range",
"target)) /2 ### Style Loss Fucntion def gram_matrix(input_tensor): # if input tensor is",
"generated_output_activations[:num_content_layers] generated_style_activations = generated_output_activations[num_content_layers:] style_weight, content_weight = loss_weights style_score = 0 content_score =",
"= [vgg19.get_layer(name).output for name in style_layers] content_model_outputs = [vgg19.get_layer(name).output for name in content_layers]",
"# weightages of each content and style images i.e alpha & beta loss_weights",
"** 2) ### Use to pass content and style image through it def",
"height) #(4.0 * (channels ** 2) * (width * height) ** 2) ###",
"tf.global_variables_initializer() resets the weights vgg19.load_weights(vgg_weights) # Put loss as infinity before training starts",
"used for loading and saving images from PIL import Image # numPy is",
"content and style features content_outputs = model(content_image) style_outputs = model(style_image) # Get the",
"Update best loss and best image from total loss. best_loss = total_loss #",
"same size as that of content image # but in later images content",
"processed_img.copy() # perform the inverse of the preprocessiing step x[:, :, 0] +=",
"we set it's trainable to false. vgg19.trainable = False style_model_outputs = [vgg19.get_layer(name).output for",
"load_img(content_path) style_image = load_img(style_path) # batch compute content and style features content_outputs =",
"is only used to load VGG19 model as a high level API to",
"'content.jpg' style_path = 'style.jpg' # Save the result as save_name = 'generated.jpg' #",
"Save the result as save_name = 'generated.jpg' # path to where Vgg19 model",
"tensor is a 3D array of size Nh x Nw X Nc #",
"of array of object i.e Image in our case import numpy as np",
"images in content_image = load_img(content_path) style_image = load_img(style_path) # batch compute content and",
"= 0 # Accumulate style losses from all layers # Here, we equally",
"model return Model(inputs = vgg19.input, outputs = model_outputs), vgg19 def run_style_transfer(content_path, style_path, num_iterations=200,",
"by VGG19 model out = tf.keras.applications.vgg19.preprocess_input(img) return tf.convert_to_tensor(out) def deprocess_img(processed_img): x = processed_img.copy()",
"content_features ### Total Loss def compute_loss(model, loss_weights, generated_output_activations, gram_style_features, content_features, num_content_layers, num_style_layers): generated_content_activations",
"images content image was used instead on random values for first stylized image",
"len(content_layers) num_style_layers = len(style_layers) # path where the content and style images are",
"512 img = Image.open(path_to_img) img_size = max(img.size) scale = max_dim/img_size img = img.resize((round(img.size[0]*scale),",
"Get the style and content feature representations from our model style_features = [",
"n = tf.shape(a)[0] # get gram matrix gram = tf.matmul(a, a, transpose_a=True) return",
"gram def get_style_loss(base_style, gram_target): height, width, channels = base_style.get_shape().as_list() gram_style = gram_matrix(base_style) #",
"= len(content_layers) num_style_layers = len(style_layers) # path where the content and style images",
"and style features content_outputs = model(content_image) style_outputs = model(style_image) # Get the style",
"# Get the style and content feature representations from our model style_features =",
",'loss: ', total_loss ,' style_loss: ', s_loss,' content_loss: ', c_loss) # Save image",
"# Create a tensorflow session sess = tf.Session() # Assign keras back-end to",
"get_model(content_layers,style_layers): # Load our model. We load pretrained VGG, trained on imagenet data",
"= ['block3_conv3'] style_layers = ['block1_conv1','block2_conv2','block4_conv3'] num_content_layers = len(content_layers) num_style_layers = len(style_layers) # path",
"1.0 / float(num_style_layers) for target_style, comb_style in zip(gram_style_features, generated_style_activations): temp = get_style_loss(comb_style[0], target_style)",
"as K # pillow is used for loading and saving images from PIL",
"imagenet data vgg19 = VGG19(weights=None, include_top=False) # We don't need to (or want",
"representations (from our specified intermediate layers) style_features, content_features = get_feature_representations(model, content_path, style_path, num_content_layers)",
"resets the weights vgg19.load_weights(vgg_weights) # Put loss as infinity before training starts and",
"Image in our case import numpy as np ## ## ## # list",
"# Original eqn as a constant to divide i.e 1/(4. * (channels **",
"Loss Function ############################################################################################################ ############################################################################################################ ### Content Loss Function def get_content_loss(content, target): return tf.reduce_mean(tf.square(content",
"# Build model return Model(inputs = vgg19.input, outputs = model_outputs), vgg19 def run_style_transfer(content_path,",
"is located vgg_weights = \"vgg_weights/vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5\" ############################################################################################################ ############################################################################################################ # UTILS ############################################################################################################ ############################################################################################################ def load_img(path_to_img):",
"it's trainable to false. vgg19.trainable = False style_model_outputs = [vgg19.get_layer(name).output for name in",
"deprocess_img(processed_img): x = processed_img.copy() # perform the inverse of the preprocessiing step x[:,",
"Nc # we reshape it to a 2D array of Nc x (Nh*Nw)",
"round(img.size[1]*scale)), Image.ANTIALIAS) img = kp_image.img_to_array(img) # We need to broadcast the image array",
"total_loss = total_loss.eval(session=sess) if total_loss < best_loss: # Update best loss and best",
"beta loss_weights = (style_weight, content_weight) # Create our optimizer loss = compute_loss(model, loss_weights,",
"raw images to make it suitable to be used by VGG19 model out",
"', c_loss) # Save image after every 100 iterations if (i+1)%100 == 0:",
"help to stylize faster generated_image = load_img(content_path) # generated_image = np.random.randint(0,255, size=generated_image.shape) #",
"of each content and style images i.e alpha & beta loss_weights = (style_weight,",
"back-end to the TF session which we created K.set_session(sess) model, vgg19 = get_model(content_layers,style_layers)",
"and style images i.e alpha & beta loss_weights = (style_weight, content_weight) # Create",
"# Make sure image values stays in the range of max-min value of",
"0, 255).astype('uint8') return x ############################################################################################################ ############################################################################################################ # Loss Function ############################################################################################################ ############################################################################################################ ### Content",
"# UTILS ############################################################################################################ ############################################################################################################ def load_img(path_to_img): max_dim = 512 img = Image.open(path_to_img) img_size",
"trained on imagenet data vgg19 = VGG19(weights=None, include_top=False) # We don't need to",
"max(img.size) scale = max_dim/img_size img = img.resize((round(img.size[0]*scale), round(img.size[1]*scale)), Image.ANTIALIAS) img = kp_image.img_to_array(img) #",
"style_path, num_iterations=200, content_weight=0.1, style_weight=0.9): # Create a tensorflow session sess = tf.Session() #",
"variable to hold best image (i.e image with minimum loss) best_loss, best_img =",
"Function def get_content_loss(content, target): return tf.reduce_mean(tf.square(content - target)) /2 ### Style Loss Fucntion",
"generated image is of shape (1, h, w, 3) convert it to (h,",
"as kp_image # Keras is only used to load VGG19 model as a",
"loss and best image from total loss. best_loss = total_loss # generated image",
"content_weight = loss_weights style_score = 0 content_score = 0 # Accumulate style losses",
"# VGG default normalization norm_means = np.array([103.939, 116.779, 123.68]) min_vals = -norm_means max_vals",
"content_loss: ', c_loss) # Save image after every 100 iterations if (i+1)%100 ==",
"tf.reduce_mean(tf.square(gram_style - gram_target)) / (channels**2 * width * height) #(4.0 * (channels **",
"generated_image.assign(clipped) # Open the Tuple of tensors total_loss, style_score, content_score = loss total_loss",
"############################################################################################################ # CREATE STYLE TRANFER ############################################################################################################ ############################################################################################################ # Using Keras Load VGG19 model",
"img = Image.open(path_to_img) img_size = max(img.size) scale = max_dim/img_size img = img.resize((round(img.size[0]*scale), round(img.size[1]*scale)),",
"the weights vgg19.load_weights(vgg_weights) # Put loss as infinity before training starts and Create",
"size Nh x Nw X Nc # we reshape it to a 2D",
"the clipped value to the tensor stylized image generated_image.assign(clipped) # Open the Tuple",
"clipped value to the tensor stylized image generated_image.assign(clipped) # Open the Tuple of",
"TensorFlow from keras.applications.vgg19 import VGG19 from keras.models import Model from keras import backend",
"= Image.fromarray(best_img) output.save(str(i+1)+'-'+save_name) # after num_iterations iterations are completed, close the TF session",
"# get gram matrix gram = tf.matmul(a, a, transpose_a=True) return gram def get_style_loss(base_style,",
"import backend as K # pillow is used for loading and saving images",
"Accumulate style losses from all layers # Here, we equally weight each contribution",
"of Nc x (Nh*Nw) channels = int(input_tensor.shape[-1]) a = tf.reshape(input_tensor, [-1, channels]) n",
"generated_image = load_img(content_path) # generated_image = np.random.randint(0,255, size=generated_image.shape) # Create tensorflow variable to",
"keras.applications.vgg19 import VGG19 from keras.models import Model from keras import backend as K",
"Create a tensorflow session sess = tf.Session() # Assign keras back-end to the",
"gram_style_features = [gram_matrix(style_feature) for style_feature in style_features] # VGG default normalization norm_means =",
"as a high level API to TensorFlow from keras.applications.vgg19 import VGG19 from keras.models",
"VGG19 model def get_model(content_layers,style_layers): # Load our model. We load pretrained VGG, trained",
"model def get_model(content_layers,style_layers): # Load our model. We load pretrained VGG, trained on",
"np.random.randint(0,255, size=generated_image.shape) # Create tensorflow variable to hold a stylized/generated image during the",
"norm clipped = tf.clip_by_value(generated_image, min_vals, max_vals) # assign the clipped value to the",
"to load VGG19 model as a high level API to TensorFlow from keras.applications.vgg19",
"on imagenet data vgg19 = VGG19(weights=None, include_top=False) # We don't need to (or",
"kp_image # Keras is only used to load VGG19 model as a high",
"is used for manipulation of array of object i.e Image in our case",
"shape (1, h, w, 3) convert it to (h, w, 3) temp_generated_image =",
"sure image values stays in the range of max-min value of VGG norm",
"total_loss.eval(session=sess) if total_loss < best_loss: # Update best loss and best image from",
"'style.jpg' # Save the result as save_name = 'generated.jpg' # path to where",
"generated_style_activations = generated_output_activations[num_content_layers:] style_weight, content_weight = loss_weights style_score = 0 content_score = 0",
"values stays in the range of max-min value of VGG norm clipped =",
"convert it to (h, w, 3) temp_generated_image = sess.run(generated_image)[0] best_img = deprocess_img(temp_generated_image) s_loss",
"model(content_image) style_outputs = model(style_image) # Get the style and content feature representations from",
"return loss, style_score, content_score ############################################################################################################ ############################################################################################################ # CREATE STYLE TRANFER ############################################################################################################ ############################################################################################################ #",
"the result as save_name = 'generated.jpg' # path to where Vgg19 model weight",
"def get_content_loss(content, target): return tf.reduce_mean(tf.square(content - target)) /2 ### Style Loss Fucntion def",
"style_score += weight_per_style_layer * temp # Accumulate content losses from all layers weight_per_content_layer",
"Save image after every 100 iterations if (i+1)%100 == 0: output = Image.fromarray(best_img)",
"content_features, num_content_layers, num_style_layers): generated_content_activations = generated_output_activations[:num_content_layers] generated_style_activations = generated_output_activations[num_content_layers:] style_weight, content_weight = loss_weights",
"content_weight) # Create our optimizer loss = compute_loss(model, loss_weights, model_outputs, gram_style_features, content_features, num_content_layers,",
"a variable to hold best image (i.e image with minimum loss) best_loss, best_img",
"iterations if (i+1)%100 == 0: output = Image.fromarray(best_img) output.save(str(i+1)+'-'+save_name) # after num_iterations iterations",
"VGG19 model as a high level API to TensorFlow from keras.applications.vgg19 import VGG19",
"feature representations from our model style_features = [ style_layer[0] for style_layer in style_outputs[num_content_layers:]",
"/2 ### Style Loss Fucntion def gram_matrix(input_tensor): # if input tensor is a",
"int(input_tensor.shape[-1]) a = tf.reshape(input_tensor, [-1, channels]) n = tf.shape(a)[0] # get gram matrix",
"loss_weights, model_outputs, gram_style_features, content_features, num_content_layers, num_style_layers) opt = tf.train.AdamOptimizer(learning_rate=9, beta1=0.9, epsilon=1e-1).minimize( loss[0], var_list",
"import VGG19 from keras.models import Model from keras import backend as K #",
"the style and content feature representations from our model style_features = [ style_layer[0]",
"so we set it's trainable to false. vgg19.trainable = False style_model_outputs = [vgg19.get_layer(name).output",
"1/(4. * (channels ** 2) * (width * height) ** 2) return tf.reduce_mean(tf.square(gram_style",
"it to a 2D array of Nc x (Nh*Nw) channels = int(input_tensor.shape[-1]) a",
"each contribution of each loss layer weight_per_style_layer = 1.0 / float(num_style_layers) for target_style,",
"= get_content_loss(comb_content[0], target_content) content_score += weight_per_content_layer* temp # Get total loss loss =",
"= kp_image.img_to_array(img) # We need to broadcast the image array such that it",
"sess.run(style_score) c_loss = sess.run(content_score) # print best loss print('best: iteration: ', i ,'loss:",
"and content feature representations from our model style_features = [ style_layer[0] for style_layer",
"# Accumulate style losses from all layers # Here, we equally weight each",
"############################################################################################################ ############################################################################################################ # Using Keras Load VGG19 model def get_model(content_layers,style_layers): # Load our",
"= model_outputs), vgg19 def run_style_transfer(content_path, style_path, num_iterations=200, content_weight=0.1, style_weight=0.9): # Create a tensorflow",
"to pass content and style image through it def get_feature_representations(model, content_path, style_path, num_content_layers):",
"pass content and style image through it def get_feature_representations(model, content_path, style_path, num_content_layers): #",
"image from total loss. best_loss = total_loss # generated image is of shape",
"layers of our pre-trained vgg model, so we set it's trainable to false.",
"vgg19.load_weights(vgg_weights) # Put loss as infinity before training starts and Create a variable",
"return tf.convert_to_tensor(out) def deprocess_img(processed_img): x = processed_img.copy() # perform the inverse of the",
"Loss def compute_loss(model, loss_weights, generated_output_activations, gram_style_features, content_features, num_content_layers, num_style_layers): generated_content_activations = generated_output_activations[:num_content_layers] generated_style_activations",
"c_loss) # Save image after every 100 iterations if (i+1)%100 == 0: output",
"style_features, content_features = get_feature_representations(model, content_path, style_path, num_content_layers) gram_style_features = [gram_matrix(style_feature) for style_feature in",
"kp_image.img_to_array(img) # We need to broadcast the image array such that it has",
"step x[:, :, 0] += 103.939 x[:, :, 1] += 116.779 x[:, :,",
"each content and style images i.e alpha & beta loss_weights = (style_weight, content_weight)",
"created K.set_session(sess) model, vgg19 = get_model(content_layers,style_layers) # Get the style and content feature",
"path where the content and style images are located content_path = 'content.jpg' style_path",
"2] += 123.68 x = x[:, :, ::-1] x = np.clip(x, 0, 255).astype('uint8')",
"* height) #(4.0 * (channels ** 2) * (width * height) ** 2)",
"a tensorflow session sess = tf.Session() # Assign keras back-end to the TF",
"for manipulation of array of object i.e Image in our case import numpy",
"iterations are completed, close the TF session sess.close() return best_img, best_loss best, best_loss",
"# print best loss print('best: iteration: ', i ,'loss: ', total_loss ,' style_loss:",
"content_features, num_content_layers, num_style_layers) opt = tf.train.AdamOptimizer(learning_rate=9, beta1=0.9, epsilon=1e-1).minimize( loss[0], var_list = [generated_image]) sess.run(tf.global_variables_initializer())",
"loss loss = style_weight*style_score + content_weight*content_score return loss, style_score, content_score ############################################################################################################ ############################################################################################################ #",
"tf.Session() # Assign keras back-end to the TF session which we created K.set_session(sess)",
"= 1.0 / float(num_content_layers) for target_content, comb_content in zip(content_features, generated_content_activations): temp = get_content_loss(comb_content[0],",
"want to) train any layers of our pre-trained vgg model, so we set",
"to hold a stylized/generated image during the training generated_image = tf.Variable(generated_image, dtype=tf.float32) model_outputs",
"as a constant to divide i.e 1/(4. * (channels ** 2) * (width",
"VGG19(weights=None, include_top=False) # We don't need to (or want to) train any layers",
"images to make it suitable to be used by VGG19 model out =",
"['block1_conv1','block2_conv2','block4_conv3'] num_content_layers = len(content_layers) num_style_layers = len(style_layers) # path where the content and",
"preprocess raw images to make it suitable to be used by VGG19 model",
"255).astype('uint8') return x ############################################################################################################ ############################################################################################################ # Loss Function ############################################################################################################ ############################################################################################################ ### Content Loss",
"CREATE STYLE TRANFER ############################################################################################################ ############################################################################################################ # Using Keras Load VGG19 model def get_model(content_layers,style_layers):",
"style_weight*style_score + content_weight*content_score return loss, style_score, content_score ############################################################################################################ ############################################################################################################ # CREATE STYLE TRANFER",
"list of layers to be considered for calculation of Content and Style Loss",
"gram_style_features, content_features, num_content_layers, num_style_layers): generated_content_activations = generated_output_activations[:num_content_layers] generated_style_activations = generated_output_activations[num_content_layers:] style_weight, content_weight =",
"max_dim = 512 img = Image.open(path_to_img) img_size = max(img.size) scale = max_dim/img_size img",
"batch compute content and style features content_outputs = model(content_image) style_outputs = model(style_image) #",
"the style and content feature representations (from our specified intermediate layers) style_features, content_features",
"norm_means # In original paper, the initial stylized image is random matrix of",
"style and content feature representations from our model style_features = [ style_layer[0] for",
"Content and Style Loss content_layers = ['block3_conv3'] style_layers = ['block1_conv1','block2_conv2','block4_conv3'] num_content_layers = len(content_layers)",
"result as save_name = 'generated.jpg' # path to where Vgg19 model weight is",
"image is random matrix of same size as that of content image #",
"1] += 116.779 x[:, :, 2] += 123.68 x = x[:, :, ::-1]",
"image as kp_image # Keras is only used to load VGG19 model as",
"In original paper, the initial stylized image is random matrix of same size",
"tf from tensorflow.python.keras.preprocessing import image as kp_image # Keras is only used to",
"# numPy is used for manipulation of array of object i.e Image in",
"# Save the result as save_name = 'generated.jpg' # path to where Vgg19",
"vgg19 = get_model(content_layers,style_layers) # Get the style and content feature representations (from our",
"len(style_layers) # path where the content and style images are located content_path =",
"# perform the inverse of the preprocessiing step x[:, :, 0] += 103.939",
"= base_style.get_shape().as_list() gram_style = gram_matrix(base_style) # Original eqn as a constant to divide",
"in style_outputs[num_content_layers:] ] content_features = [ content_layer[0] for content_layer in content_outputs[:num_content_layers] ] return",
"stylized image # because it proved to help to stylize faster generated_image =",
"content_score = loss total_loss = total_loss.eval(session=sess) if total_loss < best_loss: # Update best",
"s_loss = sess.run(style_score) c_loss = sess.run(content_score) # print best loss print('best: iteration: ',",
"the content and style images are located content_path = 'content.jpg' style_path = 'style.jpg'",
"= 'content.jpg' style_path = 'style.jpg' # Save the result as save_name = 'generated.jpg'",
"= 'style.jpg' # Save the result as save_name = 'generated.jpg' # path to",
"layers weight_per_content_layer = 1.0 / float(num_content_layers) for target_content, comb_content in zip(content_features, generated_content_activations): temp",
"## ## # list of layers to be considered for calculation of Content",
"(width * height) ** 2) return tf.reduce_mean(tf.square(gram_style - gram_target)) / (channels**2 * width",
"to hold best image (i.e image with minimum loss) best_loss, best_img = float('inf'),",
"to the TF session which we created K.set_session(sess) model, vgg19 = get_model(content_layers,style_layers) #",
"TF session which we created K.set_session(sess) model, vgg19 = get_model(content_layers,style_layers) # Get the",
"* width * height) #(4.0 * (channels ** 2) * (width * height)",
"= -norm_means max_vals = 255 - norm_means # In original paper, the initial",
"model style_features = [ style_layer[0] for style_layer in style_outputs[num_content_layers:] ] content_features = [",
"3) convert it to (h, w, 3) temp_generated_image = sess.run(generated_image)[0] best_img = deprocess_img(temp_generated_image)",
"in later images content image was used instead on random values for first",
"in zip(content_features, generated_content_activations): temp = get_content_loss(comb_content[0], target_content) content_score += weight_per_content_layer* temp # Get",
"intermediate layers) style_features, content_features = get_feature_representations(model, content_path, style_path, num_content_layers) gram_style_features = [gram_matrix(style_feature) for",
"don't need to (or want to) train any layers of our pre-trained vgg",
"if total_loss < best_loss: # Update best loss and best image from total",
"dimension img = np.expand_dims(img, axis=0) # preprocess raw images to make it suitable",
"as tf from tensorflow.python.keras.preprocessing import image as kp_image # Keras is only used",
"sess.run(tf.global_variables_initializer()) sess.run(generated_image.initializer) # loading the weights again because tf.global_variables_initializer() resets the weights vgg19.load_weights(vgg_weights)",
"= max(img.size) scale = max_dim/img_size img = img.resize((round(img.size[0]*scale), round(img.size[1]*scale)), Image.ANTIALIAS) img = kp_image.img_to_array(img)",
"input tensor is a 3D array of size Nh x Nw X Nc",
"- gram_target)) / (channels**2 * width * height) #(4.0 * (channels ** 2)",
"hold a stylized/generated image during the training generated_image = tf.Variable(generated_image, dtype=tf.float32) model_outputs =",
"Load VGG19 model def get_model(content_layers,style_layers): # Load our model. We load pretrained VGG,",
"optimizer loss = compute_loss(model, loss_weights, model_outputs, gram_style_features, content_features, num_content_layers, num_style_layers) opt = tf.train.AdamOptimizer(learning_rate=9,",
"= generated_output_activations[num_content_layers:] style_weight, content_weight = loss_weights style_score = 0 content_score = 0 #",
"Model from keras import backend as K # pillow is used for loading",
"that of content image # but in later images content image was used",
"hold best image (i.e image with minimum loss) best_loss, best_img = float('inf'), None",
"get_feature_representations(model, content_path, style_path, num_content_layers) gram_style_features = [gram_matrix(style_feature) for style_feature in style_features] # VGG",
"gram_target): height, width, channels = base_style.get_shape().as_list() gram_style = gram_matrix(base_style) # Original eqn as",
"= total_loss # generated image is of shape (1, h, w, 3) convert",
"content_image = load_img(content_path) style_image = load_img(style_path) # batch compute content and style features",
"content_features = get_feature_representations(model, content_path, style_path, num_content_layers) gram_style_features = [gram_matrix(style_feature) for style_feature in style_features]",
"to help to stylize faster generated_image = load_img(content_path) # generated_image = np.random.randint(0,255, size=generated_image.shape)",
"* (channels ** 2) * (width * height) ** 2) ### Use to",
"import tensorflow as tf from tensorflow.python.keras.preprocessing import image as kp_image # Keras is",
"and content feature representations (from our specified intermediate layers) style_features, content_features = get_feature_representations(model,",
"to the tensor stylized image generated_image.assign(clipped) # Open the Tuple of tensors total_loss,",
"stylized image generated_image.assign(clipped) # Open the Tuple of tensors total_loss, style_score, content_score =",
"Create tensorflow variable to hold a stylized/generated image during the training generated_image =",
"every 100 iterations if (i+1)%100 == 0: output = Image.fromarray(best_img) output.save(str(i+1)+'-'+save_name) # after",
"= Image.open(path_to_img) img_size = max(img.size) scale = max_dim/img_size img = img.resize((round(img.size[0]*scale), round(img.size[1]*scale)), Image.ANTIALIAS)",
"style_outputs[num_content_layers:] ] content_features = [ content_layer[0] for content_layer in content_outputs[:num_content_layers] ] return style_features,",
"in zip(gram_style_features, generated_style_activations): temp = get_style_loss(comb_style[0], target_style) style_score += weight_per_style_layer * temp #",
"2) ### Use to pass content and style image through it def get_feature_representations(model,",
"= np.clip(x, 0, 255).astype('uint8') return x ############################################################################################################ ############################################################################################################ # Loss Function ############################################################################################################ ############################################################################################################",
"of VGG norm clipped = tf.clip_by_value(generated_image, min_vals, max_vals) # assign the clipped value",
"tensorflow variable to hold a stylized/generated image during the training generated_image = tf.Variable(generated_image,",
"############################################################################################################ ############################################################################################################ # UTILS ############################################################################################################ ############################################################################################################ def load_img(path_to_img): max_dim = 512 img =",
"because it proved to help to stylize faster generated_image = load_img(content_path) # generated_image",
"best image from total loss. best_loss = total_loss # generated image is of",
"a high level API to TensorFlow from keras.applications.vgg19 import VGG19 from keras.models import",
"False style_model_outputs = [vgg19.get_layer(name).output for name in style_layers] content_model_outputs = [vgg19.get_layer(name).output for name",
"compute content and style features content_outputs = model(content_image) style_outputs = model(style_image) # Get",
"style and content feature representations (from our specified intermediate layers) style_features, content_features =",
"best loss print('best: iteration: ', i ,'loss: ', total_loss ,' style_loss: ', s_loss,'",
"contribution of each loss layer weight_per_style_layer = 1.0 / float(num_style_layers) for target_style, comb_style",
"= ['block1_conv1','block2_conv2','block4_conv3'] num_content_layers = len(content_layers) num_style_layers = len(style_layers) # path where the content",
"need to broadcast the image array such that it has a batch dimension",
"# preprocess raw images to make it suitable to be used by VGG19",
"= tf.reshape(input_tensor, [-1, channels]) n = tf.shape(a)[0] # get gram matrix gram =",
"[gram_matrix(style_feature) for style_feature in style_features] # VGG default normalization norm_means = np.array([103.939, 116.779,",
"a, transpose_a=True) return gram def get_style_loss(base_style, gram_target): height, width, channels = base_style.get_shape().as_list() gram_style",
"instead on random values for first stylized image # because it proved to",
"= total_loss.eval(session=sess) if total_loss < best_loss: # Update best loss and best image",
"+= weight_per_content_layer* temp # Get total loss loss = style_weight*style_score + content_weight*content_score return",
"= model(generated_image) # weightages of each content and style images i.e alpha &",
"+ style_model_outputs # Build model return Model(inputs = vgg19.input, outputs = model_outputs), vgg19",
"temp_generated_image = sess.run(generated_image)[0] best_img = deprocess_img(temp_generated_image) s_loss = sess.run(style_score) c_loss = sess.run(content_score) #",
"get_style_loss(base_style, gram_target): height, width, channels = base_style.get_shape().as_list() gram_style = gram_matrix(base_style) # Original eqn",
"** 2) * (width * height) ** 2) return tf.reduce_mean(tf.square(gram_style - gram_target)) /",
"0 # Accumulate style losses from all layers # Here, we equally weight",
"= len(style_layers) # path where the content and style images are located content_path",
"get_content_loss(comb_content[0], target_content) content_score += weight_per_content_layer* temp # Get total loss loss = style_weight*style_score",
"(channels ** 2) * (width * height) ** 2) return tf.reduce_mean(tf.square(gram_style - gram_target))",
"content_layer in content_outputs[:num_content_layers] ] return style_features, content_features ### Total Loss def compute_loss(model, loss_weights,",
"are completed, close the TF session sess.close() return best_img, best_loss best, best_loss =",
"located content_path = 'content.jpg' style_path = 'style.jpg' # Save the result as save_name",
"float(num_content_layers) for target_content, comb_content in zip(content_features, generated_content_activations): temp = get_content_loss(comb_content[0], target_content) content_score +=",
"# pillow is used for loading and saving images from PIL import Image",
"used by VGG19 model out = tf.keras.applications.vgg19.preprocess_input(img) return tf.convert_to_tensor(out) def deprocess_img(processed_img): x =",
"= load_img(content_path) style_image = load_img(style_path) # batch compute content and style features content_outputs",
"to divide i.e 1/(4. * (channels ** 2) * (width * height) **",
"layer weight_per_style_layer = 1.0 / float(num_style_layers) for target_style, comb_style in zip(gram_style_features, generated_style_activations): temp",
"which we created K.set_session(sess) model, vgg19 = get_model(content_layers,style_layers) # Get the style and",
"but in later images content image was used instead on random values for",
"train any layers of our pre-trained vgg model, so we set it's trainable",
"opt = tf.train.AdamOptimizer(learning_rate=9, beta1=0.9, epsilon=1e-1).minimize( loss[0], var_list = [generated_image]) sess.run(tf.global_variables_initializer()) sess.run(generated_image.initializer) # loading",
"= gram_matrix(base_style) # Original eqn as a constant to divide i.e 1/(4. *",
"target_style) style_score += weight_per_style_layer * temp # Accumulate content losses from all layers",
"it to (h, w, 3) temp_generated_image = sess.run(generated_image)[0] best_img = deprocess_img(temp_generated_image) s_loss =",
"tensorflow session sess = tf.Session() # Assign keras back-end to the TF session",
"assign the clipped value to the tensor stylized image generated_image.assign(clipped) # Open the",
"100 iterations if (i+1)%100 == 0: output = Image.fromarray(best_img) output.save(str(i+1)+'-'+save_name) # after num_iterations",
"for name in content_layers] model_outputs = content_model_outputs + style_model_outputs # Build model return",
"norm_means = np.array([103.939, 116.779, 123.68]) min_vals = -norm_means max_vals = 255 - norm_means",
"pillow is used for loading and saving images from PIL import Image #",
"# Accumulate content losses from all layers weight_per_content_layer = 1.0 / float(num_content_layers) for",
"run_style_transfer(content_path, style_path, num_iterations=200, content_weight=0.1, style_weight=0.9): # Create a tensorflow session sess = tf.Session()",
"VGG default normalization norm_means = np.array([103.939, 116.779, 123.68]) min_vals = -norm_means max_vals =",
"content_model_outputs = [vgg19.get_layer(name).output for name in content_layers] model_outputs = content_model_outputs + style_model_outputs #",
"channels = base_style.get_shape().as_list() gram_style = gram_matrix(base_style) # Original eqn as a constant to",
"feature representations (from our specified intermediate layers) style_features, content_features = get_feature_representations(model, content_path, style_path,",
"c_loss = sess.run(content_score) # print best loss print('best: iteration: ', i ,'loss: ',",
"var_list = [generated_image]) sess.run(tf.global_variables_initializer()) sess.run(generated_image.initializer) # loading the weights again because tf.global_variables_initializer() resets",
"Fucntion def gram_matrix(input_tensor): # if input tensor is a 3D array of size",
"stylized image is random matrix of same size as that of content image",
"array of Nc x (Nh*Nw) channels = int(input_tensor.shape[-1]) a = tf.reshape(input_tensor, [-1, channels])",
"height) ** 2) ### Use to pass content and style image through it",
"= tf.train.AdamOptimizer(learning_rate=9, beta1=0.9, epsilon=1e-1).minimize( loss[0], var_list = [generated_image]) sess.run(tf.global_variables_initializer()) sess.run(generated_image.initializer) # loading the",
"get_feature_representations(model, content_path, style_path, num_content_layers): # Load our images in content_image = load_img(content_path) style_image",
"generated_style_activations): temp = get_style_loss(comb_style[0], target_style) style_score += weight_per_style_layer * temp # Accumulate content",
"preprocessiing step x[:, :, 0] += 103.939 x[:, :, 1] += 116.779 x[:,",
"Using Keras Load VGG19 model def get_model(content_layers,style_layers): # Load our model. We load",
"a = tf.reshape(input_tensor, [-1, channels]) n = tf.shape(a)[0] # get gram matrix gram",
"w, 3) temp_generated_image = sess.run(generated_image)[0] best_img = deprocess_img(temp_generated_image) s_loss = sess.run(style_score) c_loss =",
"print best loss print('best: iteration: ', i ,'loss: ', total_loss ,' style_loss: ',",
"= model(content_image) style_outputs = model(style_image) # Get the style and content feature representations",
"Here, we equally weight each contribution of each loss layer weight_per_style_layer = 1.0",
"Load our images in content_image = load_img(content_path) style_image = load_img(style_path) # batch compute",
"total_loss ,' style_loss: ', s_loss,' content_loss: ', c_loss) # Save image after every",
"style_weight, content_weight = loss_weights style_score = 0 content_score = 0 # Accumulate style",
"img = img.resize((round(img.size[0]*scale), round(img.size[1]*scale)), Image.ANTIALIAS) img = kp_image.img_to_array(img) # We need to broadcast",
"return tf.reduce_mean(tf.square(gram_style - gram_target)) / (channels**2 * width * height) #(4.0 * (channels",
"x[:, :, 0] += 103.939 x[:, :, 1] += 116.779 x[:, :, 2]",
"a batch dimension img = np.expand_dims(img, axis=0) # preprocess raw images to make",
"= tf.clip_by_value(generated_image, min_vals, max_vals) # assign the clipped value to the tensor stylized",
"tensor stylized image generated_image.assign(clipped) # Open the Tuple of tensors total_loss, style_score, content_score",
"to where Vgg19 model weight is located vgg_weights = \"vgg_weights/vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5\" ############################################################################################################ ############################################################################################################ #",
"sess.run(generated_image)[0] best_img = deprocess_img(temp_generated_image) s_loss = sess.run(style_score) c_loss = sess.run(content_score) # print best",
"of shape (1, h, w, 3) convert it to (h, w, 3) temp_generated_image",
"trainable to false. vgg19.trainable = False style_model_outputs = [vgg19.get_layer(name).output for name in style_layers]",
"loading the weights again because tf.global_variables_initializer() resets the weights vgg19.load_weights(vgg_weights) # Put loss",
"for calculation of Content and Style Loss content_layers = ['block3_conv3'] style_layers = ['block1_conv1','block2_conv2','block4_conv3']",
"Accumulate content losses from all layers weight_per_content_layer = 1.0 / float(num_content_layers) for target_content,",
"style_features] # VGG default normalization norm_means = np.array([103.939, 116.779, 123.68]) min_vals = -norm_means",
"from PIL import Image # numPy is used for manipulation of array of",
"our pre-trained vgg model, so we set it's trainable to false. vgg19.trainable =",
"Tuple of tensors total_loss, style_score, content_score = loss total_loss = total_loss.eval(session=sess) if total_loss",
"as save_name = 'generated.jpg' # path to where Vgg19 model weight is located",
"# Assign keras back-end to the TF session which we created K.set_session(sess) model,",
"sess.run(content_score) # print best loss print('best: iteration: ', i ,'loss: ', total_loss ,'",
"= 1.0 / float(num_style_layers) for target_style, comb_style in zip(gram_style_features, generated_style_activations): temp = get_style_loss(comb_style[0],",
"target_content, comb_content in zip(content_features, generated_content_activations): temp = get_content_loss(comb_content[0], target_content) content_score += weight_per_content_layer* temp",
"where the content and style images are located content_path = 'content.jpg' style_path =",
"temp = get_style_loss(comb_style[0], target_style) style_score += weight_per_style_layer * temp # Accumulate content losses",
"content_layers = ['block3_conv3'] style_layers = ['block1_conv1','block2_conv2','block4_conv3'] num_content_layers = len(content_layers) num_style_layers = len(style_layers) #",
"in range(num_iterations): # Do optimization sess.run(opt) # Make sure image values stays in",
"# generated_image = np.random.randint(0,255, size=generated_image.shape) # Create tensorflow variable to hold a stylized/generated",
"the range of max-min value of VGG norm clipped = tf.clip_by_value(generated_image, min_vals, max_vals)",
"img.resize((round(img.size[0]*scale), round(img.size[1]*scale)), Image.ANTIALIAS) img = kp_image.img_to_array(img) # We need to broadcast the image",
"is used for loading and saving images from PIL import Image # numPy",
"# Keras is only used to load VGG19 model as a high level",
"weight_per_style_layer * temp # Accumulate content losses from all layers weight_per_content_layer = 1.0",
"content_score += weight_per_content_layer* temp # Get total loss loss = style_weight*style_score + content_weight*content_score",
"= 'generated.jpg' # path to where Vgg19 model weight is located vgg_weights =",
"= [vgg19.get_layer(name).output for name in content_layers] model_outputs = content_model_outputs + style_model_outputs # Build",
"0 content_score = 0 # Accumulate style losses from all layers # Here,",
"= x[:, :, ::-1] x = np.clip(x, 0, 255).astype('uint8') return x ############################################################################################################ ############################################################################################################",
"Content Loss Function def get_content_loss(content, target): return tf.reduce_mean(tf.square(content - target)) /2 ### Style",
"= load_img(style_path) # batch compute content and style features content_outputs = model(content_image) style_outputs",
"comb_content in zip(content_features, generated_content_activations): temp = get_content_loss(comb_content[0], target_content) content_score += weight_per_content_layer* temp #",
"= [generated_image]) sess.run(tf.global_variables_initializer()) sess.run(generated_image.initializer) # loading the weights again because tf.global_variables_initializer() resets the",
"reshape it to a 2D array of Nc x (Nh*Nw) channels = int(input_tensor.shape[-1])",
"model, so we set it's trainable to false. vgg19.trainable = False style_model_outputs =",
"(style_weight, content_weight) # Create our optimizer loss = compute_loss(model, loss_weights, model_outputs, gram_style_features, content_features,",
"= tf.shape(a)[0] # get gram matrix gram = tf.matmul(a, a, transpose_a=True) return gram",
"model out = tf.keras.applications.vgg19.preprocess_input(img) return tf.convert_to_tensor(out) def deprocess_img(processed_img): x = processed_img.copy() # perform",
"include_top=False) # We don't need to (or want to) train any layers of",
"iteration: ', i ,'loss: ', total_loss ,' style_loss: ', s_loss,' content_loss: ', c_loss)",
"== 0: output = Image.fromarray(best_img) output.save(str(i+1)+'-'+save_name) # after num_iterations iterations are completed, close",
"* (width * height) ** 2) ### Use to pass content and style",
"w, 3) convert it to (h, w, 3) temp_generated_image = sess.run(generated_image)[0] best_img =",
"3) temp_generated_image = sess.run(generated_image)[0] best_img = deprocess_img(temp_generated_image) s_loss = sess.run(style_score) c_loss = sess.run(content_score)",
"to a 2D array of Nc x (Nh*Nw) channels = int(input_tensor.shape[-1]) a =",
"of tensors total_loss, style_score, content_score = loss total_loss = total_loss.eval(session=sess) if total_loss <",
"path to where Vgg19 model weight is located vgg_weights = \"vgg_weights/vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5\" ############################################################################################################ ############################################################################################################",
"get_style_loss(comb_style[0], target_style) style_score += weight_per_style_layer * temp # Accumulate content losses from all",
"K.set_session(sess) model, vgg19 = get_model(content_layers,style_layers) # Get the style and content feature representations",
"float(num_style_layers) for target_style, comb_style in zip(gram_style_features, generated_style_activations): temp = get_style_loss(comb_style[0], target_style) style_score +=",
"completed, close the TF session sess.close() return best_img, best_loss best, best_loss = run_style_transfer(content_path,",
"divide i.e 1/(4. * (channels ** 2) * (width * height) ** 2)",
"the inverse of the preprocessiing step x[:, :, 0] += 103.939 x[:, :,",
"############################################################################################################ def load_img(path_to_img): max_dim = 512 img = Image.open(path_to_img) img_size = max(img.size) scale",
"sess = tf.Session() # Assign keras back-end to the TF session which we",
"content_features = [ content_layer[0] for content_layer in content_outputs[:num_content_layers] ] return style_features, content_features ###",
"### Style Loss Fucntion def gram_matrix(input_tensor): # if input tensor is a 3D",
"alpha & beta loss_weights = (style_weight, content_weight) # Create our optimizer loss =",
"weight_per_content_layer* temp # Get total loss loss = style_weight*style_score + content_weight*content_score return loss,",
"Use to pass content and style image through it def get_feature_representations(model, content_path, style_path,",
"vgg19 = VGG19(weights=None, include_top=False) # We don't need to (or want to) train",
"style_layers] content_model_outputs = [vgg19.get_layer(name).output for name in content_layers] model_outputs = content_model_outputs + style_model_outputs",
"batch dimension img = np.expand_dims(img, axis=0) # preprocess raw images to make it",
"num_content_layers, num_style_layers) opt = tf.train.AdamOptimizer(learning_rate=9, beta1=0.9, epsilon=1e-1).minimize( loss[0], var_list = [generated_image]) sess.run(tf.global_variables_initializer()) sess.run(generated_image.initializer)",
"minimum loss) best_loss, best_img = float('inf'), None for i in range(num_iterations): # Do",
"np.expand_dims(img, axis=0) # preprocess raw images to make it suitable to be used",
"= vgg19.input, outputs = model_outputs), vgg19 def run_style_transfer(content_path, style_path, num_iterations=200, content_weight=0.1, style_weight=0.9): #",
"num_style_layers): generated_content_activations = generated_output_activations[:num_content_layers] generated_style_activations = generated_output_activations[num_content_layers:] style_weight, content_weight = loss_weights style_score =",
"image values stays in the range of max-min value of VGG norm clipped",
"(i+1)%100 == 0: output = Image.fromarray(best_img) output.save(str(i+1)+'-'+save_name) # after num_iterations iterations are completed,",
"= np.random.randint(0,255, size=generated_image.shape) # Create tensorflow variable to hold a stylized/generated image during",
"+= 123.68 x = x[:, :, ::-1] x = np.clip(x, 0, 255).astype('uint8') return",
"is a 3D array of size Nh x Nw X Nc # we",
"weights again because tf.global_variables_initializer() resets the weights vgg19.load_weights(vgg_weights) # Put loss as infinity",
"vgg19 def run_style_transfer(content_path, style_path, num_iterations=200, content_weight=0.1, style_weight=0.9): # Create a tensorflow session sess",
"num_content_layers, num_style_layers): generated_content_activations = generated_output_activations[:num_content_layers] generated_style_activations = generated_output_activations[num_content_layers:] style_weight, content_weight = loss_weights style_score",
"Nc x (Nh*Nw) channels = int(input_tensor.shape[-1]) a = tf.reshape(input_tensor, [-1, channels]) n =",
"value of VGG norm clipped = tf.clip_by_value(generated_image, min_vals, max_vals) # assign the clipped",
"< best_loss: # Update best loss and best image from total loss. best_loss",
"## # list of layers to be considered for calculation of Content and",
"num_content_layers) gram_style_features = [gram_matrix(style_feature) for style_feature in style_features] # VGG default normalization norm_means",
"array of size Nh x Nw X Nc # we reshape it to",
"range(num_iterations): # Do optimization sess.run(opt) # Make sure image values stays in the",
"compute_loss(model, loss_weights, model_outputs, gram_style_features, content_features, num_content_layers, num_style_layers) opt = tf.train.AdamOptimizer(learning_rate=9, beta1=0.9, epsilon=1e-1).minimize( loss[0],",
"-norm_means max_vals = 255 - norm_means # In original paper, the initial stylized",
"image with minimum loss) best_loss, best_img = float('inf'), None for i in range(num_iterations):",
"Total Loss def compute_loss(model, loss_weights, generated_output_activations, gram_style_features, content_features, num_content_layers, num_style_layers): generated_content_activations = generated_output_activations[:num_content_layers]",
"in content_image = load_img(content_path) style_image = load_img(style_path) # batch compute content and style",
"content_score ############################################################################################################ ############################################################################################################ # CREATE STYLE TRANFER ############################################################################################################ ############################################################################################################ # Using Keras Load",
"= processed_img.copy() # perform the inverse of the preprocessiing step x[:, :, 0]",
"############################################################################################################ ### Content Loss Function def get_content_loss(content, target): return tf.reduce_mean(tf.square(content - target)) /2",
"value to the tensor stylized image generated_image.assign(clipped) # Open the Tuple of tensors",
"print('best: iteration: ', i ,'loss: ', total_loss ,' style_loss: ', s_loss,' content_loss: ',",
"116.779 x[:, :, 2] += 123.68 x = x[:, :, ::-1] x =",
"values for first stylized image # because it proved to help to stylize",
"best loss and best image from total loss. best_loss = total_loss # generated",
"= 255 - norm_means # In original paper, the initial stylized image is",
"############################################################################################################ ############################################################################################################ ### Content Loss Function def get_content_loss(content, target): return tf.reduce_mean(tf.square(content - target))",
"] content_features = [ content_layer[0] for content_layer in content_outputs[:num_content_layers] ] return style_features, content_features",
"TRANFER ############################################################################################################ ############################################################################################################ # Using Keras Load VGG19 model def get_model(content_layers,style_layers): # Load",
"for style_feature in style_features] # VGG default normalization norm_means = np.array([103.939, 116.779, 123.68])",
"target_style, comb_style in zip(gram_style_features, generated_style_activations): temp = get_style_loss(comb_style[0], target_style) style_score += weight_per_style_layer *",
"deprocess_img(temp_generated_image) s_loss = sess.run(style_score) c_loss = sess.run(content_score) # print best loss print('best: iteration:",
"x[:, :, ::-1] x = np.clip(x, 0, 255).astype('uint8') return x ############################################################################################################ ############################################################################################################ #",
"base_style.get_shape().as_list() gram_style = gram_matrix(base_style) # Original eqn as a constant to divide i.e",
"= False style_model_outputs = [vgg19.get_layer(name).output for name in style_layers] content_model_outputs = [vgg19.get_layer(name).output for",
"Image.ANTIALIAS) img = kp_image.img_to_array(img) # We need to broadcast the image array such",
"gram_matrix(base_style) # Original eqn as a constant to divide i.e 1/(4. * (channels",
"compute_loss(model, loss_weights, generated_output_activations, gram_style_features, content_features, num_content_layers, num_style_layers): generated_content_activations = generated_output_activations[:num_content_layers] generated_style_activations = generated_output_activations[num_content_layers:]",
"Do optimization sess.run(opt) # Make sure image values stays in the range of",
"############################################################################################################ ############################################################################################################ # CREATE STYLE TRANFER ############################################################################################################ ############################################################################################################ # Using Keras Load VGG19",
"training starts and Create a variable to hold best image (i.e image with",
"are located content_path = 'content.jpg' style_path = 'style.jpg' # Save the result as",
"PIL import Image # numPy is used for manipulation of array of object",
"def get_feature_representations(model, content_path, style_path, num_content_layers): # Load our images in content_image = load_img(content_path)",
"faster generated_image = load_img(content_path) # generated_image = np.random.randint(0,255, size=generated_image.shape) # Create tensorflow variable",
"# assign the clipped value to the tensor stylized image generated_image.assign(clipped) # Open",
"+= 103.939 x[:, :, 1] += 116.779 x[:, :, 2] += 123.68 x",
"= [ content_layer[0] for content_layer in content_outputs[:num_content_layers] ] return style_features, content_features ### Total",
"image (i.e image with minimum loss) best_loss, best_img = float('inf'), None for i",
"= compute_loss(model, loss_weights, model_outputs, gram_style_features, content_features, num_content_layers, num_style_layers) opt = tf.train.AdamOptimizer(learning_rate=9, beta1=0.9, epsilon=1e-1).minimize(",
"= tf.Session() # Assign keras back-end to the TF session which we created",
"None for i in range(num_iterations): # Do optimization sess.run(opt) # Make sure image",
"for i in range(num_iterations): # Do optimization sess.run(opt) # Make sure image values",
"loss) best_loss, best_img = float('inf'), None for i in range(num_iterations): # Do optimization",
"from our model style_features = [ style_layer[0] for style_layer in style_outputs[num_content_layers:] ] content_features",
"level API to TensorFlow from keras.applications.vgg19 import VGG19 from keras.models import Model from",
"return tf.reduce_mean(tf.square(content - target)) /2 ### Style Loss Fucntion def gram_matrix(input_tensor): # if",
"loss layer weight_per_style_layer = 1.0 / float(num_style_layers) for target_style, comb_style in zip(gram_style_features, generated_style_activations):",
"['block3_conv3'] style_layers = ['block1_conv1','block2_conv2','block4_conv3'] num_content_layers = len(content_layers) num_style_layers = len(style_layers) # path where",
"style_feature in style_features] # VGG default normalization norm_means = np.array([103.939, 116.779, 123.68]) min_vals",
"load_img(content_path) # generated_image = np.random.randint(0,255, size=generated_image.shape) # Create tensorflow variable to hold a",
"zip(gram_style_features, generated_style_activations): temp = get_style_loss(comb_style[0], target_style) style_score += weight_per_style_layer * temp # Accumulate",
"We don't need to (or want to) train any layers of our pre-trained",
"Model(inputs = vgg19.input, outputs = model_outputs), vgg19 def run_style_transfer(content_path, style_path, num_iterations=200, content_weight=0.1, style_weight=0.9):",
"images from PIL import Image # numPy is used for manipulation of array",
"random values for first stylized image # because it proved to help to",
"= (style_weight, content_weight) # Create our optimizer loss = compute_loss(model, loss_weights, model_outputs, gram_style_features,",
"style_layer[0] for style_layer in style_outputs[num_content_layers:] ] content_features = [ content_layer[0] for content_layer in",
"numPy is used for manipulation of array of object i.e Image in our",
"best_loss = total_loss # generated image is of shape (1, h, w, 3)",
"content_model_outputs + style_model_outputs # Build model return Model(inputs = vgg19.input, outputs = model_outputs),",
"from all layers weight_per_content_layer = 1.0 / float(num_content_layers) for target_content, comb_content in zip(content_features,",
"as np ## ## ## # list of layers to be considered for",
"gram = tf.matmul(a, a, transpose_a=True) return gram def get_style_loss(base_style, gram_target): height, width, channels",
"content_weight*content_score return loss, style_score, content_score ############################################################################################################ ############################################################################################################ # CREATE STYLE TRANFER ############################################################################################################ ############################################################################################################",
"clipped = tf.clip_by_value(generated_image, min_vals, max_vals) # assign the clipped value to the tensor",
"import Image # numPy is used for manipulation of array of object i.e",
"during the training generated_image = tf.Variable(generated_image, dtype=tf.float32) model_outputs = model(generated_image) # weightages of",
"tf.keras.applications.vgg19.preprocess_input(img) return tf.convert_to_tensor(out) def deprocess_img(processed_img): x = processed_img.copy() # perform the inverse of",
"VGG, trained on imagenet data vgg19 = VGG19(weights=None, include_top=False) # We don't need",
"normalization norm_means = np.array([103.939, 116.779, 123.68]) min_vals = -norm_means max_vals = 255 -",
"tensors total_loss, style_score, content_score = loss total_loss = total_loss.eval(session=sess) if total_loss < best_loss:",
"x = processed_img.copy() # perform the inverse of the preprocessiing step x[:, :,",
"height) ** 2) return tf.reduce_mean(tf.square(gram_style - gram_target)) / (channels**2 * width * height)",
"need to (or want to) train any layers of our pre-trained vgg model,",
"keras back-end to the TF session which we created K.set_session(sess) model, vgg19 =",
"all layers # Here, we equally weight each contribution of each loss layer",
"X Nc # we reshape it to a 2D array of Nc x",
"tf.reduce_mean(tf.square(content - target)) /2 ### Style Loss Fucntion def gram_matrix(input_tensor): # if input",
"for content_layer in content_outputs[:num_content_layers] ] return style_features, content_features ### Total Loss def compute_loss(model,",
"stylize faster generated_image = load_img(content_path) # generated_image = np.random.randint(0,255, size=generated_image.shape) # Create tensorflow",
"def load_img(path_to_img): max_dim = 512 img = Image.open(path_to_img) img_size = max(img.size) scale =",
"get_content_loss(content, target): return tf.reduce_mean(tf.square(content - target)) /2 ### Style Loss Fucntion def gram_matrix(input_tensor):",
"total loss. best_loss = total_loss # generated image is of shape (1, h,",
"content and style image through it def get_feature_representations(model, content_path, style_path, num_content_layers): # Load",
"pre-trained vgg model, so we set it's trainable to false. vgg19.trainable = False",
"weights vgg19.load_weights(vgg_weights) # Put loss as infinity before training starts and Create a",
"save_name = 'generated.jpg' # path to where Vgg19 model weight is located vgg_weights",
"loss. best_loss = total_loss # generated image is of shape (1, h, w,",
"before training starts and Create a variable to hold best image (i.e image",
"variable to hold a stylized/generated image during the training generated_image = tf.Variable(generated_image, dtype=tf.float32)",
"# but in later images content image was used instead on random values",
"style losses from all layers # Here, we equally weight each contribution of",
"= sess.run(style_score) c_loss = sess.run(content_score) # print best loss print('best: iteration: ', i",
"Original eqn as a constant to divide i.e 1/(4. * (channels ** 2)",
"numpy as np ## ## ## # list of layers to be considered",
"### Content Loss Function def get_content_loss(content, target): return tf.reduce_mean(tf.square(content - target)) /2 ###",
"of layers to be considered for calculation of Content and Style Loss content_layers",
"layers # Here, we equally weight each contribution of each loss layer weight_per_style_layer",
"/ float(num_content_layers) for target_content, comb_content in zip(content_features, generated_content_activations): temp = get_content_loss(comb_content[0], target_content) content_score",
"vgg_weights = \"vgg_weights/vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5\" ############################################################################################################ ############################################################################################################ # UTILS ############################################################################################################ ############################################################################################################ def load_img(path_to_img): max_dim =",
"of the preprocessiing step x[:, :, 0] += 103.939 x[:, :, 1] +=",
"model, vgg19 = get_model(content_layers,style_layers) # Get the style and content feature representations (from",
"import Model from keras import backend as K # pillow is used for",
"array of object i.e Image in our case import numpy as np ##",
"image after every 100 iterations if (i+1)%100 == 0: output = Image.fromarray(best_img) output.save(str(i+1)+'-'+save_name)",
"+ content_weight*content_score return loss, style_score, content_score ############################################################################################################ ############################################################################################################ # CREATE STYLE TRANFER ############################################################################################################",
"case import numpy as np ## ## ## # list of layers to",
"layers to be considered for calculation of Content and Style Loss content_layers =",
"2) * (width * height) ** 2) return tf.reduce_mean(tf.square(gram_style - gram_target)) / (channels**2",
"# Create tensorflow variable to hold a stylized/generated image during the training generated_image",
"output.save(str(i+1)+'-'+save_name) # after num_iterations iterations are completed, close the TF session sess.close() return",
"(Nh*Nw) channels = int(input_tensor.shape[-1]) a = tf.reshape(input_tensor, [-1, channels]) n = tf.shape(a)[0] #",
"gram_style_features, content_features, num_content_layers, num_style_layers) opt = tf.train.AdamOptimizer(learning_rate=9, beta1=0.9, epsilon=1e-1).minimize( loss[0], var_list = [generated_image])",
"weightages of each content and style images i.e alpha & beta loss_weights =",
":, 1] += 116.779 x[:, :, 2] += 123.68 x = x[:, :,",
"num_style_layers) opt = tf.train.AdamOptimizer(learning_rate=9, beta1=0.9, epsilon=1e-1).minimize( loss[0], var_list = [generated_image]) sess.run(tf.global_variables_initializer()) sess.run(generated_image.initializer) #",
"beta1=0.9, epsilon=1e-1).minimize( loss[0], var_list = [generated_image]) sess.run(tf.global_variables_initializer()) sess.run(generated_image.initializer) # loading the weights again",
"generated_output_activations, gram_style_features, content_features, num_content_layers, num_style_layers): generated_content_activations = generated_output_activations[:num_content_layers] generated_style_activations = generated_output_activations[num_content_layers:] style_weight, content_weight",
"optimization sess.run(opt) # Make sure image values stays in the range of max-min",
"for loading and saving images from PIL import Image # numPy is used",
"# Load our model. We load pretrained VGG, trained on imagenet data vgg19",
"to broadcast the image array such that it has a batch dimension img",
"if input tensor is a 3D array of size Nh x Nw X",
"name in content_layers] model_outputs = content_model_outputs + style_model_outputs # Build model return Model(inputs",
"Loss Fucntion def gram_matrix(input_tensor): # if input tensor is a 3D array of",
"it def get_feature_representations(model, content_path, style_path, num_content_layers): # Load our images in content_image =",
"# we reshape it to a 2D array of Nc x (Nh*Nw) channels",
"matrix gram = tf.matmul(a, a, transpose_a=True) return gram def get_style_loss(base_style, gram_target): height, width,",
"vgg19.trainable = False style_model_outputs = [vgg19.get_layer(name).output for name in style_layers] content_model_outputs = [vgg19.get_layer(name).output",
"style_path = 'style.jpg' # Save the result as save_name = 'generated.jpg' # path",
"import image as kp_image # Keras is only used to load VGG19 model",
"after num_iterations iterations are completed, close the TF session sess.close() return best_img, best_loss",
"= get_style_loss(comb_style[0], target_style) style_score += weight_per_style_layer * temp # Accumulate content losses from",
"Make sure image values stays in the range of max-min value of VGG",
"it proved to help to stylize faster generated_image = load_img(content_path) # generated_image =",
"* (width * height) ** 2) return tf.reduce_mean(tf.square(gram_style - gram_target)) / (channels**2 *",
"stylized/generated image during the training generated_image = tf.Variable(generated_image, dtype=tf.float32) model_outputs = model(generated_image) #",
"and Create a variable to hold best image (i.e image with minimum loss)",
"best_loss: # Update best loss and best image from total loss. best_loss =",
"content_outputs = model(content_image) style_outputs = model(style_image) # Get the style and content feature",
"** 2) * (width * height) ** 2) ### Use to pass content",
"load_img(path_to_img): max_dim = 512 img = Image.open(path_to_img) img_size = max(img.size) scale = max_dim/img_size",
"model. We load pretrained VGG, trained on imagenet data vgg19 = VGG19(weights=None, include_top=False)",
"it suitable to be used by VGG19 model out = tf.keras.applications.vgg19.preprocess_input(img) return tf.convert_to_tensor(out)",
"best_img = deprocess_img(temp_generated_image) s_loss = sess.run(style_score) c_loss = sess.run(content_score) # print best loss",
"= img.resize((round(img.size[0]*scale), round(img.size[1]*scale)), Image.ANTIALIAS) img = kp_image.img_to_array(img) # We need to broadcast the",
"2) * (width * height) ** 2) ### Use to pass content and",
"tf.Variable(generated_image, dtype=tf.float32) model_outputs = model(generated_image) # weightages of each content and style images",
"best_loss, best_img = float('inf'), None for i in range(num_iterations): # Do optimization sess.run(opt)",
"s_loss,' content_loss: ', c_loss) # Save image after every 100 iterations if (i+1)%100",
"** 2) return tf.reduce_mean(tf.square(gram_style - gram_target)) / (channels**2 * width * height) #(4.0",
"of content image # but in later images content image was used instead",
"style features content_outputs = model(content_image) style_outputs = model(style_image) # Get the style and",
"123.68]) min_vals = -norm_means max_vals = 255 - norm_means # In original paper,",
"loading and saving images from PIL import Image # numPy is used for",
"in our case import numpy as np ## ## ## # list of",
"# path to where Vgg19 model weight is located vgg_weights = \"vgg_weights/vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5\" ############################################################################################################",
"representations from our model style_features = [ style_layer[0] for style_layer in style_outputs[num_content_layers:] ]",
"object i.e Image in our case import numpy as np ## ## ##",
"high level API to TensorFlow from keras.applications.vgg19 import VGG19 from keras.models import Model",
"# path where the content and style images are located content_path = 'content.jpg'",
"# batch compute content and style features content_outputs = model(content_image) style_outputs = model(style_image)",
"used to load VGG19 model as a high level API to TensorFlow from",
"Open the Tuple of tensors total_loss, style_score, content_score = loss total_loss = total_loss.eval(session=sess)",
"keras import backend as K # pillow is used for loading and saving",
"& beta loss_weights = (style_weight, content_weight) # Create our optimizer loss = compute_loss(model,",
"weight is located vgg_weights = \"vgg_weights/vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5\" ############################################################################################################ ############################################################################################################ # UTILS ############################################################################################################ ############################################################################################################ def",
"random matrix of same size as that of content image # but in",
"a stylized/generated image during the training generated_image = tf.Variable(generated_image, dtype=tf.float32) model_outputs = model(generated_image)",
"x (Nh*Nw) channels = int(input_tensor.shape[-1]) a = tf.reshape(input_tensor, [-1, channels]) n = tf.shape(a)[0]",
"model weight is located vgg_weights = \"vgg_weights/vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5\" ############################################################################################################ ############################################################################################################ # UTILS ############################################################################################################ ############################################################################################################",
"Nw X Nc # we reshape it to a 2D array of Nc",
"= VGG19(weights=None, include_top=False) # We don't need to (or want to) train any",
"def run_style_transfer(content_path, style_path, num_iterations=200, content_weight=0.1, style_weight=0.9): # Create a tensorflow session sess =",
"on random values for first stylized image # because it proved to help",
"image # but in later images content image was used instead on random",
"suitable to be used by VGG19 model out = tf.keras.applications.vgg19.preprocess_input(img) return tf.convert_to_tensor(out) def",
"target_content) content_score += weight_per_content_layer* temp # Get total loss loss = style_weight*style_score +",
"of our pre-trained vgg model, so we set it's trainable to false. vgg19.trainable",
"vgg19.input, outputs = model_outputs), vgg19 def run_style_transfer(content_path, style_path, num_iterations=200, content_weight=0.1, style_weight=0.9): # Create",
"sess.run(opt) # Make sure image values stays in the range of max-min value",
"- target)) /2 ### Style Loss Fucntion def gram_matrix(input_tensor): # if input tensor",
"model(generated_image) # weightages of each content and style images i.e alpha & beta",
"temp = get_content_loss(comb_content[0], target_content) content_score += weight_per_content_layer* temp # Get total loss loss",
"again because tf.global_variables_initializer() resets the weights vgg19.load_weights(vgg_weights) # Put loss as infinity before",
"the tensor stylized image generated_image.assign(clipped) # Open the Tuple of tensors total_loss, style_score,",
"style_layers = ['block1_conv1','block2_conv2','block4_conv3'] num_content_layers = len(content_layers) num_style_layers = len(style_layers) # path where the",
"target): return tf.reduce_mean(tf.square(content - target)) /2 ### Style Loss Fucntion def gram_matrix(input_tensor): #",
"i ,'loss: ', total_loss ,' style_loss: ', s_loss,' content_loss: ', c_loss) # Save",
"= sess.run(content_score) # print best loss print('best: iteration: ', i ,'loss: ', total_loss",
"return style_features, content_features ### Total Loss def compute_loss(model, loss_weights, generated_output_activations, gram_style_features, content_features, num_content_layers,",
"session sess = tf.Session() # Assign keras back-end to the TF session which",
"model_outputs, gram_style_features, content_features, num_content_layers, num_style_layers) opt = tf.train.AdamOptimizer(learning_rate=9, beta1=0.9, epsilon=1e-1).minimize( loss[0], var_list =",
"the initial stylized image is random matrix of same size as that of",
"[generated_image]) sess.run(tf.global_variables_initializer()) sess.run(generated_image.initializer) # loading the weights again because tf.global_variables_initializer() resets the weights",
"inverse of the preprocessiing step x[:, :, 0] += 103.939 x[:, :, 1]",
"eqn as a constant to divide i.e 1/(4. * (channels ** 2) *",
"# Update best loss and best image from total loss. best_loss = total_loss",
"', total_loss ,' style_loss: ', s_loss,' content_loss: ', c_loss) # Save image after",
"model(style_image) # Get the style and content feature representations from our model style_features",
"vgg model, so we set it's trainable to false. vgg19.trainable = False style_model_outputs",
"= tf.keras.applications.vgg19.preprocess_input(img) return tf.convert_to_tensor(out) def deprocess_img(processed_img): x = processed_img.copy() # perform the inverse",
"style_path, num_content_layers) gram_style_features = [gram_matrix(style_feature) for style_feature in style_features] # VGG default normalization",
"= \"vgg_weights/vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5\" ############################################################################################################ ############################################################################################################ # UTILS ############################################################################################################ ############################################################################################################ def load_img(path_to_img): max_dim = 512",
"content feature representations from our model style_features = [ style_layer[0] for style_layer in",
"to TensorFlow from keras.applications.vgg19 import VGG19 from keras.models import Model from keras import",
"tf.reshape(input_tensor, [-1, channels]) n = tf.shape(a)[0] # get gram matrix gram = tf.matmul(a,",
"style_features = [ style_layer[0] for style_layer in style_outputs[num_content_layers:] ] content_features = [ content_layer[0]",
"total_loss # generated image is of shape (1, h, w, 3) convert it",
"### Use to pass content and style image through it def get_feature_representations(model, content_path,",
"be used by VGG19 model out = tf.keras.applications.vgg19.preprocess_input(img) return tf.convert_to_tensor(out) def deprocess_img(processed_img): x",
"max_vals) # assign the clipped value to the tensor stylized image generated_image.assign(clipped) #",
"* height) ** 2) return tf.reduce_mean(tf.square(gram_style - gram_target)) / (channels**2 * width *",
"manipulation of array of object i.e Image in our case import numpy as",
"loss print('best: iteration: ', i ,'loss: ', total_loss ,' style_loss: ', s_loss,' content_loss:",
"channels]) n = tf.shape(a)[0] # get gram matrix gram = tf.matmul(a, a, transpose_a=True)",
"# list of layers to be considered for calculation of Content and Style",
"zip(content_features, generated_content_activations): temp = get_content_loss(comb_content[0], target_content) content_score += weight_per_content_layer* temp # Get total",
"Image # numPy is used for manipulation of array of object i.e Image",
"#(4.0 * (channels ** 2) * (width * height) ** 2) ### Use",
"We load pretrained VGG, trained on imagenet data vgg19 = VGG19(weights=None, include_top=False) #",
"constant to divide i.e 1/(4. * (channels ** 2) * (width * height)",
"* temp # Accumulate content losses from all layers weight_per_content_layer = 1.0 /",
"Function ############################################################################################################ ############################################################################################################ ### Content Loss Function def get_content_loss(content, target): return tf.reduce_mean(tf.square(content -",
"(1, h, w, 3) convert it to (h, w, 3) temp_generated_image = sess.run(generated_image)[0]",
"= max_dim/img_size img = img.resize((round(img.size[0]*scale), round(img.size[1]*scale)), Image.ANTIALIAS) img = kp_image.img_to_array(img) # We need",
"img = kp_image.img_to_array(img) # We need to broadcast the image array such that",
"get gram matrix gram = tf.matmul(a, a, transpose_a=True) return gram def get_style_loss(base_style, gram_target):",
"any layers of our pre-trained vgg model, so we set it's trainable to",
"Get total loss loss = style_weight*style_score + content_weight*content_score return loss, style_score, content_score ############################################################################################################",
"temp # Accumulate content losses from all layers weight_per_content_layer = 1.0 / float(num_content_layers)",
"= loss total_loss = total_loss.eval(session=sess) if total_loss < best_loss: # Update best loss",
"K # pillow is used for loading and saving images from PIL import",
"/ float(num_style_layers) for target_style, comb_style in zip(gram_style_features, generated_style_activations): temp = get_style_loss(comb_style[0], target_style) style_score",
"# loading the weights again because tf.global_variables_initializer() resets the weights vgg19.load_weights(vgg_weights) # Put",
"epsilon=1e-1).minimize( loss[0], var_list = [generated_image]) sess.run(tf.global_variables_initializer()) sess.run(generated_image.initializer) # loading the weights again because",
"content_weight=0.1, style_weight=0.9): # Create a tensorflow session sess = tf.Session() # Assign keras",
":, 2] += 123.68 x = x[:, :, ::-1] x = np.clip(x, 0,",
"weight_per_style_layer = 1.0 / float(num_style_layers) for target_style, comb_style in zip(gram_style_features, generated_style_activations): temp =",
"it has a batch dimension img = np.expand_dims(img, axis=0) # preprocess raw images",
"in style_features] # VGG default normalization norm_means = np.array([103.939, 116.779, 123.68]) min_vals =",
"= sess.run(generated_image)[0] best_img = deprocess_img(temp_generated_image) s_loss = sess.run(style_score) c_loss = sess.run(content_score) # print",
"tf.convert_to_tensor(out) def deprocess_img(processed_img): x = processed_img.copy() # perform the inverse of the preprocessiing",
"return x ############################################################################################################ ############################################################################################################ # Loss Function ############################################################################################################ ############################################################################################################ ### Content Loss Function",
"Loss content_layers = ['block3_conv3'] style_layers = ['block1_conv1','block2_conv2','block4_conv3'] num_content_layers = len(content_layers) num_style_layers = len(style_layers)",
"= load_img(content_path) # generated_image = np.random.randint(0,255, size=generated_image.shape) # Create tensorflow variable to hold",
"our model style_features = [ style_layer[0] for style_layer in style_outputs[num_content_layers:] ] content_features =",
"= generated_output_activations[:num_content_layers] generated_style_activations = generated_output_activations[num_content_layers:] style_weight, content_weight = loss_weights style_score = 0 content_score",
"in the range of max-min value of VGG norm clipped = tf.clip_by_value(generated_image, min_vals,",
"i.e 1/(4. * (channels ** 2) * (width * height) ** 2) return",
"loss as infinity before training starts and Create a variable to hold best",
"image # because it proved to help to stylize faster generated_image = load_img(content_path)",
"= model(style_image) # Get the style and content feature representations from our model",
"layers) style_features, content_features = get_feature_representations(model, content_path, style_path, num_content_layers) gram_style_features = [gram_matrix(style_feature) for style_feature",
"generated_content_activations): temp = get_content_loss(comb_content[0], target_content) content_score += weight_per_content_layer* temp # Get total loss",
"num_content_layers = len(content_layers) num_style_layers = len(style_layers) # path where the content and style",
"Image.open(path_to_img) img_size = max(img.size) scale = max_dim/img_size img = img.resize((round(img.size[0]*scale), round(img.size[1]*scale)), Image.ANTIALIAS) img",
"x = x[:, :, ::-1] x = np.clip(x, 0, 255).astype('uint8') return x ############################################################################################################",
"first stylized image # because it proved to help to stylize faster generated_image",
"and best image from total loss. best_loss = total_loss # generated image is",
"backend as K # pillow is used for loading and saving images from",
"because tf.global_variables_initializer() resets the weights vgg19.load_weights(vgg_weights) # Put loss as infinity before training",
"+= weight_per_style_layer * temp # Accumulate content losses from all layers weight_per_content_layer =",
"image is of shape (1, h, w, 3) convert it to (h, w,",
":, ::-1] x = np.clip(x, 0, 255).astype('uint8') return x ############################################################################################################ ############################################################################################################ # Loss",
"VGG norm clipped = tf.clip_by_value(generated_image, min_vals, max_vals) # assign the clipped value to",
"scale = max_dim/img_size img = img.resize((round(img.size[0]*scale), round(img.size[1]*scale)), Image.ANTIALIAS) img = kp_image.img_to_array(img) # We",
"weight each contribution of each loss layer weight_per_style_layer = 1.0 / float(num_style_layers) for",
"losses from all layers # Here, we equally weight each contribution of each",
"[vgg19.get_layer(name).output for name in content_layers] model_outputs = content_model_outputs + style_model_outputs # Build model",
"is of shape (1, h, w, 3) convert it to (h, w, 3)",
"Vgg19 model weight is located vgg_weights = \"vgg_weights/vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5\" ############################################################################################################ ############################################################################################################ # UTILS ############################################################################################################",
"def get_style_loss(base_style, gram_target): height, width, channels = base_style.get_shape().as_list() gram_style = gram_matrix(base_style) # Original",
"Style Loss Fucntion def gram_matrix(input_tensor): # if input tensor is a 3D array",
"style image through it def get_feature_representations(model, content_path, style_path, num_content_layers): # Load our images",
"content_path, style_path, num_content_layers): # Load our images in content_image = load_img(content_path) style_image =",
"min_vals = -norm_means max_vals = 255 - norm_means # In original paper, the",
"np.array([103.939, 116.779, 123.68]) min_vals = -norm_means max_vals = 255 - norm_means # In",
"i.e Image in our case import numpy as np ## ## ## #",
"return Model(inputs = vgg19.input, outputs = model_outputs), vgg19 def run_style_transfer(content_path, style_path, num_iterations=200, content_weight=0.1,",
"specified intermediate layers) style_features, content_features = get_feature_representations(model, content_path, style_path, num_content_layers) gram_style_features = [gram_matrix(style_feature)",
"proved to help to stylize faster generated_image = load_img(content_path) # generated_image = np.random.randint(0,255,",
"a 3D array of size Nh x Nw X Nc # we reshape",
"to false. vgg19.trainable = False style_model_outputs = [vgg19.get_layer(name).output for name in style_layers] content_model_outputs",
"used instead on random values for first stylized image # because it proved",
"image generated_image.assign(clipped) # Open the Tuple of tensors total_loss, style_score, content_score = loss",
"# Save image after every 100 iterations if (i+1)%100 == 0: output =",
"style_path, num_content_layers): # Load our images in content_image = load_img(content_path) style_image = load_img(style_path)",
"tensorflow.python.keras.preprocessing import image as kp_image # Keras is only used to load VGG19",
"total_loss, style_score, content_score = loss total_loss = total_loss.eval(session=sess) if total_loss < best_loss: #",
"Style Loss content_layers = ['block3_conv3'] style_layers = ['block1_conv1','block2_conv2','block4_conv3'] num_content_layers = len(content_layers) num_style_layers =",
"# generated image is of shape (1, h, w, 3) convert it to",
"', i ,'loss: ', total_loss ,' style_loss: ', s_loss,' content_loss: ', c_loss) #",
"Loss Function def get_content_loss(content, target): return tf.reduce_mean(tf.square(content - target)) /2 ### Style Loss",
"equally weight each contribution of each loss layer weight_per_style_layer = 1.0 / float(num_style_layers)",
"gram_style = gram_matrix(base_style) # Original eqn as a constant to divide i.e 1/(4.",
"comb_style in zip(gram_style_features, generated_style_activations): temp = get_style_loss(comb_style[0], target_style) style_score += weight_per_style_layer * temp",
"(h, w, 3) temp_generated_image = sess.run(generated_image)[0] best_img = deprocess_img(temp_generated_image) s_loss = sess.run(style_score) c_loss",
"= get_model(content_layers,style_layers) # Get the style and content feature representations (from our specified",
"############################################################################################################ ############################################################################################################ # Loss Function ############################################################################################################ ############################################################################################################ ### Content Loss Function def get_content_loss(content,",
"(or want to) train any layers of our pre-trained vgg model, so we",
"content and style images i.e alpha & beta loss_weights = (style_weight, content_weight) #",
"img_size = max(img.size) scale = max_dim/img_size img = img.resize((round(img.size[0]*scale), round(img.size[1]*scale)), Image.ANTIALIAS) img =",
"style_weight=0.9): # Create a tensorflow session sess = tf.Session() # Assign keras back-end",
"116.779, 123.68]) min_vals = -norm_means max_vals = 255 - norm_means # In original",
"x[:, :, 2] += 123.68 x = x[:, :, ::-1] x = np.clip(x,",
"style_image = load_img(style_path) # batch compute content and style features content_outputs = model(content_image)",
"load_img(style_path) # batch compute content and style features content_outputs = model(content_image) style_outputs =",
"############################################################################################################ # Using Keras Load VGG19 model def get_model(content_layers,style_layers): # Load our model.",
"of same size as that of content image # but in later images",
"= style_weight*style_score + content_weight*content_score return loss, style_score, content_score ############################################################################################################ ############################################################################################################ # CREATE STYLE",
"255 - norm_means # In original paper, the initial stylized image is random",
"x[:, :, 1] += 116.779 x[:, :, 2] += 123.68 x = x[:,",
"name in style_layers] content_model_outputs = [vgg19.get_layer(name).output for name in content_layers] model_outputs = content_model_outputs",
"for first stylized image # because it proved to help to stylize faster",
"= float('inf'), None for i in range(num_iterations): # Do optimization sess.run(opt) # Make",
"= [gram_matrix(style_feature) for style_feature in style_features] # VGG default normalization norm_means = np.array([103.939,",
"size=generated_image.shape) # Create tensorflow variable to hold a stylized/generated image during the training",
"and style images are located content_path = 'content.jpg' style_path = 'style.jpg' # Save",
"# if input tensor is a 3D array of size Nh x Nw",
"VGG19 model out = tf.keras.applications.vgg19.preprocess_input(img) return tf.convert_to_tensor(out) def deprocess_img(processed_img): x = processed_img.copy() #",
"loss_weights, generated_output_activations, gram_style_features, content_features, num_content_layers, num_style_layers): generated_content_activations = generated_output_activations[:num_content_layers] generated_style_activations = generated_output_activations[num_content_layers:] style_weight,",
"and style image through it def get_feature_representations(model, content_path, style_path, num_content_layers): # Load our",
"'generated.jpg' # path to where Vgg19 model weight is located vgg_weights = \"vgg_weights/vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5\"",
"Assign keras back-end to the TF session which we created K.set_session(sess) model, vgg19",
"gram matrix gram = tf.matmul(a, a, transpose_a=True) return gram def get_style_loss(base_style, gram_target): height,"
] |
[
"under a 3-clause BSD style license - see LICENSE.rst from .robust_file_opener import _compression_safe_opener",
"# Licensed under a 3-clause BSD style license - see LICENSE.rst from .robust_file_opener",
"Licensed under a 3-clause BSD style license - see LICENSE.rst from .robust_file_opener import"
] |
[
"def test_import_ml(self): \"\"\"Test ml module.\"\"\" import ml self.assertEqual( inspect.getfile(ml), str(Path.cwd().joinpath('src', 'ml', '__init__.py')), )",
"from pathlib import Path class TestImportModule(unittest.TestCase): \"\"\"Module testing.\"\"\" def test_import_ml(self): \"\"\"Test ml module.\"\"\"",
"Path class TestImportModule(unittest.TestCase): \"\"\"Module testing.\"\"\" def test_import_ml(self): \"\"\"Test ml module.\"\"\" import ml self.assertEqual(",
"module.\"\"\" import inspect import unittest from pathlib import Path class TestImportModule(unittest.TestCase): \"\"\"Module testing.\"\"\"",
"\"\"\"Test for loading ml module.\"\"\" import inspect import unittest from pathlib import Path",
"test_import_ml(self): \"\"\"Test ml module.\"\"\" import ml self.assertEqual( inspect.getfile(ml), str(Path.cwd().joinpath('src', 'ml', '__init__.py')), ) if",
"import inspect import unittest from pathlib import Path class TestImportModule(unittest.TestCase): \"\"\"Module testing.\"\"\" def",
"<reponame>ChuaHanChong/MLOps-Project \"\"\"Test for loading ml module.\"\"\" import inspect import unittest from pathlib import",
"TestImportModule(unittest.TestCase): \"\"\"Module testing.\"\"\" def test_import_ml(self): \"\"\"Test ml module.\"\"\" import ml self.assertEqual( inspect.getfile(ml), str(Path.cwd().joinpath('src',",
"import ml self.assertEqual( inspect.getfile(ml), str(Path.cwd().joinpath('src', 'ml', '__init__.py')), ) if __name__ == '__main__': unittest.main()",
"for loading ml module.\"\"\" import inspect import unittest from pathlib import Path class",
"import unittest from pathlib import Path class TestImportModule(unittest.TestCase): \"\"\"Module testing.\"\"\" def test_import_ml(self): \"\"\"Test",
"import Path class TestImportModule(unittest.TestCase): \"\"\"Module testing.\"\"\" def test_import_ml(self): \"\"\"Test ml module.\"\"\" import ml",
"ml module.\"\"\" import inspect import unittest from pathlib import Path class TestImportModule(unittest.TestCase): \"\"\"Module",
"inspect import unittest from pathlib import Path class TestImportModule(unittest.TestCase): \"\"\"Module testing.\"\"\" def test_import_ml(self):",
"pathlib import Path class TestImportModule(unittest.TestCase): \"\"\"Module testing.\"\"\" def test_import_ml(self): \"\"\"Test ml module.\"\"\" import",
"ml module.\"\"\" import ml self.assertEqual( inspect.getfile(ml), str(Path.cwd().joinpath('src', 'ml', '__init__.py')), ) if __name__ ==",
"unittest from pathlib import Path class TestImportModule(unittest.TestCase): \"\"\"Module testing.\"\"\" def test_import_ml(self): \"\"\"Test ml",
"\"\"\"Test ml module.\"\"\" import ml self.assertEqual( inspect.getfile(ml), str(Path.cwd().joinpath('src', 'ml', '__init__.py')), ) if __name__",
"class TestImportModule(unittest.TestCase): \"\"\"Module testing.\"\"\" def test_import_ml(self): \"\"\"Test ml module.\"\"\" import ml self.assertEqual( inspect.getfile(ml),",
"module.\"\"\" import ml self.assertEqual( inspect.getfile(ml), str(Path.cwd().joinpath('src', 'ml', '__init__.py')), ) if __name__ == '__main__':",
"loading ml module.\"\"\" import inspect import unittest from pathlib import Path class TestImportModule(unittest.TestCase):",
"testing.\"\"\" def test_import_ml(self): \"\"\"Test ml module.\"\"\" import ml self.assertEqual( inspect.getfile(ml), str(Path.cwd().joinpath('src', 'ml', '__init__.py')),",
"\"\"\"Module testing.\"\"\" def test_import_ml(self): \"\"\"Test ml module.\"\"\" import ml self.assertEqual( inspect.getfile(ml), str(Path.cwd().joinpath('src', 'ml',"
] |
[
"plyer import notification def send_desk_message(title, message): notification.notify( title=title, message=message, app_icon=\"circle-48.ico\", timeout=5 ) send_desk_message(\"TITLE\",",
"<filename>Project 8/DeskNotification.py # pip install plyer from plyer import notification def send_desk_message(title, message):",
"8/DeskNotification.py # pip install plyer from plyer import notification def send_desk_message(title, message): notification.notify(",
"install plyer from plyer import notification def send_desk_message(title, message): notification.notify( title=title, message=message, app_icon=\"circle-48.ico\",",
"# pip install plyer from plyer import notification def send_desk_message(title, message): notification.notify( title=title,",
"plyer from plyer import notification def send_desk_message(title, message): notification.notify( title=title, message=message, app_icon=\"circle-48.ico\", timeout=5",
"notification def send_desk_message(title, message): notification.notify( title=title, message=message, app_icon=\"circle-48.ico\", timeout=5 ) send_desk_message(\"TITLE\", \"This is",
"send_desk_message(title, message): notification.notify( title=title, message=message, app_icon=\"circle-48.ico\", timeout=5 ) send_desk_message(\"TITLE\", \"This is a message....\")",
"from plyer import notification def send_desk_message(title, message): notification.notify( title=title, message=message, app_icon=\"circle-48.ico\", timeout=5 )",
"def send_desk_message(title, message): notification.notify( title=title, message=message, app_icon=\"circle-48.ico\", timeout=5 ) send_desk_message(\"TITLE\", \"This is a",
"pip install plyer from plyer import notification def send_desk_message(title, message): notification.notify( title=title, message=message,",
"import notification def send_desk_message(title, message): notification.notify( title=title, message=message, app_icon=\"circle-48.ico\", timeout=5 ) send_desk_message(\"TITLE\", \"This"
] |
[
"int = width self.height: int = height self.bg_colour: str = bg_colour self.font: str",
"fill=self.style_var.get().split(\":\")[1], # 'white', fill='white', font=self.style.font) utils.draw_circle(canvas, self.style.width // 2, self.style.height // 2, self.style.width",
"is to work properly with tkinter. It also seems I can't move it",
"of the TextPanel \"\"\" def __init__(self, width: int, height: int, bg_colour: str, font:",
"'white', fill='white', font=self.style.font) utils.draw_circle(canvas, self.style.width // 2, self.style.height // 2, self.style.width // 3,",
"tk from typing import Callable from src.graphics import utils from src.graphics.interfaces import Panel",
"canvas.itemconfigure(text_id, text=hour) minutes = int(self.style_var.get().split(\":\")[1]) extent = utils.calc_arc_extent(self.clock.day, self.clock.hour, minutes) canvas.itemconfigure(arc_id, extent=extent) self.style_var.trace_add('write',",
"self.style.width // 3, outline='white', width=8) arc_id = utils.draw_circle(canvas, self.style.width // 2, self.style.height //",
"\"\"\" def __init__(self, root: tk.Tk, clock: Clock, style: PanelStyle, var_callback: Callable[[Clock], str]): self.root:",
"# fill=self.style_var.get().split(\":\")[1], # 'white', fill='white', font=self.style.font) utils.draw_circle(canvas, self.style.width // 2, self.style.height // 2,",
"from src.graphics.interfaces import Panel from src.timer import Clock class PanelStyle: \"\"\" This class",
"width self.height: int = height self.bg_colour: str = bg_colour self.font: str = font",
"Represents a canvas containing one or more texts with, possibly, some variable styles",
"font=self.style.font) canvas.pack() def on_change(varname, index, mode): \"\"\" The signature of the method must",
"anchor=tk.CENTER, text=self.style_var.get().split(\":\")[0], fill=self.style_var.get().split(\":\")[1], font=self.style.font) canvas.pack() def on_change(varname, index, mode): \"\"\" The signature of",
"place. \"\"\" canvas.itemconfigure(text_id, text=self.style_var.get().split(\":\")[0], fill=self.style_var.get().split(\":\")[1]) self.style_var.trace_add('write', on_change) def tick(self) -> None: self.style_var.set(self.var_callback(self.clock)) class",
"outline='red', width=6, extent=-1 * int(self.style_var.get().split(\":\")[1]) * 6) canvas.pack() def on_change(varname, index, mode): \"\"\"",
"TextPanel(Panel): \"\"\" Represents a canvas containing one or more texts with, possibly, some",
"self.style: PanelStyle = style self.var_callback: Callable = var_callback self.style_var = tk.StringVar(self.root, self.var_callback(self.clock)) def",
"\"\"\" canvas.itemconfigure(text_id, text=self.style_var.get().split(\":\")[0], fill=self.style_var.get().split(\":\")[1]) self.style_var.trace_add('write', on_change) def tick(self) -> None: self.style_var.set(self.var_callback(self.clock)) class ClockPanel(Panel):",
"one or more texts with, possibly, some variable styles and content. \"\"\" def",
"= int(self.style_var.get().split(\":\")[1]) extent = utils.calc_arc_extent(self.clock.day, self.clock.hour, minutes) canvas.itemconfigure(arc_id, extent=extent) self.style_var.trace_add('write', on_change) def tick(self)",
"\"\"\" Represents the canvas containing the clock with the hours and the circle.",
"can't move it from here to a more sensible place. \"\"\" hour =",
"int = height self.bg_colour: str = bg_colour self.font: str = font class TextPanel(Panel):",
"outline='white', width=8) arc_id = utils.draw_circle(canvas, self.style.width // 2, self.style.height // 2, self.style.width //",
"import Panel from src.timer import Clock class PanelStyle: \"\"\" This class holds the",
"* int(self.style_var.get().split(\":\")[1]) * 6) canvas.pack() def on_change(varname, index, mode): \"\"\" The signature of",
"containing one or more texts with, possibly, some variable styles and content. \"\"\"",
"tk.StringVar(self.root, self.var_callback(self.clock)) def draw(self) -> None: canvas = tk.Canvas(self.root, width=self.style.width, height=self.style.height, bg=self.style.bg_colour, highlightthickness=0)",
"__init__(self, root: tk.Tk, clock: Clock, style: PanelStyle, var_callback: Callable[[Clock], str]): self.root: tk.Tk =",
"self.root: tk.Tk = root self.clock: Clock = clock self.style: PanelStyle = style self.var_callback:",
"var_callback: Callable[[Clock], str]): self.root: tk.Tk = root self.clock: Clock = clock self.style: PanelStyle",
"2, self.style.height // 2, self.style.width // 3, outline='white', width=8) arc_id = utils.draw_circle(canvas, self.style.width",
"width=6, extent=-1 * int(self.style_var.get().split(\":\")[1]) * 6) canvas.pack() def on_change(varname, index, mode): \"\"\" The",
"a more sensible place. \"\"\" canvas.itemconfigure(text_id, text=self.style_var.get().split(\":\")[0], fill=self.style_var.get().split(\":\")[1]) self.style_var.trace_add('write', on_change) def tick(self) ->",
"class holds the immutable style properties of the TextPanel \"\"\" def __init__(self, width:",
"= font class TextPanel(Panel): \"\"\" Represents a canvas containing one or more texts",
"font: str): self.width: int = width self.height: int = height self.bg_colour: str =",
"Clock class PanelStyle: \"\"\" This class holds the immutable style properties of the",
"from typing import Callable from src.graphics import utils from src.graphics.interfaces import Panel from",
"or more texts with, possibly, some variable styles and content. \"\"\" def __init__(self,",
"tk.Tk, clock: Clock, style: PanelStyle, var_callback: Callable[[Clock], str]): self.root: tk.Tk = root self.clock:",
"must stay as is to work properly with tkinter. It also seems I",
"I can't move it from here to a more sensible place. \"\"\" canvas.itemconfigure(text_id,",
"here to a more sensible place. \"\"\" canvas.itemconfigure(text_id, text=self.style_var.get().split(\":\")[0], fill=self.style_var.get().split(\":\")[1]) self.style_var.trace_add('write', on_change) def",
"height self.bg_colour: str = bg_colour self.font: str = font class TextPanel(Panel): \"\"\" Represents",
"2, self.style.height // 2, self.style.width // 3, outline='red', width=6, extent=-1 * int(self.style_var.get().split(\":\")[1]) *",
"src.graphics import utils from src.graphics.interfaces import Panel from src.timer import Clock class PanelStyle:",
"str): self.width: int = width self.height: int = height self.bg_colour: str = bg_colour",
"None: canvas = tk.Canvas(self.root, width=self.style.width, height=self.style.height, bg=self.style.bg_colour, highlightthickness=0) text_id = canvas.create_text(self.style.width / 2,",
"def tick(self) -> None: self.style_var.set(self.var_callback(self.clock)) class ClockPanel(Panel): \"\"\" Represents the canvas containing the",
"self.bg_colour: str = bg_colour self.font: str = font class TextPanel(Panel): \"\"\" Represents a",
"import annotations import tkinter as tk from typing import Callable from src.graphics import",
"class TextPanel(Panel): \"\"\" Represents a canvas containing one or more texts with, possibly,",
"draw(self) -> None: canvas = tk.Canvas(self.root, width=self.style.width, height=self.style.height, bg=self.style.bg_colour, highlightthickness=0) text_id = canvas.create_text(self.style.width",
"of the method must stay as is to work properly with tkinter. It",
"Panel from src.timer import Clock class PanelStyle: \"\"\" This class holds the immutable",
"canvas.itemconfigure(text_id, text=self.style_var.get().split(\":\")[0], fill=self.style_var.get().split(\":\")[1]) self.style_var.trace_add('write', on_change) def tick(self) -> None: self.style_var.set(self.var_callback(self.clock)) class ClockPanel(Panel): \"\"\"",
"def __init__(self, width: int, height: int, bg_colour: str, font: str): self.width: int =",
"the canvas containing the clock with the hours and the circle. \"\"\" def",
"clock with the hours and the circle. \"\"\" def __init__(self, root: tk.Tk, clock:",
"None: self.style_var.set(self.var_callback(self.clock)) class ClockPanel(Panel): \"\"\" Represents the canvas containing the clock with the",
"arc_id = utils.draw_circle(canvas, self.style.width // 2, self.style.height // 2, self.style.width // 3, outline='red',",
"self.style.width // 3, outline='red', width=6, extent=-1 * int(self.style_var.get().split(\":\")[1]) * 6) canvas.pack() def on_change(varname,",
"the clock with the hours and the circle. \"\"\" def __init__(self, root: tk.Tk,",
"self.style_var.get().split(\":\")[0] canvas.itemconfigure(text_id, text=hour) minutes = int(self.style_var.get().split(\":\")[1]) extent = utils.calc_arc_extent(self.clock.day, self.clock.hour, minutes) canvas.itemconfigure(arc_id, extent=extent)",
"= style self.var_callback: Callable = var_callback self.style_var = tk.StringVar(self.root, self.var_callback(self.clock)) def draw(self) ->",
"str = font class TextPanel(Panel): \"\"\" Represents a canvas containing one or more",
"signature of the method must stay as is to work properly with tkinter.",
"as is to work properly with tkinter. It also seems I can't move",
"= canvas.create_text(self.style.width / 2, self.style.height / 2, anchor=tk.CENTER, text=self.style_var.get().split(\":\")[0], fill=self.style_var.get().split(\":\")[1], font=self.style.font) canvas.pack() def",
"str]): self.root: tk.Tk = root self.clock: Clock = clock self.style: PanelStyle = style",
"The signature of the method must stay as is to work properly with",
"This class holds the immutable style properties of the TextPanel \"\"\" def __init__(self,",
"text_id = canvas.create_text(self.style.width / 2, self.style.height / 2, anchor=tk.CENTER, text=self.style_var.get().split(\":\")[0], # fill=self.style_var.get().split(\":\")[1], #",
"canvas.create_text(self.style.width / 2, self.style.height / 2, anchor=tk.CENTER, text=self.style_var.get().split(\":\")[0], fill=self.style_var.get().split(\":\")[1], font=self.style.font) canvas.pack() def on_change(varname,",
"clock: Clock, style: PanelStyle, var_callback: Callable[[Clock], str]): self.root: tk.Tk = root self.clock: Clock",
"= canvas.create_text(self.style.width / 2, self.style.height / 2, anchor=tk.CENTER, text=self.style_var.get().split(\":\")[0], # fill=self.style_var.get().split(\":\")[1], # 'white',",
"and content. \"\"\" def __init__(self, root: tk.Tk, clock: Clock, style: PanelStyle, var_callback: Callable[[Clock],",
"from here to a more sensible place. \"\"\" hour = self.style_var.get().split(\":\")[0] canvas.itemconfigure(text_id, text=hour)",
"self.style.height // 2, self.style.width // 3, outline='red', width=6, extent=-1 * int(self.style_var.get().split(\":\")[1]) * 6)",
"text=hour) minutes = int(self.style_var.get().split(\":\")[1]) extent = utils.calc_arc_extent(self.clock.day, self.clock.hour, minutes) canvas.itemconfigure(arc_id, extent=extent) self.style_var.trace_add('write', on_change)",
"seems I can't move it from here to a more sensible place. \"\"\"",
"more sensible place. \"\"\" canvas.itemconfigure(text_id, text=self.style_var.get().split(\":\")[0], fill=self.style_var.get().split(\":\")[1]) self.style_var.trace_add('write', on_change) def tick(self) -> None:",
"from src.graphics import utils from src.graphics.interfaces import Panel from src.timer import Clock class",
"def draw(self) -> None: canvas = tk.Canvas(self.root, width=self.style.width, height=self.style.height, bg=self.style.bg_colour, highlightthickness=0) text_id =",
"src.timer import Clock class PanelStyle: \"\"\" This class holds the immutable style properties",
"utils.draw_circle(canvas, self.style.width // 2, self.style.height // 2, self.style.width // 3, outline='red', width=6, extent=-1",
"can't move it from here to a more sensible place. \"\"\" canvas.itemconfigure(text_id, text=self.style_var.get().split(\":\")[0],",
"// 2, self.style.width // 3, outline='white', width=8) arc_id = utils.draw_circle(canvas, self.style.width // 2,",
"Callable from src.graphics import utils from src.graphics.interfaces import Panel from src.timer import Clock",
"self.var_callback: Callable = var_callback self.style_var = tk.StringVar(self.root, self.var_callback(self.clock)) def draw(self) -> None: canvas",
"self.style_var.set(self.var_callback(self.clock)) class ClockPanel(Panel): \"\"\" Represents the canvas containing the clock with the hours",
"import utils from src.graphics.interfaces import Panel from src.timer import Clock class PanelStyle: \"\"\"",
"def on_change(varname, index, mode): \"\"\" The signature of the method must stay as",
"the method must stay as is to work properly with tkinter. It also",
"sensible place. \"\"\" hour = self.style_var.get().split(\":\")[0] canvas.itemconfigure(text_id, text=hour) minutes = int(self.style_var.get().split(\":\")[1]) extent =",
"2, self.style.width // 3, outline='white', width=8) arc_id = utils.draw_circle(canvas, self.style.width // 2, self.style.height",
"extent = utils.calc_arc_extent(self.clock.day, self.clock.hour, minutes) canvas.itemconfigure(arc_id, extent=extent) self.style_var.trace_add('write', on_change) def tick(self) -> None:",
"width: int, height: int, bg_colour: str, font: str): self.width: int = width self.height:",
"self.style.width // 2, self.style.height // 2, self.style.width // 3, outline='white', width=8) arc_id =",
"-> None: self.style_var.set(self.var_callback(self.clock)) class ClockPanel(Panel): \"\"\" Represents the canvas containing the clock with",
"root self.clock: Clock = clock self.style: PanelStyle = style self.var_callback: Callable = var_callback",
"int, bg_colour: str, font: str): self.width: int = width self.height: int = height",
"= clock self.style: PanelStyle = style self.var_callback: Callable = var_callback self.style_var = tk.StringVar(self.root,",
"a canvas containing one or more texts with, possibly, some variable styles and",
"= bg_colour self.font: str = font class TextPanel(Panel): \"\"\" Represents a canvas containing",
"2, anchor=tk.CENTER, text=self.style_var.get().split(\":\")[0], # fill=self.style_var.get().split(\":\")[1], # 'white', fill='white', font=self.style.font) utils.draw_circle(canvas, self.style.width // 2,",
"from src.timer import Clock class PanelStyle: \"\"\" This class holds the immutable style",
"3, outline='red', width=6, extent=-1 * int(self.style_var.get().split(\":\")[1]) * 6) canvas.pack() def on_change(varname, index, mode):",
"content. \"\"\" def __init__(self, root: tk.Tk, clock: Clock, style: PanelStyle, var_callback: Callable[[Clock], str]):",
"\"\"\" def __init__(self, width: int, height: int, bg_colour: str, font: str): self.width: int",
"self.style.height / 2, anchor=tk.CENTER, text=self.style_var.get().split(\":\")[0], # fill=self.style_var.get().split(\":\")[1], # 'white', fill='white', font=self.style.font) utils.draw_circle(canvas, self.style.width",
"highlightthickness=0) text_id = canvas.create_text(self.style.width / 2, self.style.height / 2, anchor=tk.CENTER, text=self.style_var.get().split(\":\")[0], fill=self.style_var.get().split(\":\")[1], font=self.style.font)",
"text=self.style_var.get().split(\":\")[0], fill=self.style_var.get().split(\":\")[1]) self.style_var.trace_add('write', on_change) def tick(self) -> None: self.style_var.set(self.var_callback(self.clock)) class ClockPanel(Panel): \"\"\" Represents",
"highlightthickness=0) text_id = canvas.create_text(self.style.width / 2, self.style.height / 2, anchor=tk.CENTER, text=self.style_var.get().split(\":\")[0], # fill=self.style_var.get().split(\":\")[1],",
"// 3, outline='red', width=6, extent=-1 * int(self.style_var.get().split(\":\")[1]) * 6) canvas.pack() def on_change(varname, index,",
"import Clock class PanelStyle: \"\"\" This class holds the immutable style properties of",
"self.height: int = height self.bg_colour: str = bg_colour self.font: str = font class",
"self.font: str = font class TextPanel(Panel): \"\"\" Represents a canvas containing one or",
"= width self.height: int = height self.bg_colour: str = bg_colour self.font: str =",
"possibly, some variable styles and content. \"\"\" def __init__(self, root: tk.Tk, clock: Clock,",
"2, self.style.height / 2, anchor=tk.CENTER, text=self.style_var.get().split(\":\")[0], fill=self.style_var.get().split(\":\")[1], font=self.style.font) canvas.pack() def on_change(varname, index, mode):",
"\"\"\" hour = self.style_var.get().split(\":\")[0] canvas.itemconfigure(text_id, text=hour) minutes = int(self.style_var.get().split(\":\")[1]) extent = utils.calc_arc_extent(self.clock.day, self.clock.hour,",
"= self.style_var.get().split(\":\")[0] canvas.itemconfigure(text_id, text=hour) minutes = int(self.style_var.get().split(\":\")[1]) extent = utils.calc_arc_extent(self.clock.day, self.clock.hour, minutes) canvas.itemconfigure(arc_id,",
"PanelStyle: \"\"\" This class holds the immutable style properties of the TextPanel \"\"\"",
"annotations import tkinter as tk from typing import Callable from src.graphics import utils",
"2, anchor=tk.CENTER, text=self.style_var.get().split(\":\")[0], fill=self.style_var.get().split(\":\")[1], font=self.style.font) canvas.pack() def on_change(varname, index, mode): \"\"\" The signature",
"to work properly with tkinter. It also seems I can't move it from",
"text=self.style_var.get().split(\":\")[0], # fill=self.style_var.get().split(\":\")[1], # 'white', fill='white', font=self.style.font) utils.draw_circle(canvas, self.style.width // 2, self.style.height //",
"self.style.height / 2, anchor=tk.CENTER, text=self.style_var.get().split(\":\")[0], fill=self.style_var.get().split(\":\")[1], font=self.style.font) canvas.pack() def on_change(varname, index, mode): \"\"\"",
"fill=self.style_var.get().split(\":\")[1]) self.style_var.trace_add('write', on_change) def tick(self) -> None: self.style_var.set(self.var_callback(self.clock)) class ClockPanel(Panel): \"\"\" Represents the",
"fill='white', font=self.style.font) utils.draw_circle(canvas, self.style.width // 2, self.style.height // 2, self.style.width // 3, outline='white',",
"bg_colour: str, font: str): self.width: int = width self.height: int = height self.bg_colour:",
"with the hours and the circle. \"\"\" def __init__(self, root: tk.Tk, clock: Clock,",
"= utils.draw_circle(canvas, self.style.width // 2, self.style.height // 2, self.style.width // 3, outline='red', width=6,",
"properly with tkinter. It also seems I can't move it from here to",
"canvas containing one or more texts with, possibly, some variable styles and content.",
"variable styles and content. \"\"\" def __init__(self, root: tk.Tk, clock: Clock, style: PanelStyle,",
"self.clock: Clock = clock self.style: PanelStyle = style self.var_callback: Callable = var_callback self.style_var",
"mode): \"\"\" The signature of the method must stay as is to work",
"holds the immutable style properties of the TextPanel \"\"\" def __init__(self, width: int,",
"canvas.pack() def on_change(varname, index, mode): \"\"\" The signature of the method must stay",
"style properties of the TextPanel \"\"\" def __init__(self, width: int, height: int, bg_colour:",
"src.graphics.interfaces import Panel from src.timer import Clock class PanelStyle: \"\"\" This class holds",
"# 'white', fill='white', font=self.style.font) utils.draw_circle(canvas, self.style.width // 2, self.style.height // 2, self.style.width //",
"fill=self.style_var.get().split(\":\")[1], font=self.style.font) canvas.pack() def on_change(varname, index, mode): \"\"\" The signature of the method",
"6) canvas.pack() def on_change(varname, index, mode): \"\"\" The signature of the method must",
"font class TextPanel(Panel): \"\"\" Represents a canvas containing one or more texts with,",
"with tkinter. It also seems I can't move it from here to a",
"move it from here to a more sensible place. \"\"\" hour = self.style_var.get().split(\":\")[0]",
"tick(self) -> None: self.style_var.set(self.var_callback(self.clock)) class ClockPanel(Panel): \"\"\" Represents the canvas containing the clock",
"import Callable from src.graphics import utils from src.graphics.interfaces import Panel from src.timer import",
"Callable[[Clock], str]): self.root: tk.Tk = root self.clock: Clock = clock self.style: PanelStyle =",
"bg=self.style.bg_colour, highlightthickness=0) text_id = canvas.create_text(self.style.width / 2, self.style.height / 2, anchor=tk.CENTER, text=self.style_var.get().split(\":\")[0], fill=self.style_var.get().split(\":\")[1],",
"containing the clock with the hours and the circle. \"\"\" def __init__(self, root:",
"width=8) arc_id = utils.draw_circle(canvas, self.style.width // 2, self.style.height // 2, self.style.width // 3,",
"int(self.style_var.get().split(\":\")[1]) extent = utils.calc_arc_extent(self.clock.day, self.clock.hour, minutes) canvas.itemconfigure(arc_id, extent=extent) self.style_var.trace_add('write', on_change) def tick(self) ->",
"root: tk.Tk, clock: Clock, style: PanelStyle, var_callback: Callable[[Clock], str]): self.root: tk.Tk = root",
"font=self.style.font) utils.draw_circle(canvas, self.style.width // 2, self.style.height // 2, self.style.width // 3, outline='white', width=8)",
"it from here to a more sensible place. \"\"\" hour = self.style_var.get().split(\":\")[0] canvas.itemconfigure(text_id,",
"\"\"\" The signature of the method must stay as is to work properly",
"var_callback self.style_var = tk.StringVar(self.root, self.var_callback(self.clock)) def draw(self) -> None: canvas = tk.Canvas(self.root, width=self.style.width,",
"utils from src.graphics.interfaces import Panel from src.timer import Clock class PanelStyle: \"\"\" This",
"index, mode): \"\"\" The signature of the method must stay as is to",
"tkinter. It also seems I can't move it from here to a more",
"/ 2, anchor=tk.CENTER, text=self.style_var.get().split(\":\")[0], fill=self.style_var.get().split(\":\")[1], font=self.style.font) canvas.pack() def on_change(varname, index, mode): \"\"\" The",
"stay as is to work properly with tkinter. It also seems I can't",
"* 6) canvas.pack() def on_change(varname, index, mode): \"\"\" The signature of the method",
"str, font: str): self.width: int = width self.height: int = height self.bg_colour: str",
"// 2, self.style.height // 2, self.style.width // 3, outline='white', width=8) arc_id = utils.draw_circle(canvas,",
"a more sensible place. \"\"\" hour = self.style_var.get().split(\":\")[0] canvas.itemconfigure(text_id, text=hour) minutes = int(self.style_var.get().split(\":\")[1])",
"some variable styles and content. \"\"\" def __init__(self, root: tk.Tk, clock: Clock, style:",
"class ClockPanel(Panel): \"\"\" Represents the canvas containing the clock with the hours and",
"tk.Canvas(self.root, width=self.style.width, height=self.style.height, bg=self.style.bg_colour, highlightthickness=0) text_id = canvas.create_text(self.style.width / 2, self.style.height / 2,",
"/ 2, self.style.height / 2, anchor=tk.CENTER, text=self.style_var.get().split(\":\")[0], fill=self.style_var.get().split(\":\")[1], font=self.style.font) canvas.pack() def on_change(varname, index,",
"It also seems I can't move it from here to a more sensible",
"extent=-1 * int(self.style_var.get().split(\":\")[1]) * 6) canvas.pack() def on_change(varname, index, mode): \"\"\" The signature",
"the circle. \"\"\" def __init__(self, root: tk.Tk, clock: Clock, style: PanelStyle, var_callback: Callable[[Clock],",
"width=self.style.width, height=self.style.height, bg=self.style.bg_colour, highlightthickness=0) text_id = canvas.create_text(self.style.width / 2, self.style.height / 2, anchor=tk.CENTER,",
"text_id = canvas.create_text(self.style.width / 2, self.style.height / 2, anchor=tk.CENTER, text=self.style_var.get().split(\":\")[0], fill=self.style_var.get().split(\":\")[1], font=self.style.font) canvas.pack()",
"work properly with tkinter. It also seems I can't move it from here",
"the hours and the circle. \"\"\" def __init__(self, root: tk.Tk, clock: Clock, style:",
"utils.draw_circle(canvas, self.style.width // 2, self.style.height // 2, self.style.width // 3, outline='white', width=8) arc_id",
"// 2, self.style.width // 3, outline='red', width=6, extent=-1 * int(self.style_var.get().split(\":\")[1]) * 6) canvas.pack()",
"immutable style properties of the TextPanel \"\"\" def __init__(self, width: int, height: int,",
"method must stay as is to work properly with tkinter. It also seems",
"style self.var_callback: Callable = var_callback self.style_var = tk.StringVar(self.root, self.var_callback(self.clock)) def draw(self) -> None:",
"the immutable style properties of the TextPanel \"\"\" def __init__(self, width: int, height:",
"move it from here to a more sensible place. \"\"\" canvas.itemconfigure(text_id, text=self.style_var.get().split(\":\")[0], fill=self.style_var.get().split(\":\")[1])",
"tk.Tk = root self.clock: Clock = clock self.style: PanelStyle = style self.var_callback: Callable",
"from here to a more sensible place. \"\"\" canvas.itemconfigure(text_id, text=self.style_var.get().split(\":\")[0], fill=self.style_var.get().split(\":\")[1]) self.style_var.trace_add('write', on_change)",
"// 2, self.style.height // 2, self.style.width // 3, outline='red', width=6, extent=-1 * int(self.style_var.get().split(\":\")[1])",
"here to a more sensible place. \"\"\" hour = self.style_var.get().split(\":\")[0] canvas.itemconfigure(text_id, text=hour) minutes",
"the TextPanel \"\"\" def __init__(self, width: int, height: int, bg_colour: str, font: str):",
"canvas containing the clock with the hours and the circle. \"\"\" def __init__(self,",
"and the circle. \"\"\" def __init__(self, root: tk.Tk, clock: Clock, style: PanelStyle, var_callback:",
"to a more sensible place. \"\"\" hour = self.style_var.get().split(\":\")[0] canvas.itemconfigure(text_id, text=hour) minutes =",
"int(self.style_var.get().split(\":\")[1]) * 6) canvas.pack() def on_change(varname, index, mode): \"\"\" The signature of the",
"// 3, outline='white', width=8) arc_id = utils.draw_circle(canvas, self.style.width // 2, self.style.height // 2,",
"self.style_var = tk.StringVar(self.root, self.var_callback(self.clock)) def draw(self) -> None: canvas = tk.Canvas(self.root, width=self.style.width, height=self.style.height,",
"hours and the circle. \"\"\" def __init__(self, root: tk.Tk, clock: Clock, style: PanelStyle,",
"hour = self.style_var.get().split(\":\")[0] canvas.itemconfigure(text_id, text=hour) minutes = int(self.style_var.get().split(\":\")[1]) extent = utils.calc_arc_extent(self.clock.day, self.clock.hour, minutes)",
"3, outline='white', width=8) arc_id = utils.draw_circle(canvas, self.style.width // 2, self.style.height // 2, self.style.width",
"properties of the TextPanel \"\"\" def __init__(self, width: int, height: int, bg_colour: str,",
"= tk.Canvas(self.root, width=self.style.width, height=self.style.height, bg=self.style.bg_colour, highlightthickness=0) text_id = canvas.create_text(self.style.width / 2, self.style.height /",
"on_change) def tick(self) -> None: self.style_var.set(self.var_callback(self.clock)) class ClockPanel(Panel): \"\"\" Represents the canvas containing",
"styles and content. \"\"\" def __init__(self, root: tk.Tk, clock: Clock, style: PanelStyle, var_callback:",
"with, possibly, some variable styles and content. \"\"\" def __init__(self, root: tk.Tk, clock:",
"I can't move it from here to a more sensible place. \"\"\" hour",
"place. \"\"\" hour = self.style_var.get().split(\":\")[0] canvas.itemconfigure(text_id, text=hour) minutes = int(self.style_var.get().split(\":\")[1]) extent = utils.calc_arc_extent(self.clock.day,",
"\"\"\" This class holds the immutable style properties of the TextPanel \"\"\" def",
"__future__ import annotations import tkinter as tk from typing import Callable from src.graphics",
"-> None: canvas = tk.Canvas(self.root, width=self.style.width, height=self.style.height, bg=self.style.bg_colour, highlightthickness=0) text_id = canvas.create_text(self.style.width /",
"/ 2, self.style.height / 2, anchor=tk.CENTER, text=self.style_var.get().split(\":\")[0], # fill=self.style_var.get().split(\":\")[1], # 'white', fill='white', font=self.style.font)",
"self.style_var.trace_add('write', on_change) def tick(self) -> None: self.style_var.set(self.var_callback(self.clock)) class ClockPanel(Panel): \"\"\" Represents the canvas",
"= utils.calc_arc_extent(self.clock.day, self.clock.hour, minutes) canvas.itemconfigure(arc_id, extent=extent) self.style_var.trace_add('write', on_change) def tick(self) -> None: self.style_var.set(self.var_callback(self.clock))",
"as tk from typing import Callable from src.graphics import utils from src.graphics.interfaces import",
"self.var_callback(self.clock)) def draw(self) -> None: canvas = tk.Canvas(self.root, width=self.style.width, height=self.style.height, bg=self.style.bg_colour, highlightthickness=0) text_id",
"text=self.style_var.get().split(\":\")[0], fill=self.style_var.get().split(\":\")[1], font=self.style.font) canvas.pack() def on_change(varname, index, mode): \"\"\" The signature of the",
"sensible place. \"\"\" canvas.itemconfigure(text_id, text=self.style_var.get().split(\":\")[0], fill=self.style_var.get().split(\":\")[1]) self.style_var.trace_add('write', on_change) def tick(self) -> None: self.style_var.set(self.var_callback(self.clock))",
"ClockPanel(Panel): \"\"\" Represents the canvas containing the clock with the hours and the",
"PanelStyle = style self.var_callback: Callable = var_callback self.style_var = tk.StringVar(self.root, self.var_callback(self.clock)) def draw(self)",
"texts with, possibly, some variable styles and content. \"\"\" def __init__(self, root: tk.Tk,",
"/ 2, anchor=tk.CENTER, text=self.style_var.get().split(\":\")[0], # fill=self.style_var.get().split(\":\")[1], # 'white', fill='white', font=self.style.font) utils.draw_circle(canvas, self.style.width //",
"more texts with, possibly, some variable styles and content. \"\"\" def __init__(self, root:",
"Represents the canvas containing the clock with the hours and the circle. \"\"\"",
"tkinter as tk from typing import Callable from src.graphics import utils from src.graphics.interfaces",
"= var_callback self.style_var = tk.StringVar(self.root, self.var_callback(self.clock)) def draw(self) -> None: canvas = tk.Canvas(self.root,",
"self.style.height // 2, self.style.width // 3, outline='white', width=8) arc_id = utils.draw_circle(canvas, self.style.width //",
"on_change(varname, index, mode): \"\"\" The signature of the method must stay as is",
"circle. \"\"\" def __init__(self, root: tk.Tk, clock: Clock, style: PanelStyle, var_callback: Callable[[Clock], str]):",
"Clock, style: PanelStyle, var_callback: Callable[[Clock], str]): self.root: tk.Tk = root self.clock: Clock =",
"from __future__ import annotations import tkinter as tk from typing import Callable from",
"import tkinter as tk from typing import Callable from src.graphics import utils from",
"style: PanelStyle, var_callback: Callable[[Clock], str]): self.root: tk.Tk = root self.clock: Clock = clock",
"TextPanel \"\"\" def __init__(self, width: int, height: int, bg_colour: str, font: str): self.width:",
"anchor=tk.CENTER, text=self.style_var.get().split(\":\")[0], # fill=self.style_var.get().split(\":\")[1], # 'white', fill='white', font=self.style.font) utils.draw_circle(canvas, self.style.width // 2, self.style.height",
"self.style.width // 2, self.style.height // 2, self.style.width // 3, outline='red', width=6, extent=-1 *",
"\"\"\" Represents a canvas containing one or more texts with, possibly, some variable",
"canvas.create_text(self.style.width / 2, self.style.height / 2, anchor=tk.CENTER, text=self.style_var.get().split(\":\")[0], # fill=self.style_var.get().split(\":\")[1], # 'white', fill='white',",
"minutes = int(self.style_var.get().split(\":\")[1]) extent = utils.calc_arc_extent(self.clock.day, self.clock.hour, minutes) canvas.itemconfigure(arc_id, extent=extent) self.style_var.trace_add('write', on_change) def",
"= tk.StringVar(self.root, self.var_callback(self.clock)) def draw(self) -> None: canvas = tk.Canvas(self.root, width=self.style.width, height=self.style.height, bg=self.style.bg_colour,",
"Callable = var_callback self.style_var = tk.StringVar(self.root, self.var_callback(self.clock)) def draw(self) -> None: canvas =",
"def __init__(self, root: tk.Tk, clock: Clock, style: PanelStyle, var_callback: Callable[[Clock], str]): self.root: tk.Tk",
"Clock = clock self.style: PanelStyle = style self.var_callback: Callable = var_callback self.style_var =",
"2, self.style.height / 2, anchor=tk.CENTER, text=self.style_var.get().split(\":\")[0], # fill=self.style_var.get().split(\":\")[1], # 'white', fill='white', font=self.style.font) utils.draw_circle(canvas,",
"__init__(self, width: int, height: int, bg_colour: str, font: str): self.width: int = width",
"2, self.style.width // 3, outline='red', width=6, extent=-1 * int(self.style_var.get().split(\":\")[1]) * 6) canvas.pack() def",
"clock self.style: PanelStyle = style self.var_callback: Callable = var_callback self.style_var = tk.StringVar(self.root, self.var_callback(self.clock))",
"class PanelStyle: \"\"\" This class holds the immutable style properties of the TextPanel",
"height: int, bg_colour: str, font: str): self.width: int = width self.height: int =",
"int, height: int, bg_colour: str, font: str): self.width: int = width self.height: int",
"str = bg_colour self.font: str = font class TextPanel(Panel): \"\"\" Represents a canvas",
"bg_colour self.font: str = font class TextPanel(Panel): \"\"\" Represents a canvas containing one",
"typing import Callable from src.graphics import utils from src.graphics.interfaces import Panel from src.timer",
"= root self.clock: Clock = clock self.style: PanelStyle = style self.var_callback: Callable =",
"PanelStyle, var_callback: Callable[[Clock], str]): self.root: tk.Tk = root self.clock: Clock = clock self.style:",
"height=self.style.height, bg=self.style.bg_colour, highlightthickness=0) text_id = canvas.create_text(self.style.width / 2, self.style.height / 2, anchor=tk.CENTER, text=self.style_var.get().split(\":\")[0],",
"self.width: int = width self.height: int = height self.bg_colour: str = bg_colour self.font:",
"= height self.bg_colour: str = bg_colour self.font: str = font class TextPanel(Panel): \"\"\"",
"canvas = tk.Canvas(self.root, width=self.style.width, height=self.style.height, bg=self.style.bg_colour, highlightthickness=0) text_id = canvas.create_text(self.style.width / 2, self.style.height",
"to a more sensible place. \"\"\" canvas.itemconfigure(text_id, text=self.style_var.get().split(\":\")[0], fill=self.style_var.get().split(\":\")[1]) self.style_var.trace_add('write', on_change) def tick(self)",
"also seems I can't move it from here to a more sensible place.",
"it from here to a more sensible place. \"\"\" canvas.itemconfigure(text_id, text=self.style_var.get().split(\":\")[0], fill=self.style_var.get().split(\":\")[1]) self.style_var.trace_add('write',",
"bg=self.style.bg_colour, highlightthickness=0) text_id = canvas.create_text(self.style.width / 2, self.style.height / 2, anchor=tk.CENTER, text=self.style_var.get().split(\":\")[0], #",
"more sensible place. \"\"\" hour = self.style_var.get().split(\":\")[0] canvas.itemconfigure(text_id, text=hour) minutes = int(self.style_var.get().split(\":\")[1]) extent"
] |
[
"SLICE_OCTOMAP_SIZE / 2 - xy[0], np.full(len(xy[0]), lev)]).T * res all.extend(xyz.tolist()) pcd = o3d.geometry.PointCloud()",
"goals)) path = find_path(drivable, start, goals, verbose=False) if path is not None: break",
"color=(0, 0xFF, 0) STATE_FREE = 255 # color=(0xFF, 0xFF, 0xFF) STATE_OCCUPIED = 1",
":param xyz: list of voxels (xyz and \"size\") :param color: value 0..255 to",
"# 'octo.mp4' # optional video output generation self.min_z = config.get('min_z', 0.5) # should",
"+ [rot // 2]) elif val == 1: free.append(prefix + [rot // 2])",
"def on_sim_time_sec(self, data): if self.time_limit_sec is None: self.time_limit_sec = data def on_pose3d(self, data):",
"5, 6, 7]: z += d d //= 2 xyz.append(((x, y, z), len(seq)))",
"not None: print('Waypoints', data[0], self.waypoints[0], self.waypoints[-1]) self.waypoints_sent_time = self.publish('waypoints', self.waypoints) self.waypoints = None",
"+ channel, None) if handler is not None: handler(getattr(self, channel)) else: assert False,",
"if key == ord(' '): paused = not paused if ord('0') <= key",
"lev)]).T * res all.extend(xyz.tolist()) pcd = o3d.geometry.PointCloud() xyz = np.array(all) pcd.points = o3d.utility.Vector3dVector(xyz)",
"struct import math import numpy as np import cv2 from osgar.node import Node",
"xyz = seq2xyz(free) xyz2img(img, xyz, color=STATE_FREE, level=level) xyz = seq2xyz(occupied) xyz2img(img, xyz, color=STATE_OCCUPIED,",
"print('Path not found!') return img, path class Octomap(Node): def __init__(self, config, bus): super().__init__(config,",
"seq_arr: d = 2 ** (max_len - 1) x, y, z = -32767,",
"= np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE, num_z_levels), dtype=np.uint8) for level in range(num_z_levels): img3d[:, :, level] =",
"print('Waypoints', data[0], self.waypoints[0], self.waypoints[-1]) self.waypoints_sent_time = self.publish('waypoints', self.waypoints) self.waypoints = None def on_octomap(self,",
"dtype=np.bool) drivable = np.vstack([z, tmp, z]) for limit_score in [3*max(score)/4, max(score)/4, 0]: #",
"None or self.pose3d is None or self.sim_time_sec < self.time_limit_sec: return self.time_limit_sec += 1",
"y), radius=0, color=(255, 0, 0), thickness=-1) cv2.circle(img2, start[:2], radius=0, color=(39, 127, 255), thickness=-1)",
"frame to match original image size z = np.zeros((size[0] - 2, 1, size[2]),",
"in [1, 3, 5, 7]: x += d if code in [2, 3,",
"[-1, 0, 1]: for dz in [0]: #[-1, 0, 1]: goals.append(xy2 + np.repeat(np.asarray([[dy],",
"= find_path(drivable, start, goals, verbose=False) if path is not None: break img[mask] =",
":] == STATE_UNKNOWN white = img[:, :, :] == STATE_FREE mask_right = green[:,",
"= data continue if waypoints is None: # speed up display/processing - maybe",
"len(xy[0]) == 0: # there are no frontiers, i.e. no exploration path return",
"all.extend(xyz.tolist()) pcd = o3d.geometry.PointCloud() xyz = np.array(all) pcd.points = o3d.utility.Vector3dVector(xyz) voxel_grid = o3d.geometry.VoxelGrid.create_from_point_cloud(pcd,",
"for s in seq_arr]) for seq in seq_arr: d = 2 ** (max_len",
"= False def on_sim_time_sec(self, data): if self.time_limit_sec is None: self.time_limit_sec = data def",
"bytes([(d + 256) % 256 for d in data]) last_octo_data = data key",
"Convert octomap sequence (0..7) into XYZ coordinate :param seq_arr: list of parent-child sequences",
"mask = np.vstack([z, mask2, z]) | mask z_mask_up = green[:, :, 2:] &",
"1]: for dz in [0]: #[-1, 0, 1]: goals.append(xy2 + np.repeat(np.asarray([[dy], [dx], [dz]]),",
"for seq in seq_arr: d = 2 ** (max_len - 1) x, y,",
"o3d.visualization.draw_geometries([line_set, voxel_grid]) if not paused: break return key if __name__ == \"__main__\": import",
"pose3d_stream_id, waypoints_stream_id]) as logreader: level = 2 scaled = True for time, stream,",
"y2 = xy[1][j]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][j] dist = math.hypot(x - x2, y - y2) if",
"None x, y, z = 0, 0, 0 resolution = 0.5 waypoints =",
"= pos assert 1 <= size <= 16, size d = 2 **",
"not touch external boundary so it would never find path # to frontier.",
"score[i] += 1.0 if draw: import matplotlib.pyplot as plt line = plt.plot(xy[1]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0],",
"pose_str = '(%.02f, %.02f, %.02f)' % tuple(pose3d[0]) if pose3d is not None else",
"first sim_time_sec self.debug_arr = [] self.waypoints = None # experimental trigger of navigation",
"green[:, :, 2:] & white[:, :, 1:-1] z_mask_down = green[:, :, :-2] &",
"from osgar.lib.pplanner import find_path # http://www.arminhornung.de/Research/pub/hornung13auro.pdf # 00: unknown; 01: occupied; 10: free;",
"y, z in path] def update(self): channel = super().update() handler = getattr(self, \"on_\"",
"128, 256 + 128:-256 - 128], img.shape) cv2.imshow('Octomap', img) pose_str = '(%.02f, %.02f,",
"SLICE_OCTOMAP_SIZE / 2, SLICE_OCTOMAP_SIZE / 2 - xy[0], np.full(len(xy[0]), lev)]).T * res all.extend(xyz.tolist())",
"config.get('min_z', 0.5) # should be multiply of \"resolution\" self.max_z = config.get('max_z', 0.5) #",
"pose3d is not None else 'None' cv2.setWindowTitle('Octomap', f'Octomap {time}, {pose_str}, level={level}' + ('",
"self.verbose: for i in range(num_z_levels): cv2.imwrite('octo_%03d.png' % i, img3d[:, :, i]) img2 =",
"is not None: for x, y, z in path: cv2.circle(img2, (x, y), radius=0,",
"occupied.append(prefix + [rot // 2]) elif val == 1: free.append(prefix + [rot //",
"key if __name__ == \"__main__\": import argparse from osgar.lib.serialize import deserialize from osgar.logger",
"= np.hstack(goals).T[:, [1, 0, 2]] # the path planner currently expects goals as",
"- 128, 256 + 128:-256 - 128], img.shape) cv2.imshow('Octomap', img) pose_str = '(%.02f,",
"and score[i] > 0: # ~ 5 meters, only inside score[i] += 1.0",
"drivable_safe_y[:, :-2] # add non-drivable frame to match original image size z =",
"occupied, unknown) :return: list of XYZ boxes with their \"size category\" (shorted the",
"return img def data2stack(data): \"\"\" Convert binary ocotomap data into three lists (occupied,",
"and \"size\") :param color: value 0..255 to be assigned to voxels at given",
"color=(0xFF, 0x00, 0x00) SLICE_OCTOMAP_SIZE = 1024 # size of slice/image in XY octomap",
"= [[1, 0, 0] for i in range(len(lines))] line_set = o3d.geometry.LineSet() line_set.points =",
"0, 0 resolution = 0.5 waypoints = None last_octo_data = None with LogReader(args.logfile,",
"- y img[max(0, py-d+1):min(SLICE_OCTOMAP_SIZE, py+1), max(0, px):min(SLICE_OCTOMAP_SIZE, px+d)] = color return img def",
"xy[1][j]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][j] dist = math.hypot(x - x2, y - y2) if dist <",
"= [[(x - SLICE_OCTOMAP_SIZE//2)/2, (SLICE_OCTOMAP_SIZE//2 - y)/2, z * self.resolution + self.min_z] for",
"128 # color=(0, 0xFF, 0) STATE_FREE = 255 # color=(0xFF, 0xFF, 0xFF) STATE_OCCUPIED",
"None: break img[mask] = STATE_FRONTIER if path is not None: for x, y,",
"np.concatenate([z, mask3, z], axis=2) | mask xy = np.where(mask) if len(xy[0]) == 0:",
"next in the stream STATE_UNKNOWN = 128 # color=(0, 0xFF, 0) STATE_FREE =",
"octomap coordinates (for given Z) def seq2xyz(seq_arr): \"\"\" Convert octomap sequence (0..7) into",
"green[:, :, :-2] & white[:, :, 1:-1] z = np.zeros((size[0], size[1], 1), dtype=np.bool)",
"one of given type (free, occupied, unknown) :return: list of XYZ boxes with",
"0, 0), thickness=-1) cv2.circle(img2, start[:2], radius=0, color=(39, 127, 255), thickness=-1) cv2.imwrite('octo_cut.png', img2) #",
"* self.resolution + self.min_z] for x, y, z in path] def update(self): channel",
"extra large (unknown) squares, for now continue px = SLICE_OCTOMAP_SIZE//2 + x py",
"cv2.imwrite('octo_cut.png', img2) # used for replay debugging if self.video_outfile is not None: if",
"unknown self.sim_time_sec = None self.pose3d = None self.video_writer = None self.video_outfile = None",
"level = max(0, min(num_z_levels - 1, start[2])) img2[:, :, 0] = img3d[:, :,",
"xyz, color=STATE_FREE, level=level) xyz = seq2xyz(occupied) xyz2img(img, xyz, color=STATE_OCCUPIED, level=level) xyz = seq2xyz(unknown)",
"= np.zeros(len(xy[0])) for i in range(len(xy[0])): x, y = xy[1][i]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][i] if x",
"self.time_limit_sec: return self.time_limit_sec += 1 # simulated seconds if self.waypoints_sent_time is not None",
"z * self.resolution + self.min_z] for x, y, z in path] def update(self):",
"pixel :param draw: debug frontiers in pyplot :return: extended image with drawn start",
"return img def frontiers(img, start, draw=False): \"\"\" Find path to the best frontier",
"dtype=np.uint8) for level in range(num_z_levels): img3d[:, :, level] = data2maplevel(data, level=level + int(round(self.min_z/self.resolution)))",
"!= 0, which is original unknown/black/undefined STATE_FRONTIER = 196 # color=(0xFF, 0x00, 0xFF)",
"wait for next waypoints message if last_octo_data is not None: draw_iteration(last_octo_data, waypoints, paused=True)",
"= [] while True: img = data2maplevel(data, level=level) cv2.circle(img, start[:2], radius=0, color=(39, 127,",
"if __name__ == \"__main__\": import argparse from osgar.lib.serialize import deserialize from osgar.logger import",
"add also all 8-neighbors of frontiers. goals = [] xy2 = np.array(xy)[:, score",
"voxel_grid = o3d.geometry.VoxelGrid.create_from_point_cloud(pcd, voxel_size=0.1) lines = [[i, i + 1] for i in",
"z = 0, 0, 0 resolution = 0.5 waypoints = None last_octo_data =",
"== STATE_UNKNOWN white = img[:, :, :] == STATE_FREE mask_right = green[:, 2:,",
"+ int(round(self.min_z/self.resolution))) if self.verbose: for i in range(num_z_levels): cv2.imwrite('octo_%03d.png' % i, img3d[:, :,",
"0, 1]: for dz in [0]: #[-1, 0, 1]: goals.append(xy2 + np.repeat(np.asarray([[dy], [dx],",
"to the best frontier (free-unknown transition) :param img: color image with free=white, unknown=green",
":, 1:-1] z = np.zeros((size[0], size[1], 1), dtype=np.bool) mask3 = z_mask_up | z_mask_down",
"self.waypoints = [[(x - SLICE_OCTOMAP_SIZE//2)/2, (SLICE_OCTOMAP_SIZE//2 - y)/2, z * self.resolution + self.min_z]",
"xyz, color=STATE_UNKNOWN, level=level) return img def frontiers(img, start, draw=False): \"\"\" Find path to",
"0xFF) ... just to be != 0, which is original unknown/black/undefined STATE_FRONTIER =",
"np.repeat(np.asarray([[dy], [dx], [dz]]), xy2.shape[1], axis=1)) goals = np.hstack(goals).T[:, [1, 0, 2]] # the",
"size[1], size[2]), dtype=np.bool) drivable = np.vstack([z, tmp, z]) for limit_score in [3*max(score)/4, max(score)/4,",
"cv2.circle(img2, start[:2], radius=0, color=(39, 127, 255), thickness=-1) cv2.imwrite('octo_cut.png', img2) # used for replay",
"> 100: # do not try to fill extra large (unknown) squares, for",
"in range(len(xy[0])): x, y = xy[1][i]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][i] if x > 4: # TODO",
"seconds if self.waypoints_sent_time is not None and self.waypoints_sent_time > self.time: self.publish('dropped', self.time_limit_sec) #",
"1 # color=(0x00, 0x00, 0xFF) ... just to be != 0, which is",
"= np.zeros((1, size[1], size[2]), dtype=np.bool) drivable = np.vstack([z, tmp, z]) for limit_score in",
"self.time_limit_sec is None: self.time_limit_sec = data def on_pose3d(self, data): if self.waypoints is not",
"# 00: unknown; 01: occupied; 10: free; 11: inner node with child next",
"== ord('d'): import open3d as o3d res = 0.5 all = [] for",
"level=level) return img def frontiers(img, start, draw=False): \"\"\" Find path to the best",
"| mask_right z = np.zeros((size[0], 1, size[2]), dtype=np.bool) mask = np.hstack([z, mask, z])",
"waypoints_stream_id: waypoints = data continue if waypoints is None: # speed up display/processing",
"def on_pose3d(self, data): if self.waypoints is not None: print('Waypoints', data[0], self.waypoints[0], self.waypoints[-1]) self.waypoints_sent_time",
"None: fps = 1 height, width = img2.shape[:2] self.video_writer = cv2.VideoWriter(self.video_outfile, cv2.VideoWriter_fourcc(*\"mp4v\"), fps,",
"for i in range(len(xy[0])): x, y = xy[1][i]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][i] for j in range(len(xy[0])):",
"limit_score] for dx in [-1, 0, 1]: for dy in [-1, 0, 1]:",
"scaled: img = cv2.resize(img[256 + 128:-256 - 128, 256 + 128:-256 - 128],",
"on_pose3d(self, data): if self.waypoints is not None: print('Waypoints', data[0], self.waypoints[0], self.waypoints[-1]) self.waypoints_sent_time =",
"2, SLICE_OCTOMAP_SIZE / 2 - xy[0], np.full(len(xy[0]), lev)]).T * res all.extend(xyz.tolist()) pcd =",
"and path, path \"\"\" size = img.shape green = img[:, :, :] ==",
"#[-1, 0, 1]: goals.append(xy2 + np.repeat(np.asarray([[dy], [dx], [dz]]), xy2.shape[1], axis=1)) goals = np.hstack(goals).T[:,",
"STATE_UNKNOWN white = img[:, :, :] == STATE_FREE mask_right = green[:, 2:, :]",
"cut :return: updated image \"\"\" for pos, size in xyz: x, y, z",
"Binary Octomap parsing and processing \"\"\" import struct import math import numpy as",
"osgar.lib.serialize import deserialize from osgar.logger import LogReader, lookup_stream_id parser = argparse.ArgumentParser(\"Analyze ocotomap data\")",
"[] for lev in range(-3, 10): img = data2maplevel(data, level=lev) xy = np.where(img",
"= getattr(self, \"on_\" + channel, None) if handler is not None: handler(getattr(self, channel))",
"start pixel :param draw: debug frontiers in pyplot :return: extended image with drawn",
"x/resolution), int(SLICE_OCTOMAP_SIZE//2 - y/resolution), int(z / resolution) continue if stream == waypoints_stream_id: waypoints",
"# there are no frontiers, i.e. no exploration path return img, None score",
"i.e. no exploration path return img, None score = np.zeros(len(xy[0])) for i in",
"if stream == waypoints_stream_id: waypoints = data continue if waypoints is None: #",
"\"\"\" Draw given list of voxels into existing image :param img: I/O image",
"start[:2], radius=0, color=(39, 127, 255), thickness=-1) if scaled: img = cv2.resize(img[256 + 128:-256",
"class Octomap(Node): def __init__(self, config, bus): super().__init__(config, bus) bus.register('waypoints', 'dropped') self.prev_data = None",
"optional video output generation self.min_z = config.get('min_z', 0.5) # should be multiply of",
"\"\"\" for pos, size in xyz: x, y, z = pos assert 1",
"z = np.zeros((1, size[1], size[2]), dtype=np.bool) mask2 = mask_up | mask_down mask =",
"PNG image', default='out.png') parser.add_argument('--draw', action='store_true', help='draw pyplot frontiers') args = parser.parse_args() octomap_stream_id =",
"drivable[2:, :] & drivable[1:-1, :] & drivable[:-2, :] drivable_safe_xy = drivable_safe_y[:, 2:] &",
"octomap data (depth first) :return: (occupied, free, unknown) lists of sequences \"\"\" stack",
"of frontiers. goals = [] xy2 = np.array(xy)[:, score > limit_score] for dx",
"if key == ord('m'): level -= 1 if key == ord('p'): level +=",
"== 0: unknown.append(prefix + [rot // 2]) assert len(stack) == 0, len(stack) return",
"-32767 for code in seq: if code in [1, 3, 5, 7]: x",
"if self.time_limit_sec is None: self.time_limit_sec = data def on_pose3d(self, data): if self.waypoints is",
"y, z = pos assert 1 <= size <= 16, size d =",
"octomap data') parser.add_argument('--out', help='output path to PNG image', default='out.png') parser.add_argument('--draw', action='store_true', help='draw pyplot",
"for now continue px = SLICE_OCTOMAP_SIZE//2 + x py = SLICE_OCTOMAP_SIZE//2 - y",
"of voxels into existing image :param img: I/O image :param xyz: list of",
"stream == pose3d_stream_id: pose3d = data x, y, z = pose3d[0] start =",
"256) % 256 for d in data]) last_octo_data = data key = draw_iteration(data,",
"None: # speed up display/processing - maybe optional? continue assert len(data) % 2",
"if self.video_writer is None: fps = 1 height, width = img2.shape[:2] self.video_writer =",
"d = 2 ** (16 - size) if z <= level < z",
"None # experimental trigger of navigation self.waypoints_sent_time = None # unknown self.sim_time_sec =",
"sim_time_sec self.debug_arr = [] self.waypoints = None # experimental trigger of navigation self.waypoints_sent_time",
"= (d & (0x3 << rot)) >> rot if val == 3: stack.insert(0,",
"if z <= level < z + d: if d > 100: #",
"y = xy[1][i]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][i] if x > 4: # TODO - resolution and",
"[rot // 2]) elif val == 0: unknown.append(prefix + [rot // 2]) assert",
"on_sim_time_sec(self, data): if self.time_limit_sec is None: self.time_limit_sec = data def on_pose3d(self, data): if",
"None: self.time_limit_sec = data def on_pose3d(self, data): if self.waypoints is not None: print('Waypoints',",
"with child next in the stream STATE_UNKNOWN = 128 # color=(0, 0xFF, 0)",
"image :param xyz: list of voxels (xyz and \"size\") :param color: value 0..255",
"np.full(len(xy[0]), lev)]).T * res all.extend(xyz.tolist()) pcd = o3d.geometry.PointCloud() xyz = np.array(all) pcd.points =",
"size[2]), dtype=np.bool) mask = np.hstack([z, mask, z]) mask_up = green[2:, :, :] &",
":, i]) img2 = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE, 3), dtype=np.uint8) level = max(0, min(num_z_levels -",
"xyz: x, y, z = pos assert 1 <= size <= 16, size",
"return key if __name__ == \"__main__\": import argparse from osgar.lib.serialize import deserialize from",
"if val == 3: stack.insert(0, prefix + [rot // 2]) elif val ==",
"= struct.unpack_from('<H', data, i * 2)[0] for rot in range(14, -2, -2): #",
"range(len(xy[0])): x, y = xy[1][i]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][i] if x > 4: # TODO -",
"limits are included self.resolution = config.get('resolution', 0.5) self.verbose = False def on_sim_time_sec(self, data):",
"self.pose3d[0] start = int(SLICE_OCTOMAP_SIZE//2 + x/self.resolution), int(SLICE_OCTOMAP_SIZE//2 - y/self.resolution), int((z - self.min_z)/self.resolution) num_z_levels",
"not None: self.waypoints = [[(x - SLICE_OCTOMAP_SIZE//2)/2, (SLICE_OCTOMAP_SIZE//2 - y)/2, z * self.resolution",
"(SLICE_OCTOMAP_SIZE//2 - y)/2, z * self.resolution + self.min_z] for x, y, z in",
"img = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE), dtype=np.uint8) occupied, free, unknown = data2stack(data) xyz = seq2xyz(free)",
"img, path class Octomap(Node): def __init__(self, config, bus): super().__init__(config, bus) bus.register('waypoints', 'dropped') self.prev_data",
"level=level) xyz = seq2xyz(occupied) xyz2img(img, xyz, color=STATE_OCCUPIED, level=level) xyz = seq2xyz(unknown) xyz2img(img, xyz,",
"plt.plot(xy[1][m] - SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2 - xy[0][m], 'ro') plt.axes().set_aspect('equal', 'datalim') plt.show() drivable = white",
"-32767, -32767 for code in seq: if code in [1, 3, 5, 7]:",
"0.5 all = [] for lev in range(-3, 10): img = data2maplevel(data, level=lev)",
"x += d if code in [2, 3, 6, 7]: y += d",
"(width, height)) self.video_writer.write(img2) if path is not None: self.waypoints = [[(x - SLICE_OCTOMAP_SIZE//2)/2,",
"< self.time_limit_sec: return self.time_limit_sec += 1 # simulated seconds if self.waypoints_sent_time is not",
"import math import numpy as np import cv2 from osgar.node import Node from",
"existing image :param img: I/O image :param xyz: list of voxels (xyz and",
"break if key == ord(' '): paused = not paused if ord('0') <=",
"start[2])) img2[:, :, 0] = img3d[:, :, level] img2[:, :, 1] = img3d[:,",
"= drivable[2:, :] & drivable[1:-1, :] & drivable[:-2, :] drivable_safe_xy = drivable_safe_y[:, 2:]",
"dtype=np.bool) tmp = np.hstack([z, drivable_safe_xy, z]) z = np.zeros((1, size[1], size[2]), dtype=np.bool) drivable",
"= -32767, -32767, -32767 for code in seq: if code in [1, 3,",
"data (depth first) :return: (occupied, free, unknown) lists of sequences \"\"\" stack =",
"z_mask_down # mask = np.concatenate([z, mask3, z], axis=2) | mask xy = np.where(mask)",
"in range(len(xy[0])): x2, y2 = xy[1][j]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][j] dist = math.hypot(x - x2, y",
"// 2]) elif val == 0: unknown.append(prefix + [rot // 2]) assert len(stack)",
"message if last_octo_data is not None: draw_iteration(last_octo_data, waypoints, paused=True) # vim: expandtab sw=4",
"'bo') m = score > 3*max(score)/4 plt.plot(xy[1][m] - SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2 - xy[0][m], 'ro')",
"return # bit unlucky conversion from existing Python2 data assert len(data) % 2",
"lev in range(-3, 10): img = data2maplevel(data, level=lev) xy = np.where(img == STATE_OCCUPIED)",
"key = cv2.waitKey(1) & 0xFF KEY_Q = ord('q') if key == KEY_Q: break",
"Convert binary ocotomap data into three lists (occupied, free, unknown) :param data: binary",
"= green[:, :, :-2] & white[:, :, 1:-1] z = np.zeros((size[0], size[1], 1),",
"== 0, len(data) data = bytes([(d + 256) % 256 for d in",
"score = np.zeros(len(xy[0])) for i in range(len(xy[0])): x, y = xy[1][i]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][i] if",
"for j in range(len(xy[0])): x2, y2 = xy[1][j]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][j] dist = math.hypot(x -",
"range(len(data) // 2): prefix = stack.pop(0) d = struct.unpack_from('<H', data, i * 2)[0]",
"KEY_Q: break if key == ord(' '): paused = not paused if ord('0')",
"goals = [] xy2 = np.array(xy)[:, score > limit_score] for dx in [-1,",
"None else 'None' cv2.setWindowTitle('Octomap', f'Octomap {time}, {pose_str}, level={level}' + (' (paused)' if paused",
"for d in data]) x, y, z = self.pose3d[0] start = int(SLICE_OCTOMAP_SIZE//2 +",
"# TODO fix this in cloudsim2osgar data = bytes([(d + 256) % 256",
"xyz2img(img, xyz, color=STATE_FREE, level=level) xyz = seq2xyz(occupied) xyz2img(img, xyz, color=STATE_OCCUPIED, level=level) xyz =",
"# optional video output generation self.min_z = config.get('min_z', 0.5) # should be multiply",
"[[1, 0, 0] for i in range(len(lines))] line_set = o3d.geometry.LineSet() line_set.points = o3d.utility.Vector3dVector(waypoints)",
"as np import cv2 from osgar.node import Node from osgar.lib.pplanner import find_path #",
":return: extended image with drawn start and path, path \"\"\" size = img.shape",
"given type (free, occupied, unknown) :return: list of XYZ boxes with their \"size",
"False def on_sim_time_sec(self, data): if self.time_limit_sec is None: self.time_limit_sec = data def on_pose3d(self,",
"osgar.logger import LogReader, lookup_stream_id parser = argparse.ArgumentParser(\"Analyze ocotomap data\") parser.add_argument('logfile', help='path to logfile",
"else 'None' cv2.setWindowTitle('Octomap', f'Octomap {time}, {pose_str}, level={level}' + (' (paused)' if paused else",
"way only (0 is not sufficient due to impecise position score[i] = math.hypot(x,",
"pose3d_stream_id: pose3d = data x, y, z = pose3d[0] start = int(SLICE_OCTOMAP_SIZE//2 +",
"green = img[:, :, :] == STATE_UNKNOWN white = img[:, :, :] ==",
"not sufficient due to impecise position score[i] = math.hypot(x, y) * 0.03 else:",
"y = xy[1][i]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][i] for j in range(len(xy[0])): x2, y2 = xy[1][j]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][j]",
"and detect gate as one way only (0 is not sufficient due to",
"waypoints) if key == ord('q'): break waypoints = None # force wait for",
"display/processing - maybe optional? continue assert len(data) % 2 == 0, len(data) #",
"z = self.pose3d[0] start = int(SLICE_OCTOMAP_SIZE//2 + x/self.resolution), int(SLICE_OCTOMAP_SIZE//2 - y/self.resolution), int((z -",
"== 0: return xyz max_len = max([len(s) for s in seq_arr]) for seq",
"break waypoints = None # force wait for next waypoints message if last_octo_data",
"= self.publish('waypoints', self.waypoints) self.waypoints = None def on_octomap(self, data): if self.sim_time_sec is None",
":] drivable_safe_xy = drivable_safe_y[:, 2:] & drivable_safe_y[:, 1:-1] & drivable_safe_y[:, :-2] # add",
"with octomap data') parser.add_argument('--out', help='output path to PNG image', default='out.png') parser.add_argument('--draw', action='store_true', help='draw",
"super().__init__(config, bus) bus.register('waypoints', 'dropped') self.prev_data = None self.time_limit_sec = None # initialized with",
"= green[:, 2:, :] & white[:, 1:-1, :] mask_left = green[:, :-2, :]",
"mask_left | mask_right z = np.zeros((size[0], 1, size[2]), dtype=np.bool) mask = np.hstack([z, mask,",
"\"\"\" stack = [[]] unknown = [] free = [] occupied = []",
"(0 is not sufficient due to impecise position score[i] = math.hypot(x, y) *",
"is original unknown/black/undefined STATE_FRONTIER = 196 # color=(0xFF, 0x00, 0xFF) STATE_PATH = 64",
":return: list of XYZ boxes with their \"size category\" (shorted the sequence bigger",
"data2maplevel(data, level): \"\"\" Convert Octomap data to image/level \"\"\" img = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE),",
"0 # too cruel cut for X positive semi-space, but let's move INSIDE!",
"planner currently expects goals as tuple (x, y) and operation \"in\" goals =",
"= 0, 0, 0 resolution = 0.5 waypoints = None last_octo_data = None",
"is not None: self.waypoints = [[(x - SLICE_OCTOMAP_SIZE//2)/2, (SLICE_OCTOMAP_SIZE//2 - y)/2, z *",
"1:-1, :] mask_left = green[:, :-2, :] & white[:, 1:-1, :] mask =",
"2 == 0, len(data) # TODO fix this in cloudsim2osgar data = bytes([(d",
"move INSIDE! for i in range(len(xy[0])): x, y = xy[1][i]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][i] for j",
"x, y, z in path] def update(self): channel = super().update() handler = getattr(self,",
"i in range(len(data) // 2): prefix = stack.pop(0) d = struct.unpack_from('<H', data, i",
"(free-unknown transition) :param img: color image with free=white, unknown=green :param start: start pixel",
"- y)/2, z * self.resolution + self.min_z] for x, y, z in path]",
"0..255 to be assigned to voxels at given level :param level: Z-level for",
"start: start pixel :param draw: debug frontiers in pyplot :return: extended image with",
"SLICE_OCTOMAP_SIZE//2 - xy[0][m], 'ro') plt.axes().set_aspect('equal', 'datalim') plt.show() drivable = white # use 1",
"in logreader: data = deserialize(data) if stream == pose3d_stream_id: pose3d = data x,",
":param draw: debug frontiers in pyplot :return: extended image with drawn start and",
"sufficient due to impecise position score[i] = math.hypot(x, y) * 0.03 else: score[i]",
"= 64 # color=(0xFF, 0x00, 0x00) SLICE_OCTOMAP_SIZE = 1024 # size of slice/image",
"[] xy2 = np.array(xy)[:, score > limit_score] for dx in [-1, 0, 1]:",
"range(-3, 10): img = data2maplevel(data, level=lev) xy = np.where(img == STATE_OCCUPIED) xyz =",
"self.pose3d = None self.video_writer = None self.video_outfile = None # 'octo.mp4' # optional",
"[] occupied = [] for i in range(len(data) // 2): prefix = stack.pop(0)",
"dtype=np.bool) mask = np.hstack([z, mask, z]) mask_up = green[2:, :, :] & white[1:-1,",
"x, y, z = 0, 0, 0 resolution = 0.5 waypoints = None",
"sequence (0..7) into XYZ coordinate :param seq_arr: list of parent-child sequences for one",
"only inside score[i] += 1.0 if draw: import matplotlib.pyplot as plt line =",
"unknown=green :param start: start pixel :param draw: debug frontiers in pyplot :return: extended",
"np.array(xy)[:, score > limit_score] for dx in [-1, 0, 1]: for dy in",
"(16 - size) if z <= level < z + d: if d",
"channel)) else: assert False, channel # unknown channel def draw_iteration(data, waypoints=None, paused=False): global",
"- self.min_z)/self.resolution) num_z_levels = int(round((self.max_z - self.min_z)/self.resolution)) + 1 img3d = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE,",
"# used for replay debugging if self.video_outfile is not None: if self.video_writer is",
"if waypoints is None: waypoints = [] while True: img = data2maplevel(data, level=level)",
"boxes with their \"size category\" (shorted the sequence bigger the voxel) \"\"\" xyz",
"= cv2.resize(img[256 + 128:-256 - 128, 256 + 128:-256 - 128], img.shape) cv2.imshow('Octomap',",
"00: unknown; 01: occupied; 10: free; 11: inner node with child next in",
"y), radius=0, color=(255, 0, 255), thickness=-1) if path is not None: for x,",
"color=(39, 127, 255), thickness=-1) cv2.imwrite('octo_cut.png', img2) # used for replay debugging if self.video_outfile",
"stream STATE_UNKNOWN = 128 # color=(0, 0xFF, 0) STATE_FREE = 255 # color=(0xFF,",
"// 2]) elif val == 1: free.append(prefix + [rot // 2]) elif val",
"1)] colors = [[1, 0, 0] for i in range(len(lines))] line_set = o3d.geometry.LineSet()",
"mask xy = np.where(mask) if len(xy[0]) == 0: # there are no frontiers,",
"paused else '')) key = cv2.waitKey(1) & 0xFF KEY_Q = ord('q') if key",
"data): if self.waypoints is not None: print('Waypoints', data[0], self.waypoints[0], self.waypoints[-1]) self.waypoints_sent_time = self.publish('waypoints',",
"z in path: img[y][x] = STATE_PATH else: print('Path not found!') return img, path",
"in the stream STATE_UNKNOWN = 128 # color=(0, 0xFF, 0) STATE_FREE = 255",
"o3d.geometry.PointCloud() xyz = np.array(all) pcd.points = o3d.utility.Vector3dVector(xyz) voxel_grid = o3d.geometry.VoxelGrid.create_from_point_cloud(pcd, voxel_size=0.1) lines =",
"0), thickness=-1) cv2.circle(img2, start[:2], radius=0, color=(39, 127, 255), thickness=-1) cv2.imwrite('octo_cut.png', img2) # used",
"score[i] = 0 # too cruel cut for X positive semi-space, but let's",
"mask z_mask_up = green[:, :, 2:] & white[:, :, 1:-1] z_mask_down = green[:,",
"z = np.zeros((1, size[1], size[2]), dtype=np.bool) drivable = np.vstack([z, tmp, z]) for limit_score",
"workaround add also all 8-neighbors of frontiers. goals = [] xy2 = np.array(xy)[:,",
"pose3d = data x, y, z = pose3d[0] start = int(SLICE_OCTOMAP_SIZE//2 + x/resolution),",
"[-1, 0, 1]: for dy in [-1, 0, 1]: for dz in [0]:",
"y, z = pose3d[0] start = int(SLICE_OCTOMAP_SIZE//2 + x/resolution), int(SLICE_OCTOMAP_SIZE//2 - y/resolution), int(z",
"seq2xyz(unknown) xyz2img(img, xyz, color=STATE_UNKNOWN, level=level) return img def frontiers(img, start, draw=False): \"\"\" Find",
"bit unlucky conversion from existing Python2 data assert len(data) % 2 == 0,",
"= mask_left | mask_right z = np.zeros((size[0], 1, size[2]), dtype=np.bool) mask = np.hstack([z,",
"- resolution and detect gate as one way only (0 is not sufficient",
"+ 1 img3d = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE, num_z_levels), dtype=np.uint8) for level in range(num_z_levels): img3d[:,",
"range(len(waypoints) - 1)] colors = [[1, 0, 0] for i in range(len(lines))] line_set",
"scaled = not scaled if key == ord('d'): import open3d as o3d res",
"unknown def data2maplevel(data, level): \"\"\" Convert Octomap data to image/level \"\"\" img =",
"+= 1.0 if draw: import matplotlib.pyplot as plt line = plt.plot(xy[1]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0], 'bo')",
"None: print('Waypoints', data[0], self.waypoints[0], self.waypoints[-1]) self.waypoints_sent_time = self.publish('waypoints', self.waypoints) self.waypoints = None def",
"self.min_z)/self.resolution) num_z_levels = int(round((self.max_z - self.min_z)/self.resolution)) + 1 img3d = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE, num_z_levels),",
"i]) img2 = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE, 3), dtype=np.uint8) level = max(0, min(num_z_levels - 1,",
"for dy in [-1, 0, 1]: for dz in [0]: #[-1, 0, 1]:",
"is not None: for x, y, z in path: img[y][x] = STATE_PATH else:",
"boundary so it would never find path # to frontier. As a workaround",
"xyz = [] if len(seq_arr) == 0: return xyz max_len = max([len(s) for",
":param start: start pixel :param draw: debug frontiers in pyplot :return: extended image",
"None and self.waypoints_sent_time > self.time: self.publish('dropped', self.time_limit_sec) # log skipped sim_time return #",
"is not None: print('Waypoints', data[0], self.waypoints[0], self.waypoints[-1]) self.waypoints_sent_time = self.publish('waypoints', self.waypoints) self.waypoints =",
"initialized with the first sim_time_sec self.debug_arr = [] self.waypoints = None # experimental",
"for limit_score in [3*max(score)/4, max(score)/4, 0]: # select goal positions above the limit_score",
"in range(len(lines))] line_set = o3d.geometry.LineSet() line_set.points = o3d.utility.Vector3dVector(waypoints) line_set.lines = o3d.utility.Vector2iVector(lines) line_set.colors =",
"(d & (0x3 << rot)) >> rot if val == 3: stack.insert(0, prefix",
":param seq_arr: list of parent-child sequences for one of given type (free, occupied,",
"TODO fix this in cloudsim2osgar data = bytes([(d + 256) % 256 for",
"green[:, :-2, :] & white[:, 1:-1, :] mask = mask_left | mask_right z",
"video output generation self.min_z = config.get('min_z', 0.5) # should be multiply of \"resolution\"",
"Octomap parsing and processing \"\"\" import struct import math import numpy as np",
"i, img3d[:, :, i]) img2 = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE, 3), dtype=np.uint8) level = max(0,",
":, 2:] & white[:, :, 1:-1] z_mask_down = green[:, :, :-2] & white[:,",
"xyz = np.array(all) pcd.points = o3d.utility.Vector3dVector(xyz) voxel_grid = o3d.geometry.VoxelGrid.create_from_point_cloud(pcd, voxel_size=0.1) lines = [[i,",
"x, y, z = pos assert 1 <= size <= 16, size d",
"self.waypoints_sent_time > self.time: self.publish('dropped', self.time_limit_sec) # log skipped sim_time return # bit unlucky",
"__name__ == \"__main__\": import argparse from osgar.lib.serialize import deserialize from osgar.logger import LogReader,",
"mask = np.hstack([z, mask, z]) mask_up = green[2:, :, :] & white[1:-1, :,",
"== pose3d_stream_id: pose3d = data x, y, z = pose3d[0] start = int(SLICE_OCTOMAP_SIZE//2",
"image with free=white, unknown=green :param start: start pixel :param draw: debug frontiers in",
"max_len = max([len(s) for s in seq_arr]) for seq in seq_arr: d =",
"//= 2 xyz.append(((x, y, z), len(seq))) return xyz def xyz2img(img, xyz, color, level=2):",
"data]) x, y, z = self.pose3d[0] start = int(SLICE_OCTOMAP_SIZE//2 + x/self.resolution), int(SLICE_OCTOMAP_SIZE//2 -",
"osgar.lib.pplanner import find_path # http://www.arminhornung.de/Research/pub/hornung13auro.pdf # 00: unknown; 01: occupied; 10: free; 11:",
"next waypoints message if last_octo_data is not None: draw_iteration(last_octo_data, waypoints, paused=True) # vim:",
"start[2]: cv2.circle(img2, (x, y), radius=0, color=(255, 0, 255), thickness=-1) if path is not",
"py-d+1):min(SLICE_OCTOMAP_SIZE, py+1), max(0, px):min(SLICE_OCTOMAP_SIZE, px+d)] = color return img def data2stack(data): \"\"\" Convert",
"px+d)] = color return img def data2stack(data): \"\"\" Convert binary ocotomap data into",
"0.5) # should be multiply of \"resolution\" self.max_z = config.get('max_z', 0.5) # the",
"is modified in place anyway if self.verbose: f = (img3d == STATE_FRONTIER).nonzero() for",
"size[2]), dtype=np.bool) tmp = np.hstack([z, drivable_safe_xy, z]) z = np.zeros((1, size[1], size[2]), dtype=np.bool)",
"= math.hypot(x, y) * 0.03 else: score[i] = 0 # too cruel cut",
"== 3: stack.insert(0, prefix + [rot // 2]) elif val == 2: occupied.append(prefix",
"lookup_stream_id(args.logfile, 'fromrospy.pose3d') waypoints_stream_id = lookup_stream_id(args.logfile, 'octomap.waypoints') pose3d = None x, y, z =",
"<= key <= ord('9'): level = key - ord('0') if key == ord('m'):",
"level < z + d: if d > 100: # do not try",
"-2, -2): # range(0, 16, 2): val = (d & (0x3 << rot))",
"tmp, z]) for limit_score in [3*max(score)/4, max(score)/4, 0]: # select goal positions above",
"gate as one way only (0 is not sufficient due to impecise position",
"waypoints = data continue if waypoints is None: # speed up display/processing -",
"positions above the limit_score # note, that the \"safe path\" does not touch",
"= [[i, i + 1] for i in range(len(waypoints) - 1)] colors =",
"unknown) :param data: binary octomap data (depth first) :return: (occupied, free, unknown) lists",
"level={level}' + (' (paused)' if paused else '')) key = cv2.waitKey(1) & 0xFF",
"o3d.utility.Vector2iVector(lines) line_set.colors = o3d.utility.Vector3dVector(colors) o3d.visualization.draw_geometries([line_set, voxel_grid]) if not paused: break return key if",
"\"\"\" Find path to the best frontier (free-unknown transition) :param img: color image",
"0.5 waypoints = None last_octo_data = None with LogReader(args.logfile, only_stream_id=[octomap_stream_id, pose3d_stream_id, waypoints_stream_id]) as",
"assert len(data) % 2 == 0, len(data) # TODO fix this in cloudsim2osgar",
"free; 11: inner node with child next in the stream STATE_UNKNOWN = 128",
"= o3d.geometry.VoxelGrid.create_from_point_cloud(pcd, voxel_size=0.1) lines = [[i, i + 1] for i in range(len(waypoints)",
"= z_mask_up | z_mask_down # mask = np.concatenate([z, mask3, z], axis=2) | mask",
"waypoints message if last_octo_data is not None: draw_iteration(last_octo_data, waypoints, paused=True) # vim: expandtab",
"2:] & drivable_safe_y[:, 1:-1] & drivable_safe_y[:, :-2] # add non-drivable frame to match",
"return self.time_limit_sec += 1 # simulated seconds if self.waypoints_sent_time is not None and",
"8-neighbors of frontiers. goals = [] xy2 = np.array(xy)[:, score > limit_score] for",
"if key == ord('q'): break waypoints = None # force wait for next",
"(x, y), radius=0, color=(255, 0, 0), thickness=-1) cv2.circle(img2, start[:2], radius=0, color=(39, 127, 255),",
"color: value 0..255 to be assigned to voxels at given level :param level:",
"parser.add_argument('logfile', help='path to logfile with octomap data') parser.add_argument('--out', help='output path to PNG image',",
"impecise position score[i] = math.hypot(x, y) * 0.03 else: score[i] = 0 #",
"list of XYZ boxes with their \"size category\" (shorted the sequence bigger the",
"- y/self.resolution), int((z - self.min_z)/self.resolution) num_z_levels = int(round((self.max_z - self.min_z)/self.resolution)) + 1 img3d",
"# speed up display/processing - maybe optional? continue assert len(data) % 2 ==",
"(unknown) squares, for now continue px = SLICE_OCTOMAP_SIZE//2 + x py = SLICE_OCTOMAP_SIZE//2",
"= o3d.geometry.LineSet() line_set.points = o3d.utility.Vector3dVector(waypoints) line_set.lines = o3d.utility.Vector2iVector(lines) line_set.colors = o3d.utility.Vector3dVector(colors) o3d.visualization.draw_geometries([line_set, voxel_grid])",
"octomap_stream_id = lookup_stream_id(args.logfile, 'fromrospy.octomap') pose3d_stream_id = lookup_stream_id(args.logfile, 'fromrospy.pose3d') waypoints_stream_id = lookup_stream_id(args.logfile, 'octomap.waypoints') pose3d",
"score > 3*max(score)/4 plt.plot(xy[1][m] - SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2 - xy[0][m], 'ro') plt.axes().set_aspect('equal', 'datalim') plt.show()",
"config.get('max_z', 0.5) # the limits are included self.resolution = config.get('resolution', 0.5) self.verbose =",
"level = 2 scaled = True for time, stream, data in logreader: data",
"x2, y - y2) if dist < 10 and score[i] > 0: #",
"getattr(self, \"on_\" + channel, None) if handler is not None: handler(getattr(self, channel)) else:",
"for time, stream, data in logreader: data = deserialize(data) if stream == pose3d_stream_id:",
"key - ord('0') if key == ord('m'): level -= 1 if key ==",
"data): if self.sim_time_sec is None or self.pose3d is None or self.sim_time_sec < self.time_limit_sec:",
"size d = 2 ** (16 - size) if z <= level <",
"1 height, width = img2.shape[:2] self.video_writer = cv2.VideoWriter(self.video_outfile, cv2.VideoWriter_fourcc(*\"mp4v\"), fps, (width, height)) self.video_writer.write(img2)",
"[] while True: img = data2maplevel(data, level=level) cv2.circle(img, start[:2], radius=0, color=(39, 127, 255),",
"= data2maplevel(data, level=lev) xy = np.where(img == STATE_OCCUPIED) xyz = np.array( [xy[1] -",
"color=STATE_OCCUPIED, level=level) xyz = seq2xyz(unknown) xyz2img(img, xyz, color=STATE_UNKNOWN, level=level) return img def frontiers(img,",
"size[1], size[2]), dtype=np.bool) mask2 = mask_up | mask_down mask = np.vstack([z, mask2, z])",
"in [4, 5, 6, 7]: z += d d //= 2 xyz.append(((x, y,",
"as o3d res = 0.5 all = [] for lev in range(-3, 10):",
"goals = np.hstack(goals).T[:, [1, 0, 2]] # the path planner currently expects goals",
"level] img2[:, :, 2] = img3d[:, :, level] __, path = frontiers(img3d, start)",
"image :param img: I/O image :param xyz: list of voxels (xyz and \"size\")",
"self.time_limit_sec = data def on_pose3d(self, data): if self.waypoints is not None: print('Waypoints', data[0],",
"np import cv2 from osgar.node import Node from osgar.lib.pplanner import find_path # http://www.arminhornung.de/Research/pub/hornung13auro.pdf",
"image', default='out.png') parser.add_argument('--draw', action='store_true', help='draw pyplot frontiers') args = parser.parse_args() octomap_stream_id = lookup_stream_id(args.logfile,",
"\"\"\" import struct import math import numpy as np import cv2 from osgar.node",
"0]: # select goal positions above the limit_score # note, that the \"safe",
"z = np.zeros((size[0], 1, size[2]), dtype=np.bool) mask = np.hstack([z, mask, z]) mask_up =",
":] & drivable[:-2, :] drivable_safe_xy = drivable_safe_y[:, 2:] & drivable_safe_y[:, 1:-1] & drivable_safe_y[:,",
"is None: # speed up display/processing - maybe optional? continue assert len(data) %",
"10: free; 11: inner node with child next in the stream STATE_UNKNOWN =",
"detect gate as one way only (0 is not sufficient due to impecise",
"int(SLICE_OCTOMAP_SIZE//2 - y/self.resolution), int((z - self.min_z)/self.resolution) num_z_levels = int(round((self.max_z - self.min_z)/self.resolution)) + 1",
"of given type (free, occupied, unknown) :return: list of XYZ boxes with their",
"y, z in zip(f[1], f[0], f[2]): if z == start[2]: cv2.circle(img2, (x, y),",
"fps = 1 height, width = img2.shape[:2] self.video_writer = cv2.VideoWriter(self.video_outfile, cv2.VideoWriter_fourcc(*\"mp4v\"), fps, (width,",
"size[1], 1), dtype=np.bool) mask3 = z_mask_up | z_mask_down # mask = np.concatenate([z, mask3,",
"code in [1, 3, 5, 7]: x += d if code in [2,",
"pos assert 1 <= size <= 16, size d = 2 ** (16",
"img, None score = np.zeros(len(xy[0])) for i in range(len(xy[0])): x, y = xy[1][i]-SLICE_OCTOMAP_SIZE//2,",
"img2[:, :, 2] = img3d[:, :, level] __, path = frontiers(img3d, start) #",
"not None: if self.video_writer is None: fps = 1 height, width = img2.shape[:2]",
"external boundary so it would never find path # to frontier. As a",
"~ 5 meters, only inside score[i] += 1.0 if draw: import matplotlib.pyplot as",
"int(SLICE_OCTOMAP_SIZE//2 + x/resolution), int(SLICE_OCTOMAP_SIZE//2 - y/resolution), int(z / resolution) continue if stream ==",
"2]) elif val == 2: occupied.append(prefix + [rot // 2]) elif val ==",
"replay debugging if self.video_outfile is not None: if self.video_writer is None: fps =",
"path\" does not touch external boundary so it would never find path #",
"np.hstack([z, drivable_safe_xy, z]) z = np.zeros((1, size[1], size[2]), dtype=np.bool) drivable = np.vstack([z, tmp,",
":] mask = mask_left | mask_right z = np.zeros((size[0], 1, size[2]), dtype=np.bool) mask",
"LogReader, lookup_stream_id parser = argparse.ArgumentParser(\"Analyze ocotomap data\") parser.add_argument('logfile', help='path to logfile with octomap",
"import Node from osgar.lib.pplanner import find_path # http://www.arminhornung.de/Research/pub/hornung13auro.pdf # 00: unknown; 01: occupied;",
":] & white[1:-1, :, :] mask_down = green[:-2, :, :] & white[1:-1, :,",
"1:-1] z_mask_down = green[:, :, :-2] & white[:, :, 1:-1] z = np.zeros((size[0],",
"cut for X positive semi-space, but let's move INSIDE! for i in range(len(xy[0])):",
"ord('s'): scaled = not scaled if key == ord('d'): import open3d as o3d",
"xyz = seq2xyz(occupied) xyz2img(img, xyz, color=STATE_OCCUPIED, level=level) xyz = seq2xyz(unknown) xyz2img(img, xyz, color=STATE_UNKNOWN,",
"- y2) if dist < 10 and score[i] > 0: # ~ 5",
"'fromrospy.octomap') pose3d_stream_id = lookup_stream_id(args.logfile, 'fromrospy.pose3d') waypoints_stream_id = lookup_stream_id(args.logfile, 'octomap.waypoints') pose3d = None x,",
"touch external boundary so it would never find path # to frontier. As",
"7]: y += d if code in [4, 5, 6, 7]: z +=",
"sequences \"\"\" stack = [[]] unknown = [] free = [] occupied =",
"- ord('0') if key == ord('m'): level -= 1 if key == ord('p'):",
"INSIDE! for i in range(len(xy[0])): x, y = xy[1][i]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][i] for j in",
"self.verbose: f = (img3d == STATE_FRONTIER).nonzero() for x, y, z in zip(f[1], f[0],",
"= [] if len(seq_arr) == 0: return xyz max_len = max([len(s) for s",
"+ self.min_z] for x, y, z in path] def update(self): channel = super().update()",
"np.zeros((size[0], size[1], 1), dtype=np.bool) mask3 = z_mask_up | z_mask_down # mask = np.concatenate([z,",
"waypoints_stream_id]) as logreader: level = 2 scaled = True for time, stream, data",
"goals = set(map(tuple, goals)) path = find_path(drivable, start, goals, verbose=False) if path is",
"// 2]) assert len(stack) == 0, len(stack) return occupied, free, unknown def data2maplevel(data,",
"= None # experimental trigger of navigation self.waypoints_sent_time = None # unknown self.sim_time_sec",
"0] for i in range(len(lines))] line_set = o3d.geometry.LineSet() line_set.points = o3d.utility.Vector3dVector(waypoints) line_set.lines =",
"3, 5, 7]: x += d if code in [2, 3, 6, 7]:",
"for x, y, z in path] def update(self): channel = super().update() handler =",
"val == 0: unknown.append(prefix + [rot // 2]) assert len(stack) == 0, len(stack)",
"range(len(xy[0])): x2, y2 = xy[1][j]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][j] dist = math.hypot(x - x2, y -",
"# simulated seconds if self.waypoints_sent_time is not None and self.waypoints_sent_time > self.time: self.publish('dropped',",
"1]: goals.append(xy2 + np.repeat(np.asarray([[dy], [dx], [dz]]), xy2.shape[1], axis=1)) goals = np.hstack(goals).T[:, [1, 0,",
"paused = not paused if ord('0') <= key <= ord('9'): level = key",
"0xFF) STATE_PATH = 64 # color=(0xFF, 0x00, 0x00) SLICE_OCTOMAP_SIZE = 1024 # size",
"else: print('Path not found!') return img, path class Octomap(Node): def __init__(self, config, bus):",
":-2] # add non-drivable frame to match original image size z = np.zeros((size[0]",
"not paused: break return key if __name__ == \"__main__\": import argparse from osgar.lib.serialize",
"+ [rot // 2]) elif val == 0: unknown.append(prefix + [rot // 2])",
"if code in [4, 5, 6, 7]: z += d d //= 2",
"seq2xyz(occupied) xyz2img(img, xyz, color=STATE_OCCUPIED, level=level) xyz = seq2xyz(unknown) xyz2img(img, xyz, color=STATE_UNKNOWN, level=level) return",
"radius=0, color=(255, 0, 0), thickness=-1) cv2.circle(img2, start[:2], radius=0, color=(39, 127, 255), thickness=-1) cv2.imwrite('octo_cut.png',",
"o3d.utility.Vector3dVector(colors) o3d.visualization.draw_geometries([line_set, voxel_grid]) if not paused: break return key if __name__ == \"__main__\":",
"just to be != 0, which is original unknown/black/undefined STATE_FRONTIER = 196 #",
"limit_score # note, that the \"safe path\" does not touch external boundary so",
"[1, 3, 5, 7]: x += d if code in [2, 3, 6,",
"and self.waypoints_sent_time > self.time: self.publish('dropped', self.time_limit_sec) # log skipped sim_time return # bit",
"= xy[1][i]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][i] if x > 4: # TODO - resolution and detect",
"prefix = stack.pop(0) d = struct.unpack_from('<H', data, i * 2)[0] for rot in",
"= data2maplevel(data, level=level) cv2.circle(img, start[:2], radius=0, color=(39, 127, 255), thickness=-1) if scaled: img",
"level=2): \"\"\" Draw given list of voxels into existing image :param img: I/O",
"occupied, free, unknown = data2stack(data) xyz = seq2xyz(free) xyz2img(img, xyz, color=STATE_FREE, level=level) xyz",
"their \"size category\" (shorted the sequence bigger the voxel) \"\"\" xyz = []",
"child next in the stream STATE_UNKNOWN = 128 # color=(0, 0xFF, 0) STATE_FREE",
"= np.concatenate([z, mask3, z], axis=2) | mask xy = np.where(mask) if len(xy[0]) ==",
"drivable_safe_y = drivable[2:, :] & drivable[1:-1, :] & drivable[:-2, :] drivable_safe_xy = drivable_safe_y[:,",
"& drivable[1:-1, :] & drivable[:-2, :] drivable_safe_xy = drivable_safe_y[:, 2:] & drivable_safe_y[:, 1:-1]",
"else '')) key = cv2.waitKey(1) & 0xFF KEY_Q = ord('q') if key ==",
"= green[2:, :, :] & white[1:-1, :, :] mask_down = green[:-2, :, :]",
"of voxels (xyz and \"size\") :param color: value 0..255 to be assigned to",
"= img[:, :, :] == STATE_FREE mask_right = green[:, 2:, :] & white[:,",
"drivable_safe_y[:, 2:] & drivable_safe_y[:, 1:-1] & drivable_safe_y[:, :-2] # add non-drivable frame to",
"= [] xy2 = np.array(xy)[:, score > limit_score] for dx in [-1, 0,",
"int(round((self.max_z - self.min_z)/self.resolution)) + 1 img3d = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE, num_z_levels), dtype=np.uint8) for level",
"generation self.min_z = config.get('min_z', 0.5) # should be multiply of \"resolution\" self.max_z =",
"for pos, size in xyz: x, y, z = pos assert 1 <=",
":, level] = data2maplevel(data, level=level + int(round(self.min_z/self.resolution))) if self.verbose: for i in range(num_z_levels):",
">> rot if val == 3: stack.insert(0, prefix + [rot // 2]) elif",
"= xy[1][i]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][i] for j in range(len(xy[0])): x2, y2 = xy[1][j]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][j] dist",
"the first sim_time_sec self.debug_arr = [] self.waypoints = None # experimental trigger of",
"pyplot :return: extended image with drawn start and path, path \"\"\" size =",
"for i in range(num_z_levels): cv2.imwrite('octo_%03d.png' % i, img3d[:, :, i]) img2 = np.zeros((SLICE_OCTOMAP_SIZE,",
"drivable_safe_xy = drivable_safe_y[:, 2:] & drivable_safe_y[:, 1:-1] & drivable_safe_y[:, :-2] # add non-drivable",
"handler is not None: handler(getattr(self, channel)) else: assert False, channel # unknown channel",
"be != 0, which is original unknown/black/undefined STATE_FRONTIER = 196 # color=(0xFF, 0x00,",
"elif val == 1: free.append(prefix + [rot // 2]) elif val == 0:",
"5 meters, only inside score[i] += 1.0 if draw: import matplotlib.pyplot as plt",
"- SLICE_OCTOMAP_SIZE//2)/2, (SLICE_OCTOMAP_SIZE//2 - y)/2, z * self.resolution + self.min_z] for x, y,",
"to image/level \"\"\" img = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE), dtype=np.uint8) occupied, free, unknown = data2stack(data)",
"img3d[:, :, level] __, path = frontiers(img3d, start) # this image is modified",
"None def on_octomap(self, data): if self.sim_time_sec is None or self.pose3d is None or",
"for x, y, z in zip(f[1], f[0], f[2]): if z == start[2]: cv2.circle(img2,",
"paused if ord('0') <= key <= ord('9'): level = key - ord('0') if",
"= SLICE_OCTOMAP_SIZE//2 - y img[max(0, py-d+1):min(SLICE_OCTOMAP_SIZE, py+1), max(0, px):min(SLICE_OCTOMAP_SIZE, px+d)] = color return",
"cv2.resize(img[256 + 128:-256 - 128, 256 + 128:-256 - 128], img.shape) cv2.imshow('Octomap', img)",
"white[:, 1:-1, :] mask = mask_left | mask_right z = np.zeros((size[0], 1, size[2]),",
"experimental trigger of navigation self.waypoints_sent_time = None # unknown self.sim_time_sec = None self.pose3d",
"= lookup_stream_id(args.logfile, 'octomap.waypoints') pose3d = None x, y, z = 0, 0, 0",
"= white # use 1 pixel surrounding drivable_safe_y = drivable[2:, :] & drivable[1:-1,",
"px = SLICE_OCTOMAP_SIZE//2 + x py = SLICE_OCTOMAP_SIZE//2 - y img[max(0, py-d+1):min(SLICE_OCTOMAP_SIZE, py+1),",
"if code in [1, 3, 5, 7]: x += d if code in",
"np.zeros((1, size[1], size[2]), dtype=np.bool) drivable = np.vstack([z, tmp, z]) for limit_score in [3*max(score)/4,",
"True for time, stream, data in logreader: data = deserialize(data) if stream ==",
"xyz2img(img, xyz, color=STATE_UNKNOWN, level=level) return img def frontiers(img, start, draw=False): \"\"\" Find path",
"# do not try to fill extra large (unknown) squares, for now continue",
"[4, 5, 6, 7]: z += d d //= 2 xyz.append(((x, y, z),",
"0.5) # the limits are included self.resolution = config.get('resolution', 0.5) self.verbose = False",
"parser = argparse.ArgumentParser(\"Analyze ocotomap data\") parser.add_argument('logfile', help='path to logfile with octomap data') parser.add_argument('--out',",
"z_mask_up = green[:, :, 2:] & white[:, :, 1:-1] z_mask_down = green[:, :,",
"to frontier. As a workaround add also all 8-neighbors of frontiers. goals =",
"select goal positions above the limit_score # note, that the \"safe path\" does",
"for i in range(len(lines))] line_set = o3d.geometry.LineSet() line_set.points = o3d.utility.Vector3dVector(waypoints) line_set.lines = o3d.utility.Vector2iVector(lines)",
":] mask_down = green[:-2, :, :] & white[1:-1, :, :] z = np.zeros((1,",
":return: (occupied, free, unknown) lists of sequences \"\"\" stack = [[]] unknown =",
"find path # to frontier. As a workaround add also all 8-neighbors of",
"handler(getattr(self, channel)) else: assert False, channel # unknown channel def draw_iteration(data, waypoints=None, paused=False):",
"waypoints = None # force wait for next waypoints message if last_octo_data is",
"[dz]]), xy2.shape[1], axis=1)) goals = np.hstack(goals).T[:, [1, 0, 2]] # the path planner",
"[[i, i + 1] for i in range(len(waypoints) - 1)] colors = [[1,",
"is not None else 'None' cv2.setWindowTitle('Octomap', f'Octomap {time}, {pose_str}, level={level}' + (' (paused)'",
"only (0 is not sufficient due to impecise position score[i] = math.hypot(x, y)",
":, 2] = img3d[:, :, level] __, path = frontiers(img3d, start) # this",
"for lev in range(-3, 10): img = data2maplevel(data, level=lev) xy = np.where(img ==",
"SLICE_OCTOMAP_SIZE//2-xy[0][j] dist = math.hypot(x - x2, y - y2) if dist < 10",
"self.video_writer is None: fps = 1 height, width = img2.shape[:2] self.video_writer = cv2.VideoWriter(self.video_outfile,",
"1]: for dy in [-1, 0, 1]: for dz in [0]: #[-1, 0,",
"data x, y, z = pose3d[0] start = int(SLICE_OCTOMAP_SIZE//2 + x/resolution), int(SLICE_OCTOMAP_SIZE//2 -",
"min(num_z_levels - 1, start[2])) img2[:, :, 0] = img3d[:, :, level] img2[:, :,",
"x, y = xy[1][i]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][i] if x > 4: # TODO - resolution",
"# unknown channel def draw_iteration(data, waypoints=None, paused=False): global level, scaled if waypoints is",
"None: for x, y, z in path: img[y][x] = STATE_PATH else: print('Path not",
"self.debug_arr = [] self.waypoints = None # experimental trigger of navigation self.waypoints_sent_time =",
"y) * 0.03 else: score[i] = 0 # too cruel cut for X",
"is not None: handler(getattr(self, channel)) else: assert False, channel # unknown channel def",
"data[0], self.waypoints[0], self.waypoints[-1]) self.waypoints_sent_time = self.publish('waypoints', self.waypoints) self.waypoints = None def on_octomap(self, data):",
"line_set = o3d.geometry.LineSet() line_set.points = o3d.utility.Vector3dVector(waypoints) line_set.lines = o3d.utility.Vector2iVector(lines) line_set.colors = o3d.utility.Vector3dVector(colors) o3d.visualization.draw_geometries([line_set,",
"& (0x3 << rot)) >> rot if val == 3: stack.insert(0, prefix +",
"dz in [0]: #[-1, 0, 1]: goals.append(xy2 + np.repeat(np.asarray([[dy], [dx], [dz]]), xy2.shape[1], axis=1))",
"py+1), max(0, px):min(SLICE_OCTOMAP_SIZE, px+d)] = color return img def data2stack(data): \"\"\" Convert binary",
"d = 2 ** (max_len - 1) x, y, z = -32767, -32767,",
"= seq2xyz(free) xyz2img(img, xyz, color=STATE_FREE, level=level) xyz = seq2xyz(occupied) xyz2img(img, xyz, color=STATE_OCCUPIED, level=level)",
"2:, :] & white[:, 1:-1, :] mask_left = green[:, :-2, :] & white[:,",
"0, which is original unknown/black/undefined STATE_FRONTIER = 196 # color=(0xFF, 0x00, 0xFF) STATE_PATH",
"[rot // 2]) elif val == 1: free.append(prefix + [rot // 2]) elif",
"skipped sim_time return # bit unlucky conversion from existing Python2 data assert len(data)",
"+ [rot // 2]) elif val == 2: occupied.append(prefix + [rot // 2])",
"100: # do not try to fill extra large (unknown) squares, for now",
"image is modified in place anyway if self.verbose: f = (img3d == STATE_FRONTIER).nonzero()",
"= None # force wait for next waypoints message if last_octo_data is not",
"[[]] unknown = [] free = [] occupied = [] for i in",
"self.resolution + self.min_z] for x, y, z in path] def update(self): channel =",
"== \"__main__\": import argparse from osgar.lib.serialize import deserialize from osgar.logger import LogReader, lookup_stream_id",
"self.time: self.publish('dropped', self.time_limit_sec) # log skipped sim_time return # bit unlucky conversion from",
"[[(x - SLICE_OCTOMAP_SIZE//2)/2, (SLICE_OCTOMAP_SIZE//2 - y)/2, z * self.resolution + self.min_z] for x,",
"__init__(self, config, bus): super().__init__(config, bus) bus.register('waypoints', 'dropped') self.prev_data = None self.time_limit_sec = None",
"* 0.03 else: score[i] = 0 # too cruel cut for X positive",
"waypoints is None: waypoints = [] while True: img = data2maplevel(data, level=level) cv2.circle(img,",
"= None self.video_writer = None self.video_outfile = None # 'octo.mp4' # optional video",
"with their \"size category\" (shorted the sequence bigger the voxel) \"\"\" xyz =",
"force wait for next waypoints message if last_octo_data is not None: draw_iteration(last_octo_data, waypoints,",
"def xyz2img(img, xyz, color, level=2): \"\"\" Draw given list of voxels into existing",
"the sequence bigger the voxel) \"\"\" xyz = [] if len(seq_arr) == 0:",
"self.waypoints = None def on_octomap(self, data): if self.sim_time_sec is None or self.pose3d is",
"== KEY_Q: break if key == ord(' '): paused = not paused if",
"= STATE_PATH else: print('Path not found!') return img, path class Octomap(Node): def __init__(self,",
"= 1024 # size of slice/image in XY octomap coordinates (for given Z)",
"** (max_len - 1) x, y, z = -32767, -32767, -32767 for code",
"time, stream, data in logreader: data = deserialize(data) if stream == pose3d_stream_id: pose3d",
"paused=False): global level, scaled if waypoints is None: waypoints = [] while True:",
"voxel_grid]) if not paused: break return key if __name__ == \"__main__\": import argparse",
"4: # TODO - resolution and detect gate as one way only (0",
"\"resolution\" self.max_z = config.get('max_z', 0.5) # the limits are included self.resolution = config.get('resolution',",
"self.sim_time_sec = None self.pose3d = None self.video_writer = None self.video_outfile = None #",
"self.video_writer = cv2.VideoWriter(self.video_outfile, cv2.VideoWriter_fourcc(*\"mp4v\"), fps, (width, height)) self.video_writer.write(img2) if path is not None:",
"= 0.5 waypoints = None last_octo_data = None with LogReader(args.logfile, only_stream_id=[octomap_stream_id, pose3d_stream_id, waypoints_stream_id])",
"if path is not None: for x, y, z in path: img[y][x] =",
"if self.waypoints is not None: print('Waypoints', data[0], self.waypoints[0], self.waypoints[-1]) self.waypoints_sent_time = self.publish('waypoints', self.waypoints)",
"# size of slice/image in XY octomap coordinates (for given Z) def seq2xyz(seq_arr):",
"for next waypoints message if last_octo_data is not None: draw_iteration(last_octo_data, waypoints, paused=True) #",
"goals as tuple (x, y) and operation \"in\" goals = set(map(tuple, goals)) path",
"fps, (width, height)) self.video_writer.write(img2) if path is not None: self.waypoints = [[(x -",
"self.video_writer = None self.video_outfile = None # 'octo.mp4' # optional video output generation",
"in pyplot :return: extended image with drawn start and path, path \"\"\" size",
"continue px = SLICE_OCTOMAP_SIZE//2 + x py = SLICE_OCTOMAP_SIZE//2 - y img[max(0, py-d+1):min(SLICE_OCTOMAP_SIZE,",
"z]) mask_up = green[2:, :, :] & white[1:-1, :, :] mask_down = green[:-2,",
":, 0] = img3d[:, :, level] img2[:, :, 1] = img3d[:, :, level]",
"img = data2maplevel(data, level=level) cv2.circle(img, start[:2], radius=0, color=(39, 127, 255), thickness=-1) if scaled:",
"- 2, 1, size[2]), dtype=np.bool) tmp = np.hstack([z, drivable_safe_xy, z]) z = np.zeros((1,",
"is None: fps = 1 height, width = img2.shape[:2] self.video_writer = cv2.VideoWriter(self.video_outfile, cv2.VideoWriter_fourcc(*\"mp4v\"),",
"last_octo_data = data key = draw_iteration(data, waypoints) if key == ord('q'): break waypoints",
"drivable_safe_xy, z]) z = np.zeros((1, size[1], size[2]), dtype=np.bool) drivable = np.vstack([z, tmp, z])",
"binary ocotomap data into three lists (occupied, free, unknown) :param data: binary octomap",
"= lookup_stream_id(args.logfile, 'fromrospy.octomap') pose3d_stream_id = lookup_stream_id(args.logfile, 'fromrospy.pose3d') waypoints_stream_id = lookup_stream_id(args.logfile, 'octomap.waypoints') pose3d =",
"None self.video_writer = None self.video_outfile = None # 'octo.mp4' # optional video output",
"y, z = -32767, -32767, -32767 for code in seq: if code in",
"set(map(tuple, goals)) path = find_path(drivable, start, goals, verbose=False) if path is not None:",
"STATE_PATH else: print('Path not found!') return img, path class Octomap(Node): def __init__(self, config,",
"x > 4: # TODO - resolution and detect gate as one way",
"in XY octomap coordinates (for given Z) def seq2xyz(seq_arr): \"\"\" Convert octomap sequence",
"+= d d //= 2 xyz.append(((x, y, z), len(seq))) return xyz def xyz2img(img,",
"color=(0x00, 0x00, 0xFF) ... just to be != 0, which is original unknown/black/undefined",
"+ 128:-256 - 128], img.shape) cv2.imshow('Octomap', img) pose_str = '(%.02f, %.02f, %.02f)' %",
"so it would never find path # to frontier. As a workaround add",
"log skipped sim_time return # bit unlucky conversion from existing Python2 data assert",
"[1, 0, 2]] # the path planner currently expects goals as tuple (x,",
"(for given Z) def seq2xyz(seq_arr): \"\"\" Convert octomap sequence (0..7) into XYZ coordinate",
"dtype=np.bool) mask3 = z_mask_up | z_mask_down # mask = np.concatenate([z, mask3, z], axis=2)",
"fix this in cloudsim2osgar data = bytes([(d + 256) % 256 for d",
"color return img def data2stack(data): \"\"\" Convert binary ocotomap data into three lists",
"to impecise position score[i] = math.hypot(x, y) * 0.03 else: score[i] = 0",
"y2) if dist < 10 and score[i] > 0: # ~ 5 meters,",
"& drivable_safe_y[:, 1:-1] & drivable_safe_y[:, :-2] # add non-drivable frame to match original",
"0, 1]: for dy in [-1, 0, 1]: for dz in [0]: #[-1,",
"occupied = [] for i in range(len(data) // 2): prefix = stack.pop(0) d",
":, level] __, path = frontiers(img3d, start) # this image is modified in",
"= plt.plot(xy[1]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0], 'bo') m = score > 3*max(score)/4 plt.plot(xy[1][m] - SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2",
"if waypoints is None: # speed up display/processing - maybe optional? continue assert",
"is not sufficient due to impecise position score[i] = math.hypot(x, y) * 0.03",
"goals, verbose=False) if path is not None: break img[mask] = STATE_FRONTIER if path",
"np.vstack([z, tmp, z]) for limit_score in [3*max(score)/4, max(score)/4, 0]: # select goal positions",
"\"\"\" img = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE), dtype=np.uint8) occupied, free, unknown = data2stack(data) xyz =",
"argparse.ArgumentParser(\"Analyze ocotomap data\") parser.add_argument('logfile', help='path to logfile with octomap data') parser.add_argument('--out', help='output path",
"= max(0, min(num_z_levels - 1, start[2])) img2[:, :, 0] = img3d[:, :, level]",
"mask_up = green[2:, :, :] & white[1:-1, :, :] mask_down = green[:-2, :,",
"# to frontier. As a workaround add also all 8-neighbors of frontiers. goals",
"also all 8-neighbors of frontiers. goals = [] xy2 = np.array(xy)[:, score >",
"(x, y) and operation \"in\" goals = set(map(tuple, goals)) path = find_path(drivable, start,",
"m = score > 3*max(score)/4 plt.plot(xy[1][m] - SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2 - xy[0][m], 'ro') plt.axes().set_aspect('equal',",
"code in seq: if code in [1, 3, 5, 7]: x += d",
"= config.get('max_z', 0.5) # the limits are included self.resolution = config.get('resolution', 0.5) self.verbose",
"= not paused if ord('0') <= key <= ord('9'): level = key -",
"d if code in [2, 3, 6, 7]: y += d if code",
"cv2.waitKey(1) & 0xFF KEY_Q = ord('q') if key == KEY_Q: break if key",
"voxels into existing image :param img: I/O image :param xyz: list of voxels",
"data continue if waypoints is None: # speed up display/processing - maybe optional?",
"'None' cv2.setWindowTitle('Octomap', f'Octomap {time}, {pose_str}, level={level}' + (' (paused)' if paused else ''))",
"1 # simulated seconds if self.waypoints_sent_time is not None and self.waypoints_sent_time > self.time:",
"path is not None: for x, y, z in path: cv2.circle(img2, (x, y),",
"+ (' (paused)' if paused else '')) key = cv2.waitKey(1) & 0xFF KEY_Q",
"level = key - ord('0') if key == ord('m'): level -= 1 if",
"is not None and self.waypoints_sent_time > self.time: self.publish('dropped', self.time_limit_sec) # log skipped sim_time",
"try to fill extra large (unknown) squares, for now continue px = SLICE_OCTOMAP_SIZE//2",
"& white[:, 1:-1, :] mask = mask_left | mask_right z = np.zeros((size[0], 1,",
"in range(len(waypoints) - 1)] colors = [[1, 0, 0] for i in range(len(lines))]",
"(0x3 << rot)) >> rot if val == 3: stack.insert(0, prefix + [rot",
"10 and score[i] > 0: # ~ 5 meters, only inside score[i] +=",
"= [] self.waypoints = None # experimental trigger of navigation self.waypoints_sent_time = None",
"(max_len - 1) x, y, z = -32767, -32767, -32767 for code in",
"-2): # range(0, 16, 2): val = (d & (0x3 << rot)) >>",
"\"\"\" Convert binary ocotomap data into three lists (occupied, free, unknown) :param data:",
"as tuple (x, y) and operation \"in\" goals = set(map(tuple, goals)) path =",
"z = -32767, -32767, -32767 for code in seq: if code in [1,",
"val == 1: free.append(prefix + [rot // 2]) elif val == 0: unknown.append(prefix",
"scaled = True for time, stream, data in logreader: data = deserialize(data) if",
"occupied; 10: free; 11: inner node with child next in the stream STATE_UNKNOWN",
"in range(-3, 10): img = data2maplevel(data, level=lev) xy = np.where(img == STATE_OCCUPIED) xyz",
"= True for time, stream, data in logreader: data = deserialize(data) if stream",
"bus) bus.register('waypoints', 'dropped') self.prev_data = None self.time_limit_sec = None # initialized with the",
"= mask_up | mask_down mask = np.vstack([z, mask2, z]) | mask z_mask_up =",
"// 2): prefix = stack.pop(0) d = struct.unpack_from('<H', data, i * 2)[0] for",
"# TODO - resolution and detect gate as one way only (0 is",
"0x00, 0x00) SLICE_OCTOMAP_SIZE = 1024 # size of slice/image in XY octomap coordinates",
"\"\"\" xyz = [] if len(seq_arr) == 0: return xyz max_len = max([len(s)",
"y/self.resolution), int((z - self.min_z)/self.resolution) num_z_levels = int(round((self.max_z - self.min_z)/self.resolution)) + 1 img3d =",
"if pose3d is not None else 'None' cv2.setWindowTitle('Octomap', f'Octomap {time}, {pose_str}, level={level}' +",
"- 128], img.shape) cv2.imshow('Octomap', img) pose_str = '(%.02f, %.02f, %.02f)' % tuple(pose3d[0]) if",
"None # unknown self.sim_time_sec = None self.pose3d = None self.video_writer = None self.video_outfile",
"stack.insert(0, prefix + [rot // 2]) elif val == 2: occupied.append(prefix + [rot",
"assert False, channel # unknown channel def draw_iteration(data, waypoints=None, paused=False): global level, scaled",
"z in path: cv2.circle(img2, (x, y), radius=0, color=(255, 0, 0), thickness=-1) cv2.circle(img2, start[:2],",
"np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE, num_z_levels), dtype=np.uint8) for level in range(num_z_levels): img3d[:, :, level] = data2maplevel(data,",
"None # 'octo.mp4' # optional video output generation self.min_z = config.get('min_z', 0.5) #",
"def __init__(self, config, bus): super().__init__(config, bus) bus.register('waypoints', 'dropped') self.prev_data = None self.time_limit_sec =",
":return: updated image \"\"\" for pos, size in xyz: x, y, z =",
"seq: if code in [1, 3, 5, 7]: x += d if code",
"x2, y2 = xy[1][j]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][j] dist = math.hypot(x - x2, y - y2)",
"KEY_Q = ord('q') if key == KEY_Q: break if key == ord(' '):",
"if self.sim_time_sec is None or self.pose3d is None or self.sim_time_sec < self.time_limit_sec: return",
"self.time_limit_sec = None # initialized with the first sim_time_sec self.debug_arr = [] self.waypoints",
"# color=(0x00, 0x00, 0xFF) ... just to be != 0, which is original",
"path, path \"\"\" size = img.shape green = img[:, :, :] == STATE_UNKNOWN",
"(x, y), radius=0, color=(255, 0, 255), thickness=-1) if path is not None: for",
"parser.add_argument('--draw', action='store_true', help='draw pyplot frontiers') args = parser.parse_args() octomap_stream_id = lookup_stream_id(args.logfile, 'fromrospy.octomap') pose3d_stream_id",
"channel = super().update() handler = getattr(self, \"on_\" + channel, None) if handler is",
"- SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2 - xy[0][m], 'ro') plt.axes().set_aspect('equal', 'datalim') plt.show() drivable = white #",
"img[max(0, py-d+1):min(SLICE_OCTOMAP_SIZE, py+1), max(0, px):min(SLICE_OCTOMAP_SIZE, px+d)] = color return img def data2stack(data): \"\"\"",
"prefix + [rot // 2]) elif val == 2: occupied.append(prefix + [rot //",
"img3d[:, :, i]) img2 = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE, 3), dtype=np.uint8) level = max(0, min(num_z_levels",
"data2stack(data) xyz = seq2xyz(free) xyz2img(img, xyz, color=STATE_FREE, level=level) xyz = seq2xyz(occupied) xyz2img(img, xyz,",
"1] for i in range(len(waypoints) - 1)] colors = [[1, 0, 0] for",
"mask = mask_left | mask_right z = np.zeros((size[0], 1, size[2]), dtype=np.bool) mask =",
"drivable[:-2, :] drivable_safe_xy = drivable_safe_y[:, 2:] & drivable_safe_y[:, 1:-1] & drivable_safe_y[:, :-2] #",
"action='store_true', help='draw pyplot frontiers') args = parser.parse_args() octomap_stream_id = lookup_stream_id(args.logfile, 'fromrospy.octomap') pose3d_stream_id =",
"in range(len(data) // 2): prefix = stack.pop(0) d = struct.unpack_from('<H', data, i *",
"in range(14, -2, -2): # range(0, 16, 2): val = (d & (0x3",
"key == KEY_Q: break if key == ord(' '): paused = not paused",
"self.sim_time_sec is None or self.pose3d is None or self.sim_time_sec < self.time_limit_sec: return self.time_limit_sec",
"data2maplevel(data, level=lev) xy = np.where(img == STATE_OCCUPIED) xyz = np.array( [xy[1] - SLICE_OCTOMAP_SIZE",
"data = bytes([(d + 256) % 256 for d in data]) x, y,",
"256 for d in data]) x, y, z = self.pose3d[0] start = int(SLICE_OCTOMAP_SIZE//2",
"As a workaround add also all 8-neighbors of frontiers. goals = [] xy2",
"squares, for now continue px = SLICE_OCTOMAP_SIZE//2 + x py = SLICE_OCTOMAP_SIZE//2 -",
"XYZ boxes with their \"size category\" (shorted the sequence bigger the voxel) \"\"\"",
"be assigned to voxels at given level :param level: Z-level for the cut",
"draw: import matplotlib.pyplot as plt line = plt.plot(xy[1]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0], 'bo') m = score",
"would never find path # to frontier. As a workaround add also all",
"# log skipped sim_time return # bit unlucky conversion from existing Python2 data",
"lookup_stream_id(args.logfile, 'octomap.waypoints') pose3d = None x, y, z = 0, 0, 0 resolution",
"img2.shape[:2] self.video_writer = cv2.VideoWriter(self.video_outfile, cv2.VideoWriter_fourcc(*\"mp4v\"), fps, (width, height)) self.video_writer.write(img2) if path is not",
"the path planner currently expects goals as tuple (x, y) and operation \"in\"",
"2]] # the path planner currently expects goals as tuple (x, y) and",
"// 2]) elif val == 2: occupied.append(prefix + [rot // 2]) elif val",
"len(stack) return occupied, free, unknown def data2maplevel(data, level): \"\"\" Convert Octomap data to",
"None: handler(getattr(self, channel)) else: assert False, channel # unknown channel def draw_iteration(data, waypoints=None,",
"if code in [2, 3, 6, 7]: y += d if code in",
":] z = np.zeros((1, size[1], size[2]), dtype=np.bool) mask2 = mask_up | mask_down mask",
"z in path] def update(self): channel = super().update() handler = getattr(self, \"on_\" +",
"dtype=np.uint8) occupied, free, unknown = data2stack(data) xyz = seq2xyz(free) xyz2img(img, xyz, color=STATE_FREE, level=level)",
"0, 1]: goals.append(xy2 + np.repeat(np.asarray([[dy], [dx], [dz]]), xy2.shape[1], axis=1)) goals = np.hstack(goals).T[:, [1,",
"(img3d == STATE_FRONTIER).nonzero() for x, y, z in zip(f[1], f[0], f[2]): if z",
"d: if d > 100: # do not try to fill extra large",
"level=level + int(round(self.min_z/self.resolution))) if self.verbose: for i in range(num_z_levels): cv2.imwrite('octo_%03d.png' % i, img3d[:,",
"[2, 3, 6, 7]: y += d if code in [4, 5, 6,",
"o3d.utility.Vector3dVector(waypoints) line_set.lines = o3d.utility.Vector2iVector(lines) line_set.colors = o3d.utility.Vector3dVector(colors) o3d.visualization.draw_geometries([line_set, voxel_grid]) if not paused: break",
"= o3d.geometry.PointCloud() xyz = np.array(all) pcd.points = o3d.utility.Vector3dVector(xyz) voxel_grid = o3d.geometry.VoxelGrid.create_from_point_cloud(pcd, voxel_size=0.1) lines",
"too cruel cut for X positive semi-space, but let's move INSIDE! for i",
"seq in seq_arr: d = 2 ** (max_len - 1) x, y, z",
"value 0..255 to be assigned to voxels at given level :param level: Z-level",
"0: # ~ 5 meters, only inside score[i] += 1.0 if draw: import",
"speed up display/processing - maybe optional? continue assert len(data) % 2 == 0,",
":, :] == STATE_FREE mask_right = green[:, 2:, :] & white[:, 1:-1, :]",
"5, 7]: x += d if code in [2, 3, 6, 7]: y",
"+= d if code in [4, 5, 6, 7]: z += d d",
"http://www.arminhornung.de/Research/pub/hornung13auro.pdf # 00: unknown; 01: occupied; 10: free; 11: inner node with child",
"+ 128:-256 - 128, 256 + 128:-256 - 128], img.shape) cv2.imshow('Octomap', img) pose_str",
"-= 1 if key == ord('p'): level += 1 if key == ord('s'):",
"unknown.append(prefix + [rot // 2]) assert len(stack) == 0, len(stack) return occupied, free,",
"xyz = seq2xyz(unknown) xyz2img(img, xyz, color=STATE_UNKNOWN, level=level) return img def frontiers(img, start, draw=False):",
"not None else 'None' cv2.setWindowTitle('Octomap', f'Octomap {time}, {pose_str}, level={level}' + (' (paused)' if",
"key == ord('p'): level += 1 if key == ord('s'): scaled = not",
"pose3d_stream_id = lookup_stream_id(args.logfile, 'fromrospy.pose3d') waypoints_stream_id = lookup_stream_id(args.logfile, 'octomap.waypoints') pose3d = None x, y,",
"np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE, 3), dtype=np.uint8) level = max(0, min(num_z_levels - 1, start[2])) img2[:, :,",
"fill extra large (unknown) squares, for now continue px = SLICE_OCTOMAP_SIZE//2 + x",
"radius=0, color=(39, 127, 255), thickness=-1) if scaled: img = cv2.resize(img[256 + 128:-256 -",
"SLICE_OCTOMAP_SIZE//2)/2, (SLICE_OCTOMAP_SIZE//2 - y)/2, z * self.resolution + self.min_z] for x, y, z",
"ocotomap data into three lists (occupied, free, unknown) :param data: binary octomap data",
"mask_down = green[:-2, :, :] & white[1:-1, :, :] z = np.zeros((1, size[1],",
"return xyz max_len = max([len(s) for s in seq_arr]) for seq in seq_arr:",
"self.sim_time_sec < self.time_limit_sec: return self.time_limit_sec += 1 # simulated seconds if self.waypoints_sent_time is",
"= int(SLICE_OCTOMAP_SIZE//2 + x/self.resolution), int(SLICE_OCTOMAP_SIZE//2 - y/self.resolution), int((z - self.min_z)/self.resolution) num_z_levels = int(round((self.max_z",
"cv2.VideoWriter_fourcc(*\"mp4v\"), fps, (width, height)) self.video_writer.write(img2) if path is not None: self.waypoints = [[(x",
"np.zeros((1, size[1], size[2]), dtype=np.bool) mask2 = mask_up | mask_down mask = np.vstack([z, mask2,",
"in path] def update(self): channel = super().update() handler = getattr(self, \"on_\" + channel,",
"2 ** (16 - size) if z <= level < z + d:",
"dist = math.hypot(x - x2, y - y2) if dist < 10 and",
"= STATE_FRONTIER if path is not None: for x, y, z in path:",
"\"in\" goals = set(map(tuple, goals)) path = find_path(drivable, start, goals, verbose=False) if path",
"to be assigned to voxels at given level :param level: Z-level for the",
"z]) z = np.zeros((1, size[1], size[2]), dtype=np.bool) drivable = np.vstack([z, tmp, z]) for",
"given level :param level: Z-level for the cut :return: updated image \"\"\" for",
"np.zeros((size[0] - 2, 1, size[2]), dtype=np.bool) tmp = np.hstack([z, drivable_safe_xy, z]) z =",
"of XYZ boxes with their \"size category\" (shorted the sequence bigger the voxel)",
"unknown; 01: occupied; 10: free; 11: inner node with child next in the",
"self.video_outfile is not None: if self.video_writer is None: fps = 1 height, width",
"path is not None: break img[mask] = STATE_FRONTIER if path is not None:",
"dy in [-1, 0, 1]: for dz in [0]: #[-1, 0, 1]: goals.append(xy2",
"parser.parse_args() octomap_stream_id = lookup_stream_id(args.logfile, 'fromrospy.octomap') pose3d_stream_id = lookup_stream_id(args.logfile, 'fromrospy.pose3d') waypoints_stream_id = lookup_stream_id(args.logfile, 'octomap.waypoints')",
"0x00, 0xFF) STATE_PATH = 64 # color=(0xFF, 0x00, 0x00) SLICE_OCTOMAP_SIZE = 1024 #",
"self.waypoints) self.waypoints = None def on_octomap(self, data): if self.sim_time_sec is None or self.pose3d",
"start, goals, verbose=False) if path is not None: break img[mask] = STATE_FRONTIER if",
"= max([len(s) for s in seq_arr]) for seq in seq_arr: d = 2",
"frontiers. goals = [] xy2 = np.array(xy)[:, score > limit_score] for dx in",
"0.5) self.verbose = False def on_sim_time_sec(self, data): if self.time_limit_sec is None: self.time_limit_sec =",
"voxels (xyz and \"size\") :param color: value 0..255 to be assigned to voxels",
"i in range(num_z_levels): cv2.imwrite('octo_%03d.png' % i, img3d[:, :, i]) img2 = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE,",
"/ 2, SLICE_OCTOMAP_SIZE / 2 - xy[0], np.full(len(xy[0]), lev)]).T * res all.extend(xyz.tolist()) pcd",
"find_path # http://www.arminhornung.de/Research/pub/hornung13auro.pdf # 00: unknown; 01: occupied; 10: free; 11: inner node",
"cv2 from osgar.node import Node from osgar.lib.pplanner import find_path # http://www.arminhornung.de/Research/pub/hornung13auro.pdf # 00:",
"verbose=False) if path is not None: break img[mask] = STATE_FRONTIER if path is",
":-2] & white[:, :, 1:-1] z = np.zeros((size[0], size[1], 1), dtype=np.bool) mask3 =",
"o3d.geometry.VoxelGrid.create_from_point_cloud(pcd, voxel_size=0.1) lines = [[i, i + 1] for i in range(len(waypoints) -",
"xy = np.where(mask) if len(xy[0]) == 0: # there are no frontiers, i.e.",
"goal positions above the limit_score # note, that the \"safe path\" does not",
"o3d.utility.Vector3dVector(xyz) voxel_grid = o3d.geometry.VoxelGrid.create_from_point_cloud(pcd, voxel_size=0.1) lines = [[i, i + 1] for i",
"= 255 # color=(0xFF, 0xFF, 0xFF) STATE_OCCUPIED = 1 # color=(0x00, 0x00, 0xFF)",
"> limit_score] for dx in [-1, 0, 1]: for dy in [-1, 0,",
"STATE_FRONTIER = 196 # color=(0xFF, 0x00, 0xFF) STATE_PATH = 64 # color=(0xFF, 0x00,",
"size) if z <= level < z + d: if d > 100:",
"resolution) continue if stream == waypoints_stream_id: waypoints = data continue if waypoints is",
"frontiers(img3d, start) # this image is modified in place anyway if self.verbose: f",
"2): prefix = stack.pop(0) d = struct.unpack_from('<H', data, i * 2)[0] for rot",
"img3d[:, :, level] img2[:, :, 1] = img3d[:, :, level] img2[:, :, 2]",
"not None: handler(getattr(self, channel)) else: assert False, channel # unknown channel def draw_iteration(data,",
"waypoints = None last_octo_data = None with LogReader(args.logfile, only_stream_id=[octomap_stream_id, pose3d_stream_id, waypoints_stream_id]) as logreader:",
"if x > 4: # TODO - resolution and detect gate as one",
"0, 0] for i in range(len(lines))] line_set = o3d.geometry.LineSet() line_set.points = o3d.utility.Vector3dVector(waypoints) line_set.lines",
"large (unknown) squares, for now continue px = SLICE_OCTOMAP_SIZE//2 + x py =",
"help='path to logfile with octomap data') parser.add_argument('--out', help='output path to PNG image', default='out.png')",
"to voxels at given level :param level: Z-level for the cut :return: updated",
"num_z_levels), dtype=np.uint8) for level in range(num_z_levels): img3d[:, :, level] = data2maplevel(data, level=level +",
"== waypoints_stream_id: waypoints = data continue if waypoints is None: # speed up",
":, level] img2[:, :, 2] = img3d[:, :, level] __, path = frontiers(img3d,",
"256 + 128:-256 - 128], img.shape) cv2.imshow('Octomap', img) pose_str = '(%.02f, %.02f, %.02f)'",
"(free, occupied, unknown) :return: list of XYZ boxes with their \"size category\" (shorted",
"= np.where(mask) if len(xy[0]) == 0: # there are no frontiers, i.e. no",
"frontiers(img, start, draw=False): \"\"\" Find path to the best frontier (free-unknown transition) :param",
"= None with LogReader(args.logfile, only_stream_id=[octomap_stream_id, pose3d_stream_id, waypoints_stream_id]) as logreader: level = 2 scaled",
"= [] for i in range(len(data) // 2): prefix = stack.pop(0) d =",
"open3d as o3d res = 0.5 all = [] for lev in range(-3,",
"bigger the voxel) \"\"\" xyz = [] if len(seq_arr) == 0: return xyz",
"green[2:, :, :] & white[1:-1, :, :] mask_down = green[:-2, :, :] &",
"d in data]) x, y, z = self.pose3d[0] start = int(SLICE_OCTOMAP_SIZE//2 + x/self.resolution),",
"i + 1] for i in range(len(waypoints) - 1)] colors = [[1, 0,",
"list of parent-child sequences for one of given type (free, occupied, unknown) :return:",
"in zip(f[1], f[0], f[2]): if z == start[2]: cv2.circle(img2, (x, y), radius=0, color=(255,",
"in data]) x, y, z = self.pose3d[0] start = int(SLICE_OCTOMAP_SIZE//2 + x/self.resolution), int(SLICE_OCTOMAP_SIZE//2",
"list of voxels into existing image :param img: I/O image :param xyz: list",
"val = (d & (0x3 << rot)) >> rot if val == 3:",
"| z_mask_down # mask = np.concatenate([z, mask3, z], axis=2) | mask xy =",
"= set(map(tuple, goals)) path = find_path(drivable, start, goals, verbose=False) if path is not",
"self.waypoints_sent_time is not None and self.waypoints_sent_time > self.time: self.publish('dropped', self.time_limit_sec) # log skipped",
"True: img = data2maplevel(data, level=level) cv2.circle(img, start[:2], radius=0, color=(39, 127, 255), thickness=-1) if",
"0xFF, 0xFF) STATE_OCCUPIED = 1 # color=(0x00, 0x00, 0xFF) ... just to be",
"z_mask_up | z_mask_down # mask = np.concatenate([z, mask3, z], axis=2) | mask xy",
"= int(round((self.max_z - self.min_z)/self.resolution)) + 1 img3d = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE, num_z_levels), dtype=np.uint8) for",
"z), len(seq))) return xyz def xyz2img(img, xyz, color, level=2): \"\"\" Draw given list",
":, 1:-1] z_mask_down = green[:, :, :-2] & white[:, :, 1:-1] z =",
"== ord(' '): paused = not paused if ord('0') <= key <= ord('9'):",
"if draw: import matplotlib.pyplot as plt line = plt.plot(xy[1]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0], 'bo') m =",
"import numpy as np import cv2 from osgar.node import Node from osgar.lib.pplanner import",
"0) STATE_FREE = 255 # color=(0xFF, 0xFF, 0xFF) STATE_OCCUPIED = 1 # color=(0x00,",
"only_stream_id=[octomap_stream_id, pose3d_stream_id, waypoints_stream_id]) as logreader: level = 2 scaled = True for time,",
"green[:, 2:, :] & white[:, 1:-1, :] mask_left = green[:, :-2, :] &",
":] & white[:, 1:-1, :] mask_left = green[:, :-2, :] & white[:, 1:-1,",
"score[i] = math.hypot(x, y) * 0.03 else: score[i] = 0 # too cruel",
"for x, y, z in path: cv2.circle(img2, (x, y), radius=0, color=(255, 0, 0),",
"with drawn start and path, path \"\"\" size = img.shape green = img[:,",
"'octo.mp4' # optional video output generation self.min_z = config.get('min_z', 0.5) # should be",
"slice/image in XY octomap coordinates (for given Z) def seq2xyz(seq_arr): \"\"\" Convert octomap",
"of slice/image in XY octomap coordinates (for given Z) def seq2xyz(seq_arr): \"\"\" Convert",
"bus): super().__init__(config, bus) bus.register('waypoints', 'dropped') self.prev_data = None self.time_limit_sec = None # initialized",
"[] for i in range(len(data) // 2): prefix = stack.pop(0) d = struct.unpack_from('<H',",
"voxel_size=0.1) lines = [[i, i + 1] for i in range(len(waypoints) - 1)]",
"= '(%.02f, %.02f, %.02f)' % tuple(pose3d[0]) if pose3d is not None else 'None'",
"white = img[:, :, :] == STATE_FREE mask_right = green[:, 2:, :] &",
"def on_octomap(self, data): if self.sim_time_sec is None or self.pose3d is None or self.sim_time_sec",
"= super().update() handler = getattr(self, \"on_\" + channel, None) if handler is not",
"\"size\") :param color: value 0..255 to be assigned to voxels at given level",
"{pose_str}, level={level}' + (' (paused)' if paused else '')) key = cv2.waitKey(1) &",
"0: unknown.append(prefix + [rot // 2]) assert len(stack) == 0, len(stack) return occupied,",
"= stack.pop(0) d = struct.unpack_from('<H', data, i * 2)[0] for rot in range(14,",
"paused: break return key if __name__ == \"__main__\": import argparse from osgar.lib.serialize import",
"= img[:, :, :] == STATE_UNKNOWN white = img[:, :, :] == STATE_FREE",
"None: self.waypoints = [[(x - SLICE_OCTOMAP_SIZE//2)/2, (SLICE_OCTOMAP_SIZE//2 - y)/2, z * self.resolution +",
"line_set.colors = o3d.utility.Vector3dVector(colors) o3d.visualization.draw_geometries([line_set, voxel_grid]) if not paused: break return key if __name__",
"debugging if self.video_outfile is not None: if self.video_writer is None: fps = 1",
"range(num_z_levels): img3d[:, :, level] = data2maplevel(data, level=level + int(round(self.min_z/self.resolution))) if self.verbose: for i",
"conversion from existing Python2 data assert len(data) % 2 == 0, len(data) data",
"elif val == 0: unknown.append(prefix + [rot // 2]) assert len(stack) == 0,",
"does not touch external boundary so it would never find path # to",
"ord('0') <= key <= ord('9'): level = key - ord('0') if key ==",
"for the cut :return: updated image \"\"\" for pos, size in xyz: x,",
"d = struct.unpack_from('<H', data, i * 2)[0] for rot in range(14, -2, -2):",
"16, size d = 2 ** (16 - size) if z <= level",
":param img: color image with free=white, unknown=green :param start: start pixel :param draw:",
"o3d.geometry.LineSet() line_set.points = o3d.utility.Vector3dVector(waypoints) line_set.lines = o3d.utility.Vector2iVector(lines) line_set.colors = o3d.utility.Vector3dVector(colors) o3d.visualization.draw_geometries([line_set, voxel_grid]) if",
"i in range(len(waypoints) - 1)] colors = [[1, 0, 0] for i in",
"len(seq_arr) == 0: return xyz max_len = max([len(s) for s in seq_arr]) for",
"3, 6, 7]: y += d if code in [4, 5, 6, 7]:",
"if handler is not None: handler(getattr(self, channel)) else: assert False, channel # unknown",
"mask, z]) mask_up = green[2:, :, :] & white[1:-1, :, :] mask_down =",
"0xFF KEY_Q = ord('q') if key == KEY_Q: break if key == ord('",
"- 1)] colors = [[1, 0, 0] for i in range(len(lines))] line_set =",
"None self.video_outfile = None # 'octo.mp4' # optional video output generation self.min_z =",
"== STATE_OCCUPIED) xyz = np.array( [xy[1] - SLICE_OCTOMAP_SIZE / 2, SLICE_OCTOMAP_SIZE / 2",
"coordinates (for given Z) def seq2xyz(seq_arr): \"\"\" Convert octomap sequence (0..7) into XYZ",
"import argparse from osgar.lib.serialize import deserialize from osgar.logger import LogReader, lookup_stream_id parser =",
"SLICE_OCTOMAP_SIZE), dtype=np.uint8) occupied, free, unknown = data2stack(data) xyz = seq2xyz(free) xyz2img(img, xyz, color=STATE_FREE,",
"+= 1 if key == ord('s'): scaled = not scaled if key ==",
"pyplot frontiers') args = parser.parse_args() octomap_stream_id = lookup_stream_id(args.logfile, 'fromrospy.octomap') pose3d_stream_id = lookup_stream_id(args.logfile, 'fromrospy.pose3d')",
"image/level \"\"\" img = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE), dtype=np.uint8) occupied, free, unknown = data2stack(data) xyz",
"frontier (free-unknown transition) :param img: color image with free=white, unknown=green :param start: start",
"'')) key = cv2.waitKey(1) & 0xFF KEY_Q = ord('q') if key == KEY_Q:",
":, 1] = img3d[:, :, level] img2[:, :, 2] = img3d[:, :, level]",
"= config.get('min_z', 0.5) # should be multiply of \"resolution\" self.max_z = config.get('max_z', 0.5)",
"color=(255, 0, 0), thickness=-1) cv2.circle(img2, start[:2], radius=0, color=(39, 127, 255), thickness=-1) cv2.imwrite('octo_cut.png', img2)",
"size <= 16, size d = 2 ** (16 - size) if z",
"the limits are included self.resolution = config.get('resolution', 0.5) self.verbose = False def on_sim_time_sec(self,",
"exploration path return img, None score = np.zeros(len(xy[0])) for i in range(len(xy[0])): x,",
"<= 16, size d = 2 ** (16 - size) if z <=",
"color=(0xFF, 0xFF, 0xFF) STATE_OCCUPIED = 1 # color=(0x00, 0x00, 0xFF) ... just to",
"= math.hypot(x - x2, y - y2) if dist < 10 and score[i]",
"given list of voxels into existing image :param img: I/O image :param xyz:",
"'ro') plt.axes().set_aspect('equal', 'datalim') plt.show() drivable = white # use 1 pixel surrounding drivable_safe_y",
"y, z in path: img[y][x] = STATE_PATH else: print('Path not found!') return img,",
"img3d[:, :, level] img2[:, :, 2] = img3d[:, :, level] __, path =",
"<= ord('9'): level = key - ord('0') if key == ord('m'): level -=",
"* 2)[0] for rot in range(14, -2, -2): # range(0, 16, 2): val",
"def data2maplevel(data, level): \"\"\" Convert Octomap data to image/level \"\"\" img = np.zeros((SLICE_OCTOMAP_SIZE,",
"free=white, unknown=green :param start: start pixel :param draw: debug frontiers in pyplot :return:",
"# range(0, 16, 2): val = (d & (0x3 << rot)) >> rot",
"dx in [-1, 0, 1]: for dy in [-1, 0, 1]: for dz",
"drivable = np.vstack([z, tmp, z]) for limit_score in [3*max(score)/4, max(score)/4, 0]: # select",
"= np.zeros((size[0] - 2, 1, size[2]), dtype=np.bool) tmp = np.hstack([z, drivable_safe_xy, z]) z",
"color image with free=white, unknown=green :param start: start pixel :param draw: debug frontiers",
"3), dtype=np.uint8) level = max(0, min(num_z_levels - 1, start[2])) img2[:, :, 0] =",
"= self.pose3d[0] start = int(SLICE_OCTOMAP_SIZE//2 + x/self.resolution), int(SLICE_OCTOMAP_SIZE//2 - y/self.resolution), int((z - self.min_z)/self.resolution)",
"simulated seconds if self.waypoints_sent_time is not None and self.waypoints_sent_time > self.time: self.publish('dropped', self.time_limit_sec)",
"pcd = o3d.geometry.PointCloud() xyz = np.array(all) pcd.points = o3d.utility.Vector3dVector(xyz) voxel_grid = o3d.geometry.VoxelGrid.create_from_point_cloud(pcd, voxel_size=0.1)",
"path class Octomap(Node): def __init__(self, config, bus): super().__init__(config, bus) bus.register('waypoints', 'dropped') self.prev_data =",
"in [3*max(score)/4, max(score)/4, 0]: # select goal positions above the limit_score # note,",
"= o3d.utility.Vector3dVector(waypoints) line_set.lines = o3d.utility.Vector2iVector(lines) line_set.colors = o3d.utility.Vector3dVector(colors) o3d.visualization.draw_geometries([line_set, voxel_grid]) if not paused:",
"<= size <= 16, size d = 2 ** (16 - size) if",
"%.02f)' % tuple(pose3d[0]) if pose3d is not None else 'None' cv2.setWindowTitle('Octomap', f'Octomap {time},",
"z = np.zeros((size[0] - 2, 1, size[2]), dtype=np.bool) tmp = np.hstack([z, drivable_safe_xy, z])",
"assert len(stack) == 0, len(stack) return occupied, free, unknown def data2maplevel(data, level): \"\"\"",
"plt line = plt.plot(xy[1]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0], 'bo') m = score > 3*max(score)/4 plt.plot(xy[1][m] -",
"SLICE_OCTOMAP_SIZE//2-xy[0], 'bo') m = score > 3*max(score)/4 plt.plot(xy[1][m] - SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2 - xy[0][m],",
"if self.waypoints_sent_time is not None and self.waypoints_sent_time > self.time: self.publish('dropped', self.time_limit_sec) # log",
"xyz, color=STATE_OCCUPIED, level=level) xyz = seq2xyz(unknown) xyz2img(img, xyz, color=STATE_UNKNOWN, level=level) return img def",
"level, scaled if waypoints is None: waypoints = [] while True: img =",
"255), thickness=-1) if scaled: img = cv2.resize(img[256 + 128:-256 - 128, 256 +",
"currently expects goals as tuple (x, y) and operation \"in\" goals = set(map(tuple,",
"# http://www.arminhornung.de/Research/pub/hornung13auro.pdf # 00: unknown; 01: occupied; 10: free; 11: inner node with",
"in [-1, 0, 1]: for dy in [-1, 0, 1]: for dz in",
"three lists (occupied, free, unknown) :param data: binary octomap data (depth first) :return:",
"code in [2, 3, 6, 7]: y += d if code in [4,",
"= None last_octo_data = None with LogReader(args.logfile, only_stream_id=[octomap_stream_id, pose3d_stream_id, waypoints_stream_id]) as logreader: level",
"score[i] > 0: # ~ 5 meters, only inside score[i] += 1.0 if",
"xyz def xyz2img(img, xyz, color, level=2): \"\"\" Draw given list of voxels into",
"\"on_\" + channel, None) if handler is not None: handler(getattr(self, channel)) else: assert",
"2 xyz.append(((x, y, z), len(seq))) return xyz def xyz2img(img, xyz, color, level=2): \"\"\"",
"size in xyz: x, y, z = pos assert 1 <= size <=",
"None self.pose3d = None self.video_writer = None self.video_outfile = None # 'octo.mp4' #",
"+ 256) % 256 for d in data]) last_octo_data = data key =",
"# experimental trigger of navigation self.waypoints_sent_time = None # unknown self.sim_time_sec = None",
"np.hstack([z, mask, z]) mask_up = green[2:, :, :] & white[1:-1, :, :] mask_down",
"STATE_FREE mask_right = green[:, 2:, :] & white[:, 1:-1, :] mask_left = green[:,",
"data in logreader: data = deserialize(data) if stream == pose3d_stream_id: pose3d = data",
"- xy[0], np.full(len(xy[0]), lev)]).T * res all.extend(xyz.tolist()) pcd = o3d.geometry.PointCloud() xyz = np.array(all)",
"img3d = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE, num_z_levels), dtype=np.uint8) for level in range(num_z_levels): img3d[:, :, level]",
"code in [4, 5, 6, 7]: z += d d //= 2 xyz.append(((x,",
"STATE_FRONTIER if path is not None: for x, y, z in path: img[y][x]",
"to be != 0, which is original unknown/black/undefined STATE_FRONTIER = 196 # color=(0xFF,",
"unknown channel def draw_iteration(data, waypoints=None, paused=False): global level, scaled if waypoints is None:",
"mask3, z], axis=2) | mask xy = np.where(mask) if len(xy[0]) == 0: #",
"break img[mask] = STATE_FRONTIER if path is not None: for x, y, z",
"11: inner node with child next in the stream STATE_UNKNOWN = 128 #",
"0xFF) STATE_OCCUPIED = 1 # color=(0x00, 0x00, 0xFF) ... just to be !=",
"first) :return: (occupied, free, unknown) lists of sequences \"\"\" stack = [[]] unknown",
"position score[i] = math.hypot(x, y) * 0.03 else: score[i] = 0 # too",
"key == ord(' '): paused = not paused if ord('0') <= key <=",
"range(len(lines))] line_set = o3d.geometry.LineSet() line_set.points = o3d.utility.Vector3dVector(waypoints) line_set.lines = o3d.utility.Vector2iVector(lines) line_set.colors = o3d.utility.Vector3dVector(colors)",
"this in cloudsim2osgar data = bytes([(d + 256) % 256 for d in",
"assert len(data) % 2 == 0, len(data) data = bytes([(d + 256) %",
"multiply of \"resolution\" self.max_z = config.get('max_z', 0.5) # the limits are included self.resolution",
"2] = img3d[:, :, level] __, path = frontiers(img3d, start) # this image",
"| mask z_mask_up = green[:, :, 2:] & white[:, :, 1:-1] z_mask_down =",
"x, y, z in zip(f[1], f[0], f[2]): if z == start[2]: cv2.circle(img2, (x,",
"img[:, :, :] == STATE_UNKNOWN white = img[:, :, :] == STATE_FREE mask_right",
"with free=white, unknown=green :param start: start pixel :param draw: debug frontiers in pyplot",
"0x00) SLICE_OCTOMAP_SIZE = 1024 # size of slice/image in XY octomap coordinates (for",
"in seq: if code in [1, 3, 5, 7]: x += d if",
"with LogReader(args.logfile, only_stream_id=[octomap_stream_id, pose3d_stream_id, waypoints_stream_id]) as logreader: level = 2 scaled = True",
"# this image is modified in place anyway if self.verbose: f = (img3d",
"int((z - self.min_z)/self.resolution) num_z_levels = int(round((self.max_z - self.min_z)/self.resolution)) + 1 img3d = np.zeros((SLICE_OCTOMAP_SIZE,",
"'datalim') plt.show() drivable = white # use 1 pixel surrounding drivable_safe_y = drivable[2:,",
"data = deserialize(data) if stream == pose3d_stream_id: pose3d = data x, y, z",
"else: score[i] = 0 # too cruel cut for X positive semi-space, but",
"stack = [[]] unknown = [] free = [] occupied = [] for",
"is None or self.pose3d is None or self.sim_time_sec < self.time_limit_sec: return self.time_limit_sec +=",
"output generation self.min_z = config.get('min_z', 0.5) # should be multiply of \"resolution\" self.max_z",
"np.vstack([z, mask2, z]) | mask z_mask_up = green[:, :, 2:] & white[:, :,",
"start and path, path \"\"\" size = img.shape green = img[:, :, :]",
"not paused if ord('0') <= key <= ord('9'): level = key - ord('0')",
"radius=0, color=(39, 127, 255), thickness=-1) cv2.imwrite('octo_cut.png', img2) # used for replay debugging if",
"for dz in [0]: #[-1, 0, 1]: goals.append(xy2 + np.repeat(np.asarray([[dy], [dx], [dz]]), xy2.shape[1],",
"= None self.pose3d = None self.video_writer = None self.video_outfile = None # 'octo.mp4'",
"= 2 ** (16 - size) if z <= level < z +",
"color=(255, 0, 255), thickness=-1) if path is not None: for x, y, z",
"= 1 # color=(0x00, 0x00, 0xFF) ... just to be != 0, which",
"6, 7]: z += d d //= 2 xyz.append(((x, y, z), len(seq))) return",
"(occupied, free, unknown) :param data: binary octomap data (depth first) :return: (occupied, free,",
"in range(num_z_levels): cv2.imwrite('octo_%03d.png' % i, img3d[:, :, i]) img2 = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE, 3),",
"256 for d in data]) last_octo_data = data key = draw_iteration(data, waypoints) if",
"super().update() handler = getattr(self, \"on_\" + channel, None) if handler is not None:",
"if d > 100: # do not try to fill extra large (unknown)",
"cruel cut for X positive semi-space, but let's move INSIDE! for i in",
"& drivable[:-2, :] drivable_safe_xy = drivable_safe_y[:, 2:] & drivable_safe_y[:, 1:-1] & drivable_safe_y[:, :-2]",
"= data2stack(data) xyz = seq2xyz(free) xyz2img(img, xyz, color=STATE_FREE, level=level) xyz = seq2xyz(occupied) xyz2img(img,",
"+ x/self.resolution), int(SLICE_OCTOMAP_SIZE//2 - y/self.resolution), int((z - self.min_z)/self.resolution) num_z_levels = int(round((self.max_z - self.min_z)/self.resolution))",
"and operation \"in\" goals = set(map(tuple, goals)) path = find_path(drivable, start, goals, verbose=False)",
"- SLICE_OCTOMAP_SIZE / 2, SLICE_OCTOMAP_SIZE / 2 - xy[0], np.full(len(xy[0]), lev)]).T * res",
"'fromrospy.pose3d') waypoints_stream_id = lookup_stream_id(args.logfile, 'octomap.waypoints') pose3d = None x, y, z = 0,",
"& white[1:-1, :, :] mask_down = green[:-2, :, :] & white[1:-1, :, :]",
"(xyz and \"size\") :param color: value 0..255 to be assigned to voxels at",
"Convert Octomap data to image/level \"\"\" img = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE), dtype=np.uint8) occupied, free,",
"1: free.append(prefix + [rot // 2]) elif val == 0: unknown.append(prefix + [rot",
"= ord('q') if key == KEY_Q: break if key == ord(' '): paused",
"channel # unknown channel def draw_iteration(data, waypoints=None, paused=False): global level, scaled if waypoints",
"** (16 - size) if z <= level < z + d: if",
"pose3d[0] start = int(SLICE_OCTOMAP_SIZE//2 + x/resolution), int(SLICE_OCTOMAP_SIZE//2 - y/resolution), int(z / resolution) continue",
"x, y, z = pose3d[0] start = int(SLICE_OCTOMAP_SIZE//2 + x/resolution), int(SLICE_OCTOMAP_SIZE//2 - y/resolution),",
"# the path planner currently expects goals as tuple (x, y) and operation",
"self.time_limit_sec) # log skipped sim_time return # bit unlucky conversion from existing Python2",
"path return img, None score = np.zeros(len(xy[0])) for i in range(len(xy[0])): x, y",
"waypoints_stream_id = lookup_stream_id(args.logfile, 'octomap.waypoints') pose3d = None x, y, z = 0, 0,",
"= None # 'octo.mp4' # optional video output generation self.min_z = config.get('min_z', 0.5)",
"continue assert len(data) % 2 == 0, len(data) # TODO fix this in",
"plt.plot(xy[1]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0], 'bo') m = score > 3*max(score)/4 plt.plot(xy[1][m] - SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2 -",
"= np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE), dtype=np.uint8) occupied, free, unknown = data2stack(data) xyz = seq2xyz(free) xyz2img(img,",
"0, len(stack) return occupied, free, unknown def data2maplevel(data, level): \"\"\" Convert Octomap data",
"255 # color=(0xFF, 0xFF, 0xFF) STATE_OCCUPIED = 1 # color=(0x00, 0x00, 0xFF) ...",
"None: waypoints = [] while True: img = data2maplevel(data, level=level) cv2.circle(img, start[:2], radius=0,",
"y)/2, z * self.resolution + self.min_z] for x, y, z in path] def",
"[] self.waypoints = None # experimental trigger of navigation self.waypoints_sent_time = None #",
"resolution and detect gate as one way only (0 is not sufficient due",
"in [0]: #[-1, 0, 1]: goals.append(xy2 + np.repeat(np.asarray([[dy], [dx], [dz]]), xy2.shape[1], axis=1)) goals",
"= None x, y, z = 0, 0, 0 resolution = 0.5 waypoints",
"cloudsim2osgar data = bytes([(d + 256) % 256 for d in data]) last_octo_data",
"optional? continue assert len(data) % 2 == 0, len(data) # TODO fix this",
"if path is not None: for x, y, z in path: cv2.circle(img2, (x,",
"* res all.extend(xyz.tolist()) pcd = o3d.geometry.PointCloud() xyz = np.array(all) pcd.points = o3d.utility.Vector3dVector(xyz) voxel_grid",
"ord('q'): break waypoints = None # force wait for next waypoints message if",
"used for replay debugging if self.video_outfile is not None: if self.video_writer is None:",
"| mask_down mask = np.vstack([z, mask2, z]) | mask z_mask_up = green[:, :,",
"= np.zeros((1, size[1], size[2]), dtype=np.bool) mask2 = mask_up | mask_down mask = np.vstack([z,",
"px):min(SLICE_OCTOMAP_SIZE, px+d)] = color return img def data2stack(data): \"\"\" Convert binary ocotomap data",
"from osgar.logger import LogReader, lookup_stream_id parser = argparse.ArgumentParser(\"Analyze ocotomap data\") parser.add_argument('logfile', help='path to",
"val == 2: occupied.append(prefix + [rot // 2]) elif val == 1: free.append(prefix",
"help='draw pyplot frontiers') args = parser.parse_args() octomap_stream_id = lookup_stream_id(args.logfile, 'fromrospy.octomap') pose3d_stream_id = lookup_stream_id(args.logfile,",
"= SLICE_OCTOMAP_SIZE//2 + x py = SLICE_OCTOMAP_SIZE//2 - y img[max(0, py-d+1):min(SLICE_OCTOMAP_SIZE, py+1), max(0,",
"int(SLICE_OCTOMAP_SIZE//2 + x/self.resolution), int(SLICE_OCTOMAP_SIZE//2 - y/self.resolution), int((z - self.min_z)/self.resolution) num_z_levels = int(round((self.max_z -",
"in [-1, 0, 1]: for dz in [0]: #[-1, 0, 1]: goals.append(xy2 +",
"given Z) def seq2xyz(seq_arr): \"\"\" Convert octomap sequence (0..7) into XYZ coordinate :param",
"deserialize from osgar.logger import LogReader, lookup_stream_id parser = argparse.ArgumentParser(\"Analyze ocotomap data\") parser.add_argument('logfile', help='path",
"1, size[2]), dtype=np.bool) tmp = np.hstack([z, drivable_safe_xy, z]) z = np.zeros((1, size[1], size[2]),",
"in path: cv2.circle(img2, (x, y), radius=0, color=(255, 0, 0), thickness=-1) cv2.circle(img2, start[:2], radius=0,",
"matplotlib.pyplot as plt line = plt.plot(xy[1]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0], 'bo') m = score > 3*max(score)/4",
"16, 2): val = (d & (0x3 << rot)) >> rot if val",
"import open3d as o3d res = 0.5 all = [] for lev in",
"unknown = [] free = [] occupied = [] for i in range(len(data)",
"2 scaled = True for time, stream, data in logreader: data = deserialize(data)",
"x, y = xy[1][i]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][i] for j in range(len(xy[0])): x2, y2 = xy[1][j]-SLICE_OCTOMAP_SIZE//2,",
"int(SLICE_OCTOMAP_SIZE//2 - y/resolution), int(z / resolution) continue if stream == waypoints_stream_id: waypoints =",
"1 img3d = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE, num_z_levels), dtype=np.uint8) for level in range(num_z_levels): img3d[:, :,",
"# force wait for next waypoints message if last_octo_data is not None: draw_iteration(last_octo_data,",
"(shorted the sequence bigger the voxel) \"\"\" xyz = [] if len(seq_arr) ==",
"= config.get('resolution', 0.5) self.verbose = False def on_sim_time_sec(self, data): if self.time_limit_sec is None:",
"% 256 for d in data]) last_octo_data = data key = draw_iteration(data, waypoints)",
"trigger of navigation self.waypoints_sent_time = None # unknown self.sim_time_sec = None self.pose3d =",
"binary octomap data (depth first) :return: (occupied, free, unknown) lists of sequences \"\"\"",
"path to PNG image', default='out.png') parser.add_argument('--draw', action='store_true', help='draw pyplot frontiers') args = parser.parse_args()",
"updated image \"\"\" for pos, size in xyz: x, y, z = pos",
"drivable[1:-1, :] & drivable[:-2, :] drivable_safe_xy = drivable_safe_y[:, 2:] & drivable_safe_y[:, 1:-1] &",
"if key == KEY_Q: break if key == ord(' '): paused = not",
"size of slice/image in XY octomap coordinates (for given Z) def seq2xyz(seq_arr): \"\"\"",
"to logfile with octomap data') parser.add_argument('--out', help='output path to PNG image', default='out.png') parser.add_argument('--draw',",
"img: I/O image :param xyz: list of voxels (xyz and \"size\") :param color:",
"modified in place anyway if self.verbose: f = (img3d == STATE_FRONTIER).nonzero() for x,",
"x, y, z = -32767, -32767, -32767 for code in seq: if code",
"# ~ 5 meters, only inside score[i] += 1.0 if draw: import matplotlib.pyplot",
"debug frontiers in pyplot :return: extended image with drawn start and path, path",
"= argparse.ArgumentParser(\"Analyze ocotomap data\") parser.add_argument('logfile', help='path to logfile with octomap data') parser.add_argument('--out', help='output",
"6, 7]: y += d if code in [4, 5, 6, 7]: z",
"# color=(0xFF, 0xFF, 0xFF) STATE_OCCUPIED = 1 # color=(0x00, 0x00, 0xFF) ... just",
"self.max_z = config.get('max_z', 0.5) # the limits are included self.resolution = config.get('resolution', 0.5)",
"- 1) x, y, z = -32767, -32767, -32767 for code in seq:",
"frontier. As a workaround add also all 8-neighbors of frontiers. goals = []",
"image size z = np.zeros((size[0] - 2, 1, size[2]), dtype=np.bool) tmp = np.hstack([z,",
"X positive semi-space, but let's move INSIDE! for i in range(len(xy[0])): x, y",
"path: cv2.circle(img2, (x, y), radius=0, color=(255, 0, 0), thickness=-1) cv2.circle(img2, start[:2], radius=0, color=(39,",
"False, channel # unknown channel def draw_iteration(data, waypoints=None, paused=False): global level, scaled if",
"mask2 = mask_up | mask_down mask = np.vstack([z, mask2, z]) | mask z_mask_up",
"maybe optional? continue assert len(data) % 2 == 0, len(data) # TODO fix",
"image with drawn start and path, path \"\"\" size = img.shape green =",
"self.publish('waypoints', self.waypoints) self.waypoints = None def on_octomap(self, data): if self.sim_time_sec is None or",
"score > limit_score] for dx in [-1, 0, 1]: for dy in [-1,",
"[] if len(seq_arr) == 0: return xyz max_len = max([len(s) for s in",
"= np.zeros((size[0], 1, size[2]), dtype=np.bool) mask = np.hstack([z, mask, z]) mask_up = green[2:,",
"data\") parser.add_argument('logfile', help='path to logfile with octomap data') parser.add_argument('--out', help='output path to PNG",
"SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2 - xy[0][m], 'ro') plt.axes().set_aspect('equal', 'datalim') plt.show() drivable = white # use",
"np.zeros(len(xy[0])) for i in range(len(xy[0])): x, y = xy[1][i]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][i] if x >",
"+ 1] for i in range(len(waypoints) - 1)] colors = [[1, 0, 0]",
"start = int(SLICE_OCTOMAP_SIZE//2 + x/self.resolution), int(SLICE_OCTOMAP_SIZE//2 - y/self.resolution), int((z - self.min_z)/self.resolution) num_z_levels =",
"as one way only (0 is not sufficient due to impecise position score[i]",
"% 2 == 0, len(data) # TODO fix this in cloudsim2osgar data =",
"not None: break img[mask] = STATE_FRONTIER if path is not None: for x,",
"of navigation self.waypoints_sent_time = None # unknown self.sim_time_sec = None self.pose3d = None",
"- x2, y - y2) if dist < 10 and score[i] > 0:",
"in place anyway if self.verbose: f = (img3d == STATE_FRONTIER).nonzero() for x, y,",
"None # force wait for next waypoints message if last_octo_data is not None:",
"= bytes([(d + 256) % 256 for d in data]) x, y, z",
"TODO - resolution and detect gate as one way only (0 is not",
"xyz, color, level=2): \"\"\" Draw given list of voxels into existing image :param",
"data to image/level \"\"\" img = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE), dtype=np.uint8) occupied, free, unknown =",
"= [] occupied = [] for i in range(len(data) // 2): prefix =",
"into existing image :param img: I/O image :param xyz: list of voxels (xyz",
"[rot // 2]) elif val == 2: occupied.append(prefix + [rot // 2]) elif",
"z == start[2]: cv2.circle(img2, (x, y), radius=0, color=(255, 0, 255), thickness=-1) if path",
"else: assert False, channel # unknown channel def draw_iteration(data, waypoints=None, paused=False): global level,",
"f[2]): if z == start[2]: cv2.circle(img2, (x, y), radius=0, color=(255, 0, 255), thickness=-1)",
"osgar.node import Node from osgar.lib.pplanner import find_path # http://www.arminhornung.de/Research/pub/hornung13auro.pdf # 00: unknown; 01:",
"return img, path class Octomap(Node): def __init__(self, config, bus): super().__init__(config, bus) bus.register('waypoints', 'dropped')",
"self.prev_data = None self.time_limit_sec = None # initialized with the first sim_time_sec self.debug_arr",
"color, level=2): \"\"\" Draw given list of voxels into existing image :param img:",
"y) and operation \"in\" goals = set(map(tuple, goals)) path = find_path(drivable, start, goals,",
"on_octomap(self, data): if self.sim_time_sec is None or self.pose3d is None or self.sim_time_sec <",
"'dropped') self.prev_data = None self.time_limit_sec = None # initialized with the first sim_time_sec",
"Octomap(Node): def __init__(self, config, bus): super().__init__(config, bus) bus.register('waypoints', 'dropped') self.prev_data = None self.time_limit_sec",
"is None or self.sim_time_sec < self.time_limit_sec: return self.time_limit_sec += 1 # simulated seconds",
"into three lists (occupied, free, unknown) :param data: binary octomap data (depth first)",
"from osgar.node import Node from osgar.lib.pplanner import find_path # http://www.arminhornung.de/Research/pub/hornung13auro.pdf # 00: unknown;",
"self.waypoints = None # experimental trigger of navigation self.waypoints_sent_time = None # unknown",
"self.video_outfile = None # 'octo.mp4' # optional video output generation self.min_z = config.get('min_z',",
"np.array( [xy[1] - SLICE_OCTOMAP_SIZE / 2, SLICE_OCTOMAP_SIZE / 2 - xy[0], np.full(len(xy[0]), lev)]).T",
"# color=(0xFF, 0x00, 0xFF) STATE_PATH = 64 # color=(0xFF, 0x00, 0x00) SLICE_OCTOMAP_SIZE =",
"pos, size in xyz: x, y, z = pos assert 1 <= size",
"lookup_stream_id(args.logfile, 'fromrospy.octomap') pose3d_stream_id = lookup_stream_id(args.logfile, 'fromrospy.pose3d') waypoints_stream_id = lookup_stream_id(args.logfile, 'octomap.waypoints') pose3d = None",
"if dist < 10 and score[i] > 0: # ~ 5 meters, only",
"height)) self.video_writer.write(img2) if path is not None: self.waypoints = [[(x - SLICE_OCTOMAP_SIZE//2)/2, (SLICE_OCTOMAP_SIZE//2",
"np.hstack(goals).T[:, [1, 0, 2]] # the path planner currently expects goals as tuple",
"mask3 = z_mask_up | z_mask_down # mask = np.concatenate([z, mask3, z], axis=2) |",
"2 == 0, len(data) data = bytes([(d + 256) % 256 for d",
"xy[0][m], 'ro') plt.axes().set_aspect('equal', 'datalim') plt.show() drivable = white # use 1 pixel surrounding",
"inside score[i] += 1.0 if draw: import matplotlib.pyplot as plt line = plt.plot(xy[1]-SLICE_OCTOMAP_SIZE//2,",
"level] img2[:, :, 1] = img3d[:, :, level] img2[:, :, 2] = img3d[:,",
"= np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE, 3), dtype=np.uint8) level = max(0, min(num_z_levels - 1, start[2])) img2[:,",
"color=STATE_FREE, level=level) xyz = seq2xyz(occupied) xyz2img(img, xyz, color=STATE_OCCUPIED, level=level) xyz = seq2xyz(unknown) xyz2img(img,",
"node with child next in the stream STATE_UNKNOWN = 128 # color=(0, 0xFF,",
"ord('m'): level -= 1 if key == ord('p'): level += 1 if key",
"level += 1 if key == ord('s'): scaled = not scaled if key",
"y - y2) if dist < 10 and score[i] > 0: # ~",
"x, y, z in path: img[y][x] = STATE_PATH else: print('Path not found!') return",
"len(data) # TODO fix this in cloudsim2osgar data = bytes([(d + 256) %",
"+ np.repeat(np.asarray([[dy], [dx], [dz]]), xy2.shape[1], axis=1)) goals = np.hstack(goals).T[:, [1, 0, 2]] #",
"navigation self.waypoints_sent_time = None # unknown self.sim_time_sec = None self.pose3d = None self.video_writer",
"list of voxels (xyz and \"size\") :param color: value 0..255 to be assigned",
"Find path to the best frontier (free-unknown transition) :param img: color image with",
"= deserialize(data) if stream == pose3d_stream_id: pose3d = data x, y, z =",
"assert 1 <= size <= 16, size d = 2 ** (16 -",
"if ord('0') <= key <= ord('9'): level = key - ord('0') if key",
"draw_iteration(data, waypoints=None, paused=False): global level, scaled if waypoints is None: waypoints = []",
"at given level :param level: Z-level for the cut :return: updated image \"\"\"",
"transition) :param img: color image with free=white, unknown=green :param start: start pixel :param",
"# too cruel cut for X positive semi-space, but let's move INSIDE! for",
"for replay debugging if self.video_outfile is not None: if self.video_writer is None: fps",
"math.hypot(x, y) * 0.03 else: score[i] = 0 # too cruel cut for",
"use 1 pixel surrounding drivable_safe_y = drivable[2:, :] & drivable[1:-1, :] & drivable[:-2,",
"for x, y, z in path: img[y][x] = STATE_PATH else: print('Path not found!')",
"None with LogReader(args.logfile, only_stream_id=[octomap_stream_id, pose3d_stream_id, waypoints_stream_id]) as logreader: level = 2 scaled =",
"white[1:-1, :, :] mask_down = green[:-2, :, :] & white[1:-1, :, :] z",
"not None: for x, y, z in path: cv2.circle(img2, (x, y), radius=0, color=(255,",
"= img3d[:, :, level] __, path = frontiers(img3d, start) # this image is",
"[3*max(score)/4, max(score)/4, 0]: # select goal positions above the limit_score # note, that",
"if path is not None: self.waypoints = [[(x - SLICE_OCTOMAP_SIZE//2)/2, (SLICE_OCTOMAP_SIZE//2 - y)/2,",
"1 pixel surrounding drivable_safe_y = drivable[2:, :] & drivable[1:-1, :] & drivable[:-2, :]",
"/ 2 - xy[0], np.full(len(xy[0]), lev)]).T * res all.extend(xyz.tolist()) pcd = o3d.geometry.PointCloud() xyz",
"self.waypoints is not None: print('Waypoints', data[0], self.waypoints[0], self.waypoints[-1]) self.waypoints_sent_time = self.publish('waypoints', self.waypoints) self.waypoints",
"= img.shape green = img[:, :, :] == STATE_UNKNOWN white = img[:, :,",
"existing Python2 data assert len(data) % 2 == 0, len(data) data = bytes([(d",
"# the limits are included self.resolution = config.get('resolution', 0.5) self.verbose = False def",
"= score > 3*max(score)/4 plt.plot(xy[1][m] - SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2 - xy[0][m], 'ro') plt.axes().set_aspect('equal', 'datalim')",
"radius=0, color=(255, 0, 255), thickness=-1) if path is not None: for x, y,",
"img def frontiers(img, start, draw=False): \"\"\" Find path to the best frontier (free-unknown",
"(0..7) into XYZ coordinate :param seq_arr: list of parent-child sequences for one of",
"% tuple(pose3d[0]) if pose3d is not None else 'None' cv2.setWindowTitle('Octomap', f'Octomap {time}, {pose_str},",
"# note, that the \"safe path\" does not touch external boundary so it",
"zip(f[1], f[0], f[2]): if z == start[2]: cv2.circle(img2, (x, y), radius=0, color=(255, 0,",
"or self.sim_time_sec < self.time_limit_sec: return self.time_limit_sec += 1 # simulated seconds if self.waypoints_sent_time",
"Octomap data to image/level \"\"\" img = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE), dtype=np.uint8) occupied, free, unknown",
"np.where(img == STATE_OCCUPIED) xyz = np.array( [xy[1] - SLICE_OCTOMAP_SIZE / 2, SLICE_OCTOMAP_SIZE /",
"int(z / resolution) continue if stream == waypoints_stream_id: waypoints = data continue if",
"path] def update(self): channel = super().update() handler = getattr(self, \"on_\" + channel, None)",
"i in range(len(lines))] line_set = o3d.geometry.LineSet() line_set.points = o3d.utility.Vector3dVector(waypoints) line_set.lines = o3d.utility.Vector2iVector(lines) line_set.colors",
"= green[:, :-2, :] & white[:, 1:-1, :] mask = mask_left | mask_right",
"128:-256 - 128, 256 + 128:-256 - 128], img.shape) cv2.imshow('Octomap', img) pose_str =",
"data, i * 2)[0] for rot in range(14, -2, -2): # range(0, 16,",
"# mask = np.concatenate([z, mask3, z], axis=2) | mask xy = np.where(mask) if",
"== STATE_FREE mask_right = green[:, 2:, :] & white[:, 1:-1, :] mask_left =",
"for code in seq: if code in [1, 3, 5, 7]: x +=",
"ocotomap data\") parser.add_argument('logfile', help='path to logfile with octomap data') parser.add_argument('--out', help='output path to",
"= None # unknown self.sim_time_sec = None self.pose3d = None self.video_writer = None",
"% i, img3d[:, :, i]) img2 = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE, 3), dtype=np.uint8) level =",
"sequence bigger the voxel) \"\"\" xyz = [] if len(seq_arr) == 0: return",
"unknown = data2stack(data) xyz = seq2xyz(free) xyz2img(img, xyz, color=STATE_FREE, level=level) xyz = seq2xyz(occupied)",
"level] __, path = frontiers(img3d, start) # this image is modified in place",
"data = bytes([(d + 256) % 256 for d in data]) last_octo_data =",
"range(num_z_levels): cv2.imwrite('octo_%03d.png' % i, img3d[:, :, i]) img2 = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE, 3), dtype=np.uint8)",
"== 1: free.append(prefix + [rot // 2]) elif val == 0: unknown.append(prefix +",
"# bit unlucky conversion from existing Python2 data assert len(data) % 2 ==",
"surrounding drivable_safe_y = drivable[2:, :] & drivable[1:-1, :] & drivable[:-2, :] drivable_safe_xy =",
"None: for x, y, z in path: cv2.circle(img2, (x, y), radius=0, color=(255, 0,",
"in xyz: x, y, z = pos assert 1 <= size <= 16,",
"lists (occupied, free, unknown) :param data: binary octomap data (depth first) :return: (occupied,",
"for i in range(len(xy[0])): x, y = xy[1][i]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][i] if x > 4:",
"z = pos assert 1 <= size <= 16, size d = 2",
"%.02f, %.02f)' % tuple(pose3d[0]) if pose3d is not None else 'None' cv2.setWindowTitle('Octomap', f'Octomap",
"up display/processing - maybe optional? continue assert len(data) % 2 == 0, len(data)",
"'(%.02f, %.02f, %.02f)' % tuple(pose3d[0]) if pose3d is not None else 'None' cv2.setWindowTitle('Octomap',",
"key <= ord('9'): level = key - ord('0') if key == ord('m'): level",
"xy[1][i]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][i] if x > 4: # TODO - resolution and detect gate",
"xy = np.where(img == STATE_OCCUPIED) xyz = np.array( [xy[1] - SLICE_OCTOMAP_SIZE / 2,",
"y, z = 0, 0, 0 resolution = 0.5 waypoints = None last_octo_data",
"z += d d //= 2 xyz.append(((x, y, z), len(seq))) return xyz def",
"last_octo_data = None with LogReader(args.logfile, only_stream_id=[octomap_stream_id, pose3d_stream_id, waypoints_stream_id]) as logreader: level = 2",
"y, z in path: cv2.circle(img2, (x, y), radius=0, color=(255, 0, 0), thickness=-1) cv2.circle(img2,",
"/ resolution) continue if stream == waypoints_stream_id: waypoints = data continue if waypoints",
"global level, scaled if waypoints is None: waypoints = [] while True: img",
"image \"\"\" for pos, size in xyz: x, y, z = pos assert",
"STATE_UNKNOWN = 128 # color=(0, 0xFF, 0) STATE_FREE = 255 # color=(0xFF, 0xFF,",
"= pose3d[0] start = int(SLICE_OCTOMAP_SIZE//2 + x/resolution), int(SLICE_OCTOMAP_SIZE//2 - y/resolution), int(z / resolution)",
"len(stack) == 0, len(stack) return occupied, free, unknown def data2maplevel(data, level): \"\"\" Convert",
"[0]: #[-1, 0, 1]: goals.append(xy2 + np.repeat(np.asarray([[dy], [dx], [dz]]), xy2.shape[1], axis=1)) goals =",
"max(0, min(num_z_levels - 1, start[2])) img2[:, :, 0] = img3d[:, :, level] img2[:,",
"{time}, {pose_str}, level={level}' + (' (paused)' if paused else '')) key = cv2.waitKey(1)",
"255), thickness=-1) if path is not None: for x, y, z in path:",
"= img2.shape[:2] self.video_writer = cv2.VideoWriter(self.video_outfile, cv2.VideoWriter_fourcc(*\"mp4v\"), fps, (width, height)) self.video_writer.write(img2) if path is",
"3: stack.insert(0, prefix + [rot // 2]) elif val == 2: occupied.append(prefix +",
"| mask xy = np.where(mask) if len(xy[0]) == 0: # there are no",
"for dx in [-1, 0, 1]: for dy in [-1, 0, 1]: for",
"x/self.resolution), int(SLICE_OCTOMAP_SIZE//2 - y/self.resolution), int((z - self.min_z)/self.resolution) num_z_levels = int(round((self.max_z - self.min_z)/self.resolution)) +",
"unlucky conversion from existing Python2 data assert len(data) % 2 == 0, len(data)",
"for d in data]) last_octo_data = data key = draw_iteration(data, waypoints) if key",
"i in range(len(xy[0])): x, y = xy[1][i]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][i] if x > 4: #",
"= data key = draw_iteration(data, waypoints) if key == ord('q'): break waypoints =",
"7]: x += d if code in [2, 3, 6, 7]: y +=",
"self.min_z)/self.resolution)) + 1 img3d = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE, num_z_levels), dtype=np.uint8) for level in range(num_z_levels):",
"d d //= 2 xyz.append(((x, y, z), len(seq))) return xyz def xyz2img(img, xyz,",
"i in range(len(xy[0])): x, y = xy[1][i]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][i] for j in range(len(xy[0])): x2,",
":param color: value 0..255 to be assigned to voxels at given level :param",
"pose3d = None x, y, z = 0, 0, 0 resolution = 0.5",
"self.video_writer.write(img2) if path is not None: self.waypoints = [[(x - SLICE_OCTOMAP_SIZE//2)/2, (SLICE_OCTOMAP_SIZE//2 -",
"path is not None: self.waypoints = [[(x - SLICE_OCTOMAP_SIZE//2)/2, (SLICE_OCTOMAP_SIZE//2 - y)/2, z",
"2:] & white[:, :, 1:-1] z_mask_down = green[:, :, :-2] & white[:, :,",
"it would never find path # to frontier. As a workaround add also",
"= 0 # too cruel cut for X positive semi-space, but let's move",
"operation \"in\" goals = set(map(tuple, goals)) path = find_path(drivable, start, goals, verbose=False) if",
"ord('p'): level += 1 if key == ord('s'): scaled = not scaled if",
"ord('d'): import open3d as o3d res = 0.5 all = [] for lev",
"colors = [[1, 0, 0] for i in range(len(lines))] line_set = o3d.geometry.LineSet() line_set.points",
"of parent-child sequences for one of given type (free, occupied, unknown) :return: list",
"2)[0] for rot in range(14, -2, -2): # range(0, 16, 2): val =",
"in [2, 3, 6, 7]: y += d if code in [4, 5,",
"for rot in range(14, -2, -2): # range(0, 16, 2): val = (d",
"img def data2stack(data): \"\"\" Convert binary ocotomap data into three lists (occupied, free,",
"path = find_path(drivable, start, goals, verbose=False) if path is not None: break img[mask]",
"= o3d.utility.Vector3dVector(colors) o3d.visualization.draw_geometries([line_set, voxel_grid]) if not paused: break return key if __name__ ==",
"STATE_OCCUPIED) xyz = np.array( [xy[1] - SLICE_OCTOMAP_SIZE / 2, SLICE_OCTOMAP_SIZE / 2 -",
"(occupied, free, unknown) lists of sequences \"\"\" stack = [[]] unknown = []",
"- y/resolution), int(z / resolution) continue if stream == waypoints_stream_id: waypoints = data",
"level=level) xyz = seq2xyz(unknown) xyz2img(img, xyz, color=STATE_UNKNOWN, level=level) return img def frontiers(img, start,",
"parsing and processing \"\"\" import struct import math import numpy as np import",
"stream == waypoints_stream_id: waypoints = data continue if waypoints is None: # speed",
"== ord('m'): level -= 1 if key == ord('p'): level += 1 if",
"img2[:, :, 0] = img3d[:, :, level] img2[:, :, 1] = img3d[:, :,",
"= np.zeros((size[0], size[1], 1), dtype=np.bool) mask3 = z_mask_up | z_mask_down # mask =",
"import matplotlib.pyplot as plt line = plt.plot(xy[1]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0], 'bo') m = score >",
"x, y, z = self.pose3d[0] start = int(SLICE_OCTOMAP_SIZE//2 + x/self.resolution), int(SLICE_OCTOMAP_SIZE//2 - y/self.resolution),",
"= int(SLICE_OCTOMAP_SIZE//2 + x/resolution), int(SLICE_OCTOMAP_SIZE//2 - y/resolution), int(z / resolution) continue if stream",
"above the limit_score # note, that the \"safe path\" does not touch external",
"f = (img3d == STATE_FRONTIER).nonzero() for x, y, z in zip(f[1], f[0], f[2]):",
":, :] z = np.zeros((1, size[1], size[2]), dtype=np.bool) mask2 = mask_up | mask_down",
"found!') return img, path class Octomap(Node): def __init__(self, config, bus): super().__init__(config, bus) bus.register('waypoints',",
"= [] for lev in range(-3, 10): img = data2maplevel(data, level=lev) xy =",
"self.min_z = config.get('min_z', 0.5) # should be multiply of \"resolution\" self.max_z = config.get('max_z',",
"handler = getattr(self, \"on_\" + channel, None) if handler is not None: handler(getattr(self,",
"for X positive semi-space, but let's move INSIDE! for i in range(len(xy[0])): x,",
"= frontiers(img3d, start) # this image is modified in place anyway if self.verbose:",
"# should be multiply of \"resolution\" self.max_z = config.get('max_z', 0.5) # the limits",
"are no frontiers, i.e. no exploration path return img, None score = np.zeros(len(xy[0]))",
"size[2]), dtype=np.bool) drivable = np.vstack([z, tmp, z]) for limit_score in [3*max(score)/4, max(score)/4, 0]:",
"lists of sequences \"\"\" stack = [[]] unknown = [] free = []",
"= cv2.VideoWriter(self.video_outfile, cv2.VideoWriter_fourcc(*\"mp4v\"), fps, (width, height)) self.video_writer.write(img2) if path is not None: self.waypoints",
"draw: debug frontiers in pyplot :return: extended image with drawn start and path,",
"0, 255), thickness=-1) if path is not None: for x, y, z in",
"max([len(s) for s in seq_arr]) for seq in seq_arr: d = 2 **",
"0: # there are no frontiers, i.e. no exploration path return img, None",
"white[1:-1, :, :] z = np.zeros((1, size[1], size[2]), dtype=np.bool) mask2 = mask_up |",
"in data]) last_octo_data = data key = draw_iteration(data, waypoints) if key == ord('q'):",
"Node from osgar.lib.pplanner import find_path # http://www.arminhornung.de/Research/pub/hornung13auro.pdf # 00: unknown; 01: occupied; 10:",
"0, len(data) # TODO fix this in cloudsim2osgar data = bytes([(d + 256)",
"xy[0], np.full(len(xy[0]), lev)]).T * res all.extend(xyz.tolist()) pcd = o3d.geometry.PointCloud() xyz = np.array(all) pcd.points",
"self.waypoints[0], self.waypoints[-1]) self.waypoints_sent_time = self.publish('waypoints', self.waypoints) self.waypoints = None def on_octomap(self, data): if",
"path \"\"\" size = img.shape green = img[:, :, :] == STATE_UNKNOWN white",
"should be multiply of \"resolution\" self.max_z = config.get('max_z', 0.5) # the limits are",
"\"\"\" ROS Binary Octomap parsing and processing \"\"\" import struct import math import",
"num_z_levels = int(round((self.max_z - self.min_z)/self.resolution)) + 1 img3d = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE, num_z_levels), dtype=np.uint8)",
"cv2.VideoWriter(self.video_outfile, cv2.VideoWriter_fourcc(*\"mp4v\"), fps, (width, height)) self.video_writer.write(img2) if path is not None: self.waypoints =",
"bus.register('waypoints', 'dropped') self.prev_data = None self.time_limit_sec = None # initialized with the first",
"the stream STATE_UNKNOWN = 128 # color=(0, 0xFF, 0) STATE_FREE = 255 #",
"= None self.video_outfile = None # 'octo.mp4' # optional video output generation self.min_z",
"seq2xyz(free) xyz2img(img, xyz, color=STATE_FREE, level=level) xyz = seq2xyz(occupied) xyz2img(img, xyz, color=STATE_OCCUPIED, level=level) xyz",
"0, 2]] # the path planner currently expects goals as tuple (x, y)",
"path planner currently expects goals as tuple (x, y) and operation \"in\" goals",
"config.get('resolution', 0.5) self.verbose = False def on_sim_time_sec(self, data): if self.time_limit_sec is None: self.time_limit_sec",
"1 if key == ord('s'): scaled = not scaled if key == ord('d'):",
"self.resolution = config.get('resolution', 0.5) self.verbose = False def on_sim_time_sec(self, data): if self.time_limit_sec is",
"len(data) % 2 == 0, len(data) # TODO fix this in cloudsim2osgar data",
"LogReader(args.logfile, only_stream_id=[octomap_stream_id, pose3d_stream_id, waypoints_stream_id]) as logreader: level = 2 scaled = True for",
"% 256 for d in data]) x, y, z = self.pose3d[0] start =",
"SLICE_OCTOMAP_SIZE//2 + x py = SLICE_OCTOMAP_SIZE//2 - y img[max(0, py-d+1):min(SLICE_OCTOMAP_SIZE, py+1), max(0, px):min(SLICE_OCTOMAP_SIZE,",
"XYZ coordinate :param seq_arr: list of parent-child sequences for one of given type",
"= key - ord('0') if key == ord('m'): level -= 1 if key",
"None # initialized with the first sim_time_sec self.debug_arr = [] self.waypoints = None",
"[rot // 2]) assert len(stack) == 0, len(stack) return occupied, free, unknown def",
"cv2.setWindowTitle('Octomap', f'Octomap {time}, {pose_str}, level={level}' + (' (paused)' if paused else '')) key",
"i * 2)[0] for rot in range(14, -2, -2): # range(0, 16, 2):",
"xyz: list of voxels (xyz and \"size\") :param color: value 0..255 to be",
"the best frontier (free-unknown transition) :param img: color image with free=white, unknown=green :param",
"None self.time_limit_sec = None # initialized with the first sim_time_sec self.debug_arr = []",
"range(14, -2, -2): # range(0, 16, 2): val = (d & (0x3 <<",
"processing \"\"\" import struct import math import numpy as np import cv2 from",
"mask_right = green[:, 2:, :] & white[:, 1:-1, :] mask_left = green[:, :-2,",
"- xy[0][m], 'ro') plt.axes().set_aspect('equal', 'datalim') plt.show() drivable = white # use 1 pixel",
"mask_up | mask_down mask = np.vstack([z, mask2, z]) | mask z_mask_up = green[:,",
"== 2: occupied.append(prefix + [rot // 2]) elif val == 1: free.append(prefix +",
"d in data]) last_octo_data = data key = draw_iteration(data, waypoints) if key ==",
"of sequences \"\"\" stack = [[]] unknown = [] free = [] occupied",
"level): \"\"\" Convert Octomap data to image/level \"\"\" img = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE), dtype=np.uint8)",
"127, 255), thickness=-1) cv2.imwrite('octo_cut.png', img2) # used for replay debugging if self.video_outfile is",
"= np.where(img == STATE_OCCUPIED) xyz = np.array( [xy[1] - SLICE_OCTOMAP_SIZE / 2, SLICE_OCTOMAP_SIZE",
"[dx], [dz]]), xy2.shape[1], axis=1)) goals = np.hstack(goals).T[:, [1, 0, 2]] # the path",
"== ord('q'): break waypoints = None # force wait for next waypoints message",
"0xFF, 0) STATE_FREE = 255 # color=(0xFF, 0xFF, 0xFF) STATE_OCCUPIED = 1 #",
"struct.unpack_from('<H', data, i * 2)[0] for rot in range(14, -2, -2): # range(0,",
"as plt line = plt.plot(xy[1]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0], 'bo') m = score > 3*max(score)/4 plt.plot(xy[1][m]",
"y += d if code in [4, 5, 6, 7]: z += d",
"size = img.shape green = img[:, :, :] == STATE_UNKNOWN white = img[:,",
"= np.vstack([z, tmp, z]) for limit_score in [3*max(score)/4, max(score)/4, 0]: # select goal",
"1 if key == ord('p'): level += 1 if key == ord('s'): scaled",
"key == ord('s'): scaled = not scaled if key == ord('d'): import open3d",
"import LogReader, lookup_stream_id parser = argparse.ArgumentParser(\"Analyze ocotomap data\") parser.add_argument('logfile', help='path to logfile with",
"def data2stack(data): \"\"\" Convert binary ocotomap data into three lists (occupied, free, unknown)",
"self.min_z] for x, y, z in path] def update(self): channel = super().update() handler",
"& white[:, 1:-1, :] mask_left = green[:, :-2, :] & white[:, 1:-1, :]",
"len(data) data = bytes([(d + 256) % 256 for d in data]) x,",
"= green[:, :, 2:] & white[:, :, 1:-1] z_mask_down = green[:, :, :-2]",
"10): img = data2maplevel(data, level=lev) xy = np.where(img == STATE_OCCUPIED) xyz = np.array(",
"data2stack(data): \"\"\" Convert binary ocotomap data into three lists (occupied, free, unknown) :param",
"res all.extend(xyz.tolist()) pcd = o3d.geometry.PointCloud() xyz = np.array(all) pcd.points = o3d.utility.Vector3dVector(xyz) voxel_grid =",
"y, z = self.pose3d[0] start = int(SLICE_OCTOMAP_SIZE//2 + x/self.resolution), int(SLICE_OCTOMAP_SIZE//2 - y/self.resolution), int((z",
"assigned to voxels at given level :param level: Z-level for the cut :return:",
"def update(self): channel = super().update() handler = getattr(self, \"on_\" + channel, None) if",
"max(score)/4, 0]: # select goal positions above the limit_score # note, that the",
"level=level) cv2.circle(img, start[:2], radius=0, color=(39, 127, 255), thickness=-1) if scaled: img = cv2.resize(img[256",
"1), dtype=np.bool) mask3 = z_mask_up | z_mask_down # mask = np.concatenate([z, mask3, z],",
"from osgar.lib.serialize import deserialize from osgar.logger import LogReader, lookup_stream_id parser = argparse.ArgumentParser(\"Analyze ocotomap",
"xy2.shape[1], axis=1)) goals = np.hstack(goals).T[:, [1, 0, 2]] # the path planner currently",
"<= level < z + d: if d > 100: # do not",
"== 0, len(data) # TODO fix this in cloudsim2osgar data = bytes([(d +",
"white[:, :, 1:-1] z = np.zeros((size[0], size[1], 1), dtype=np.bool) mask3 = z_mask_up |",
"- self.min_z)/self.resolution)) + 1 img3d = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE, num_z_levels), dtype=np.uint8) for level in",
"included self.resolution = config.get('resolution', 0.5) self.verbose = False def on_sim_time_sec(self, data): if self.time_limit_sec",
"== STATE_FRONTIER).nonzero() for x, y, z in zip(f[1], f[0], f[2]): if z ==",
"= color return img def data2stack(data): \"\"\" Convert binary ocotomap data into three",
"np.where(mask) if len(xy[0]) == 0: # there are no frontiers, i.e. no exploration",
"2 ** (max_len - 1) x, y, z = -32767, -32767, -32767 for",
"= np.hstack([z, mask, z]) mask_up = green[2:, :, :] & white[1:-1, :, :]",
"XY octomap coordinates (for given Z) def seq2xyz(seq_arr): \"\"\" Convert octomap sequence (0..7)",
"axis=2) | mask xy = np.where(mask) if len(xy[0]) == 0: # there are",
"import find_path # http://www.arminhornung.de/Research/pub/hornung13auro.pdf # 00: unknown; 01: occupied; 10: free; 11: inner",
"path: img[y][x] = STATE_PATH else: print('Path not found!') return img, path class Octomap(Node):",
"but let's move INSIDE! for i in range(len(xy[0])): x, y = xy[1][i]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][i]",
"from existing Python2 data assert len(data) % 2 == 0, len(data) data =",
"which is original unknown/black/undefined STATE_FRONTIER = 196 # color=(0xFF, 0x00, 0xFF) STATE_PATH =",
"data2maplevel(data, level=level) cv2.circle(img, start[:2], radius=0, color=(39, 127, 255), thickness=-1) if scaled: img =",
"ord('9'): level = key - ord('0') if key == ord('m'): level -= 1",
"ord(' '): paused = not paused if ord('0') <= key <= ord('9'): level",
"= np.vstack([z, mask2, z]) | mask z_mask_up = green[:, :, 2:] & white[:,",
"= np.hstack([z, drivable_safe_xy, z]) z = np.zeros((1, size[1], size[2]), dtype=np.bool) drivable = np.vstack([z,",
"start[:2], radius=0, color=(39, 127, 255), thickness=-1) cv2.imwrite('octo_cut.png', img2) # used for replay debugging",
"continue if stream == waypoints_stream_id: waypoints = data continue if waypoints is None:",
"range(0, 16, 2): val = (d & (0x3 << rot)) >> rot if",
"ord('0') if key == ord('m'): level -= 1 if key == ord('p'): level",
"seq2xyz(seq_arr): \"\"\" Convert octomap sequence (0..7) into XYZ coordinate :param seq_arr: list of",
"Draw given list of voxels into existing image :param img: I/O image :param",
"2]) assert len(stack) == 0, len(stack) return occupied, free, unknown def data2maplevel(data, level):",
"find_path(drivable, start, goals, verbose=False) if path is not None: break img[mask] = STATE_FRONTIER",
"== 0, len(stack) return occupied, free, unknown def data2maplevel(data, level): \"\"\" Convert Octomap",
"\"\"\" size = img.shape green = img[:, :, :] == STATE_UNKNOWN white =",
"z = pose3d[0] start = int(SLICE_OCTOMAP_SIZE//2 + x/resolution), int(SLICE_OCTOMAP_SIZE//2 - y/resolution), int(z /",
"data') parser.add_argument('--out', help='output path to PNG image', default='out.png') parser.add_argument('--draw', action='store_true', help='draw pyplot frontiers')",
"# color=(0, 0xFF, 0) STATE_FREE = 255 # color=(0xFF, 0xFF, 0xFF) STATE_OCCUPIED =",
"= o3d.utility.Vector2iVector(lines) line_set.colors = o3d.utility.Vector3dVector(colors) o3d.visualization.draw_geometries([line_set, voxel_grid]) if not paused: break return key",
"z = np.zeros((size[0], size[1], 1), dtype=np.bool) mask3 = z_mask_up | z_mask_down # mask",
"1:-1, :] mask = mask_left | mask_right z = np.zeros((size[0], 1, size[2]), dtype=np.bool)",
"channel def draw_iteration(data, waypoints=None, paused=False): global level, scaled if waypoints is None: waypoints",
"= 0.5 all = [] for lev in range(-3, 10): img = data2maplevel(data,",
"= None self.time_limit_sec = None # initialized with the first sim_time_sec self.debug_arr =",
":, :] & white[1:-1, :, :] z = np.zeros((1, size[1], size[2]), dtype=np.bool) mask2",
"no frontiers, i.e. no exploration path return img, None score = np.zeros(len(xy[0])) for",
":] mask_left = green[:, :-2, :] & white[:, 1:-1, :] mask = mask_left",
"let's move INSIDE! for i in range(len(xy[0])): x, y = xy[1][i]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][i] for",
"extended image with drawn start and path, path \"\"\" size = img.shape green",
"waypoints=None, paused=False): global level, scaled if waypoints is None: waypoints = [] while",
"1, start[2])) img2[:, :, 0] = img3d[:, :, level] img2[:, :, 1] =",
"original image size z = np.zeros((size[0] - 2, 1, size[2]), dtype=np.bool) tmp =",
"def frontiers(img, start, draw=False): \"\"\" Find path to the best frontier (free-unknown transition)",
"64 # color=(0xFF, 0x00, 0x00) SLICE_OCTOMAP_SIZE = 1024 # size of slice/image in",
"channel, None) if handler is not None: handler(getattr(self, channel)) else: assert False, channel",
"category\" (shorted the sequence bigger the voxel) \"\"\" xyz = [] if len(seq_arr)",
"if not paused: break return key if __name__ == \"__main__\": import argparse from",
"rot in range(14, -2, -2): # range(0, 16, 2): val = (d &",
"= 2 scaled = True for time, stream, data in logreader: data =",
"add non-drivable frame to match original image size z = np.zeros((size[0] - 2,",
"mask2, z]) | mask z_mask_up = green[:, :, 2:] & white[:, :, 1:-1]",
"self.waypoints[-1]) self.waypoints_sent_time = self.publish('waypoints', self.waypoints) self.waypoints = None def on_octomap(self, data): if self.sim_time_sec",
"free.append(prefix + [rot // 2]) elif val == 0: unknown.append(prefix + [rot //",
"cv2.imwrite('octo_%03d.png' % i, img3d[:, :, i]) img2 = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE, 3), dtype=np.uint8) level",
"the voxel) \"\"\" xyz = [] if len(seq_arr) == 0: return xyz max_len",
":, :] mask_down = green[:-2, :, :] & white[1:-1, :, :] z =",
"data assert len(data) % 2 == 0, len(data) data = bytes([(d + 256)",
"note, that the \"safe path\" does not touch external boundary so it would",
"y/resolution), int(z / resolution) continue if stream == waypoints_stream_id: waypoints = data continue",
"axis=1)) goals = np.hstack(goals).T[:, [1, 0, 2]] # the path planner currently expects",
"None) if handler is not None: handler(getattr(self, channel)) else: assert False, channel #",
"in path: img[y][x] = STATE_PATH else: print('Path not found!') return img, path class",
"d > 100: # do not try to fill extra large (unknown) squares,",
"free, unknown) :param data: binary octomap data (depth first) :return: (occupied, free, unknown)",
"= seq2xyz(unknown) xyz2img(img, xyz, color=STATE_UNKNOWN, level=level) return img def frontiers(img, start, draw=False): \"\"\"",
"SLICE_OCTOMAP_SIZE//2-xy[0][i] if x > 4: # TODO - resolution and detect gate as",
":] & white[:, 1:-1, :] mask = mask_left | mask_right z = np.zeros((size[0],",
"\"size category\" (shorted the sequence bigger the voxel) \"\"\" xyz = [] if",
"self.waypoints_sent_time = self.publish('waypoints', self.waypoints) self.waypoints = None def on_octomap(self, data): if self.sim_time_sec is",
"= (img3d == STATE_FRONTIER).nonzero() for x, y, z in zip(f[1], f[0], f[2]): if",
"& drivable_safe_y[:, :-2] # add non-drivable frame to match original image size z",
"= data x, y, z = pose3d[0] start = int(SLICE_OCTOMAP_SIZE//2 + x/resolution), int(SLICE_OCTOMAP_SIZE//2",
"# unknown self.sim_time_sec = None self.pose3d = None self.video_writer = None self.video_outfile =",
"z]) for limit_score in [3*max(score)/4, max(score)/4, 0]: # select goal positions above the",
"[xy[1] - SLICE_OCTOMAP_SIZE / 2, SLICE_OCTOMAP_SIZE / 2 - xy[0], np.full(len(xy[0]), lev)]).T *",
"with the first sim_time_sec self.debug_arr = [] self.waypoints = None # experimental trigger",
"= img3d[:, :, level] img2[:, :, 1] = img3d[:, :, level] img2[:, :,",
"xyz max_len = max([len(s) for s in seq_arr]) for seq in seq_arr: d",
"d if code in [4, 5, 6, 7]: z += d d //=",
"img[:, :, :] == STATE_FREE mask_right = green[:, 2:, :] & white[:, 1:-1,",
"anyway if self.verbose: f = (img3d == STATE_FRONTIER).nonzero() for x, y, z in",
"level] = data2maplevel(data, level=level + int(round(self.min_z/self.resolution))) if self.verbose: for i in range(num_z_levels): cv2.imwrite('octo_%03d.png'",
"0 resolution = 0.5 waypoints = None last_octo_data = None with LogReader(args.logfile, only_stream_id=[octomap_stream_id,",
"% 2 == 0, len(data) data = bytes([(d + 256) % 256 for",
"+ 256) % 256 for d in data]) x, y, z = self.pose3d[0]",
":-2, :] & white[:, 1:-1, :] mask = mask_left | mask_right z =",
"data into three lists (occupied, free, unknown) :param data: binary octomap data (depth",
"path = frontiers(img3d, start) # this image is modified in place anyway if",
"= [] free = [] occupied = [] for i in range(len(data) //",
"= lookup_stream_id(args.logfile, 'fromrospy.pose3d') waypoints_stream_id = lookup_stream_id(args.logfile, 'octomap.waypoints') pose3d = None x, y, z",
"# initialized with the first sim_time_sec self.debug_arr = [] self.waypoints = None #",
"img = data2maplevel(data, level=lev) xy = np.where(img == STATE_OCCUPIED) xyz = np.array( [xy[1]",
"2 - xy[0], np.full(len(xy[0]), lev)]).T * res all.extend(xyz.tolist()) pcd = o3d.geometry.PointCloud() xyz =",
"help='output path to PNG image', default='out.png') parser.add_argument('--draw', action='store_true', help='draw pyplot frontiers') args =",
"int(round(self.min_z/self.resolution))) if self.verbose: for i in range(num_z_levels): cv2.imwrite('octo_%03d.png' % i, img3d[:, :, i])",
"level -= 1 if key == ord('p'): level += 1 if key ==",
"y, z), len(seq))) return xyz def xyz2img(img, xyz, color, level=2): \"\"\" Draw given",
"if len(xy[0]) == 0: # there are no frontiers, i.e. no exploration path",
"= data def on_pose3d(self, data): if self.waypoints is not None: print('Waypoints', data[0], self.waypoints[0],",
"ord('q') if key == KEY_Q: break if key == ord(' '): paused =",
"d //= 2 xyz.append(((x, y, z), len(seq))) return xyz def xyz2img(img, xyz, color,",
"non-drivable frame to match original image size z = np.zeros((size[0] - 2, 1,",
"z_mask_down = green[:, :, :-2] & white[:, :, 1:-1] z = np.zeros((size[0], size[1],",
"(' (paused)' if paused else '')) key = cv2.waitKey(1) & 0xFF KEY_Q =",
"for one of given type (free, occupied, unknown) :return: list of XYZ boxes",
"val == 3: stack.insert(0, prefix + [rot // 2]) elif val == 2:",
"in cloudsim2osgar data = bytes([(d + 256) % 256 for d in data])",
"for level in range(num_z_levels): img3d[:, :, level] = data2maplevel(data, level=level + int(round(self.min_z/self.resolution))) if",
"that the \"safe path\" does not touch external boundary so it would never",
"x py = SLICE_OCTOMAP_SIZE//2 - y img[max(0, py-d+1):min(SLICE_OCTOMAP_SIZE, py+1), max(0, px):min(SLICE_OCTOMAP_SIZE, px+d)] =",
"= [[]] unknown = [] free = [] occupied = [] for i",
"= 196 # color=(0xFF, 0x00, 0xFF) STATE_PATH = 64 # color=(0xFF, 0x00, 0x00)",
"img[y][x] = STATE_PATH else: print('Path not found!') return img, path class Octomap(Node): def",
"for i in range(len(waypoints) - 1)] colors = [[1, 0, 0] for i",
":] & drivable[1:-1, :] & drivable[:-2, :] drivable_safe_xy = drivable_safe_y[:, 2:] & drivable_safe_y[:,",
"f'Octomap {time}, {pose_str}, level={level}' + (' (paused)' if paused else '')) key =",
"level :param level: Z-level for the cut :return: updated image \"\"\" for pos,",
"if key == ord('p'): level += 1 if key == ord('s'): scaled =",
"drawn start and path, path \"\"\" size = img.shape green = img[:, :,",
"stack.pop(0) d = struct.unpack_from('<H', data, i * 2)[0] for rot in range(14, -2,",
"# add non-drivable frame to match original image size z = np.zeros((size[0] -",
"xy[1][i]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][i] for j in range(len(xy[0])): x2, y2 = xy[1][j]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][j] dist =",
"occupied, free, unknown def data2maplevel(data, level): \"\"\" Convert Octomap data to image/level \"\"\"",
"not None and self.waypoints_sent_time > self.time: self.publish('dropped', self.time_limit_sec) # log skipped sim_time return",
"limit_score in [3*max(score)/4, max(score)/4, 0]: # select goal positions above the limit_score #",
"not try to fill extra large (unknown) squares, for now continue px =",
"STATE_OCCUPIED = 1 # color=(0x00, 0x00, 0xFF) ... just to be != 0,",
"SLICE_OCTOMAP_SIZE = 1024 # size of slice/image in XY octomap coordinates (for given",
"<reponame>robotika/osgar<filename>subt/octomap.py \"\"\" ROS Binary Octomap parsing and processing \"\"\" import struct import math",
"np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE), dtype=np.uint8) occupied, free, unknown = data2stack(data) xyz = seq2xyz(free) xyz2img(img, xyz,",
"for i in range(len(data) // 2): prefix = stack.pop(0) d = struct.unpack_from('<H', data,",
"img2[:, :, 1] = img3d[:, :, level] img2[:, :, 2] = img3d[:, :,",
"ROS Binary Octomap parsing and processing \"\"\" import struct import math import numpy",
"height, width = img2.shape[:2] self.video_writer = cv2.VideoWriter(self.video_outfile, cv2.VideoWriter_fourcc(*\"mp4v\"), fps, (width, height)) self.video_writer.write(img2) if",
"math.hypot(x - x2, y - y2) if dist < 10 and score[i] >",
"= np.array(all) pcd.points = o3d.utility.Vector3dVector(xyz) voxel_grid = o3d.geometry.VoxelGrid.create_from_point_cloud(pcd, voxel_size=0.1) lines = [[i, i",
"cv2.circle(img2, (x, y), radius=0, color=(255, 0, 0), thickness=-1) cv2.circle(img2, start[:2], radius=0, color=(39, 127,",
"= img3d[:, :, level] img2[:, :, 2] = img3d[:, :, level] __, path",
"resolution = 0.5 waypoints = None last_octo_data = None with LogReader(args.logfile, only_stream_id=[octomap_stream_id, pose3d_stream_id,",
"update(self): channel = super().update() handler = getattr(self, \"on_\" + channel, None) if handler",
"img3d[:, :, level] = data2maplevel(data, level=level + int(round(self.min_z/self.resolution))) if self.verbose: for i in",
"img.shape) cv2.imshow('Octomap', img) pose_str = '(%.02f, %.02f, %.02f)' % tuple(pose3d[0]) if pose3d is",
"do not try to fill extra large (unknown) squares, for now continue px",
"level: Z-level for the cut :return: updated image \"\"\" for pos, size in",
"2, 1, size[2]), dtype=np.bool) tmp = np.hstack([z, drivable_safe_xy, z]) z = np.zeros((1, size[1],",
"SLICE_OCTOMAP_SIZE, num_z_levels), dtype=np.uint8) for level in range(num_z_levels): img3d[:, :, level] = data2maplevel(data, level=level",
"<< rot)) >> rot if val == 3: stack.insert(0, prefix + [rot //",
"stream, data in logreader: data = deserialize(data) if stream == pose3d_stream_id: pose3d =",
"the \"safe path\" does not touch external boundary so it would never find",
"= 2 ** (max_len - 1) x, y, z = -32767, -32767, -32767",
"SLICE_OCTOMAP_SIZE, 3), dtype=np.uint8) level = max(0, min(num_z_levels - 1, start[2])) img2[:, :, 0]",
"xyz.append(((x, y, z), len(seq))) return xyz def xyz2img(img, xyz, color, level=2): \"\"\" Draw",
"# color=(0xFF, 0x00, 0x00) SLICE_OCTOMAP_SIZE = 1024 # size of slice/image in XY",
"\"safe path\" does not touch external boundary so it would never find path",
"data2maplevel(data, level=level + int(round(self.min_z/self.resolution))) if self.verbose: for i in range(num_z_levels): cv2.imwrite('octo_%03d.png' % i,",
"level in range(num_z_levels): img3d[:, :, level] = data2maplevel(data, level=level + int(round(self.min_z/self.resolution))) if self.verbose:",
"voxel) \"\"\" xyz = [] if len(seq_arr) == 0: return xyz max_len =",
"np.zeros((size[0], 1, size[2]), dtype=np.bool) mask = np.hstack([z, mask, z]) mask_up = green[2:, :,",
"if scaled: img = cv2.resize(img[256 + 128:-256 - 128, 256 + 128:-256 -",
"color=STATE_UNKNOWN, level=level) return img def frontiers(img, start, draw=False): \"\"\" Find path to the",
"0] = img3d[:, :, level] img2[:, :, 1] = img3d[:, :, level] img2[:,",
"196 # color=(0xFF, 0x00, 0xFF) STATE_PATH = 64 # color=(0xFF, 0x00, 0x00) SLICE_OCTOMAP_SIZE",
"0, 0, 0 resolution = 0.5 waypoints = None last_octo_data = None with",
"= seq2xyz(occupied) xyz2img(img, xyz, color=STATE_OCCUPIED, level=level) xyz = seq2xyz(unknown) xyz2img(img, xyz, color=STATE_UNKNOWN, level=level)",
"continue if waypoints is None: # speed up display/processing - maybe optional? continue",
"if key == ord('d'): import open3d as o3d res = 0.5 all =",
"3*max(score)/4 plt.plot(xy[1][m] - SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2 - xy[0][m], 'ro') plt.axes().set_aspect('equal', 'datalim') plt.show() drivable =",
"cv2.circle(img2, (x, y), radius=0, color=(255, 0, 255), thickness=-1) if path is not None:",
"img2 = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE, 3), dtype=np.uint8) level = max(0, min(num_z_levels - 1, start[2]))",
"& white[1:-1, :, :] z = np.zeros((1, size[1], size[2]), dtype=np.bool) mask2 = mask_up",
"data]) last_octo_data = data key = draw_iteration(data, waypoints) if key == ord('q'): break",
"pixel surrounding drivable_safe_y = drivable[2:, :] & drivable[1:-1, :] & drivable[:-2, :] drivable_safe_xy",
"not scaled if key == ord('d'): import open3d as o3d res = 0.5",
"start) # this image is modified in place anyway if self.verbose: f =",
"all = [] for lev in range(-3, 10): img = data2maplevel(data, level=lev) xy",
"= data2maplevel(data, level=level + int(round(self.min_z/self.resolution))) if self.verbose: for i in range(num_z_levels): cv2.imwrite('octo_%03d.png' %",
"parser.add_argument('--out', help='output path to PNG image', default='out.png') parser.add_argument('--draw', action='store_true', help='draw pyplot frontiers') args",
"mask = np.concatenate([z, mask3, z], axis=2) | mask xy = np.where(mask) if len(xy[0])",
"- 1, start[2])) img2[:, :, 0] = img3d[:, :, level] img2[:, :, 1]",
"+ [rot // 2]) assert len(stack) == 0, len(stack) return occupied, free, unknown",
"if self.video_outfile is not None: if self.video_writer is None: fps = 1 height,",
"import deserialize from osgar.logger import LogReader, lookup_stream_id parser = argparse.ArgumentParser(\"Analyze ocotomap data\") parser.add_argument('logfile',",
"def draw_iteration(data, waypoints=None, paused=False): global level, scaled if waypoints is None: waypoints =",
"self.verbose = False def on_sim_time_sec(self, data): if self.time_limit_sec is None: self.time_limit_sec = data",
"as logreader: level = 2 scaled = True for time, stream, data in",
"None or self.sim_time_sec < self.time_limit_sec: return self.time_limit_sec += 1 # simulated seconds if",
"xy2 = np.array(xy)[:, score > limit_score] for dx in [-1, 0, 1]: for",
":, level] img2[:, :, 1] = img3d[:, :, level] img2[:, :, 2] =",
"z in zip(f[1], f[0], f[2]): if z == start[2]: cv2.circle(img2, (x, y), radius=0,",
"path to the best frontier (free-unknown transition) :param img: color image with free=white,",
"0x00, 0xFF) ... just to be != 0, which is original unknown/black/undefined STATE_FRONTIER",
"rot)) >> rot if val == 3: stack.insert(0, prefix + [rot // 2])",
"or self.pose3d is None or self.sim_time_sec < self.time_limit_sec: return self.time_limit_sec += 1 #",
"the limit_score # note, that the \"safe path\" does not touch external boundary",
"o3d res = 0.5 all = [] for lev in range(-3, 10): img",
"tuple (x, y) and operation \"in\" goals = set(map(tuple, goals)) path = find_path(drivable,",
"img = cv2.resize(img[256 + 128:-256 - 128, 256 + 128:-256 - 128], img.shape)",
"2]) elif val == 0: unknown.append(prefix + [rot // 2]) assert len(stack) ==",
"semi-space, but let's move INSIDE! for i in range(len(xy[0])): x, y = xy[1][i]-SLICE_OCTOMAP_SIZE//2,",
"argparse from osgar.lib.serialize import deserialize from osgar.logger import LogReader, lookup_stream_id parser = argparse.ArgumentParser(\"Analyze",
"range(len(xy[0])): x, y = xy[1][i]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][i] for j in range(len(xy[0])): x2, y2 =",
"__, path = frontiers(img3d, start) # this image is modified in place anyway",
"key == ord('q'): break waypoints = None # force wait for next waypoints",
"= np.array(xy)[:, score > limit_score] for dx in [-1, 0, 1]: for dy",
"free, unknown) lists of sequences \"\"\" stack = [[]] unknown = [] free",
"draw=False): \"\"\" Find path to the best frontier (free-unknown transition) :param img: color",
"logreader: data = deserialize(data) if stream == pose3d_stream_id: pose3d = data x, y,",
"I/O image :param xyz: list of voxels (xyz and \"size\") :param color: value",
"1] = img3d[:, :, level] img2[:, :, 2] = img3d[:, :, level] __,",
"to PNG image', default='out.png') parser.add_argument('--draw', action='store_true', help='draw pyplot frontiers') args = parser.parse_args() octomap_stream_id",
"seq_arr: list of parent-child sequences for one of given type (free, occupied, unknown)",
"seq_arr]) for seq in seq_arr: d = 2 ** (max_len - 1) x,",
"thickness=-1) if scaled: img = cv2.resize(img[256 + 128:-256 - 128, 256 + 128:-256",
"size z = np.zeros((size[0] - 2, 1, size[2]), dtype=np.bool) tmp = np.hstack([z, drivable_safe_xy,",
"255), thickness=-1) cv2.imwrite('octo_cut.png', img2) # used for replay debugging if self.video_outfile is not",
"< 10 and score[i] > 0: # ~ 5 meters, only inside score[i]",
"= cv2.waitKey(1) & 0xFF KEY_Q = ord('q') if key == KEY_Q: break if",
"free, unknown def data2maplevel(data, level): \"\"\" Convert Octomap data to image/level \"\"\" img",
"in range(len(xy[0])): x, y = xy[1][i]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][i] for j in range(len(xy[0])): x2, y2",
"1 <= size <= 16, size d = 2 ** (16 - size)",
"= drivable_safe_y[:, 2:] & drivable_safe_y[:, 1:-1] & drivable_safe_y[:, :-2] # add non-drivable frame",
"s in seq_arr]) for seq in seq_arr: d = 2 ** (max_len -",
"tmp = np.hstack([z, drivable_safe_xy, z]) z = np.zeros((1, size[1], size[2]), dtype=np.bool) drivable =",
"> 4: # TODO - resolution and detect gate as one way only",
"thickness=-1) if path is not None: for x, y, z in path: cv2.circle(img2,",
"1, size[2]), dtype=np.bool) mask = np.hstack([z, mask, z]) mask_up = green[2:, :, :]",
"key == ord('m'): level -= 1 if key == ord('p'): level += 1",
"parent-child sequences for one of given type (free, occupied, unknown) :return: list of",
"= draw_iteration(data, waypoints) if key == ord('q'): break waypoints = None # force",
"scaled if waypoints is None: waypoints = [] while True: img = data2maplevel(data,",
"= None def on_octomap(self, data): if self.sim_time_sec is None or self.pose3d is None",
"+ d: if d > 100: # do not try to fill extra",
"due to impecise position score[i] = math.hypot(x, y) * 0.03 else: score[i] =",
"1:-1] z = np.zeros((size[0], size[1], 1), dtype=np.bool) mask3 = z_mask_up | z_mask_down #",
"thickness=-1) cv2.imwrite('octo_cut.png', img2) # used for replay debugging if self.video_outfile is not None:",
"[] free = [] occupied = [] for i in range(len(data) // 2):",
"now continue px = SLICE_OCTOMAP_SIZE//2 + x py = SLICE_OCTOMAP_SIZE//2 - y img[max(0,",
"256) % 256 for d in data]) x, y, z = self.pose3d[0] start",
"coordinate :param seq_arr: list of parent-child sequences for one of given type (free,",
"128:-256 - 128], img.shape) cv2.imshow('Octomap', img) pose_str = '(%.02f, %.02f, %.02f)' % tuple(pose3d[0])",
"y img[max(0, py-d+1):min(SLICE_OCTOMAP_SIZE, py+1), max(0, px):min(SLICE_OCTOMAP_SIZE, px+d)] = color return img def data2stack(data):",
"start = int(SLICE_OCTOMAP_SIZE//2 + x/resolution), int(SLICE_OCTOMAP_SIZE//2 - y/resolution), int(z / resolution) continue if",
"the cut :return: updated image \"\"\" for pos, size in xyz: x, y,",
"img[mask] = STATE_FRONTIER if path is not None: for x, y, z in",
"z]) | mask z_mask_up = green[:, :, 2:] & white[:, :, 1:-1] z_mask_down",
"data): if self.time_limit_sec is None: self.time_limit_sec = data def on_pose3d(self, data): if self.waypoints",
"into XYZ coordinate :param seq_arr: list of parent-child sequences for one of given",
"x, y, z in path: cv2.circle(img2, (x, y), radius=0, color=(255, 0, 0), thickness=-1)",
"color=(39, 127, 255), thickness=-1) if scaled: img = cv2.resize(img[256 + 128:-256 - 128,",
"and processing \"\"\" import struct import math import numpy as np import cv2",
"start, draw=False): \"\"\" Find path to the best frontier (free-unknown transition) :param img:",
"best frontier (free-unknown transition) :param img: color image with free=white, unknown=green :param start:",
"= xy[1][j]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][j] dist = math.hypot(x - x2, y - y2) if dist",
"key = draw_iteration(data, waypoints) if key == ord('q'): break waypoints = None #",
"2): val = (d & (0x3 << rot)) >> rot if val ==",
"xyz2img(img, xyz, color, level=2): \"\"\" Draw given list of voxels into existing image",
"> 0: # ~ 5 meters, only inside score[i] += 1.0 if draw:",
"= o3d.utility.Vector3dVector(xyz) voxel_grid = o3d.geometry.VoxelGrid.create_from_point_cloud(pcd, voxel_size=0.1) lines = [[i, i + 1] for",
"math import numpy as np import cv2 from osgar.node import Node from osgar.lib.pplanner",
"mask_down mask = np.vstack([z, mask2, z]) | mask z_mask_up = green[:, :, 2:]",
"= None # initialized with the first sim_time_sec self.debug_arr = [] self.waypoints =",
"'): paused = not paused if ord('0') <= key <= ord('9'): level =",
"= parser.parse_args() octomap_stream_id = lookup_stream_id(args.logfile, 'fromrospy.octomap') pose3d_stream_id = lookup_stream_id(args.logfile, 'fromrospy.pose3d') waypoints_stream_id = lookup_stream_id(args.logfile,",
"white[:, :, 1:-1] z_mask_down = green[:, :, :-2] & white[:, :, 1:-1] z",
"default='out.png') parser.add_argument('--draw', action='store_true', help='draw pyplot frontiers') args = parser.parse_args() octomap_stream_id = lookup_stream_id(args.logfile, 'fromrospy.octomap')",
"drivable_safe_y[:, 1:-1] & drivable_safe_y[:, :-2] # add non-drivable frame to match original image",
"(paused)' if paused else '')) key = cv2.waitKey(1) & 0xFF KEY_Q = ord('q')",
"1.0 if draw: import matplotlib.pyplot as plt line = plt.plot(xy[1]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0], 'bo') m",
"+= d if code in [2, 3, 6, 7]: y += d if",
"is None: self.time_limit_sec = data def on_pose3d(self, data): if self.waypoints is not None:",
"self.publish('dropped', self.time_limit_sec) # log skipped sim_time return # bit unlucky conversion from existing",
"waypoints is None: # speed up display/processing - maybe optional? continue assert len(data)",
"original unknown/black/undefined STATE_FRONTIER = 196 # color=(0xFF, 0x00, 0xFF) STATE_PATH = 64 #",
"+ x/resolution), int(SLICE_OCTOMAP_SIZE//2 - y/resolution), int(z / resolution) continue if stream == waypoints_stream_id:",
"& white[:, :, 1:-1] z_mask_down = green[:, :, :-2] & white[:, :, 1:-1]",
"max(0, px):min(SLICE_OCTOMAP_SIZE, px+d)] = color return img def data2stack(data): \"\"\" Convert binary ocotomap",
"STATE_FRONTIER).nonzero() for x, y, z in zip(f[1], f[0], f[2]): if z == start[2]:",
"place anyway if self.verbose: f = (img3d == STATE_FRONTIER).nonzero() for x, y, z",
"if len(seq_arr) == 0: return xyz max_len = max([len(s) for s in seq_arr])",
"SLICE_OCTOMAP_SIZE//2 - y img[max(0, py-d+1):min(SLICE_OCTOMAP_SIZE, py+1), max(0, px):min(SLICE_OCTOMAP_SIZE, px+d)] = color return img",
"img) pose_str = '(%.02f, %.02f, %.02f)' % tuple(pose3d[0]) if pose3d is not None",
"f[0], f[2]): if z == start[2]: cv2.circle(img2, (x, y), radius=0, color=(255, 0, 255),",
"if path is not None: break img[mask] = STATE_FRONTIER if path is not",
"# select goal positions above the limit_score # note, that the \"safe path\"",
"size[2]), dtype=np.bool) mask2 = mask_up | mask_down mask = np.vstack([z, mask2, z]) |",
":] & white[1:-1, :, :] z = np.zeros((1, size[1], size[2]), dtype=np.bool) mask2 =",
"type (free, occupied, unknown) :return: list of XYZ boxes with their \"size category\"",
"unknown) :return: list of XYZ boxes with their \"size category\" (shorted the sequence",
"never find path # to frontier. As a workaround add also all 8-neighbors",
"free = [] occupied = [] for i in range(len(data) // 2): prefix",
"positive semi-space, but let's move INSIDE! for i in range(len(xy[0])): x, y =",
"is None: waypoints = [] while True: img = data2maplevel(data, level=level) cv2.circle(img, start[:2],",
"key == ord('d'): import open3d as o3d res = 0.5 all = []",
"pcd.points = o3d.utility.Vector3dVector(xyz) voxel_grid = o3d.geometry.VoxelGrid.create_from_point_cloud(pcd, voxel_size=0.1) lines = [[i, i + 1]",
"if self.verbose: for i in range(num_z_levels): cv2.imwrite('octo_%03d.png' % i, img3d[:, :, i]) img2",
"rot if val == 3: stack.insert(0, prefix + [rot // 2]) elif val",
"dtype=np.bool) mask2 = mask_up | mask_down mask = np.vstack([z, mask2, z]) | mask",
"mask_right z = np.zeros((size[0], 1, size[2]), dtype=np.bool) mask = np.hstack([z, mask, z]) mask_up",
"to match original image size z = np.zeros((size[0] - 2, 1, size[2]), dtype=np.bool)",
"mask_left = green[:, :-2, :] & white[:, 1:-1, :] mask = mask_left |",
"lines = [[i, i + 1] for i in range(len(waypoints) - 1)] colors",
"-32767, -32767, -32767 for code in seq: if code in [1, 3, 5,",
"this image is modified in place anyway if self.verbose: f = (img3d ==",
"of \"resolution\" self.max_z = config.get('max_z', 0.5) # the limits are included self.resolution =",
"None: if self.video_writer is None: fps = 1 height, width = img2.shape[:2] self.video_writer",
"np.array(all) pcd.points = o3d.utility.Vector3dVector(xyz) voxel_grid = o3d.geometry.VoxelGrid.create_from_point_cloud(pcd, voxel_size=0.1) lines = [[i, i +",
"if self.verbose: f = (img3d == STATE_FRONTIER).nonzero() for x, y, z in zip(f[1],",
"dtype=np.uint8) level = max(0, min(num_z_levels - 1, start[2])) img2[:, :, 0] = img3d[:,",
"color=(0xFF, 0x00, 0xFF) STATE_PATH = 64 # color=(0xFF, 0x00, 0x00) SLICE_OCTOMAP_SIZE = 1024",
"self.time_limit_sec += 1 # simulated seconds if self.waypoints_sent_time is not None and self.waypoints_sent_time",
"elif val == 2: occupied.append(prefix + [rot // 2]) elif val == 1:",
"img2) # used for replay debugging if self.video_outfile is not None: if self.video_writer",
"< z + d: if d > 100: # do not try to",
"if key == ord('s'): scaled = not scaled if key == ord('d'): import",
"(depth first) :return: (occupied, free, unknown) lists of sequences \"\"\" stack = [[]]",
"STATE_FREE = 255 # color=(0xFF, 0xFF, 0xFF) STATE_OCCUPIED = 1 # color=(0x00, 0x00,",
"no exploration path return img, None score = np.zeros(len(xy[0])) for i in range(len(xy[0])):",
"+ x py = SLICE_OCTOMAP_SIZE//2 - y img[max(0, py-d+1):min(SLICE_OCTOMAP_SIZE, py+1), max(0, px):min(SLICE_OCTOMAP_SIZE, px+d)]",
"== ord('s'): scaled = not scaled if key == ord('d'): import open3d as",
"in seq_arr]) for seq in seq_arr: d = 2 ** (max_len - 1)",
"path is not None: for x, y, z in path: img[y][x] = STATE_PATH",
"self.pose3d is None or self.sim_time_sec < self.time_limit_sec: return self.time_limit_sec += 1 # simulated",
"not found!') return img, path class Octomap(Node): def __init__(self, config, bus): super().__init__(config, bus)",
"drivable = white # use 1 pixel surrounding drivable_safe_y = drivable[2:, :] &",
"STATE_PATH = 64 # color=(0xFF, 0x00, 0x00) SLICE_OCTOMAP_SIZE = 1024 # size of",
"lookup_stream_id parser = argparse.ArgumentParser(\"Analyze ocotomap data\") parser.add_argument('logfile', help='path to logfile with octomap data')",
"= bytes([(d + 256) % 256 for d in data]) last_octo_data = data",
"& white[:, :, 1:-1] z = np.zeros((size[0], size[1], 1), dtype=np.bool) mask3 = z_mask_up",
"return occupied, free, unknown def data2maplevel(data, level): \"\"\" Convert Octomap data to image/level",
"2: occupied.append(prefix + [rot // 2]) elif val == 1: free.append(prefix + [rot",
"return xyz def xyz2img(img, xyz, color, level=2): \"\"\" Draw given list of voxels",
"is not None: break img[mask] = STATE_FRONTIER if path is not None: for",
"inner node with child next in the stream STATE_UNKNOWN = 128 # color=(0,",
"> 3*max(score)/4 plt.plot(xy[1][m] - SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2 - xy[0][m], 'ro') plt.axes().set_aspect('equal', 'datalim') plt.show() drivable",
"\"\"\" Convert Octomap data to image/level \"\"\" img = np.zeros((SLICE_OCTOMAP_SIZE, SLICE_OCTOMAP_SIZE), dtype=np.uint8) occupied,",
"\"\"\" Convert octomap sequence (0..7) into XYZ coordinate :param seq_arr: list of parent-child",
"0, len(data) data = bytes([(d + 256) % 256 for d in data])",
"if z == start[2]: cv2.circle(img2, (x, y), radius=0, color=(255, 0, 255), thickness=-1) if",
"self.waypoints_sent_time = None # unknown self.sim_time_sec = None self.pose3d = None self.video_writer =",
"thickness=-1) cv2.circle(img2, start[:2], radius=0, color=(39, 127, 255), thickness=-1) cv2.imwrite('octo_cut.png', img2) # used for",
"cv2.circle(img, start[:2], radius=0, color=(39, 127, 255), thickness=-1) if scaled: img = cv2.resize(img[256 +",
"octomap sequence (0..7) into XYZ coordinate :param seq_arr: list of parent-child sequences for",
"voxels at given level :param level: Z-level for the cut :return: updated image",
"res = 0.5 all = [] for lev in range(-3, 10): img =",
"= 1 height, width = img2.shape[:2] self.video_writer = cv2.VideoWriter(self.video_outfile, cv2.VideoWriter_fourcc(*\"mp4v\"), fps, (width, height))",
"break return key if __name__ == \"__main__\": import argparse from osgar.lib.serialize import deserialize",
"j in range(len(xy[0])): x2, y2 = xy[1][j]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][j] dist = math.hypot(x - x2,",
"one way only (0 is not sufficient due to impecise position score[i] =",
"= not scaled if key == ord('d'): import open3d as o3d res =",
"- size) if z <= level < z + d: if d >",
"plt.axes().set_aspect('equal', 'datalim') plt.show() drivable = white # use 1 pixel surrounding drivable_safe_y =",
"= 128 # color=(0, 0xFF, 0) STATE_FREE = 255 # color=(0xFF, 0xFF, 0xFF)",
"width = img2.shape[:2] self.video_writer = cv2.VideoWriter(self.video_outfile, cv2.VideoWriter_fourcc(*\"mp4v\"), fps, (width, height)) self.video_writer.write(img2) if path",
"frontiers') args = parser.parse_args() octomap_stream_id = lookup_stream_id(args.logfile, 'fromrospy.octomap') pose3d_stream_id = lookup_stream_id(args.logfile, 'fromrospy.pose3d') waypoints_stream_id",
"to fill extra large (unknown) squares, for now continue px = SLICE_OCTOMAP_SIZE//2 +",
"if last_octo_data is not None: draw_iteration(last_octo_data, waypoints, paused=True) # vim: expandtab sw=4 ts=4",
"0.03 else: score[i] = 0 # too cruel cut for X positive semi-space,",
"data key = draw_iteration(data, waypoints) if key == ord('q'): break waypoints = None",
"line_set.points = o3d.utility.Vector3dVector(waypoints) line_set.lines = o3d.utility.Vector2iVector(lines) line_set.colors = o3d.utility.Vector3dVector(colors) o3d.visualization.draw_geometries([line_set, voxel_grid]) if not",
"plt.show() drivable = white # use 1 pixel surrounding drivable_safe_y = drivable[2:, :]",
"z <= level < z + d: if d > 100: # do",
"img.shape green = img[:, :, :] == STATE_UNKNOWN white = img[:, :, :]",
"> self.time: self.publish('dropped', self.time_limit_sec) # log skipped sim_time return # bit unlucky conversion",
"'octomap.waypoints') pose3d = None x, y, z = 0, 0, 0 resolution =",
"numpy as np import cv2 from osgar.node import Node from osgar.lib.pplanner import find_path",
"# use 1 pixel surrounding drivable_safe_y = drivable[2:, :] & drivable[1:-1, :] &",
"data def on_pose3d(self, data): if self.waypoints is not None: print('Waypoints', data[0], self.waypoints[0], self.waypoints[-1])",
"== start[2]: cv2.circle(img2, (x, y), radius=0, color=(255, 0, 255), thickness=-1) if path is",
"while True: img = data2maplevel(data, level=level) cv2.circle(img, start[:2], radius=0, color=(39, 127, 255), thickness=-1)",
"\"__main__\": import argparse from osgar.lib.serialize import deserialize from osgar.logger import LogReader, lookup_stream_id parser",
"127, 255), thickness=-1) if scaled: img = cv2.resize(img[256 + 128:-256 - 128, 256",
"& 0xFF KEY_Q = ord('q') if key == KEY_Q: break if key ==",
"config, bus): super().__init__(config, bus) bus.register('waypoints', 'dropped') self.prev_data = None self.time_limit_sec = None #",
"be multiply of \"resolution\" self.max_z = config.get('max_z', 0.5) # the limits are included",
"if paused else '')) key = cv2.waitKey(1) & 0xFF KEY_Q = ord('q') if",
":param img: I/O image :param xyz: list of voxels (xyz and \"size\") :param",
"expects goals as tuple (x, y) and operation \"in\" goals = set(map(tuple, goals))",
"not None: for x, y, z in path: img[y][x] = STATE_PATH else: print('Path",
"= green[:-2, :, :] & white[1:-1, :, :] z = np.zeros((1, size[1], size[2]),",
"0: return xyz max_len = max([len(s) for s in seq_arr]) for seq in",
"logfile with octomap data') parser.add_argument('--out', help='output path to PNG image', default='out.png') parser.add_argument('--draw', action='store_true',",
":param level: Z-level for the cut :return: updated image \"\"\" for pos, size",
"if stream == pose3d_stream_id: pose3d = data x, y, z = pose3d[0] start",
"z], axis=2) | mask xy = np.where(mask) if len(xy[0]) == 0: # there",
"2]) elif val == 1: free.append(prefix + [rot // 2]) elif val ==",
":, :-2] & white[:, :, 1:-1] z = np.zeros((size[0], size[1], 1), dtype=np.bool) mask3",
"frontiers, i.e. no exploration path return img, None score = np.zeros(len(xy[0])) for i",
"line = plt.plot(xy[1]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0], 'bo') m = score > 3*max(score)/4 plt.plot(xy[1][m] - SLICE_OCTOMAP_SIZE//2,",
"== 0: # there are no frontiers, i.e. no exploration path return img,",
"+= 1 # simulated seconds if self.waypoints_sent_time is not None and self.waypoints_sent_time >",
"sim_time return # bit unlucky conversion from existing Python2 data assert len(data) %",
"- maybe optional? continue assert len(data) % 2 == 0, len(data) # TODO",
"= np.array( [xy[1] - SLICE_OCTOMAP_SIZE / 2, SLICE_OCTOMAP_SIZE / 2 - xy[0], np.full(len(xy[0]),",
"... just to be != 0, which is original unknown/black/undefined STATE_FRONTIER = 196",
"z + d: if d > 100: # do not try to fill",
"bytes([(d + 256) % 256 for d in data]) x, y, z =",
"Python2 data assert len(data) % 2 == 0, len(data) data = bytes([(d +",
"01: occupied; 10: free; 11: inner node with child next in the stream",
"goals.append(xy2 + np.repeat(np.asarray([[dy], [dx], [dz]]), xy2.shape[1], axis=1)) goals = np.hstack(goals).T[:, [1, 0, 2]]",
":, :] == STATE_UNKNOWN white = img[:, :, :] == STATE_FREE mask_right =",
"import struct import math import numpy as np import cv2 from osgar.node import",
"xyz = np.array( [xy[1] - SLICE_OCTOMAP_SIZE / 2, SLICE_OCTOMAP_SIZE / 2 - xy[0],",
":] == STATE_FREE mask_right = green[:, 2:, :] & white[:, 1:-1, :] mask_left",
"SLICE_OCTOMAP_SIZE//2-xy[0][i] for j in range(len(xy[0])): x2, y2 = xy[1][j]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][j] dist = math.hypot(x",
"len(data) % 2 == 0, len(data) data = bytes([(d + 256) % 256",
"are included self.resolution = config.get('resolution', 0.5) self.verbose = False def on_sim_time_sec(self, data): if",
"path # to frontier. As a workaround add also all 8-neighbors of frontiers.",
"all 8-neighbors of frontiers. goals = [] xy2 = np.array(xy)[:, score > limit_score]",
"Z) def seq2xyz(seq_arr): \"\"\" Convert octomap sequence (0..7) into XYZ coordinate :param seq_arr:",
"len(seq))) return xyz def xyz2img(img, xyz, color, level=2): \"\"\" Draw given list of",
"unknown/black/undefined STATE_FRONTIER = 196 # color=(0xFF, 0x00, 0xFF) STATE_PATH = 64 # color=(0xFF,",
"there are no frontiers, i.e. no exploration path return img, None score =",
"1:-1] & drivable_safe_y[:, :-2] # add non-drivable frame to match original image size",
"line_set.lines = o3d.utility.Vector2iVector(lines) line_set.colors = o3d.utility.Vector3dVector(colors) o3d.visualization.draw_geometries([line_set, voxel_grid]) if not paused: break return",
"== ord('p'): level += 1 if key == ord('s'): scaled = not scaled",
"level=lev) xy = np.where(img == STATE_OCCUPIED) xyz = np.array( [xy[1] - SLICE_OCTOMAP_SIZE /",
"meters, only inside score[i] += 1.0 if draw: import matplotlib.pyplot as plt line",
"xyz2img(img, xyz, color=STATE_OCCUPIED, level=level) xyz = seq2xyz(unknown) xyz2img(img, xyz, color=STATE_UNKNOWN, level=level) return img",
"match original image size z = np.zeros((size[0] - 2, 1, size[2]), dtype=np.bool) tmp",
"Z-level for the cut :return: updated image \"\"\" for pos, size in xyz:",
"draw_iteration(data, waypoints) if key == ord('q'): break waypoints = None # force wait",
"unknown) lists of sequences \"\"\" stack = [[]] unknown = [] free =",
"logreader: level = 2 scaled = True for time, stream, data in logreader:",
":param data: binary octomap data (depth first) :return: (occupied, free, unknown) lists of",
"deserialize(data) if stream == pose3d_stream_id: pose3d = data x, y, z = pose3d[0]",
"args = parser.parse_args() octomap_stream_id = lookup_stream_id(args.logfile, 'fromrospy.octomap') pose3d_stream_id = lookup_stream_id(args.logfile, 'fromrospy.pose3d') waypoints_stream_id =",
"a workaround add also all 8-neighbors of frontiers. goals = [] xy2 =",
"in range(num_z_levels): img3d[:, :, level] = data2maplevel(data, level=level + int(round(self.min_z/self.resolution))) if self.verbose: for",
"None score = np.zeros(len(xy[0])) for i in range(len(xy[0])): x, y = xy[1][i]-SLICE_OCTOMAP_SIZE//2, SLICE_OCTOMAP_SIZE//2-xy[0][i]",
"return img, None score = np.zeros(len(xy[0])) for i in range(len(xy[0])): x, y =",
"cv2.imshow('Octomap', img) pose_str = '(%.02f, %.02f, %.02f)' % tuple(pose3d[0]) if pose3d is not",
"py = SLICE_OCTOMAP_SIZE//2 - y img[max(0, py-d+1):min(SLICE_OCTOMAP_SIZE, py+1), max(0, px):min(SLICE_OCTOMAP_SIZE, px+d)] = color",
"import cv2 from osgar.node import Node from osgar.lib.pplanner import find_path # http://www.arminhornung.de/Research/pub/hornung13auro.pdf #",
"dist < 10 and score[i] > 0: # ~ 5 meters, only inside",
"data: binary octomap data (depth first) :return: (occupied, free, unknown) lists of sequences",
":, :] & white[1:-1, :, :] mask_down = green[:-2, :, :] & white[1:-1,",
"white[:, 1:-1, :] mask_left = green[:, :-2, :] & white[:, 1:-1, :] mask",
"is not None: if self.video_writer is None: fps = 1 height, width =",
"def seq2xyz(seq_arr): \"\"\" Convert octomap sequence (0..7) into XYZ coordinate :param seq_arr: list",
"green[:-2, :, :] & white[1:-1, :, :] z = np.zeros((1, size[1], size[2]), dtype=np.bool)",
"None last_octo_data = None with LogReader(args.logfile, only_stream_id=[octomap_stream_id, pose3d_stream_id, waypoints_stream_id]) as logreader: level =",
"free, unknown = data2stack(data) xyz = seq2xyz(free) xyz2img(img, xyz, color=STATE_FREE, level=level) xyz =",
"frontiers in pyplot :return: extended image with drawn start and path, path \"\"\"",
"img: color image with free=white, unknown=green :param start: start pixel :param draw: debug",
"scaled if key == ord('d'): import open3d as o3d res = 0.5 all",
"1024 # size of slice/image in XY octomap coordinates (for given Z) def",
"in seq_arr: d = 2 ** (max_len - 1) x, y, z =",
"128], img.shape) cv2.imshow('Octomap', img) pose_str = '(%.02f, %.02f, %.02f)' % tuple(pose3d[0]) if pose3d",
"7]: z += d d //= 2 xyz.append(((x, y, z), len(seq))) return xyz",
"1) x, y, z = -32767, -32767, -32767 for code in seq: if",
"tuple(pose3d[0]) if pose3d is not None else 'None' cv2.setWindowTitle('Octomap', f'Octomap {time}, {pose_str}, level={level}'",
"white # use 1 pixel surrounding drivable_safe_y = drivable[2:, :] & drivable[1:-1, :]",
"waypoints = [] while True: img = data2maplevel(data, level=level) cv2.circle(img, start[:2], radius=0, color=(39,",
"sequences for one of given type (free, occupied, unknown) :return: list of XYZ"
] |
[
"cmpe = CircuitMPE('permutation-4.vtree', 'permutation-4.sdd') wmc = cmpe.get_tf_ac([[1.0 - ny,ny] for ny in yu])",
"sess.run(accuracy, feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) print \"Validation accuracy: %f\" % sess.run(accuracy, feed_dict={x: sushi_data.valid_data,",
"logits=y)) loss = cross_entropy - FLAGS.wmc * tf.log(tf.reduce_mean(wmc)) # train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss) #",
"0: print(\"After %d iterations\" % i) # Computing \"true\" accuracies correct_prediction = tf.equal(tf.reduce_sum(tf.abs(tf.to_int32(tf.nn.sigmoid(y)+0.5)",
"print \"Validation accuracy: %f\" % sess.run(accuracy, feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) # Computing MPE",
"in range(FLAGS.iters): # batch_xs, batch_ys = sushi_data.get_batch(400) batch_xs, batch_ys = sushi_data.train_data, sushi_data.train_labels sess.run(train_step,",
"- train_pw)))/float(10*sushi_data.train_data.shape[0])) valid_mpe_pred_pw = to_pairwise_comp(valid_mpe_pred, 5) print \"Validation pairwise mpe accuracy: %f\" %",
"sushi_data.valid_data, y_: sushi_data.valid_labels}) print(\"Percentage of predictions that follow constraint: %f\" % (float(np.sum([cmpe.weighted_model_count([(1-p, p)",
"compute pairwise comparisons once for labels train_pw = to_pairwise_comp(sushi_data.train_labels, np.sqrt(OUTPUT_SIZE)) valid_pw = to_pairwise_comp(sushi_data.valid_labels,",
"of WMC in loss') parser.add_argument('--iters', type=int, default=10000, help='Number of minibatch steps to do')",
"% (1. - np.sum(np.abs(np.array(valid_pred + 0.5, int) - sushi_data.valid_labels))/float(sushi_data.valid_labels.shape[0] * sushi_data.valid_labels.shape[1]))) # Compute",
"valid_pred]) print \"Validation mpe accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(valid_mpe_pred - sushi_data.valid_labels), axis=1), 0))) /",
"SushiData('sushi.soc') INPUT_SIZE = sushi_data.train_data.shape[1] OUTPUT_SIZE = sushi_data.train_labels.shape[1] # Create the model # Input(25)",
"= [] b = [] ys = [] W.append(weight_variable([INPUT_SIZE, FLAGS.units])) b.append(bias_variable([FLAGS.units])) ys.append(tf.nn.sigmoid(tf.matmul(x, W[0])",
"+ b[i])) # Layer n(units) - Output(25) W.append(weight_variable([FLAGS.units, OUTPUT_SIZE])) b.append(bias_variable([OUTPUT_SIZE])) y = tf.matmul(ys[-1],",
"sys import numpy as np from sushi_data import SushiData, to_pairwise_comp from compute_mpe import",
"% valid_loss # Print WMC print \"Train WMC: %f\" % sess.run(tf.reduce_mean(wmc), feed_dict={x: sushi_data.train_data,",
"early\" print \"Test accuracy: %f\" % sess.run(accuracy, feed_dict={x: sushi_data.test_data, y_: sushi_data.test_labels}) test_pred =",
"1(units) x = tf.placeholder(tf.float32, [None, INPUT_SIZE]) W = [] b = [] ys",
"axis=1) # Create AC # yleaves = [[ny, 1.0 - ny] for ny",
"np.sqrt(OUTPUT_SIZE)) test_pw = to_pairwise_comp(sushi_data.test_labels, np.sqrt(OUTPUT_SIZE)) print train_pw.shape print train_pw # For early stopping",
"# train_step = tf.train.MomentumOptimizer(0.1, 0.5).minimize(loss) train_step = tf.train.AdamOptimizer().minimize(loss) # Train loop sess =",
"= sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.test_data, y_: sushi_data.test_labels}) test_mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p) for p in",
"# Computing MPE instiation accuracies pred = sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) mpe_pred",
"= argparse.ArgumentParser() # Args go here parser.add_argument('--units', type=int, default=100, help='Number of units per",
"tf.Variable(tf.truncated_normal(shape, 0.1)) def bias_variable(shape): return tf.Variable(tf.truncated_normal(shape, 0.1)) def main(_): # Get data sushi_data",
"= tf.train.AdamOptimizer().minimize(loss) # Train loop sess = tf.InteractiveSession() tf.global_variables_initializer().run() # Should only compute",
"- sushi_data.test_labels), axis=1), 0))) / float(sushi_data.test_data.shape[0])) print(\"Percentage of individual labels in test that",
"0) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print \"Train accuracy: %f\" % sess.run(accuracy, feed_dict={x: sushi_data.train_data,",
"INPUT_SIZE]) W = [] b = [] ys = [] W.append(weight_variable([INPUT_SIZE, FLAGS.units])) b.append(bias_variable([FLAGS.units]))",
"predictions cmpe = CircuitMPE('permutation-4.vtree', 'permutation-4.sdd') wmc = cmpe.get_tf_ac([[1.0 - ny,ny] for ny in",
"= SushiData('sushi.soc') INPUT_SIZE = sushi_data.train_data.shape[1] OUTPUT_SIZE = sushi_data.train_labels.shape[1] # Create the model #",
"yu = tf.unstack(tf.nn.sigmoid(y), axis=1) # Create AC # yleaves = [[ny, 1.0 -",
"p) for p in o]) for o in np.array(valid_pred + 0.5, int)]))/float(sushi_data.valid_data.shape[0]))) #",
"# Define loss and optimizer y_ = tf.placeholder(tf.float32, [None, OUTPUT_SIZE]) yu = tf.unstack(tf.nn.sigmoid(y),",
"(1. - float(np.sum(np.abs(mpe_pred_pw - train_pw)))/float(10*sushi_data.train_data.shape[0])) valid_mpe_pred_pw = to_pairwise_comp(valid_mpe_pred, 5) print \"Validation pairwise mpe",
"%f\" % sess.run(accuracy, feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) print \"Validation accuracy: %f\" % sess.run(accuracy,",
"+ b[-1] + np.finfo(float).eps * 10 # Define loss and optimizer y_ =",
"help='Coefficient of WMC in loss') parser.add_argument('--iters', type=int, default=10000, help='Number of minibatch steps to",
"ys = [] W.append(weight_variable([INPUT_SIZE, FLAGS.units])) b.append(bias_variable([FLAGS.units])) ys.append(tf.nn.sigmoid(tf.matmul(x, W[0]) + b[0])) for i in",
"right: %f\" % (1. - np.sum(np.abs(np.array(test_pred + 0.5, int) - sushi_data.test_labels))/float(sushi_data.test_labels.shape[0] * sushi_data.test_labels.shape[1])))",
"0))) / float(sushi_data.test_data.shape[0])) print(\"Percentage of individual labels in test that are right: %f\"",
"in test that are right: %f\" % (1. - np.sum(np.abs(np.array(test_pred + 0.5, int)",
"\"Train pairwise mpe accuracy: %f\" % (1. - float(np.sum(np.abs(mpe_pred_pw - train_pw)))/float(10*sushi_data.train_data.shape[0])) valid_mpe_pred_pw =",
"%f\" % sess.run(tf.reduce_mean(wmc), feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) print \"Validation WMC: %f\" % sess.run(tf.reduce_mean(wmc),",
"print \"Test accuracy: %f\" % sess.run(accuracy, feed_dict={x: sushi_data.test_data, y_: sushi_data.test_labels}) test_pred = sess.run(tf.nn.sigmoid(y),",
"CircuitMPE instance for our predictions cmpe = CircuitMPE('permutation-4.vtree', 'permutation-4.sdd') wmc = cmpe.get_tf_ac([[1.0 -",
"sushi_data.valid_labels.shape[1]))) # Compute pairwise accuracies using MPE mpe_pred_pw = to_pairwise_comp(mpe_pred, 5) print \"Train",
"Get data sushi_data = SushiData('sushi.soc') INPUT_SIZE = sushi_data.train_data.shape[1] OUTPUT_SIZE = sushi_data.train_labels.shape[1] # Create",
"iterations\" % i) # Computing \"true\" accuracies correct_prediction = tf.equal(tf.reduce_sum(tf.abs(tf.to_int32(tf.nn.sigmoid(y)+0.5) - tf.to_int32(y_)), 1),",
"sushi_data.train_labels}) valid_loss = sess.run(loss, feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) print \"Validation loss: %f\" %",
"sushi_data.test_labels), axis=1), 0))) / float(sushi_data.test_data.shape[0])) print(\"Percentage of individual labels in test that are",
"help='Number of hidden layers') parser.add_argument('--wmc', type=float, default=0.0, help='Coefficient of WMC in loss') parser.add_argument('--iters',",
"test_pw)))/float(10*sushi_data.test_data.shape[0])) sys.exit() else: prev_loss = valid_loss if __name__ == '__main__': parser = argparse.ArgumentParser()",
"Create CircuitMPE instance for our predictions cmpe = CircuitMPE('permutation-4.vtree', 'permutation-4.sdd') wmc = cmpe.get_tf_ac([[1.0",
"= tf.equal(tf.reduce_sum(tf.abs(tf.to_int32(tf.nn.sigmoid(y)+0.5) - tf.to_int32(y_)), 1), 0) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print \"Train accuracy:",
"= valid_loss if __name__ == '__main__': parser = argparse.ArgumentParser() # Args go here",
"ys.append(tf.nn.sigmoid(tf.matmul(x, W[0]) + b[0])) for i in range(1, FLAGS.layers): # Layer i(units) -",
"= CircuitMPE('permutation-4.vtree', 'permutation-4.sdd') wmc = cmpe.get_tf_ac([[1.0 - ny,ny] for ny in yu]) cross_entropy",
"b[0])) for i in range(1, FLAGS.layers): # Layer i(units) - Layer i+1(units) W.append(weight_variable([FLAGS.units,",
"if i % 100 == 0: print(\"After %d iterations\" % i) # Computing",
"are right: %f\" % (1. - np.sum(np.abs(np.array(test_pred + 0.5, int) - sushi_data.test_labels))/float(sushi_data.test_labels.shape[0] *",
"labels that are right print(\"Percentage of individual labels in training that are right:",
"in o]) for o in np.array(valid_pred + 0.5, int)]))/float(sushi_data.valid_data.shape[0]))) # Early stopping if",
"mpe accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(test_mpe_pred - sushi_data.test_labels), axis=1), 0))) / float(sushi_data.test_data.shape[0])) print(\"Percentage of",
"0.5, int) - sushi_data.train_labels))/float(sushi_data.train_labels.shape[0] * sushi_data.train_labels.shape[1]))) print(\"Percentage of individual labels in validation that",
"Print loss print \"Train loss: %f\" % sess.run(loss, feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) valid_loss",
"tf.placeholder(tf.float32, [None, OUTPUT_SIZE]) yu = tf.unstack(tf.nn.sigmoid(y), axis=1) # Create AC # yleaves =",
"batch_xs, batch_ys = sushi_data.get_batch(400) batch_xs, batch_ys = sushi_data.train_data, sushi_data.train_labels sess.run(train_step, feed_dict={x: batch_xs, y_:",
"batch_ys}) # Every 1k iterations check accuracy if i % 100 == 0:",
"tf.matmul(ys[-1], W[-1]) + b[-1] + np.finfo(float).eps * 10 # Define loss and optimizer",
"to_pairwise_comp from compute_mpe import CircuitMPE import tensorflow as tf FLAGS =None def weight_variable(shape):",
"[] b = [] ys = [] W.append(weight_variable([INPUT_SIZE, FLAGS.units])) b.append(bias_variable([FLAGS.units])) ys.append(tf.nn.sigmoid(tf.matmul(x, W[0]) +",
"# yleaves = [[ny, 1.0 - ny] for ny in yu] # ac",
"+ b[0])) for i in range(1, FLAGS.layers): # Layer i(units) - Layer i+1(units)",
"# Percentage of individual labels that are right print(\"Percentage of individual labels in",
"right: %f\" % (1. - np.sum(np.abs(np.array(pred + 0.5, int) - sushi_data.train_labels))/float(sushi_data.train_labels.shape[0] * sushi_data.train_labels.shape[1])))",
"the model # Input(25) - Layer 1(units) x = tf.placeholder(tf.float32, [None, INPUT_SIZE]) W",
"accuracies correct_prediction = tf.equal(tf.reduce_sum(tf.abs(tf.to_int32(tf.nn.sigmoid(y)+0.5) - tf.to_int32(y_)), 1), 0) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print",
"o]) for o in np.array(valid_pred + 0.5, int)]))/float(sushi_data.valid_data.shape[0]))) # Early stopping if prev_loss",
"= tf.unstack(tf.nn.sigmoid(y), axis=1) # Create AC # yleaves = [[ny, 1.0 - ny]",
"test that are right: %f\" % (1. - np.sum(np.abs(np.array(test_pred + 0.5, int) -",
"model # Input(25) - Layer 1(units) x = tf.placeholder(tf.float32, [None, INPUT_SIZE]) W =",
"print(\"After %d iterations\" % i) # Computing \"true\" accuracies correct_prediction = tf.equal(tf.reduce_sum(tf.abs(tf.to_int32(tf.nn.sigmoid(y)+0.5) -",
"p in o]) for o in valid_pred]) print \"Validation mpe accuracy: %f\" %",
"(1. - float(np.sum(np.abs(valid_mpe_pred_pw - valid_pw)))/float(10*sushi_data.valid_data.shape[0])) # Print loss print \"Train loss: %f\" %",
"y_: sushi_data.test_labels}) test_mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p) for p in o]) for o in",
"+ 0.5, int) - sushi_data.test_labels))/float(sushi_data.test_labels.shape[0] * sushi_data.test_labels.shape[1]))) test_mpe_pred_pw = to_pairwise_comp(test_mpe_pred, 5) print \"Test",
"loss: %f\" % sess.run(loss, feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) valid_loss = sess.run(loss, feed_dict={x: sushi_data.valid_data,",
"\"Test mpe accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(test_mpe_pred - sushi_data.test_labels), axis=1), 0))) / float(sushi_data.test_data.shape[0])) print(\"Percentage",
"print \"Train loss: %f\" % sess.run(loss, feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) valid_loss = sess.run(loss,",
"train_pw = to_pairwise_comp(sushi_data.train_labels, np.sqrt(OUTPUT_SIZE)) valid_pw = to_pairwise_comp(sushi_data.valid_labels, np.sqrt(OUTPUT_SIZE)) test_pw = to_pairwise_comp(sushi_data.test_labels, np.sqrt(OUTPUT_SIZE)) print",
"= cross_entropy - FLAGS.wmc * tf.log(tf.reduce_mean(wmc)) # train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss) # train_step =",
"accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print \"Train accuracy: %f\" % sess.run(accuracy, feed_dict={x: sushi_data.train_data, y_:",
"in yu] # ac = AC('permutation-4.ac',yleaves) # Create CircuitMPE instance for our predictions",
"* sushi_data.valid_labels.shape[1]))) # Compute pairwise accuracies using MPE mpe_pred_pw = to_pairwise_comp(mpe_pred, 5) print",
"return tf.Variable(tf.truncated_normal(shape, 0.1)) def bias_variable(shape): return tf.Variable(tf.truncated_normal(shape, 0.1)) def main(_): # Get data",
"y_: sushi_data.valid_labels}) print(\"Percentage of predictions that follow constraint: %f\" % (float(np.sum([cmpe.weighted_model_count([(1-p, p) for",
"that are right: %f\" % (1. - np.sum(np.abs(np.array(test_pred + 0.5, int) - sushi_data.test_labels))/float(sushi_data.test_labels.shape[0]",
"stopping if prev_loss < valid_loss: print \"Stopping early\" print \"Test accuracy: %f\" %",
"prev_loss = valid_loss if __name__ == '__main__': parser = argparse.ArgumentParser() # Args go",
"1.0 - ny] for ny in yu] # ac = AC('permutation-4.ac',yleaves) # Create",
"% sess.run(accuracy, feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) # Computing MPE instiation accuracies pred =",
"WMC print \"Train WMC: %f\" % sess.run(tf.reduce_mean(wmc), feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) print \"Validation",
"sushi_data.valid_labels}) # Computing MPE instiation accuracies pred = sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels})",
"WMC: %f\" % sess.run(tf.reduce_mean(wmc), feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) print(\"Percentage of predictions that follow",
"test_mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p) for p in o]) for o in test_pred]) print",
"Computing \"true\" accuracies correct_prediction = tf.equal(tf.reduce_sum(tf.abs(tf.to_int32(tf.nn.sigmoid(y)+0.5) - tf.to_int32(y_)), 1), 0) accuracy = tf.reduce_mean(tf.cast(correct_prediction,",
"valid_loss # Print WMC print \"Train WMC: %f\" % sess.run(tf.reduce_mean(wmc), feed_dict={x: sushi_data.train_data, y_:",
"%f\" % sess.run(accuracy, feed_dict={x: sushi_data.test_data, y_: sushi_data.test_labels}) test_pred = sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.test_data, y_:",
"= tf.train.MomentumOptimizer(0.1, 0.5).minimize(loss) train_step = tf.train.AdamOptimizer().minimize(loss) # Train loop sess = tf.InteractiveSession() tf.global_variables_initializer().run()",
"type=int, default=3, help='Number of hidden layers') parser.add_argument('--wmc', type=float, default=0.0, help='Coefficient of WMC in",
"np.array([cmpe.compute_mpe_inst([(1-p, p) for p in o]) for o in pred]) print \"Train mpe",
"in loss') parser.add_argument('--iters', type=int, default=10000, help='Number of minibatch steps to do') FLAGS, unparsed",
"ny in yu] # ac = AC('permutation-4.ac',yleaves) # Create CircuitMPE instance for our",
"train_pw # For early stopping prev_loss = 1e15 # Train for i in",
"(float(np.sum([cmpe.weighted_model_count([(1-p, p) for p in o]) for o in np.array(valid_pred + 0.5, int)]))/float(sushi_data.valid_data.shape[0])))",
"FLAGS.units])) b.append(bias_variable([FLAGS.units])) ys.append(tf.nn.sigmoid(tf.matmul(ys[i-1], W[i]) + b[i])) # Layer n(units) - Output(25) W.append(weight_variable([FLAGS.units, OUTPUT_SIZE]))",
"yu]) cross_entropy = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=y_, logits=y)) loss = cross_entropy - FLAGS.wmc * tf.log(tf.reduce_mean(wmc)) #",
"ac = AC('permutation-4.ac',yleaves) # Create CircuitMPE instance for our predictions cmpe = CircuitMPE('permutation-4.vtree',",
"sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.test_data, y_: sushi_data.test_labels}) test_mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p) for p in o])",
"AC # yleaves = [[ny, 1.0 - ny] for ny in yu] #",
"= tf.placeholder(tf.float32, [None, INPUT_SIZE]) W = [] b = [] ys = []",
"to_pairwise_comp(sushi_data.train_labels, np.sqrt(OUTPUT_SIZE)) valid_pw = to_pairwise_comp(sushi_data.valid_labels, np.sqrt(OUTPUT_SIZE)) test_pw = to_pairwise_comp(sushi_data.test_labels, np.sqrt(OUTPUT_SIZE)) print train_pw.shape print",
"Train for i in range(FLAGS.iters): # batch_xs, batch_ys = sushi_data.get_batch(400) batch_xs, batch_ys =",
"parser = argparse.ArgumentParser() # Args go here parser.add_argument('--units', type=int, default=100, help='Number of units",
"% i) # Computing \"true\" accuracies correct_prediction = tf.equal(tf.reduce_sum(tf.abs(tf.to_int32(tf.nn.sigmoid(y)+0.5) - tf.to_int32(y_)), 1), 0)",
"print \"Test mpe accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(test_mpe_pred - sushi_data.test_labels), axis=1), 0))) / float(sushi_data.test_data.shape[0]))",
"i in range(1, FLAGS.layers): # Layer i(units) - Layer i+1(units) W.append(weight_variable([FLAGS.units, FLAGS.units])) b.append(bias_variable([FLAGS.units]))",
"- np.sum(np.abs(np.array(valid_pred + 0.5, int) - sushi_data.valid_labels))/float(sushi_data.valid_labels.shape[0] * sushi_data.valid_labels.shape[1]))) # Compute pairwise accuracies",
"valid_loss = sess.run(loss, feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) print \"Validation loss: %f\" % valid_loss",
"optimizer y_ = tf.placeholder(tf.float32, [None, OUTPUT_SIZE]) yu = tf.unstack(tf.nn.sigmoid(y), axis=1) # Create AC",
"1), 0) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print \"Train accuracy: %f\" % sess.run(accuracy, feed_dict={x:",
"y_ = tf.placeholder(tf.float32, [None, OUTPUT_SIZE]) yu = tf.unstack(tf.nn.sigmoid(y), axis=1) # Create AC #",
"b = [] ys = [] W.append(weight_variable([INPUT_SIZE, FLAGS.units])) b.append(bias_variable([FLAGS.units])) ys.append(tf.nn.sigmoid(tf.matmul(x, W[0]) + b[0]))",
"% (float(np.sum(np.equal(np.sum(np.abs(test_mpe_pred - sushi_data.test_labels), axis=1), 0))) / float(sushi_data.test_data.shape[0])) print(\"Percentage of individual labels in",
"import numpy as np from sushi_data import SushiData, to_pairwise_comp from compute_mpe import CircuitMPE",
"import argparse import sys import numpy as np from sushi_data import SushiData, to_pairwise_comp",
"that follow constraint: %f\" % (float(np.sum([cmpe.weighted_model_count([(1-p, p) for p in o]) for o",
"as np from sushi_data import SushiData, to_pairwise_comp from compute_mpe import CircuitMPE import tensorflow",
"Output(25) W.append(weight_variable([FLAGS.units, OUTPUT_SIZE])) b.append(bias_variable([OUTPUT_SIZE])) y = tf.matmul(ys[-1], W[-1]) + b[-1] + np.finfo(float).eps *",
"i in range(FLAGS.iters): # batch_xs, batch_ys = sushi_data.get_batch(400) batch_xs, batch_ys = sushi_data.train_data, sushi_data.train_labels",
"to_pairwise_comp(mpe_pred, 5) print \"Train pairwise mpe accuracy: %f\" % (1. - float(np.sum(np.abs(mpe_pred_pw -",
"sushi_data.train_labels), axis=1), 0))) / float(sushi_data.train_data.shape[0])) valid_pred = sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) valid_mpe_pred",
"- Output(25) W.append(weight_variable([FLAGS.units, OUTPUT_SIZE])) b.append(bias_variable([OUTPUT_SIZE])) y = tf.matmul(ys[-1], W[-1]) + b[-1] + np.finfo(float).eps",
"sushi_data.valid_data, y_: sushi_data.valid_labels}) # Computing MPE instiation accuracies pred = sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.train_data,",
"that are right: %f\" % (1. - np.sum(np.abs(np.array(valid_pred + 0.5, int) - sushi_data.valid_labels))/float(sushi_data.valid_labels.shape[0]",
"train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss) # train_step = tf.train.AdagradOptimizer(0.1).minimize(loss) # train_step = tf.train.MomentumOptimizer(0.1, 0.5).minimize(loss) train_step",
"feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) # Computing MPE instiation accuracies pred = sess.run(tf.nn.sigmoid(y), feed_dict={x:",
"mpe accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(valid_mpe_pred - sushi_data.valid_labels), axis=1), 0))) / float(sushi_data.valid_data.shape[0])) # Percentage",
"(1. - np.sum(np.abs(np.array(pred + 0.5, int) - sushi_data.train_labels))/float(sushi_data.train_labels.shape[0] * sushi_data.train_labels.shape[1]))) print(\"Percentage of individual",
"feed_dict={x: batch_xs, y_: batch_ys}) # Every 1k iterations check accuracy if i %",
"# Create CircuitMPE instance for our predictions cmpe = CircuitMPE('permutation-4.vtree', 'permutation-4.sdd') wmc =",
"and optimizer y_ = tf.placeholder(tf.float32, [None, OUTPUT_SIZE]) yu = tf.unstack(tf.nn.sigmoid(y), axis=1) # Create",
"to_pairwise_comp(sushi_data.test_labels, np.sqrt(OUTPUT_SIZE)) print train_pw.shape print train_pw # For early stopping prev_loss = 1e15",
"%f\" % (1. - np.sum(np.abs(np.array(test_pred + 0.5, int) - sushi_data.test_labels))/float(sushi_data.test_labels.shape[0] * sushi_data.test_labels.shape[1]))) test_mpe_pred_pw",
"layer') parser.add_argument('--layers', type=int, default=3, help='Number of hidden layers') parser.add_argument('--wmc', type=float, default=0.0, help='Coefficient of",
"of minibatch steps to do') FLAGS, unparsed = parser.parse_known_args() tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)",
"sess.run(loss, feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) print \"Validation loss: %f\" % valid_loss # Print",
"default=10000, help='Number of minibatch steps to do') FLAGS, unparsed = parser.parse_known_args() tf.app.run(main=main, argv=[sys.argv[0]]",
"for o in test_pred]) print \"Test mpe accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(test_mpe_pred - sushi_data.test_labels),",
"labels in test that are right: %f\" % (1. - np.sum(np.abs(np.array(test_pred + 0.5,",
"accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(test_mpe_pred - sushi_data.test_labels), axis=1), 0))) / float(sushi_data.test_data.shape[0])) print(\"Percentage of individual",
"i % 100 == 0: print(\"After %d iterations\" % i) # Computing \"true\"",
"0.5, int) - sushi_data.test_labels))/float(sushi_data.test_labels.shape[0] * sushi_data.test_labels.shape[1]))) test_mpe_pred_pw = to_pairwise_comp(test_mpe_pred, 5) print \"Test pairwise",
"+ np.finfo(float).eps * 10 # Define loss and optimizer y_ = tf.placeholder(tf.float32, [None,",
"< valid_loss: print \"Stopping early\" print \"Test accuracy: %f\" % sess.run(accuracy, feed_dict={x: sushi_data.test_data,",
"valid_loss: print \"Stopping early\" print \"Test accuracy: %f\" % sess.run(accuracy, feed_dict={x: sushi_data.test_data, y_:",
"early stopping prev_loss = 1e15 # Train for i in range(FLAGS.iters): # batch_xs,",
"type=float, default=0.0, help='Coefficient of WMC in loss') parser.add_argument('--iters', type=int, default=10000, help='Number of minibatch",
"range(1, FLAGS.layers): # Layer i(units) - Layer i+1(units) W.append(weight_variable([FLAGS.units, FLAGS.units])) b.append(bias_variable([FLAGS.units])) ys.append(tf.nn.sigmoid(tf.matmul(ys[i-1], W[i])",
"%f\" % (float(np.sum(np.equal(np.sum(np.abs(valid_mpe_pred - sushi_data.valid_labels), axis=1), 0))) / float(sushi_data.valid_data.shape[0])) # Percentage of individual",
"valid_pw)))/float(10*sushi_data.valid_data.shape[0])) # Print loss print \"Train loss: %f\" % sess.run(loss, feed_dict={x: sushi_data.train_data, y_:",
"argparse import sys import numpy as np from sushi_data import SushiData, to_pairwise_comp from",
"y_: sushi_data.test_labels}) test_pred = sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.test_data, y_: sushi_data.test_labels}) test_mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p)",
"o]) for o in pred]) print \"Train mpe accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(mpe_pred -",
"ny,ny] for ny in yu]) cross_entropy = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=y_, logits=y)) loss = cross_entropy -",
"constraint: %f\" % (float(np.sum([cmpe.weighted_model_count([(1-p, p) for p in o]) for o in np.array(valid_pred",
"print(\"Percentage of individual labels in training that are right: %f\" % (1. -",
"W.append(weight_variable([FLAGS.units, FLAGS.units])) b.append(bias_variable([FLAGS.units])) ys.append(tf.nn.sigmoid(tf.matmul(ys[i-1], W[i]) + b[i])) # Layer n(units) - Output(25) W.append(weight_variable([FLAGS.units,",
"are right print(\"Percentage of individual labels in training that are right: %f\" %",
"sushi_data.train_data.shape[1] OUTPUT_SIZE = sushi_data.train_labels.shape[1] # Create the model # Input(25) - Layer 1(units)",
"%f\" % sess.run(tf.reduce_mean(wmc), feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) print(\"Percentage of predictions that follow constraint:",
"train_step = tf.train.AdamOptimizer().minimize(loss) # Train loop sess = tf.InteractiveSession() tf.global_variables_initializer().run() # Should only",
"print \"Stopping early\" print \"Test accuracy: %f\" % sess.run(accuracy, feed_dict={x: sushi_data.test_data, y_: sushi_data.test_labels})",
"sushi_data.train_data, sushi_data.train_labels sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) # Every 1k iterations check accuracy",
"i) # Computing \"true\" accuracies correct_prediction = tf.equal(tf.reduce_sum(tf.abs(tf.to_int32(tf.nn.sigmoid(y)+0.5) - tf.to_int32(y_)), 1), 0) accuracy",
"y_: sushi_data.train_labels}) mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p) for p in o]) for o in",
"wmc = cmpe.get_tf_ac([[1.0 - ny,ny] for ny in yu]) cross_entropy = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=y_, logits=y))",
"- FLAGS.wmc * tf.log(tf.reduce_mean(wmc)) # train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss) # train_step = tf.train.AdagradOptimizer(0.1).minimize(loss) #",
"# Get data sushi_data = SushiData('sushi.soc') INPUT_SIZE = sushi_data.train_data.shape[1] OUTPUT_SIZE = sushi_data.train_labels.shape[1] #",
"- float(np.sum(np.abs(mpe_pred_pw - train_pw)))/float(10*sushi_data.train_data.shape[0])) valid_mpe_pred_pw = to_pairwise_comp(valid_mpe_pred, 5) print \"Validation pairwise mpe accuracy:",
"feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) print \"Validation WMC: %f\" % sess.run(tf.reduce_mean(wmc), feed_dict={x: sushi_data.valid_data, y_:",
"Input(25) - Layer 1(units) x = tf.placeholder(tf.float32, [None, INPUT_SIZE]) W = [] b",
"sushi_data.get_batch(400) batch_xs, batch_ys = sushi_data.train_data, sushi_data.train_labels sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) # Every",
"in validation that are right: %f\" % (1. - np.sum(np.abs(np.array(valid_pred + 0.5, int)",
"Percentage of individual labels that are right print(\"Percentage of individual labels in training",
"accuracy: %f\" % sess.run(accuracy, feed_dict={x: sushi_data.test_data, y_: sushi_data.test_labels}) test_pred = sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.test_data,",
"# Layer n(units) - Output(25) W.append(weight_variable([FLAGS.units, OUTPUT_SIZE])) b.append(bias_variable([OUTPUT_SIZE])) y = tf.matmul(ys[-1], W[-1]) +",
"labels train_pw = to_pairwise_comp(sushi_data.train_labels, np.sqrt(OUTPUT_SIZE)) valid_pw = to_pairwise_comp(sushi_data.valid_labels, np.sqrt(OUTPUT_SIZE)) test_pw = to_pairwise_comp(sushi_data.test_labels, np.sqrt(OUTPUT_SIZE))",
"* 10 # Define loss and optimizer y_ = tf.placeholder(tf.float32, [None, OUTPUT_SIZE]) yu",
"float(sushi_data.train_data.shape[0])) valid_pred = sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) valid_mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p) for",
"sushi_data.valid_labels}) print(\"Percentage of predictions that follow constraint: %f\" % (float(np.sum([cmpe.weighted_model_count([(1-p, p) for p",
"o in valid_pred]) print \"Validation mpe accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(valid_mpe_pred - sushi_data.valid_labels), axis=1),",
"% (float(np.sum([cmpe.weighted_model_count([(1-p, p) for p in o]) for o in np.array(valid_pred + 0.5,",
"=None def weight_variable(shape): return tf.Variable(tf.truncated_normal(shape, 0.1)) def bias_variable(shape): return tf.Variable(tf.truncated_normal(shape, 0.1)) def main(_):",
"SushiData, to_pairwise_comp from compute_mpe import CircuitMPE import tensorflow as tf FLAGS =None def",
"CircuitMPE('permutation-4.vtree', 'permutation-4.sdd') wmc = cmpe.get_tf_ac([[1.0 - ny,ny] for ny in yu]) cross_entropy =",
"help='Number of units per hidden layer') parser.add_argument('--layers', type=int, default=3, help='Number of hidden layers')",
"# Print loss print \"Train loss: %f\" % sess.run(loss, feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels})",
"for p in o]) for o in np.array(valid_pred + 0.5, int)]))/float(sushi_data.valid_data.shape[0]))) # Early",
"'permutation-4.sdd') wmc = cmpe.get_tf_ac([[1.0 - ny,ny] for ny in yu]) cross_entropy = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=y_,",
"cross_entropy = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=y_, logits=y)) loss = cross_entropy - FLAGS.wmc * tf.log(tf.reduce_mean(wmc)) # train_step",
"# Input(25) - Layer 1(units) x = tf.placeholder(tf.float32, [None, INPUT_SIZE]) W = []",
"sushi_data.train_data, y_: sushi_data.train_labels}) print \"Validation accuracy: %f\" % sess.run(accuracy, feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels})",
"\"Validation mpe accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(valid_mpe_pred - sushi_data.valid_labels), axis=1), 0))) / float(sushi_data.valid_data.shape[0])) #",
"# train_step = tf.train.AdagradOptimizer(0.1).minimize(loss) # train_step = tf.train.MomentumOptimizer(0.1, 0.5).minimize(loss) train_step = tf.train.AdamOptimizer().minimize(loss) #",
"per hidden layer') parser.add_argument('--layers', type=int, default=3, help='Number of hidden layers') parser.add_argument('--wmc', type=float, default=0.0,",
"- np.sum(np.abs(np.array(test_pred + 0.5, int) - sushi_data.test_labels))/float(sushi_data.test_labels.shape[0] * sushi_data.test_labels.shape[1]))) test_mpe_pred_pw = to_pairwise_comp(test_mpe_pred, 5)",
"feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) print \"Validation accuracy: %f\" % sess.run(accuracy, feed_dict={x: sushi_data.valid_data, y_:",
"feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) valid_loss = sess.run(loss, feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) print \"Validation",
"- sushi_data.valid_labels), axis=1), 0))) / float(sushi_data.valid_data.shape[0])) # Percentage of individual labels that are",
"Args go here parser.add_argument('--units', type=int, default=100, help='Number of units per hidden layer') parser.add_argument('--layers',",
"for i in range(1, FLAGS.layers): # Layer i(units) - Layer i+1(units) W.append(weight_variable([FLAGS.units, FLAGS.units]))",
"from compute_mpe import CircuitMPE import tensorflow as tf FLAGS =None def weight_variable(shape): return",
"__name__ == '__main__': parser = argparse.ArgumentParser() # Args go here parser.add_argument('--units', type=int, default=100,",
"int)]))/float(sushi_data.valid_data.shape[0]))) # Early stopping if prev_loss < valid_loss: print \"Stopping early\" print \"Test",
"follow constraint: %f\" % (float(np.sum([cmpe.weighted_model_count([(1-p, p) for p in o]) for o in",
"float(sushi_data.valid_data.shape[0])) # Percentage of individual labels that are right print(\"Percentage of individual labels",
"from sushi_data import SushiData, to_pairwise_comp from compute_mpe import CircuitMPE import tensorflow as tf",
"feed_dict={x: sushi_data.test_data, y_: sushi_data.test_labels}) test_pred = sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.test_data, y_: sushi_data.test_labels}) test_mpe_pred =",
"test_pred = sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.test_data, y_: sushi_data.test_labels}) test_mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p) for p",
"= 1e15 # Train for i in range(FLAGS.iters): # batch_xs, batch_ys = sushi_data.get_batch(400)",
"valid_loss if __name__ == '__main__': parser = argparse.ArgumentParser() # Args go here parser.add_argument('--units',",
"tf.float32)) print \"Train accuracy: %f\" % sess.run(accuracy, feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) print \"Validation",
"labels in training that are right: %f\" % (1. - np.sum(np.abs(np.array(pred + 0.5,",
"0.5).minimize(loss) train_step = tf.train.AdamOptimizer().minimize(loss) # Train loop sess = tf.InteractiveSession() tf.global_variables_initializer().run() # Should",
"y_: sushi_data.train_labels}) print \"Validation WMC: %f\" % sess.run(tf.reduce_mean(wmc), feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) print(\"Percentage",
"sushi_data = SushiData('sushi.soc') INPUT_SIZE = sushi_data.train_data.shape[1] OUTPUT_SIZE = sushi_data.train_labels.shape[1] # Create the model",
"loss: %f\" % valid_loss # Print WMC print \"Train WMC: %f\" % sess.run(tf.reduce_mean(wmc),",
"pairwise accuracies using MPE mpe_pred_pw = to_pairwise_comp(mpe_pred, 5) print \"Train pairwise mpe accuracy:",
"np.sum(np.abs(np.array(pred + 0.5, int) - sushi_data.train_labels))/float(sushi_data.train_labels.shape[0] * sushi_data.train_labels.shape[1]))) print(\"Percentage of individual labels in",
"sess.run(tf.reduce_mean(wmc), feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) print \"Validation WMC: %f\" % sess.run(tf.reduce_mean(wmc), feed_dict={x: sushi_data.valid_data,",
"print(\"Percentage of individual labels in validation that are right: %f\" % (1. -",
"sushi_data.valid_labels))/float(sushi_data.valid_labels.shape[0] * sushi_data.valid_labels.shape[1]))) # Compute pairwise accuracies using MPE mpe_pred_pw = to_pairwise_comp(mpe_pred, 5)",
"Compute pairwise accuracies using MPE mpe_pred_pw = to_pairwise_comp(mpe_pred, 5) print \"Train pairwise mpe",
"%f\" % valid_loss # Print WMC print \"Train WMC: %f\" % sess.run(tf.reduce_mean(wmc), feed_dict={x:",
"tf FLAGS =None def weight_variable(shape): return tf.Variable(tf.truncated_normal(shape, 0.1)) def bias_variable(shape): return tf.Variable(tf.truncated_normal(shape, 0.1))",
"of units per hidden layer') parser.add_argument('--layers', type=int, default=3, help='Number of hidden layers') parser.add_argument('--wmc',",
"tf.global_variables_initializer().run() # Should only compute pairwise comparisons once for labels train_pw = to_pairwise_comp(sushi_data.train_labels,",
"0))) / float(sushi_data.train_data.shape[0])) valid_pred = sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) valid_mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p,",
"OUTPUT_SIZE]) yu = tf.unstack(tf.nn.sigmoid(y), axis=1) # Create AC # yleaves = [[ny, 1.0",
"y = tf.matmul(ys[-1], W[-1]) + b[-1] + np.finfo(float).eps * 10 # Define loss",
"for p in o]) for o in test_pred]) print \"Test mpe accuracy: %f\"",
"test_mpe_pred_pw = to_pairwise_comp(test_mpe_pred, 5) print \"Test pairwise mpe accuracy: %f\" % (1. -",
"that are right print(\"Percentage of individual labels in training that are right: %f\"",
"print(\"Percentage of predictions that follow constraint: %f\" % (float(np.sum([cmpe.weighted_model_count([(1-p, p) for p in",
"sushi_data.train_labels))/float(sushi_data.train_labels.shape[0] * sushi_data.train_labels.shape[1]))) print(\"Percentage of individual labels in validation that are right: %f\"",
"W.append(weight_variable([FLAGS.units, OUTPUT_SIZE])) b.append(bias_variable([OUTPUT_SIZE])) y = tf.matmul(ys[-1], W[-1]) + b[-1] + np.finfo(float).eps * 10",
"if prev_loss < valid_loss: print \"Stopping early\" print \"Test accuracy: %f\" % sess.run(accuracy,",
"help='Number of minibatch steps to do') FLAGS, unparsed = parser.parse_known_args() tf.app.run(main=main, argv=[sys.argv[0]] +",
"p) for p in o]) for o in pred]) print \"Train mpe accuracy:",
"* tf.log(tf.reduce_mean(wmc)) # train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss) # train_step = tf.train.AdagradOptimizer(0.1).minimize(loss) # train_step =",
"# Layer i(units) - Layer i+1(units) W.append(weight_variable([FLAGS.units, FLAGS.units])) b.append(bias_variable([FLAGS.units])) ys.append(tf.nn.sigmoid(tf.matmul(ys[i-1], W[i]) + b[i]))",
"\"Validation loss: %f\" % valid_loss # Print WMC print \"Train WMC: %f\" %",
"compute_mpe import CircuitMPE import tensorflow as tf FLAGS =None def weight_variable(shape): return tf.Variable(tf.truncated_normal(shape,",
"sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) # Every 1k iterations check accuracy if i",
"b[-1] + np.finfo(float).eps * 10 # Define loss and optimizer y_ = tf.placeholder(tf.float32,",
"that are right: %f\" % (1. - np.sum(np.abs(np.array(pred + 0.5, int) - sushi_data.train_labels))/float(sushi_data.train_labels.shape[0]",
"ys.append(tf.nn.sigmoid(tf.matmul(ys[i-1], W[i]) + b[i])) # Layer n(units) - Output(25) W.append(weight_variable([FLAGS.units, OUTPUT_SIZE])) b.append(bias_variable([OUTPUT_SIZE])) y",
"Layer i+1(units) W.append(weight_variable([FLAGS.units, FLAGS.units])) b.append(bias_variable([FLAGS.units])) ys.append(tf.nn.sigmoid(tf.matmul(ys[i-1], W[i]) + b[i])) # Layer n(units) -",
"sess.run(accuracy, feed_dict={x: sushi_data.test_data, y_: sushi_data.test_labels}) test_pred = sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.test_data, y_: sushi_data.test_labels}) test_mpe_pred",
"of hidden layers') parser.add_argument('--wmc', type=float, default=0.0, help='Coefficient of WMC in loss') parser.add_argument('--iters', type=int,",
"%f\" % sess.run(accuracy, feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) # Computing MPE instiation accuracies pred",
"in training that are right: %f\" % (1. - np.sum(np.abs(np.array(pred + 0.5, int)",
"= AC('permutation-4.ac',yleaves) # Create CircuitMPE instance for our predictions cmpe = CircuitMPE('permutation-4.vtree', 'permutation-4.sdd')",
"print \"Validation WMC: %f\" % sess.run(tf.reduce_mean(wmc), feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) print(\"Percentage of predictions",
"b.append(bias_variable([FLAGS.units])) ys.append(tf.nn.sigmoid(tf.matmul(x, W[0]) + b[0])) for i in range(1, FLAGS.layers): # Layer i(units)",
"sushi_data.valid_data, y_: sushi_data.valid_labels}) valid_mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p) for p in o]) for o",
"% (float(np.sum(np.equal(np.sum(np.abs(valid_mpe_pred - sushi_data.valid_labels), axis=1), 0))) / float(sushi_data.valid_data.shape[0])) # Percentage of individual labels",
"print \"Train accuracy: %f\" % sess.run(accuracy, feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) print \"Validation accuracy:",
"layers') parser.add_argument('--wmc', type=float, default=0.0, help='Coefficient of WMC in loss') parser.add_argument('--iters', type=int, default=10000, help='Number",
"y_: sushi_data.valid_labels}) # Computing MPE instiation accuracies pred = sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.train_data, y_:",
"feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) print(\"Percentage of predictions that follow constraint: %f\" % (float(np.sum([cmpe.weighted_model_count([(1-p,",
"numpy as np from sushi_data import SushiData, to_pairwise_comp from compute_mpe import CircuitMPE import",
"pred]) print \"Train mpe accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(mpe_pred - sushi_data.train_labels), axis=1), 0))) /",
"argparse.ArgumentParser() # Args go here parser.add_argument('--units', type=int, default=100, help='Number of units per hidden",
"print \"Validation pairwise mpe accuracy: %f\" % (1. - float(np.sum(np.abs(valid_mpe_pred_pw - valid_pw)))/float(10*sushi_data.valid_data.shape[0])) #",
"parser.add_argument('--units', type=int, default=100, help='Number of units per hidden layer') parser.add_argument('--layers', type=int, default=3, help='Number",
"mpe accuracy: %f\" % (1. - float(np.sum(np.abs(mpe_pred_pw - train_pw)))/float(10*sushi_data.train_data.shape[0])) valid_mpe_pred_pw = to_pairwise_comp(valid_mpe_pred, 5)",
"== 0: print(\"After %d iterations\" % i) # Computing \"true\" accuracies correct_prediction =",
"accuracy: %f\" % sess.run(accuracy, feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) # Computing MPE instiation accuracies",
"(float(np.sum(np.equal(np.sum(np.abs(valid_mpe_pred - sushi_data.valid_labels), axis=1), 0))) / float(sushi_data.valid_data.shape[0])) # Percentage of individual labels that",
"float(np.sum(np.abs(mpe_pred_pw - train_pw)))/float(10*sushi_data.train_data.shape[0])) valid_mpe_pred_pw = to_pairwise_comp(valid_mpe_pred, 5) print \"Validation pairwise mpe accuracy: %f\"",
"W = [] b = [] ys = [] W.append(weight_variable([INPUT_SIZE, FLAGS.units])) b.append(bias_variable([FLAGS.units])) ys.append(tf.nn.sigmoid(tf.matmul(x,",
"MPE instiation accuracies pred = sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p,",
"% (1. - float(np.sum(np.abs(mpe_pred_pw - train_pw)))/float(10*sushi_data.train_data.shape[0])) valid_mpe_pred_pw = to_pairwise_comp(valid_mpe_pred, 5) print \"Validation pairwise",
"np.array(valid_pred + 0.5, int)]))/float(sushi_data.valid_data.shape[0]))) # Early stopping if prev_loss < valid_loss: print \"Stopping",
"FLAGS.units])) b.append(bias_variable([FLAGS.units])) ys.append(tf.nn.sigmoid(tf.matmul(x, W[0]) + b[0])) for i in range(1, FLAGS.layers): # Layer",
"p) for p in o]) for o in valid_pred]) print \"Validation mpe accuracy:",
"our predictions cmpe = CircuitMPE('permutation-4.vtree', 'permutation-4.sdd') wmc = cmpe.get_tf_ac([[1.0 - ny,ny] for ny",
"tensorflow as tf FLAGS =None def weight_variable(shape): return tf.Variable(tf.truncated_normal(shape, 0.1)) def bias_variable(shape): return",
"if __name__ == '__main__': parser = argparse.ArgumentParser() # Args go here parser.add_argument('--units', type=int,",
"bias_variable(shape): return tf.Variable(tf.truncated_normal(shape, 0.1)) def main(_): # Get data sushi_data = SushiData('sushi.soc') INPUT_SIZE",
"print \"Validation loss: %f\" % valid_loss # Print WMC print \"Train WMC: %f\"",
"main(_): # Get data sushi_data = SushiData('sushi.soc') INPUT_SIZE = sushi_data.train_data.shape[1] OUTPUT_SIZE = sushi_data.train_labels.shape[1]",
"correct_prediction = tf.equal(tf.reduce_sum(tf.abs(tf.to_int32(tf.nn.sigmoid(y)+0.5) - tf.to_int32(y_)), 1), 0) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print \"Train",
"import CircuitMPE import tensorflow as tf FLAGS =None def weight_variable(shape): return tf.Variable(tf.truncated_normal(shape, 0.1))",
"- ny] for ny in yu] # ac = AC('permutation-4.ac',yleaves) # Create CircuitMPE",
"- sushi_data.test_labels))/float(sushi_data.test_labels.shape[0] * sushi_data.test_labels.shape[1]))) test_mpe_pred_pw = to_pairwise_comp(test_mpe_pred, 5) print \"Test pairwise mpe accuracy:",
"Early stopping if prev_loss < valid_loss: print \"Stopping early\" print \"Test accuracy: %f\"",
"FLAGS.layers): # Layer i(units) - Layer i+1(units) W.append(weight_variable([FLAGS.units, FLAGS.units])) b.append(bias_variable([FLAGS.units])) ys.append(tf.nn.sigmoid(tf.matmul(ys[i-1], W[i]) +",
"= tf.InteractiveSession() tf.global_variables_initializer().run() # Should only compute pairwise comparisons once for labels train_pw",
"(float(np.sum(np.equal(np.sum(np.abs(mpe_pred - sushi_data.train_labels), axis=1), 0))) / float(sushi_data.train_data.shape[0])) valid_pred = sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.valid_data, y_:",
"sushi_data.test_labels))/float(sushi_data.test_labels.shape[0] * sushi_data.test_labels.shape[1]))) test_mpe_pred_pw = to_pairwise_comp(test_mpe_pred, 5) print \"Test pairwise mpe accuracy: %f\"",
"in o]) for o in valid_pred]) print \"Validation mpe accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(valid_mpe_pred",
"print \"Train WMC: %f\" % sess.run(tf.reduce_mean(wmc), feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) print \"Validation WMC:",
"train_pw)))/float(10*sushi_data.train_data.shape[0])) valid_mpe_pred_pw = to_pairwise_comp(valid_mpe_pred, 5) print \"Validation pairwise mpe accuracy: %f\" % (1.",
"WMC: %f\" % sess.run(tf.reduce_mean(wmc), feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) print \"Validation WMC: %f\" %",
"axis=1), 0))) / float(sushi_data.test_data.shape[0])) print(\"Percentage of individual labels in test that are right:",
"float(np.sum(np.abs(valid_mpe_pred_pw - valid_pw)))/float(10*sushi_data.valid_data.shape[0])) # Print loss print \"Train loss: %f\" % sess.run(loss, feed_dict={x:",
"train_step = tf.train.MomentumOptimizer(0.1, 0.5).minimize(loss) train_step = tf.train.AdamOptimizer().minimize(loss) # Train loop sess = tf.InteractiveSession()",
"# Compute pairwise accuracies using MPE mpe_pred_pw = to_pairwise_comp(mpe_pred, 5) print \"Train pairwise",
"= [[ny, 1.0 - ny] for ny in yu] # ac = AC('permutation-4.ac',yleaves)",
"once for labels train_pw = to_pairwise_comp(sushi_data.train_labels, np.sqrt(OUTPUT_SIZE)) valid_pw = to_pairwise_comp(sushi_data.valid_labels, np.sqrt(OUTPUT_SIZE)) test_pw =",
"FLAGS =None def weight_variable(shape): return tf.Variable(tf.truncated_normal(shape, 0.1)) def bias_variable(shape): return tf.Variable(tf.truncated_normal(shape, 0.1)) def",
"CircuitMPE import tensorflow as tf FLAGS =None def weight_variable(shape): return tf.Variable(tf.truncated_normal(shape, 0.1)) def",
"# Should only compute pairwise comparisons once for labels train_pw = to_pairwise_comp(sushi_data.train_labels, np.sqrt(OUTPUT_SIZE))",
"hidden layer') parser.add_argument('--layers', type=int, default=3, help='Number of hidden layers') parser.add_argument('--wmc', type=float, default=0.0, help='Coefficient",
"sushi_data.test_labels.shape[1]))) test_mpe_pred_pw = to_pairwise_comp(test_mpe_pred, 5) print \"Test pairwise mpe accuracy: %f\" % (1.",
"individual labels that are right print(\"Percentage of individual labels in training that are",
"accuracy: %f\" % (1. - float(np.sum(np.abs(valid_mpe_pred_pw - valid_pw)))/float(10*sushi_data.valid_data.shape[0])) # Print loss print \"Train",
"right print(\"Percentage of individual labels in training that are right: %f\" % (1.",
"pred = sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p) for p",
"tf.to_int32(y_)), 1), 0) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print \"Train accuracy: %f\" % sess.run(accuracy,",
"5) print \"Test pairwise mpe accuracy: %f\" % (1. - float(np.sum(np.abs(test_mpe_pred_pw - test_pw)))/float(10*sushi_data.test_data.shape[0]))",
"= np.array([cmpe.compute_mpe_inst([(1-p, p) for p in o]) for o in valid_pred]) print \"Validation",
"validation that are right: %f\" % (1. - np.sum(np.abs(np.array(valid_pred + 0.5, int) -",
"OUTPUT_SIZE = sushi_data.train_labels.shape[1] # Create the model # Input(25) - Layer 1(units) x",
"o in test_pred]) print \"Test mpe accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(test_mpe_pred - sushi_data.test_labels), axis=1),",
"sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) valid_mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p) for p in o])",
"float(sushi_data.test_data.shape[0])) print(\"Percentage of individual labels in test that are right: %f\" % (1.",
"= tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print \"Train accuracy: %f\" % sess.run(accuracy, feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels})",
"= sushi_data.train_labels.shape[1] # Create the model # Input(25) - Layer 1(units) x =",
"x = tf.placeholder(tf.float32, [None, INPUT_SIZE]) W = [] b = [] ys =",
"default=100, help='Number of units per hidden layer') parser.add_argument('--layers', type=int, default=3, help='Number of hidden",
"Layer i(units) - Layer i+1(units) W.append(weight_variable([FLAGS.units, FLAGS.units])) b.append(bias_variable([FLAGS.units])) ys.append(tf.nn.sigmoid(tf.matmul(ys[i-1], W[i]) + b[i])) #",
"return tf.Variable(tf.truncated_normal(shape, 0.1)) def main(_): # Get data sushi_data = SushiData('sushi.soc') INPUT_SIZE =",
"+ 0.5, int) - sushi_data.valid_labels))/float(sushi_data.valid_labels.shape[0] * sushi_data.valid_labels.shape[1]))) # Compute pairwise accuracies using MPE",
"weight_variable(shape): return tf.Variable(tf.truncated_normal(shape, 0.1)) def bias_variable(shape): return tf.Variable(tf.truncated_normal(shape, 0.1)) def main(_): # Get",
"[None, INPUT_SIZE]) W = [] b = [] ys = [] W.append(weight_variable([INPUT_SIZE, FLAGS.units]))",
"only compute pairwise comparisons once for labels train_pw = to_pairwise_comp(sushi_data.train_labels, np.sqrt(OUTPUT_SIZE)) valid_pw =",
"in pred]) print \"Train mpe accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(mpe_pred - sushi_data.train_labels), axis=1), 0)))",
"data sushi_data = SushiData('sushi.soc') INPUT_SIZE = sushi_data.train_data.shape[1] OUTPUT_SIZE = sushi_data.train_labels.shape[1] # Create the",
"- float(np.sum(np.abs(valid_mpe_pred_pw - valid_pw)))/float(10*sushi_data.valid_data.shape[0])) # Print loss print \"Train loss: %f\" % sess.run(loss,",
"\"Validation WMC: %f\" % sess.run(tf.reduce_mean(wmc), feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) print(\"Percentage of predictions that",
"import SushiData, to_pairwise_comp from compute_mpe import CircuitMPE import tensorflow as tf FLAGS =None",
"FLAGS.wmc * tf.log(tf.reduce_mean(wmc)) # train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss) # train_step = tf.train.AdagradOptimizer(0.1).minimize(loss) # train_step",
"ny] for ny in yu] # ac = AC('permutation-4.ac',yleaves) # Create CircuitMPE instance",
"tf.train.GradientDescentOptimizer(0.5).minimize(loss) # train_step = tf.train.AdagradOptimizer(0.1).minimize(loss) # train_step = tf.train.MomentumOptimizer(0.1, 0.5).minimize(loss) train_step = tf.train.AdamOptimizer().minimize(loss)",
"print \"Train pairwise mpe accuracy: %f\" % (1. - float(np.sum(np.abs(mpe_pred_pw - train_pw)))/float(10*sushi_data.train_data.shape[0])) valid_mpe_pred_pw",
"\"Train accuracy: %f\" % sess.run(accuracy, feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) print \"Validation accuracy: %f\"",
"loop sess = tf.InteractiveSession() tf.global_variables_initializer().run() # Should only compute pairwise comparisons once for",
"tf.equal(tf.reduce_sum(tf.abs(tf.to_int32(tf.nn.sigmoid(y)+0.5) - tf.to_int32(y_)), 1), 0) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print \"Train accuracy: %f\"",
"= tf.train.AdagradOptimizer(0.1).minimize(loss) # train_step = tf.train.MomentumOptimizer(0.1, 0.5).minimize(loss) train_step = tf.train.AdamOptimizer().minimize(loss) # Train loop",
"individual labels in test that are right: %f\" % (1. - np.sum(np.abs(np.array(test_pred +",
"print(\"Percentage of individual labels in test that are right: %f\" % (1. -",
"W.append(weight_variable([INPUT_SIZE, FLAGS.units])) b.append(bias_variable([FLAGS.units])) ys.append(tf.nn.sigmoid(tf.matmul(x, W[0]) + b[0])) for i in range(1, FLAGS.layers): #",
"= cmpe.get_tf_ac([[1.0 - ny,ny] for ny in yu]) cross_entropy = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=y_, logits=y)) loss",
"n(units) - Output(25) W.append(weight_variable([FLAGS.units, OUTPUT_SIZE])) b.append(bias_variable([OUTPUT_SIZE])) y = tf.matmul(ys[-1], W[-1]) + b[-1] +",
"i(units) - Layer i+1(units) W.append(weight_variable([FLAGS.units, FLAGS.units])) b.append(bias_variable([FLAGS.units])) ys.append(tf.nn.sigmoid(tf.matmul(ys[i-1], W[i]) + b[i])) # Layer",
"test_pw = to_pairwise_comp(sushi_data.test_labels, np.sqrt(OUTPUT_SIZE)) print train_pw.shape print train_pw # For early stopping prev_loss",
"INPUT_SIZE = sushi_data.train_data.shape[1] OUTPUT_SIZE = sushi_data.train_labels.shape[1] # Create the model # Input(25) -",
"using MPE mpe_pred_pw = to_pairwise_comp(mpe_pred, 5) print \"Train pairwise mpe accuracy: %f\" %",
"tf.placeholder(tf.float32, [None, INPUT_SIZE]) W = [] b = [] ys = [] W.append(weight_variable([INPUT_SIZE,",
"for o in np.array(valid_pred + 0.5, int)]))/float(sushi_data.valid_data.shape[0]))) # Early stopping if prev_loss <",
"accuracy: %f\" % sess.run(accuracy, feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) print \"Validation accuracy: %f\" %",
"# Create AC # yleaves = [[ny, 1.0 - ny] for ny in",
"mpe accuracy: %f\" % (1. - float(np.sum(np.abs(test_mpe_pred_pw - test_pw)))/float(10*sushi_data.test_data.shape[0])) sys.exit() else: prev_loss =",
"y_: batch_ys}) # Every 1k iterations check accuracy if i % 100 ==",
"WMC in loss') parser.add_argument('--iters', type=int, default=10000, help='Number of minibatch steps to do') FLAGS,",
"default=0.0, help='Coefficient of WMC in loss') parser.add_argument('--iters', type=int, default=10000, help='Number of minibatch steps",
"\"Test accuracy: %f\" % sess.run(accuracy, feed_dict={x: sushi_data.test_data, y_: sushi_data.test_labels}) test_pred = sess.run(tf.nn.sigmoid(y), feed_dict={x:",
"tf.train.AdagradOptimizer(0.1).minimize(loss) # train_step = tf.train.MomentumOptimizer(0.1, 0.5).minimize(loss) train_step = tf.train.AdamOptimizer().minimize(loss) # Train loop sess",
"% (1. - float(np.sum(np.abs(valid_mpe_pred_pw - valid_pw)))/float(10*sushi_data.valid_data.shape[0])) # Print loss print \"Train loss: %f\"",
"tf.Variable(tf.truncated_normal(shape, 0.1)) def main(_): # Get data sushi_data = SushiData('sushi.soc') INPUT_SIZE = sushi_data.train_data.shape[1]",
"== '__main__': parser = argparse.ArgumentParser() # Args go here parser.add_argument('--units', type=int, default=100, help='Number",
"sys.exit() else: prev_loss = valid_loss if __name__ == '__main__': parser = argparse.ArgumentParser() #",
"for o in pred]) print \"Train mpe accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(mpe_pred - sushi_data.train_labels),",
"are right: %f\" % (1. - np.sum(np.abs(np.array(valid_pred + 0.5, int) - sushi_data.valid_labels))/float(sushi_data.valid_labels.shape[0] *",
"training that are right: %f\" % (1. - np.sum(np.abs(np.array(pred + 0.5, int) -",
"batch_xs, batch_ys = sushi_data.train_data, sushi_data.train_labels sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) # Every 1k",
"'__main__': parser = argparse.ArgumentParser() # Args go here parser.add_argument('--units', type=int, default=100, help='Number of",
"W[-1]) + b[-1] + np.finfo(float).eps * 10 # Define loss and optimizer y_",
"# Computing \"true\" accuracies correct_prediction = tf.equal(tf.reduce_sum(tf.abs(tf.to_int32(tf.nn.sigmoid(y)+0.5) - tf.to_int32(y_)), 1), 0) accuracy =",
"Create AC # yleaves = [[ny, 1.0 - ny] for ny in yu]",
"type=int, default=10000, help='Number of minibatch steps to do') FLAGS, unparsed = parser.parse_known_args() tf.app.run(main=main,",
"loss print \"Train loss: %f\" % sess.run(loss, feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) valid_loss =",
"%f\" % (1. - float(np.sum(np.abs(mpe_pred_pw - train_pw)))/float(10*sushi_data.train_data.shape[0])) valid_mpe_pred_pw = to_pairwise_comp(valid_mpe_pred, 5) print \"Validation",
"= to_pairwise_comp(mpe_pred, 5) print \"Train pairwise mpe accuracy: %f\" % (1. - float(np.sum(np.abs(mpe_pred_pw",
"test_pred]) print \"Test mpe accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(test_mpe_pred - sushi_data.test_labels), axis=1), 0))) /",
"sushi_data.test_data, y_: sushi_data.test_labels}) test_pred = sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.test_data, y_: sushi_data.test_labels}) test_mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p,",
"sushi_data.valid_labels}) valid_mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p) for p in o]) for o in valid_pred])",
"hidden layers') parser.add_argument('--wmc', type=float, default=0.0, help='Coefficient of WMC in loss') parser.add_argument('--iters', type=int, default=10000,",
"tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print \"Train accuracy: %f\" % sess.run(accuracy, feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) print",
"np.sum(np.abs(np.array(valid_pred + 0.5, int) - sushi_data.valid_labels))/float(sushi_data.valid_labels.shape[0] * sushi_data.valid_labels.shape[1]))) # Compute pairwise accuracies using",
"b.append(bias_variable([OUTPUT_SIZE])) y = tf.matmul(ys[-1], W[-1]) + b[-1] + np.finfo(float).eps * 10 # Define",
"= to_pairwise_comp(test_mpe_pred, 5) print \"Test pairwise mpe accuracy: %f\" % (1. - float(np.sum(np.abs(test_mpe_pred_pw",
"\"Train loss: %f\" % sess.run(loss, feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) valid_loss = sess.run(loss, feed_dict={x:",
"individual labels in validation that are right: %f\" % (1. - np.sum(np.abs(np.array(valid_pred +",
"1k iterations check accuracy if i % 100 == 0: print(\"After %d iterations\"",
"- ny,ny] for ny in yu]) cross_entropy = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=y_, logits=y)) loss = cross_entropy",
"- sushi_data.train_labels), axis=1), 0))) / float(sushi_data.train_data.shape[0])) valid_pred = sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels})",
"= [] ys = [] W.append(weight_variable([INPUT_SIZE, FLAGS.units])) b.append(bias_variable([FLAGS.units])) ys.append(tf.nn.sigmoid(tf.matmul(x, W[0]) + b[0])) for",
"units per hidden layer') parser.add_argument('--layers', type=int, default=3, help='Number of hidden layers') parser.add_argument('--wmc', type=float,",
"b.append(bias_variable([FLAGS.units])) ys.append(tf.nn.sigmoid(tf.matmul(ys[i-1], W[i]) + b[i])) # Layer n(units) - Output(25) W.append(weight_variable([FLAGS.units, OUTPUT_SIZE])) b.append(bias_variable([OUTPUT_SIZE]))",
"train_step = tf.train.AdagradOptimizer(0.1).minimize(loss) # train_step = tf.train.MomentumOptimizer(0.1, 0.5).minimize(loss) train_step = tf.train.AdamOptimizer().minimize(loss) # Train",
"np from sushi_data import SushiData, to_pairwise_comp from compute_mpe import CircuitMPE import tensorflow as",
"% sess.run(accuracy, feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) print \"Validation accuracy: %f\" % sess.run(accuracy, feed_dict={x:",
"= tf.matmul(ys[-1], W[-1]) + b[-1] + np.finfo(float).eps * 10 # Define loss and",
"prev_loss < valid_loss: print \"Stopping early\" print \"Test accuracy: %f\" % sess.run(accuracy, feed_dict={x:",
"b[i])) # Layer n(units) - Output(25) W.append(weight_variable([FLAGS.units, OUTPUT_SIZE])) b.append(bias_variable([OUTPUT_SIZE])) y = tf.matmul(ys[-1], W[-1])",
"100 == 0: print(\"After %d iterations\" % i) # Computing \"true\" accuracies correct_prediction",
"def main(_): # Get data sushi_data = SushiData('sushi.soc') INPUT_SIZE = sushi_data.train_data.shape[1] OUTPUT_SIZE =",
"sushi_data.test_labels}) test_pred = sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.test_data, y_: sushi_data.test_labels}) test_mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p) for",
"\"Validation accuracy: %f\" % sess.run(accuracy, feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) # Computing MPE instiation",
"sushi_data.test_data, y_: sushi_data.test_labels}) test_mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p) for p in o]) for o",
"% (1. - np.sum(np.abs(np.array(test_pred + 0.5, int) - sushi_data.test_labels))/float(sushi_data.test_labels.shape[0] * sushi_data.test_labels.shape[1]))) test_mpe_pred_pw =",
"[] ys = [] W.append(weight_variable([INPUT_SIZE, FLAGS.units])) b.append(bias_variable([FLAGS.units])) ys.append(tf.nn.sigmoid(tf.matmul(x, W[0]) + b[0])) for i",
"for labels train_pw = to_pairwise_comp(sushi_data.train_labels, np.sqrt(OUTPUT_SIZE)) valid_pw = to_pairwise_comp(sushi_data.valid_labels, np.sqrt(OUTPUT_SIZE)) test_pw = to_pairwise_comp(sushi_data.test_labels,",
"sess = tf.InteractiveSession() tf.global_variables_initializer().run() # Should only compute pairwise comparisons once for labels",
"W[0]) + b[0])) for i in range(1, FLAGS.layers): # Layer i(units) - Layer",
"to_pairwise_comp(valid_mpe_pred, 5) print \"Validation pairwise mpe accuracy: %f\" % (1. - float(np.sum(np.abs(valid_mpe_pred_pw -",
"train_pw.shape print train_pw # For early stopping prev_loss = 1e15 # Train for",
"= tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=y_, logits=y)) loss = cross_entropy - FLAGS.wmc * tf.log(tf.reduce_mean(wmc)) # train_step =",
"in valid_pred]) print \"Validation mpe accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(valid_mpe_pred - sushi_data.valid_labels), axis=1), 0)))",
"% sess.run(accuracy, feed_dict={x: sushi_data.test_data, y_: sushi_data.test_labels}) test_pred = sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.test_data, y_: sushi_data.test_labels})",
"[[ny, 1.0 - ny] for ny in yu] # ac = AC('permutation-4.ac',yleaves) #",
"labels in validation that are right: %f\" % (1. - np.sum(np.abs(np.array(valid_pred + 0.5,",
"predictions that follow constraint: %f\" % (float(np.sum([cmpe.weighted_model_count([(1-p, p) for p in o]) for",
"p in o]) for o in np.array(valid_pred + 0.5, int)]))/float(sushi_data.valid_data.shape[0]))) # Early stopping",
"\"Train mpe accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(mpe_pred - sushi_data.train_labels), axis=1), 0))) / float(sushi_data.train_data.shape[0])) valid_pred",
"parser.add_argument('--wmc', type=float, default=0.0, help='Coefficient of WMC in loss') parser.add_argument('--iters', type=int, default=10000, help='Number of",
"\"Test pairwise mpe accuracy: %f\" % (1. - float(np.sum(np.abs(test_mpe_pred_pw - test_pw)))/float(10*sushi_data.test_data.shape[0])) sys.exit() else:",
"in yu]) cross_entropy = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=y_, logits=y)) loss = cross_entropy - FLAGS.wmc * tf.log(tf.reduce_mean(wmc))",
"For early stopping prev_loss = 1e15 # Train for i in range(FLAGS.iters): #",
"pairwise comparisons once for labels train_pw = to_pairwise_comp(sushi_data.train_labels, np.sqrt(OUTPUT_SIZE)) valid_pw = to_pairwise_comp(sushi_data.valid_labels, np.sqrt(OUTPUT_SIZE))",
"# Early stopping if prev_loss < valid_loss: print \"Stopping early\" print \"Test accuracy:",
"to_pairwise_comp(sushi_data.valid_labels, np.sqrt(OUTPUT_SIZE)) test_pw = to_pairwise_comp(sushi_data.test_labels, np.sqrt(OUTPUT_SIZE)) print train_pw.shape print train_pw # For early",
"pairwise mpe accuracy: %f\" % (1. - float(np.sum(np.abs(valid_mpe_pred_pw - valid_pw)))/float(10*sushi_data.valid_data.shape[0])) # Print loss",
"np.sqrt(OUTPUT_SIZE)) print train_pw.shape print train_pw # For early stopping prev_loss = 1e15 #",
"float(np.sum(np.abs(test_mpe_pred_pw - test_pw)))/float(10*sushi_data.test_data.shape[0])) sys.exit() else: prev_loss = valid_loss if __name__ == '__main__': parser",
"import tensorflow as tf FLAGS =None def weight_variable(shape): return tf.Variable(tf.truncated_normal(shape, 0.1)) def bias_variable(shape):",
"of individual labels in test that are right: %f\" % (1. - np.sum(np.abs(np.array(test_pred",
"+ 0.5, int) - sushi_data.train_labels))/float(sushi_data.train_labels.shape[0] * sushi_data.train_labels.shape[1]))) print(\"Percentage of individual labels in validation",
"batch_ys = sushi_data.train_data, sushi_data.train_labels sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) # Every 1k iterations",
"\"Train WMC: %f\" % sess.run(tf.reduce_mean(wmc), feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) print \"Validation WMC: %f\"",
"# Create the model # Input(25) - Layer 1(units) x = tf.placeholder(tf.float32, [None,",
"- sushi_data.valid_labels))/float(sushi_data.valid_labels.shape[0] * sushi_data.valid_labels.shape[1]))) # Compute pairwise accuracies using MPE mpe_pred_pw = to_pairwise_comp(mpe_pred,",
"= sushi_data.train_data, sushi_data.train_labels sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) # Every 1k iterations check",
"% sess.run(tf.reduce_mean(wmc), feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) print(\"Percentage of predictions that follow constraint: %f\"",
"- np.sum(np.abs(np.array(pred + 0.5, int) - sushi_data.train_labels))/float(sushi_data.train_labels.shape[0] * sushi_data.train_labels.shape[1]))) print(\"Percentage of individual labels",
"for ny in yu] # ac = AC('permutation-4.ac',yleaves) # Create CircuitMPE instance for",
"p in o]) for o in pred]) print \"Train mpe accuracy: %f\" %",
"np.sum(np.abs(np.array(test_pred + 0.5, int) - sushi_data.test_labels))/float(sushi_data.test_labels.shape[0] * sushi_data.test_labels.shape[1]))) test_mpe_pred_pw = to_pairwise_comp(test_mpe_pred, 5) print",
"def weight_variable(shape): return tf.Variable(tf.truncated_normal(shape, 0.1)) def bias_variable(shape): return tf.Variable(tf.truncated_normal(shape, 0.1)) def main(_): #",
"sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p) for p in o])",
"are right: %f\" % (1. - np.sum(np.abs(np.array(pred + 0.5, int) - sushi_data.train_labels))/float(sushi_data.train_labels.shape[0] *",
"0.5, int) - sushi_data.valid_labels))/float(sushi_data.valid_labels.shape[0] * sushi_data.valid_labels.shape[1]))) # Compute pairwise accuracies using MPE mpe_pred_pw",
"y_: sushi_data.valid_labels}) valid_mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p) for p in o]) for o in",
"for i in range(FLAGS.iters): # batch_xs, batch_ys = sushi_data.get_batch(400) batch_xs, batch_ys = sushi_data.train_data,",
"accuracy if i % 100 == 0: print(\"After %d iterations\" % i) #",
"sess.run(loss, feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) valid_loss = sess.run(loss, feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) print",
"accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(valid_mpe_pred - sushi_data.valid_labels), axis=1), 0))) / float(sushi_data.valid_data.shape[0])) # Percentage of",
"def bias_variable(shape): return tf.Variable(tf.truncated_normal(shape, 0.1)) def main(_): # Get data sushi_data = SushiData('sushi.soc')",
"% (float(np.sum(np.equal(np.sum(np.abs(mpe_pred - sushi_data.train_labels), axis=1), 0))) / float(sushi_data.train_data.shape[0])) valid_pred = sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.valid_data,",
"to_pairwise_comp(test_mpe_pred, 5) print \"Test pairwise mpe accuracy: %f\" % (1. - float(np.sum(np.abs(test_mpe_pred_pw -",
"/ float(sushi_data.valid_data.shape[0])) # Percentage of individual labels that are right print(\"Percentage of individual",
"cmpe.get_tf_ac([[1.0 - ny,ny] for ny in yu]) cross_entropy = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=y_, logits=y)) loss =",
"valid_pw = to_pairwise_comp(sushi_data.valid_labels, np.sqrt(OUTPUT_SIZE)) test_pw = to_pairwise_comp(sushi_data.test_labels, np.sqrt(OUTPUT_SIZE)) print train_pw.shape print train_pw #",
"o]) for o in test_pred]) print \"Test mpe accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(test_mpe_pred -",
"sushi_data.train_labels sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) # Every 1k iterations check accuracy if",
"# Train for i in range(FLAGS.iters): # batch_xs, batch_ys = sushi_data.get_batch(400) batch_xs, batch_ys",
"# Every 1k iterations check accuracy if i % 100 == 0: print(\"After",
"y_: sushi_data.train_labels}) print \"Validation accuracy: %f\" % sess.run(accuracy, feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) #",
"np.array([cmpe.compute_mpe_inst([(1-p, p) for p in o]) for o in test_pred]) print \"Test mpe",
"= tf.placeholder(tf.float32, [None, OUTPUT_SIZE]) yu = tf.unstack(tf.nn.sigmoid(y), axis=1) # Create AC # yleaves",
"instiation accuracies pred = sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p)",
"+ 0.5, int)]))/float(sushi_data.valid_data.shape[0]))) # Early stopping if prev_loss < valid_loss: print \"Stopping early\"",
"- Layer i+1(units) W.append(weight_variable([FLAGS.units, FLAGS.units])) b.append(bias_variable([FLAGS.units])) ys.append(tf.nn.sigmoid(tf.matmul(ys[i-1], W[i]) + b[i])) # Layer n(units)",
"in np.array(valid_pred + 0.5, int)]))/float(sushi_data.valid_data.shape[0]))) # Early stopping if prev_loss < valid_loss: print",
"5) print \"Train pairwise mpe accuracy: %f\" % (1. - float(np.sum(np.abs(mpe_pred_pw - train_pw)))/float(10*sushi_data.train_data.shape[0]))",
"pairwise mpe accuracy: %f\" % (1. - float(np.sum(np.abs(test_mpe_pred_pw - test_pw)))/float(10*sushi_data.test_data.shape[0])) sys.exit() else: prev_loss",
"valid_mpe_pred_pw = to_pairwise_comp(valid_mpe_pred, 5) print \"Validation pairwise mpe accuracy: %f\" % (1. -",
"np.array([cmpe.compute_mpe_inst([(1-p, p) for p in o]) for o in valid_pred]) print \"Validation mpe",
"= sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p) for p in",
"accuracies pred = sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p) for",
"sushi_data import SushiData, to_pairwise_comp from compute_mpe import CircuitMPE import tensorflow as tf FLAGS",
"mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p) for p in o]) for o in pred]) print",
"* sushi_data.train_labels.shape[1]))) print(\"Percentage of individual labels in validation that are right: %f\" %",
"sushi_data.train_labels}) print \"Validation WMC: %f\" % sess.run(tf.reduce_mean(wmc), feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) print(\"Percentage of",
"%f\" % (float(np.sum(np.equal(np.sum(np.abs(mpe_pred - sushi_data.train_labels), axis=1), 0))) / float(sushi_data.train_data.shape[0])) valid_pred = sess.run(tf.nn.sigmoid(y), feed_dict={x:",
"# Print WMC print \"Train WMC: %f\" % sess.run(tf.reduce_mean(wmc), feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels})",
"* sushi_data.test_labels.shape[1]))) test_mpe_pred_pw = to_pairwise_comp(test_mpe_pred, 5) print \"Test pairwise mpe accuracy: %f\" %",
"(float(np.sum(np.equal(np.sum(np.abs(test_mpe_pred - sushi_data.test_labels), axis=1), 0))) / float(sushi_data.test_data.shape[0])) print(\"Percentage of individual labels in test",
"tf.train.MomentumOptimizer(0.1, 0.5).minimize(loss) train_step = tf.train.AdamOptimizer().minimize(loss) # Train loop sess = tf.InteractiveSession() tf.global_variables_initializer().run() #",
"= np.array([cmpe.compute_mpe_inst([(1-p, p) for p in o]) for o in pred]) print \"Train",
"feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) valid_mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p) for p in o]) for",
"o in np.array(valid_pred + 0.5, int)]))/float(sushi_data.valid_data.shape[0]))) # Early stopping if prev_loss < valid_loss:",
"int) - sushi_data.test_labels))/float(sushi_data.test_labels.shape[0] * sushi_data.test_labels.shape[1]))) test_mpe_pred_pw = to_pairwise_comp(test_mpe_pred, 5) print \"Test pairwise mpe",
"%f\" % sess.run(loss, feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) valid_loss = sess.run(loss, feed_dict={x: sushi_data.valid_data, y_:",
"10 # Define loss and optimizer y_ = tf.placeholder(tf.float32, [None, OUTPUT_SIZE]) yu =",
"# ac = AC('permutation-4.ac',yleaves) # Create CircuitMPE instance for our predictions cmpe =",
"sushi_data.train_labels}) print \"Validation accuracy: %f\" % sess.run(accuracy, feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) # Computing",
"(1. - np.sum(np.abs(np.array(valid_pred + 0.5, int) - sushi_data.valid_labels))/float(sushi_data.valid_labels.shape[0] * sushi_data.valid_labels.shape[1]))) # Compute pairwise",
"y_: sushi_data.train_labels}) valid_loss = sess.run(loss, feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) print \"Validation loss: %f\"",
"\"Stopping early\" print \"Test accuracy: %f\" % sess.run(accuracy, feed_dict={x: sushi_data.test_data, y_: sushi_data.test_labels}) test_pred",
"Layer 1(units) x = tf.placeholder(tf.float32, [None, INPUT_SIZE]) W = [] b = []",
"# Train loop sess = tf.InteractiveSession() tf.global_variables_initializer().run() # Should only compute pairwise comparisons",
"right: %f\" % (1. - np.sum(np.abs(np.array(valid_pred + 0.5, int) - sushi_data.valid_labels))/float(sushi_data.valid_labels.shape[0] * sushi_data.valid_labels.shape[1])))",
"prev_loss = 1e15 # Train for i in range(FLAGS.iters): # batch_xs, batch_ys =",
"\"true\" accuracies correct_prediction = tf.equal(tf.reduce_sum(tf.abs(tf.to_int32(tf.nn.sigmoid(y)+0.5) - tf.to_int32(y_)), 1), 0) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))",
"in o]) for o in test_pred]) print \"Test mpe accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(test_mpe_pred",
"% 100 == 0: print(\"After %d iterations\" % i) # Computing \"true\" accuracies",
"default=3, help='Number of hidden layers') parser.add_argument('--wmc', type=float, default=0.0, help='Coefficient of WMC in loss')",
"of individual labels that are right print(\"Percentage of individual labels in training that",
"% (1. - float(np.sum(np.abs(test_mpe_pred_pw - test_pw)))/float(10*sushi_data.test_data.shape[0])) sys.exit() else: prev_loss = valid_loss if __name__",
"tf.log(tf.reduce_mean(wmc)) # train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss) # train_step = tf.train.AdagradOptimizer(0.1).minimize(loss) # train_step = tf.train.MomentumOptimizer(0.1,",
"[] W.append(weight_variable([INPUT_SIZE, FLAGS.units])) b.append(bias_variable([FLAGS.units])) ys.append(tf.nn.sigmoid(tf.matmul(x, W[0]) + b[0])) for i in range(1, FLAGS.layers):",
"tf.unstack(tf.nn.sigmoid(y), axis=1) # Create AC # yleaves = [[ny, 1.0 - ny] for",
"range(FLAGS.iters): # batch_xs, batch_ys = sushi_data.get_batch(400) batch_xs, batch_ys = sushi_data.train_data, sushi_data.train_labels sess.run(train_step, feed_dict={x:",
"valid_pred = sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) valid_mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p) for p",
"0.5, int)]))/float(sushi_data.valid_data.shape[0]))) # Early stopping if prev_loss < valid_loss: print \"Stopping early\" print",
"for p in o]) for o in valid_pred]) print \"Validation mpe accuracy: %f\"",
"W[i]) + b[i])) # Layer n(units) - Output(25) W.append(weight_variable([FLAGS.units, OUTPUT_SIZE])) b.append(bias_variable([OUTPUT_SIZE])) y =",
"sushi_data.test_labels}) test_mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p) for p in o]) for o in test_pred])",
"sushi_data.train_data, y_: sushi_data.train_labels}) valid_loss = sess.run(loss, feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) print \"Validation loss:",
"accuracy: %f\" % (1. - float(np.sum(np.abs(test_mpe_pred_pw - test_pw)))/float(10*sushi_data.test_data.shape[0])) sys.exit() else: prev_loss = valid_loss",
"iterations check accuracy if i % 100 == 0: print(\"After %d iterations\" %",
"/ float(sushi_data.train_data.shape[0])) valid_pred = sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) valid_mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p)",
"np.finfo(float).eps * 10 # Define loss and optimizer y_ = tf.placeholder(tf.float32, [None, OUTPUT_SIZE])",
"= to_pairwise_comp(sushi_data.train_labels, np.sqrt(OUTPUT_SIZE)) valid_pw = to_pairwise_comp(sushi_data.valid_labels, np.sqrt(OUTPUT_SIZE)) test_pw = to_pairwise_comp(sushi_data.test_labels, np.sqrt(OUTPUT_SIZE)) print train_pw.shape",
"in range(1, FLAGS.layers): # Layer i(units) - Layer i+1(units) W.append(weight_variable([FLAGS.units, FLAGS.units])) b.append(bias_variable([FLAGS.units])) ys.append(tf.nn.sigmoid(tf.matmul(ys[i-1],",
"= sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) valid_mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p) for p in",
"%f\" % (float(np.sum([cmpe.weighted_model_count([(1-p, p) for p in o]) for o in np.array(valid_pred +",
"AC('permutation-4.ac',yleaves) # Create CircuitMPE instance for our predictions cmpe = CircuitMPE('permutation-4.vtree', 'permutation-4.sdd') wmc",
"int) - sushi_data.valid_labels))/float(sushi_data.valid_labels.shape[0] * sushi_data.valid_labels.shape[1]))) # Compute pairwise accuracies using MPE mpe_pred_pw =",
"axis=1), 0))) / float(sushi_data.valid_data.shape[0])) # Percentage of individual labels that are right print(\"Percentage",
"= to_pairwise_comp(sushi_data.valid_labels, np.sqrt(OUTPUT_SIZE)) test_pw = to_pairwise_comp(sushi_data.test_labels, np.sqrt(OUTPUT_SIZE)) print train_pw.shape print train_pw # For",
"o in pred]) print \"Train mpe accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(mpe_pred - sushi_data.train_labels), axis=1),",
"valid_mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p) for p in o]) for o in valid_pred]) print",
"p) for p in o]) for o in test_pred]) print \"Test mpe accuracy:",
"loss = cross_entropy - FLAGS.wmc * tf.log(tf.reduce_mean(wmc)) # train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss) # train_step",
"= np.array([cmpe.compute_mpe_inst([(1-p, p) for p in o]) for o in test_pred]) print \"Test",
"% sess.run(loss, feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) valid_loss = sess.run(loss, feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels})",
"sushi_data.valid_labels), axis=1), 0))) / float(sushi_data.valid_data.shape[0])) # Percentage of individual labels that are right",
"mpe_pred_pw = to_pairwise_comp(mpe_pred, 5) print \"Train pairwise mpe accuracy: %f\" % (1. -",
"% (1. - np.sum(np.abs(np.array(pred + 0.5, int) - sushi_data.train_labels))/float(sushi_data.train_labels.shape[0] * sushi_data.train_labels.shape[1]))) print(\"Percentage of",
"tf.InteractiveSession() tf.global_variables_initializer().run() # Should only compute pairwise comparisons once for labels train_pw =",
"# Args go here parser.add_argument('--units', type=int, default=100, help='Number of units per hidden layer')",
"i+1(units) W.append(weight_variable([FLAGS.units, FLAGS.units])) b.append(bias_variable([FLAGS.units])) ys.append(tf.nn.sigmoid(tf.matmul(ys[i-1], W[i]) + b[i])) # Layer n(units) - Output(25)",
"o]) for o in valid_pred]) print \"Validation mpe accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(valid_mpe_pred -",
"type=int, default=100, help='Number of units per hidden layer') parser.add_argument('--layers', type=int, default=3, help='Number of",
"Define loss and optimizer y_ = tf.placeholder(tf.float32, [None, OUTPUT_SIZE]) yu = tf.unstack(tf.nn.sigmoid(y), axis=1)",
"yleaves = [[ny, 1.0 - ny] for ny in yu] # ac =",
"sushi_data.train_labels.shape[1]))) print(\"Percentage of individual labels in validation that are right: %f\" % (1.",
"Computing MPE instiation accuracies pred = sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) mpe_pred =",
"feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p) for p in o]) for",
"of predictions that follow constraint: %f\" % (float(np.sum([cmpe.weighted_model_count([(1-p, p) for p in o])",
"= sushi_data.train_data.shape[1] OUTPUT_SIZE = sushi_data.train_labels.shape[1] # Create the model # Input(25) - Layer",
"%f\" % (1. - np.sum(np.abs(np.array(valid_pred + 0.5, int) - sushi_data.valid_labels))/float(sushi_data.valid_labels.shape[0] * sushi_data.valid_labels.shape[1]))) #",
"sushi_data.valid_data, y_: sushi_data.valid_labels}) print \"Validation loss: %f\" % valid_loss # Print WMC print",
"instance for our predictions cmpe = CircuitMPE('permutation-4.vtree', 'permutation-4.sdd') wmc = cmpe.get_tf_ac([[1.0 - ny,ny]",
"- Layer 1(units) x = tf.placeholder(tf.float32, [None, INPUT_SIZE]) W = [] b =",
"(1. - float(np.sum(np.abs(test_mpe_pred_pw - test_pw)))/float(10*sushi_data.test_data.shape[0])) sys.exit() else: prev_loss = valid_loss if __name__ ==",
"parser.add_argument('--iters', type=int, default=10000, help='Number of minibatch steps to do') FLAGS, unparsed = parser.parse_known_args()",
"cross_entropy - FLAGS.wmc * tf.log(tf.reduce_mean(wmc)) # train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss) # train_step = tf.train.AdagradOptimizer(0.1).minimize(loss)",
"\"Validation pairwise mpe accuracy: %f\" % (1. - float(np.sum(np.abs(valid_mpe_pred_pw - valid_pw)))/float(10*sushi_data.valid_data.shape[0])) # Print",
"# batch_xs, batch_ys = sushi_data.get_batch(400) batch_xs, batch_ys = sushi_data.train_data, sushi_data.train_labels sess.run(train_step, feed_dict={x: batch_xs,",
"y_: sushi_data.valid_labels}) print \"Validation loss: %f\" % valid_loss # Print WMC print \"Train",
"print train_pw.shape print train_pw # For early stopping prev_loss = 1e15 # Train",
"tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=y_, logits=y)) loss = cross_entropy - FLAGS.wmc * tf.log(tf.reduce_mean(wmc)) # train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss)",
"for our predictions cmpe = CircuitMPE('permutation-4.vtree', 'permutation-4.sdd') wmc = cmpe.get_tf_ac([[1.0 - ny,ny] for",
"yu] # ac = AC('permutation-4.ac',yleaves) # Create CircuitMPE instance for our predictions cmpe",
"0.1)) def bias_variable(shape): return tf.Variable(tf.truncated_normal(shape, 0.1)) def main(_): # Get data sushi_data =",
"go here parser.add_argument('--units', type=int, default=100, help='Number of units per hidden layer') parser.add_argument('--layers', type=int,",
"for o in valid_pred]) print \"Validation mpe accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(valid_mpe_pred - sushi_data.valid_labels),",
"print \"Train mpe accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(mpe_pred - sushi_data.train_labels), axis=1), 0))) / float(sushi_data.train_data.shape[0]))",
"print \"Test pairwise mpe accuracy: %f\" % (1. - float(np.sum(np.abs(test_mpe_pred_pw - test_pw)))/float(10*sushi_data.test_data.shape[0])) sys.exit()",
"in o]) for o in pred]) print \"Train mpe accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(mpe_pred",
"individual labels in training that are right: %f\" % (1. - np.sum(np.abs(np.array(pred +",
"= to_pairwise_comp(valid_mpe_pred, 5) print \"Validation pairwise mpe accuracy: %f\" % (1. - float(np.sum(np.abs(valid_mpe_pred_pw",
"sess.run(tf.reduce_mean(wmc), feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) print(\"Percentage of predictions that follow constraint: %f\" %",
"in test_pred]) print \"Test mpe accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(test_mpe_pred - sushi_data.test_labels), axis=1), 0)))",
"- test_pw)))/float(10*sushi_data.test_data.shape[0])) sys.exit() else: prev_loss = valid_loss if __name__ == '__main__': parser =",
"p in o]) for o in test_pred]) print \"Test mpe accuracy: %f\" %",
"accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(mpe_pred - sushi_data.train_labels), axis=1), 0))) / float(sushi_data.train_data.shape[0])) valid_pred = sess.run(tf.nn.sigmoid(y),",
"of individual labels in training that are right: %f\" % (1. - np.sum(np.abs(np.array(pred",
"batch_xs, y_: batch_ys}) # Every 1k iterations check accuracy if i % 100",
"%f\" % (1. - np.sum(np.abs(np.array(pred + 0.5, int) - sushi_data.train_labels))/float(sushi_data.train_labels.shape[0] * sushi_data.train_labels.shape[1]))) print(\"Percentage",
"accuracies using MPE mpe_pred_pw = to_pairwise_comp(mpe_pred, 5) print \"Train pairwise mpe accuracy: %f\"",
"axis=1), 0))) / float(sushi_data.train_data.shape[0])) valid_pred = sess.run(tf.nn.sigmoid(y), feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) valid_mpe_pred =",
"int) - sushi_data.train_labels))/float(sushi_data.train_labels.shape[0] * sushi_data.train_labels.shape[1]))) print(\"Percentage of individual labels in validation that are",
"= sushi_data.get_batch(400) batch_xs, batch_ys = sushi_data.train_data, sushi_data.train_labels sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) #",
"= sess.run(loss, feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) print \"Validation loss: %f\" % valid_loss #",
"0))) / float(sushi_data.valid_data.shape[0])) # Percentage of individual labels that are right print(\"Percentage of",
"mpe accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(mpe_pred - sushi_data.train_labels), axis=1), 0))) / float(sushi_data.train_data.shape[0])) valid_pred =",
"- sushi_data.train_labels))/float(sushi_data.train_labels.shape[0] * sushi_data.train_labels.shape[1]))) print(\"Percentage of individual labels in validation that are right:",
"sushi_data.train_data, y_: sushi_data.train_labels}) print \"Validation WMC: %f\" % sess.run(tf.reduce_mean(wmc), feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels})",
"of individual labels in validation that are right: %f\" % (1. - np.sum(np.abs(np.array(valid_pred",
"tf.train.AdamOptimizer().minimize(loss) # Train loop sess = tf.InteractiveSession() tf.global_variables_initializer().run() # Should only compute pairwise",
"parser.add_argument('--layers', type=int, default=3, help='Number of hidden layers') parser.add_argument('--wmc', type=float, default=0.0, help='Coefficient of WMC",
"Print WMC print \"Train WMC: %f\" % sess.run(tf.reduce_mean(wmc), feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) print",
"%f\" % (float(np.sum(np.equal(np.sum(np.abs(test_mpe_pred - sushi_data.test_labels), axis=1), 0))) / float(sushi_data.test_data.shape[0])) print(\"Percentage of individual labels",
"as tf FLAGS =None def weight_variable(shape): return tf.Variable(tf.truncated_normal(shape, 0.1)) def bias_variable(shape): return tf.Variable(tf.truncated_normal(shape,",
"# train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss) # train_step = tf.train.AdagradOptimizer(0.1).minimize(loss) # train_step = tf.train.MomentumOptimizer(0.1, 0.5).minimize(loss)",
"np.sqrt(OUTPUT_SIZE)) valid_pw = to_pairwise_comp(sushi_data.valid_labels, np.sqrt(OUTPUT_SIZE)) test_pw = to_pairwise_comp(sushi_data.test_labels, np.sqrt(OUTPUT_SIZE)) print train_pw.shape print train_pw",
"feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) print \"Validation loss: %f\" % valid_loss # Print WMC",
"sess.run(accuracy, feed_dict={x: sushi_data.valid_data, y_: sushi_data.valid_labels}) # Computing MPE instiation accuracies pred = sess.run(tf.nn.sigmoid(y),",
"= to_pairwise_comp(sushi_data.test_labels, np.sqrt(OUTPUT_SIZE)) print train_pw.shape print train_pw # For early stopping prev_loss =",
"MPE mpe_pred_pw = to_pairwise_comp(mpe_pred, 5) print \"Train pairwise mpe accuracy: %f\" % (1.",
"check accuracy if i % 100 == 0: print(\"After %d iterations\" % i)",
"comparisons once for labels train_pw = to_pairwise_comp(sushi_data.train_labels, np.sqrt(OUTPUT_SIZE)) valid_pw = to_pairwise_comp(sushi_data.valid_labels, np.sqrt(OUTPUT_SIZE)) test_pw",
"sushi_data.train_data, y_: sushi_data.train_labels}) mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p) for p in o]) for o",
"- valid_pw)))/float(10*sushi_data.valid_data.shape[0])) # Print loss print \"Train loss: %f\" % sess.run(loss, feed_dict={x: sushi_data.train_data,",
"here parser.add_argument('--units', type=int, default=100, help='Number of units per hidden layer') parser.add_argument('--layers', type=int, default=3,",
"pairwise mpe accuracy: %f\" % (1. - float(np.sum(np.abs(mpe_pred_pw - train_pw)))/float(10*sushi_data.train_data.shape[0])) valid_mpe_pred_pw = to_pairwise_comp(valid_mpe_pred,",
"Train loop sess = tf.InteractiveSession() tf.global_variables_initializer().run() # Should only compute pairwise comparisons once",
"loss and optimizer y_ = tf.placeholder(tf.float32, [None, OUTPUT_SIZE]) yu = tf.unstack(tf.nn.sigmoid(y), axis=1) #",
"for ny in yu]) cross_entropy = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=y_, logits=y)) loss = cross_entropy - FLAGS.wmc",
"= tf.train.GradientDescentOptimizer(0.5).minimize(loss) # train_step = tf.train.AdagradOptimizer(0.1).minimize(loss) # train_step = tf.train.MomentumOptimizer(0.1, 0.5).minimize(loss) train_step =",
"1e15 # Train for i in range(FLAGS.iters): # batch_xs, batch_ys = sushi_data.get_batch(400) batch_xs,",
"OUTPUT_SIZE])) b.append(bias_variable([OUTPUT_SIZE])) y = tf.matmul(ys[-1], W[-1]) + b[-1] + np.finfo(float).eps * 10 #",
"Should only compute pairwise comparisons once for labels train_pw = to_pairwise_comp(sushi_data.train_labels, np.sqrt(OUTPUT_SIZE)) valid_pw",
"sushi_data.train_labels.shape[1] # Create the model # Input(25) - Layer 1(units) x = tf.placeholder(tf.float32,",
"else: prev_loss = valid_loss if __name__ == '__main__': parser = argparse.ArgumentParser() # Args",
"= [] W.append(weight_variable([INPUT_SIZE, FLAGS.units])) b.append(bias_variable([FLAGS.units])) ys.append(tf.nn.sigmoid(tf.matmul(x, W[0]) + b[0])) for i in range(1,",
"Create the model # Input(25) - Layer 1(units) x = tf.placeholder(tf.float32, [None, INPUT_SIZE])",
"stopping prev_loss = 1e15 # Train for i in range(FLAGS.iters): # batch_xs, batch_ys",
"Every 1k iterations check accuracy if i % 100 == 0: print(\"After %d",
"Layer n(units) - Output(25) W.append(weight_variable([FLAGS.units, OUTPUT_SIZE])) b.append(bias_variable([OUTPUT_SIZE])) y = tf.matmul(ys[-1], W[-1]) + b[-1]",
"mpe accuracy: %f\" % (1. - float(np.sum(np.abs(valid_mpe_pred_pw - valid_pw)))/float(10*sushi_data.valid_data.shape[0])) # Print loss print",
"%f\" % (1. - float(np.sum(np.abs(test_mpe_pred_pw - test_pw)))/float(10*sushi_data.test_data.shape[0])) sys.exit() else: prev_loss = valid_loss if",
"loss') parser.add_argument('--iters', type=int, default=10000, help='Number of minibatch steps to do') FLAGS, unparsed =",
"[None, OUTPUT_SIZE]) yu = tf.unstack(tf.nn.sigmoid(y), axis=1) # Create AC # yleaves = [[ny,",
"sushi_data.valid_labels}) print \"Validation loss: %f\" % valid_loss # Print WMC print \"Train WMC:",
"accuracy: %f\" % (1. - float(np.sum(np.abs(mpe_pred_pw - train_pw)))/float(10*sushi_data.train_data.shape[0])) valid_mpe_pred_pw = to_pairwise_comp(valid_mpe_pred, 5) print",
"/ float(sushi_data.test_data.shape[0])) print(\"Percentage of individual labels in test that are right: %f\" %",
"sushi_data.train_labels}) mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p) for p in o]) for o in pred])",
"ny in yu]) cross_entropy = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=y_, logits=y)) loss = cross_entropy - FLAGS.wmc *",
"5) print \"Validation pairwise mpe accuracy: %f\" % (1. - float(np.sum(np.abs(valid_mpe_pred_pw - valid_pw)))/float(10*sushi_data.valid_data.shape[0]))",
"feed_dict={x: sushi_data.test_data, y_: sushi_data.test_labels}) test_mpe_pred = np.array([cmpe.compute_mpe_inst([(1-p, p) for p in o]) for",
"print \"Validation mpe accuracy: %f\" % (float(np.sum(np.equal(np.sum(np.abs(valid_mpe_pred - sushi_data.valid_labels), axis=1), 0))) / float(sushi_data.valid_data.shape[0]))",
"%d iterations\" % i) # Computing \"true\" accuracies correct_prediction = tf.equal(tf.reduce_sum(tf.abs(tf.to_int32(tf.nn.sigmoid(y)+0.5) - tf.to_int32(y_)),",
"for p in o]) for o in pred]) print \"Train mpe accuracy: %f\"",
"print train_pw # For early stopping prev_loss = 1e15 # Train for i",
"# For early stopping prev_loss = 1e15 # Train for i in range(FLAGS.iters):",
"% sess.run(tf.reduce_mean(wmc), feed_dict={x: sushi_data.train_data, y_: sushi_data.train_labels}) print \"Validation WMC: %f\" % sess.run(tf.reduce_mean(wmc), feed_dict={x:",
"(1. - np.sum(np.abs(np.array(test_pred + 0.5, int) - sushi_data.test_labels))/float(sushi_data.test_labels.shape[0] * sushi_data.test_labels.shape[1]))) test_mpe_pred_pw = to_pairwise_comp(test_mpe_pred,",
"batch_ys = sushi_data.get_batch(400) batch_xs, batch_ys = sushi_data.train_data, sushi_data.train_labels sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})",
"0.1)) def main(_): # Get data sushi_data = SushiData('sushi.soc') INPUT_SIZE = sushi_data.train_data.shape[1] OUTPUT_SIZE",
"import sys import numpy as np from sushi_data import SushiData, to_pairwise_comp from compute_mpe",
"- tf.to_int32(y_)), 1), 0) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print \"Train accuracy: %f\" %",
"%f\" % (1. - float(np.sum(np.abs(valid_mpe_pred_pw - valid_pw)))/float(10*sushi_data.valid_data.shape[0])) # Print loss print \"Train loss:",
"- float(np.sum(np.abs(test_mpe_pred_pw - test_pw)))/float(10*sushi_data.test_data.shape[0])) sys.exit() else: prev_loss = valid_loss if __name__ == '__main__':"
] |
[
"handler return decorator def role_or_self_check(): def decorator(func): @wraps(func) async def handler(request, *args, **kwargs):",
"*args, **kwargs): if (request.app.name not in request.args['auth_roles']): return json({\"message\":\"没有权限查看\"},401) else: return await func(request,",
"def role_or_self_check(): def decorator(func): @wraps(func) async def handler(request, *args, **kwargs): try: _id =",
"def decorator(func): @wraps(func) async def handler(request, *args, **kwargs): if (request.app.name not in request.args['auth_roles']):",
"in request.args['auth_roles']) or _id == request.args['auth_id']): return json({\"message\":\"没有权限查看\"},401) else: return await func(request, *args,",
"except: return json({\"message\":\"url中需要有`_id`\"},400) if not ((request.app.name in request.args['auth_roles']) or _id == request.args['auth_id']): return",
"async def handler(request, *args, **kwargs): try: _id = kwargs[\"_id\"] except: return json({\"message\":\"url中需要有`_id`\"},400) if",
"App.model import User def role_check(): def decorator(func): @wraps(func) async def handler(request, *args, **kwargs):",
"json({\"message\":\"url中需要有`_id`\"},400) if not ((request.app.name in request.args['auth_roles']) or _id == request.args['auth_id']): return json({\"message\":\"没有权限查看\"},401) else:",
"json({\"message\":\"没有权限查看\"},401) else: return await func(request, *args, **kwargs) return handler return decorator def role_or_self_check():",
"try: _id = kwargs[\"_id\"] except: return json({\"message\":\"url中需要有`_id`\"},400) if not ((request.app.name in request.args['auth_roles']) or",
"**kwargs): if (request.app.name not in request.args['auth_roles']): return json({\"message\":\"没有权限查看\"},401) else: return await func(request, *args,",
"User def role_check(): def decorator(func): @wraps(func) async def handler(request, *args, **kwargs): if (request.app.name",
"def handler(request, *args, **kwargs): try: _id = kwargs[\"_id\"] except: return json({\"message\":\"url中需要有`_id`\"},400) if not",
"else: return await func(request, *args, **kwargs) return handler return decorator def role_or_self_check(): def",
"role_or_self_check(): def decorator(func): @wraps(func) async def handler(request, *args, **kwargs): try: _id = kwargs[\"_id\"]",
"kwargs[\"_id\"] except: return json({\"message\":\"url中需要有`_id`\"},400) if not ((request.app.name in request.args['auth_roles']) or _id == request.args['auth_id']):",
"await func(request, *args, **kwargs) return handler return decorator def role_or_self_check(): def decorator(func): @wraps(func)",
"json from App.model import User def role_check(): def decorator(func): @wraps(func) async def handler(request,",
"handler(request, *args, **kwargs): if (request.app.name not in request.args['auth_roles']): return json({\"message\":\"没有权限查看\"},401) else: return await",
"from sanic.response import json from App.model import User def role_check(): def decorator(func): @wraps(func)",
"func(request, *args, **kwargs) return handler return decorator def role_or_self_check(): def decorator(func): @wraps(func) async",
"if not ((request.app.name in request.args['auth_roles']) or _id == request.args['auth_id']): return json({\"message\":\"没有权限查看\"},401) else: return",
"request.args['auth_roles']) or _id == request.args['auth_id']): return json({\"message\":\"没有权限查看\"},401) else: return await func(request, *args, **kwargs)",
"_id == request.args['auth_id']): return json({\"message\":\"没有权限查看\"},401) else: return await func(request, *args, **kwargs) return handler",
"functools import wraps from sanic.response import json from App.model import User def role_check():",
"def decorator(func): @wraps(func) async def handler(request, *args, **kwargs): try: _id = kwargs[\"_id\"] except:",
"@wraps(func) async def handler(request, *args, **kwargs): try: _id = kwargs[\"_id\"] except: return json({\"message\":\"url中需要有`_id`\"},400)",
"**kwargs): try: _id = kwargs[\"_id\"] except: return json({\"message\":\"url中需要有`_id`\"},400) if not ((request.app.name in request.args['auth_roles'])",
"return await func(request, *args, **kwargs) return handler return decorator def role_or_self_check(): def decorator(func):",
"decorator(func): @wraps(func) async def handler(request, *args, **kwargs): if (request.app.name not in request.args['auth_roles']): return",
"<gh_stars>1-10 from functools import wraps from sanic.response import json from App.model import User",
"from functools import wraps from sanic.response import json from App.model import User def",
"return decorator def role_or_self_check(): def decorator(func): @wraps(func) async def handler(request, *args, **kwargs): try:",
"*args, **kwargs): try: _id = kwargs[\"_id\"] except: return json({\"message\":\"url中需要有`_id`\"},400) if not ((request.app.name in",
"@wraps(func) async def handler(request, *args, **kwargs): if (request.app.name not in request.args['auth_roles']): return json({\"message\":\"没有权限查看\"},401)",
"async def handler(request, *args, **kwargs): if (request.app.name not in request.args['auth_roles']): return json({\"message\":\"没有权限查看\"},401) else:",
"return json({\"message\":\"url中需要有`_id`\"},400) if not ((request.app.name in request.args['auth_roles']) or _id == request.args['auth_id']): return json({\"message\":\"没有权限查看\"},401)",
"_id = kwargs[\"_id\"] except: return json({\"message\":\"url中需要有`_id`\"},400) if not ((request.app.name in request.args['auth_roles']) or _id",
"== request.args['auth_id']): return json({\"message\":\"没有权限查看\"},401) else: return await func(request, *args, **kwargs) return handler return",
"*args, **kwargs) return handler return decorator def role_or_self_check(): def decorator(func): @wraps(func) async def",
"import wraps from sanic.response import json from App.model import User def role_check(): def",
"**kwargs) return handler return decorator def role_or_self_check(): def decorator(func): @wraps(func) async def handler(request,",
"import json from App.model import User def role_check(): def decorator(func): @wraps(func) async def",
"return handler return decorator def role_or_self_check(): def decorator(func): @wraps(func) async def handler(request, *args,",
"not in request.args['auth_roles']): return json({\"message\":\"没有权限查看\"},401) else: return await func(request, *args, **kwargs) return handler",
"decorator def role_or_self_check(): def decorator(func): @wraps(func) async def handler(request, *args, **kwargs): try: _id",
"decorator(func): @wraps(func) async def handler(request, *args, **kwargs): try: _id = kwargs[\"_id\"] except: return",
"return json({\"message\":\"没有权限查看\"},401) else: return await func(request, *args, **kwargs) return handler return decorator def",
"((request.app.name in request.args['auth_roles']) or _id == request.args['auth_id']): return json({\"message\":\"没有权限查看\"},401) else: return await func(request,",
"def handler(request, *args, **kwargs): if (request.app.name not in request.args['auth_roles']): return json({\"message\":\"没有权限查看\"},401) else: return",
"def role_check(): def decorator(func): @wraps(func) async def handler(request, *args, **kwargs): if (request.app.name not",
"from App.model import User def role_check(): def decorator(func): @wraps(func) async def handler(request, *args,",
"= kwargs[\"_id\"] except: return json({\"message\":\"url中需要有`_id`\"},400) if not ((request.app.name in request.args['auth_roles']) or _id ==",
"request.args['auth_id']): return json({\"message\":\"没有权限查看\"},401) else: return await func(request, *args, **kwargs) return handler return decorator",
"if (request.app.name not in request.args['auth_roles']): return json({\"message\":\"没有权限查看\"},401) else: return await func(request, *args, **kwargs)",
"import User def role_check(): def decorator(func): @wraps(func) async def handler(request, *args, **kwargs): if",
"or _id == request.args['auth_id']): return json({\"message\":\"没有权限查看\"},401) else: return await func(request, *args, **kwargs) return",
"handler(request, *args, **kwargs): try: _id = kwargs[\"_id\"] except: return json({\"message\":\"url中需要有`_id`\"},400) if not ((request.app.name",
"(request.app.name not in request.args['auth_roles']): return json({\"message\":\"没有权限查看\"},401) else: return await func(request, *args, **kwargs) return",
"in request.args['auth_roles']): return json({\"message\":\"没有权限查看\"},401) else: return await func(request, *args, **kwargs) return handler return",
"not ((request.app.name in request.args['auth_roles']) or _id == request.args['auth_id']): return json({\"message\":\"没有权限查看\"},401) else: return await",
"role_check(): def decorator(func): @wraps(func) async def handler(request, *args, **kwargs): if (request.app.name not in",
"wraps from sanic.response import json from App.model import User def role_check(): def decorator(func):",
"sanic.response import json from App.model import User def role_check(): def decorator(func): @wraps(func) async",
"request.args['auth_roles']): return json({\"message\":\"没有权限查看\"},401) else: return await func(request, *args, **kwargs) return handler return decorator"
] |
[
"x.dim() return zeros(*dim, batch_size=batch_size) def ones(*dim, batch_size: int = 1) -> Expression: a",
"device=moire.config.device) def diagonal(x: Expression) -> Expression: (dim0, dim1), batch_size = x.dim() return dy.cmult(x,",
"high: float, batch_size: int = 1) -> Expression: a = np.random.uniform(low=low, high=high, size=(*dim,",
"stddev: float = 1.0, batch_size: int = 1) -> Expression: a = np.random.normal(loc=mean,",
"-> Expression: a = np.random.normal(loc=mean, scale=stddev, size=(*dim, batch_size)).astype(np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def",
"import moire from moire import Expression __all__ = [ 'zeros', 'ones', 'full', 'normal',",
"size=(*dim, batch_size)).astype(np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def normal_like(x: Expression, mean: float = 0.0,",
"= dy.inputTensor([[1, 2, 3], [2, 3, 4], ]) moire.debug(f'a :: {a.dim()} => {a.value()}')",
"np.random.uniform(low=low, high=high, size=(*dim, batch_size)) return dy.inputTensor(a, batched=True, device=moire.config.device) def uniform_like(x: Expression, low: float,",
"= [ 'zeros', 'ones', 'full', 'normal', 'bernoulli', 'uniform', 'gumbel', 'zeros_like', 'ones_like', 'full_like', 'normal_like',",
"mean: float = 0.0, stddev: float = 1.0) -> Expression: dim, batch_size =",
"dtype=np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def zeros_like(x: Expression) -> Expression: dim, batch_size =",
"batched=True, device=moire.config.device) def uniform_like(x: Expression, low: float, high: float) -> Expression: dim, batch_size",
"-> Expression: dim, batch_size = x.dim() return ones(*dim, batch_size=batch_size) def eye(N: int, M:",
"'uniform', 'gumbel', 'zeros_like', 'ones_like', 'full_like', 'normal_like', 'bernoulli_like', 'uniform_like', 'gumbel_like', 'eye', 'diagonal', 'where', ]",
"high=high, size=(*dim, batch_size)) return dy.inputTensor(a, batched=True, device=moire.config.device) def uniform_like(x: Expression, low: float, high:",
"batch_size=batch_size) def eye(N: int, M: int = None, k: int = 0) ->",
"Expression: a = np.random.uniform(low=low, high=high, size=(*dim, batch_size)) return dy.inputTensor(a, batched=True, device=moire.config.device) def uniform_like(x:",
"zeros(*dim, batch_size=batch_size) def ones(*dim, batch_size: int = 1) -> Expression: a = np.ones((*dim,",
"moire import Expression __all__ = [ 'zeros', 'ones', 'full', 'normal', 'bernoulli', 'uniform', 'gumbel',",
"def normal_like(x: Expression, mean: float = 0.0, stddev: float = 1.0) -> Expression:",
"x.dim() return uniform(dim, low=low, high=high, batch_size=batch_size) def gumbel(*dim, mu: float = 0.0, beta:",
"def full_like(x: Expression, value) -> Expression: dim, batch_size = x.dim() return full(*dim, value=value,",
"gumbel(*dim, mu: float = 0.0, beta: float = 1.0, batch_size: int = 1)",
"dim, batch_size = x.dim() return normal(*dim, mean=mean, stddev=stddev, batch_size=batch_size) def bernoulli(*dim, p: float,",
"float = 0.0, stddev: float = 1.0) -> Expression: dim, batch_size = x.dim()",
"dy.inputTensor(a, batched=True, device=moire.config.device) def uniform_like(x: Expression, low: float, high: float) -> Expression: dim,",
"diagonal(x: Expression) -> Expression: (dim0, dim1), batch_size = x.dim() return dy.cmult(x, eye(dim0, dim1))",
"1.0, batch_size: int = 1) -> Expression: a = np.random.gumbel(loc=mu, scale=beta, size=(*dim, batch_size))",
"where(cond: Expression, x: Expression, y: Expression) -> Expression: return dy.cmult(cond, x) + dy.cmult(1.0",
"batch_size=batch_size) def where(cond: Expression, x: Expression, y: Expression) -> Expression: return dy.cmult(cond, x)",
"= 0.0, stddev: float = 1.0) -> Expression: dim, batch_size = x.dim() return",
"dy.inputTensor(a, batched=True, device=moire.config.device) def ones_like(x: Expression) -> Expression: dim, batch_size = x.dim() return",
"dim, batch_size = x.dim() return gumbel(*dim, mu=mu, beta=beta, batch_size=batch_size) def where(cond: Expression, x:",
"= x.dim() return normal(*dim, mean=mean, stddev=stddev, batch_size=batch_size) def bernoulli(*dim, p: float, batch_size: int",
"high=high, batch_size=batch_size) def gumbel(*dim, mu: float = 0.0, beta: float = 1.0, batch_size:",
"if __name__ == '__main__': a = dy.inputTensor([[1, 2, 3], [2, 3, 4], ])",
"= np.random.gumbel(loc=mu, scale=beta, size=(*dim, batch_size)) return dy.inputTensor(a, batched=True, device=moire.config.device) def gumbel_like(x: Expression, mu:",
"bernoulli(*dim, p: float, batch_size: int = 1) -> Expression: a = np.random.uniform(low=0, high=1.0,",
"int = None, k: int = 0) -> Expression: return dy.inputTensor(np.eye(N, M, k),",
"Expression, mean: float = 0.0, stddev: float = 1.0) -> Expression: dim, batch_size",
"1.0, batch_size: int = 1) -> Expression: a = np.random.normal(loc=mean, scale=stddev, size=(*dim, batch_size)).astype(np.float32)",
"def where(cond: Expression, x: Expression, y: Expression) -> Expression: return dy.cmult(cond, x) +",
"batch_size), dtype=np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def zeros_like(x: Expression) -> Expression: dim, batch_size",
"= x.dim() return bernoulli(*dim, p=p, batch_size=batch_size) def uniform(*dim, low: float, high: float, batch_size:",
"Expression: dim, batch_size = x.dim() return uniform(dim, low=low, high=high, batch_size=batch_size) def gumbel(*dim, mu:",
"Expression, p: float) -> Expression: dim, batch_size = x.dim() return bernoulli(*dim, p=p, batch_size=batch_size)",
"= np.ones((*dim, batch_size), dtype=np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def ones_like(x: Expression) -> Expression:",
"full(*dim, value=value, batch_size=batch_size) def normal(*dim, mean: float = 0.0, stddev: float = 1.0,",
"uniform(dim, low=low, high=high, batch_size=batch_size) def gumbel(*dim, mu: float = 0.0, beta: float =",
"moire.debug(f'a :: {a.dim()} => {a.value()}') b = diagonal(a) moire.debug(f'b :: {b.dim()} => {b.value()}')",
"-> Expression: return dy.cmult(cond, x) + dy.cmult(1.0 - cond, y) if __name__ ==",
"dim1)) def full(*dim, value, batch_size: int = 1) -> Expression: a = np.full((*dim,",
"dtype=np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def ones_like(x: Expression) -> Expression: dim, batch_size =",
"def diagonal(x: Expression) -> Expression: (dim0, dim1), batch_size = x.dim() return dy.cmult(x, eye(dim0,",
"dy.inputTensor(a, batched=True, device=moire.config.device) def full_like(x: Expression, value) -> Expression: dim, batch_size = x.dim()",
"dy.inputTensor(np.eye(N, M, k), batched=False, device=moire.config.device) def diagonal(x: Expression) -> Expression: (dim0, dim1), batch_size",
"Expression: dim, batch_size = x.dim() return bernoulli(*dim, p=p, batch_size=batch_size) def uniform(*dim, low: float,",
"x.dim() return dy.cmult(x, eye(dim0, dim1)) def full(*dim, value, batch_size: int = 1) ->",
"0.0, stddev: float = 1.0, batch_size: int = 1) -> Expression: a =",
"Expression) -> Expression: (dim0, dim1), batch_size = x.dim() return dy.cmult(x, eye(dim0, dim1)) def",
"batch_size: int = 1) -> Expression: a = np.full((*dim, batch_size), fill_value=value, dtype=np.float32) return",
"int = 1) -> Expression: a = np.random.gumbel(loc=mu, scale=beta, size=(*dim, batch_size)) return dy.inputTensor(a,",
"'full_like', 'normal_like', 'bernoulli_like', 'uniform_like', 'gumbel_like', 'eye', 'diagonal', 'where', ] def zeros(*dim, batch_size: int",
"np.ones((*dim, batch_size), dtype=np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def ones_like(x: Expression) -> Expression: dim,",
"'eye', 'diagonal', 'where', ] def zeros(*dim, batch_size: int = 1) -> Expression: a",
"batch_size), fill_value=value, dtype=np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def full_like(x: Expression, value) -> Expression:",
"batch_size)) < p return dy.inputTensor(a.astype(np.int32), batched=True, device=moire.config.device) def bernoulli_like(x: Expression, p: float) ->",
"batch_size = x.dim() return gumbel(*dim, mu=mu, beta=beta, batch_size=batch_size) def where(cond: Expression, x: Expression,",
"[2, 3, 4], ]) moire.debug(f'a :: {a.dim()} => {a.value()}') b = diagonal(a) moire.debug(f'b",
"float = 1.0) -> Expression: dim, batch_size = x.dim() return gumbel(*dim, mu=mu, beta=beta,",
"'zeros_like', 'ones_like', 'full_like', 'normal_like', 'bernoulli_like', 'uniform_like', 'gumbel_like', 'eye', 'diagonal', 'where', ] def zeros(*dim,",
"Expression __all__ = [ 'zeros', 'ones', 'full', 'normal', 'bernoulli', 'uniform', 'gumbel', 'zeros_like', 'ones_like',",
"batched=True, device=moire.config.device) def normal_like(x: Expression, mean: float = 0.0, stddev: float = 1.0)",
"batch_size: int = 1) -> Expression: a = np.random.uniform(low=low, high=high, size=(*dim, batch_size)) return",
"Expression: dim, batch_size = x.dim() return normal(*dim, mean=mean, stddev=stddev, batch_size=batch_size) def bernoulli(*dim, p:",
"Expression: dim, batch_size = x.dim() return ones(*dim, batch_size=batch_size) def eye(N: int, M: int",
"def uniform(*dim, low: float, high: float, batch_size: int = 1) -> Expression: a",
"'normal_like', 'bernoulli_like', 'uniform_like', 'gumbel_like', 'eye', 'diagonal', 'where', ] def zeros(*dim, batch_size: int =",
"value, batch_size: int = 1) -> Expression: a = np.full((*dim, batch_size), fill_value=value, dtype=np.float32)",
"dim1), batch_size = x.dim() return dy.cmult(x, eye(dim0, dim1)) def full(*dim, value, batch_size: int",
"1) -> Expression: a = np.random.uniform(low=low, high=high, size=(*dim, batch_size)) return dy.inputTensor(a, batched=True, device=moire.config.device)",
"np.zeros((*dim, batch_size), dtype=np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def zeros_like(x: Expression) -> Expression: dim,",
"batched=True, device=moire.config.device) def zeros_like(x: Expression) -> Expression: dim, batch_size = x.dim() return zeros(*dim,",
"'bernoulli', 'uniform', 'gumbel', 'zeros_like', 'ones_like', 'full_like', 'normal_like', 'bernoulli_like', 'uniform_like', 'gumbel_like', 'eye', 'diagonal', 'where',",
"int = 1) -> Expression: a = np.ones((*dim, batch_size), dtype=np.float32) return dy.inputTensor(a, batched=True,",
"= 0.0, beta: float = 1.0) -> Expression: dim, batch_size = x.dim() return",
"-> Expression: dim, batch_size = x.dim() return zeros(*dim, batch_size=batch_size) def ones(*dim, batch_size: int",
"'where', ] def zeros(*dim, batch_size: int = 1) -> Expression: a = np.zeros((*dim,",
"def zeros(*dim, batch_size: int = 1) -> Expression: a = np.zeros((*dim, batch_size), dtype=np.float32)",
"= 1.0) -> Expression: dim, batch_size = x.dim() return gumbel(*dim, mu=mu, beta=beta, batch_size=batch_size)",
"p: float, batch_size: int = 1) -> Expression: a = np.random.uniform(low=0, high=1.0, size=(*dim,",
"float) -> Expression: dim, batch_size = x.dim() return bernoulli(*dim, p=p, batch_size=batch_size) def uniform(*dim,",
"device=moire.config.device) def zeros_like(x: Expression) -> Expression: dim, batch_size = x.dim() return zeros(*dim, batch_size=batch_size)",
"'ones', 'full', 'normal', 'bernoulli', 'uniform', 'gumbel', 'zeros_like', 'ones_like', 'full_like', 'normal_like', 'bernoulli_like', 'uniform_like', 'gumbel_like',",
"= 1) -> Expression: a = np.random.normal(loc=mean, scale=stddev, size=(*dim, batch_size)).astype(np.float32) return dy.inputTensor(a, batched=True,",
"batch_size=batch_size) def uniform(*dim, low: float, high: float, batch_size: int = 1) -> Expression:",
"batch_size: int = 1) -> Expression: a = np.zeros((*dim, batch_size), dtype=np.float32) return dy.inputTensor(a,",
"float, batch_size: int = 1) -> Expression: a = np.random.uniform(low=low, high=high, size=(*dim, batch_size))",
"= np.random.normal(loc=mean, scale=stddev, size=(*dim, batch_size)).astype(np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def normal_like(x: Expression, mean:",
"mean=mean, stddev=stddev, batch_size=batch_size) def bernoulli(*dim, p: float, batch_size: int = 1) -> Expression:",
"1) -> Expression: a = np.zeros((*dim, batch_size), dtype=np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def",
"dim, batch_size = x.dim() return ones(*dim, batch_size=batch_size) def eye(N: int, M: int =",
"Expression) -> Expression: dim, batch_size = x.dim() return zeros(*dim, batch_size=batch_size) def ones(*dim, batch_size:",
"mean: float = 0.0, stddev: float = 1.0, batch_size: int = 1) ->",
"return dy.cmult(cond, x) + dy.cmult(1.0 - cond, y) if __name__ == '__main__': a",
"-> Expression: dim, batch_size = x.dim() return bernoulli(*dim, p=p, batch_size=batch_size) def uniform(*dim, low:",
"2, 3], [2, 3, 4], ]) moire.debug(f'a :: {a.dim()} => {a.value()}') b =",
"= 0) -> Expression: return dy.inputTensor(np.eye(N, M, k), batched=False, device=moire.config.device) def diagonal(x: Expression)",
"size=(*dim, batch_size)) return dy.inputTensor(a, batched=True, device=moire.config.device) def gumbel_like(x: Expression, mu: float = 0.0,",
"= 1) -> Expression: a = np.random.uniform(low=low, high=high, size=(*dim, batch_size)) return dy.inputTensor(a, batched=True,",
"return dy.inputTensor(a, batched=True, device=moire.config.device) def full_like(x: Expression, value) -> Expression: dim, batch_size =",
"batch_size: int = 1) -> Expression: a = np.random.gumbel(loc=mu, scale=beta, size=(*dim, batch_size)) return",
"return dy.inputTensor(a, batched=True, device=moire.config.device) def ones_like(x: Expression) -> Expression: dim, batch_size = x.dim()",
"normal(*dim, mean=mean, stddev=stddev, batch_size=batch_size) def bernoulli(*dim, p: float, batch_size: int = 1) ->",
"float) -> Expression: dim, batch_size = x.dim() return uniform(dim, low=low, high=high, batch_size=batch_size) def",
"= 1.0, batch_size: int = 1) -> Expression: a = np.random.gumbel(loc=mu, scale=beta, size=(*dim,",
"float = 1.0, batch_size: int = 1) -> Expression: a = np.random.gumbel(loc=mu, scale=beta,",
"low: float, high: float, batch_size: int = 1) -> Expression: a = np.random.uniform(low=low,",
"x.dim() return full(*dim, value=value, batch_size=batch_size) def normal(*dim, mean: float = 0.0, stddev: float",
"normal(*dim, mean: float = 0.0, stddev: float = 1.0, batch_size: int = 1)",
"np.random.uniform(low=0, high=1.0, size=(*dim, batch_size)) < p return dy.inputTensor(a.astype(np.int32), batched=True, device=moire.config.device) def bernoulli_like(x: Expression,",
"p: float) -> Expression: dim, batch_size = x.dim() return bernoulli(*dim, p=p, batch_size=batch_size) def",
"zeros(*dim, batch_size: int = 1) -> Expression: a = np.zeros((*dim, batch_size), dtype=np.float32) return",
"import numpy as np import moire from moire import Expression __all__ = [",
"] def zeros(*dim, batch_size: int = 1) -> Expression: a = np.zeros((*dim, batch_size),",
"-> Expression: return dy.inputTensor(np.eye(N, M, k), batched=False, device=moire.config.device) def diagonal(x: Expression) -> Expression:",
"]) moire.debug(f'a :: {a.dim()} => {a.value()}') b = diagonal(a) moire.debug(f'b :: {b.dim()} =>",
"np.random.normal(loc=mean, scale=stddev, size=(*dim, batch_size)).astype(np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def normal_like(x: Expression, mean: float",
"Expression: a = np.random.gumbel(loc=mu, scale=beta, size=(*dim, batch_size)) return dy.inputTensor(a, batched=True, device=moire.config.device) def gumbel_like(x:",
"Expression: dim, batch_size = x.dim() return zeros(*dim, batch_size=batch_size) def ones(*dim, batch_size: int =",
"-> Expression: dim, batch_size = x.dim() return full(*dim, value=value, batch_size=batch_size) def normal(*dim, mean:",
"float, batch_size: int = 1) -> Expression: a = np.random.uniform(low=0, high=1.0, size=(*dim, batch_size))",
"[ 'zeros', 'ones', 'full', 'normal', 'bernoulli', 'uniform', 'gumbel', 'zeros_like', 'ones_like', 'full_like', 'normal_like', 'bernoulli_like',",
"Expression: a = np.full((*dim, batch_size), fill_value=value, dtype=np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def full_like(x:",
"return dy.inputTensor(a, batched=True, device=moire.config.device) def uniform_like(x: Expression, low: float, high: float) -> Expression:",
"dy import numpy as np import moire from moire import Expression __all__ =",
"batch_size = x.dim() return bernoulli(*dim, p=p, batch_size=batch_size) def uniform(*dim, low: float, high: float,",
"- cond, y) if __name__ == '__main__': a = dy.inputTensor([[1, 2, 3], [2,",
"Expression: (dim0, dim1), batch_size = x.dim() return dy.cmult(x, eye(dim0, dim1)) def full(*dim, value,",
"= 1) -> Expression: a = np.zeros((*dim, batch_size), dtype=np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device)",
"fill_value=value, dtype=np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def full_like(x: Expression, value) -> Expression: dim,",
"= np.random.uniform(low=low, high=high, size=(*dim, batch_size)) return dy.inputTensor(a, batched=True, device=moire.config.device) def uniform_like(x: Expression, low:",
"+ dy.cmult(1.0 - cond, y) if __name__ == '__main__': a = dy.inputTensor([[1, 2,",
"__name__ == '__main__': a = dy.inputTensor([[1, 2, 3], [2, 3, 4], ]) moire.debug(f'a",
"dy.cmult(cond, x) + dy.cmult(1.0 - cond, y) if __name__ == '__main__': a =",
"a = np.random.normal(loc=mean, scale=stddev, size=(*dim, batch_size)).astype(np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def normal_like(x: Expression,",
"cond, y) if __name__ == '__main__': a = dy.inputTensor([[1, 2, 3], [2, 3,",
"a = dy.inputTensor([[1, 2, 3], [2, 3, 4], ]) moire.debug(f'a :: {a.dim()} =>",
"float = 0.0, beta: float = 1.0) -> Expression: dim, batch_size = x.dim()",
"Expression, mu: float = 0.0, beta: float = 1.0) -> Expression: dim, batch_size",
"1) -> Expression: a = np.random.normal(loc=mean, scale=stddev, size=(*dim, batch_size)).astype(np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device)",
"int = 1) -> Expression: a = np.full((*dim, batch_size), fill_value=value, dtype=np.float32) return dy.inputTensor(a,",
"Expression: a = np.zeros((*dim, batch_size), dtype=np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def zeros_like(x: Expression)",
"float = 1.0, batch_size: int = 1) -> Expression: a = np.random.normal(loc=mean, scale=stddev,",
"float = 1.0) -> Expression: dim, batch_size = x.dim() return normal(*dim, mean=mean, stddev=stddev,",
"import Expression __all__ = [ 'zeros', 'ones', 'full', 'normal', 'bernoulli', 'uniform', 'gumbel', 'zeros_like',",
"= 1.0, batch_size: int = 1) -> Expression: a = np.random.normal(loc=mean, scale=stddev, size=(*dim,",
"int = 1) -> Expression: a = np.random.uniform(low=0, high=1.0, size=(*dim, batch_size)) < p",
"dynet as dy import numpy as np import moire from moire import Expression",
"batch_size = x.dim() return full(*dim, value=value, batch_size=batch_size) def normal(*dim, mean: float = 0.0,",
"0) -> Expression: return dy.inputTensor(np.eye(N, M, k), batched=False, device=moire.config.device) def diagonal(x: Expression) ->",
"int = 1) -> Expression: a = np.zeros((*dim, batch_size), dtype=np.float32) return dy.inputTensor(a, batched=True,",
"bernoulli_like(x: Expression, p: float) -> Expression: dim, batch_size = x.dim() return bernoulli(*dim, p=p,",
"return normal(*dim, mean=mean, stddev=stddev, batch_size=batch_size) def bernoulli(*dim, p: float, batch_size: int = 1)",
"eye(N: int, M: int = None, k: int = 0) -> Expression: return",
"return zeros(*dim, batch_size=batch_size) def ones(*dim, batch_size: int = 1) -> Expression: a =",
"Expression: return dy.inputTensor(np.eye(N, M, k), batched=False, device=moire.config.device) def diagonal(x: Expression) -> Expression: (dim0,",
"Expression, y: Expression) -> Expression: return dy.cmult(cond, x) + dy.cmult(1.0 - cond, y)",
"batch_size = x.dim() return ones(*dim, batch_size=batch_size) def eye(N: int, M: int = None,",
"'diagonal', 'where', ] def zeros(*dim, batch_size: int = 1) -> Expression: a =",
"None, k: int = 0) -> Expression: return dy.inputTensor(np.eye(N, M, k), batched=False, device=moire.config.device)",
"batched=True, device=moire.config.device) def ones_like(x: Expression) -> Expression: dim, batch_size = x.dim() return ones(*dim,",
"np.full((*dim, batch_size), fill_value=value, dtype=np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def full_like(x: Expression, value) ->",
"numpy as np import moire from moire import Expression __all__ = [ 'zeros',",
"value=value, batch_size=batch_size) def normal(*dim, mean: float = 0.0, stddev: float = 1.0, batch_size:",
"x.dim() return bernoulli(*dim, p=p, batch_size=batch_size) def uniform(*dim, low: float, high: float, batch_size: int",
"dy.inputTensor(a, batched=True, device=moire.config.device) def gumbel_like(x: Expression, mu: float = 0.0, beta: float =",
"x.dim() return normal(*dim, mean=mean, stddev=stddev, batch_size=batch_size) def bernoulli(*dim, p: float, batch_size: int =",
"bernoulli(*dim, p=p, batch_size=batch_size) def uniform(*dim, low: float, high: float, batch_size: int = 1)",
"= 1.0) -> Expression: dim, batch_size = x.dim() return normal(*dim, mean=mean, stddev=stddev, batch_size=batch_size)",
"scale=stddev, size=(*dim, batch_size)).astype(np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def normal_like(x: Expression, mean: float =",
"def bernoulli_like(x: Expression, p: float) -> Expression: dim, batch_size = x.dim() return bernoulli(*dim,",
"low: float, high: float) -> Expression: dim, batch_size = x.dim() return uniform(dim, low=low,",
"def ones(*dim, batch_size: int = 1) -> Expression: a = np.ones((*dim, batch_size), dtype=np.float32)",
"return full(*dim, value=value, batch_size=batch_size) def normal(*dim, mean: float = 0.0, stddev: float =",
"batch_size)) return dy.inputTensor(a, batched=True, device=moire.config.device) def gumbel_like(x: Expression, mu: float = 0.0, beta:",
"device=moire.config.device) def gumbel_like(x: Expression, mu: float = 0.0, beta: float = 1.0) ->",
"-> Expression: a = np.full((*dim, batch_size), fill_value=value, dtype=np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def",
"= None, k: int = 0) -> Expression: return dy.inputTensor(np.eye(N, M, k), batched=False,",
"device=moire.config.device) def uniform_like(x: Expression, low: float, high: float) -> Expression: dim, batch_size =",
"dy.inputTensor(a, batched=True, device=moire.config.device) def zeros_like(x: Expression) -> Expression: dim, batch_size = x.dim() return",
"= np.full((*dim, batch_size), fill_value=value, dtype=np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def full_like(x: Expression, value)",
"-> Expression: a = np.ones((*dim, batch_size), dtype=np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def ones_like(x:",
"4], ]) moire.debug(f'a :: {a.dim()} => {a.value()}') b = diagonal(a) moire.debug(f'b :: {b.dim()}",
"a = np.full((*dim, batch_size), fill_value=value, dtype=np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def full_like(x: Expression,",
"np import moire from moire import Expression __all__ = [ 'zeros', 'ones', 'full',",
"def ones_like(x: Expression) -> Expression: dim, batch_size = x.dim() return ones(*dim, batch_size=batch_size) def",
"full_like(x: Expression, value) -> Expression: dim, batch_size = x.dim() return full(*dim, value=value, batch_size=batch_size)",
"= 0.0, stddev: float = 1.0, batch_size: int = 1) -> Expression: a",
"Expression: a = np.random.uniform(low=0, high=1.0, size=(*dim, batch_size)) < p return dy.inputTensor(a.astype(np.int32), batched=True, device=moire.config.device)",
"batched=True, device=moire.config.device) def full_like(x: Expression, value) -> Expression: dim, batch_size = x.dim() return",
"= x.dim() return full(*dim, value=value, batch_size=batch_size) def normal(*dim, mean: float = 0.0, stddev:",
"1.0) -> Expression: dim, batch_size = x.dim() return normal(*dim, mean=mean, stddev=stddev, batch_size=batch_size) def",
"Expression, low: float, high: float) -> Expression: dim, batch_size = x.dim() return uniform(dim,",
"< p return dy.inputTensor(a.astype(np.int32), batched=True, device=moire.config.device) def bernoulli_like(x: Expression, p: float) -> Expression:",
"1) -> Expression: a = np.random.uniform(low=0, high=1.0, size=(*dim, batch_size)) < p return dy.inputTensor(a.astype(np.int32),",
"def bernoulli(*dim, p: float, batch_size: int = 1) -> Expression: a = np.random.uniform(low=0,",
"zeros_like(x: Expression) -> Expression: dim, batch_size = x.dim() return zeros(*dim, batch_size=batch_size) def ones(*dim,",
"return dy.cmult(x, eye(dim0, dim1)) def full(*dim, value, batch_size: int = 1) -> Expression:",
"x: Expression, y: Expression) -> Expression: return dy.cmult(cond, x) + dy.cmult(1.0 - cond,",
"batch_size=batch_size) def normal(*dim, mean: float = 0.0, stddev: float = 1.0, batch_size: int",
"-> Expression: dim, batch_size = x.dim() return gumbel(*dim, mu=mu, beta=beta, batch_size=batch_size) def where(cond:",
"x.dim() return gumbel(*dim, mu=mu, beta=beta, batch_size=batch_size) def where(cond: Expression, x: Expression, y: Expression)",
"return dy.inputTensor(np.eye(N, M, k), batched=False, device=moire.config.device) def diagonal(x: Expression) -> Expression: (dim0, dim1),",
"stddev: float = 1.0) -> Expression: dim, batch_size = x.dim() return normal(*dim, mean=mean,",
"x.dim() return ones(*dim, batch_size=batch_size) def eye(N: int, M: int = None, k: int",
"moire from moire import Expression __all__ = [ 'zeros', 'ones', 'full', 'normal', 'bernoulli',",
"batch_size)).astype(np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def normal_like(x: Expression, mean: float = 0.0, stddev:",
"0.0, beta: float = 1.0) -> Expression: dim, batch_size = x.dim() return gumbel(*dim,",
"batched=True, device=moire.config.device) def bernoulli_like(x: Expression, p: float) -> Expression: dim, batch_size = x.dim()",
"M, k), batched=False, device=moire.config.device) def diagonal(x: Expression) -> Expression: (dim0, dim1), batch_size =",
"device=moire.config.device) def ones_like(x: Expression) -> Expression: dim, batch_size = x.dim() return ones(*dim, batch_size=batch_size)",
"'zeros', 'ones', 'full', 'normal', 'bernoulli', 'uniform', 'gumbel', 'zeros_like', 'ones_like', 'full_like', 'normal_like', 'bernoulli_like', 'uniform_like',",
"= 1) -> Expression: a = np.full((*dim, batch_size), fill_value=value, dtype=np.float32) return dy.inputTensor(a, batched=True,",
"int = 1) -> Expression: a = np.random.normal(loc=mean, scale=stddev, size=(*dim, batch_size)).astype(np.float32) return dy.inputTensor(a,",
"ones_like(x: Expression) -> Expression: dim, batch_size = x.dim() return ones(*dim, batch_size=batch_size) def eye(N:",
"-> Expression: a = np.random.uniform(low=0, high=1.0, size=(*dim, batch_size)) < p return dy.inputTensor(a.astype(np.int32), batched=True,",
"return bernoulli(*dim, p=p, batch_size=batch_size) def uniform(*dim, low: float, high: float, batch_size: int =",
"batch_size: int = 1) -> Expression: a = np.random.normal(loc=mean, scale=stddev, size=(*dim, batch_size)).astype(np.float32) return",
"def gumbel(*dim, mu: float = 0.0, beta: float = 1.0, batch_size: int =",
"float = 0.0, beta: float = 1.0, batch_size: int = 1) -> Expression:",
"'bernoulli_like', 'uniform_like', 'gumbel_like', 'eye', 'diagonal', 'where', ] def zeros(*dim, batch_size: int = 1)",
"1) -> Expression: a = np.full((*dim, batch_size), fill_value=value, dtype=np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device)",
"batch_size = x.dim() return dy.cmult(x, eye(dim0, dim1)) def full(*dim, value, batch_size: int =",
"'gumbel_like', 'eye', 'diagonal', 'where', ] def zeros(*dim, batch_size: int = 1) -> Expression:",
"dy.inputTensor(a, batched=True, device=moire.config.device) def normal_like(x: Expression, mean: float = 0.0, stddev: float =",
"= np.random.uniform(low=0, high=1.0, size=(*dim, batch_size)) < p return dy.inputTensor(a.astype(np.int32), batched=True, device=moire.config.device) def bernoulli_like(x:",
"= x.dim() return gumbel(*dim, mu=mu, beta=beta, batch_size=batch_size) def where(cond: Expression, x: Expression, y:",
"Expression) -> Expression: return dy.cmult(cond, x) + dy.cmult(1.0 - cond, y) if __name__",
"k: int = 0) -> Expression: return dy.inputTensor(np.eye(N, M, k), batched=False, device=moire.config.device) def",
"high: float) -> Expression: dim, batch_size = x.dim() return uniform(dim, low=low, high=high, batch_size=batch_size)",
"x) + dy.cmult(1.0 - cond, y) if __name__ == '__main__': a = dy.inputTensor([[1,",
"p=p, batch_size=batch_size) def uniform(*dim, low: float, high: float, batch_size: int = 1) ->",
"= np.zeros((*dim, batch_size), dtype=np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def zeros_like(x: Expression) -> Expression:",
"Expression, x: Expression, y: Expression) -> Expression: return dy.cmult(cond, x) + dy.cmult(1.0 -",
"import dynet as dy import numpy as np import moire from moire import",
"= 1) -> Expression: a = np.ones((*dim, batch_size), dtype=np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device)",
"beta: float = 1.0) -> Expression: dim, batch_size = x.dim() return gumbel(*dim, mu=mu,",
"Expression: dim, batch_size = x.dim() return full(*dim, value=value, batch_size=batch_size) def normal(*dim, mean: float",
"np.random.gumbel(loc=mu, scale=beta, size=(*dim, batch_size)) return dy.inputTensor(a, batched=True, device=moire.config.device) def gumbel_like(x: Expression, mu: float",
"Expression: dim, batch_size = x.dim() return gumbel(*dim, mu=mu, beta=beta, batch_size=batch_size) def where(cond: Expression,",
"size=(*dim, batch_size)) < p return dy.inputTensor(a.astype(np.int32), batched=True, device=moire.config.device) def bernoulli_like(x: Expression, p: float)",
"p return dy.inputTensor(a.astype(np.int32), batched=True, device=moire.config.device) def bernoulli_like(x: Expression, p: float) -> Expression: dim,",
"return dy.inputTensor(a, batched=True, device=moire.config.device) def zeros_like(x: Expression) -> Expression: dim, batch_size = x.dim()",
"dtype=np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def full_like(x: Expression, value) -> Expression: dim, batch_size",
"scale=beta, size=(*dim, batch_size)) return dy.inputTensor(a, batched=True, device=moire.config.device) def gumbel_like(x: Expression, mu: float =",
"batch_size=batch_size) def bernoulli(*dim, p: float, batch_size: int = 1) -> Expression: a =",
"= x.dim() return dy.cmult(x, eye(dim0, dim1)) def full(*dim, value, batch_size: int = 1)",
"'full', 'normal', 'bernoulli', 'uniform', 'gumbel', 'zeros_like', 'ones_like', 'full_like', 'normal_like', 'bernoulli_like', 'uniform_like', 'gumbel_like', 'eye',",
"dy.cmult(x, eye(dim0, dim1)) def full(*dim, value, batch_size: int = 1) -> Expression: a",
"a = np.ones((*dim, batch_size), dtype=np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def ones_like(x: Expression) ->",
"batched=True, device=moire.config.device) def gumbel_like(x: Expression, mu: float = 0.0, beta: float = 1.0)",
"mu: float = 0.0, beta: float = 1.0, batch_size: int = 1) ->",
"beta: float = 1.0, batch_size: int = 1) -> Expression: a = np.random.gumbel(loc=mu,",
"size=(*dim, batch_size)) return dy.inputTensor(a, batched=True, device=moire.config.device) def uniform_like(x: Expression, low: float, high: float)",
"3], [2, 3, 4], ]) moire.debug(f'a :: {a.dim()} => {a.value()}') b = diagonal(a)",
"eye(dim0, dim1)) def full(*dim, value, batch_size: int = 1) -> Expression: a =",
"Expression: a = np.ones((*dim, batch_size), dtype=np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def ones_like(x: Expression)",
"ones(*dim, batch_size: int = 1) -> Expression: a = np.ones((*dim, batch_size), dtype=np.float32) return",
"dim, batch_size = x.dim() return uniform(dim, low=low, high=high, batch_size=batch_size) def gumbel(*dim, mu: float",
"-> Expression: a = np.random.gumbel(loc=mu, scale=beta, size=(*dim, batch_size)) return dy.inputTensor(a, batched=True, device=moire.config.device) def",
"batched=False, device=moire.config.device) def diagonal(x: Expression) -> Expression: (dim0, dim1), batch_size = x.dim() return",
"batch_size=batch_size) def ones(*dim, batch_size: int = 1) -> Expression: a = np.ones((*dim, batch_size),",
"batch_size: int = 1) -> Expression: a = np.ones((*dim, batch_size), dtype=np.float32) return dy.inputTensor(a,",
"a = np.random.uniform(low=low, high=high, size=(*dim, batch_size)) return dy.inputTensor(a, batched=True, device=moire.config.device) def uniform_like(x: Expression,",
"1) -> Expression: a = np.ones((*dim, batch_size), dtype=np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def",
"def normal(*dim, mean: float = 0.0, stddev: float = 1.0, batch_size: int =",
"as np import moire from moire import Expression __all__ = [ 'zeros', 'ones',",
"1) -> Expression: a = np.random.gumbel(loc=mu, scale=beta, size=(*dim, batch_size)) return dy.inputTensor(a, batched=True, device=moire.config.device)",
"batch_size = x.dim() return uniform(dim, low=low, high=high, batch_size=batch_size) def gumbel(*dim, mu: float =",
"__all__ = [ 'zeros', 'ones', 'full', 'normal', 'bernoulli', 'uniform', 'gumbel', 'zeros_like', 'ones_like', 'full_like',",
"device=moire.config.device) def normal_like(x: Expression, mean: float = 0.0, stddev: float = 1.0) ->",
"y) if __name__ == '__main__': a = dy.inputTensor([[1, 2, 3], [2, 3, 4],",
"return ones(*dim, batch_size=batch_size) def eye(N: int, M: int = None, k: int =",
"gumbel_like(x: Expression, mu: float = 0.0, beta: float = 1.0) -> Expression: dim,",
"dy.inputTensor(a.astype(np.int32), batched=True, device=moire.config.device) def bernoulli_like(x: Expression, p: float) -> Expression: dim, batch_size =",
"int = 0) -> Expression: return dy.inputTensor(np.eye(N, M, k), batched=False, device=moire.config.device) def diagonal(x:",
"a = np.random.uniform(low=0, high=1.0, size=(*dim, batch_size)) < p return dy.inputTensor(a.astype(np.int32), batched=True, device=moire.config.device) def",
"= x.dim() return zeros(*dim, batch_size=batch_size) def ones(*dim, batch_size: int = 1) -> Expression:",
"int = 1) -> Expression: a = np.random.uniform(low=low, high=high, size=(*dim, batch_size)) return dy.inputTensor(a,",
"high=1.0, size=(*dim, batch_size)) < p return dy.inputTensor(a.astype(np.int32), batched=True, device=moire.config.device) def bernoulli_like(x: Expression, p:",
"batch_size = x.dim() return normal(*dim, mean=mean, stddev=stddev, batch_size=batch_size) def bernoulli(*dim, p: float, batch_size:",
"value) -> Expression: dim, batch_size = x.dim() return full(*dim, value=value, batch_size=batch_size) def normal(*dim,",
"def full(*dim, value, batch_size: int = 1) -> Expression: a = np.full((*dim, batch_size),",
"batch_size)) return dy.inputTensor(a, batched=True, device=moire.config.device) def uniform_like(x: Expression, low: float, high: float) ->",
"def uniform_like(x: Expression, low: float, high: float) -> Expression: dim, batch_size = x.dim()",
"return dy.inputTensor(a, batched=True, device=moire.config.device) def normal_like(x: Expression, mean: float = 0.0, stddev: float",
"= x.dim() return uniform(dim, low=low, high=high, batch_size=batch_size) def gumbel(*dim, mu: float = 0.0,",
"= 1) -> Expression: a = np.random.uniform(low=0, high=1.0, size=(*dim, batch_size)) < p return",
"dim, batch_size = x.dim() return zeros(*dim, batch_size=batch_size) def ones(*dim, batch_size: int = 1)",
"device=moire.config.device) def bernoulli_like(x: Expression, p: float) -> Expression: dim, batch_size = x.dim() return",
"(dim0, dim1), batch_size = x.dim() return dy.cmult(x, eye(dim0, dim1)) def full(*dim, value, batch_size:",
"uniform(*dim, low: float, high: float, batch_size: int = 1) -> Expression: a =",
"ones(*dim, batch_size=batch_size) def eye(N: int, M: int = None, k: int = 0)",
"-> Expression: dim, batch_size = x.dim() return uniform(dim, low=low, high=high, batch_size=batch_size) def gumbel(*dim,",
"Expression: a = np.random.normal(loc=mean, scale=stddev, size=(*dim, batch_size)).astype(np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def normal_like(x:",
"k), batched=False, device=moire.config.device) def diagonal(x: Expression) -> Expression: (dim0, dim1), batch_size = x.dim()",
"dy.cmult(1.0 - cond, y) if __name__ == '__main__': a = dy.inputTensor([[1, 2, 3],",
"mu: float = 0.0, beta: float = 1.0) -> Expression: dim, batch_size =",
"dim, batch_size = x.dim() return full(*dim, value=value, batch_size=batch_size) def normal(*dim, mean: float =",
"3, 4], ]) moire.debug(f'a :: {a.dim()} => {a.value()}') b = diagonal(a) moire.debug(f'b ::",
"= 1) -> Expression: a = np.random.gumbel(loc=mu, scale=beta, size=(*dim, batch_size)) return dy.inputTensor(a, batched=True,",
"dy.inputTensor([[1, 2, 3], [2, 3, 4], ]) moire.debug(f'a :: {a.dim()} => {a.value()}') b",
"a = np.zeros((*dim, batch_size), dtype=np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def zeros_like(x: Expression) ->",
"batch_size: int = 1) -> Expression: a = np.random.uniform(low=0, high=1.0, size=(*dim, batch_size)) <",
"= x.dim() return ones(*dim, batch_size=batch_size) def eye(N: int, M: int = None, k:",
"float, high: float, batch_size: int = 1) -> Expression: a = np.random.uniform(low=low, high=high,",
"y: Expression) -> Expression: return dy.cmult(cond, x) + dy.cmult(1.0 - cond, y) if",
"'normal', 'bernoulli', 'uniform', 'gumbel', 'zeros_like', 'ones_like', 'full_like', 'normal_like', 'bernoulli_like', 'uniform_like', 'gumbel_like', 'eye', 'diagonal',",
"return dy.inputTensor(a, batched=True, device=moire.config.device) def gumbel_like(x: Expression, mu: float = 0.0, beta: float",
"-> Expression: (dim0, dim1), batch_size = x.dim() return dy.cmult(x, eye(dim0, dim1)) def full(*dim,",
"-> Expression: a = np.random.uniform(low=low, high=high, size=(*dim, batch_size)) return dy.inputTensor(a, batched=True, device=moire.config.device) def",
"beta=beta, batch_size=batch_size) def where(cond: Expression, x: Expression, y: Expression) -> Expression: return dy.cmult(cond,",
"stddev=stddev, batch_size=batch_size) def bernoulli(*dim, p: float, batch_size: int = 1) -> Expression: a",
"== '__main__': a = dy.inputTensor([[1, 2, 3], [2, 3, 4], ]) moire.debug(f'a ::",
"'uniform_like', 'gumbel_like', 'eye', 'diagonal', 'where', ] def zeros(*dim, batch_size: int = 1) ->",
"Expression, value) -> Expression: dim, batch_size = x.dim() return full(*dim, value=value, batch_size=batch_size) def",
"return dy.inputTensor(a.astype(np.int32), batched=True, device=moire.config.device) def bernoulli_like(x: Expression, p: float) -> Expression: dim, batch_size",
"'__main__': a = dy.inputTensor([[1, 2, 3], [2, 3, 4], ]) moire.debug(f'a :: {a.dim()}",
"mu=mu, beta=beta, batch_size=batch_size) def where(cond: Expression, x: Expression, y: Expression) -> Expression: return",
"as dy import numpy as np import moire from moire import Expression __all__",
"-> Expression: a = np.zeros((*dim, batch_size), dtype=np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def zeros_like(x:",
"batch_size = x.dim() return zeros(*dim, batch_size=batch_size) def ones(*dim, batch_size: int = 1) ->",
"M: int = None, k: int = 0) -> Expression: return dy.inputTensor(np.eye(N, M,",
"Expression) -> Expression: dim, batch_size = x.dim() return ones(*dim, batch_size=batch_size) def eye(N: int,",
"gumbel(*dim, mu=mu, beta=beta, batch_size=batch_size) def where(cond: Expression, x: Expression, y: Expression) -> Expression:",
"'ones_like', 'full_like', 'normal_like', 'bernoulli_like', 'uniform_like', 'gumbel_like', 'eye', 'diagonal', 'where', ] def zeros(*dim, batch_size:",
"0.0, beta: float = 1.0, batch_size: int = 1) -> Expression: a =",
"batch_size), dtype=np.float32) return dy.inputTensor(a, batched=True, device=moire.config.device) def ones_like(x: Expression) -> Expression: dim, batch_size",
"Expression: return dy.cmult(cond, x) + dy.cmult(1.0 - cond, y) if __name__ == '__main__':",
"from moire import Expression __all__ = [ 'zeros', 'ones', 'full', 'normal', 'bernoulli', 'uniform',",
"def gumbel_like(x: Expression, mu: float = 0.0, beta: float = 1.0) -> Expression:",
"return uniform(dim, low=low, high=high, batch_size=batch_size) def gumbel(*dim, mu: float = 0.0, beta: float",
"batch_size=batch_size) def gumbel(*dim, mu: float = 0.0, beta: float = 1.0, batch_size: int",
"full(*dim, value, batch_size: int = 1) -> Expression: a = np.full((*dim, batch_size), fill_value=value,",
"return gumbel(*dim, mu=mu, beta=beta, batch_size=batch_size) def where(cond: Expression, x: Expression, y: Expression) ->",
"uniform_like(x: Expression, low: float, high: float) -> Expression: dim, batch_size = x.dim() return",
"def zeros_like(x: Expression) -> Expression: dim, batch_size = x.dim() return zeros(*dim, batch_size=batch_size) def",
"'gumbel', 'zeros_like', 'ones_like', 'full_like', 'normal_like', 'bernoulli_like', 'uniform_like', 'gumbel_like', 'eye', 'diagonal', 'where', ] def",
"float, high: float) -> Expression: dim, batch_size = x.dim() return uniform(dim, low=low, high=high,",
"normal_like(x: Expression, mean: float = 0.0, stddev: float = 1.0) -> Expression: dim,",
"low=low, high=high, batch_size=batch_size) def gumbel(*dim, mu: float = 0.0, beta: float = 1.0,",
"1.0) -> Expression: dim, batch_size = x.dim() return gumbel(*dim, mu=mu, beta=beta, batch_size=batch_size) def",
"a = np.random.gumbel(loc=mu, scale=beta, size=(*dim, batch_size)) return dy.inputTensor(a, batched=True, device=moire.config.device) def gumbel_like(x: Expression,",
"-> Expression: dim, batch_size = x.dim() return normal(*dim, mean=mean, stddev=stddev, batch_size=batch_size) def bernoulli(*dim,",
"int, M: int = None, k: int = 0) -> Expression: return dy.inputTensor(np.eye(N,",
"0.0, stddev: float = 1.0) -> Expression: dim, batch_size = x.dim() return normal(*dim,",
"device=moire.config.device) def full_like(x: Expression, value) -> Expression: dim, batch_size = x.dim() return full(*dim,",
"dim, batch_size = x.dim() return bernoulli(*dim, p=p, batch_size=batch_size) def uniform(*dim, low: float, high:",
"= 0.0, beta: float = 1.0, batch_size: int = 1) -> Expression: a",
"float = 0.0, stddev: float = 1.0, batch_size: int = 1) -> Expression:",
"def eye(N: int, M: int = None, k: int = 0) -> Expression:"
] |
[
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version",
"KIND, either express or implied. # See the License for the specific language",
"in sorted(kwargs.keys())] loss = torch.zeros_like(values[0]) for loss_idx, loss_value in enumerate(values): if self._weights is",
"Unless required by applicable law or agreed to in writing, software # distributed",
"ports. \"\"\" return {\"loss\": NeuralType(elements_type=LossType())} def __init__(self, num_inputs: int = 2, weights: List[float]",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"# See the License for the specific language governing permissions and # limitations",
"License. # You may obtain a copy of the License at # #",
"rights reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"= ['AggregatorLoss'] class AggregatorLoss(Loss): \"\"\" Sums several losses into one. Args: num_inputs: number",
"NeuralType __all__ = ['AggregatorLoss'] class AggregatorLoss(Loss): \"\"\" Sums several losses into one. Args:",
"module output ports. \"\"\" return {\"loss\": NeuralType(elements_type=LossType())} def __init__(self, num_inputs: int = 2,",
"import Loss, typecheck from nemo.core.neural_types import LossType, NeuralType __all__ = ['AggregatorLoss'] class AggregatorLoss(Loss):",
"for i in range(self._num_losses): input_types[\"loss_\" + str(i + 1)] = NeuralType(elements_type=LossType()) return input_types",
"law or agreed to in writing, software # distributed under the License is",
"in range(self._num_losses): input_types[\"loss_\" + str(i + 1)] = NeuralType(elements_type=LossType()) return input_types @property def",
"def forward(self, **kwargs): values = [kwargs[x] for x in sorted(kwargs.keys())] loss = torch.zeros_like(values[0])",
"the License for the specific language governing permissions and # limitations under the",
"inputs (num_inputs)\") self._weights = weights @typecheck() def forward(self, **kwargs): values = [kwargs[x] for",
"compliance with the License. # You may obtain a copy of the License",
"the specific language governing permissions and # limitations under the License. from typing",
"__init__(self, num_inputs: int = 2, weights: List[float] = None): super().__init__() self._num_losses = num_inputs",
"should be equal to the number of inputs (num_inputs)\") self._weights = weights @typecheck()",
"NeuralType(elements_type=LossType())} def __init__(self, num_inputs: int = 2, weights: List[float] = None): super().__init__() self._num_losses",
"self._weights = weights @typecheck() def forward(self, **kwargs): values = [kwargs[x] for x in",
"\"\"\" input_types = {} for i in range(self._num_losses): input_types[\"loss_\" + str(i + 1)]",
"input_types = {} for i in range(self._num_losses): input_types[\"loss_\" + str(i + 1)] =",
"governing permissions and # limitations under the License. from typing import List import",
"(c) 2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"this file except in compliance with the License. # You may obtain a",
"is not None: loss = loss.add(loss_value, alpha=self._weights[loss_idx]) else: loss = loss.add(loss_value) return loss",
"is not None and len(weights) != num_inputs: raise ValueError(\"Length of weights should be",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"into one. Args: num_inputs: number of input losses weights: a list of coefficient",
"from nemo.core.classes import Loss, typecheck from nemo.core.neural_types import LossType, NeuralType __all__ = ['AggregatorLoss']",
"you may not use this file except in compliance with the License. #",
"under the License. from typing import List import torch from nemo.core.classes import Loss,",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"import LossType, NeuralType __all__ = ['AggregatorLoss'] class AggregatorLoss(Loss): \"\"\" Sums several losses into",
"License. from typing import List import torch from nemo.core.classes import Loss, typecheck from",
"['AggregatorLoss'] class AggregatorLoss(Loss): \"\"\" Sums several losses into one. Args: num_inputs: number of",
"output_types(self): \"\"\"Returns definitions of module output ports. \"\"\" return {\"loss\": NeuralType(elements_type=LossType())} def __init__(self,",
"to the number of inputs (num_inputs)\") self._weights = weights @typecheck() def forward(self, **kwargs):",
"ANY KIND, either express or implied. # See the License for the specific",
"of coefficient for merging losses \"\"\" @property def input_types(self): \"\"\"Returns definitions of module",
"for x in sorted(kwargs.keys())] loss = torch.zeros_like(values[0]) for loss_idx, loss_value in enumerate(values): if",
"the number of inputs (num_inputs)\") self._weights = weights @typecheck() def forward(self, **kwargs): values",
"torch.zeros_like(values[0]) for loss_idx, loss_value in enumerate(values): if self._weights is not None: loss =",
"if self._weights is not None: loss = loss.add(loss_value, alpha=self._weights[loss_idx]) else: loss = loss.add(loss_value)",
"len(weights) != num_inputs: raise ValueError(\"Length of weights should be equal to the number",
"self._num_losses = num_inputs if weights is not None and len(weights) != num_inputs: raise",
"equal to the number of inputs (num_inputs)\") self._weights = weights @typecheck() def forward(self,",
"typing import List import torch from nemo.core.classes import Loss, typecheck from nemo.core.neural_types import",
"in compliance with the License. # You may obtain a copy of the",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"losses weights: a list of coefficient for merging losses \"\"\" @property def input_types(self):",
"and len(weights) != num_inputs: raise ValueError(\"Length of weights should be equal to the",
"module input ports. \"\"\" input_types = {} for i in range(self._num_losses): input_types[\"loss_\" +",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"!= num_inputs: raise ValueError(\"Length of weights should be equal to the number of",
"not None and len(weights) != num_inputs: raise ValueError(\"Length of weights should be equal",
"use this file except in compliance with the License. # You may obtain",
"for loss_idx, loss_value in enumerate(values): if self._weights is not None: loss = loss.add(loss_value,",
"self._weights is not None: loss = loss.add(loss_value, alpha=self._weights[loss_idx]) else: loss = loss.add(loss_value) return",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"coefficient for merging losses \"\"\" @property def input_types(self): \"\"\"Returns definitions of module input",
"1)] = NeuralType(elements_type=LossType()) return input_types @property def output_types(self): \"\"\"Returns definitions of module output",
"not use this file except in compliance with the License. # You may",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"and # limitations under the License. from typing import List import torch from",
"= num_inputs if weights is not None and len(weights) != num_inputs: raise ValueError(\"Length",
"@property def input_types(self): \"\"\"Returns definitions of module input ports. \"\"\" input_types = {}",
"several losses into one. Args: num_inputs: number of input losses weights: a list",
"= None): super().__init__() self._num_losses = num_inputs if weights is not None and len(weights)",
"import List import torch from nemo.core.classes import Loss, typecheck from nemo.core.neural_types import LossType,",
"See the License for the specific language governing permissions and # limitations under",
"num_inputs if weights is not None and len(weights) != num_inputs: raise ValueError(\"Length of",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"return {\"loss\": NeuralType(elements_type=LossType())} def __init__(self, num_inputs: int = 2, weights: List[float] = None):",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"Loss, typecheck from nemo.core.neural_types import LossType, NeuralType __all__ = ['AggregatorLoss'] class AggregatorLoss(Loss): \"\"\"",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"\"\"\" Sums several losses into one. Args: num_inputs: number of input losses weights:",
"a list of coefficient for merging losses \"\"\" @property def input_types(self): \"\"\"Returns definitions",
"of inputs (num_inputs)\") self._weights = weights @typecheck() def forward(self, **kwargs): values = [kwargs[x]",
"loss = torch.zeros_like(values[0]) for loss_idx, loss_value in enumerate(values): if self._weights is not None:",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"weights is not None and len(weights) != num_inputs: raise ValueError(\"Length of weights should",
"typecheck from nemo.core.neural_types import LossType, NeuralType __all__ = ['AggregatorLoss'] class AggregatorLoss(Loss): \"\"\" Sums",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"= NeuralType(elements_type=LossType()) return input_types @property def output_types(self): \"\"\"Returns definitions of module output ports.",
"int = 2, weights: List[float] = None): super().__init__() self._num_losses = num_inputs if weights",
"return input_types @property def output_types(self): \"\"\"Returns definitions of module output ports. \"\"\" return",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"merging losses \"\"\" @property def input_types(self): \"\"\"Returns definitions of module input ports. \"\"\"",
"input ports. \"\"\" input_types = {} for i in range(self._num_losses): input_types[\"loss_\" + str(i",
"{\"loss\": NeuralType(elements_type=LossType())} def __init__(self, num_inputs: int = 2, weights: List[float] = None): super().__init__()",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"None and len(weights) != num_inputs: raise ValueError(\"Length of weights should be equal to",
"ValueError(\"Length of weights should be equal to the number of inputs (num_inputs)\") self._weights",
"def input_types(self): \"\"\"Returns definitions of module input ports. \"\"\" input_types = {} for",
"language governing permissions and # limitations under the License. from typing import List",
"OF ANY KIND, either express or implied. # See the License for the",
"num_inputs: raise ValueError(\"Length of weights should be equal to the number of inputs",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"2, weights: List[float] = None): super().__init__() self._num_losses = num_inputs if weights is not",
"input_types[\"loss_\" + str(i + 1)] = NeuralType(elements_type=LossType()) return input_types @property def output_types(self): \"\"\"Returns",
"of module output ports. \"\"\" return {\"loss\": NeuralType(elements_type=LossType())} def __init__(self, num_inputs: int =",
"# you may not use this file except in compliance with the License.",
"{} for i in range(self._num_losses): input_types[\"loss_\" + str(i + 1)] = NeuralType(elements_type=LossType()) return",
"permissions and # limitations under the License. from typing import List import torch",
"Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the",
"@typecheck() def forward(self, **kwargs): values = [kwargs[x] for x in sorted(kwargs.keys())] loss =",
"agreed to in writing, software # distributed under the License is distributed on",
"limitations under the License. from typing import List import torch from nemo.core.classes import",
"weights: a list of coefficient for merging losses \"\"\" @property def input_types(self): \"\"\"Returns",
"str(i + 1)] = NeuralType(elements_type=LossType()) return input_types @property def output_types(self): \"\"\"Returns definitions of",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"= [kwargs[x] for x in sorted(kwargs.keys())] loss = torch.zeros_like(values[0]) for loss_idx, loss_value in",
"super().__init__() self._num_losses = num_inputs if weights is not None and len(weights) != num_inputs:",
"# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under",
"(the \"License\"); # you may not use this file except in compliance with",
"be equal to the number of inputs (num_inputs)\") self._weights = weights @typecheck() def",
"from nemo.core.neural_types import LossType, NeuralType __all__ = ['AggregatorLoss'] class AggregatorLoss(Loss): \"\"\" Sums several",
"\"\"\"Returns definitions of module input ports. \"\"\" input_types = {} for i in",
"def __init__(self, num_inputs: int = 2, weights: List[float] = None): super().__init__() self._num_losses =",
"num_inputs: int = 2, weights: List[float] = None): super().__init__() self._num_losses = num_inputs if",
"# # Unless required by applicable law or agreed to in writing, software",
"None): super().__init__() self._num_losses = num_inputs if weights is not None and len(weights) !=",
"input_types @property def output_types(self): \"\"\"Returns definitions of module output ports. \"\"\" return {\"loss\":",
"if weights is not None and len(weights) != num_inputs: raise ValueError(\"Length of weights",
"losses into one. Args: num_inputs: number of input losses weights: a list of",
"express or implied. # See the License for the specific language governing permissions",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"# Unless required by applicable law or agreed to in writing, software #",
"for the specific language governing permissions and # limitations under the License. from",
"except in compliance with the License. # You may obtain a copy of",
"\"\"\"Returns definitions of module output ports. \"\"\" return {\"loss\": NeuralType(elements_type=LossType())} def __init__(self, num_inputs:",
"by applicable law or agreed to in writing, software # distributed under the",
"= {} for i in range(self._num_losses): input_types[\"loss_\" + str(i + 1)] = NeuralType(elements_type=LossType())",
"specific language governing permissions and # limitations under the License. from typing import",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"input losses weights: a list of coefficient for merging losses \"\"\" @property def",
"definitions of module input ports. \"\"\" input_types = {} for i in range(self._num_losses):",
"of weights should be equal to the number of inputs (num_inputs)\") self._weights =",
"one. Args: num_inputs: number of input losses weights: a list of coefficient for",
"weights: List[float] = None): super().__init__() self._num_losses = num_inputs if weights is not None",
"either express or implied. # See the License for the specific language governing",
"from typing import List import torch from nemo.core.classes import Loss, typecheck from nemo.core.neural_types",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"\"\"\" return {\"loss\": NeuralType(elements_type=LossType())} def __init__(self, num_inputs: int = 2, weights: List[float] =",
"input_types(self): \"\"\"Returns definitions of module input ports. \"\"\" input_types = {} for i",
"# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"may not use this file except in compliance with the License. # You",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"= torch.zeros_like(values[0]) for loss_idx, loss_value in enumerate(values): if self._weights is not None: loss",
"LossType, NeuralType __all__ = ['AggregatorLoss'] class AggregatorLoss(Loss): \"\"\" Sums several losses into one.",
"forward(self, **kwargs): values = [kwargs[x] for x in sorted(kwargs.keys())] loss = torch.zeros_like(values[0]) for",
"= 2, weights: List[float] = None): super().__init__() self._num_losses = num_inputs if weights is",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"for merging losses \"\"\" @property def input_types(self): \"\"\"Returns definitions of module input ports.",
"losses \"\"\" @property def input_types(self): \"\"\"Returns definitions of module input ports. \"\"\" input_types",
"file except in compliance with the License. # You may obtain a copy",
"loss_idx, loss_value in enumerate(values): if self._weights is not None: loss = loss.add(loss_value, alpha=self._weights[loss_idx])",
"List import torch from nemo.core.classes import Loss, typecheck from nemo.core.neural_types import LossType, NeuralType",
"**kwargs): values = [kwargs[x] for x in sorted(kwargs.keys())] loss = torch.zeros_like(values[0]) for loss_idx,",
"import torch from nemo.core.classes import Loss, typecheck from nemo.core.neural_types import LossType, NeuralType __all__",
"CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0",
"of input losses weights: a list of coefficient for merging losses \"\"\" @property",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"+ str(i + 1)] = NeuralType(elements_type=LossType()) return input_types @property def output_types(self): \"\"\"Returns definitions",
"License for the specific language governing permissions and # limitations under the License.",
"values = [kwargs[x] for x in sorted(kwargs.keys())] loss = torch.zeros_like(values[0]) for loss_idx, loss_value",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"x in sorted(kwargs.keys())] loss = torch.zeros_like(values[0]) for loss_idx, loss_value in enumerate(values): if self._weights",
"the License. # You may obtain a copy of the License at #",
"class AggregatorLoss(Loss): \"\"\" Sums several losses into one. Args: num_inputs: number of input",
"[kwargs[x] for x in sorted(kwargs.keys())] loss = torch.zeros_like(values[0]) for loss_idx, loss_value in enumerate(values):",
"range(self._num_losses): input_types[\"loss_\" + str(i + 1)] = NeuralType(elements_type=LossType()) return input_types @property def output_types(self):",
"to in writing, software # distributed under the License is distributed on an",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"# limitations under the License. from typing import List import torch from nemo.core.classes",
"NeuralType(elements_type=LossType()) return input_types @property def output_types(self): \"\"\"Returns definitions of module output ports. \"\"\"",
"ports. \"\"\" input_types = {} for i in range(self._num_losses): input_types[\"loss_\" + str(i +",
"output ports. \"\"\" return {\"loss\": NeuralType(elements_type=LossType())} def __init__(self, num_inputs: int = 2, weights:",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"implied. # See the License for the specific language governing permissions and #",
"(num_inputs)\") self._weights = weights @typecheck() def forward(self, **kwargs): values = [kwargs[x] for x",
"\"License\"); # you may not use this file except in compliance with the",
"of module input ports. \"\"\" input_types = {} for i in range(self._num_losses): input_types[\"loss_\"",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"weights should be equal to the number of inputs (num_inputs)\") self._weights = weights",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"sorted(kwargs.keys())] loss = torch.zeros_like(values[0]) for loss_idx, loss_value in enumerate(values): if self._weights is not",
"required by applicable law or agreed to in writing, software # distributed under",
"torch from nemo.core.classes import Loss, typecheck from nemo.core.neural_types import LossType, NeuralType __all__ =",
"nemo.core.neural_types import LossType, NeuralType __all__ = ['AggregatorLoss'] class AggregatorLoss(Loss): \"\"\" Sums several losses",
"@property def output_types(self): \"\"\"Returns definitions of module output ports. \"\"\" return {\"loss\": NeuralType(elements_type=LossType())}",
"applicable law or agreed to in writing, software # distributed under the License",
"Args: num_inputs: number of input losses weights: a list of coefficient for merging",
"nemo.core.classes import Loss, typecheck from nemo.core.neural_types import LossType, NeuralType __all__ = ['AggregatorLoss'] class",
"def output_types(self): \"\"\"Returns definitions of module output ports. \"\"\" return {\"loss\": NeuralType(elements_type=LossType())} def",
"or agreed to in writing, software # distributed under the License is distributed",
"2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License,",
"loss_value in enumerate(values): if self._weights is not None: loss = loss.add(loss_value, alpha=self._weights[loss_idx]) else:",
"or implied. # See the License for the specific language governing permissions and",
"+ 1)] = NeuralType(elements_type=LossType()) return input_types @property def output_types(self): \"\"\"Returns definitions of module",
"list of coefficient for merging losses \"\"\" @property def input_types(self): \"\"\"Returns definitions of",
"Sums several losses into one. Args: num_inputs: number of input losses weights: a",
"\"\"\" @property def input_types(self): \"\"\"Returns definitions of module input ports. \"\"\" input_types =",
"= weights @typecheck() def forward(self, **kwargs): values = [kwargs[x] for x in sorted(kwargs.keys())]",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"All rights reserved. # # Licensed under the Apache License, Version 2.0 (the",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"the License. from typing import List import torch from nemo.core.classes import Loss, typecheck",
"AggregatorLoss(Loss): \"\"\" Sums several losses into one. Args: num_inputs: number of input losses",
"definitions of module output ports. \"\"\" return {\"loss\": NeuralType(elements_type=LossType())} def __init__(self, num_inputs: int",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"List[float] = None): super().__init__() self._num_losses = num_inputs if weights is not None and",
"in enumerate(values): if self._weights is not None: loss = loss.add(loss_value, alpha=self._weights[loss_idx]) else: loss",
"__all__ = ['AggregatorLoss'] class AggregatorLoss(Loss): \"\"\" Sums several losses into one. Args: num_inputs:",
"weights @typecheck() def forward(self, **kwargs): values = [kwargs[x] for x in sorted(kwargs.keys())] loss",
"with the License. # You may obtain a copy of the License at",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"enumerate(values): if self._weights is not None: loss = loss.add(loss_value, alpha=self._weights[loss_idx]) else: loss =",
"in writing, software # distributed under the License is distributed on an \"AS",
"number of input losses weights: a list of coefficient for merging losses \"\"\"",
"raise ValueError(\"Length of weights should be equal to the number of inputs (num_inputs)\")",
"i in range(self._num_losses): input_types[\"loss_\" + str(i + 1)] = NeuralType(elements_type=LossType()) return input_types @property",
"number of inputs (num_inputs)\") self._weights = weights @typecheck() def forward(self, **kwargs): values =",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use",
"num_inputs: number of input losses weights: a list of coefficient for merging losses"
] |
[
"produto_menos = nome produtovalor = preco resp = str(input('Quer continuar? [S/N]')).upper().strip()[0] if resp",
"= '' print(20*'-') print('{:^20}'.format('<NAME>')) print(20*'-') while True: nome = str(input('Nome do produto: ')).strip()",
"[S/N]')).upper().strip()[0] if resp == 'N': break print(20*'=') print(f'O total do valor foi R${soma:.2f}')",
"gasto na compra B)Quantos produtos custão mais que 1000 C)Qual é o nome",
"True: nome = str(input('Nome do produto: ')).strip() preco = float(input('Preço R$: ')) soma",
"1 or produtovalor > preco: produto_menos = nome produtovalor = preco resp =",
"= preco resp = str(input('Quer continuar? [S/N]')).upper().strip()[0] if resp == 'N': break print(20*'=')",
"final, mostre: A) Qual é o total gasto na compra B)Quantos produtos custão",
"or produtovalor > preco: produto_menos = nome produtovalor = preco resp = str(input('Quer",
"cont == 1 or produtovalor > preco: produto_menos = nome produtovalor = preco",
"e o preço de vários produtos. O program ddeverá perguntar se o usuário",
"> preco: produto_menos = nome produtovalor = preco resp = str(input('Quer continuar? [S/N]')).upper().strip()[0]",
"usuário vai continuar. #No final, mostre: A) Qual é o total gasto na",
"+= 1 if preco > 1000: produto_mais += 1 if cont == 1",
"valor foi R${soma:.2f}') print(f'Temos {produto_mais} produtos que custão mais de R$1000.00') print(f'O produto",
"produtovalor > preco: produto_menos = nome produtovalor = preco resp = str(input('Quer continuar?",
"1 if cont == 1 or produtovalor > preco: produto_menos = nome produtovalor",
"nome do produto mais barato. cont = soma = produto_mais = produtovalor =",
"#No final, mostre: A) Qual é o total gasto na compra B)Quantos produtos",
"soma += preco cont += 1 if preco > 1000: produto_mais += 1",
"C)Qual é o nome do produto mais barato. cont = soma = produto_mais",
"do produto mais barato. cont = soma = produto_mais = produtovalor = 0",
"ddeverá perguntar se o usuário vai continuar. #No final, mostre: A) Qual é",
"se o usuário vai continuar. #No final, mostre: A) Qual é o total",
"custão mais que 1000 C)Qual é o nome do produto mais barato. cont",
"R$: ')) soma += preco cont += 1 if preco > 1000: produto_mais",
"{produto_mais} produtos que custão mais de R$1000.00') print(f'O produto mais barato foi {produto_menos}",
"produtovalor = preco resp = str(input('Quer continuar? [S/N]')).upper().strip()[0] if resp == 'N': break",
"'N': break print(20*'=') print(f'O total do valor foi R${soma:.2f}') print(f'Temos {produto_mais} produtos que",
"o nome e o preço de vários produtos. O program ddeverá perguntar se",
"vai continuar. #No final, mostre: A) Qual é o total gasto na compra",
"compra B)Quantos produtos custão mais que 1000 C)Qual é o nome do produto",
"0 produto_menos = '' print(20*'-') print('{:^20}'.format('<NAME>')) print(20*'-') while True: nome = str(input('Nome do",
"O program ddeverá perguntar se o usuário vai continuar. #No final, mostre: A)",
"preco cont += 1 if preco > 1000: produto_mais += 1 if cont",
"str(input('Nome do produto: ')).strip() preco = float(input('Preço R$: ')) soma += preco cont",
"custão mais de R$1000.00') print(f'O produto mais barato foi {produto_menos} que custa R${produtovalor:.2f}')",
"A) Qual é o total gasto na compra B)Quantos produtos custão mais que",
"= produto_mais = produtovalor = 0 produto_menos = '' print(20*'-') print('{:^20}'.format('<NAME>')) print(20*'-') while",
"break print(20*'=') print(f'O total do valor foi R${soma:.2f}') print(f'Temos {produto_mais} produtos que custão",
"preco > 1000: produto_mais += 1 if cont == 1 or produtovalor >",
"que 1000 C)Qual é o nome do produto mais barato. cont = soma",
"= float(input('Preço R$: ')) soma += preco cont += 1 if preco >",
"str(input('Quer continuar? [S/N]')).upper().strip()[0] if resp == 'N': break print(20*'=') print(f'O total do valor",
"o nome do produto mais barato. cont = soma = produto_mais = produtovalor",
"print(f'O total do valor foi R${soma:.2f}') print(f'Temos {produto_mais} produtos que custão mais de",
"Qual é o total gasto na compra B)Quantos produtos custão mais que 1000",
"continuar? [S/N]')).upper().strip()[0] if resp == 'N': break print(20*'=') print(f'O total do valor foi",
"programa que leia o nome e o preço de vários produtos. O program",
"print('{:^20}'.format('<NAME>')) print(20*'-') while True: nome = str(input('Nome do produto: ')).strip() preco = float(input('Preço",
"produtos que custão mais de R$1000.00') print(f'O produto mais barato foi {produto_menos} que",
"nome produtovalor = preco resp = str(input('Quer continuar? [S/N]')).upper().strip()[0] if resp == 'N':",
"print(f'Temos {produto_mais} produtos que custão mais de R$1000.00') print(f'O produto mais barato foi",
"+= 1 if cont == 1 or produtovalor > preco: produto_menos = nome",
"produto_mais += 1 if cont == 1 or produtovalor > preco: produto_menos =",
"preco resp = str(input('Quer continuar? [S/N]')).upper().strip()[0] if resp == 'N': break print(20*'=') print(f'O",
"mostre: A) Qual é o total gasto na compra B)Quantos produtos custão mais",
"produtos. O program ddeverá perguntar se o usuário vai continuar. #No final, mostre:",
"= soma = produto_mais = produtovalor = 0 produto_menos = '' print(20*'-') print('{:^20}'.format('<NAME>'))",
"produto mais barato. cont = soma = produto_mais = produtovalor = 0 produto_menos",
"o preço de vários produtos. O program ddeverá perguntar se o usuário vai",
"do valor foi R${soma:.2f}') print(f'Temos {produto_mais} produtos que custão mais de R$1000.00') print(f'O",
"foi R${soma:.2f}') print(f'Temos {produto_mais} produtos que custão mais de R$1000.00') print(f'O produto mais",
"= str(input('Nome do produto: ')).strip() preco = float(input('Preço R$: ')) soma += preco",
"= produtovalor = 0 produto_menos = '' print(20*'-') print('{:^20}'.format('<NAME>')) print(20*'-') while True: nome",
"')) soma += preco cont += 1 if preco > 1000: produto_mais +=",
"== 1 or produtovalor > preco: produto_menos = nome produtovalor = preco resp",
"soma = produto_mais = produtovalor = 0 produto_menos = '' print(20*'-') print('{:^20}'.format('<NAME>')) print(20*'-')",
"= str(input('Quer continuar? [S/N]')).upper().strip()[0] if resp == 'N': break print(20*'=') print(f'O total do",
"'' print(20*'-') print('{:^20}'.format('<NAME>')) print(20*'-') while True: nome = str(input('Nome do produto: ')).strip() preco",
"print(20*'-') while True: nome = str(input('Nome do produto: ')).strip() preco = float(input('Preço R$:",
"o usuário vai continuar. #No final, mostre: A) Qual é o total gasto",
"continuar. #No final, mostre: A) Qual é o total gasto na compra B)Quantos",
"preco = float(input('Preço R$: ')) soma += preco cont += 1 if preco",
"= 0 produto_menos = '' print(20*'-') print('{:^20}'.format('<NAME>')) print(20*'-') while True: nome = str(input('Nome",
"preço de vários produtos. O program ddeverá perguntar se o usuário vai continuar.",
"resp == 'N': break print(20*'=') print(f'O total do valor foi R${soma:.2f}') print(f'Temos {produto_mais}",
"print(20*'-') print('{:^20}'.format('<NAME>')) print(20*'-') while True: nome = str(input('Nome do produto: ')).strip() preco =",
"leia o nome e o preço de vários produtos. O program ddeverá perguntar",
"cont += 1 if preco > 1000: produto_mais += 1 if cont ==",
"o total gasto na compra B)Quantos produtos custão mais que 1000 C)Qual é",
"program ddeverá perguntar se o usuário vai continuar. #No final, mostre: A) Qual",
"é o nome do produto mais barato. cont = soma = produto_mais =",
"produtovalor = 0 produto_menos = '' print(20*'-') print('{:^20}'.format('<NAME>')) print(20*'-') while True: nome =",
"if preco > 1000: produto_mais += 1 if cont == 1 or produtovalor",
"== 'N': break print(20*'=') print(f'O total do valor foi R${soma:.2f}') print(f'Temos {produto_mais} produtos",
"#Crie um programa que leia o nome e o preço de vários produtos.",
"R${soma:.2f}') print(f'Temos {produto_mais} produtos que custão mais de R$1000.00') print(f'O produto mais barato",
"um programa que leia o nome e o preço de vários produtos. O",
"> 1000: produto_mais += 1 if cont == 1 or produtovalor > preco:",
"preco: produto_menos = nome produtovalor = preco resp = str(input('Quer continuar? [S/N]')).upper().strip()[0] if",
"na compra B)Quantos produtos custão mais que 1000 C)Qual é o nome do",
"if resp == 'N': break print(20*'=') print(f'O total do valor foi R${soma:.2f}') print(f'Temos",
"produtos custão mais que 1000 C)Qual é o nome do produto mais barato.",
"de vários produtos. O program ddeverá perguntar se o usuário vai continuar. #No",
"while True: nome = str(input('Nome do produto: ')).strip() preco = float(input('Preço R$: '))",
"produto_mais = produtovalor = 0 produto_menos = '' print(20*'-') print('{:^20}'.format('<NAME>')) print(20*'-') while True:",
"1 if preco > 1000: produto_mais += 1 if cont == 1 or",
"perguntar se o usuário vai continuar. #No final, mostre: A) Qual é o",
"1000: produto_mais += 1 if cont == 1 or produtovalor > preco: produto_menos",
"')).strip() preco = float(input('Preço R$: ')) soma += preco cont += 1 if",
"nome e o preço de vários produtos. O program ddeverá perguntar se o",
"+= preco cont += 1 if preco > 1000: produto_mais += 1 if",
"mais barato. cont = soma = produto_mais = produtovalor = 0 produto_menos =",
"é o total gasto na compra B)Quantos produtos custão mais que 1000 C)Qual",
"produto: ')).strip() preco = float(input('Preço R$: ')) soma += preco cont += 1",
"resp = str(input('Quer continuar? [S/N]')).upper().strip()[0] if resp == 'N': break print(20*'=') print(f'O total",
"que leia o nome e o preço de vários produtos. O program ddeverá",
"1000 C)Qual é o nome do produto mais barato. cont = soma =",
"print(20*'=') print(f'O total do valor foi R${soma:.2f}') print(f'Temos {produto_mais} produtos que custão mais",
"cont = soma = produto_mais = produtovalor = 0 produto_menos = '' print(20*'-')",
"total do valor foi R${soma:.2f}') print(f'Temos {produto_mais} produtos que custão mais de R$1000.00')",
"mais que 1000 C)Qual é o nome do produto mais barato. cont =",
"vários produtos. O program ddeverá perguntar se o usuário vai continuar. #No final,",
"B)Quantos produtos custão mais que 1000 C)Qual é o nome do produto mais",
"que custão mais de R$1000.00') print(f'O produto mais barato foi {produto_menos} que custa",
"nome = str(input('Nome do produto: ')).strip() preco = float(input('Preço R$: ')) soma +=",
"do produto: ')).strip() preco = float(input('Preço R$: ')) soma += preco cont +=",
"= nome produtovalor = preco resp = str(input('Quer continuar? [S/N]')).upper().strip()[0] if resp ==",
"produto_menos = '' print(20*'-') print('{:^20}'.format('<NAME>')) print(20*'-') while True: nome = str(input('Nome do produto:",
"total gasto na compra B)Quantos produtos custão mais que 1000 C)Qual é o",
"barato. cont = soma = produto_mais = produtovalor = 0 produto_menos = ''",
"if cont == 1 or produtovalor > preco: produto_menos = nome produtovalor =",
"float(input('Preço R$: ')) soma += preco cont += 1 if preco > 1000:"
] |
[
"def backup(self, backup, volume_file): LOG.info('Starting backup...... Creating a new backup for volume:%s.' %",
"volume_file): LOG.info('Starting backup...... Creating a new backup for volume:%s.' % backup['volume_id']) backup_id =",
"Creating a new backup for volume:%s.' % backup['volume_id']) backup_id = backup['id'] url =",
"msg = \"redirect backup cmd failed!\" raise exception.BackupOperationError(msg) while True: url = 'http://'",
"finished.') break time.sleep(3) return size def restore(self, backup, target_volume_id, volume_file): LOG.info('Starting restore...... restore",
"to dst_volume:%(dst)s' % {'src': backup['volume_id'], 'dst': str(\"volume-\" + target_volume_id)}) backup_id = backup['id'] url",
"+ self._server_ip + '/v2/admin/backups/' + backup_id try: urllib2.urlopen(url) except urllib2.HTTPError, e: LOG.debug(e.code) if",
"'application/json') req.get_method = lambda:'DELETE' try: response = urllib2.urlopen(req) LOG.debug(response.read()) except urllib2.HTTPError, e: LOG.debug(e.code)",
"msg = \"redirect restore cmd failed!\" raise exception.BackupOperationError(msg) while True: url = 'http://'",
"= backup['id'] url = 'http://' + self._server_ip + '/v2/admin/backups' data = { \"backup\":{",
"self.context = context self._server_ip = self._utf8(CONF.cinder_ip) @staticmethod def _utf8(s): \"\"\"Ensure string s is",
"logging.getLogger(__name__) service_opts = [ cfg.StrOpt('cinder_ip', default='172.16.172.250:8776', help='ebs management node ip.'), ] CONF =",
"self._server_ip + '/v2/admin/backups/' + backup_id try: urllib2.urlopen(url) except urllib2.HTTPError, e: LOG.debug(e.code) if e.code",
"msg = \"confirm delete cmd failed!\" raise exception.BackupOperationError(msg) time.sleep(3) def get_backup_driver(context): return SheepdogBackupDriver(context)",
"= 'http://' + self._server_ip + '/v2/admin/backups/' + backup_id try: response = urllib2.urlopen(url) ret",
"LOG.info('delete finished.') break else: msg = \"confirm delete cmd failed!\" raise exception.BackupOperationError(msg) time.sleep(3)",
"'dst': str(\"volume-\" + target_volume_id)}) backup_id = backup['id'] url = 'http://' + self._server_ip +",
"= \"redirect restore cmd failed!\" raise exception.BackupOperationError(msg) while True: url = 'http://' +",
"e.code == 404: msg = \"backup does not exist!\" LOG.info(msg) raise exception.BackupOperationError(msg) #help",
"cmd failed!\" raise exception.BackupOperationError(msg) if data['backup']['status'] == 'available': size = data['backup']['object_count'] LOG.debug(\"size %s",
"= urllib2.Request(url, jdata) req.add_header('Content-type', 'application/json') try: response = urllib2.urlopen(req) LOG.debug(response.read()) except urllib2.HTTPError, e:",
"backup['volume_id']) backup_id = backup['id'] url = 'http://' + self._server_ip + '/v2/admin/backups' data =",
"'/v2/admin/backups/' + backup_id + '/restore' data = { \"restore\":{ \"volume_id\": target_volume_id } }",
"= 'http://' + self._server_ip + '/v2/admin/backups/' + backup_id + '/restore' data = {",
"e: LOG.debug(e.code) msg = \"confirm restore cmd failed!\" raise exception.BackupOperationError(msg) if data['backup']['status'] ==",
"break else: msg = \"confirm delete cmd failed!\" raise exception.BackupOperationError(msg) time.sleep(3) def get_backup_driver(context):",
"LOG.info('backup finished.') break time.sleep(3) return size def restore(self, backup, target_volume_id, volume_file): LOG.info('Starting restore......",
"failed!\" raise exception.BackupOperationError(msg) while True: url = 'http://' + self._server_ip + '/v2/admin/backups/' +",
"as logging from cinder.backup.driver import BackupDriver LOG = logging.getLogger(__name__) service_opts = [ cfg.StrOpt('cinder_ip',",
"backup cmd failed!\" raise exception.BackupOperationError(msg) if data['backup']['status'] == 'available': size = data['backup']['object_count'] LOG.debug(\"size",
"\"redirect backup cmd failed!\" raise exception.BackupOperationError(msg) while True: url = 'http://' + self._server_ip",
"s return s.encode('utf8') def backup(self, backup, volume_file): LOG.info('Starting backup...... Creating a new backup",
"cinder.backup.driver import BackupDriver LOG = logging.getLogger(__name__) service_opts = [ cfg.StrOpt('cinder_ip', default='172.16.172.250:8776', help='ebs management",
"LOG.debug(response.read()) except urllib2.HTTPError, e: LOG.debug(e.code) msg = \"redirect backup cmd failed!\" raise exception.BackupOperationError(msg)",
"except urllib2.HTTPError, e: LOG.debug(e.code) msg = \"redirect restore cmd failed!\" raise exception.BackupOperationError(msg) while",
"% backup['id']) backup_id = backup['id'] url = 'http://' + self._server_ip + '/v2/admin/backups/' +",
"url = 'http://' + self._server_ip + '/v2/admin/backups/' + backup_id try: response = urllib2.urlopen(url)",
"not exist!\" LOG.info(msg) raise exception.BackupOperationError(msg) #help to decide the volume whether belongs to",
"ret) data = json.loads(ret) except urllib2.HTTPError, e: LOG.debug(e.code) msg = \"confirm restore cmd",
"LOG.info('Starting restore...... restore from src_volume:%(src)s to dst_volume:%(dst)s' % {'src': backup['volume_id'], 'dst': str(\"volume-\" +",
"does not exist! already success!\"\"\" LOG.info('delete finished.') break else: msg = \"confirm delete",
"backup_id = backup['id'] url = 'http://' + self._server_ip + '/v2/admin/backups/' + backup_id req",
"_utf8(s): \"\"\"Ensure string s is utf8 (i.e. not unicode).\"\"\" if isinstance(s, str): return",
"break time.sleep(3) return size def restore(self, backup, target_volume_id, volume_file): LOG.info('Starting restore...... restore from",
"LOG.debug(e.code) msg = \"confirm restore cmd failed!\" raise exception.BackupOperationError(msg) if data['backup']['status'] == 'available':",
"def __init__(self, context, db_driver=None): super(SheepdogBackupDriver, self).__init__(db_driver) self.context = context self._server_ip = self._utf8(CONF.cinder_ip) @staticmethod",
"def delete(self, backup): LOG.info('Starting delete...... backupid:%s' % backup['id']) backup_id = backup['id'] url =",
"urllib2 from oslo.config import cfg from cinder import exception from oslo_log import log",
"already success!\"\"\" LOG.info('delete finished.') break else: msg = \"confirm delete cmd failed!\" raise",
"self._server_ip + '/v2/admin/backups/' + backup_id + '/restore' data = { \"restore\":{ \"volume_id\": target_volume_id",
"LOG.debug(response.read()) except urllib2.HTTPError, e: LOG.debug(e.code) msg = \"redirect restore cmd failed!\" raise exception.BackupOperationError(msg)",
"oslo.config import cfg from cinder import exception from oslo_log import log as logging",
"{ \"restore\":{ \"volume_id\": target_volume_id } } jdata = json.dumps(data) req = urllib2.Request(url, jdata)",
"= cfg.CONF CONF.register_opts(service_opts) class SheepdogBackupDriver(BackupDriver): def __init__(self, context, db_driver=None): super(SheepdogBackupDriver, self).__init__(db_driver) self.context =",
"ret = response.read() LOG.debug(\"RET: %r\" % ret) data = json.loads(ret) except urllib2.HTTPError, e:",
"= urllib2.Request(url) req.add_header('Content-Type', 'application/json') req.get_method = lambda:'DELETE' try: response = urllib2.urlopen(req) LOG.debug(response.read()) except",
"LOG.info('Starting delete...... backupid:%s' % backup['id']) backup_id = backup['id'] url = 'http://' + self._server_ip",
"== 404: msg = \"backup does not exist!\" LOG.info(msg) raise exception.BackupOperationError(msg) #help to",
"import log as logging from cinder.backup.driver import BackupDriver LOG = logging.getLogger(__name__) service_opts =",
"def restore(self, backup, target_volume_id, volume_file): LOG.info('Starting restore...... restore from src_volume:%(src)s to dst_volume:%(dst)s' %",
"response = urllib2.urlopen(req) LOG.debug(response.read()) except urllib2.HTTPError, e: LOG.debug(e.code) msg = \"redirect restore cmd",
"+ '/v2/admin/backups' data = { \"backup\":{ \"container\" : backup['container'], \"description\": backup['display_description'], \"name\" :",
"import time import json import urllib2 from oslo.config import cfg from cinder import",
"delete...... backupid:%s' % backup['id']) backup_id = backup['id'] url = 'http://' + self._server_ip +",
"context, db_driver=None): super(SheepdogBackupDriver, self).__init__(db_driver) self.context = context self._server_ip = self._utf8(CONF.cinder_ip) @staticmethod def _utf8(s):",
"backup_id try: response = urllib2.urlopen(url) ret = response.read() LOG.debug(\"RET: %r\" % ret) data",
"exception.BackupOperationError(msg) #help to decide the volume whether belongs to ebs else: msg =",
"(i.e. not unicode).\"\"\" if isinstance(s, str): return s return s.encode('utf8') def backup(self, backup,",
"data['backup']['status'] == 'available': LOG.info('restore finished.') break time.sleep(3) def delete(self, backup): LOG.info('Starting delete...... backupid:%s'",
"json.loads(ret) except urllib2.HTTPError, e: LOG.debug(e.code) msg = \"confirm backup cmd failed!\" raise exception.BackupOperationError(msg)",
"== 404: \"\"\"backup does not exist! already success!\"\"\" LOG.info('delete finished.') break else: msg",
"self._server_ip + '/v2/admin/backups/' + backup_id try: response = urllib2.urlopen(url) ret = response.read() LOG.debug(\"RET:",
"jdata) req.add_header('Content-type', 'application/json') try: response = urllib2.urlopen(req) LOG.debug(response.read()) except urllib2.HTTPError, e: LOG.debug(e.code) msg",
"size) LOG.info('backup finished.') break time.sleep(3) return size def restore(self, backup, target_volume_id, volume_file): LOG.info('Starting",
"= \"confirm backup cmd failed!\" raise exception.BackupOperationError(msg) if data['backup']['status'] == 'available': size =",
"backup['display_description'], \"name\" : backup['display_name'], \"volume_id\" : backup['volume_id'], \"backupid\" : backup_id } } jdata",
"= response.read() LOG.debug(\"RET: %r\" % ret) data = json.loads(ret) except urllib2.HTTPError, e: LOG.debug(e.code)",
"urllib2.urlopen(url) except urllib2.HTTPError, e: LOG.debug(e.code) if e.code == 404: \"\"\"backup does not exist!",
"'http://' + self._server_ip + '/v2/admin/backups/' + backup_id + '/restore' data = { \"restore\":{",
"'available': LOG.info('restore finished.') break time.sleep(3) def delete(self, backup): LOG.info('Starting delete...... backupid:%s' % backup['id'])",
"'http://' + self._server_ip + '/v2/admin/backups' data = { \"backup\":{ \"container\" : backup['container'], \"description\":",
"backup['container'], \"description\": backup['display_description'], \"name\" : backup['display_name'], \"volume_id\" : backup['volume_id'], \"backupid\" : backup_id }",
"msg = \"confirm restore cmd failed!\" raise exception.BackupOperationError(msg) if data['backup']['status'] == 'available': LOG.info('restore",
"except urllib2.HTTPError, e: LOG.debug(e.code) if e.code == 404: \"\"\"backup does not exist! already",
"= logging.getLogger(__name__) service_opts = [ cfg.StrOpt('cinder_ip', default='172.16.172.250:8776', help='ebs management node ip.'), ] CONF",
"%s MB.\" % size) LOG.info('backup finished.') break time.sleep(3) return size def restore(self, backup,",
"backup['volume_id'], 'dst': str(\"volume-\" + target_volume_id)}) backup_id = backup['id'] url = 'http://' + self._server_ip",
"= { \"restore\":{ \"volume_id\": target_volume_id } } jdata = json.dumps(data) req = urllib2.Request(url,",
"backup_id + '/restore' data = { \"restore\":{ \"volume_id\": target_volume_id } } jdata =",
"exist! already success!\"\"\" LOG.info('delete finished.') break else: msg = \"confirm delete cmd failed!\"",
"+ backup_id try: response = urllib2.urlopen(url) ret = response.read() LOG.debug(\"RET: %r\" % ret)",
"= data['backup']['object_count'] LOG.debug(\"size %s MB.\" % size) LOG.info('backup finished.') break time.sleep(3) return size",
"BackupDriver LOG = logging.getLogger(__name__) service_opts = [ cfg.StrOpt('cinder_ip', default='172.16.172.250:8776', help='ebs management node ip.'),",
"except urllib2.HTTPError, e: LOG.debug(e.code) msg = \"confirm restore cmd failed!\" raise exception.BackupOperationError(msg) if",
"= \"backup does not exist!\" LOG.info(msg) raise exception.BackupOperationError(msg) #help to decide the volume",
"} } jdata = json.dumps(data) req = urllib2.Request(url, jdata) req.add_header('Content-type', 'application/json') try: response",
"exception from oslo_log import log as logging from cinder.backup.driver import BackupDriver LOG =",
"\"backup does not exist!\" LOG.info(msg) raise exception.BackupOperationError(msg) #help to decide the volume whether",
"volume whether belongs to ebs else: msg = \"redirect delete cmd failed!\" raise",
"e: LOG.debug(e.code) if e.code == 404: msg = \"backup does not exist!\" LOG.info(msg)",
"super(SheepdogBackupDriver, self).__init__(db_driver) self.context = context self._server_ip = self._utf8(CONF.cinder_ip) @staticmethod def _utf8(s): \"\"\"Ensure string",
"self._utf8(CONF.cinder_ip) @staticmethod def _utf8(s): \"\"\"Ensure string s is utf8 (i.e. not unicode).\"\"\" if",
"\"restore\":{ \"volume_id\": target_volume_id } } jdata = json.dumps(data) req = urllib2.Request(url, jdata) req.add_header('Content-type',",
"raise exception.BackupOperationError(msg) time.sleep(3) def get_backup_driver(context): return SheepdogBackupDriver(context) if __name__ == '__main__': driver =",
"exist!\" LOG.info(msg) raise exception.BackupOperationError(msg) #help to decide the volume whether belongs to ebs",
"try: response = urllib2.urlopen(req) LOG.debug(response.read()) except urllib2.HTTPError, e: LOG.debug(e.code) msg = \"redirect backup",
"if isinstance(s, str): return s return s.encode('utf8') def backup(self, backup, volume_file): LOG.info('Starting backup......",
"LOG.info(msg) raise exception.BackupOperationError(msg) #help to decide the volume whether belongs to ebs else:",
"backup_id } } jdata = json.dumps(data) req = urllib2.Request(url, jdata) req.add_header('Content-type', 'application/json') try:",
"delete(self, backup): LOG.info('Starting delete...... backupid:%s' % backup['id']) backup_id = backup['id'] url = 'http://'",
"+ '/v2/admin/backups/' + backup_id try: urllib2.urlopen(url) except urllib2.HTTPError, e: LOG.debug(e.code) if e.code ==",
"cmd failed!\" raise exception.BackupOperationError(msg) while True: url = 'http://' + self._server_ip + '/v2/admin/backups/'",
"url = 'http://' + self._server_ip + '/v2/admin/backups/' + backup_id try: urllib2.urlopen(url) except urllib2.HTTPError,",
"data = json.loads(ret) except urllib2.HTTPError, e: LOG.debug(e.code) msg = \"confirm restore cmd failed!\"",
"dst_volume:%(dst)s' % {'src': backup['volume_id'], 'dst': str(\"volume-\" + target_volume_id)}) backup_id = backup['id'] url =",
"url = 'http://' + self._server_ip + '/v2/admin/backups/' + backup_id + '/restore' data =",
"404: \"\"\"backup does not exist! already success!\"\"\" LOG.info('delete finished.') break else: msg =",
"'/v2/admin/backups/' + backup_id try: urllib2.urlopen(url) except urllib2.HTTPError, e: LOG.debug(e.code) if e.code == 404:",
"service_opts = [ cfg.StrOpt('cinder_ip', default='172.16.172.250:8776', help='ebs management node ip.'), ] CONF = cfg.CONF",
"db_driver=None): super(SheepdogBackupDriver, self).__init__(db_driver) self.context = context self._server_ip = self._utf8(CONF.cinder_ip) @staticmethod def _utf8(s): \"\"\"Ensure",
"backup for volume:%s.' % backup['volume_id']) backup_id = backup['id'] url = 'http://' + self._server_ip",
"restore cmd failed!\" raise exception.BackupOperationError(msg) if data['backup']['status'] == 'available': LOG.info('restore finished.') break time.sleep(3)",
"'available': size = data['backup']['object_count'] LOG.debug(\"size %s MB.\" % size) LOG.info('backup finished.') break time.sleep(3)",
"src_volume:%(src)s to dst_volume:%(dst)s' % {'src': backup['volume_id'], 'dst': str(\"volume-\" + target_volume_id)}) backup_id = backup['id']",
"LOG.debug(e.code) msg = \"redirect backup cmd failed!\" raise exception.BackupOperationError(msg) while True: url =",
"True: url = 'http://' + self._server_ip + '/v2/admin/backups/' + backup_id try: urllib2.urlopen(url) except",
"[ cfg.StrOpt('cinder_ip', default='172.16.172.250:8776', help='ebs management node ip.'), ] CONF = cfg.CONF CONF.register_opts(service_opts) class",
"cfg.StrOpt('cinder_ip', default='172.16.172.250:8776', help='ebs management node ip.'), ] CONF = cfg.CONF CONF.register_opts(service_opts) class SheepdogBackupDriver(BackupDriver):",
"'http://' + self._server_ip + '/v2/admin/backups/' + backup_id try: urllib2.urlopen(url) except urllib2.HTTPError, e: LOG.debug(e.code)",
"failed!\" raise exception.BackupOperationError(msg) if data['backup']['status'] == 'available': size = data['backup']['object_count'] LOG.debug(\"size %s MB.\"",
"raise exception.BackupOperationError(msg) if data['backup']['status'] == 'available': LOG.info('restore finished.') break time.sleep(3) def delete(self, backup):",
"time.sleep(3) return size def restore(self, backup, target_volume_id, volume_file): LOG.info('Starting restore...... restore from src_volume:%(src)s",
"data = { \"backup\":{ \"container\" : backup['container'], \"description\": backup['display_description'], \"name\" : backup['display_name'], \"volume_id\"",
"% ret) data = json.loads(ret) except urllib2.HTTPError, e: LOG.debug(e.code) msg = \"confirm backup",
"try: response = urllib2.urlopen(req) LOG.debug(response.read()) except urllib2.HTTPError, e: LOG.debug(e.code) if e.code == 404:",
"except urllib2.HTTPError, e: LOG.debug(e.code) if e.code == 404: msg = \"backup does not",
"raise exception.BackupOperationError(msg) #help to decide the volume whether belongs to ebs else: msg",
"import exception from oslo_log import log as logging from cinder.backup.driver import BackupDriver LOG",
"backup['display_name'], \"volume_id\" : backup['volume_id'], \"backupid\" : backup_id } } jdata = json.dumps(data) req",
"class SheepdogBackupDriver(BackupDriver): def __init__(self, context, db_driver=None): super(SheepdogBackupDriver, self).__init__(db_driver) self.context = context self._server_ip =",
"urllib2.Request(url, jdata) req.add_header('Content-type', 'application/json') try: response = urllib2.urlopen(req) LOG.debug(response.read()) except urllib2.HTTPError, e: LOG.debug(e.code)",
"if e.code == 404: \"\"\"backup does not exist! already success!\"\"\" LOG.info('delete finished.') break",
"else: msg = \"confirm delete cmd failed!\" raise exception.BackupOperationError(msg) time.sleep(3) def get_backup_driver(context): return",
"management node ip.'), ] CONF = cfg.CONF CONF.register_opts(service_opts) class SheepdogBackupDriver(BackupDriver): def __init__(self, context,",
"% backup['volume_id']) backup_id = backup['id'] url = 'http://' + self._server_ip + '/v2/admin/backups' data",
"'/v2/admin/backups/' + backup_id req = urllib2.Request(url) req.add_header('Content-Type', 'application/json') req.get_method = lambda:'DELETE' try: response",
"if data['backup']['status'] == 'available': size = data['backup']['object_count'] LOG.debug(\"size %s MB.\" % size) LOG.info('backup",
"not unicode).\"\"\" if isinstance(s, str): return s return s.encode('utf8') def backup(self, backup, volume_file):",
"success!\"\"\" LOG.info('delete finished.') break else: msg = \"confirm delete cmd failed!\" raise exception.BackupOperationError(msg)",
"return s.encode('utf8') def backup(self, backup, volume_file): LOG.info('Starting backup...... Creating a new backup for",
"== 'available': size = data['backup']['object_count'] LOG.debug(\"size %s MB.\" % size) LOG.info('backup finished.') break",
"+ '/v2/admin/backups/' + backup_id + '/restore' data = { \"restore\":{ \"volume_id\": target_volume_id }",
"except urllib2.HTTPError, e: LOG.debug(e.code) msg = \"redirect backup cmd failed!\" raise exception.BackupOperationError(msg) while",
"+ self._server_ip + '/v2/admin/backups' data = { \"backup\":{ \"container\" : backup['container'], \"description\": backup['display_description'],",
"LOG = logging.getLogger(__name__) service_opts = [ cfg.StrOpt('cinder_ip', default='172.16.172.250:8776', help='ebs management node ip.'), ]",
"exception.BackupOperationError(msg) if data['backup']['status'] == 'available': size = data['backup']['object_count'] LOG.debug(\"size %s MB.\" % size)",
"lambda:'DELETE' try: response = urllib2.urlopen(req) LOG.debug(response.read()) except urllib2.HTTPError, e: LOG.debug(e.code) if e.code ==",
"to ebs else: msg = \"redirect delete cmd failed!\" raise exception.BackupOperationError(msg) while True:",
"the volume whether belongs to ebs else: msg = \"redirect delete cmd failed!\"",
"does not exist!\" LOG.info(msg) raise exception.BackupOperationError(msg) #help to decide the volume whether belongs",
"= \"confirm restore cmd failed!\" raise exception.BackupOperationError(msg) if data['backup']['status'] == 'available': LOG.info('restore finished.')",
"+ backup_id try: urllib2.urlopen(url) except urllib2.HTTPError, e: LOG.debug(e.code) if e.code == 404: \"\"\"backup",
"'application/json') try: response = urllib2.urlopen(req) LOG.debug(response.read()) except urllib2.HTTPError, e: LOG.debug(e.code) msg = \"redirect",
"response = urllib2.urlopen(req) LOG.debug(response.read()) except urllib2.HTTPError, e: LOG.debug(e.code) msg = \"redirect backup cmd",
"req = urllib2.Request(url) req.add_header('Content-Type', 'application/json') req.get_method = lambda:'DELETE' try: response = urllib2.urlopen(req) LOG.debug(response.read())",
"e.code == 404: \"\"\"backup does not exist! already success!\"\"\" LOG.info('delete finished.') break else:",
"is utf8 (i.e. not unicode).\"\"\" if isinstance(s, str): return s return s.encode('utf8') def",
"node ip.'), ] CONF = cfg.CONF CONF.register_opts(service_opts) class SheepdogBackupDriver(BackupDriver): def __init__(self, context, db_driver=None):",
"= urllib2.urlopen(req) LOG.debug(response.read()) except urllib2.HTTPError, e: LOG.debug(e.code) if e.code == 404: msg =",
"exception.BackupOperationError(msg) while True: url = 'http://' + self._server_ip + '/v2/admin/backups/' + backup_id try:",
"MB.\" % size) LOG.info('backup finished.') break time.sleep(3) return size def restore(self, backup, target_volume_id,",
"try: response = urllib2.urlopen(req) LOG.debug(response.read()) except urllib2.HTTPError, e: LOG.debug(e.code) msg = \"redirect restore",
"to decide the volume whether belongs to ebs else: msg = \"redirect delete",
"urllib2.HTTPError, e: LOG.debug(e.code) msg = \"confirm backup cmd failed!\" raise exception.BackupOperationError(msg) if data['backup']['status']",
": backup['volume_id'], \"backupid\" : backup_id } } jdata = json.dumps(data) req = urllib2.Request(url,",
"unicode).\"\"\" if isinstance(s, str): return s return s.encode('utf8') def backup(self, backup, volume_file): LOG.info('Starting",
"json.loads(ret) except urllib2.HTTPError, e: LOG.debug(e.code) msg = \"confirm restore cmd failed!\" raise exception.BackupOperationError(msg)",
"backup['id']) backup_id = backup['id'] url = 'http://' + self._server_ip + '/v2/admin/backups/' + backup_id",
"str): return s return s.encode('utf8') def backup(self, backup, volume_file): LOG.info('Starting backup...... Creating a",
"target_volume_id } } jdata = json.dumps(data) req = urllib2.Request(url, jdata) req.add_header('Content-type', 'application/json') try:",
"= backup['id'] url = 'http://' + self._server_ip + '/v2/admin/backups/' + backup_id req =",
"+ self._server_ip + '/v2/admin/backups/' + backup_id try: response = urllib2.urlopen(url) ret = response.read()",
": backup['container'], \"description\": backup['display_description'], \"name\" : backup['display_name'], \"volume_id\" : backup['volume_id'], \"backupid\" : backup_id",
"LOG.info('restore finished.') break time.sleep(3) def delete(self, backup): LOG.info('Starting delete...... backupid:%s' % backup['id']) backup_id",
"belongs to ebs else: msg = \"redirect delete cmd failed!\" raise exception.BackupOperationError(msg) while",
"= 'http://' + self._server_ip + '/v2/admin/backups/' + backup_id try: urllib2.urlopen(url) except urllib2.HTTPError, e:",
"self._server_ip + '/v2/admin/backups' data = { \"backup\":{ \"container\" : backup['container'], \"description\": backup['display_description'], \"name\"",
"404: msg = \"backup does not exist!\" LOG.info(msg) raise exception.BackupOperationError(msg) #help to decide",
"backup(self, backup, volume_file): LOG.info('Starting backup...... Creating a new backup for volume:%s.' % backup['volume_id'])",
"e: LOG.debug(e.code) if e.code == 404: \"\"\"backup does not exist! already success!\"\"\" LOG.info('delete",
"e: LOG.debug(e.code) msg = \"redirect backup cmd failed!\" raise exception.BackupOperationError(msg) while True: url",
"LOG.debug(e.code) msg = \"confirm backup cmd failed!\" raise exception.BackupOperationError(msg) if data['backup']['status'] == 'available':",
"not exist! already success!\"\"\" LOG.info('delete finished.') break else: msg = \"confirm delete cmd",
"backup_id = backup['id'] url = 'http://' + self._server_ip + '/v2/admin/backups' data = {",
"backup, volume_file): LOG.info('Starting backup...... Creating a new backup for volume:%s.' % backup['volume_id']) backup_id",
"= json.dumps(data) req = urllib2.Request(url, jdata) req.add_header('Content-type', 'application/json') try: response = urllib2.urlopen(req) LOG.debug(response.read())",
"self._server_ip = self._utf8(CONF.cinder_ip) @staticmethod def _utf8(s): \"\"\"Ensure string s is utf8 (i.e. not",
"req = urllib2.Request(url, jdata) req.add_header('Content-type', 'application/json') try: response = urllib2.urlopen(req) LOG.debug(response.read()) except urllib2.HTTPError,",
"exception.BackupOperationError(msg) if data['backup']['status'] == 'available': LOG.info('restore finished.') break time.sleep(3) def delete(self, backup): LOG.info('Starting",
"\"container\" : backup['container'], \"description\": backup['display_description'], \"name\" : backup['display_name'], \"volume_id\" : backup['volume_id'], \"backupid\" :",
"e: LOG.debug(e.code) msg = \"redirect restore cmd failed!\" raise exception.BackupOperationError(msg) while True: url",
"cmd failed!\" raise exception.BackupOperationError(msg) if data['backup']['status'] == 'available': LOG.info('restore finished.') break time.sleep(3) def",
"backup cmd failed!\" raise exception.BackupOperationError(msg) while True: url = 'http://' + self._server_ip +",
"= [ cfg.StrOpt('cinder_ip', default='172.16.172.250:8776', help='ebs management node ip.'), ] CONF = cfg.CONF CONF.register_opts(service_opts)",
"restore from src_volume:%(src)s to dst_volume:%(dst)s' % {'src': backup['volume_id'], 'dst': str(\"volume-\" + target_volume_id)}) backup_id",
"\"name\" : backup['display_name'], \"volume_id\" : backup['volume_id'], \"backupid\" : backup_id } } jdata =",
"from oslo_log import log as logging from cinder.backup.driver import BackupDriver LOG = logging.getLogger(__name__)",
"= urllib2.urlopen(req) LOG.debug(response.read()) except urllib2.HTTPError, e: LOG.debug(e.code) msg = \"redirect restore cmd failed!\"",
"import json import urllib2 from oslo.config import cfg from cinder import exception from",
"oslo_log import log as logging from cinder.backup.driver import BackupDriver LOG = logging.getLogger(__name__) service_opts",
"\"backup\":{ \"container\" : backup['container'], \"description\": backup['display_description'], \"name\" : backup['display_name'], \"volume_id\" : backup['volume_id'], \"backupid\"",
"size def restore(self, backup, target_volume_id, volume_file): LOG.info('Starting restore...... restore from src_volume:%(src)s to dst_volume:%(dst)s'",
"url = 'http://' + self._server_ip + '/v2/admin/backups/' + backup_id req = urllib2.Request(url) req.add_header('Content-Type',",
"urllib2.urlopen(req) LOG.debug(response.read()) except urllib2.HTTPError, e: LOG.debug(e.code) msg = \"redirect restore cmd failed!\" raise",
"backup_id try: urllib2.urlopen(url) except urllib2.HTTPError, e: LOG.debug(e.code) if e.code == 404: \"\"\"backup does",
"jdata = json.dumps(data) req = urllib2.Request(url, jdata) req.add_header('Content-type', 'application/json') try: response = urllib2.urlopen(req)",
"= json.loads(ret) except urllib2.HTTPError, e: LOG.debug(e.code) msg = \"confirm restore cmd failed!\" raise",
"urllib2.HTTPError, e: LOG.debug(e.code) msg = \"redirect restore cmd failed!\" raise exception.BackupOperationError(msg) while True:",
"= { \"backup\":{ \"container\" : backup['container'], \"description\": backup['display_description'], \"name\" : backup['display_name'], \"volume_id\" :",
"delete cmd failed!\" raise exception.BackupOperationError(msg) time.sleep(3) def get_backup_driver(context): return SheepdogBackupDriver(context) if __name__ ==",
"import BackupDriver LOG = logging.getLogger(__name__) service_opts = [ cfg.StrOpt('cinder_ip', default='172.16.172.250:8776', help='ebs management node",
"\"volume_id\" : backup['volume_id'], \"backupid\" : backup_id } } jdata = json.dumps(data) req =",
"req.add_header('Content-Type', 'application/json') req.get_method = lambda:'DELETE' try: response = urllib2.urlopen(req) LOG.debug(response.read()) except urllib2.HTTPError, e:",
"urllib2.HTTPError, e: LOG.debug(e.code) msg = \"confirm restore cmd failed!\" raise exception.BackupOperationError(msg) if data['backup']['status']",
"'/v2/admin/backups/' + backup_id try: response = urllib2.urlopen(url) ret = response.read() LOG.debug(\"RET: %r\" %",
"import cfg from cinder import exception from oslo_log import log as logging from",
": backup_id } } jdata = json.dumps(data) req = urllib2.Request(url, jdata) req.add_header('Content-type', 'application/json')",
"\"confirm restore cmd failed!\" raise exception.BackupOperationError(msg) if data['backup']['status'] == 'available': LOG.info('restore finished.') break",
"backupid:%s' % backup['id']) backup_id = backup['id'] url = 'http://' + self._server_ip + '/v2/admin/backups/'",
"\"redirect restore cmd failed!\" raise exception.BackupOperationError(msg) while True: url = 'http://' + self._server_ip",
"s is utf8 (i.e. not unicode).\"\"\" if isinstance(s, str): return s return s.encode('utf8')",
"backup['volume_id'], \"backupid\" : backup_id } } jdata = json.dumps(data) req = urllib2.Request(url, jdata)",
"= \"redirect backup cmd failed!\" raise exception.BackupOperationError(msg) while True: url = 'http://' +",
"True: url = 'http://' + self._server_ip + '/v2/admin/backups/' + backup_id try: response =",
"= 'http://' + self._server_ip + '/v2/admin/backups' data = { \"backup\":{ \"container\" : backup['container'],",
"= json.loads(ret) except urllib2.HTTPError, e: LOG.debug(e.code) msg = \"confirm backup cmd failed!\" raise",
"backup_id req = urllib2.Request(url) req.add_header('Content-Type', 'application/json') req.get_method = lambda:'DELETE' try: response = urllib2.urlopen(req)",
"urllib2.HTTPError, e: LOG.debug(e.code) msg = \"redirect backup cmd failed!\" raise exception.BackupOperationError(msg) while True:",
"SheepdogBackupDriver(BackupDriver): def __init__(self, context, db_driver=None): super(SheepdogBackupDriver, self).__init__(db_driver) self.context = context self._server_ip = self._utf8(CONF.cinder_ip)",
"\"redirect delete cmd failed!\" raise exception.BackupOperationError(msg) while True: url = 'http://' + self._server_ip",
"size = data['backup']['object_count'] LOG.debug(\"size %s MB.\" % size) LOG.info('backup finished.') break time.sleep(3) return",
"= \"redirect delete cmd failed!\" raise exception.BackupOperationError(msg) while True: url = 'http://' +",
"data = json.loads(ret) except urllib2.HTTPError, e: LOG.debug(e.code) msg = \"confirm backup cmd failed!\"",
"req.get_method = lambda:'DELETE' try: response = urllib2.urlopen(req) LOG.debug(response.read()) except urllib2.HTTPError, e: LOG.debug(e.code) if",
"<gh_stars>0 #coding:utf-8 import time import json import urllib2 from oslo.config import cfg from",
"from src_volume:%(src)s to dst_volume:%(dst)s' % {'src': backup['volume_id'], 'dst': str(\"volume-\" + target_volume_id)}) backup_id =",
"= backup['id'] url = 'http://' + self._server_ip + '/v2/admin/backups/' + backup_id + '/restore'",
"ip.'), ] CONF = cfg.CONF CONF.register_opts(service_opts) class SheepdogBackupDriver(BackupDriver): def __init__(self, context, db_driver=None): super(SheepdogBackupDriver,",
"cfg from cinder import exception from oslo_log import log as logging from cinder.backup.driver",
"\"volume_id\": target_volume_id } } jdata = json.dumps(data) req = urllib2.Request(url, jdata) req.add_header('Content-type', 'application/json')",
"'/restore' data = { \"restore\":{ \"volume_id\": target_volume_id } } jdata = json.dumps(data) req",
"'http://' + self._server_ip + '/v2/admin/backups/' + backup_id req = urllib2.Request(url) req.add_header('Content-Type', 'application/json') req.get_method",
"try: urllib2.urlopen(url) except urllib2.HTTPError, e: LOG.debug(e.code) if e.code == 404: \"\"\"backup does not",
"from cinder.backup.driver import BackupDriver LOG = logging.getLogger(__name__) service_opts = [ cfg.StrOpt('cinder_ip', default='172.16.172.250:8776', help='ebs",
"] CONF = cfg.CONF CONF.register_opts(service_opts) class SheepdogBackupDriver(BackupDriver): def __init__(self, context, db_driver=None): super(SheepdogBackupDriver, self).__init__(db_driver)",
"urllib2.urlopen(req) LOG.debug(response.read()) except urllib2.HTTPError, e: LOG.debug(e.code) msg = \"redirect backup cmd failed!\" raise",
"%r\" % ret) data = json.loads(ret) except urllib2.HTTPError, e: LOG.debug(e.code) msg = \"confirm",
"__init__(self, context, db_driver=None): super(SheepdogBackupDriver, self).__init__(db_driver) self.context = context self._server_ip = self._utf8(CONF.cinder_ip) @staticmethod def",
"urllib2.HTTPError, e: LOG.debug(e.code) if e.code == 404: \"\"\"backup does not exist! already success!\"\"\"",
"json.dumps(data) req = urllib2.Request(url, jdata) req.add_header('Content-type', 'application/json') try: response = urllib2.urlopen(req) LOG.debug(response.read()) except",
"raise exception.BackupOperationError(msg) if data['backup']['status'] == 'available': size = data['backup']['object_count'] LOG.debug(\"size %s MB.\" %",
"raise exception.BackupOperationError(msg) while True: url = 'http://' + self._server_ip + '/v2/admin/backups/' + backup_id",
"= urllib2.urlopen(req) LOG.debug(response.read()) except urllib2.HTTPError, e: LOG.debug(e.code) msg = \"redirect backup cmd failed!\"",
"response = urllib2.urlopen(url) ret = response.read() LOG.debug(\"RET: %r\" % ret) data = json.loads(ret)",
"== 'available': LOG.info('restore finished.') break time.sleep(3) def delete(self, backup): LOG.info('Starting delete...... backupid:%s' %",
"restore(self, backup, target_volume_id, volume_file): LOG.info('Starting restore...... restore from src_volume:%(src)s to dst_volume:%(dst)s' % {'src':",
"try: response = urllib2.urlopen(url) ret = response.read() LOG.debug(\"RET: %r\" % ret) data =",
"volume_file): LOG.info('Starting restore...... restore from src_volume:%(src)s to dst_volume:%(dst)s' % {'src': backup['volume_id'], 'dst': str(\"volume-\"",
"LOG.debug(e.code) if e.code == 404: msg = \"backup does not exist!\" LOG.info(msg) raise",
"\"\"\"backup does not exist! already success!\"\"\" LOG.info('delete finished.') break else: msg = \"confirm",
"s.encode('utf8') def backup(self, backup, volume_file): LOG.info('Starting backup...... Creating a new backup for volume:%s.'",
"LOG.debug(e.code) if e.code == 404: \"\"\"backup does not exist! already success!\"\"\" LOG.info('delete finished.')",
"ebs else: msg = \"redirect delete cmd failed!\" raise exception.BackupOperationError(msg) while True: url",
"= 'http://' + self._server_ip + '/v2/admin/backups/' + backup_id req = urllib2.Request(url) req.add_header('Content-Type', 'application/json')",
"whether belongs to ebs else: msg = \"redirect delete cmd failed!\" raise exception.BackupOperationError(msg)",
"LOG.debug(response.read()) except urllib2.HTTPError, e: LOG.debug(e.code) if e.code == 404: msg = \"backup does",
"except urllib2.HTTPError, e: LOG.debug(e.code) msg = \"confirm backup cmd failed!\" raise exception.BackupOperationError(msg) if",
"json import urllib2 from oslo.config import cfg from cinder import exception from oslo_log",
"def _utf8(s): \"\"\"Ensure string s is utf8 (i.e. not unicode).\"\"\" if isinstance(s, str):",
"time import json import urllib2 from oslo.config import cfg from cinder import exception",
"'/v2/admin/backups' data = { \"backup\":{ \"container\" : backup['container'], \"description\": backup['display_description'], \"name\" : backup['display_name'],",
"default='172.16.172.250:8776', help='ebs management node ip.'), ] CONF = cfg.CONF CONF.register_opts(service_opts) class SheepdogBackupDriver(BackupDriver): def",
"e: LOG.debug(e.code) msg = \"confirm backup cmd failed!\" raise exception.BackupOperationError(msg) if data['backup']['status'] ==",
"return size def restore(self, backup, target_volume_id, volume_file): LOG.info('Starting restore...... restore from src_volume:%(src)s to",
"CONF = cfg.CONF CONF.register_opts(service_opts) class SheepdogBackupDriver(BackupDriver): def __init__(self, context, db_driver=None): super(SheepdogBackupDriver, self).__init__(db_driver) self.context",
"% size) LOG.info('backup finished.') break time.sleep(3) return size def restore(self, backup, target_volume_id, volume_file):",
"response = urllib2.urlopen(req) LOG.debug(response.read()) except urllib2.HTTPError, e: LOG.debug(e.code) if e.code == 404: msg",
"LOG.debug(\"size %s MB.\" % size) LOG.info('backup finished.') break time.sleep(3) return size def restore(self,",
"CONF.register_opts(service_opts) class SheepdogBackupDriver(BackupDriver): def __init__(self, context, db_driver=None): super(SheepdogBackupDriver, self).__init__(db_driver) self.context = context self._server_ip",
"exception.BackupOperationError(msg) time.sleep(3) def get_backup_driver(context): return SheepdogBackupDriver(context) if __name__ == '__main__': driver = SheepdogBackupDriver()",
"\"description\": backup['display_description'], \"name\" : backup['display_name'], \"volume_id\" : backup['volume_id'], \"backupid\" : backup_id } }",
"volume:%s.' % backup['volume_id']) backup_id = backup['id'] url = 'http://' + self._server_ip + '/v2/admin/backups'",
"{'src': backup['volume_id'], 'dst': str(\"volume-\" + target_volume_id)}) backup_id = backup['id'] url = 'http://' +",
"#coding:utf-8 import time import json import urllib2 from oslo.config import cfg from cinder",
"time.sleep(3) def delete(self, backup): LOG.info('Starting delete...... backupid:%s' % backup['id']) backup_id = backup['id'] url",
"data = { \"restore\":{ \"volume_id\": target_volume_id } } jdata = json.dumps(data) req =",
"= lambda:'DELETE' try: response = urllib2.urlopen(req) LOG.debug(response.read()) except urllib2.HTTPError, e: LOG.debug(e.code) if e.code",
"finished.') break else: msg = \"confirm delete cmd failed!\" raise exception.BackupOperationError(msg) time.sleep(3) def",
"'http://' + self._server_ip + '/v2/admin/backups/' + backup_id try: response = urllib2.urlopen(url) ret =",
"failed!\" raise exception.BackupOperationError(msg) time.sleep(3) def get_backup_driver(context): return SheepdogBackupDriver(context) if __name__ == '__main__': driver",
"utf8 (i.e. not unicode).\"\"\" if isinstance(s, str): return s return s.encode('utf8') def backup(self,",
"\"confirm backup cmd failed!\" raise exception.BackupOperationError(msg) if data['backup']['status'] == 'available': size = data['backup']['object_count']",
"backup['id'] url = 'http://' + self._server_ip + '/v2/admin/backups/' + backup_id req = urllib2.Request(url)",
"cmd failed!\" raise exception.BackupOperationError(msg) time.sleep(3) def get_backup_driver(context): return SheepdogBackupDriver(context) if __name__ == '__main__':",
"req.add_header('Content-type', 'application/json') try: response = urllib2.urlopen(req) LOG.debug(response.read()) except urllib2.HTTPError, e: LOG.debug(e.code) msg =",
"+ '/v2/admin/backups/' + backup_id try: response = urllib2.urlopen(url) ret = response.read() LOG.debug(\"RET: %r\"",
"urllib2.HTTPError, e: LOG.debug(e.code) if e.code == 404: msg = \"backup does not exist!\"",
"= self._utf8(CONF.cinder_ip) @staticmethod def _utf8(s): \"\"\"Ensure string s is utf8 (i.e. not unicode).\"\"\"",
"string s is utf8 (i.e. not unicode).\"\"\" if isinstance(s, str): return s return",
"log as logging from cinder.backup.driver import BackupDriver LOG = logging.getLogger(__name__) service_opts = [",
"backup['id'] url = 'http://' + self._server_ip + '/v2/admin/backups/' + backup_id + '/restore' data",
"self).__init__(db_driver) self.context = context self._server_ip = self._utf8(CONF.cinder_ip) @staticmethod def _utf8(s): \"\"\"Ensure string s",
"\"\"\"Ensure string s is utf8 (i.e. not unicode).\"\"\" if isinstance(s, str): return s",
"for volume:%s.' % backup['volume_id']) backup_id = backup['id'] url = 'http://' + self._server_ip +",
"msg = \"backup does not exist!\" LOG.info(msg) raise exception.BackupOperationError(msg) #help to decide the",
"backup['id'] url = 'http://' + self._server_ip + '/v2/admin/backups' data = { \"backup\":{ \"container\"",
"#help to decide the volume whether belongs to ebs else: msg = \"redirect",
"LOG.debug(\"RET: %r\" % ret) data = json.loads(ret) except urllib2.HTTPError, e: LOG.debug(e.code) msg =",
"cfg.CONF CONF.register_opts(service_opts) class SheepdogBackupDriver(BackupDriver): def __init__(self, context, db_driver=None): super(SheepdogBackupDriver, self).__init__(db_driver) self.context = context",
"urllib2.urlopen(req) LOG.debug(response.read()) except urllib2.HTTPError, e: LOG.debug(e.code) if e.code == 404: msg = \"backup",
"LOG.info('Starting backup...... Creating a new backup for volume:%s.' % backup['volume_id']) backup_id = backup['id']",
"+ backup_id + '/restore' data = { \"restore\":{ \"volume_id\": target_volume_id } } jdata",
"% {'src': backup['volume_id'], 'dst': str(\"volume-\" + target_volume_id)}) backup_id = backup['id'] url = 'http://'",
"+ '/v2/admin/backups/' + backup_id req = urllib2.Request(url) req.add_header('Content-Type', 'application/json') req.get_method = lambda:'DELETE' try:",
"backup_id = backup['id'] url = 'http://' + self._server_ip + '/v2/admin/backups/' + backup_id +",
"+ target_volume_id)}) backup_id = backup['id'] url = 'http://' + self._server_ip + '/v2/admin/backups/' +",
"return s return s.encode('utf8') def backup(self, backup, volume_file): LOG.info('Starting backup...... Creating a new",
"+ backup_id req = urllib2.Request(url) req.add_header('Content-Type', 'application/json') req.get_method = lambda:'DELETE' try: response =",
"while True: url = 'http://' + self._server_ip + '/v2/admin/backups/' + backup_id try: urllib2.urlopen(url)",
"while True: url = 'http://' + self._server_ip + '/v2/admin/backups/' + backup_id try: response",
"target_volume_id)}) backup_id = backup['id'] url = 'http://' + self._server_ip + '/v2/admin/backups/' + backup_id",
"urllib2.urlopen(url) ret = response.read() LOG.debug(\"RET: %r\" % ret) data = json.loads(ret) except urllib2.HTTPError,",
"= \"confirm delete cmd failed!\" raise exception.BackupOperationError(msg) time.sleep(3) def get_backup_driver(context): return SheepdogBackupDriver(context) if",
"failed!\" raise exception.BackupOperationError(msg) if data['backup']['status'] == 'available': LOG.info('restore finished.') break time.sleep(3) def delete(self,",
"LOG.debug(e.code) msg = \"redirect restore cmd failed!\" raise exception.BackupOperationError(msg) while True: url =",
"from oslo.config import cfg from cinder import exception from oslo_log import log as",
"msg = \"confirm backup cmd failed!\" raise exception.BackupOperationError(msg) if data['backup']['status'] == 'available': size",
"break time.sleep(3) def delete(self, backup): LOG.info('Starting delete...... backupid:%s' % backup['id']) backup_id = backup['id']",
"delete cmd failed!\" raise exception.BackupOperationError(msg) while True: url = 'http://' + self._server_ip +",
"else: msg = \"redirect delete cmd failed!\" raise exception.BackupOperationError(msg) while True: url =",
"+ '/restore' data = { \"restore\":{ \"volume_id\": target_volume_id } } jdata = json.dumps(data)",
"import urllib2 from oslo.config import cfg from cinder import exception from oslo_log import",
"= urllib2.urlopen(url) ret = response.read() LOG.debug(\"RET: %r\" % ret) data = json.loads(ret) except",
"msg = \"redirect delete cmd failed!\" raise exception.BackupOperationError(msg) while True: url = 'http://'",
"backup, target_volume_id, volume_file): LOG.info('Starting restore...... restore from src_volume:%(src)s to dst_volume:%(dst)s' % {'src': backup['volume_id'],",
"help='ebs management node ip.'), ] CONF = cfg.CONF CONF.register_opts(service_opts) class SheepdogBackupDriver(BackupDriver): def __init__(self,",
"restore cmd failed!\" raise exception.BackupOperationError(msg) while True: url = 'http://' + self._server_ip +",
"response.read() LOG.debug(\"RET: %r\" % ret) data = json.loads(ret) except urllib2.HTTPError, e: LOG.debug(e.code) msg",
"str(\"volume-\" + target_volume_id)}) backup_id = backup['id'] url = 'http://' + self._server_ip + '/v2/admin/backups/'",
": backup['display_name'], \"volume_id\" : backup['volume_id'], \"backupid\" : backup_id } } jdata = json.dumps(data)",
"@staticmethod def _utf8(s): \"\"\"Ensure string s is utf8 (i.e. not unicode).\"\"\" if isinstance(s,",
"isinstance(s, str): return s return s.encode('utf8') def backup(self, backup, volume_file): LOG.info('Starting backup...... Creating",
"restore...... restore from src_volume:%(src)s to dst_volume:%(dst)s' % {'src': backup['volume_id'], 'dst': str(\"volume-\" + target_volume_id)})",
"backup...... Creating a new backup for volume:%s.' % backup['volume_id']) backup_id = backup['id'] url",
"self._server_ip + '/v2/admin/backups/' + backup_id req = urllib2.Request(url) req.add_header('Content-Type', 'application/json') req.get_method = lambda:'DELETE'",
"from cinder import exception from oslo_log import log as logging from cinder.backup.driver import",
"if e.code == 404: msg = \"backup does not exist!\" LOG.info(msg) raise exception.BackupOperationError(msg)",
"\"confirm delete cmd failed!\" raise exception.BackupOperationError(msg) time.sleep(3) def get_backup_driver(context): return SheepdogBackupDriver(context) if __name__",
"logging from cinder.backup.driver import BackupDriver LOG = logging.getLogger(__name__) service_opts = [ cfg.StrOpt('cinder_ip', default='172.16.172.250:8776',",
"data['backup']['status'] == 'available': size = data['backup']['object_count'] LOG.debug(\"size %s MB.\" % size) LOG.info('backup finished.')",
"new backup for volume:%s.' % backup['volume_id']) backup_id = backup['id'] url = 'http://' +",
"target_volume_id, volume_file): LOG.info('Starting restore...... restore from src_volume:%(src)s to dst_volume:%(dst)s' % {'src': backup['volume_id'], 'dst':",
"finished.') break time.sleep(3) def delete(self, backup): LOG.info('Starting delete...... backupid:%s' % backup['id']) backup_id =",
"context self._server_ip = self._utf8(CONF.cinder_ip) @staticmethod def _utf8(s): \"\"\"Ensure string s is utf8 (i.e.",
"+ self._server_ip + '/v2/admin/backups/' + backup_id req = urllib2.Request(url) req.add_header('Content-Type', 'application/json') req.get_method =",
"} jdata = json.dumps(data) req = urllib2.Request(url, jdata) req.add_header('Content-type', 'application/json') try: response =",
"cinder import exception from oslo_log import log as logging from cinder.backup.driver import BackupDriver",
"% ret) data = json.loads(ret) except urllib2.HTTPError, e: LOG.debug(e.code) msg = \"confirm restore",
"\"backupid\" : backup_id } } jdata = json.dumps(data) req = urllib2.Request(url, jdata) req.add_header('Content-type',",
"ret) data = json.loads(ret) except urllib2.HTTPError, e: LOG.debug(e.code) msg = \"confirm backup cmd",
"+ self._server_ip + '/v2/admin/backups/' + backup_id + '/restore' data = { \"restore\":{ \"volume_id\":",
"decide the volume whether belongs to ebs else: msg = \"redirect delete cmd",
"a new backup for volume:%s.' % backup['volume_id']) backup_id = backup['id'] url = 'http://'",
"data['backup']['object_count'] LOG.debug(\"size %s MB.\" % size) LOG.info('backup finished.') break time.sleep(3) return size def",
"{ \"backup\":{ \"container\" : backup['container'], \"description\": backup['display_description'], \"name\" : backup['display_name'], \"volume_id\" : backup['volume_id'],",
"url = 'http://' + self._server_ip + '/v2/admin/backups' data = { \"backup\":{ \"container\" :",
"if data['backup']['status'] == 'available': LOG.info('restore finished.') break time.sleep(3) def delete(self, backup): LOG.info('Starting delete......",
"urllib2.Request(url) req.add_header('Content-Type', 'application/json') req.get_method = lambda:'DELETE' try: response = urllib2.urlopen(req) LOG.debug(response.read()) except urllib2.HTTPError,",
"backup): LOG.info('Starting delete...... backupid:%s' % backup['id']) backup_id = backup['id'] url = 'http://' +",
"= context self._server_ip = self._utf8(CONF.cinder_ip) @staticmethod def _utf8(s): \"\"\"Ensure string s is utf8"
] |
[
"raise ValueError def normalize_phone_number(phone): phone = phone.replace(\"+\", \"\") phone = phone.replace(\" \", \"\")",
"= phone.replace(\"+\", \"\") phone = phone.replace(\" \", \"\") if len(phone) == 10: phone",
"app.common.conf import PHONE_NUMBER_VALIDATOR def phone_number_valid(phone_number): if phone_number.isdigit(): if PHONE_NUMBER_VALIDATOR.match(phone_number): return True raise ValueError",
"phone = phone.replace(\"+\", \"\") phone = phone.replace(\" \", \"\") if len(phone) == 10:",
"from app.common.conf import PHONE_NUMBER_VALIDATOR def phone_number_valid(phone_number): if phone_number.isdigit(): if PHONE_NUMBER_VALIDATOR.match(phone_number): return True raise",
"PHONE_NUMBER_VALIDATOR.match(phone_number): return True raise ValueError def normalize_phone_number(phone): phone = phone.replace(\"+\", \"\") phone =",
"phone.replace(\"+\", \"\") phone = phone.replace(\" \", \"\") if len(phone) == 10: phone =",
"phone_number.isdigit(): if PHONE_NUMBER_VALIDATOR.match(phone_number): return True raise ValueError def normalize_phone_number(phone): phone = phone.replace(\"+\", \"\")",
"import PHONE_NUMBER_VALIDATOR def phone_number_valid(phone_number): if phone_number.isdigit(): if PHONE_NUMBER_VALIDATOR.match(phone_number): return True raise ValueError def",
"PHONE_NUMBER_VALIDATOR def phone_number_valid(phone_number): if phone_number.isdigit(): if PHONE_NUMBER_VALIDATOR.match(phone_number): return True raise ValueError def normalize_phone_number(phone):",
"def normalize_phone_number(phone): phone = phone.replace(\"+\", \"\") phone = phone.replace(\" \", \"\") if len(phone)",
"def phone_number_valid(phone_number): if phone_number.isdigit(): if PHONE_NUMBER_VALIDATOR.match(phone_number): return True raise ValueError def normalize_phone_number(phone): phone",
"<filename>app/common/helpers.py<gh_stars>1-10 from app.common.conf import PHONE_NUMBER_VALIDATOR def phone_number_valid(phone_number): if phone_number.isdigit(): if PHONE_NUMBER_VALIDATOR.match(phone_number): return True",
"True raise ValueError def normalize_phone_number(phone): phone = phone.replace(\"+\", \"\") phone = phone.replace(\" \",",
"return True raise ValueError def normalize_phone_number(phone): phone = phone.replace(\"+\", \"\") phone = phone.replace(\"",
"if phone_number.isdigit(): if PHONE_NUMBER_VALIDATOR.match(phone_number): return True raise ValueError def normalize_phone_number(phone): phone = phone.replace(\"+\",",
"ValueError def normalize_phone_number(phone): phone = phone.replace(\"+\", \"\") phone = phone.replace(\" \", \"\") if",
"= phone.replace(\" \", \"\") if len(phone) == 10: phone = f\"91{phone}\" return phone",
"phone_number_valid(phone_number): if phone_number.isdigit(): if PHONE_NUMBER_VALIDATOR.match(phone_number): return True raise ValueError def normalize_phone_number(phone): phone =",
"\"\") phone = phone.replace(\" \", \"\") if len(phone) == 10: phone = f\"91{phone}\"",
"phone = phone.replace(\" \", \"\") if len(phone) == 10: phone = f\"91{phone}\" return",
"if PHONE_NUMBER_VALIDATOR.match(phone_number): return True raise ValueError def normalize_phone_number(phone): phone = phone.replace(\"+\", \"\") phone",
"normalize_phone_number(phone): phone = phone.replace(\"+\", \"\") phone = phone.replace(\" \", \"\") if len(phone) =="
] |
[
"ai ts=4 sts=4 et sw=4 # Copyright 2016 National Research Foundation (South African",
"ap_name = \"mkat_sim/ap/1\" dev_info = PyTango.DbDevInfo() dev_info.server = \"mkat-tango-AP-DS/test\" dev_info._class = \"MkatAntennaPositioner\" dev_info.name",
"(South African Radio Astronomy Observatory) # BSD license - see LICENSE for details",
"division, print_function from future import standard_library standard_library.install_aliases() import PyTango ap_name = \"mkat_sim/ap/1\" dev_info",
"dev_info.server = \"mkat-tango-AP-DS/test\" dev_info._class = \"MkatAntennaPositioner\" dev_info.name = ap_name db = PyTango.Database() db.add_device(dev_info)",
"vim:fileencoding=utf8 ai ts=4 sts=4 et sw=4 # Copyright 2016 National Research Foundation (South",
"\"mkat-tango-AP-DS/test\" dev_info._class = \"MkatAntennaPositioner\" dev_info.name = ap_name db = PyTango.Database() db.add_device(dev_info) print(\"Registration of",
"PyTango.DbDevInfo() dev_info.server = \"mkat-tango-AP-DS/test\" dev_info._class = \"MkatAntennaPositioner\" dev_info.name = ap_name db = PyTango.Database()",
"# BSD license - see LICENSE for details from __future__ import absolute_import, division,",
"LICENSE for details from __future__ import absolute_import, division, print_function from future import standard_library",
"Research Foundation (South African Radio Astronomy Observatory) # BSD license - see LICENSE",
"sw=4 # Copyright 2016 National Research Foundation (South African Radio Astronomy Observatory) #",
"PyTango ap_name = \"mkat_sim/ap/1\" dev_info = PyTango.DbDevInfo() dev_info.server = \"mkat-tango-AP-DS/test\" dev_info._class = \"MkatAntennaPositioner\"",
"-*- coding: utf8 -*- # vim:fileencoding=utf8 ai ts=4 sts=4 et sw=4 # Copyright",
"details from __future__ import absolute_import, division, print_function from future import standard_library standard_library.install_aliases() import",
"# vim:fileencoding=utf8 ai ts=4 sts=4 et sw=4 # Copyright 2016 National Research Foundation",
"Foundation (South African Radio Astronomy Observatory) # BSD license - see LICENSE for",
"standard_library standard_library.install_aliases() import PyTango ap_name = \"mkat_sim/ap/1\" dev_info = PyTango.DbDevInfo() dev_info.server = \"mkat-tango-AP-DS/test\"",
"Observatory) # BSD license - see LICENSE for details from __future__ import absolute_import,",
"__future__ import absolute_import, division, print_function from future import standard_library standard_library.install_aliases() import PyTango ap_name",
"\"mkat_sim/ap/1\" dev_info = PyTango.DbDevInfo() dev_info.server = \"mkat-tango-AP-DS/test\" dev_info._class = \"MkatAntennaPositioner\" dev_info.name = ap_name",
"see LICENSE for details from __future__ import absolute_import, division, print_function from future import",
"-*- # vim:fileencoding=utf8 ai ts=4 sts=4 et sw=4 # Copyright 2016 National Research",
"absolute_import, division, print_function from future import standard_library standard_library.install_aliases() import PyTango ap_name = \"mkat_sim/ap/1\"",
"register_ap_ds.py # -*- coding: utf8 -*- # vim:fileencoding=utf8 ai ts=4 sts=4 et sw=4",
"future import standard_library standard_library.install_aliases() import PyTango ap_name = \"mkat_sim/ap/1\" dev_info = PyTango.DbDevInfo() dev_info.server",
"- see LICENSE for details from __future__ import absolute_import, division, print_function from future",
"standard_library.install_aliases() import PyTango ap_name = \"mkat_sim/ap/1\" dev_info = PyTango.DbDevInfo() dev_info.server = \"mkat-tango-AP-DS/test\" dev_info._class",
"<reponame>ska-sa/mkat-tango # register_ap_ds.py # -*- coding: utf8 -*- # vim:fileencoding=utf8 ai ts=4 sts=4",
"# register_ap_ds.py # -*- coding: utf8 -*- # vim:fileencoding=utf8 ai ts=4 sts=4 et",
"= \"mkat_sim/ap/1\" dev_info = PyTango.DbDevInfo() dev_info.server = \"mkat-tango-AP-DS/test\" dev_info._class = \"MkatAntennaPositioner\" dev_info.name =",
"\"MkatAntennaPositioner\" dev_info.name = ap_name db = PyTango.Database() db.add_device(dev_info) print(\"Registration of antenna positioner Successful\")",
"import standard_library standard_library.install_aliases() import PyTango ap_name = \"mkat_sim/ap/1\" dev_info = PyTango.DbDevInfo() dev_info.server =",
"= PyTango.DbDevInfo() dev_info.server = \"mkat-tango-AP-DS/test\" dev_info._class = \"MkatAntennaPositioner\" dev_info.name = ap_name db =",
"BSD license - see LICENSE for details from __future__ import absolute_import, division, print_function",
"license - see LICENSE for details from __future__ import absolute_import, division, print_function from",
"dev_info = PyTango.DbDevInfo() dev_info.server = \"mkat-tango-AP-DS/test\" dev_info._class = \"MkatAntennaPositioner\" dev_info.name = ap_name db",
"# -*- coding: utf8 -*- # vim:fileencoding=utf8 ai ts=4 sts=4 et sw=4 #",
"dev_info._class = \"MkatAntennaPositioner\" dev_info.name = ap_name db = PyTango.Database() db.add_device(dev_info) print(\"Registration of antenna",
"coding: utf8 -*- # vim:fileencoding=utf8 ai ts=4 sts=4 et sw=4 # Copyright 2016",
"ts=4 sts=4 et sw=4 # Copyright 2016 National Research Foundation (South African Radio",
"utf8 -*- # vim:fileencoding=utf8 ai ts=4 sts=4 et sw=4 # Copyright 2016 National",
"National Research Foundation (South African Radio Astronomy Observatory) # BSD license - see",
"sts=4 et sw=4 # Copyright 2016 National Research Foundation (South African Radio Astronomy",
"African Radio Astronomy Observatory) # BSD license - see LICENSE for details from",
"Copyright 2016 National Research Foundation (South African Radio Astronomy Observatory) # BSD license",
"import PyTango ap_name = \"mkat_sim/ap/1\" dev_info = PyTango.DbDevInfo() dev_info.server = \"mkat-tango-AP-DS/test\" dev_info._class =",
"= \"MkatAntennaPositioner\" dev_info.name = ap_name db = PyTango.Database() db.add_device(dev_info) print(\"Registration of antenna positioner",
"print_function from future import standard_library standard_library.install_aliases() import PyTango ap_name = \"mkat_sim/ap/1\" dev_info =",
"import absolute_import, division, print_function from future import standard_library standard_library.install_aliases() import PyTango ap_name =",
"et sw=4 # Copyright 2016 National Research Foundation (South African Radio Astronomy Observatory)",
"for details from __future__ import absolute_import, division, print_function from future import standard_library standard_library.install_aliases()",
"from future import standard_library standard_library.install_aliases() import PyTango ap_name = \"mkat_sim/ap/1\" dev_info = PyTango.DbDevInfo()",
"= \"mkat-tango-AP-DS/test\" dev_info._class = \"MkatAntennaPositioner\" dev_info.name = ap_name db = PyTango.Database() db.add_device(dev_info) print(\"Registration",
"Radio Astronomy Observatory) # BSD license - see LICENSE for details from __future__",
"from __future__ import absolute_import, division, print_function from future import standard_library standard_library.install_aliases() import PyTango",
"2016 National Research Foundation (South African Radio Astronomy Observatory) # BSD license -",
"# Copyright 2016 National Research Foundation (South African Radio Astronomy Observatory) # BSD",
"Astronomy Observatory) # BSD license - see LICENSE for details from __future__ import"
] |
[
"= page_soup.find_all('div',class_ = 'update-box') newz = [] for new in news: newz.append([new.strong.text,new.a.text.strip(),new.a['href']]) return",
"BeautifulSoup(page_html,\"html.parser\") news = page_soup.find_all('div',class_ = 'update-box') newz = [] for new in news:",
"uClient.read() uClient.close() page_soup = BeautifulSoup(page_html,\"html.parser\") news = page_soup.find_all('div',class_ = 'update-box') newz = []",
"BeautifulSoup def get_go(): url = \"https://www.mohfw.gov.in/\" uClient = urllib.request.urlopen(url) page_html = uClient.read() uClient.close()",
"get_go(): url = \"https://www.mohfw.gov.in/\" uClient = urllib.request.urlopen(url) page_html = uClient.read() uClient.close() page_soup =",
"= BeautifulSoup(page_html,\"html.parser\") news = page_soup.find_all('div',class_ = 'update-box') newz = [] for new in",
"page_soup.find_all('div',class_ = 'update-box') newz = [] for new in news: newz.append([new.strong.text,new.a.text.strip(),new.a['href']]) return newz",
"urllib.request.urlopen(url) page_html = uClient.read() uClient.close() page_soup = BeautifulSoup(page_html,\"html.parser\") news = page_soup.find_all('div',class_ = 'update-box')",
"\"https://www.mohfw.gov.in/\" uClient = urllib.request.urlopen(url) page_html = uClient.read() uClient.close() page_soup = BeautifulSoup(page_html,\"html.parser\") news =",
"page_soup = BeautifulSoup(page_html,\"html.parser\") news = page_soup.find_all('div',class_ = 'update-box') newz = [] for new",
"uClient.close() page_soup = BeautifulSoup(page_html,\"html.parser\") news = page_soup.find_all('div',class_ = 'update-box') newz = [] for",
"bs4 import BeautifulSoup def get_go(): url = \"https://www.mohfw.gov.in/\" uClient = urllib.request.urlopen(url) page_html =",
"from bs4 import BeautifulSoup def get_go(): url = \"https://www.mohfw.gov.in/\" uClient = urllib.request.urlopen(url) page_html",
"def get_go(): url = \"https://www.mohfw.gov.in/\" uClient = urllib.request.urlopen(url) page_html = uClient.read() uClient.close() page_soup",
"news = page_soup.find_all('div',class_ = 'update-box') newz = [] for new in news: newz.append([new.strong.text,new.a.text.strip(),new.a['href']])",
"page_html = uClient.read() uClient.close() page_soup = BeautifulSoup(page_html,\"html.parser\") news = page_soup.find_all('div',class_ = 'update-box') newz",
"= uClient.read() uClient.close() page_soup = BeautifulSoup(page_html,\"html.parser\") news = page_soup.find_all('div',class_ = 'update-box') newz =",
"= \"https://www.mohfw.gov.in/\" uClient = urllib.request.urlopen(url) page_html = uClient.read() uClient.close() page_soup = BeautifulSoup(page_html,\"html.parser\") news",
"uClient = urllib.request.urlopen(url) page_html = uClient.read() uClient.close() page_soup = BeautifulSoup(page_html,\"html.parser\") news = page_soup.find_all('div',class_",
"= urllib.request.urlopen(url) page_html = uClient.read() uClient.close() page_soup = BeautifulSoup(page_html,\"html.parser\") news = page_soup.find_all('div',class_ =",
"import urllib.request from bs4 import BeautifulSoup def get_go(): url = \"https://www.mohfw.gov.in/\" uClient =",
"urllib.request from bs4 import BeautifulSoup def get_go(): url = \"https://www.mohfw.gov.in/\" uClient = urllib.request.urlopen(url)",
"import BeautifulSoup def get_go(): url = \"https://www.mohfw.gov.in/\" uClient = urllib.request.urlopen(url) page_html = uClient.read()",
"url = \"https://www.mohfw.gov.in/\" uClient = urllib.request.urlopen(url) page_html = uClient.read() uClient.close() page_soup = BeautifulSoup(page_html,\"html.parser\")"
] |
[
"x = 5 / 3 x = 5 / 0 # capturing the",
"commonly used in object oriented systems. # ValueError: is the token i.e. it",
": {sys.exc_info()[1]}') # else block gets executed only if you don't have any",
"# Copyright 2009-2017 BHG http://bw.org/ # Exceptions are powerful runtime error reporting mechanism",
"def main(): print('Hello, World.') try: # x = int('foo') # x = 5",
"sys has lot of constants in it. import sys def main(): print('Hello, World.')",
"sys def main(): print('Hello, World.') try: # x = int('foo') # x =",
"executed only if you don't have any errors! else: print('Good Job!') print(x) if",
"the error gracefully # if you don't catch the errors it will stop",
"# x = int('foo') # x = 5 / 3 x = 5",
"print('Hello, World.') try: # x = int('foo') # x = 5 / 3",
"don't know which error it is! except: print(f'unknown error! : {sys.exc_info()[1]}') # else",
"/ 3 x = 5 / 0 # capturing the error gracefully #",
"except: print(f'unknown error! : {sys.exc_info()[1]}') # else block gets executed only if you",
"the token i.e. it is the name of the error that is being",
"catch the errors it will stop the execution of your python script. except",
"it. import sys def main(): print('Hello, World.') try: # x = int('foo') #",
"except ValueError: print('I caught a ValueError!') except ZeroDivisionError: print('Don\\'t divide by zero') #",
"by zero') # if you don't know which error it is! except: print(f'unknown",
"print('I caught a ValueError!') except ZeroDivisionError: print('Don\\'t divide by zero') # if you",
"if you don't catch the errors it will stop the execution of your",
"errors it will stop the execution of your python script. except ValueError: print('I",
"error gracefully # if you don't catch the errors it will stop the",
"int('foo') # x = 5 / 3 x = 5 / 0 #",
"object oriented systems. # ValueError: is the token i.e. it is the name",
"it is the name of the error that is being generated here. #",
"powerful runtime error reporting mechanism commonly used in object oriented systems. # ValueError:",
"runtime error reporting mechanism commonly used in object oriented systems. # ValueError: is",
"you don't know which error it is! except: print(f'unknown error! : {sys.exc_info()[1]}') #",
"error it is! except: print(f'unknown error! : {sys.exc_info()[1]}') # else block gets executed",
"<filename>Chap10/hello.py #!/usr/bin/env python3 # Copyright 2009-2017 BHG http://bw.org/ # Exceptions are powerful runtime",
"in object oriented systems. # ValueError: is the token i.e. it is the",
"it is! except: print(f'unknown error! : {sys.exc_info()[1]}') # else block gets executed only",
"of the error that is being generated here. # sys has lot of",
"# capturing the error gracefully # if you don't catch the errors it",
"has lot of constants in it. import sys def main(): print('Hello, World.') try:",
"Copyright 2009-2017 BHG http://bw.org/ # Exceptions are powerful runtime error reporting mechanism commonly",
"# ValueError: is the token i.e. it is the name of the error",
"# if you don't catch the errors it will stop the execution of",
"in it. import sys def main(): print('Hello, World.') try: # x = int('foo')",
"constants in it. import sys def main(): print('Hello, World.') try: # x =",
"main(): print('Hello, World.') try: # x = int('foo') # x = 5 /",
"World.') try: # x = int('foo') # x = 5 / 3 x",
"try: # x = int('foo') # x = 5 / 3 x =",
"the execution of your python script. except ValueError: print('I caught a ValueError!') except",
"of constants in it. import sys def main(): print('Hello, World.') try: # x",
"# if you don't know which error it is! except: print(f'unknown error! :",
"don't catch the errors it will stop the execution of your python script.",
"http://bw.org/ # Exceptions are powerful runtime error reporting mechanism commonly used in object",
"caught a ValueError!') except ZeroDivisionError: print('Don\\'t divide by zero') # if you don't",
"2009-2017 BHG http://bw.org/ # Exceptions are powerful runtime error reporting mechanism commonly used",
"if you don't have any errors! else: print('Good Job!') print(x) if __name__ ==",
"BHG http://bw.org/ # Exceptions are powerful runtime error reporting mechanism commonly used in",
"if you don't know which error it is! except: print(f'unknown error! : {sys.exc_info()[1]}')",
"name of the error that is being generated here. # sys has lot",
"a ValueError!') except ZeroDivisionError: print('Don\\'t divide by zero') # if you don't know",
"#!/usr/bin/env python3 # Copyright 2009-2017 BHG http://bw.org/ # Exceptions are powerful runtime error",
"which error it is! except: print(f'unknown error! : {sys.exc_info()[1]}') # else block gets",
"you don't catch the errors it will stop the execution of your python",
"the errors it will stop the execution of your python script. except ValueError:",
"the error that is being generated here. # sys has lot of constants",
"lot of constants in it. import sys def main(): print('Hello, World.') try: #",
"else block gets executed only if you don't have any errors! else: print('Good",
"block gets executed only if you don't have any errors! else: print('Good Job!')",
"are powerful runtime error reporting mechanism commonly used in object oriented systems. #",
"the name of the error that is being generated here. # sys has",
"{sys.exc_info()[1]}') # else block gets executed only if you don't have any errors!",
"/ 0 # capturing the error gracefully # if you don't catch the",
"oriented systems. # ValueError: is the token i.e. it is the name of",
"# x = 5 / 3 x = 5 / 0 # capturing",
"execution of your python script. except ValueError: print('I caught a ValueError!') except ZeroDivisionError:",
"Exceptions are powerful runtime error reporting mechanism commonly used in object oriented systems.",
"token i.e. it is the name of the error that is being generated",
"systems. # ValueError: is the token i.e. it is the name of the",
"script. except ValueError: print('I caught a ValueError!') except ZeroDivisionError: print('Don\\'t divide by zero')",
"ValueError!') except ZeroDivisionError: print('Don\\'t divide by zero') # if you don't know which",
"print(f'unknown error! : {sys.exc_info()[1]}') # else block gets executed only if you don't",
"python script. except ValueError: print('I caught a ValueError!') except ZeroDivisionError: print('Don\\'t divide by",
"ValueError: is the token i.e. it is the name of the error that",
"error reporting mechanism commonly used in object oriented systems. # ValueError: is the",
"stop the execution of your python script. except ValueError: print('I caught a ValueError!')",
"only if you don't have any errors! else: print('Good Job!') print(x) if __name__",
"# Exceptions are powerful runtime error reporting mechanism commonly used in object oriented",
"know which error it is! except: print(f'unknown error! : {sys.exc_info()[1]}') # else block",
"divide by zero') # if you don't know which error it is! except:",
"generated here. # sys has lot of constants in it. import sys def",
"is! except: print(f'unknown error! : {sys.exc_info()[1]}') # else block gets executed only if",
"# else block gets executed only if you don't have any errors! else:",
"gets executed only if you don't have any errors! else: print('Good Job!') print(x)",
"zero') # if you don't know which error it is! except: print(f'unknown error!",
"# sys has lot of constants in it. import sys def main(): print('Hello,",
"import sys def main(): print('Hello, World.') try: # x = int('foo') # x",
"is the token i.e. it is the name of the error that is",
"x = int('foo') # x = 5 / 3 x = 5 /",
"5 / 3 x = 5 / 0 # capturing the error gracefully",
"you don't have any errors! else: print('Good Job!') print(x) if __name__ == '__main__':",
"don't have any errors! else: print('Good Job!') print(x) if __name__ == '__main__': main()",
"will stop the execution of your python script. except ValueError: print('I caught a",
"used in object oriented systems. # ValueError: is the token i.e. it is",
"of your python script. except ValueError: print('I caught a ValueError!') except ZeroDivisionError: print('Don\\'t",
"gracefully # if you don't catch the errors it will stop the execution",
"it will stop the execution of your python script. except ValueError: print('I caught",
"is being generated here. # sys has lot of constants in it. import",
"i.e. it is the name of the error that is being generated here.",
"except ZeroDivisionError: print('Don\\'t divide by zero') # if you don't know which error",
"python3 # Copyright 2009-2017 BHG http://bw.org/ # Exceptions are powerful runtime error reporting",
"5 / 0 # capturing the error gracefully # if you don't catch",
"0 # capturing the error gracefully # if you don't catch the errors",
"= 5 / 3 x = 5 / 0 # capturing the error",
"error! : {sys.exc_info()[1]}') # else block gets executed only if you don't have",
"= 5 / 0 # capturing the error gracefully # if you don't",
"that is being generated here. # sys has lot of constants in it.",
"reporting mechanism commonly used in object oriented systems. # ValueError: is the token",
"being generated here. # sys has lot of constants in it. import sys",
"ZeroDivisionError: print('Don\\'t divide by zero') # if you don't know which error it",
"ValueError: print('I caught a ValueError!') except ZeroDivisionError: print('Don\\'t divide by zero') # if",
"print('Don\\'t divide by zero') # if you don't know which error it is!",
"x = 5 / 0 # capturing the error gracefully # if you",
"3 x = 5 / 0 # capturing the error gracefully # if",
"your python script. except ValueError: print('I caught a ValueError!') except ZeroDivisionError: print('Don\\'t divide",
"= int('foo') # x = 5 / 3 x = 5 / 0",
"is the name of the error that is being generated here. # sys",
"error that is being generated here. # sys has lot of constants in",
"mechanism commonly used in object oriented systems. # ValueError: is the token i.e.",
"capturing the error gracefully # if you don't catch the errors it will",
"here. # sys has lot of constants in it. import sys def main():"
] |
[
"total_size = 0 for path in get_mdsd_csv_cbow_data_output_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') total_size =",
"batch_size): batch = np.stack(batch, axis=0) yield batch def get_mdsd_csv_cbow_data_output_iter(batch_size, main_path=MDSD_MAIN_PATH): iterators = []",
"import bisect_left import itertools from numpy.lib.npyio import load as npload import numpy as",
"load as npload import numpy as np from utils import ( get_mdsd_csv_cbow_data_input_files_iter, get_mdsd_csv_cbow_data_output_files_iter,",
"npload import numpy as np from utils import ( get_mdsd_csv_cbow_data_input_files_iter, get_mdsd_csv_cbow_data_output_files_iter, grouper, MDSD_MAIN_PATH,",
"closest_batch_size(total_size, seed_size): # produce all factors of total_size factors = [d for d",
"== 0: return factors[0] if pos == len(factors): return factors[-1] before = factors[pos",
"= factors[pos - 1] after = factors[pos] closest = before if after -",
"for tr, lb in gens: yield tr, lb def get_mdsd_csv_cbow_data_input_size(main_path=MDSD_MAIN_PATH): total_size = 0",
"after = factors[pos] closest = before if after - seed_size < seed_size -",
"[d for d in range(1, total_size // 2 + 1) if not total_size",
"zip( get_mdsd_csv_cbow_data_input_iter(batch_size, main_path=main_path), get_mdsd_csv_cbow_data_output_iter(batch_size, main_path=main_path) ) for tr, lb in gens: yield tr,",
"total_size // 2 + 1) if not total_size % d] # select number",
"factors of total_size factors = [d for d in range(1, total_size // 2",
"lb in gens: yield tr, lb def get_mdsd_csv_cbow_data_input_size(main_path=MDSD_MAIN_PATH): total_size = 0 for path",
"fit_generator_it(batch_size, main_path): yield res def fit_generator_it(batch_size, main_path=MDSD_MAIN_PATH): gens = zip( get_mdsd_csv_cbow_data_input_iter(batch_size, main_path=main_path), get_mdsd_csv_cbow_data_output_iter(batch_size,",
"while True: for res in fit_generator_it(batch_size, main_path): yield res def fit_generator_it(batch_size, main_path=MDSD_MAIN_PATH): gens",
"def fit_generator_it(batch_size, main_path=MDSD_MAIN_PATH): gens = zip( get_mdsd_csv_cbow_data_input_iter(batch_size, main_path=main_path), get_mdsd_csv_cbow_data_output_iter(batch_size, main_path=main_path) ) for tr,",
"# https://stackoverflow.com/questions/12141150/from-list-of-integers-get-number-closest-to-a-given-value pos = bisect_left(factors, seed_size) if pos == 0: return factors[0] if",
"in np.nditer(array, flags=['external_loop']): for el in grouper(els, 2): yield el def get_mdsd_csv_cbow_data_input_iter(batch_size, main_path=MDSD_MAIN_PATH):",
"size # https://stackoverflow.com/questions/12141150/from-list-of-integers-get-number-closest-to-a-given-value pos = bisect_left(factors, seed_size) if pos == 0: return factors[0]",
"main_path=MDSD_MAIN_PATH): iterators = [] for path in get_mdsd_csv_cbow_data_output_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') iterators.append(gen_array(data))",
"d] # select number closest to seed size # https://stackoverflow.com/questions/12141150/from-list-of-integers-get-number-closest-to-a-given-value pos = bisect_left(factors,",
"not total_size % d] # select number closest to seed size # https://stackoverflow.com/questions/12141150/from-list-of-integers-get-number-closest-to-a-given-value",
"yield tr, lb def get_mdsd_csv_cbow_data_input_size(main_path=MDSD_MAIN_PATH): total_size = 0 for path in get_mdsd_csv_cbow_data_input_files_iter(main_path=main_path): data",
"batch in grouper(main_it, batch_size): batch = np.stack(batch, axis=0) yield batch def get_mdsd_csv_cbow_data_output_iter(batch_size, main_path=MDSD_MAIN_PATH):",
"main_path=main_path), get_mdsd_csv_cbow_data_output_iter(batch_size, main_path=main_path) ) for tr, lb in gens: yield tr, lb def",
"in gens: yield tr, lb def get_mdsd_csv_cbow_data_input_size(main_path=MDSD_MAIN_PATH): total_size = 0 for path in",
"< seed_size - before: closest = after return closest def gen_array(array): for els",
"np.stack(batch, axis=0) yield batch def fit_generator(batch_size, main_path=MDSD_MAIN_PATH): while True: for res in fit_generator_it(batch_size,",
"# select number closest to seed size # https://stackoverflow.com/questions/12141150/from-list-of-integers-get-number-closest-to-a-given-value pos = bisect_left(factors, seed_size)",
"as npload import numpy as np from utils import ( get_mdsd_csv_cbow_data_input_files_iter, get_mdsd_csv_cbow_data_output_files_iter, grouper,",
"in grouper(els, 2): yield el def get_mdsd_csv_cbow_data_input_iter(batch_size, main_path=MDSD_MAIN_PATH): iterators = [] for path",
"total_size = total_size + data.shape[0] return total_size def get_mdsd_csv_cbow_data_output_size(main_path=MDSD_MAIN_PATH): total_size = 0 for",
"yield el def get_mdsd_csv_cbow_data_input_iter(batch_size, main_path=MDSD_MAIN_PATH): iterators = [] for path in get_mdsd_csv_cbow_data_input_files_iter(main_path=main_path): data",
"0 for path in get_mdsd_csv_cbow_data_output_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') total_size = total_size +",
"2): yield el def get_mdsd_csv_cbow_data_input_iter(batch_size, main_path=MDSD_MAIN_PATH): iterators = [] for path in get_mdsd_csv_cbow_data_input_files_iter(main_path=main_path):",
"el in grouper(els, 2): yield el def get_mdsd_csv_cbow_data_input_iter(batch_size, main_path=MDSD_MAIN_PATH): iterators = [] for",
"in fit_generator_it(batch_size, main_path): yield res def fit_generator_it(batch_size, main_path=MDSD_MAIN_PATH): gens = zip( get_mdsd_csv_cbow_data_input_iter(batch_size, main_path=main_path),",
"els in np.nditer(array, flags=['external_loop']): for el in grouper(els, 2): yield el def get_mdsd_csv_cbow_data_input_iter(batch_size,",
"batch in grouper(main_it, batch_size): batch = np.stack(batch, axis=0) yield batch def fit_generator(batch_size, main_path=MDSD_MAIN_PATH):",
"= before if after - seed_size < seed_size - before: closest = after",
"factors[0] if pos == len(factors): return factors[-1] before = factors[pos - 1] after",
"2 + 1) if not total_size % d] # select number closest to",
"if pos == len(factors): return factors[-1] before = factors[pos - 1] after =",
"iterators.append(gen_array(data)) main_it = itertools.chain.from_iterable(iterators) for batch in grouper(main_it, batch_size): batch = np.stack(batch, axis=0)",
"for path in get_mdsd_csv_cbow_data_input_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') total_size = total_size + data.shape[0]",
"tr, lb def get_mdsd_csv_cbow_data_input_size(main_path=MDSD_MAIN_PATH): total_size = 0 for path in get_mdsd_csv_cbow_data_input_files_iter(main_path=main_path): data =",
"axis=0) yield batch def get_mdsd_csv_cbow_data_output_iter(batch_size, main_path=MDSD_MAIN_PATH): iterators = [] for path in get_mdsd_csv_cbow_data_output_files_iter(main_path=main_path):",
"yield batch def fit_generator(batch_size, main_path=MDSD_MAIN_PATH): while True: for res in fit_generator_it(batch_size, main_path): yield",
"path in get_mdsd_csv_cbow_data_input_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') total_size = total_size + data.shape[0] return",
"get_mdsd_csv_cbow_data_input_iter(batch_size, main_path=MDSD_MAIN_PATH): iterators = [] for path in get_mdsd_csv_cbow_data_input_files_iter(main_path=main_path): data = npload(path, mmap_mode='r')",
"total_size def get_mdsd_csv_cbow_data_output_size(main_path=MDSD_MAIN_PATH): total_size = 0 for path in get_mdsd_csv_cbow_data_output_files_iter(main_path=main_path): data = npload(path,",
"get_mdsd_csv_cbow_data_output_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') iterators.append(gen_array(data)) main_it = itertools.chain.from_iterable(iterators) for batch in grouper(main_it,",
"yield batch def get_mdsd_csv_cbow_data_output_iter(batch_size, main_path=MDSD_MAIN_PATH): iterators = [] for path in get_mdsd_csv_cbow_data_output_files_iter(main_path=main_path): data",
"iterators = [] for path in get_mdsd_csv_cbow_data_output_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') iterators.append(gen_array(data)) main_it",
"for els in np.nditer(array, flags=['external_loop']): for el in grouper(els, 2): yield el def",
"main_path=MDSD_MAIN_PATH): while True: for res in fit_generator_it(batch_size, main_path): yield res def fit_generator_it(batch_size, main_path=MDSD_MAIN_PATH):",
"- 1] after = factors[pos] closest = before if after - seed_size <",
"def closest_batch_size(total_size, seed_size): # produce all factors of total_size factors = [d for",
"return total_size def get_mdsd_csv_cbow_data_output_size(main_path=MDSD_MAIN_PATH): total_size = 0 for path in get_mdsd_csv_cbow_data_output_files_iter(main_path=main_path): data =",
"<reponame>gregor8003/text_word_embed<filename>utils_batch.py from bisect import bisect_left import itertools from numpy.lib.npyio import load as npload",
"( get_mdsd_csv_cbow_data_input_files_iter, get_mdsd_csv_cbow_data_output_files_iter, grouper, MDSD_MAIN_PATH, ) def closest_batch_size(total_size, seed_size): # produce all factors",
"import load as npload import numpy as np from utils import ( get_mdsd_csv_cbow_data_input_files_iter,",
"= total_size + data.shape[0] return total_size def get_mdsd_csv_cbow_data_output_size(main_path=MDSD_MAIN_PATH): total_size = 0 for path",
"1) if not total_size % d] # select number closest to seed size",
"if after - seed_size < seed_size - before: closest = after return closest",
"as np from utils import ( get_mdsd_csv_cbow_data_input_files_iter, get_mdsd_csv_cbow_data_output_files_iter, grouper, MDSD_MAIN_PATH, ) def closest_batch_size(total_size,",
"closest = before if after - seed_size < seed_size - before: closest =",
"seed_size): # produce all factors of total_size factors = [d for d in",
"main_it = itertools.chain.from_iterable(iterators) for batch in grouper(main_it, batch_size): batch = np.stack(batch, axis=0) yield",
"def get_mdsd_csv_cbow_data_output_iter(batch_size, main_path=MDSD_MAIN_PATH): iterators = [] for path in get_mdsd_csv_cbow_data_output_files_iter(main_path=main_path): data = npload(path,",
"after - seed_size < seed_size - before: closest = after return closest def",
"batch = np.stack(batch, axis=0) yield batch def get_mdsd_csv_cbow_data_output_iter(batch_size, main_path=MDSD_MAIN_PATH): iterators = [] for",
"len(factors): return factors[-1] before = factors[pos - 1] after = factors[pos] closest =",
"def get_mdsd_csv_cbow_data_input_size(main_path=MDSD_MAIN_PATH): total_size = 0 for path in get_mdsd_csv_cbow_data_input_files_iter(main_path=main_path): data = npload(path, mmap_mode='r')",
"= itertools.chain.from_iterable(iterators) for batch in grouper(main_it, batch_size): batch = np.stack(batch, axis=0) yield batch",
"np.nditer(array, flags=['external_loop']): for el in grouper(els, 2): yield el def get_mdsd_csv_cbow_data_input_iter(batch_size, main_path=MDSD_MAIN_PATH): iterators",
"in get_mdsd_csv_cbow_data_output_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') total_size = total_size + data.shape[0] return total_size",
"in get_mdsd_csv_cbow_data_output_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') iterators.append(gen_array(data)) main_it = itertools.chain.from_iterable(iterators) for batch in",
"in get_mdsd_csv_cbow_data_input_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') total_size = total_size + data.shape[0] return total_size",
"el def get_mdsd_csv_cbow_data_input_iter(batch_size, main_path=MDSD_MAIN_PATH): iterators = [] for path in get_mdsd_csv_cbow_data_input_files_iter(main_path=main_path): data =",
"fit_generator_it(batch_size, main_path=MDSD_MAIN_PATH): gens = zip( get_mdsd_csv_cbow_data_input_iter(batch_size, main_path=main_path), get_mdsd_csv_cbow_data_output_iter(batch_size, main_path=main_path) ) for tr, lb",
"get_mdsd_csv_cbow_data_input_files_iter, get_mdsd_csv_cbow_data_output_files_iter, grouper, MDSD_MAIN_PATH, ) def closest_batch_size(total_size, seed_size): # produce all factors of",
") def closest_batch_size(total_size, seed_size): # produce all factors of total_size factors = [d",
"= [] for path in get_mdsd_csv_cbow_data_output_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') iterators.append(gen_array(data)) main_it =",
"for path in get_mdsd_csv_cbow_data_output_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') iterators.append(gen_array(data)) main_it = itertools.chain.from_iterable(iterators) for",
"number closest to seed size # https://stackoverflow.com/questions/12141150/from-list-of-integers-get-number-closest-to-a-given-value pos = bisect_left(factors, seed_size) if pos",
"res def fit_generator_it(batch_size, main_path=MDSD_MAIN_PATH): gens = zip( get_mdsd_csv_cbow_data_input_iter(batch_size, main_path=main_path), get_mdsd_csv_cbow_data_output_iter(batch_size, main_path=main_path) ) for",
"for d in range(1, total_size // 2 + 1) if not total_size %",
"get_mdsd_csv_cbow_data_input_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') total_size = total_size + data.shape[0] return total_size def",
"produce all factors of total_size factors = [d for d in range(1, total_size",
"np from utils import ( get_mdsd_csv_cbow_data_input_files_iter, get_mdsd_csv_cbow_data_output_files_iter, grouper, MDSD_MAIN_PATH, ) def closest_batch_size(total_size, seed_size):",
"total_size factors = [d for d in range(1, total_size // 2 + 1)",
"0: return factors[0] if pos == len(factors): return factors[-1] before = factors[pos -",
"get_mdsd_csv_cbow_data_input_iter(batch_size, main_path=main_path), get_mdsd_csv_cbow_data_output_iter(batch_size, main_path=main_path) ) for tr, lb in gens: yield tr, lb",
"select number closest to seed size # https://stackoverflow.com/questions/12141150/from-list-of-integers-get-number-closest-to-a-given-value pos = bisect_left(factors, seed_size) if",
"to seed size # https://stackoverflow.com/questions/12141150/from-list-of-integers-get-number-closest-to-a-given-value pos = bisect_left(factors, seed_size) if pos == 0:",
"axis=0) yield batch def fit_generator(batch_size, main_path=MDSD_MAIN_PATH): while True: for res in fit_generator_it(batch_size, main_path):",
"factors[-1] before = factors[pos - 1] after = factors[pos] closest = before if",
"d in range(1, total_size // 2 + 1) if not total_size % d]",
"before = factors[pos - 1] after = factors[pos] closest = before if after",
"for batch in grouper(main_it, batch_size): batch = np.stack(batch, axis=0) yield batch def fit_generator(batch_size,",
"if pos == 0: return factors[0] if pos == len(factors): return factors[-1] before",
"path in get_mdsd_csv_cbow_data_input_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') iterators.append(gen_array(data)) main_it = itertools.chain.from_iterable(iterators) for batch",
"= zip( get_mdsd_csv_cbow_data_input_iter(batch_size, main_path=main_path), get_mdsd_csv_cbow_data_output_iter(batch_size, main_path=main_path) ) for tr, lb in gens: yield",
"True: for res in fit_generator_it(batch_size, main_path): yield res def fit_generator_it(batch_size, main_path=MDSD_MAIN_PATH): gens =",
"iterators = [] for path in get_mdsd_csv_cbow_data_input_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') iterators.append(gen_array(data)) main_it",
"seed size # https://stackoverflow.com/questions/12141150/from-list-of-integers-get-number-closest-to-a-given-value pos = bisect_left(factors, seed_size) if pos == 0: return",
"= 0 for path in get_mdsd_csv_cbow_data_output_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') total_size = total_size",
"1] after = factors[pos] closest = before if after - seed_size < seed_size",
"= factors[pos] closest = before if after - seed_size < seed_size - before:",
"== len(factors): return factors[-1] before = factors[pos - 1] after = factors[pos] closest",
"def gen_array(array): for els in np.nditer(array, flags=['external_loop']): for el in grouper(els, 2): yield",
"# produce all factors of total_size factors = [d for d in range(1,",
"before if after - seed_size < seed_size - before: closest = after return",
"= np.stack(batch, axis=0) yield batch def fit_generator(batch_size, main_path=MDSD_MAIN_PATH): while True: for res in",
"numpy as np from utils import ( get_mdsd_csv_cbow_data_input_files_iter, get_mdsd_csv_cbow_data_output_files_iter, grouper, MDSD_MAIN_PATH, ) def",
"in grouper(main_it, batch_size): batch = np.stack(batch, axis=0) yield batch def get_mdsd_csv_cbow_data_output_iter(batch_size, main_path=MDSD_MAIN_PATH): iterators",
"factors = [d for d in range(1, total_size // 2 + 1) if",
"seed_size) if pos == 0: return factors[0] if pos == len(factors): return factors[-1]",
"npload(path, mmap_mode='r') total_size = total_size + data.shape[0] return total_size def get_mdsd_csv_cbow_data_output_size(main_path=MDSD_MAIN_PATH): total_size =",
"import numpy as np from utils import ( get_mdsd_csv_cbow_data_input_files_iter, get_mdsd_csv_cbow_data_output_files_iter, grouper, MDSD_MAIN_PATH, )",
"in grouper(main_it, batch_size): batch = np.stack(batch, axis=0) yield batch def fit_generator(batch_size, main_path=MDSD_MAIN_PATH): while",
"data = npload(path, mmap_mode='r') total_size = total_size + data.shape[0] return total_size def get_mdsd_csv_cbow_data_output_size(main_path=MDSD_MAIN_PATH):",
"get_mdsd_csv_cbow_data_input_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') iterators.append(gen_array(data)) main_it = itertools.chain.from_iterable(iterators) for batch in grouper(main_it,",
"[] for path in get_mdsd_csv_cbow_data_input_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') iterators.append(gen_array(data)) main_it = itertools.chain.from_iterable(iterators)",
"for el in grouper(els, 2): yield el def get_mdsd_csv_cbow_data_input_iter(batch_size, main_path=MDSD_MAIN_PATH): iterators = []",
"def get_mdsd_csv_cbow_data_input_iter(batch_size, main_path=MDSD_MAIN_PATH): iterators = [] for path in get_mdsd_csv_cbow_data_input_files_iter(main_path=main_path): data = npload(path,",
"pos = bisect_left(factors, seed_size) if pos == 0: return factors[0] if pos ==",
"[] for path in get_mdsd_csv_cbow_data_output_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') iterators.append(gen_array(data)) main_it = itertools.chain.from_iterable(iterators)",
"data.shape[0] return total_size def get_mdsd_csv_cbow_data_output_size(main_path=MDSD_MAIN_PATH): total_size = 0 for path in get_mdsd_csv_cbow_data_output_files_iter(main_path=main_path): data",
"seed_size < seed_size - before: closest = after return closest def gen_array(array): for",
"range(1, total_size // 2 + 1) if not total_size % d] # select",
"batch def fit_generator(batch_size, main_path=MDSD_MAIN_PATH): while True: for res in fit_generator_it(batch_size, main_path): yield res",
"= np.stack(batch, axis=0) yield batch def get_mdsd_csv_cbow_data_output_iter(batch_size, main_path=MDSD_MAIN_PATH): iterators = [] for path",
"bisect_left import itertools from numpy.lib.npyio import load as npload import numpy as np",
"= npload(path, mmap_mode='r') iterators.append(gen_array(data)) main_it = itertools.chain.from_iterable(iterators) for batch in grouper(main_it, batch_size): batch",
"seed_size - before: closest = after return closest def gen_array(array): for els in",
"for path in get_mdsd_csv_cbow_data_output_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') total_size = total_size + data.shape[0]",
"batch_size): batch = np.stack(batch, axis=0) yield batch def fit_generator(batch_size, main_path=MDSD_MAIN_PATH): while True: for",
"batch def get_mdsd_csv_cbow_data_output_iter(batch_size, main_path=MDSD_MAIN_PATH): iterators = [] for path in get_mdsd_csv_cbow_data_output_files_iter(main_path=main_path): data =",
"get_mdsd_csv_cbow_data_output_iter(batch_size, main_path=main_path) ) for tr, lb in gens: yield tr, lb def get_mdsd_csv_cbow_data_input_size(main_path=MDSD_MAIN_PATH):",
"mmap_mode='r') total_size = total_size + data.shape[0] return total_size def get_mdsd_csv_cbow_data_output_size(main_path=MDSD_MAIN_PATH): total_size = 0",
"all factors of total_size factors = [d for d in range(1, total_size //",
"gens: yield tr, lb def get_mdsd_csv_cbow_data_input_size(main_path=MDSD_MAIN_PATH): total_size = 0 for path in get_mdsd_csv_cbow_data_input_files_iter(main_path=main_path):",
"return closest def gen_array(array): for els in np.nditer(array, flags=['external_loop']): for el in grouper(els,",
"data = npload(path, mmap_mode='r') iterators.append(gen_array(data)) main_it = itertools.chain.from_iterable(iterators) for batch in grouper(main_it, batch_size):",
"grouper(main_it, batch_size): batch = np.stack(batch, axis=0) yield batch def fit_generator(batch_size, main_path=MDSD_MAIN_PATH): while True:",
"res in fit_generator_it(batch_size, main_path): yield res def fit_generator_it(batch_size, main_path=MDSD_MAIN_PATH): gens = zip( get_mdsd_csv_cbow_data_input_iter(batch_size,",
"0 for path in get_mdsd_csv_cbow_data_input_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') total_size = total_size +",
"bisect_left(factors, seed_size) if pos == 0: return factors[0] if pos == len(factors): return",
"- before: closest = after return closest def gen_array(array): for els in np.nditer(array,",
"mmap_mode='r') iterators.append(gen_array(data)) main_it = itertools.chain.from_iterable(iterators) for batch in grouper(main_it, batch_size): batch = np.stack(batch,",
"return factors[-1] before = factors[pos - 1] after = factors[pos] closest = before",
"= [] for path in get_mdsd_csv_cbow_data_input_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') iterators.append(gen_array(data)) main_it =",
"in get_mdsd_csv_cbow_data_input_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') iterators.append(gen_array(data)) main_it = itertools.chain.from_iterable(iterators) for batch in",
"gen_array(array): for els in np.nditer(array, flags=['external_loop']): for el in grouper(els, 2): yield el",
"path in get_mdsd_csv_cbow_data_output_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') total_size = total_size + data.shape[0] return",
"closest def gen_array(array): for els in np.nditer(array, flags=['external_loop']): for el in grouper(els, 2):",
"gens = zip( get_mdsd_csv_cbow_data_input_iter(batch_size, main_path=main_path), get_mdsd_csv_cbow_data_output_iter(batch_size, main_path=main_path) ) for tr, lb in gens:",
"get_mdsd_csv_cbow_data_output_size(main_path=MDSD_MAIN_PATH): total_size = 0 for path in get_mdsd_csv_cbow_data_output_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') total_size",
"def get_mdsd_csv_cbow_data_output_size(main_path=MDSD_MAIN_PATH): total_size = 0 for path in get_mdsd_csv_cbow_data_output_files_iter(main_path=main_path): data = npload(path, mmap_mode='r')",
"total_size + data.shape[0] return total_size def get_mdsd_csv_cbow_data_output_size(main_path=MDSD_MAIN_PATH): total_size = 0 for path in",
"bisect import bisect_left import itertools from numpy.lib.npyio import load as npload import numpy",
"tr, lb in gens: yield tr, lb def get_mdsd_csv_cbow_data_input_size(main_path=MDSD_MAIN_PATH): total_size = 0 for",
"fit_generator(batch_size, main_path=MDSD_MAIN_PATH): while True: for res in fit_generator_it(batch_size, main_path): yield res def fit_generator_it(batch_size,",
"numpy.lib.npyio import load as npload import numpy as np from utils import (",
"if not total_size % d] # select number closest to seed size #",
"for res in fit_generator_it(batch_size, main_path): yield res def fit_generator_it(batch_size, main_path=MDSD_MAIN_PATH): gens = zip(",
"from bisect import bisect_left import itertools from numpy.lib.npyio import load as npload import",
"total_size % d] # select number closest to seed size # https://stackoverflow.com/questions/12141150/from-list-of-integers-get-number-closest-to-a-given-value pos",
"= [d for d in range(1, total_size // 2 + 1) if not",
"utils import ( get_mdsd_csv_cbow_data_input_files_iter, get_mdsd_csv_cbow_data_output_files_iter, grouper, MDSD_MAIN_PATH, ) def closest_batch_size(total_size, seed_size): # produce",
"// 2 + 1) if not total_size % d] # select number closest",
"= bisect_left(factors, seed_size) if pos == 0: return factors[0] if pos == len(factors):",
"= after return closest def gen_array(array): for els in np.nditer(array, flags=['external_loop']): for el",
"grouper(els, 2): yield el def get_mdsd_csv_cbow_data_input_iter(batch_size, main_path=MDSD_MAIN_PATH): iterators = [] for path in",
"get_mdsd_csv_cbow_data_input_size(main_path=MDSD_MAIN_PATH): total_size = 0 for path in get_mdsd_csv_cbow_data_input_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') total_size",
"- seed_size < seed_size - before: closest = after return closest def gen_array(array):",
"= 0 for path in get_mdsd_csv_cbow_data_input_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') total_size = total_size",
"get_mdsd_csv_cbow_data_output_iter(batch_size, main_path=MDSD_MAIN_PATH): iterators = [] for path in get_mdsd_csv_cbow_data_output_files_iter(main_path=main_path): data = npload(path, mmap_mode='r')",
"https://stackoverflow.com/questions/12141150/from-list-of-integers-get-number-closest-to-a-given-value pos = bisect_left(factors, seed_size) if pos == 0: return factors[0] if pos",
"grouper(main_it, batch_size): batch = np.stack(batch, axis=0) yield batch def get_mdsd_csv_cbow_data_output_iter(batch_size, main_path=MDSD_MAIN_PATH): iterators =",
"main_path): yield res def fit_generator_it(batch_size, main_path=MDSD_MAIN_PATH): gens = zip( get_mdsd_csv_cbow_data_input_iter(batch_size, main_path=main_path), get_mdsd_csv_cbow_data_output_iter(batch_size, main_path=main_path)",
"for path in get_mdsd_csv_cbow_data_input_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') iterators.append(gen_array(data)) main_it = itertools.chain.from_iterable(iterators) for",
"pos == len(factors): return factors[-1] before = factors[pos - 1] after = factors[pos]",
"in range(1, total_size // 2 + 1) if not total_size % d] #",
"flags=['external_loop']): for el in grouper(els, 2): yield el def get_mdsd_csv_cbow_data_input_iter(batch_size, main_path=MDSD_MAIN_PATH): iterators =",
"of total_size factors = [d for d in range(1, total_size // 2 +",
"batch = np.stack(batch, axis=0) yield batch def fit_generator(batch_size, main_path=MDSD_MAIN_PATH): while True: for res",
"yield res def fit_generator_it(batch_size, main_path=MDSD_MAIN_PATH): gens = zip( get_mdsd_csv_cbow_data_input_iter(batch_size, main_path=main_path), get_mdsd_csv_cbow_data_output_iter(batch_size, main_path=main_path) )",
"path in get_mdsd_csv_cbow_data_output_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') iterators.append(gen_array(data)) main_it = itertools.chain.from_iterable(iterators) for batch",
"total_size = 0 for path in get_mdsd_csv_cbow_data_input_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') total_size =",
"% d] # select number closest to seed size # https://stackoverflow.com/questions/12141150/from-list-of-integers-get-number-closest-to-a-given-value pos =",
"for batch in grouper(main_it, batch_size): batch = np.stack(batch, axis=0) yield batch def get_mdsd_csv_cbow_data_output_iter(batch_size,",
"itertools from numpy.lib.npyio import load as npload import numpy as np from utils",
") for tr, lb in gens: yield tr, lb def get_mdsd_csv_cbow_data_input_size(main_path=MDSD_MAIN_PATH): total_size =",
"from numpy.lib.npyio import load as npload import numpy as np from utils import",
"main_path=MDSD_MAIN_PATH): iterators = [] for path in get_mdsd_csv_cbow_data_input_files_iter(main_path=main_path): data = npload(path, mmap_mode='r') iterators.append(gen_array(data))",
"= npload(path, mmap_mode='r') total_size = total_size + data.shape[0] return total_size def get_mdsd_csv_cbow_data_output_size(main_path=MDSD_MAIN_PATH): total_size",
"+ data.shape[0] return total_size def get_mdsd_csv_cbow_data_output_size(main_path=MDSD_MAIN_PATH): total_size = 0 for path in get_mdsd_csv_cbow_data_output_files_iter(main_path=main_path):",
"before: closest = after return closest def gen_array(array): for els in np.nditer(array, flags=['external_loop']):",
"closest = after return closest def gen_array(array): for els in np.nditer(array, flags=['external_loop']): for",
"+ 1) if not total_size % d] # select number closest to seed",
"factors[pos - 1] after = factors[pos] closest = before if after - seed_size",
"MDSD_MAIN_PATH, ) def closest_batch_size(total_size, seed_size): # produce all factors of total_size factors =",
"main_path=main_path) ) for tr, lb in gens: yield tr, lb def get_mdsd_csv_cbow_data_input_size(main_path=MDSD_MAIN_PATH): total_size",
"import ( get_mdsd_csv_cbow_data_input_files_iter, get_mdsd_csv_cbow_data_output_files_iter, grouper, MDSD_MAIN_PATH, ) def closest_batch_size(total_size, seed_size): # produce all",
"grouper, MDSD_MAIN_PATH, ) def closest_batch_size(total_size, seed_size): # produce all factors of total_size factors",
"closest to seed size # https://stackoverflow.com/questions/12141150/from-list-of-integers-get-number-closest-to-a-given-value pos = bisect_left(factors, seed_size) if pos ==",
"return factors[0] if pos == len(factors): return factors[-1] before = factors[pos - 1]",
"factors[pos] closest = before if after - seed_size < seed_size - before: closest",
"after return closest def gen_array(array): for els in np.nditer(array, flags=['external_loop']): for el in",
"itertools.chain.from_iterable(iterators) for batch in grouper(main_it, batch_size): batch = np.stack(batch, axis=0) yield batch def",
"lb def get_mdsd_csv_cbow_data_input_size(main_path=MDSD_MAIN_PATH): total_size = 0 for path in get_mdsd_csv_cbow_data_input_files_iter(main_path=main_path): data = npload(path,",
"get_mdsd_csv_cbow_data_output_files_iter, grouper, MDSD_MAIN_PATH, ) def closest_batch_size(total_size, seed_size): # produce all factors of total_size",
"pos == 0: return factors[0] if pos == len(factors): return factors[-1] before =",
"main_path=MDSD_MAIN_PATH): gens = zip( get_mdsd_csv_cbow_data_input_iter(batch_size, main_path=main_path), get_mdsd_csv_cbow_data_output_iter(batch_size, main_path=main_path) ) for tr, lb in",
"def fit_generator(batch_size, main_path=MDSD_MAIN_PATH): while True: for res in fit_generator_it(batch_size, main_path): yield res def",
"np.stack(batch, axis=0) yield batch def get_mdsd_csv_cbow_data_output_iter(batch_size, main_path=MDSD_MAIN_PATH): iterators = [] for path in",
"import itertools from numpy.lib.npyio import load as npload import numpy as np from",
"npload(path, mmap_mode='r') iterators.append(gen_array(data)) main_it = itertools.chain.from_iterable(iterators) for batch in grouper(main_it, batch_size): batch =",
"from utils import ( get_mdsd_csv_cbow_data_input_files_iter, get_mdsd_csv_cbow_data_output_files_iter, grouper, MDSD_MAIN_PATH, ) def closest_batch_size(total_size, seed_size): #"
] |
[
"= \"python \" + sys.argv[0] + \" [-h | --help] [-a | --app",
"ClientError as e: if e.response[\"Error\"][\"Code\"] == \"InvalidKeyPair.NotFound\": res = ec2.create_key_pair( KeyName=app_name, ) private_key",
"help=\"~/.aws/config.\") argparser.add_argument(\"-r\", \"--region\", type=str, default=\"ap-northeast-1\", help=\"AWs regions. e.g. ap-northeast-1, us-east-1, ...\") return argparser.parse_args()",
"stack_name) except ClientError as e: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Create CFn stacks. def",
"body = open(path).read() stack_name = app_name + \"-\" + re.sub('\\/(.*)\\/(.*)\\.yml', '\\\\1-\\\\2', t) self.valid_template(t,",
"<AWS_PROFILE>] [-r | --region <AWS_REGION>]\" argparser = ArgumentParser(usage=usage) argparser.add_argument(\"-a\", \"--app\", type=str, default=\"snatch\", help=\"Target",
"logger.info(\"%s KeyPair created.\", app_name) else: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Provisiond stack def provisiond(self,",
"], ) return logger.info(\"%s KeyPair already exists.\", app_name) except ClientError as e: if",
"ClientError as e: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Create EC2 keypair. # 秘密鍵は ~/.ssh/",
"ec2.create_key_pair( KeyName=app_name, ) private_key = res[\"KeyMaterial\"] pem_file = open(os.environ[\"HOME\"] + \"/.ssh/\" + app_name",
"\"AlreadyExistsException\": self.update_stack(stack_name, cfn, input) return else: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Valid CFn template.",
"private_key = res[\"KeyMaterial\"] pem_file = open(os.environ[\"HOME\"] + \"/.ssh/\" + app_name + \".pem\", \"w\")",
"t body = open(path).read() stack_name = app_name + \"-\" + re.sub('\\/(.*)\\/(.*)\\.yml', '\\\\1-\\\\2', t)",
"...\") return argparser.parse_args() # Update CFn stacks. def update_stack(self, stack_name, cfn, input): w",
"0o600) return logger.info(\"%s KeyPair created.\", app_name) else: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Provisiond stack",
"app_name) except ClientError as e: if e.response[\"Error\"][\"Code\"] == \"InvalidKeyPair.NotFound\": res = ec2.create_key_pair( KeyName=app_name,",
"stacks. def update_stack(self, stack_name, cfn, input): w = cfn.get_waiter(\"stack_update_complete\") try: cfn.update_stack(**input) logger.info(\"Update %s.\",",
"return logger.info(\"%s KeyPair created.\", app_name) else: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Provisiond stack def",
"cfn, input): w = cfn.get_waiter(\"stack_update_complete\") try: cfn.update_stack(**input) logger.info(\"Update %s.\", stack_name) w.wait( StackName =",
"= '%(levelname)s : %(asctime)s : %(message)s' logging.basicConfig(level=logging.INFO, format=formatter) class DeployStack: # Option parser.",
"cfn = session.client(\"cloudformation\") for t in TEMPLATES: path = os.getcwd() + t body",
"TEMPLATES = [ \"/scripts/ec2.yml\", ] logger = logging.getLogger() formatter = '%(levelname)s : %(asctime)s",
"import ClientError from argparse import ArgumentParser TEMPLATES = [ \"/scripts/ec2.yml\", ] logger =",
") return logger.info(\"Update %s complete.\", stack_name) except ClientError as e: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"])",
"os.getcwd() + t body = open(path).read() stack_name = app_name + \"-\" + re.sub('\\/(.*)\\/(.*)\\.yml',",
"argparser = ArgumentParser(usage=usage) argparser.add_argument(\"-a\", \"--app\", type=str, default=\"snatch\", help=\"Target app name.\") argparser.add_argument(\"-p\", \"--profile\", type=str,",
"w.wait( StackName = stack_name, ) return logger.info(\"Create %s complete.\", stack_name) except ClientError as",
"cfn.get_waiter(\"stack_update_complete\") try: cfn.update_stack(**input) logger.info(\"Update %s.\", stack_name) w.wait( StackName = stack_name, ) return logger.info(\"Update",
"\"Capabilities\": [ 'CAPABILITY_NAMED_IAM', ], \"Parameters\": [ { \"ParameterKey\": \"AppName\", \"ParameterValue\": app_name, }, ],",
"import os import re import sys import logging from boto3.session import Session from",
"logger.info(\"Update %s complete.\", stack_name) except ClientError as e: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Create",
"\"ParameterKey\": \"AppName\", \"ParameterValue\": app_name, }, ], } try: self.create_stack(stack_name, cfn, input) except ClientError",
"# -*- coding: utf-8 -*- import glob import os import re import sys",
"{ \"StackName\": stack_name, \"TemplateBody\": body, \"Capabilities\": [ 'CAPABILITY_NAMED_IAM', ], \"Parameters\": [ { \"ParameterKey\":",
"e.response[\"Error\"][\"Message\"]) # Valid CFn template. def valid_template(self, template, body, cfn): logger.info(\"Validate checks %s\",",
"# Update CFn stacks. def update_stack(self, stack_name, cfn, input): w = cfn.get_waiter(\"stack_update_complete\") try:",
"# Provisiond stack def provisiond(self, app_name, profile, region): session = Session(profile_name=profile, region_name=region) self.create_keypair(app_name,",
"+ \"-\" + re.sub('\\/(.*)\\/(.*)\\.yml', '\\\\1-\\\\2', t) self.valid_template(t, body, cfn) input = { \"StackName\":",
"e: if e.response[\"Error\"][\"Code\"] == \"AlreadyExistsException\": self.update_stack(stack_name, cfn, input) return else: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"])",
"cfn): logger.info(\"Validate checks %s\", template) try: cfn.validate_template( TemplateBody = body, ) return logger.info(\"%s",
"= DeployStack() options = self.get_option() app_name = options.app profile = options.profile region =",
"+ re.sub('\\/(.*)\\/(.*)\\.yml', '\\\\1-\\\\2', t) self.valid_template(t, body, cfn) input = { \"StackName\": stack_name, \"TemplateBody\":",
"KeyNames=[ app_name, ], ) return logger.info(\"%s KeyPair already exists.\", app_name) except ClientError as",
"| --help] [-a | --app <APP_NAME>] [-p | --profile <AWS_PROFILE>] [-r | --region",
"logging.getLogger() formatter = '%(levelname)s : %(asctime)s : %(message)s' logging.basicConfig(level=logging.INFO, format=formatter) class DeployStack: #",
"ap-northeast-1, us-east-1, ...\") return argparser.parse_args() # Update CFn stacks. def update_stack(self, stack_name, cfn,",
"= ArgumentParser(usage=usage) argparser.add_argument(\"-a\", \"--app\", type=str, default=\"snatch\", help=\"Target app name.\") argparser.add_argument(\"-p\", \"--profile\", type=str, default=\"default\",",
"app_name) else: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Provisiond stack def provisiond(self, app_name, profile, region):",
"# Create EC2 keypair. # 秘密鍵は ~/.ssh/ 配下に書き出す(file permission: 0600) def create_keypair(self, app_name,",
"logger = logging.getLogger() formatter = '%(levelname)s : %(asctime)s : %(message)s' logging.basicConfig(level=logging.INFO, format=formatter) class",
"-*- coding: utf-8 -*- import glob import os import re import sys import",
"as e: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Create CFn stacks. def create_stack(self, stack_name, cfn,",
"\"TemplateBody\": body, \"Capabilities\": [ 'CAPABILITY_NAMED_IAM', ], \"Parameters\": [ { \"ParameterKey\": \"AppName\", \"ParameterValue\": app_name,",
"botocore.exceptions import ClientError from argparse import ArgumentParser TEMPLATES = [ \"/scripts/ec2.yml\", ] logger",
"complete.\", stack_name) except ClientError as e: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Create CFn stacks.",
"\" [-h | --help] [-a | --app <APP_NAME>] [-p | --profile <AWS_PROFILE>] [-r",
"options.app profile = options.profile region = options.region self.provisiond(app_name, profile, region) return logger.info(\"Finish provision",
"\"--profile\", type=str, default=\"default\", help=\"~/.aws/config.\") argparser.add_argument(\"-r\", \"--region\", type=str, default=\"ap-northeast-1\", help=\"AWs regions. e.g. ap-northeast-1, us-east-1,",
"app_name + \".pem\", \"w\") pem_file.write(private_key) pem_file.close os.chmod(os.environ[\"HOME\"] + \"/.ssh/\" + app_name + \".pem\",",
"CFn template. def valid_template(self, template, body, cfn): logger.info(\"Validate checks %s\", template) try: cfn.validate_template(",
"+ \" [-h | --help] [-a | --app <APP_NAME>] [-p | --profile <AWS_PROFILE>]",
"profile = options.profile region = options.region self.provisiond(app_name, profile, region) return logger.info(\"Finish provision stacks.\")",
"except ClientError as e: if e.response[\"Error\"][\"Code\"] == \"AlreadyExistsException\": self.update_stack(stack_name, cfn, input) return else:",
"utf-8 -*- import glob import os import re import sys import logging from",
"return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Create EC2 keypair. # 秘密鍵は ~/.ssh/ 配下に書き出す(file permission: 0600)",
"input): w = cfn.get_waiter(\"stack_update_complete\") try: cfn.update_stack(**input) logger.info(\"Update %s.\", stack_name) w.wait( StackName = stack_name,",
"app name.\") argparser.add_argument(\"-p\", \"--profile\", type=str, default=\"default\", help=\"~/.aws/config.\") argparser.add_argument(\"-r\", \"--region\", type=str, default=\"ap-northeast-1\", help=\"AWs regions.",
"+ \".pem\", 0o600) return logger.info(\"%s KeyPair created.\", app_name) else: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) #",
"e.g. ap-northeast-1, us-east-1, ...\") return argparser.parse_args() # Update CFn stacks. def update_stack(self, stack_name,",
"try: cfn.update_stack(**input) logger.info(\"Update %s.\", stack_name) w.wait( StackName = stack_name, ) return logger.info(\"Update %s",
"cfn, input) return else: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Valid CFn template. def valid_template(self,",
"logging.basicConfig(level=logging.INFO, format=formatter) class DeployStack: # Option parser. def get_option(self): usage = \"python \"",
"return logger.info(\"Update %s complete.\", stack_name) except ClientError as e: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) #",
"for t in TEMPLATES: path = os.getcwd() + t body = open(path).read() stack_name",
"Session(profile_name=profile, region_name=region) self.create_keypair(app_name, session) cfn = session.client(\"cloudformation\") for t in TEMPLATES: path =",
"w = cfn.get_waiter(\"stack_update_complete\") try: cfn.update_stack(**input) logger.info(\"Update %s.\", stack_name) w.wait( StackName = stack_name, )",
") return logger.info(\"%s is validation OK.\", template) except ClientError as e: return logger.warning(\"%s\",",
"return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Create CFn stacks. def create_stack(self, stack_name, cfn, input): w",
"OK.\", template) except ClientError as e: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Create EC2 keypair.",
"type=str, default=\"ap-northeast-1\", help=\"AWs regions. e.g. ap-northeast-1, us-east-1, ...\") return argparser.parse_args() # Update CFn",
"app_name, }, ], } try: self.create_stack(stack_name, cfn, input) except ClientError as e: logger.warning(\"%s\",",
"import glob import os import re import sys import logging from boto3.session import",
"else: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Valid CFn template. def valid_template(self, template, body, cfn):",
"session.client(\"ec2\") try: ec2.describe_key_pairs( KeyNames=[ app_name, ], ) return logger.info(\"%s KeyPair already exists.\", app_name)",
"template, body, cfn): logger.info(\"Validate checks %s\", template) try: cfn.validate_template( TemplateBody = body, )",
"argparser.add_argument(\"-r\", \"--region\", type=str, default=\"ap-northeast-1\", help=\"AWs regions. e.g. ap-northeast-1, us-east-1, ...\") return argparser.parse_args() #",
"app_name) ec2 = session.client(\"ec2\") try: ec2.describe_key_pairs( KeyNames=[ app_name, ], ) return logger.info(\"%s KeyPair",
"body, ) return logger.info(\"%s is validation OK.\", template) except ClientError as e: return",
"'%(levelname)s : %(asctime)s : %(message)s' logging.basicConfig(level=logging.INFO, format=formatter) class DeployStack: # Option parser. def",
"ec2.describe_key_pairs( KeyNames=[ app_name, ], ) return logger.info(\"%s KeyPair already exists.\", app_name) except ClientError",
"return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Valid CFn template. def valid_template(self, template, body, cfn): logger.info(\"Validate",
"w.wait( StackName = stack_name, ) return logger.info(\"Update %s complete.\", stack_name) except ClientError as",
"stack_name, ) return logger.info(\"Create %s complete.\", stack_name) except ClientError as e: if e.response[\"Error\"][\"Code\"]",
"except ClientError as e: if e.response[\"Error\"][\"Code\"] == \"InvalidKeyPair.NotFound\": res = ec2.create_key_pair( KeyName=app_name, )",
"input): w = cfn.get_waiter(\"stack_create_complete\") try: cfn.create_stack(**input) logger.info(\"Create %s.\", stack_name) w.wait( StackName = stack_name,",
"stack_name) w.wait( StackName = stack_name, ) return logger.info(\"Create %s complete.\", stack_name) except ClientError",
"logger.info(\"Create %s complete.\", stack_name) except ClientError as e: if e.response[\"Error\"][\"Code\"] == \"AlreadyExistsException\": self.update_stack(stack_name,",
"session) cfn = session.client(\"cloudformation\") for t in TEMPLATES: path = os.getcwd() + t",
"\"w\") pem_file.write(private_key) pem_file.close os.chmod(os.environ[\"HOME\"] + \"/.ssh/\" + app_name + \".pem\", 0o600) return logger.info(\"%s",
"self.create_keypair(app_name, session) cfn = session.client(\"cloudformation\") for t in TEMPLATES: path = os.getcwd() +",
"Create CFn stacks. def create_stack(self, stack_name, cfn, input): w = cfn.get_waiter(\"stack_create_complete\") try: cfn.create_stack(**input)",
"t in TEMPLATES: path = os.getcwd() + t body = open(path).read() stack_name =",
"StackName = stack_name, ) return logger.info(\"Update %s complete.\", stack_name) except ClientError as e:",
"options = self.get_option() app_name = options.app profile = options.profile region = options.region self.provisiond(app_name,",
"self.get_option() app_name = options.app profile = options.profile region = options.region self.provisiond(app_name, profile, region)",
") private_key = res[\"KeyMaterial\"] pem_file = open(os.environ[\"HOME\"] + \"/.ssh/\" + app_name + \".pem\",",
"--region <AWS_REGION>]\" argparser = ArgumentParser(usage=usage) argparser.add_argument(\"-a\", \"--app\", type=str, default=\"snatch\", help=\"Target app name.\") argparser.add_argument(\"-p\",",
"0600) def create_keypair(self, app_name, session): logger.info(\"Create %s KeyPair.\", app_name) ec2 = session.client(\"ec2\") try:",
"| --profile <AWS_PROFILE>] [-r | --region <AWS_REGION>]\" argparser = ArgumentParser(usage=usage) argparser.add_argument(\"-a\", \"--app\", type=str,",
"parser. def get_option(self): usage = \"python \" + sys.argv[0] + \" [-h |",
"get_option(self): usage = \"python \" + sys.argv[0] + \" [-h | --help] [-a",
"update_stack(self, stack_name, cfn, input): w = cfn.get_waiter(\"stack_update_complete\") try: cfn.update_stack(**input) logger.info(\"Update %s.\", stack_name) w.wait(",
"= stack_name, ) return logger.info(\"Create %s complete.\", stack_name) except ClientError as e: if",
"provisiond(self, app_name, profile, region): session = Session(profile_name=profile, region_name=region) self.create_keypair(app_name, session) cfn = session.client(\"cloudformation\")",
"keypair. # 秘密鍵は ~/.ssh/ 配下に書き出す(file permission: 0600) def create_keypair(self, app_name, session): logger.info(\"Create %s",
"checks %s\", template) try: cfn.validate_template( TemplateBody = body, ) return logger.info(\"%s is validation",
"argparser.add_argument(\"-a\", \"--app\", type=str, default=\"snatch\", help=\"Target app name.\") argparser.add_argument(\"-p\", \"--profile\", type=str, default=\"default\", help=\"~/.aws/config.\") argparser.add_argument(\"-r\",",
"stack_name) w.wait( StackName = stack_name, ) return logger.info(\"Update %s complete.\", stack_name) except ClientError",
"e.response[\"Error\"][\"Message\"]) # Provisiond stack def provisiond(self, app_name, profile, region): session = Session(profile_name=profile, region_name=region)",
"[ { \"ParameterKey\": \"AppName\", \"ParameterValue\": app_name, }, ], } try: self.create_stack(stack_name, cfn, input)",
"complete.\", stack_name) except ClientError as e: if e.response[\"Error\"][\"Code\"] == \"AlreadyExistsException\": self.update_stack(stack_name, cfn, input)",
"app_name + \"-\" + re.sub('\\/(.*)\\/(.*)\\.yml', '\\\\1-\\\\2', t) self.valid_template(t, body, cfn) input = {",
"KeyPair created.\", app_name) else: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Provisiond stack def provisiond(self, app_name,",
"return @staticmethod def main(): logger.info(\"Start provision stacks.\") self = DeployStack() options = self.get_option()",
"Update CFn stacks. def update_stack(self, stack_name, cfn, input): w = cfn.get_waiter(\"stack_update_complete\") try: cfn.update_stack(**input)",
"TEMPLATES: path = os.getcwd() + t body = open(path).read() stack_name = app_name +",
"KeyName=app_name, ) private_key = res[\"KeyMaterial\"] pem_file = open(os.environ[\"HOME\"] + \"/.ssh/\" + app_name +",
"def create_stack(self, stack_name, cfn, input): w = cfn.get_waiter(\"stack_create_complete\") try: cfn.create_stack(**input) logger.info(\"Create %s.\", stack_name)",
"+ sys.argv[0] + \" [-h | --help] [-a | --app <APP_NAME>] [-p |",
"| --app <APP_NAME>] [-p | --profile <AWS_PROFILE>] [-r | --region <AWS_REGION>]\" argparser =",
"import ArgumentParser TEMPLATES = [ \"/scripts/ec2.yml\", ] logger = logging.getLogger() formatter = '%(levelname)s",
"session): logger.info(\"Create %s KeyPair.\", app_name) ec2 = session.client(\"ec2\") try: ec2.describe_key_pairs( KeyNames=[ app_name, ],",
"[-h | --help] [-a | --app <APP_NAME>] [-p | --profile <AWS_PROFILE>] [-r |",
"\".pem\", \"w\") pem_file.write(private_key) pem_file.close os.chmod(os.environ[\"HOME\"] + \"/.ssh/\" + app_name + \".pem\", 0o600) return",
"[-a | --app <APP_NAME>] [-p | --profile <AWS_PROFILE>] [-r | --region <AWS_REGION>]\" argparser",
"= session.client(\"ec2\") try: ec2.describe_key_pairs( KeyNames=[ app_name, ], ) return logger.info(\"%s KeyPair already exists.\",",
"\"ParameterValue\": app_name, }, ], } try: self.create_stack(stack_name, cfn, input) except ClientError as e:",
"cfn.get_waiter(\"stack_create_complete\") try: cfn.create_stack(**input) logger.info(\"Create %s.\", stack_name) w.wait( StackName = stack_name, ) return logger.info(\"Create",
"glob import os import re import sys import logging from boto3.session import Session",
"e.response[\"Error\"][\"Code\"] == \"InvalidKeyPair.NotFound\": res = ec2.create_key_pair( KeyName=app_name, ) private_key = res[\"KeyMaterial\"] pem_file =",
"stack_name, \"TemplateBody\": body, \"Capabilities\": [ 'CAPABILITY_NAMED_IAM', ], \"Parameters\": [ { \"ParameterKey\": \"AppName\", \"ParameterValue\":",
"provision stacks.\") self = DeployStack() options = self.get_option() app_name = options.app profile =",
"ClientError from argparse import ArgumentParser TEMPLATES = [ \"/scripts/ec2.yml\", ] logger = logging.getLogger()",
"def create_keypair(self, app_name, session): logger.info(\"Create %s KeyPair.\", app_name) ec2 = session.client(\"ec2\") try: ec2.describe_key_pairs(",
"stacks.\") self = DeployStack() options = self.get_option() app_name = options.app profile = options.profile",
"] logger = logging.getLogger() formatter = '%(levelname)s : %(asctime)s : %(message)s' logging.basicConfig(level=logging.INFO, format=formatter)",
"self.create_stack(stack_name, cfn, input) except ClientError as e: logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) return @staticmethod def main():",
": %(message)s' logging.basicConfig(level=logging.INFO, format=formatter) class DeployStack: # Option parser. def get_option(self): usage =",
"return logger.info(\"%s is validation OK.\", template) except ClientError as e: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"])",
"import logging from boto3.session import Session from botocore.exceptions import ClientError from argparse import",
"create_stack(self, stack_name, cfn, input): w = cfn.get_waiter(\"stack_create_complete\") try: cfn.create_stack(**input) logger.info(\"Create %s.\", stack_name) w.wait(",
"], } try: self.create_stack(stack_name, cfn, input) except ClientError as e: logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) return",
"in TEMPLATES: path = os.getcwd() + t body = open(path).read() stack_name = app_name",
"\" + sys.argv[0] + \" [-h | --help] [-a | --app <APP_NAME>] [-p",
"logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Provisiond stack def provisiond(self, app_name, profile, region): session = Session(profile_name=profile,",
"logger.info(\"%s is validation OK.\", template) except ClientError as e: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) #",
"re.sub('\\/(.*)\\/(.*)\\.yml', '\\\\1-\\\\2', t) self.valid_template(t, body, cfn) input = { \"StackName\": stack_name, \"TemplateBody\": body,",
"return else: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Valid CFn template. def valid_template(self, template, body,",
"self.valid_template(t, body, cfn) input = { \"StackName\": stack_name, \"TemplateBody\": body, \"Capabilities\": [ 'CAPABILITY_NAMED_IAM',",
"stack_name) except ClientError as e: if e.response[\"Error\"][\"Code\"] == \"AlreadyExistsException\": self.update_stack(stack_name, cfn, input) return",
"\"StackName\": stack_name, \"TemplateBody\": body, \"Capabilities\": [ 'CAPABILITY_NAMED_IAM', ], \"Parameters\": [ { \"ParameterKey\": \"AppName\",",
"= [ \"/scripts/ec2.yml\", ] logger = logging.getLogger() formatter = '%(levelname)s : %(asctime)s :",
"try: cfn.create_stack(**input) logger.info(\"Create %s.\", stack_name) w.wait( StackName = stack_name, ) return logger.info(\"Create %s",
"cfn) input = { \"StackName\": stack_name, \"TemplateBody\": body, \"Capabilities\": [ 'CAPABILITY_NAMED_IAM', ], \"Parameters\":",
"from argparse import ArgumentParser TEMPLATES = [ \"/scripts/ec2.yml\", ] logger = logging.getLogger() formatter",
"format=formatter) class DeployStack: # Option parser. def get_option(self): usage = \"python \" +",
"try: cfn.validate_template( TemplateBody = body, ) return logger.info(\"%s is validation OK.\", template) except",
"= res[\"KeyMaterial\"] pem_file = open(os.environ[\"HOME\"] + \"/.ssh/\" + app_name + \".pem\", \"w\") pem_file.write(private_key)",
"def get_option(self): usage = \"python \" + sys.argv[0] + \" [-h | --help]",
"CFn stacks. def update_stack(self, stack_name, cfn, input): w = cfn.get_waiter(\"stack_update_complete\") try: cfn.update_stack(**input) logger.info(\"Update",
"session.client(\"cloudformation\") for t in TEMPLATES: path = os.getcwd() + t body = open(path).read()",
"Option parser. def get_option(self): usage = \"python \" + sys.argv[0] + \" [-h",
"template) except ClientError as e: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Create EC2 keypair. #",
"--app <APP_NAME>] [-p | --profile <AWS_PROFILE>] [-r | --region <AWS_REGION>]\" argparser = ArgumentParser(usage=usage)",
"app_name, profile, region): session = Session(profile_name=profile, region_name=region) self.create_keypair(app_name, session) cfn = session.client(\"cloudformation\") for",
"logger.info(\"Create %s.\", stack_name) w.wait( StackName = stack_name, ) return logger.info(\"Create %s complete.\", stack_name)",
"%s.\", stack_name) w.wait( StackName = stack_name, ) return logger.info(\"Create %s complete.\", stack_name) except",
"coding: utf-8 -*- import glob import os import re import sys import logging",
"sys.argv[0] + \" [-h | --help] [-a | --app <APP_NAME>] [-p | --profile",
"except ClientError as e: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Create EC2 keypair. # 秘密鍵は",
"validation OK.\", template) except ClientError as e: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Create EC2",
"options.profile region = options.region self.provisiond(app_name, profile, region) return logger.info(\"Finish provision stacks.\") if __name__",
"Session from botocore.exceptions import ClientError from argparse import ArgumentParser TEMPLATES = [ \"/scripts/ec2.yml\",",
"= Session(profile_name=profile, region_name=region) self.create_keypair(app_name, session) cfn = session.client(\"cloudformation\") for t in TEMPLATES: path",
"-*- import glob import os import re import sys import logging from boto3.session",
") return logger.info(\"Create %s complete.\", stack_name) except ClientError as e: if e.response[\"Error\"][\"Code\"] ==",
"def main(): logger.info(\"Start provision stacks.\") self = DeployStack() options = self.get_option() app_name =",
"e: logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) return @staticmethod def main(): logger.info(\"Start provision stacks.\") self = DeployStack()",
"%s KeyPair.\", app_name) ec2 = session.client(\"ec2\") try: ec2.describe_key_pairs( KeyNames=[ app_name, ], ) return",
"stack_name, cfn, input): w = cfn.get_waiter(\"stack_create_complete\") try: cfn.create_stack(**input) logger.info(\"Create %s.\", stack_name) w.wait( StackName",
"stack_name = app_name + \"-\" + re.sub('\\/(.*)\\/(.*)\\.yml', '\\\\1-\\\\2', t) self.valid_template(t, body, cfn) input",
"permission: 0600) def create_keypair(self, app_name, session): logger.info(\"Create %s KeyPair.\", app_name) ec2 = session.client(\"ec2\")",
"sys import logging from boto3.session import Session from botocore.exceptions import ClientError from argparse",
"region): session = Session(profile_name=profile, region_name=region) self.create_keypair(app_name, session) cfn = session.client(\"cloudformation\") for t in",
"ArgumentParser TEMPLATES = [ \"/scripts/ec2.yml\", ] logger = logging.getLogger() formatter = '%(levelname)s :",
"return logger.info(\"Create %s complete.\", stack_name) except ClientError as e: if e.response[\"Error\"][\"Code\"] == \"AlreadyExistsException\":",
"ClientError as e: logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) return @staticmethod def main(): logger.info(\"Start provision stacks.\") self",
"open(os.environ[\"HOME\"] + \"/.ssh/\" + app_name + \".pem\", \"w\") pem_file.write(private_key) pem_file.close os.chmod(os.environ[\"HOME\"] + \"/.ssh/\"",
"t) self.valid_template(t, body, cfn) input = { \"StackName\": stack_name, \"TemplateBody\": body, \"Capabilities\": [",
"self = DeployStack() options = self.get_option() app_name = options.app profile = options.profile region",
"Valid CFn template. def valid_template(self, template, body, cfn): logger.info(\"Validate checks %s\", template) try:",
"= session.client(\"cloudformation\") for t in TEMPLATES: path = os.getcwd() + t body =",
"as e: if e.response[\"Error\"][\"Code\"] == \"AlreadyExistsException\": self.update_stack(stack_name, cfn, input) return else: return logger.warning(\"%s\",",
"type=str, default=\"default\", help=\"~/.aws/config.\") argparser.add_argument(\"-r\", \"--region\", type=str, default=\"ap-northeast-1\", help=\"AWs regions. e.g. ap-northeast-1, us-east-1, ...\")",
"pem_file = open(os.environ[\"HOME\"] + \"/.ssh/\" + app_name + \".pem\", \"w\") pem_file.write(private_key) pem_file.close os.chmod(os.environ[\"HOME\"]",
"body, cfn) input = { \"StackName\": stack_name, \"TemplateBody\": body, \"Capabilities\": [ 'CAPABILITY_NAMED_IAM', ],",
"logging from boto3.session import Session from botocore.exceptions import ClientError from argparse import ArgumentParser",
"\"/scripts/ec2.yml\", ] logger = logging.getLogger() formatter = '%(levelname)s : %(asctime)s : %(message)s' logging.basicConfig(level=logging.INFO,",
"us-east-1, ...\") return argparser.parse_args() # Update CFn stacks. def update_stack(self, stack_name, cfn, input):",
"= cfn.get_waiter(\"stack_update_complete\") try: cfn.update_stack(**input) logger.info(\"Update %s.\", stack_name) w.wait( StackName = stack_name, ) return",
"e: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Create EC2 keypair. # 秘密鍵は ~/.ssh/ 配下に書き出す(file permission:",
"--profile <AWS_PROFILE>] [-r | --region <AWS_REGION>]\" argparser = ArgumentParser(usage=usage) argparser.add_argument(\"-a\", \"--app\", type=str, default=\"snatch\",",
"already exists.\", app_name) except ClientError as e: if e.response[\"Error\"][\"Code\"] == \"InvalidKeyPair.NotFound\": res =",
"created.\", app_name) else: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Provisiond stack def provisiond(self, app_name, profile,",
"help=\"AWs regions. e.g. ap-northeast-1, us-east-1, ...\") return argparser.parse_args() # Update CFn stacks. def",
"else: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Provisiond stack def provisiond(self, app_name, profile, region): session",
"body, \"Capabilities\": [ 'CAPABILITY_NAMED_IAM', ], \"Parameters\": [ { \"ParameterKey\": \"AppName\", \"ParameterValue\": app_name, },",
"%s\", template) try: cfn.validate_template( TemplateBody = body, ) return logger.info(\"%s is validation OK.\",",
"\"AppName\", \"ParameterValue\": app_name, }, ], } try: self.create_stack(stack_name, cfn, input) except ClientError as",
"return argparser.parse_args() # Update CFn stacks. def update_stack(self, stack_name, cfn, input): w =",
"[ 'CAPABILITY_NAMED_IAM', ], \"Parameters\": [ { \"ParameterKey\": \"AppName\", \"ParameterValue\": app_name, }, ], }",
"+ \".pem\", \"w\") pem_file.write(private_key) pem_file.close os.chmod(os.environ[\"HOME\"] + \"/.ssh/\" + app_name + \".pem\", 0o600)",
"stack_name, ) return logger.info(\"Update %s complete.\", stack_name) except ClientError as e: return logger.warning(\"%s\",",
"e.response[\"Error\"][\"Message\"]) # Create EC2 keypair. # 秘密鍵は ~/.ssh/ 配下に書き出す(file permission: 0600) def create_keypair(self,",
"StackName = stack_name, ) return logger.info(\"Create %s complete.\", stack_name) except ClientError as e:",
"def update_stack(self, stack_name, cfn, input): w = cfn.get_waiter(\"stack_update_complete\") try: cfn.update_stack(**input) logger.info(\"Update %s.\", stack_name)",
"logger.info(\"%s KeyPair already exists.\", app_name) except ClientError as e: if e.response[\"Error\"][\"Code\"] == \"InvalidKeyPair.NotFound\":",
"except ClientError as e: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Create CFn stacks. def create_stack(self,",
"| --region <AWS_REGION>]\" argparser = ArgumentParser(usage=usage) argparser.add_argument(\"-a\", \"--app\", type=str, default=\"snatch\", help=\"Target app name.\")",
"= body, ) return logger.info(\"%s is validation OK.\", template) except ClientError as e:",
"e.response[\"Error\"][\"Message\"]) return @staticmethod def main(): logger.info(\"Start provision stacks.\") self = DeployStack() options =",
"boto3.session import Session from botocore.exceptions import ClientError from argparse import ArgumentParser TEMPLATES =",
"ClientError as e: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Create CFn stacks. def create_stack(self, stack_name,",
"valid_template(self, template, body, cfn): logger.info(\"Validate checks %s\", template) try: cfn.validate_template( TemplateBody = body,",
"template) try: cfn.validate_template( TemplateBody = body, ) return logger.info(\"%s is validation OK.\", template)",
"os import re import sys import logging from boto3.session import Session from botocore.exceptions",
"as e: logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) return @staticmethod def main(): logger.info(\"Start provision stacks.\") self =",
"= options.app profile = options.profile region = options.region self.provisiond(app_name, profile, region) return logger.info(\"Finish",
"= self.get_option() app_name = options.app profile = options.profile region = options.region self.provisiond(app_name, profile,",
"}, ], } try: self.create_stack(stack_name, cfn, input) except ClientError as e: logger.warning(\"%s\", e.response[\"Error\"][\"Message\"])",
"profile, region): session = Session(profile_name=profile, region_name=region) self.create_keypair(app_name, session) cfn = session.client(\"cloudformation\") for t",
"%(message)s' logging.basicConfig(level=logging.INFO, format=formatter) class DeployStack: # Option parser. def get_option(self): usage = \"python",
"path = os.getcwd() + t body = open(path).read() stack_name = app_name + \"-\"",
"app_name, ], ) return logger.info(\"%s KeyPair already exists.\", app_name) except ClientError as e:",
"cfn.create_stack(**input) logger.info(\"Create %s.\", stack_name) w.wait( StackName = stack_name, ) return logger.info(\"Create %s complete.\",",
"= options.region self.provisiond(app_name, profile, region) return logger.info(\"Finish provision stacks.\") if __name__ == '__main__':",
"%(asctime)s : %(message)s' logging.basicConfig(level=logging.INFO, format=formatter) class DeployStack: # Option parser. def get_option(self): usage",
"import Session from botocore.exceptions import ClientError from argparse import ArgumentParser TEMPLATES = [",
"ec2 = session.client(\"ec2\") try: ec2.describe_key_pairs( KeyNames=[ app_name, ], ) return logger.info(\"%s KeyPair already",
"template. def valid_template(self, template, body, cfn): logger.info(\"Validate checks %s\", template) try: cfn.validate_template( TemplateBody",
"cfn.update_stack(**input) logger.info(\"Update %s.\", stack_name) w.wait( StackName = stack_name, ) return logger.info(\"Update %s complete.\",",
"region = options.region self.provisiond(app_name, profile, region) return logger.info(\"Finish provision stacks.\") if __name__ ==",
"formatter = '%(levelname)s : %(asctime)s : %(message)s' logging.basicConfig(level=logging.INFO, format=formatter) class DeployStack: # Option",
"= os.getcwd() + t body = open(path).read() stack_name = app_name + \"-\" +",
"DeployStack() options = self.get_option() app_name = options.app profile = options.profile region = options.region",
"from boto3.session import Session from botocore.exceptions import ClientError from argparse import ArgumentParser TEMPLATES",
"\"-\" + re.sub('\\/(.*)\\/(.*)\\.yml', '\\\\1-\\\\2', t) self.valid_template(t, body, cfn) input = { \"StackName\": stack_name,",
"# 秘密鍵は ~/.ssh/ 配下に書き出す(file permission: 0600) def create_keypair(self, app_name, session): logger.info(\"Create %s KeyPair.\",",
"pem_file.write(private_key) pem_file.close os.chmod(os.environ[\"HOME\"] + \"/.ssh/\" + app_name + \".pem\", 0o600) return logger.info(\"%s KeyPair",
"if e.response[\"Error\"][\"Code\"] == \"InvalidKeyPair.NotFound\": res = ec2.create_key_pair( KeyName=app_name, ) private_key = res[\"KeyMaterial\"] pem_file",
"'\\\\1-\\\\2', t) self.valid_template(t, body, cfn) input = { \"StackName\": stack_name, \"TemplateBody\": body, \"Capabilities\":",
"# Create CFn stacks. def create_stack(self, stack_name, cfn, input): w = cfn.get_waiter(\"stack_create_complete\") try:",
"[ \"/scripts/ec2.yml\", ] logger = logging.getLogger() formatter = '%(levelname)s : %(asctime)s : %(message)s'",
"class DeployStack: # Option parser. def get_option(self): usage = \"python \" + sys.argv[0]",
"\"python \" + sys.argv[0] + \" [-h | --help] [-a | --app <APP_NAME>]",
"= open(path).read() stack_name = app_name + \"-\" + re.sub('\\/(.*)\\/(.*)\\.yml', '\\\\1-\\\\2', t) self.valid_template(t, body,",
"\".pem\", 0o600) return logger.info(\"%s KeyPair created.\", app_name) else: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Provisiond",
"options.region self.provisiond(app_name, profile, region) return logger.info(\"Finish provision stacks.\") if __name__ == '__main__': DeployStack.main()",
"logger.info(\"Update %s.\", stack_name) w.wait( StackName = stack_name, ) return logger.info(\"Update %s complete.\", stack_name)",
"= cfn.get_waiter(\"stack_create_complete\") try: cfn.create_stack(**input) logger.info(\"Create %s.\", stack_name) w.wait( StackName = stack_name, ) return",
"\"--app\", type=str, default=\"snatch\", help=\"Target app name.\") argparser.add_argument(\"-p\", \"--profile\", type=str, default=\"default\", help=\"~/.aws/config.\") argparser.add_argument(\"-r\", \"--region\",",
"region_name=region) self.create_keypair(app_name, session) cfn = session.client(\"cloudformation\") for t in TEMPLATES: path = os.getcwd()",
"default=\"snatch\", help=\"Target app name.\") argparser.add_argument(\"-p\", \"--profile\", type=str, default=\"default\", help=\"~/.aws/config.\") argparser.add_argument(\"-r\", \"--region\", type=str, default=\"ap-northeast-1\",",
"%s.\", stack_name) w.wait( StackName = stack_name, ) return logger.info(\"Update %s complete.\", stack_name) except",
"as e: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Create EC2 keypair. # 秘密鍵は ~/.ssh/ 配下に書き出す(file",
"= ec2.create_key_pair( KeyName=app_name, ) private_key = res[\"KeyMaterial\"] pem_file = open(os.environ[\"HOME\"] + \"/.ssh/\" +",
"except ClientError as e: logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) return @staticmethod def main(): logger.info(\"Start provision stacks.\")",
"input) return else: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Valid CFn template. def valid_template(self, template,",
"argparser.add_argument(\"-p\", \"--profile\", type=str, default=\"default\", help=\"~/.aws/config.\") argparser.add_argument(\"-r\", \"--region\", type=str, default=\"ap-northeast-1\", help=\"AWs regions. e.g. ap-northeast-1,",
"return logger.info(\"%s KeyPair already exists.\", app_name) except ClientError as e: if e.response[\"Error\"][\"Code\"] ==",
"\"--region\", type=str, default=\"ap-northeast-1\", help=\"AWs regions. e.g. ap-northeast-1, us-east-1, ...\") return argparser.parse_args() # Update",
"<APP_NAME>] [-p | --profile <AWS_PROFILE>] [-r | --region <AWS_REGION>]\" argparser = ArgumentParser(usage=usage) argparser.add_argument(\"-a\",",
"TemplateBody = body, ) return logger.info(\"%s is validation OK.\", template) except ClientError as",
"配下に書き出す(file permission: 0600) def create_keypair(self, app_name, session): logger.info(\"Create %s KeyPair.\", app_name) ec2 =",
"== \"InvalidKeyPair.NotFound\": res = ec2.create_key_pair( KeyName=app_name, ) private_key = res[\"KeyMaterial\"] pem_file = open(os.environ[\"HOME\"]",
"%s complete.\", stack_name) except ClientError as e: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Create CFn",
"w = cfn.get_waiter(\"stack_create_complete\") try: cfn.create_stack(**input) logger.info(\"Create %s.\", stack_name) w.wait( StackName = stack_name, )",
"'CAPABILITY_NAMED_IAM', ], \"Parameters\": [ { \"ParameterKey\": \"AppName\", \"ParameterValue\": app_name, }, ], } try:",
"res = ec2.create_key_pair( KeyName=app_name, ) private_key = res[\"KeyMaterial\"] pem_file = open(os.environ[\"HOME\"] + \"/.ssh/\"",
"open(path).read() stack_name = app_name + \"-\" + re.sub('\\/(.*)\\/(.*)\\.yml', '\\\\1-\\\\2', t) self.valid_template(t, body, cfn)",
"[-p | --profile <AWS_PROFILE>] [-r | --region <AWS_REGION>]\" argparser = ArgumentParser(usage=usage) argparser.add_argument(\"-a\", \"--app\",",
"os.chmod(os.environ[\"HOME\"] + \"/.ssh/\" + app_name + \".pem\", 0o600) return logger.info(\"%s KeyPair created.\", app_name)",
"DeployStack: # Option parser. def get_option(self): usage = \"python \" + sys.argv[0] +",
"Provisiond stack def provisiond(self, app_name, profile, region): session = Session(profile_name=profile, region_name=region) self.create_keypair(app_name, session)",
"from botocore.exceptions import ClientError from argparse import ArgumentParser TEMPLATES = [ \"/scripts/ec2.yml\", ]",
"logger.info(\"Validate checks %s\", template) try: cfn.validate_template( TemplateBody = body, ) return logger.info(\"%s is",
"+ \"/.ssh/\" + app_name + \".pem\", 0o600) return logger.info(\"%s KeyPair created.\", app_name) else:",
"e: if e.response[\"Error\"][\"Code\"] == \"InvalidKeyPair.NotFound\": res = ec2.create_key_pair( KeyName=app_name, ) private_key = res[\"KeyMaterial\"]",
"if e.response[\"Error\"][\"Code\"] == \"AlreadyExistsException\": self.update_stack(stack_name, cfn, input) return else: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) #",
"def valid_template(self, template, body, cfn): logger.info(\"Validate checks %s\", template) try: cfn.validate_template( TemplateBody =",
"logger.info(\"Start provision stacks.\") self = DeployStack() options = self.get_option() app_name = options.app profile",
"\"Parameters\": [ { \"ParameterKey\": \"AppName\", \"ParameterValue\": app_name, }, ], } try: self.create_stack(stack_name, cfn,",
"stacks. def create_stack(self, stack_name, cfn, input): w = cfn.get_waiter(\"stack_create_complete\") try: cfn.create_stack(**input) logger.info(\"Create %s.\",",
"= { \"StackName\": stack_name, \"TemplateBody\": body, \"Capabilities\": [ 'CAPABILITY_NAMED_IAM', ], \"Parameters\": [ {",
"ArgumentParser(usage=usage) argparser.add_argument(\"-a\", \"--app\", type=str, default=\"snatch\", help=\"Target app name.\") argparser.add_argument(\"-p\", \"--profile\", type=str, default=\"default\", help=\"~/.aws/config.\")",
"e.response[\"Error\"][\"Code\"] == \"AlreadyExistsException\": self.update_stack(stack_name, cfn, input) return else: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Valid",
"logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) return @staticmethod def main(): logger.info(\"Start provision stacks.\") self = DeployStack() options",
"try: ec2.describe_key_pairs( KeyNames=[ app_name, ], ) return logger.info(\"%s KeyPair already exists.\", app_name) except",
"KeyPair.\", app_name) ec2 = session.client(\"ec2\") try: ec2.describe_key_pairs( KeyNames=[ app_name, ], ) return logger.info(\"%s",
"<AWS_REGION>]\" argparser = ArgumentParser(usage=usage) argparser.add_argument(\"-a\", \"--app\", type=str, default=\"snatch\", help=\"Target app name.\") argparser.add_argument(\"-p\", \"--profile\",",
"cfn.validate_template( TemplateBody = body, ) return logger.info(\"%s is validation OK.\", template) except ClientError",
"input = { \"StackName\": stack_name, \"TemplateBody\": body, \"Capabilities\": [ 'CAPABILITY_NAMED_IAM', ], \"Parameters\": [",
"cfn, input) except ClientError as e: logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) return @staticmethod def main(): logger.info(\"Start",
"usage = \"python \" + sys.argv[0] + \" [-h | --help] [-a |",
"e.response[\"Error\"][\"Message\"]) # Create CFn stacks. def create_stack(self, stack_name, cfn, input): w = cfn.get_waiter(\"stack_create_complete\")",
"default=\"default\", help=\"~/.aws/config.\") argparser.add_argument(\"-r\", \"--region\", type=str, default=\"ap-northeast-1\", help=\"AWs regions. e.g. ap-northeast-1, us-east-1, ...\") return",
"re import sys import logging from boto3.session import Session from botocore.exceptions import ClientError",
"regions. e.g. ap-northeast-1, us-east-1, ...\") return argparser.parse_args() # Update CFn stacks. def update_stack(self,",
": %(asctime)s : %(message)s' logging.basicConfig(level=logging.INFO, format=formatter) class DeployStack: # Option parser. def get_option(self):",
"~/.ssh/ 配下に書き出す(file permission: 0600) def create_keypair(self, app_name, session): logger.info(\"Create %s KeyPair.\", app_name) ec2",
"+ app_name + \".pem\", 0o600) return logger.info(\"%s KeyPair created.\", app_name) else: return logger.warning(\"%s\",",
"@staticmethod def main(): logger.info(\"Start provision stacks.\") self = DeployStack() options = self.get_option() app_name",
"Create EC2 keypair. # 秘密鍵は ~/.ssh/ 配下に書き出す(file permission: 0600) def create_keypair(self, app_name, session):",
"%s complete.\", stack_name) except ClientError as e: if e.response[\"Error\"][\"Code\"] == \"AlreadyExistsException\": self.update_stack(stack_name, cfn,",
"+ t body = open(path).read() stack_name = app_name + \"-\" + re.sub('\\/(.*)\\/(.*)\\.yml', '\\\\1-\\\\2',",
"== \"AlreadyExistsException\": self.update_stack(stack_name, cfn, input) return else: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Valid CFn",
"+ app_name + \".pem\", \"w\") pem_file.write(private_key) pem_file.close os.chmod(os.environ[\"HOME\"] + \"/.ssh/\" + app_name +",
"input) except ClientError as e: logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) return @staticmethod def main(): logger.info(\"Start provision",
"= open(os.environ[\"HOME\"] + \"/.ssh/\" + app_name + \".pem\", \"w\") pem_file.write(private_key) pem_file.close os.chmod(os.environ[\"HOME\"] +",
"# Option parser. def get_option(self): usage = \"python \" + sys.argv[0] + \"",
"} try: self.create_stack(stack_name, cfn, input) except ClientError as e: logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) return @staticmethod",
"session = Session(profile_name=profile, region_name=region) self.create_keypair(app_name, session) cfn = session.client(\"cloudformation\") for t in TEMPLATES:",
"try: self.create_stack(stack_name, cfn, input) except ClientError as e: logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) return @staticmethod def",
"= options.profile region = options.region self.provisiond(app_name, profile, region) return logger.info(\"Finish provision stacks.\") if",
"\"/.ssh/\" + app_name + \".pem\", 0o600) return logger.info(\"%s KeyPair created.\", app_name) else: return",
"pem_file.close os.chmod(os.environ[\"HOME\"] + \"/.ssh/\" + app_name + \".pem\", 0o600) return logger.info(\"%s KeyPair created.\",",
"import sys import logging from boto3.session import Session from botocore.exceptions import ClientError from",
"argparse import ArgumentParser TEMPLATES = [ \"/scripts/ec2.yml\", ] logger = logging.getLogger() formatter =",
"logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Valid CFn template. def valid_template(self, template, body, cfn): logger.info(\"Validate checks",
"\"/.ssh/\" + app_name + \".pem\", \"w\") pem_file.write(private_key) pem_file.close os.chmod(os.environ[\"HOME\"] + \"/.ssh/\" + app_name",
"is validation OK.\", template) except ClientError as e: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Create",
"default=\"ap-northeast-1\", help=\"AWs regions. e.g. ap-northeast-1, us-east-1, ...\") return argparser.parse_args() # Update CFn stacks.",
"ClientError as e: if e.response[\"Error\"][\"Code\"] == \"AlreadyExistsException\": self.update_stack(stack_name, cfn, input) return else: return",
"app_name + \".pem\", 0o600) return logger.info(\"%s KeyPair created.\", app_name) else: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"])",
"body, cfn): logger.info(\"Validate checks %s\", template) try: cfn.validate_template( TemplateBody = body, ) return",
"e: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Create CFn stacks. def create_stack(self, stack_name, cfn, input):",
"exists.\", app_name) except ClientError as e: if e.response[\"Error\"][\"Code\"] == \"InvalidKeyPair.NotFound\": res = ec2.create_key_pair(",
"app_name = options.app profile = options.profile region = options.region self.provisiond(app_name, profile, region) return",
"type=str, default=\"snatch\", help=\"Target app name.\") argparser.add_argument(\"-p\", \"--profile\", type=str, default=\"default\", help=\"~/.aws/config.\") argparser.add_argument(\"-r\", \"--region\", type=str,",
"stack_name, cfn, input): w = cfn.get_waiter(\"stack_update_complete\") try: cfn.update_stack(**input) logger.info(\"Update %s.\", stack_name) w.wait( StackName",
"argparser.parse_args() # Update CFn stacks. def update_stack(self, stack_name, cfn, input): w = cfn.get_waiter(\"stack_update_complete\")",
"def provisiond(self, app_name, profile, region): session = Session(profile_name=profile, region_name=region) self.create_keypair(app_name, session) cfn =",
"EC2 keypair. # 秘密鍵は ~/.ssh/ 配下に書き出す(file permission: 0600) def create_keypair(self, app_name, session): logger.info(\"Create",
"秘密鍵は ~/.ssh/ 配下に書き出す(file permission: 0600) def create_keypair(self, app_name, session): logger.info(\"Create %s KeyPair.\", app_name)",
"logger.info(\"Create %s KeyPair.\", app_name) ec2 = session.client(\"ec2\") try: ec2.describe_key_pairs( KeyNames=[ app_name, ], )",
"import re import sys import logging from boto3.session import Session from botocore.exceptions import",
"KeyPair already exists.\", app_name) except ClientError as e: if e.response[\"Error\"][\"Code\"] == \"InvalidKeyPair.NotFound\": res",
"= stack_name, ) return logger.info(\"Update %s complete.\", stack_name) except ClientError as e: return",
"main(): logger.info(\"Start provision stacks.\") self = DeployStack() options = self.get_option() app_name = options.app",
"CFn stacks. def create_stack(self, stack_name, cfn, input): w = cfn.get_waiter(\"stack_create_complete\") try: cfn.create_stack(**input) logger.info(\"Create",
"+ \"/.ssh/\" + app_name + \".pem\", \"w\") pem_file.write(private_key) pem_file.close os.chmod(os.environ[\"HOME\"] + \"/.ssh/\" +",
"self.update_stack(stack_name, cfn, input) return else: return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Valid CFn template. def",
"as e: if e.response[\"Error\"][\"Code\"] == \"InvalidKeyPair.NotFound\": res = ec2.create_key_pair( KeyName=app_name, ) private_key =",
"{ \"ParameterKey\": \"AppName\", \"ParameterValue\": app_name, }, ], } try: self.create_stack(stack_name, cfn, input) except",
"app_name, session): logger.info(\"Create %s KeyPair.\", app_name) ec2 = session.client(\"ec2\") try: ec2.describe_key_pairs( KeyNames=[ app_name,",
"logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Create EC2 keypair. # 秘密鍵は ~/.ssh/ 配下に書き出す(file permission: 0600) def",
"= logging.getLogger() formatter = '%(levelname)s : %(asctime)s : %(message)s' logging.basicConfig(level=logging.INFO, format=formatter) class DeployStack:",
"return logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Provisiond stack def provisiond(self, app_name, profile, region): session =",
"logger.warning(\"%s\", e.response[\"Error\"][\"Message\"]) # Create CFn stacks. def create_stack(self, stack_name, cfn, input): w =",
"name.\") argparser.add_argument(\"-p\", \"--profile\", type=str, default=\"default\", help=\"~/.aws/config.\") argparser.add_argument(\"-r\", \"--region\", type=str, default=\"ap-northeast-1\", help=\"AWs regions. e.g.",
"# Valid CFn template. def valid_template(self, template, body, cfn): logger.info(\"Validate checks %s\", template)",
"create_keypair(self, app_name, session): logger.info(\"Create %s KeyPair.\", app_name) ec2 = session.client(\"ec2\") try: ec2.describe_key_pairs( KeyNames=[",
") return logger.info(\"%s KeyPair already exists.\", app_name) except ClientError as e: if e.response[\"Error\"][\"Code\"]",
"res[\"KeyMaterial\"] pem_file = open(os.environ[\"HOME\"] + \"/.ssh/\" + app_name + \".pem\", \"w\") pem_file.write(private_key) pem_file.close",
"help=\"Target app name.\") argparser.add_argument(\"-p\", \"--profile\", type=str, default=\"default\", help=\"~/.aws/config.\") argparser.add_argument(\"-r\", \"--region\", type=str, default=\"ap-northeast-1\", help=\"AWs",
"--help] [-a | --app <APP_NAME>] [-p | --profile <AWS_PROFILE>] [-r | --region <AWS_REGION>]\"",
"\"InvalidKeyPair.NotFound\": res = ec2.create_key_pair( KeyName=app_name, ) private_key = res[\"KeyMaterial\"] pem_file = open(os.environ[\"HOME\"] +",
"= app_name + \"-\" + re.sub('\\/(.*)\\/(.*)\\.yml', '\\\\1-\\\\2', t) self.valid_template(t, body, cfn) input =",
"cfn, input): w = cfn.get_waiter(\"stack_create_complete\") try: cfn.create_stack(**input) logger.info(\"Create %s.\", stack_name) w.wait( StackName =",
"stack def provisiond(self, app_name, profile, region): session = Session(profile_name=profile, region_name=region) self.create_keypair(app_name, session) cfn",
"[-r | --region <AWS_REGION>]\" argparser = ArgumentParser(usage=usage) argparser.add_argument(\"-a\", \"--app\", type=str, default=\"snatch\", help=\"Target app",
"], \"Parameters\": [ { \"ParameterKey\": \"AppName\", \"ParameterValue\": app_name, }, ], } try: self.create_stack(stack_name,"
] |
[
"-> None: return None class NonIntrospectableDeprecated: async def on_introspection( self, _directive_args: Dict[str, Any],",
"None def bake(schema_name, _config): sdl = \"\"\" directive @nonIntrospectable on FIELD_DEFINITION directive @non_introspectable",
"return None class NonIntrospectableDeprecated: async def on_introspection( self, _directive_args: Dict[str, Any], _next_directive: Callable,",
"-> None: print( \"@non_introspectable is deprecated, please use @nonIntrospectable, will be removed in",
"typing import Any, Callable, Dict, Optional from tartiflette import Directive class NonIntrospectable: async",
"deprecated, please use @nonIntrospectable, will be removed in 0.12.0\" ) return None def",
"\"@non_introspectable is deprecated, please use @nonIntrospectable, will be removed in 0.12.0\" ) return",
"NonIntrospectableDeprecated: async def on_introspection( self, _directive_args: Dict[str, Any], _next_directive: Callable, _introspected_element: Any, _ctx:",
"None class NonIntrospectableDeprecated: async def on_introspection( self, _directive_args: Dict[str, Any], _next_directive: Callable, _introspected_element:",
"directive @non_introspectable on FIELD_DEFINITION \"\"\" Directive(name=\"nonIntrospectable\", schema_name=schema_name)( NonIntrospectable() ) Directive(name=\"non_introspectable\", schema_name=schema_name)( NonIntrospectableDeprecated() )",
"0.12.0\" ) return None def bake(schema_name, _config): sdl = \"\"\" directive @nonIntrospectable on",
"@nonIntrospectable on FIELD_DEFINITION directive @non_introspectable on FIELD_DEFINITION \"\"\" Directive(name=\"nonIntrospectable\", schema_name=schema_name)( NonIntrospectable() ) Directive(name=\"non_introspectable\",",
"NonIntrospectable: async def on_introspection( self, _directive_args: Dict[str, Any], _next_directive: Callable, _introspected_element: Any, _ctx:",
"_introspected_element: Any, _ctx: Optional[Dict[str, Any]], _info: \"Info\", ) -> None: print( \"@non_introspectable is",
"def bake(schema_name, _config): sdl = \"\"\" directive @nonIntrospectable on FIELD_DEFINITION directive @non_introspectable on",
"_config): sdl = \"\"\" directive @nonIntrospectable on FIELD_DEFINITION directive @non_introspectable on FIELD_DEFINITION \"\"\"",
"Any, _ctx: Optional[Dict[str, Any]], _info: \"Info\", ) -> None: return None class NonIntrospectableDeprecated:",
"_info: \"Info\", ) -> None: return None class NonIntrospectableDeprecated: async def on_introspection( self,",
"on_introspection( self, _directive_args: Dict[str, Any], _next_directive: Callable, _introspected_element: Any, _ctx: Optional[Dict[str, Any]], _info:",
"from tartiflette import Directive class NonIntrospectable: async def on_introspection( self, _directive_args: Dict[str, Any],",
"_next_directive: Callable, _introspected_element: Any, _ctx: Optional[Dict[str, Any]], _info: \"Info\", ) -> None: return",
"_info: \"Info\", ) -> None: print( \"@non_introspectable is deprecated, please use @nonIntrospectable, will",
"Any]], _info: \"Info\", ) -> None: print( \"@non_introspectable is deprecated, please use @nonIntrospectable,",
"Any, Callable, Dict, Optional from tartiflette import Directive class NonIntrospectable: async def on_introspection(",
"bake(schema_name, _config): sdl = \"\"\" directive @nonIntrospectable on FIELD_DEFINITION directive @non_introspectable on FIELD_DEFINITION",
"import Any, Callable, Dict, Optional from tartiflette import Directive class NonIntrospectable: async def",
"use @nonIntrospectable, will be removed in 0.12.0\" ) return None def bake(schema_name, _config):",
"Callable, Dict, Optional from tartiflette import Directive class NonIntrospectable: async def on_introspection( self,",
") -> None: return None class NonIntrospectableDeprecated: async def on_introspection( self, _directive_args: Dict[str,",
"please use @nonIntrospectable, will be removed in 0.12.0\" ) return None def bake(schema_name,",
"Directive class NonIntrospectable: async def on_introspection( self, _directive_args: Dict[str, Any], _next_directive: Callable, _introspected_element:",
"will be removed in 0.12.0\" ) return None def bake(schema_name, _config): sdl =",
"None: print( \"@non_introspectable is deprecated, please use @nonIntrospectable, will be removed in 0.12.0\"",
"self, _directive_args: Dict[str, Any], _next_directive: Callable, _introspected_element: Any, _ctx: Optional[Dict[str, Any]], _info: \"Info\",",
"is deprecated, please use @nonIntrospectable, will be removed in 0.12.0\" ) return None",
"be removed in 0.12.0\" ) return None def bake(schema_name, _config): sdl = \"\"\"",
"def on_introspection( self, _directive_args: Dict[str, Any], _next_directive: Callable, _introspected_element: Any, _ctx: Optional[Dict[str, Any]],",
"_introspected_element: Any, _ctx: Optional[Dict[str, Any]], _info: \"Info\", ) -> None: return None class",
"\"Info\", ) -> None: return None class NonIntrospectableDeprecated: async def on_introspection( self, _directive_args:",
") -> None: print( \"@non_introspectable is deprecated, please use @nonIntrospectable, will be removed",
"<reponame>alexchamberlain/tartiflette<gh_stars>0 from typing import Any, Callable, Dict, Optional from tartiflette import Directive class",
"Callable, _introspected_element: Any, _ctx: Optional[Dict[str, Any]], _info: \"Info\", ) -> None: print( \"@non_introspectable",
"_ctx: Optional[Dict[str, Any]], _info: \"Info\", ) -> None: return None class NonIntrospectableDeprecated: async",
"Optional from tartiflette import Directive class NonIntrospectable: async def on_introspection( self, _directive_args: Dict[str,",
"class NonIntrospectable: async def on_introspection( self, _directive_args: Dict[str, Any], _next_directive: Callable, _introspected_element: Any,",
"Any], _next_directive: Callable, _introspected_element: Any, _ctx: Optional[Dict[str, Any]], _info: \"Info\", ) -> None:",
"= \"\"\" directive @nonIntrospectable on FIELD_DEFINITION directive @non_introspectable on FIELD_DEFINITION \"\"\" Directive(name=\"nonIntrospectable\", schema_name=schema_name)(",
"Callable, _introspected_element: Any, _ctx: Optional[Dict[str, Any]], _info: \"Info\", ) -> None: return None",
"class NonIntrospectableDeprecated: async def on_introspection( self, _directive_args: Dict[str, Any], _next_directive: Callable, _introspected_element: Any,",
"Any, _ctx: Optional[Dict[str, Any]], _info: \"Info\", ) -> None: print( \"@non_introspectable is deprecated,",
"\"\"\" directive @nonIntrospectable on FIELD_DEFINITION directive @non_introspectable on FIELD_DEFINITION \"\"\" Directive(name=\"nonIntrospectable\", schema_name=schema_name)( NonIntrospectable()",
"on FIELD_DEFINITION \"\"\" Directive(name=\"nonIntrospectable\", schema_name=schema_name)( NonIntrospectable() ) Directive(name=\"non_introspectable\", schema_name=schema_name)( NonIntrospectableDeprecated() ) return sdl",
"_directive_args: Dict[str, Any], _next_directive: Callable, _introspected_element: Any, _ctx: Optional[Dict[str, Any]], _info: \"Info\", )",
"Dict, Optional from tartiflette import Directive class NonIntrospectable: async def on_introspection( self, _directive_args:",
"Optional[Dict[str, Any]], _info: \"Info\", ) -> None: print( \"@non_introspectable is deprecated, please use",
"FIELD_DEFINITION directive @non_introspectable on FIELD_DEFINITION \"\"\" Directive(name=\"nonIntrospectable\", schema_name=schema_name)( NonIntrospectable() ) Directive(name=\"non_introspectable\", schema_name=schema_name)( NonIntrospectableDeprecated()",
"Optional[Dict[str, Any]], _info: \"Info\", ) -> None: return None class NonIntrospectableDeprecated: async def",
"async def on_introspection( self, _directive_args: Dict[str, Any], _next_directive: Callable, _introspected_element: Any, _ctx: Optional[Dict[str,",
"import Directive class NonIntrospectable: async def on_introspection( self, _directive_args: Dict[str, Any], _next_directive: Callable,",
"print( \"@non_introspectable is deprecated, please use @nonIntrospectable, will be removed in 0.12.0\" )",
"@nonIntrospectable, will be removed in 0.12.0\" ) return None def bake(schema_name, _config): sdl",
"return None def bake(schema_name, _config): sdl = \"\"\" directive @nonIntrospectable on FIELD_DEFINITION directive",
") return None def bake(schema_name, _config): sdl = \"\"\" directive @nonIntrospectable on FIELD_DEFINITION",
"@non_introspectable on FIELD_DEFINITION \"\"\" Directive(name=\"nonIntrospectable\", schema_name=schema_name)( NonIntrospectable() ) Directive(name=\"non_introspectable\", schema_name=schema_name)( NonIntrospectableDeprecated() ) return",
"in 0.12.0\" ) return None def bake(schema_name, _config): sdl = \"\"\" directive @nonIntrospectable",
"directive @nonIntrospectable on FIELD_DEFINITION directive @non_introspectable on FIELD_DEFINITION \"\"\" Directive(name=\"nonIntrospectable\", schema_name=schema_name)( NonIntrospectable() )",
"removed in 0.12.0\" ) return None def bake(schema_name, _config): sdl = \"\"\" directive",
"\"Info\", ) -> None: print( \"@non_introspectable is deprecated, please use @nonIntrospectable, will be",
"Any]], _info: \"Info\", ) -> None: return None class NonIntrospectableDeprecated: async def on_introspection(",
"from typing import Any, Callable, Dict, Optional from tartiflette import Directive class NonIntrospectable:",
"None: return None class NonIntrospectableDeprecated: async def on_introspection( self, _directive_args: Dict[str, Any], _next_directive:",
"on FIELD_DEFINITION directive @non_introspectable on FIELD_DEFINITION \"\"\" Directive(name=\"nonIntrospectable\", schema_name=schema_name)( NonIntrospectable() ) Directive(name=\"non_introspectable\", schema_name=schema_name)(",
"_next_directive: Callable, _introspected_element: Any, _ctx: Optional[Dict[str, Any]], _info: \"Info\", ) -> None: print(",
"tartiflette import Directive class NonIntrospectable: async def on_introspection( self, _directive_args: Dict[str, Any], _next_directive:",
"_ctx: Optional[Dict[str, Any]], _info: \"Info\", ) -> None: print( \"@non_introspectable is deprecated, please",
"Dict[str, Any], _next_directive: Callable, _introspected_element: Any, _ctx: Optional[Dict[str, Any]], _info: \"Info\", ) ->",
"sdl = \"\"\" directive @nonIntrospectable on FIELD_DEFINITION directive @non_introspectable on FIELD_DEFINITION \"\"\" Directive(name=\"nonIntrospectable\","
] |
[
"1.11.3 on 2018-06-13 11:26 from __future__ import unicode_literals from django.db import migrations, models",
"from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('book', '0002_auto_20180613_1914'), ]",
"'0002_auto_20180613_1914'), ] operations = [ migrations.AlterField( model_name='story', name='image', field=models.ImageField(blank=True, upload_to=b'', verbose_name='\\u56fe\\u7247'), ), ]",
"2018-06-13 11:26 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration):",
"import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('book',",
"-*- # Generated by Django 1.11.3 on 2018-06-13 11:26 from __future__ import unicode_literals",
"unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('book', '0002_auto_20180613_1914'),",
"import migrations, models class Migration(migrations.Migration): dependencies = [ ('book', '0002_auto_20180613_1914'), ] operations =",
"migrations, models class Migration(migrations.Migration): dependencies = [ ('book', '0002_auto_20180613_1914'), ] operations = [",
"on 2018-06-13 11:26 from __future__ import unicode_literals from django.db import migrations, models class",
"Generated by Django 1.11.3 on 2018-06-13 11:26 from __future__ import unicode_literals from django.db",
"django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('book', '0002_auto_20180613_1914'), ] operations",
"11:26 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies",
"-*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2018-06-13 11:26 from",
"# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2018-06-13 11:26",
"[ ('book', '0002_auto_20180613_1914'), ] operations = [ migrations.AlterField( model_name='story', name='image', field=models.ImageField(blank=True, upload_to=b'', verbose_name='\\u56fe\\u7247'),",
"utf-8 -*- # Generated by Django 1.11.3 on 2018-06-13 11:26 from __future__ import",
"('book', '0002_auto_20180613_1914'), ] operations = [ migrations.AlterField( model_name='story', name='image', field=models.ImageField(blank=True, upload_to=b'', verbose_name='\\u56fe\\u7247'), ),",
"by Django 1.11.3 on 2018-06-13 11:26 from __future__ import unicode_literals from django.db import",
"models class Migration(migrations.Migration): dependencies = [ ('book', '0002_auto_20180613_1914'), ] operations = [ migrations.AlterField(",
"coding: utf-8 -*- # Generated by Django 1.11.3 on 2018-06-13 11:26 from __future__",
"from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies =",
"Django 1.11.3 on 2018-06-13 11:26 from __future__ import unicode_literals from django.db import migrations,",
"<reponame>Family-TreeSY/reading<gh_stars>1-10 # -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2018-06-13",
"= [ ('book', '0002_auto_20180613_1914'), ] operations = [ migrations.AlterField( model_name='story', name='image', field=models.ImageField(blank=True, upload_to=b'',",
"dependencies = [ ('book', '0002_auto_20180613_1914'), ] operations = [ migrations.AlterField( model_name='story', name='image', field=models.ImageField(blank=True,",
"__future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [",
"Migration(migrations.Migration): dependencies = [ ('book', '0002_auto_20180613_1914'), ] operations = [ migrations.AlterField( model_name='story', name='image',",
"# Generated by Django 1.11.3 on 2018-06-13 11:26 from __future__ import unicode_literals from",
"class Migration(migrations.Migration): dependencies = [ ('book', '0002_auto_20180613_1914'), ] operations = [ migrations.AlterField( model_name='story',"
] |
[
"fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('parent', models.IntegerField(default=None, null=True)), ], ),",
"serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('parent', models.IntegerField(default=None, null=True)), ], ), migrations.AddField( model_name='media', name='folder', field=models.ForeignKey(default=None,",
"on 2021-03-06 00:49 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies",
"[ migrations.CreateModel( name='MediaFolder', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('parent', models.IntegerField(default=None,",
"name='MediaFolder', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('parent', models.IntegerField(default=None, null=True)), ],",
"django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('suncreative', '0007_postrecord_state'),",
"2.2.13 on 2021-03-06 00:49 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):",
"operations = [ migrations.CreateModel( name='MediaFolder', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)),",
"primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('parent', models.IntegerField(default=None, null=True)), ], ), migrations.AddField( model_name='media', name='folder',",
"migrations.CreateModel( name='MediaFolder', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('parent', models.IntegerField(default=None, null=True)),",
"Django 2.2.13 on 2021-03-06 00:49 from django.db import migrations, models import django.db.models.deletion class",
"'0007_postrecord_state'), ] operations = [ migrations.CreateModel( name='MediaFolder', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"verbose_name='ID')), ('name', models.CharField(max_length=100)), ('parent', models.IntegerField(default=None, null=True)), ], ), migrations.AddField( model_name='media', name='folder', field=models.ForeignKey(default=None, null=True,",
"('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('parent', models.IntegerField(default=None, null=True)), ], ), migrations.AddField(",
"('name', models.CharField(max_length=100)), ('parent', models.IntegerField(default=None, null=True)), ], ), migrations.AddField( model_name='media', name='folder', field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.CASCADE,",
"models.CharField(max_length=100)), ('parent', models.IntegerField(default=None, null=True)), ], ), migrations.AddField( model_name='media', name='folder', field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='文件夹',",
"('parent', models.IntegerField(default=None, null=True)), ], ), migrations.AddField( model_name='media', name='folder', field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='文件夹', to='suncreative.MediaFolder'),",
"import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('suncreative', '0007_postrecord_state'), ] operations = [",
"Migration(migrations.Migration): dependencies = [ ('suncreative', '0007_postrecord_state'), ] operations = [ migrations.CreateModel( name='MediaFolder', fields=[",
"2021-03-06 00:49 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies =",
"class Migration(migrations.Migration): dependencies = [ ('suncreative', '0007_postrecord_state'), ] operations = [ migrations.CreateModel( name='MediaFolder',",
"('suncreative', '0007_postrecord_state'), ] operations = [ migrations.CreateModel( name='MediaFolder', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('suncreative',",
"models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('suncreative', '0007_postrecord_state'), ] operations =",
"migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('suncreative', '0007_postrecord_state'), ] operations",
"by Django 2.2.13 on 2021-03-06 00:49 from django.db import migrations, models import django.db.models.deletion",
"[ ('suncreative', '0007_postrecord_state'), ] operations = [ migrations.CreateModel( name='MediaFolder', 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=100)), ('parent', models.IntegerField(default=None, null=True)), ], ), migrations.AddField( model_name='media',",
"# Generated by Django 2.2.13 on 2021-03-06 00:49 from django.db import migrations, models",
"<gh_stars>1-10 # Generated by Django 2.2.13 on 2021-03-06 00:49 from django.db import migrations,",
"] operations = [ migrations.CreateModel( name='MediaFolder', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name',",
"= [ ('suncreative', '0007_postrecord_state'), ] operations = [ migrations.CreateModel( name='MediaFolder', fields=[ ('id', models.AutoField(auto_created=True,",
"django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('suncreative', '0007_postrecord_state'), ] operations = [ migrations.CreateModel(",
"models.IntegerField(default=None, null=True)), ], ), migrations.AddField( model_name='media', name='folder', field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='文件夹', to='suncreative.MediaFolder'), ),",
"null=True)), ], ), migrations.AddField( model_name='media', name='folder', field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='文件夹', to='suncreative.MediaFolder'), ), ]",
"00:49 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [",
"= [ migrations.CreateModel( name='MediaFolder', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('parent',",
"Generated by Django 2.2.13 on 2021-03-06 00:49 from django.db import migrations, models import",
"import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('suncreative', '0007_postrecord_state'), ]",
"dependencies = [ ('suncreative', '0007_postrecord_state'), ] operations = [ migrations.CreateModel( name='MediaFolder', fields=[ ('id',"
] |
[
"\"\"\" Create a new experiment structure based on the information in the msrun_list.",
"else: experiment['run_start_time'] = None experiment['human_run_start_time'] = None experiment['spectra_count'] = msrun_list.info['spectrum_count'] experiment['experimental_state_id'] = None",
"from \"Peak\" WHERE experiment_id = '{}' AND spectrum_id = '{}'\"\"\"\\ .format(experiment_id, spc.ID)).fetchone() if",
"in Spectrum table. \" + \"To avoid duplicates the spectra won't be added",
"check if experiment_id already exists in Spectrum table. If not, append data to",
"'human_run_start_time', 'spectra_count', 'experimental_state_id', 'match_type_id', 'filename']) # Todo: waarden in onderstaande tabel moeten nog",
"information in the msrun_list. :param msrun_list: an open pymzml runner :param filename: name",
"+ 'scan_window_upper_limit ' + 'scan_window_lower_limit') measurement = namedtuple('measurement', 'experiment_id ' + 'spectrum_id' +",
"level'], highest_observed_mz=spc['highest observed m/z'], lowest_observed_mz=spc['lowest observed m/z'], scan_window_upper_limit=spc['scan window upper limit'], scan_window_lower_limit=spc['scan window",
"{}\".format(experiment_id, spc.ID)) measurement_list.append(m) # check if experiment_id already exists in Spectrum table. If",
".format(experiment_id)).fetchone() if check_spectrum is not None: print((\"Experiment_id {} already exists in Spectrum table.",
"on the information in the msrun_list. :param msrun_list: an open pymzml runner :param",
"DB. Continue to filling Spectrum table\") experiment_id = check[0] else: # fill the",
"'lowest_observed_mz ' + 'scan_window_upper_limit ' + 'scan_window_lower_limit') measurement = namedtuple('measurement', 'experiment_id ' +",
"spectrum_list.append(s) if i == 0: m = measurement(experiment_id=experiment_id, spectrum_id=spc.ID, mz=np.nan, intensity=np.nan) else: m",
"is not None: print( (\"Experiment_id {} + spectrum_id {} combination already exists in",
"filename: name of the pymzml file :return: \"\"\" experiment = create_experiment(msrun_list, filename) utils.append_to_experiment('Experiment',",
"Peak table. \" + \"To avoid duplicates the spectra won't be added to",
"for i, spc in enumerate(msrun_list): if i % 100 == 0: print(\"Spectrum {}\".format(i))",
"+ \"To avoid duplicates the spectra won't be added to the Spectrum table\")",
"experiment_id: :return: ''' spectrum = namedtuple('spectrum', 'experiment_id ' + 'spectrum_id ' + 'total_ion_current",
"table. :param msrun_list: an open pymzml runner :param filename: name of the pymzml",
"experiment \"\"\" experiment = dict.fromkeys(['run_id', 'run_start_time', 'human_run_start_time', 'spectra_count', 'experimental_state_id', 'match_type_id', 'filename']) # Todo:",
"if check_peak is not None: print( (\"Experiment_id {} + spectrum_id {} combination already",
"file create_spectrum_and_peak_tables(msrun_list, experiment_id) if __name__ == \"__main__\": for n, filename in enumerate(glob.iglob('{}Geconverteerd/*.mzML'.format(config.data_dir))): print(\"reading",
"experiment structure based on the information in the msrun_list. :param msrun_list: an open",
"' + 'time_passed_since_start ' + 'ms_level ' + 'highest_observed_mz ' + 'lowest_observed_mz '",
"if i == 0: m = measurement(experiment_id=experiment_id, spectrum_id=spc.ID, mz=np.nan, intensity=np.nan) else: m =",
"the Spectrum table\") .format(experiment_id)) else: spectrum_table = pd.DataFrame(spectrum_list) spectrum_table.to_sql('Spectrum', con=config.db_connection, index=False, if_exists='append') print(\"Appended",
"do not already exist in table Peak check_peak = config.db_connection.execute( \"\"\"SELECT experiment_id from",
"spectrum_id = '{}'\"\"\"\\ .format(experiment_id, spc.ID)).fetchone() if check_peak is not None: print( (\"Experiment_id {}",
"already exists in Peak table. \" + \"To avoid duplicates the spectra won't",
"experiment_id already exists in Spectrum table. If not, append data to Spectrum table",
"= None experiment['match_type_id'] = None experiment['filename'] = filename.split('/')[-1] return experiment def create_experiment_table(msrun_list, filename):",
"= list(msrun) # check if filename already in Experiment table check = config.db_connection.execute(",
"pymzml import config import lcms.utils as utils def create_spectrum_and_peak_tables(msrun_list, experiment_id): ''' fills the",
"table with data from file create_spectrum_and_peak_tables(msrun_list, experiment_id) if __name__ == \"__main__\": for n,",
"index=False, if_exists='append') print(\"Appended to Spectrum table with info from experiment_id: {}\".format(experiment_id)) def create_experiment(msrun_list,",
"spectra won't be added to the Spectrum table\") .format(experiment_id)) else: spectrum_table = pd.DataFrame(spectrum_list)",
"None: print(\"File already exists in DB. Continue to filling Spectrum table\") experiment_id =",
"spc in enumerate(msrun_list): if i % 100 == 0: print(\"Spectrum {}\".format(i)) s =",
"Spectrum table with info from experiment_id: {}\".format(experiment_id)) def create_experiment(msrun_list, filename): \"\"\" Create a",
"{}\".format(i)) s = spectrum(experiment_id=experiment_id, spectrum_id=spc.ID, total_ion_current=spc['total ion current'], time_passed_since_start=spc['scan start time'], ms_level=spc['ms level'],",
"if experiment_id already exists in Spectrum table. If not, append data to Spectrum",
"with data from file experiment_id = create_experiment_table(msrun_list, filename) # fill the Spectrum and",
"'{}' \"\"\".format( filename.split('/')[-1])).fetchone() if check is not None: print(\"File already exists in DB.",
"from file create_spectrum_and_peak_tables(msrun_list, experiment_id) if __name__ == \"__main__\": for n, filename in enumerate(glob.iglob('{}Geconverteerd/*.mzML'.format(config.data_dir))):",
"msrun_list = list(msrun) # check if filename already in Experiment table check =",
"[] for i, spc in enumerate(msrun_list): if i % 100 == 0: print(\"Spectrum",
"config.db_connection.execute( \"\"\"SELECT experiment_id from \"Peak\" WHERE experiment_id = '{}' AND spectrum_id = '{}'\"\"\"\\",
"exists in Spectrum table. \" + \"To avoid duplicates the spectra won't be",
"table check = config.db_connection.execute( \"\"\"SELECT experiment_id from \"Experiment\" WHERE filename = '{}' \"\"\".format(",
"= config.db_connection.execute( \"\"\"SELECT experiment_id from \"Spectrum\" WHERE experiment_id = '{}' \"\"\" .format(experiment_id)).fetchone() if",
":return: a dictionary containing the initialized experiment \"\"\" experiment = dict.fromkeys(['run_id', 'run_start_time', 'human_run_start_time',",
"None experiment['spectra_count'] = msrun_list.info['spectrum_count'] experiment['experimental_state_id'] = None experiment['match_type_id'] = None experiment['filename'] = filename.split('/')[-1]",
"already in Experiment table check = config.db_connection.execute( \"\"\"SELECT experiment_id from \"Experiment\" WHERE filename",
"import namedtuple import dateutil.parser import numpy as np import pandas as pd import",
"waarden in onderstaande tabel moeten nog ingevuld worden experiment['run_id'] = msrun_list.info['run_id'] if \"start_time\"",
"onderstaande tabel moeten nog ingevuld worden experiment['run_id'] = msrun_list.info['run_id'] if \"start_time\" in msrun_list.info.keys():",
"create_spectrum_and_peak_tables(msrun_list, experiment_id) if __name__ == \"__main__\": for n, filename in enumerate(glob.iglob('{}Geconverteerd/*.mzML'.format(config.data_dir))): print(\"reading file",
":param filename: name of the pymzml file :return: \"\"\" experiment = create_experiment(msrun_list, filename)",
"spectra won't be added to the Peak table\").format(experiment_id, spc.ID)) else: peak_table = pd.DataFrame({\"mz\":",
"else: spectrum_table = pd.DataFrame(spectrum_list) spectrum_table.to_sql('Spectrum', con=config.db_connection, index=False, if_exists='append') print(\"Appended to Spectrum table with",
"file {} ({})\".format(n, filename.split('/')[-1])) if '+' in filename.split('/')[-1]: print(\"Raw data, will be skipped",
"print( (\"Experiment_id {} + spectrum_id {} combination already exists in Peak table. \"",
"the spectra won't be added to the Spectrum table\") .format(experiment_id)) else: spectrum_table =",
"= create_experiment(msrun_list, filename) utils.append_to_experiment('Experiment', experiment) experiment_id = config.db_connection.execute( \"\"\"SELECT experiment_id from \"Experiment\" WHERE",
"enumerate(glob.iglob('{}Geconverteerd/*.mzML'.format(config.data_dir))): print(\"reading file {} ({})\".format(n, filename.split('/')[-1])) if '+' in filename.split('/')[-1]: print(\"Raw data, will",
"already exists in Spectrum table. \" + \"To avoid duplicates the spectra won't",
"in onderstaande tabel moeten nog ingevuld worden experiment['run_id'] = msrun_list.info['run_id'] if \"start_time\" in",
"pymzml file :return: a dictionary containing the initialized experiment \"\"\" experiment = dict.fromkeys(['run_id',",
"from file experiment_id = create_experiment_table(msrun_list, filename) # fill the Spectrum and Peak table",
"duplicates the spectra won't be added to the Peak table\").format(experiment_id, spc.ID)) else: peak_table",
"= '{}' \"\"\".format( filename.split('/')[-1])).fetchone()[0] return experiment_id def read_file(filename): msrun = pymzml.run.Reader(filename) msrun_list =",
"of the pymzml file :return: a dictionary containing the initialized experiment \"\"\" experiment",
"lcms.utils as utils def create_spectrum_and_peak_tables(msrun_list, experiment_id): ''' fills the Spectrum table and for",
"dict.fromkeys(['run_id', 'run_start_time', 'human_run_start_time', 'spectra_count', 'experimental_state_id', 'match_type_id', 'filename']) # Todo: waarden in onderstaande tabel",
"in Experiment table check = config.db_connection.execute( \"\"\"SELECT experiment_id from \"Experiment\" WHERE filename =",
"be added to the Peak table\").format(experiment_id, spc.ID)) else: peak_table = pd.DataFrame({\"mz\": spc.mz, \"intensity\":",
"spectrum_id=spc.ID, mz=np.nan, intensity=np.nan) else: m = measurement(experiment_id=experiment_id, spectrum_id=spc.ID, mz=spc.mz, intensity=spc.i) # Fill peak",
"collections import namedtuple import dateutil.parser import numpy as np import pandas as pd",
"lowest_observed_mz=spc['lowest observed m/z'], scan_window_upper_limit=spc['scan window upper limit'], scan_window_lower_limit=spc['scan window lower limit']) spectrum_list.append(s) if",
"window upper limit'], scan_window_lower_limit=spc['scan window lower limit']) spectrum_list.append(s) if i == 0: m",
"to Spectrum table with info from experiment_id: {}\".format(experiment_id)) def create_experiment(msrun_list, filename): \"\"\" Create",
"\"\"\".format( filename.split('/')[-1])).fetchone() if check is not None: print(\"File already exists in DB. Continue",
"from experiment_id: {}\".format(experiment_id)) def create_experiment(msrun_list, filename): \"\"\" Create a new experiment structure based",
"Experiment table. :param msrun_list: an open pymzml runner :param filename: name of the",
"spc.ID)) else: peak_table = pd.DataFrame({\"mz\": spc.mz, \"intensity\": spc.i}) peak_table['experiment_id'] = experiment_id peak_table['spectrum_id'] =",
"config.db_connection.execute( \"\"\"SELECT experiment_id from \"Experiment\" WHERE filename = '{}' \"\"\".format( filename.split('/')[-1])).fetchone()[0] return experiment_id",
"experiment['spectra_count'] = msrun_list.info['spectrum_count'] experiment['experimental_state_id'] = None experiment['match_type_id'] = None experiment['filename'] = filename.split('/')[-1] return",
"from experiment_id: {}, spectrum_id: {}\".format(experiment_id, spc.ID)) measurement_list.append(m) # check if experiment_id already exists",
"observed m/z'], scan_window_upper_limit=spc['scan window upper limit'], scan_window_lower_limit=spc['scan window lower limit']) spectrum_list.append(s) if i",
"'{}' \"\"\".format( filename.split('/')[-1])).fetchone()[0] return experiment_id def read_file(filename): msrun = pymzml.run.Reader(filename) msrun_list = list(msrun)",
"= msrun_list.info['spectrum_count'] experiment['experimental_state_id'] = None experiment['match_type_id'] = None experiment['filename'] = filename.split('/')[-1] return experiment",
"as np import pandas as pd import pymzml import config import lcms.utils as",
"msrun_list: :param experiment_id: :return: ''' spectrum = namedtuple('spectrum', 'experiment_id ' + 'spectrum_id '",
"to filling Spectrum table\") experiment_id = check[0] else: # fill the Experiment table",
"print((\"Experiment_id {} already exists in Spectrum table. \" + \"To avoid duplicates the",
"msrun_list.info['run_id'] if \"start_time\" in msrun_list.info.keys(): start_time_str = msrun_list.info[\"start_time\"] start_time = dateutil.parser.parse(start_time_str) experiment['run_start_time'] =",
"= [] measurement_list = [] for i, spc in enumerate(msrun_list): if i %",
"spectrum_id=spc.ID, total_ion_current=spc['total ion current'], time_passed_since_start=spc['scan start time'], ms_level=spc['ms level'], highest_observed_mz=spc['highest observed m/z'], lowest_observed_mz=spc['lowest",
"# check if experiment_id already exists in Spectrum table. If not, append data",
"filename.split('/')[-1])).fetchone() if check is not None: print(\"File already exists in DB. Continue to",
"the initialized experiment \"\"\" experiment = dict.fromkeys(['run_id', 'run_start_time', 'human_run_start_time', 'spectra_count', 'experimental_state_id', 'match_type_id', 'filename'])",
"filename.split('/')[-1] return experiment def create_experiment_table(msrun_list, filename): \"\"\" fills the Experiment table. :param msrun_list:",
"Todo: waarden in onderstaande tabel moeten nog ingevuld worden experiment['run_id'] = msrun_list.info['run_id'] if",
"+ spectrum_id {} combination already exists in Peak table. \" + \"To avoid",
"'{}'\"\"\"\\ .format(experiment_id, spc.ID)).fetchone() if check_peak is not None: print( (\"Experiment_id {} + spectrum_id",
"pd.DataFrame(spectrum_list) spectrum_table.to_sql('Spectrum', con=config.db_connection, index=False, if_exists='append') print(\"Appended to Spectrum table with info from experiment_id:",
"dateutil.parser import numpy as np import pandas as pd import pymzml import config",
"ms_level=spc['ms level'], highest_observed_mz=spc['highest observed m/z'], lowest_observed_mz=spc['lowest observed m/z'], scan_window_upper_limit=spc['scan window upper limit'], scan_window_lower_limit=spc['scan",
"check_peak = config.db_connection.execute( \"\"\"SELECT experiment_id from \"Peak\" WHERE experiment_id = '{}' AND spectrum_id",
"pd import pymzml import config import lcms.utils as utils def create_spectrum_and_peak_tables(msrun_list, experiment_id): '''",
"the Spectrum and Peak table with data from file create_spectrum_and_peak_tables(msrun_list, experiment_id) if __name__",
"dictionary containing the initialized experiment \"\"\" experiment = dict.fromkeys(['run_id', 'run_start_time', 'human_run_start_time', 'spectra_count', 'experimental_state_id',",
"spectrum(experiment_id=experiment_id, spectrum_id=spc.ID, total_ion_current=spc['total ion current'], time_passed_since_start=spc['scan start time'], ms_level=spc['ms level'], highest_observed_mz=spc['highest observed m/z'],",
"i == 0: m = measurement(experiment_id=experiment_id, spectrum_id=spc.ID, mz=np.nan, intensity=np.nan) else: m = measurement(experiment_id=experiment_id,",
"spectrum_list = [] measurement_list = [] for i, spc in enumerate(msrun_list): if i",
"tabel moeten nog ingevuld worden experiment['run_id'] = msrun_list.info['run_id'] if \"start_time\" in msrun_list.info.keys(): start_time_str",
"fills the Spectrum table and for each spectrum the Peak table :param msrun_list:",
"for each spectrum the Peak table :param msrun_list: :param experiment_id: :return: ''' spectrum",
"Peak table from experiment_id: {}, spectrum_id: {}\".format(experiment_id, spc.ID)) measurement_list.append(m) # check if experiment_id",
"the Experiment table. :param msrun_list: an open pymzml runner :param filename: name of",
"= config.db_connection.execute( \"\"\"SELECT experiment_id from \"Peak\" WHERE experiment_id = '{}' AND spectrum_id =",
"be added to the Spectrum table\") .format(experiment_id)) else: spectrum_table = pd.DataFrame(spectrum_list) spectrum_table.to_sql('Spectrum', con=config.db_connection,",
"= namedtuple('spectrum', 'experiment_id ' + 'spectrum_id ' + 'total_ion_current ' + 'time_passed_since_start '",
"enumerate(msrun_list): if i % 100 == 0: print(\"Spectrum {}\".format(i)) s = spectrum(experiment_id=experiment_id, spectrum_id=spc.ID,",
"def create_experiment_table(msrun_list, filename): \"\"\" fills the Experiment table. :param msrun_list: an open pymzml",
"Peak table :param msrun_list: :param experiment_id: :return: ''' spectrum = namedtuple('spectrum', 'experiment_id '",
"pymzml.run.Reader(filename) msrun_list = list(msrun) # check if filename already in Experiment table check",
"100 == 0: print(\"Spectrum {}\".format(i)) s = spectrum(experiment_id=experiment_id, spectrum_id=spc.ID, total_ion_current=spc['total ion current'], time_passed_since_start=spc['scan",
"experiment = create_experiment(msrun_list, filename) utils.append_to_experiment('Experiment', experiment) experiment_id = config.db_connection.execute( \"\"\"SELECT experiment_id from \"Experiment\"",
"Continue to filling Spectrum table\") experiment_id = check[0] else: # fill the Experiment",
"peak_table['spectrum_id'] = spc.ID peak_table.to_sql('Peak', con=config.db_connection, index=False, if_exists='append') print(\"Appended to Peak table from experiment_id:",
"create_spectrum_and_peak_tables(msrun_list, experiment_id): ''' fills the Spectrum table and for each spectrum the Peak",
"intensity=np.nan) else: m = measurement(experiment_id=experiment_id, spectrum_id=spc.ID, mz=spc.mz, intensity=spc.i) # Fill peak table if",
"is not None: print(\"File already exists in DB. Continue to filling Spectrum table\")",
"= '{}'\"\"\"\\ .format(experiment_id, spc.ID)).fetchone() if check_peak is not None: print( (\"Experiment_id {} +",
"\"To avoid duplicates the spectra won't be added to the Peak table\").format(experiment_id, spc.ID))",
"table and for each spectrum the Peak table :param msrun_list: :param experiment_id: :return:",
"create_experiment(msrun_list, filename) utils.append_to_experiment('Experiment', experiment) experiment_id = config.db_connection.execute( \"\"\"SELECT experiment_id from \"Experiment\" WHERE filename",
"limit'], scan_window_lower_limit=spc['scan window lower limit']) spectrum_list.append(s) if i == 0: m = measurement(experiment_id=experiment_id,",
"Peak table with data from file create_spectrum_and_peak_tables(msrun_list, experiment_id) if __name__ == \"__main__\": for",
"= experiment_id peak_table['spectrum_id'] = spc.ID peak_table.to_sql('Peak', con=config.db_connection, index=False, if_exists='append') print(\"Appended to Peak table",
"if_exists='append') print(\"Appended to Peak table from experiment_id: {}, spectrum_id: {}\".format(experiment_id, spc.ID)) measurement_list.append(m) #",
"' mz' + ' intensity') spectrum_list = [] measurement_list = [] for i,",
"scan_window_lower_limit=spc['scan window lower limit']) spectrum_list.append(s) if i == 0: m = measurement(experiment_id=experiment_id, spectrum_id=spc.ID,",
"Spectrum table\") .format(experiment_id)) else: spectrum_table = pd.DataFrame(spectrum_list) spectrum_table.to_sql('Spectrum', con=config.db_connection, index=False, if_exists='append') print(\"Appended to",
"= '{}' \"\"\".format( filename.split('/')[-1])).fetchone() if check is not None: print(\"File already exists in",
"if filename already in Experiment table check = config.db_connection.execute( \"\"\"SELECT experiment_id from \"Experiment\"",
"\" + \"To avoid duplicates the spectra won't be added to the Peak",
"else: m = measurement(experiment_id=experiment_id, spectrum_id=spc.ID, mz=spc.mz, intensity=spc.i) # Fill peak table if experiment_id",
"= msrun_list.info[\"start_time\"] start_time = dateutil.parser.parse(start_time_str) experiment['run_start_time'] = start_time.timestamp() experiment['human_run_start_time'] = start_time else: experiment['run_start_time']",
"initialized experiment \"\"\" experiment = dict.fromkeys(['run_id', 'run_start_time', 'human_run_start_time', 'spectra_count', 'experimental_state_id', 'match_type_id', 'filename']) #",
"s = spectrum(experiment_id=experiment_id, spectrum_id=spc.ID, total_ion_current=spc['total ion current'], time_passed_since_start=spc['scan start time'], ms_level=spc['ms level'], highest_observed_mz=spc['highest",
":param experiment_id: :return: ''' spectrum = namedtuple('spectrum', 'experiment_id ' + 'spectrum_id ' +",
"start_time else: experiment['run_start_time'] = None experiment['human_run_start_time'] = None experiment['spectra_count'] = msrun_list.info['spectrum_count'] experiment['experimental_state_id'] =",
"window lower limit']) spectrum_list.append(s) if i == 0: m = measurement(experiment_id=experiment_id, spectrum_id=spc.ID, mz=np.nan,",
"WHERE filename = '{}' \"\"\".format( filename.split('/')[-1])).fetchone() if check is not None: print(\"File already",
"' + 'scan_window_upper_limit ' + 'scan_window_lower_limit') measurement = namedtuple('measurement', 'experiment_id ' + 'spectrum_id'",
"nog ingevuld worden experiment['run_id'] = msrun_list.info['run_id'] if \"start_time\" in msrun_list.info.keys(): start_time_str = msrun_list.info[\"start_time\"]",
"table :param msrun_list: :param experiment_id: :return: ''' spectrum = namedtuple('spectrum', 'experiment_id ' +",
"'spectrum_id ' + 'total_ion_current ' + 'time_passed_since_start ' + 'ms_level ' + 'highest_observed_mz",
"won't be added to the Peak table\").format(experiment_id, spc.ID)) else: peak_table = pd.DataFrame({\"mz\": spc.mz,",
"the pymzml file :return: a dictionary containing the initialized experiment \"\"\" experiment =",
"m = measurement(experiment_id=experiment_id, spectrum_id=spc.ID, mz=np.nan, intensity=np.nan) else: m = measurement(experiment_id=experiment_id, spectrum_id=spc.ID, mz=spc.mz, intensity=spc.i)",
"spc.mz, \"intensity\": spc.i}) peak_table['experiment_id'] = experiment_id peak_table['spectrum_id'] = spc.ID peak_table.to_sql('Peak', con=config.db_connection, index=False, if_exists='append')",
"msrun_list.info[\"start_time\"] start_time = dateutil.parser.parse(start_time_str) experiment['run_start_time'] = start_time.timestamp() experiment['human_run_start_time'] = start_time else: experiment['run_start_time'] =",
"= None experiment['spectra_count'] = msrun_list.info['spectrum_count'] experiment['experimental_state_id'] = None experiment['match_type_id'] = None experiment['filename'] =",
"in enumerate(msrun_list): if i % 100 == 0: print(\"Spectrum {}\".format(i)) s = spectrum(experiment_id=experiment_id,",
"spectrum_id: {}\".format(experiment_id, spc.ID)) measurement_list.append(m) # check if experiment_id already exists in Spectrum table.",
"experiment_id: {}\".format(experiment_id)) def create_experiment(msrun_list, filename): \"\"\" Create a new experiment structure based on",
"experiment['filename'] = filename.split('/')[-1] return experiment def create_experiment_table(msrun_list, filename): \"\"\" fills the Experiment table.",
"not None: print(\"File already exists in DB. Continue to filling Spectrum table\") experiment_id",
"filename): \"\"\" fills the Experiment table. :param msrun_list: an open pymzml runner :param",
"peak_table.to_sql('Peak', con=config.db_connection, index=False, if_exists='append') print(\"Appended to Peak table from experiment_id: {}, spectrum_id: {}\".format(experiment_id,",
"con=config.db_connection, index=False, if_exists='append') print(\"Appended to Peak table from experiment_id: {}, spectrum_id: {}\".format(experiment_id, spc.ID))",
"'filename']) # Todo: waarden in onderstaande tabel moeten nog ingevuld worden experiment['run_id'] =",
"import glob from collections import namedtuple import dateutil.parser import numpy as np import",
"+ 'total_ion_current ' + 'time_passed_since_start ' + 'ms_level ' + 'highest_observed_mz ' +",
"and for each spectrum the Peak table :param msrun_list: :param experiment_id: :return: '''",
"msrun_list.info['spectrum_count'] experiment['experimental_state_id'] = None experiment['match_type_id'] = None experiment['filename'] = filename.split('/')[-1] return experiment def",
"lower limit']) spectrum_list.append(s) if i == 0: m = measurement(experiment_id=experiment_id, spectrum_id=spc.ID, mz=np.nan, intensity=np.nan)",
"== \"__main__\": for n, filename in enumerate(glob.iglob('{}Geconverteerd/*.mzML'.format(config.data_dir))): print(\"reading file {} ({})\".format(n, filename.split('/')[-1])) if",
"check if filename already in Experiment table check = config.db_connection.execute( \"\"\"SELECT experiment_id from",
"if i % 100 == 0: print(\"Spectrum {}\".format(i)) s = spectrum(experiment_id=experiment_id, spectrum_id=spc.ID, total_ion_current=spc['total",
"spectrum_id=spc.ID, mz=spc.mz, intensity=spc.i) # Fill peak table if experiment_id + spectrum_id do not",
"pd.DataFrame({\"mz\": spc.mz, \"intensity\": spc.i}) peak_table['experiment_id'] = experiment_id peak_table['spectrum_id'] = spc.ID peak_table.to_sql('Peak', con=config.db_connection, index=False,",
"fill the Experiment table with data from file experiment_id = create_experiment_table(msrun_list, filename) #",
"intensity=spc.i) # Fill peak table if experiment_id + spectrum_id do not already exist",
"= None experiment['human_run_start_time'] = None experiment['spectra_count'] = msrun_list.info['spectrum_count'] experiment['experimental_state_id'] = None experiment['match_type_id'] =",
"based on the information in the msrun_list. :param msrun_list: an open pymzml runner",
"{} combination already exists in Peak table. \" + \"To avoid duplicates the",
"experiment_id: {}, spectrum_id: {}\".format(experiment_id, spc.ID)) measurement_list.append(m) # check if experiment_id already exists in",
"duplicates the spectra won't be added to the Spectrum table\") .format(experiment_id)) else: spectrum_table",
"check_peak is not None: print( (\"Experiment_id {} + spectrum_id {} combination already exists",
"\" + \"To avoid duplicates the spectra won't be added to the Spectrum",
"create_experiment(msrun_list, filename): \"\"\" Create a new experiment structure based on the information in",
"to the Peak table\").format(experiment_id, spc.ID)) else: peak_table = pd.DataFrame({\"mz\": spc.mz, \"intensity\": spc.i}) peak_table['experiment_id']",
"'spectra_count', 'experimental_state_id', 'match_type_id', 'filename']) # Todo: waarden in onderstaande tabel moeten nog ingevuld",
"= filename.split('/')[-1] return experiment def create_experiment_table(msrun_list, filename): \"\"\" fills the Experiment table. :param",
"AND spectrum_id = '{}'\"\"\"\\ .format(experiment_id, spc.ID)).fetchone() if check_peak is not None: print( (\"Experiment_id",
"return experiment def create_experiment_table(msrun_list, filename): \"\"\" fills the Experiment table. :param msrun_list: an",
":param msrun_list: :param experiment_id: :return: ''' spectrum = namedtuple('spectrum', 'experiment_id ' + 'spectrum_id",
"info from experiment_id: {}\".format(experiment_id)) def create_experiment(msrun_list, filename): \"\"\" Create a new experiment structure",
"\"\"\" experiment = dict.fromkeys(['run_id', 'run_start_time', 'human_run_start_time', 'spectra_count', 'experimental_state_id', 'match_type_id', 'filename']) # Todo: waarden",
"Experiment table check = config.db_connection.execute( \"\"\"SELECT experiment_id from \"Experiment\" WHERE filename = '{}'",
"import pymzml import config import lcms.utils as utils def create_spectrum_and_peak_tables(msrun_list, experiment_id): ''' fills",
"= namedtuple('measurement', 'experiment_id ' + 'spectrum_id' + ' mz' + ' intensity') spectrum_list",
"= msrun_list.info['run_id'] if \"start_time\" in msrun_list.info.keys(): start_time_str = msrun_list.info[\"start_time\"] start_time = dateutil.parser.parse(start_time_str) experiment['run_start_time']",
"added to the Spectrum table\") .format(experiment_id)) else: spectrum_table = pd.DataFrame(spectrum_list) spectrum_table.to_sql('Spectrum', con=config.db_connection, index=False,",
"i, spc in enumerate(msrun_list): if i % 100 == 0: print(\"Spectrum {}\".format(i)) s",
"Spectrum table and for each spectrum the Peak table :param msrun_list: :param experiment_id:",
"\"Experiment\" WHERE filename = '{}' \"\"\".format( filename.split('/')[-1])).fetchone() if check is not None: print(\"File",
"check is not None: print(\"File already exists in DB. Continue to filling Spectrum",
"experiment_id from \"Peak\" WHERE experiment_id = '{}' AND spectrum_id = '{}'\"\"\"\\ .format(experiment_id, spc.ID)).fetchone()",
"WHERE experiment_id = '{}' AND spectrum_id = '{}'\"\"\"\\ .format(experiment_id, spc.ID)).fetchone() if check_peak is",
"runner :param filename: name of the pymzml file :return: a dictionary containing the",
"namedtuple('spectrum', 'experiment_id ' + 'spectrum_id ' + 'total_ion_current ' + 'time_passed_since_start ' +",
"= dateutil.parser.parse(start_time_str) experiment['run_start_time'] = start_time.timestamp() experiment['human_run_start_time'] = start_time else: experiment['run_start_time'] = None experiment['human_run_start_time']",
"the pymzml file :return: \"\"\" experiment = create_experiment(msrun_list, filename) utils.append_to_experiment('Experiment', experiment) experiment_id =",
"= check[0] else: # fill the Experiment table with data from file experiment_id",
"in DB. Continue to filling Spectrum table\") experiment_id = check[0] else: # fill",
"def create_spectrum_and_peak_tables(msrun_list, experiment_id): ''' fills the Spectrum table and for each spectrum the",
"= config.db_connection.execute( \"\"\"SELECT experiment_id from \"Experiment\" WHERE filename = '{}' \"\"\".format( filename.split('/')[-1])).fetchone() if",
"experiment_id = create_experiment_table(msrun_list, filename) # fill the Spectrum and Peak table with data",
"[] measurement_list = [] for i, spc in enumerate(msrun_list): if i % 100",
"measurement(experiment_id=experiment_id, spectrum_id=spc.ID, mz=spc.mz, intensity=spc.i) # Fill peak table if experiment_id + spectrum_id do",
"print(\"File already exists in DB. Continue to filling Spectrum table\") experiment_id = check[0]",
"'ms_level ' + 'highest_observed_mz ' + 'lowest_observed_mz ' + 'scan_window_upper_limit ' + 'scan_window_lower_limit')",
":param msrun_list: an open pymzml runner :param filename: name of the pymzml file",
"= '{}' AND spectrum_id = '{}'\"\"\"\\ .format(experiment_id, spc.ID)).fetchone() if check_peak is not None:",
"WHERE experiment_id = '{}' \"\"\" .format(experiment_id)).fetchone() if check_spectrum is not None: print((\"Experiment_id {}",
"exists in DB. Continue to filling Spectrum table\") experiment_id = check[0] else: #",
"the Spectrum table and for each spectrum the Peak table :param msrun_list: :param",
"\"\"\".format( filename.split('/')[-1])).fetchone()[0] return experiment_id def read_file(filename): msrun = pymzml.run.Reader(filename) msrun_list = list(msrun) #",
"Spectrum and Peak table with data from file create_spectrum_and_peak_tables(msrun_list, experiment_id) if __name__ ==",
":return: ''' spectrum = namedtuple('spectrum', 'experiment_id ' + 'spectrum_id ' + 'total_ion_current '",
"pymzml runner :param filename: name of the pymzml file :return: a dictionary containing",
"peak table if experiment_id + spectrum_id do not already exist in table Peak",
"con=config.db_connection, index=False, if_exists='append') print(\"Appended to Spectrum table with info from experiment_id: {}\".format(experiment_id)) def",
"from \"Spectrum\" WHERE experiment_id = '{}' \"\"\" .format(experiment_id)).fetchone() if check_spectrum is not None:",
"if check is not None: print(\"File already exists in DB. Continue to filling",
"+ \"To avoid duplicates the spectra won't be added to the Peak table\").format(experiment_id,",
"experiment['run_start_time'] = None experiment['human_run_start_time'] = None experiment['spectra_count'] = msrun_list.info['spectrum_count'] experiment['experimental_state_id'] = None experiment['match_type_id']",
"import numpy as np import pandas as pd import pymzml import config import",
"Peak table\").format(experiment_id, spc.ID)) else: peak_table = pd.DataFrame({\"mz\": spc.mz, \"intensity\": spc.i}) peak_table['experiment_id'] = experiment_id",
"\"\"\"SELECT experiment_id from \"Experiment\" WHERE filename = '{}' \"\"\".format( filename.split('/')[-1])).fetchone() if check is",
"spectrum = namedtuple('spectrum', 'experiment_id ' + 'spectrum_id ' + 'total_ion_current ' + 'time_passed_since_start",
"fills the Experiment table. :param msrun_list: an open pymzml runner :param filename: name",
"{}, spectrum_id: {}\".format(experiment_id, spc.ID)) measurement_list.append(m) # check if experiment_id already exists in Spectrum",
"filename in enumerate(glob.iglob('{}Geconverteerd/*.mzML'.format(config.data_dir))): print(\"reading file {} ({})\".format(n, filename.split('/')[-1])) if '+' in filename.split('/')[-1]: print(\"Raw",
"+ ' intensity') spectrum_list = [] measurement_list = [] for i, spc in",
"from collections import namedtuple import dateutil.parser import numpy as np import pandas as",
"None experiment['filename'] = filename.split('/')[-1] return experiment def create_experiment_table(msrun_list, filename): \"\"\" fills the Experiment",
"a new experiment structure based on the information in the msrun_list. :param msrun_list:",
"list(msrun) # check if filename already in Experiment table check = config.db_connection.execute( \"\"\"SELECT",
"table from experiment_id: {}, spectrum_id: {}\".format(experiment_id, spc.ID)) measurement_list.append(m) # check if experiment_id already",
"measurement(experiment_id=experiment_id, spectrum_id=spc.ID, mz=np.nan, intensity=np.nan) else: m = measurement(experiment_id=experiment_id, spectrum_id=spc.ID, mz=spc.mz, intensity=spc.i) # Fill",
"{} already exists in Spectrum table. \" + \"To avoid duplicates the spectra",
"experiment) experiment_id = config.db_connection.execute( \"\"\"SELECT experiment_id from \"Experiment\" WHERE filename = '{}' \"\"\".format(",
"'match_type_id', 'filename']) # Todo: waarden in onderstaande tabel moeten nog ingevuld worden experiment['run_id']",
"n, filename in enumerate(glob.iglob('{}Geconverteerd/*.mzML'.format(config.data_dir))): print(\"reading file {} ({})\".format(n, filename.split('/')[-1])) if '+' in filename.split('/')[-1]:",
"% 100 == 0: print(\"Spectrum {}\".format(i)) s = spectrum(experiment_id=experiment_id, spectrum_id=spc.ID, total_ion_current=spc['total ion current'],",
"config.db_connection.execute( \"\"\"SELECT experiment_id from \"Experiment\" WHERE filename = '{}' \"\"\".format( filename.split('/')[-1])).fetchone() if check",
"filling Spectrum table\") experiment_id = check[0] else: # fill the Experiment table with",
"exist in table Peak check_peak = config.db_connection.execute( \"\"\"SELECT experiment_id from \"Peak\" WHERE experiment_id",
"the Peak table :param msrun_list: :param experiment_id: :return: ''' spectrum = namedtuple('spectrum', 'experiment_id",
"highest_observed_mz=spc['highest observed m/z'], lowest_observed_mz=spc['lowest observed m/z'], scan_window_upper_limit=spc['scan window upper limit'], scan_window_lower_limit=spc['scan window lower",
"exists in Peak table. \" + \"To avoid duplicates the spectra won't be",
"== 0: print(\"Spectrum {}\".format(i)) s = spectrum(experiment_id=experiment_id, spectrum_id=spc.ID, total_ion_current=spc['total ion current'], time_passed_since_start=spc['scan start",
"won't be added to the Spectrum table\") .format(experiment_id)) else: spectrum_table = pd.DataFrame(spectrum_list) spectrum_table.to_sql('Spectrum',",
"np import pandas as pd import pymzml import config import lcms.utils as utils",
"data to Spectrum table check_spectrum = config.db_connection.execute( \"\"\"SELECT experiment_id from \"Spectrum\" WHERE experiment_id",
"check_spectrum = config.db_connection.execute( \"\"\"SELECT experiment_id from \"Spectrum\" WHERE experiment_id = '{}' \"\"\" .format(experiment_id)).fetchone()",
"of the pymzml file :return: \"\"\" experiment = create_experiment(msrun_list, filename) utils.append_to_experiment('Experiment', experiment) experiment_id",
"+ ' mz' + ' intensity') spectrum_list = [] measurement_list = [] for",
"Spectrum table check_spectrum = config.db_connection.execute( \"\"\"SELECT experiment_id from \"Spectrum\" WHERE experiment_id = '{}'",
"dateutil.parser.parse(start_time_str) experiment['run_start_time'] = start_time.timestamp() experiment['human_run_start_time'] = start_time else: experiment['run_start_time'] = None experiment['human_run_start_time'] =",
"+ 'scan_window_lower_limit') measurement = namedtuple('measurement', 'experiment_id ' + 'spectrum_id' + ' mz' +",
"start_time = dateutil.parser.parse(start_time_str) experiment['run_start_time'] = start_time.timestamp() experiment['human_run_start_time'] = start_time else: experiment['run_start_time'] = None",
"filename.split('/')[-1])).fetchone()[0] return experiment_id def read_file(filename): msrun = pymzml.run.Reader(filename) msrun_list = list(msrun) # check",
"the msrun_list. :param msrun_list: an open pymzml runner :param filename: name of the",
"+ spectrum_id do not already exist in table Peak check_peak = config.db_connection.execute( \"\"\"SELECT",
"experiment['experimental_state_id'] = None experiment['match_type_id'] = None experiment['filename'] = filename.split('/')[-1] return experiment def create_experiment_table(msrun_list,",
"filename already in Experiment table check = config.db_connection.execute( \"\"\"SELECT experiment_id from \"Experiment\" WHERE",
"ion current'], time_passed_since_start=spc['scan start time'], ms_level=spc['ms level'], highest_observed_mz=spc['highest observed m/z'], lowest_observed_mz=spc['lowest observed m/z'],",
"measurement_list.append(m) # check if experiment_id already exists in Spectrum table. If not, append",
"None: print((\"Experiment_id {} already exists in Spectrum table. \" + \"To avoid duplicates",
"if_exists='append') print(\"Appended to Spectrum table with info from experiment_id: {}\".format(experiment_id)) def create_experiment(msrun_list, filename):",
"config import lcms.utils as utils def create_spectrum_and_peak_tables(msrun_list, experiment_id): ''' fills the Spectrum table",
"for n, filename in enumerate(glob.iglob('{}Geconverteerd/*.mzML'.format(config.data_dir))): print(\"reading file {} ({})\".format(n, filename.split('/')[-1])) if '+' in",
"not already exist in table Peak check_peak = config.db_connection.execute( \"\"\"SELECT experiment_id from \"Peak\"",
"each spectrum the Peak table :param msrun_list: :param experiment_id: :return: ''' spectrum =",
"numpy as np import pandas as pd import pymzml import config import lcms.utils",
"Spectrum table. If not, append data to Spectrum table check_spectrum = config.db_connection.execute( \"\"\"SELECT",
"\"\"\"SELECT experiment_id from \"Peak\" WHERE experiment_id = '{}' AND spectrum_id = '{}'\"\"\"\\ .format(experiment_id,",
"avoid duplicates the spectra won't be added to the Spectrum table\") .format(experiment_id)) else:",
"import pandas as pd import pymzml import config import lcms.utils as utils def",
"' + 'scan_window_lower_limit') measurement = namedtuple('measurement', 'experiment_id ' + 'spectrum_id' + ' mz'",
"= dict.fromkeys(['run_id', 'run_start_time', 'human_run_start_time', 'spectra_count', 'experimental_state_id', 'match_type_id', 'filename']) # Todo: waarden in onderstaande",
"if \"start_time\" in msrun_list.info.keys(): start_time_str = msrun_list.info[\"start_time\"] start_time = dateutil.parser.parse(start_time_str) experiment['run_start_time'] = start_time.timestamp()",
"structure based on the information in the msrun_list. :param msrun_list: an open pymzml",
"# fill the Experiment table with data from file experiment_id = create_experiment_table(msrun_list, filename)",
"experiment['match_type_id'] = None experiment['filename'] = filename.split('/')[-1] return experiment def create_experiment_table(msrun_list, filename): \"\"\" fills",
"'total_ion_current ' + 'time_passed_since_start ' + 'ms_level ' + 'highest_observed_mz ' + 'lowest_observed_mz",
"= None experiment['filename'] = filename.split('/')[-1] return experiment def create_experiment_table(msrun_list, filename): \"\"\" fills the",
"measurement_list = [] for i, spc in enumerate(msrun_list): if i % 100 ==",
"table check_spectrum = config.db_connection.execute( \"\"\"SELECT experiment_id from \"Spectrum\" WHERE experiment_id = '{}' \"\"\"",
"'spectrum_id' + ' mz' + ' intensity') spectrum_list = [] measurement_list = []",
"to Peak table from experiment_id: {}, spectrum_id: {}\".format(experiment_id, spc.ID)) measurement_list.append(m) # check if",
"experiment['run_id'] = msrun_list.info['run_id'] if \"start_time\" in msrun_list.info.keys(): start_time_str = msrun_list.info[\"start_time\"] start_time = dateutil.parser.parse(start_time_str)",
"experiment = dict.fromkeys(['run_id', 'run_start_time', 'human_run_start_time', 'spectra_count', 'experimental_state_id', 'match_type_id', 'filename']) # Todo: waarden in",
"limit']) spectrum_list.append(s) if i == 0: m = measurement(experiment_id=experiment_id, spectrum_id=spc.ID, mz=np.nan, intensity=np.nan) else:",
"+ 'ms_level ' + 'highest_observed_mz ' + 'lowest_observed_mz ' + 'scan_window_upper_limit ' +",
"Fill peak table if experiment_id + spectrum_id do not already exist in table",
"None experiment['human_run_start_time'] = None experiment['spectra_count'] = msrun_list.info['spectrum_count'] experiment['experimental_state_id'] = None experiment['match_type_id'] = None",
"= measurement(experiment_id=experiment_id, spectrum_id=spc.ID, mz=np.nan, intensity=np.nan) else: m = measurement(experiment_id=experiment_id, spectrum_id=spc.ID, mz=spc.mz, intensity=spc.i) #",
"' + 'ms_level ' + 'highest_observed_mz ' + 'lowest_observed_mz ' + 'scan_window_upper_limit '",
"read_file(filename): msrun = pymzml.run.Reader(filename) msrun_list = list(msrun) # check if filename already in",
"start_time.timestamp() experiment['human_run_start_time'] = start_time else: experiment['run_start_time'] = None experiment['human_run_start_time'] = None experiment['spectra_count'] =",
"scan_window_upper_limit=spc['scan window upper limit'], scan_window_lower_limit=spc['scan window lower limit']) spectrum_list.append(s) if i == 0:",
"experiment_id peak_table['spectrum_id'] = spc.ID peak_table.to_sql('Peak', con=config.db_connection, index=False, if_exists='append') print(\"Appended to Peak table from",
"\"To avoid duplicates the spectra won't be added to the Spectrum table\") .format(experiment_id))",
"= start_time else: experiment['run_start_time'] = None experiment['human_run_start_time'] = None experiment['spectra_count'] = msrun_list.info['spectrum_count'] experiment['experimental_state_id']",
"Spectrum table. \" + \"To avoid duplicates the spectra won't be added to",
"\"\"\"SELECT experiment_id from \"Spectrum\" WHERE experiment_id = '{}' \"\"\" .format(experiment_id)).fetchone() if check_spectrum is",
"containing the initialized experiment \"\"\" experiment = dict.fromkeys(['run_id', 'run_start_time', 'human_run_start_time', 'spectra_count', 'experimental_state_id', 'match_type_id',",
"with info from experiment_id: {}\".format(experiment_id)) def create_experiment(msrun_list, filename): \"\"\" Create a new experiment",
"= pymzml.run.Reader(filename) msrun_list = list(msrun) # check if filename already in Experiment table",
"experiment_id = '{}' AND spectrum_id = '{}'\"\"\"\\ .format(experiment_id, spc.ID)).fetchone() if check_peak is not",
"exists in Spectrum table. If not, append data to Spectrum table check_spectrum =",
"is not None: print((\"Experiment_id {} already exists in Spectrum table. \" + \"To",
"== 0: m = measurement(experiment_id=experiment_id, spectrum_id=spc.ID, mz=np.nan, intensity=np.nan) else: m = measurement(experiment_id=experiment_id, spectrum_id=spc.ID,",
"intensity') spectrum_list = [] measurement_list = [] for i, spc in enumerate(msrun_list): if",
"not None: print((\"Experiment_id {} already exists in Spectrum table. \" + \"To avoid",
"experiment_id = config.db_connection.execute( \"\"\"SELECT experiment_id from \"Experiment\" WHERE filename = '{}' \"\"\".format( filename.split('/')[-1])).fetchone()[0]",
"Experiment table with data from file experiment_id = create_experiment_table(msrun_list, filename) # fill the",
"namedtuple('measurement', 'experiment_id ' + 'spectrum_id' + ' mz' + ' intensity') spectrum_list =",
"spectrum_table = pd.DataFrame(spectrum_list) spectrum_table.to_sql('Spectrum', con=config.db_connection, index=False, if_exists='append') print(\"Appended to Spectrum table with info",
"spc.i}) peak_table['experiment_id'] = experiment_id peak_table['spectrum_id'] = spc.ID peak_table.to_sql('Peak', con=config.db_connection, index=False, if_exists='append') print(\"Appended to",
"already exists in DB. Continue to filling Spectrum table\") experiment_id = check[0] else:",
"check[0] else: # fill the Experiment table with data from file experiment_id =",
"\"__main__\": for n, filename in enumerate(glob.iglob('{}Geconverteerd/*.mzML'.format(config.data_dir))): print(\"reading file {} ({})\".format(n, filename.split('/')[-1])) if '+'",
"upper limit'], scan_window_lower_limit=spc['scan window lower limit']) spectrum_list.append(s) if i == 0: m =",
"with data from file create_spectrum_and_peak_tables(msrun_list, experiment_id) if __name__ == \"__main__\": for n, filename",
"create_experiment_table(msrun_list, filename): \"\"\" fills the Experiment table. :param msrun_list: an open pymzml runner",
"'experiment_id ' + 'spectrum_id' + ' mz' + ' intensity') spectrum_list = []",
"+ 'spectrum_id' + ' mz' + ' intensity') spectrum_list = [] measurement_list =",
"added to the Peak table\").format(experiment_id, spc.ID)) else: peak_table = pd.DataFrame({\"mz\": spc.mz, \"intensity\": spc.i})",
"time'], ms_level=spc['ms level'], highest_observed_mz=spc['highest observed m/z'], lowest_observed_mz=spc['lowest observed m/z'], scan_window_upper_limit=spc['scan window upper limit'],",
"msrun_list.info.keys(): start_time_str = msrun_list.info[\"start_time\"] start_time = dateutil.parser.parse(start_time_str) experiment['run_start_time'] = start_time.timestamp() experiment['human_run_start_time'] = start_time",
"None experiment['match_type_id'] = None experiment['filename'] = filename.split('/')[-1] return experiment def create_experiment_table(msrun_list, filename): \"\"\"",
"WHERE filename = '{}' \"\"\".format( filename.split('/')[-1])).fetchone()[0] return experiment_id def read_file(filename): msrun = pymzml.run.Reader(filename)",
"# fill the Spectrum and Peak table with data from file create_spectrum_and_peak_tables(msrun_list, experiment_id)",
"0: print(\"Spectrum {}\".format(i)) s = spectrum(experiment_id=experiment_id, spectrum_id=spc.ID, total_ion_current=spc['total ion current'], time_passed_since_start=spc['scan start time'],",
"msrun_list: an open pymzml runner :param filename: name of the pymzml file :return:",
"name of the pymzml file :return: \"\"\" experiment = create_experiment(msrun_list, filename) utils.append_to_experiment('Experiment', experiment)",
"= measurement(experiment_id=experiment_id, spectrum_id=spc.ID, mz=spc.mz, intensity=spc.i) # Fill peak table if experiment_id + spectrum_id",
"= spectrum(experiment_id=experiment_id, spectrum_id=spc.ID, total_ion_current=spc['total ion current'], time_passed_since_start=spc['scan start time'], ms_level=spc['ms level'], highest_observed_mz=spc['highest observed",
"start time'], ms_level=spc['ms level'], highest_observed_mz=spc['highest observed m/z'], lowest_observed_mz=spc['lowest observed m/z'], scan_window_upper_limit=spc['scan window upper",
"total_ion_current=spc['total ion current'], time_passed_since_start=spc['scan start time'], ms_level=spc['ms level'], highest_observed_mz=spc['highest observed m/z'], lowest_observed_mz=spc['lowest observed",
"the information in the msrun_list. :param msrun_list: an open pymzml runner :param filename:",
"worden experiment['run_id'] = msrun_list.info['run_id'] if \"start_time\" in msrun_list.info.keys(): start_time_str = msrun_list.info[\"start_time\"] start_time =",
"spc.ID)) measurement_list.append(m) # check if experiment_id already exists in Spectrum table. If not,",
"\"Peak\" WHERE experiment_id = '{}' AND spectrum_id = '{}'\"\"\"\\ .format(experiment_id, spc.ID)).fetchone() if check_peak",
"__name__ == \"__main__\": for n, filename in enumerate(glob.iglob('{}Geconverteerd/*.mzML'.format(config.data_dir))): print(\"reading file {} ({})\".format(n, filename.split('/')[-1]))",
"open pymzml runner :param filename: name of the pymzml file :return: \"\"\" experiment",
"\"Experiment\" WHERE filename = '{}' \"\"\".format( filename.split('/')[-1])).fetchone()[0] return experiment_id def read_file(filename): msrun =",
"table\").format(experiment_id, spc.ID)) else: peak_table = pd.DataFrame({\"mz\": spc.mz, \"intensity\": spc.i}) peak_table['experiment_id'] = experiment_id peak_table['spectrum_id']",
"''' fills the Spectrum table and for each spectrum the Peak table :param",
"None: print( (\"Experiment_id {} + spectrum_id {} combination already exists in Peak table.",
"in msrun_list.info.keys(): start_time_str = msrun_list.info[\"start_time\"] start_time = dateutil.parser.parse(start_time_str) experiment['run_start_time'] = start_time.timestamp() experiment['human_run_start_time'] =",
"combination already exists in Peak table. \" + \"To avoid duplicates the spectra",
"'scan_window_lower_limit') measurement = namedtuple('measurement', 'experiment_id ' + 'spectrum_id' + ' mz' + '",
"pymzml file :return: \"\"\" experiment = create_experiment(msrun_list, filename) utils.append_to_experiment('Experiment', experiment) experiment_id = config.db_connection.execute(",
"' + 'lowest_observed_mz ' + 'scan_window_upper_limit ' + 'scan_window_lower_limit') measurement = namedtuple('measurement', 'experiment_id",
"a dictionary containing the initialized experiment \"\"\" experiment = dict.fromkeys(['run_id', 'run_start_time', 'human_run_start_time', 'spectra_count',",
"msrun_list. :param msrun_list: an open pymzml runner :param filename: name of the pymzml",
"+ 'spectrum_id ' + 'total_ion_current ' + 'time_passed_since_start ' + 'ms_level ' +",
"'run_start_time', 'human_run_start_time', 'spectra_count', 'experimental_state_id', 'match_type_id', 'filename']) # Todo: waarden in onderstaande tabel moeten",
"experiment['human_run_start_time'] = start_time else: experiment['run_start_time'] = None experiment['human_run_start_time'] = None experiment['spectra_count'] = msrun_list.info['spectrum_count']",
"check = config.db_connection.execute( \"\"\"SELECT experiment_id from \"Experiment\" WHERE filename = '{}' \"\"\".format( filename.split('/')[-1])).fetchone()",
".format(experiment_id, spc.ID)).fetchone() if check_peak is not None: print( (\"Experiment_id {} + spectrum_id {}",
"'experimental_state_id', 'match_type_id', 'filename']) # Todo: waarden in onderstaande tabel moeten nog ingevuld worden",
"\"\"\"SELECT experiment_id from \"Experiment\" WHERE filename = '{}' \"\"\".format( filename.split('/')[-1])).fetchone()[0] return experiment_id def",
"mz=np.nan, intensity=np.nan) else: m = measurement(experiment_id=experiment_id, spectrum_id=spc.ID, mz=spc.mz, intensity=spc.i) # Fill peak table",
"already exists in Spectrum table. If not, append data to Spectrum table check_spectrum",
"def read_file(filename): msrun = pymzml.run.Reader(filename) msrun_list = list(msrun) # check if filename already",
"= config.db_connection.execute( \"\"\"SELECT experiment_id from \"Experiment\" WHERE filename = '{}' \"\"\".format( filename.split('/')[-1])).fetchone()[0] return",
"table with data from file experiment_id = create_experiment_table(msrun_list, filename) # fill the Spectrum",
"'scan_window_upper_limit ' + 'scan_window_lower_limit') measurement = namedtuple('measurement', 'experiment_id ' + 'spectrum_id' + '",
"msrun = pymzml.run.Reader(filename) msrun_list = list(msrun) # check if filename already in Experiment",
"the Experiment table with data from file experiment_id = create_experiment_table(msrun_list, filename) # fill",
"def create_experiment(msrun_list, filename): \"\"\" Create a new experiment structure based on the information",
"current'], time_passed_since_start=spc['scan start time'], ms_level=spc['ms level'], highest_observed_mz=spc['highest observed m/z'], lowest_observed_mz=spc['lowest observed m/z'], scan_window_upper_limit=spc['scan",
"filename) # fill the Spectrum and Peak table with data from file create_spectrum_and_peak_tables(msrun_list,",
"If not, append data to Spectrum table check_spectrum = config.db_connection.execute( \"\"\"SELECT experiment_id from",
"experiment_id from \"Spectrum\" WHERE experiment_id = '{}' \"\"\" .format(experiment_id)).fetchone() if check_spectrum is not",
"filename) utils.append_to_experiment('Experiment', experiment) experiment_id = config.db_connection.execute( \"\"\"SELECT experiment_id from \"Experiment\" WHERE filename =",
"spectrum_id {} combination already exists in Peak table. \" + \"To avoid duplicates",
"in Peak table. \" + \"To avoid duplicates the spectra won't be added",
"import config import lcms.utils as utils def create_spectrum_and_peak_tables(msrun_list, experiment_id): ''' fills the Spectrum",
"= create_experiment_table(msrun_list, filename) # fill the Spectrum and Peak table with data from",
"an open pymzml runner :param filename: name of the pymzml file :return: a",
"= spc.ID peak_table.to_sql('Peak', con=config.db_connection, index=False, if_exists='append') print(\"Appended to Peak table from experiment_id: {},",
"experiment_id def read_file(filename): msrun = pymzml.run.Reader(filename) msrun_list = list(msrun) # check if filename",
"return experiment_id def read_file(filename): msrun = pymzml.run.Reader(filename) msrun_list = list(msrun) # check if",
"i % 100 == 0: print(\"Spectrum {}\".format(i)) s = spectrum(experiment_id=experiment_id, spectrum_id=spc.ID, total_ion_current=spc['total ion",
"already exist in table Peak check_peak = config.db_connection.execute( \"\"\"SELECT experiment_id from \"Peak\" WHERE",
"from \"Experiment\" WHERE filename = '{}' \"\"\".format( filename.split('/')[-1])).fetchone()[0] return experiment_id def read_file(filename): msrun",
"' + 'spectrum_id ' + 'total_ion_current ' + 'time_passed_since_start ' + 'ms_level '",
"' + 'total_ion_current ' + 'time_passed_since_start ' + 'ms_level ' + 'highest_observed_mz '",
"experiment['human_run_start_time'] = None experiment['spectra_count'] = msrun_list.info['spectrum_count'] experiment['experimental_state_id'] = None experiment['match_type_id'] = None experiment['filename']",
"mz=spc.mz, intensity=spc.i) # Fill peak table if experiment_id + spectrum_id do not already",
"0: m = measurement(experiment_id=experiment_id, spectrum_id=spc.ID, mz=np.nan, intensity=np.nan) else: m = measurement(experiment_id=experiment_id, spectrum_id=spc.ID, mz=spc.mz,",
"+ 'highest_observed_mz ' + 'lowest_observed_mz ' + 'scan_window_upper_limit ' + 'scan_window_lower_limit') measurement =",
"'{}' AND spectrum_id = '{}'\"\"\"\\ .format(experiment_id, spc.ID)).fetchone() if check_peak is not None: print(",
"table with info from experiment_id: {}\".format(experiment_id)) def create_experiment(msrun_list, filename): \"\"\" Create a new",
"\"start_time\" in msrun_list.info.keys(): start_time_str = msrun_list.info[\"start_time\"] start_time = dateutil.parser.parse(start_time_str) experiment['run_start_time'] = start_time.timestamp() experiment['human_run_start_time']",
"filename.split('/')[-1])) if '+' in filename.split('/')[-1]: print(\"Raw data, will be skipped for now\") continue",
"namedtuple import dateutil.parser import numpy as np import pandas as pd import pymzml",
"an open pymzml runner :param filename: name of the pymzml file :return: \"\"\"",
"print(\"Appended to Peak table from experiment_id: {}, spectrum_id: {}\".format(experiment_id, spc.ID)) measurement_list.append(m) # check",
"# Fill peak table if experiment_id + spectrum_id do not already exist in",
"observed m/z'], lowest_observed_mz=spc['lowest observed m/z'], scan_window_upper_limit=spc['scan window upper limit'], scan_window_lower_limit=spc['scan window lower limit'])",
"start_time_str = msrun_list.info[\"start_time\"] start_time = dateutil.parser.parse(start_time_str) experiment['run_start_time'] = start_time.timestamp() experiment['human_run_start_time'] = start_time else:",
"open pymzml runner :param filename: name of the pymzml file :return: a dictionary",
"file :return: a dictionary containing the initialized experiment \"\"\" experiment = dict.fromkeys(['run_id', 'run_start_time',",
"filename: name of the pymzml file :return: a dictionary containing the initialized experiment",
"fill the Spectrum and Peak table with data from file create_spectrum_and_peak_tables(msrun_list, experiment_id) if",
"({})\".format(n, filename.split('/')[-1])) if '+' in filename.split('/')[-1]: print(\"Raw data, will be skipped for now\")",
"{} + spectrum_id {} combination already exists in Peak table. \" + \"To",
":param filename: name of the pymzml file :return: a dictionary containing the initialized",
"experiment def create_experiment_table(msrun_list, filename): \"\"\" fills the Experiment table. :param msrun_list: an open",
"= pd.DataFrame({\"mz\": spc.mz, \"intensity\": spc.i}) peak_table['experiment_id'] = experiment_id peak_table['spectrum_id'] = spc.ID peak_table.to_sql('Peak', con=config.db_connection,",
"append data to Spectrum table check_spectrum = config.db_connection.execute( \"\"\"SELECT experiment_id from \"Spectrum\" WHERE",
"peak_table = pd.DataFrame({\"mz\": spc.mz, \"intensity\": spc.i}) peak_table['experiment_id'] = experiment_id peak_table['spectrum_id'] = spc.ID peak_table.to_sql('Peak',",
"table Peak check_peak = config.db_connection.execute( \"\"\"SELECT experiment_id from \"Peak\" WHERE experiment_id = '{}'",
"from \"Experiment\" WHERE filename = '{}' \"\"\".format( filename.split('/')[-1])).fetchone() if check is not None:",
"' + 'highest_observed_mz ' + 'lowest_observed_mz ' + 'scan_window_upper_limit ' + 'scan_window_lower_limit') measurement",
"(\"Experiment_id {} + spectrum_id {} combination already exists in Peak table. \" +",
"print(\"reading file {} ({})\".format(n, filename.split('/')[-1])) if '+' in filename.split('/')[-1]: print(\"Raw data, will be",
"glob from collections import namedtuple import dateutil.parser import numpy as np import pandas",
"moeten nog ingevuld worden experiment['run_id'] = msrun_list.info['run_id'] if \"start_time\" in msrun_list.info.keys(): start_time_str =",
"import lcms.utils as utils def create_spectrum_and_peak_tables(msrun_list, experiment_id): ''' fills the Spectrum table and",
"file experiment_id = create_experiment_table(msrun_list, filename) # fill the Spectrum and Peak table with",
"+ 'time_passed_since_start ' + 'ms_level ' + 'highest_observed_mz ' + 'lowest_observed_mz ' +",
"\"\"\" fills the Experiment table. :param msrun_list: an open pymzml runner :param filename:",
"'experiment_id ' + 'spectrum_id ' + 'total_ion_current ' + 'time_passed_since_start ' + 'ms_level",
"# check if filename already in Experiment table check = config.db_connection.execute( \"\"\"SELECT experiment_id",
"''' spectrum = namedtuple('spectrum', 'experiment_id ' + 'spectrum_id ' + 'total_ion_current ' +",
"if check_spectrum is not None: print((\"Experiment_id {} already exists in Spectrum table. \"",
"in enumerate(glob.iglob('{}Geconverteerd/*.mzML'.format(config.data_dir))): print(\"reading file {} ({})\".format(n, filename.split('/')[-1])) if '+' in filename.split('/')[-1]: print(\"Raw data,",
"experiment['run_start_time'] = start_time.timestamp() experiment['human_run_start_time'] = start_time else: experiment['run_start_time'] = None experiment['human_run_start_time'] = None",
"utils def create_spectrum_and_peak_tables(msrun_list, experiment_id): ''' fills the Spectrum table and for each spectrum",
"filename = '{}' \"\"\".format( filename.split('/')[-1])).fetchone()[0] return experiment_id def read_file(filename): msrun = pymzml.run.Reader(filename) msrun_list",
"ingevuld worden experiment['run_id'] = msrun_list.info['run_id'] if \"start_time\" in msrun_list.info.keys(): start_time_str = msrun_list.info[\"start_time\"] start_time",
"create_experiment_table(msrun_list, filename) # fill the Spectrum and Peak table with data from file",
"' intensity') spectrum_list = [] measurement_list = [] for i, spc in enumerate(msrun_list):",
"print(\"Spectrum {}\".format(i)) s = spectrum(experiment_id=experiment_id, spectrum_id=spc.ID, total_ion_current=spc['total ion current'], time_passed_since_start=spc['scan start time'], ms_level=spc['ms",
"= [] for i, spc in enumerate(msrun_list): if i % 100 == 0:",
"\"\"\" experiment = create_experiment(msrun_list, filename) utils.append_to_experiment('Experiment', experiment) experiment_id = config.db_connection.execute( \"\"\"SELECT experiment_id from",
":return: \"\"\" experiment = create_experiment(msrun_list, filename) utils.append_to_experiment('Experiment', experiment) experiment_id = config.db_connection.execute( \"\"\"SELECT experiment_id",
"in the msrun_list. :param msrun_list: an open pymzml runner :param filename: name of",
"experiment_id = '{}' \"\"\" .format(experiment_id)).fetchone() if check_spectrum is not None: print((\"Experiment_id {} already",
"spc.ID)).fetchone() if check_peak is not None: print( (\"Experiment_id {} + spectrum_id {} combination",
"\"\"\" .format(experiment_id)).fetchone() if check_spectrum is not None: print((\"Experiment_id {} already exists in Spectrum",
"name of the pymzml file :return: a dictionary containing the initialized experiment \"\"\"",
"avoid duplicates the spectra won't be added to the Peak table\").format(experiment_id, spc.ID)) else:",
"index=False, if_exists='append') print(\"Appended to Peak table from experiment_id: {}, spectrum_id: {}\".format(experiment_id, spc.ID)) measurement_list.append(m)",
"'time_passed_since_start ' + 'ms_level ' + 'highest_observed_mz ' + 'lowest_observed_mz ' + 'scan_window_upper_limit",
"not, append data to Spectrum table check_spectrum = config.db_connection.execute( \"\"\"SELECT experiment_id from \"Spectrum\"",
"experiment_id) if __name__ == \"__main__\": for n, filename in enumerate(glob.iglob('{}Geconverteerd/*.mzML'.format(config.data_dir))): print(\"reading file {}",
"not None: print( (\"Experiment_id {} + spectrum_id {} combination already exists in Peak",
"as utils def create_spectrum_and_peak_tables(msrun_list, experiment_id): ''' fills the Spectrum table and for each",
"{}\".format(experiment_id)) def create_experiment(msrun_list, filename): \"\"\" Create a new experiment structure based on the",
"experiment_id + spectrum_id do not already exist in table Peak check_peak = config.db_connection.execute(",
"= '{}' \"\"\" .format(experiment_id)).fetchone() if check_spectrum is not None: print((\"Experiment_id {} already exists",
"Create a new experiment structure based on the information in the msrun_list. :param",
"spc.ID peak_table.to_sql('Peak', con=config.db_connection, index=False, if_exists='append') print(\"Appended to Peak table from experiment_id: {}, spectrum_id:",
"table\") .format(experiment_id)) else: spectrum_table = pd.DataFrame(spectrum_list) spectrum_table.to_sql('Spectrum', con=config.db_connection, index=False, if_exists='append') print(\"Appended to Spectrum",
"and Peak table with data from file create_spectrum_and_peak_tables(msrun_list, experiment_id) if __name__ == \"__main__\":",
"time_passed_since_start=spc['scan start time'], ms_level=spc['ms level'], highest_observed_mz=spc['highest observed m/z'], lowest_observed_mz=spc['lowest observed m/z'], scan_window_upper_limit=spc['scan window",
"'highest_observed_mz ' + 'lowest_observed_mz ' + 'scan_window_upper_limit ' + 'scan_window_lower_limit') measurement = namedtuple('measurement',",
"file :return: \"\"\" experiment = create_experiment(msrun_list, filename) utils.append_to_experiment('Experiment', experiment) experiment_id = config.db_connection.execute( \"\"\"SELECT",
"'{}' \"\"\" .format(experiment_id)).fetchone() if check_spectrum is not None: print((\"Experiment_id {} already exists in",
"pymzml runner :param filename: name of the pymzml file :return: \"\"\" experiment =",
"Peak check_peak = config.db_connection.execute( \"\"\"SELECT experiment_id from \"Peak\" WHERE experiment_id = '{}' AND",
"print(\"Appended to Spectrum table with info from experiment_id: {}\".format(experiment_id)) def create_experiment(msrun_list, filename): \"\"\"",
"= pd.DataFrame(spectrum_list) spectrum_table.to_sql('Spectrum', con=config.db_connection, index=False, if_exists='append') print(\"Appended to Spectrum table with info from",
"runner :param filename: name of the pymzml file :return: \"\"\" experiment = create_experiment(msrun_list,",
"measurement = namedtuple('measurement', 'experiment_id ' + 'spectrum_id' + ' mz' + ' intensity')",
"m/z'], lowest_observed_mz=spc['lowest observed m/z'], scan_window_upper_limit=spc['scan window upper limit'], scan_window_lower_limit=spc['scan window lower limit']) spectrum_list.append(s)",
"m = measurement(experiment_id=experiment_id, spectrum_id=spc.ID, mz=spc.mz, intensity=spc.i) # Fill peak table if experiment_id +",
"\"Spectrum\" WHERE experiment_id = '{}' \"\"\" .format(experiment_id)).fetchone() if check_spectrum is not None: print((\"Experiment_id",
"{} ({})\".format(n, filename.split('/')[-1])) if '+' in filename.split('/')[-1]: print(\"Raw data, will be skipped for",
"import dateutil.parser import numpy as np import pandas as pd import pymzml import",
"data from file create_spectrum_and_peak_tables(msrun_list, experiment_id) if __name__ == \"__main__\": for n, filename in",
"if experiment_id + spectrum_id do not already exist in table Peak check_peak =",
"to the Spectrum table\") .format(experiment_id)) else: spectrum_table = pd.DataFrame(spectrum_list) spectrum_table.to_sql('Spectrum', con=config.db_connection, index=False, if_exists='append')",
"' + 'spectrum_id' + ' mz' + ' intensity') spectrum_list = [] measurement_list",
"spectrum the Peak table :param msrun_list: :param experiment_id: :return: ''' spectrum = namedtuple('spectrum',",
"the spectra won't be added to the Peak table\").format(experiment_id, spc.ID)) else: peak_table =",
"table\") experiment_id = check[0] else: # fill the Experiment table with data from",
"if __name__ == \"__main__\": for n, filename in enumerate(glob.iglob('{}Geconverteerd/*.mzML'.format(config.data_dir))): print(\"reading file {} ({})\".format(n,",
"new experiment structure based on the information in the msrun_list. :param msrun_list: an",
"in table Peak check_peak = config.db_connection.execute( \"\"\"SELECT experiment_id from \"Peak\" WHERE experiment_id =",
"peak_table['experiment_id'] = experiment_id peak_table['spectrum_id'] = spc.ID peak_table.to_sql('Peak', con=config.db_connection, index=False, if_exists='append') print(\"Appended to Peak",
"to Spectrum table check_spectrum = config.db_connection.execute( \"\"\"SELECT experiment_id from \"Spectrum\" WHERE experiment_id =",
"data from file experiment_id = create_experiment_table(msrun_list, filename) # fill the Spectrum and Peak",
"else: # fill the Experiment table with data from file experiment_id = create_experiment_table(msrun_list,",
"experiment_id): ''' fills the Spectrum table and for each spectrum the Peak table",
"filename = '{}' \"\"\".format( filename.split('/')[-1])).fetchone() if check is not None: print(\"File already exists",
"spectrum_table.to_sql('Spectrum', con=config.db_connection, index=False, if_exists='append') print(\"Appended to Spectrum table with info from experiment_id: {}\".format(experiment_id))",
"check_spectrum is not None: print((\"Experiment_id {} already exists in Spectrum table. \" +",
"if '+' in filename.split('/')[-1]: print(\"Raw data, will be skipped for now\") continue read_file(filename)",
"the Peak table\").format(experiment_id, spc.ID)) else: peak_table = pd.DataFrame({\"mz\": spc.mz, \"intensity\": spc.i}) peak_table['experiment_id'] =",
"as pd import pymzml import config import lcms.utils as utils def create_spectrum_and_peak_tables(msrun_list, experiment_id):",
"table. If not, append data to Spectrum table check_spectrum = config.db_connection.execute( \"\"\"SELECT experiment_id",
"experiment_id from \"Experiment\" WHERE filename = '{}' \"\"\".format( filename.split('/')[-1])).fetchone()[0] return experiment_id def read_file(filename):",
"= start_time.timestamp() experiment['human_run_start_time'] = start_time else: experiment['run_start_time'] = None experiment['human_run_start_time'] = None experiment['spectra_count']",
"m/z'], scan_window_upper_limit=spc['scan window upper limit'], scan_window_lower_limit=spc['scan window lower limit']) spectrum_list.append(s) if i ==",
"spectrum_id do not already exist in table Peak check_peak = config.db_connection.execute( \"\"\"SELECT experiment_id",
"filename): \"\"\" Create a new experiment structure based on the information in the",
"table. \" + \"To avoid duplicates the spectra won't be added to the",
".format(experiment_id)) else: spectrum_table = pd.DataFrame(spectrum_list) spectrum_table.to_sql('Spectrum', con=config.db_connection, index=False, if_exists='append') print(\"Appended to Spectrum table",
"experiment_id from \"Experiment\" WHERE filename = '{}' \"\"\".format( filename.split('/')[-1])).fetchone() if check is not",
"+ 'lowest_observed_mz ' + 'scan_window_upper_limit ' + 'scan_window_lower_limit') measurement = namedtuple('measurement', 'experiment_id '",
"mz' + ' intensity') spectrum_list = [] measurement_list = [] for i, spc",
"\"intensity\": spc.i}) peak_table['experiment_id'] = experiment_id peak_table['spectrum_id'] = spc.ID peak_table.to_sql('Peak', con=config.db_connection, index=False, if_exists='append') print(\"Appended",
"config.db_connection.execute( \"\"\"SELECT experiment_id from \"Spectrum\" WHERE experiment_id = '{}' \"\"\" .format(experiment_id)).fetchone() if check_spectrum",
"in Spectrum table. If not, append data to Spectrum table check_spectrum = config.db_connection.execute(",
"table if experiment_id + spectrum_id do not already exist in table Peak check_peak",
"# Todo: waarden in onderstaande tabel moeten nog ingevuld worden experiment['run_id'] = msrun_list.info['run_id']",
"Spectrum table\") experiment_id = check[0] else: # fill the Experiment table with data",
"utils.append_to_experiment('Experiment', experiment) experiment_id = config.db_connection.execute( \"\"\"SELECT experiment_id from \"Experiment\" WHERE filename = '{}'",
"pandas as pd import pymzml import config import lcms.utils as utils def create_spectrum_and_peak_tables(msrun_list,",
"else: peak_table = pd.DataFrame({\"mz\": spc.mz, \"intensity\": spc.i}) peak_table['experiment_id'] = experiment_id peak_table['spectrum_id'] = spc.ID",
"experiment_id = check[0] else: # fill the Experiment table with data from file"
] |
[
"= ver, description = 'High level directory utilities', keywords = ['dir', 'directory', 'workdir',",
"'<EMAIL>', packages = find_packages(), test_suite = 'dirutil.get_tests', url = 'https://github.com/ddolzhenko/dirutil', download_url = 'https://github.com/ddolzhenko/dirutil/archive/v{}.tar.gz'.format(ver),",
"description = 'High level directory utilities', keywords = ['dir', 'directory', 'workdir', 'tempdir'], author",
"utilities', keywords = ['dir', 'directory', 'workdir', 'tempdir'], author = '<NAME>', author_email = '<EMAIL>',",
"\"0.4\" setup( name = 'dirutil', version = ver, description = 'High level directory",
"ver, description = 'High level directory utilities', keywords = ['dir', 'directory', 'workdir', 'tempdir'],",
"'https://github.com/ddolzhenko/dirutil', download_url = 'https://github.com/ddolzhenko/dirutil/archive/v{}.tar.gz'.format(ver), classifiers = [], install_requires = [ # \"checksumdir==1.0.5\", ],",
"'dirutil.get_tests', url = 'https://github.com/ddolzhenko/dirutil', download_url = 'https://github.com/ddolzhenko/dirutil/archive/v{}.tar.gz'.format(ver), classifiers = [], install_requires = [",
"packages = find_packages(), test_suite = 'dirutil.get_tests', url = 'https://github.com/ddolzhenko/dirutil', download_url = 'https://github.com/ddolzhenko/dirutil/archive/v{}.tar.gz'.format(ver), classifiers",
"['dir', 'directory', 'workdir', 'tempdir'], author = '<NAME>', author_email = '<EMAIL>', packages = find_packages(),",
"= find_packages(), test_suite = 'dirutil.get_tests', url = 'https://github.com/ddolzhenko/dirutil', download_url = 'https://github.com/ddolzhenko/dirutil/archive/v{}.tar.gz'.format(ver), classifiers =",
"'directory', 'workdir', 'tempdir'], author = '<NAME>', author_email = '<EMAIL>', packages = find_packages(), test_suite",
"= '<EMAIL>', packages = find_packages(), test_suite = 'dirutil.get_tests', url = 'https://github.com/ddolzhenko/dirutil', download_url =",
"url = 'https://github.com/ddolzhenko/dirutil', download_url = 'https://github.com/ddolzhenko/dirutil/archive/v{}.tar.gz'.format(ver), classifiers = [], install_requires = [ #",
"= 'dirutil.get_tests', url = 'https://github.com/ddolzhenko/dirutil', download_url = 'https://github.com/ddolzhenko/dirutil/archive/v{}.tar.gz'.format(ver), classifiers = [], install_requires =",
"= 'https://github.com/ddolzhenko/dirutil', download_url = 'https://github.com/ddolzhenko/dirutil/archive/v{}.tar.gz'.format(ver), classifiers = [], install_requires = [ # \"checksumdir==1.0.5\",",
"find_packages ver = \"0.4\" setup( name = 'dirutil', version = ver, description =",
"'workdir', 'tempdir'], author = '<NAME>', author_email = '<EMAIL>', packages = find_packages(), test_suite =",
"setup( name = 'dirutil', version = ver, description = 'High level directory utilities',",
"directory utilities', keywords = ['dir', 'directory', 'workdir', 'tempdir'], author = '<NAME>', author_email =",
"ver = \"0.4\" setup( name = 'dirutil', version = ver, description = 'High",
"setuptools import setup, find_packages ver = \"0.4\" setup( name = 'dirutil', version =",
"name = 'dirutil', version = ver, description = 'High level directory utilities', keywords",
"test_suite = 'dirutil.get_tests', url = 'https://github.com/ddolzhenko/dirutil', download_url = 'https://github.com/ddolzhenko/dirutil/archive/v{}.tar.gz'.format(ver), classifiers = [], install_requires",
"from setuptools import setup, find_packages ver = \"0.4\" setup( name = 'dirutil', version",
"level directory utilities', keywords = ['dir', 'directory', 'workdir', 'tempdir'], author = '<NAME>', author_email",
"download_url = 'https://github.com/ddolzhenko/dirutil/archive/v{}.tar.gz'.format(ver), classifiers = [], install_requires = [ # \"checksumdir==1.0.5\", ], )",
"'High level directory utilities', keywords = ['dir', 'directory', 'workdir', 'tempdir'], author = '<NAME>',",
"= ['dir', 'directory', 'workdir', 'tempdir'], author = '<NAME>', author_email = '<EMAIL>', packages =",
"'tempdir'], author = '<NAME>', author_email = '<EMAIL>', packages = find_packages(), test_suite = 'dirutil.get_tests',",
"author_email = '<EMAIL>', packages = find_packages(), test_suite = 'dirutil.get_tests', url = 'https://github.com/ddolzhenko/dirutil', download_url",
"'dirutil', version = ver, description = 'High level directory utilities', keywords = ['dir',",
"= 'dirutil', version = ver, description = 'High level directory utilities', keywords =",
"'<NAME>', author_email = '<EMAIL>', packages = find_packages(), test_suite = 'dirutil.get_tests', url = 'https://github.com/ddolzhenko/dirutil',",
"version = ver, description = 'High level directory utilities', keywords = ['dir', 'directory',",
"find_packages(), test_suite = 'dirutil.get_tests', url = 'https://github.com/ddolzhenko/dirutil', download_url = 'https://github.com/ddolzhenko/dirutil/archive/v{}.tar.gz'.format(ver), classifiers = [],",
"keywords = ['dir', 'directory', 'workdir', 'tempdir'], author = '<NAME>', author_email = '<EMAIL>', packages",
"= \"0.4\" setup( name = 'dirutil', version = ver, description = 'High level",
"= 'High level directory utilities', keywords = ['dir', 'directory', 'workdir', 'tempdir'], author =",
"= '<NAME>', author_email = '<EMAIL>', packages = find_packages(), test_suite = 'dirutil.get_tests', url =",
"import setup, find_packages ver = \"0.4\" setup( name = 'dirutil', version = ver,",
"setup, find_packages ver = \"0.4\" setup( name = 'dirutil', version = ver, description",
"author = '<NAME>', author_email = '<EMAIL>', packages = find_packages(), test_suite = 'dirutil.get_tests', url"
] |
[
"= data[:] random.shuffle(individual) return individual def crossover(parent_1, parent_2): crossover_index = random.randrange(1, len(parent_1)) child_1a",
"= mutate, fitness = fitness, selection = selection) res = optimizer() # print",
"optimizer = ga.get_optimizer(data, population_size = 200, generations = 100, crossover_probability = 0.8, mutation_probability",
"100, crossover_probability = 0.8, mutation_probability = 0.2, elitism = True, maximise_fitness = False)",
"x_position): print('-' + ''.join(['----' for _ in range(row_length)])) print('|' + ''.join([' X |'",
"= 0 for item in individual: item_index = individual.index(item) for elem in individual:",
"in parent_2 if i not in child_1a] child_1 = child_1a + child_1b child_2a",
"item_index != elem_index: if item - (elem_index - item_index) == elem\\ or (elem_index",
"(elem_index - item_index) + item == elem: collisions += 1 return collisions def",
"if i not in child_1a] child_1 = child_1a + child_1b child_2a = parent_2[crossover_index:]",
"columns in a chessboard for row in range(num_of_rows): print_x_in_row(row_length, board_representation[row]) print_board_bottom(row_length) print('\\n') optimizer",
"ingine import ga # setup seed data data = [0, 1, 2, 3,",
"mutate(individual): mutate_index1 = random.randrange(len(individual)) mutate_index2 = random.randrange(len(individual)) individual[mutate_index1], individual[mutate_index2] = individual[mutate_index2], individual[mutate_index1] def",
"''.join(['----' for _ in range(row_length)])) num_of_rows = len(board_representation) row_length = num_of_rows #rows ==",
"= [i for i in parent_2 if i not in child_1a] child_1 =",
"for elem in individual: elem_index = individual.index(elem) if item_index != elem_index: if item",
"= child_2a + child_2b return child_1, child_2 def mutate(individual): mutate_index1 = random.randrange(len(individual)) mutate_index2",
"+= 1 return collisions def print_board(board_representation): def print_x_in_row(row_length, x_position): print('-' + ''.join(['----' for",
"item in individual: item_index = individual.index(item) for elem in individual: elem_index = individual.index(elem)",
"= 0.2, elitism = True, maximise_fitness = False) # define and set function",
"best solution; a solution is valid only if there are no collisions if",
"for item in individual: item_index = individual.index(item) for elem in individual: elem_index =",
"random from pyeasyga import pyeasyga from ingine import ga # setup seed data",
"- item_index) + item == elem: collisions += 1 return collisions def print_board(board_representation):",
"' |' for i in range(row_length)])), def print_board_bottom(row_length): print('-' + ''.join(['----' for _",
"a chessboard for row in range(num_of_rows): print_x_in_row(row_length, board_representation[row]) print_board_bottom(row_length) print('\\n') optimizer = ga.get_optimizer(data,",
"num_of_rows = len(board_representation) row_length = num_of_rows #rows == columns in a chessboard for",
"= 0.8, mutation_probability = 0.2, elitism = True, maximise_fitness = False, create_individual =",
"= random.randrange(len(individual)) individual[mutate_index1], individual[mutate_index2] = individual[mutate_index2], individual[mutate_index1] def selection(population): return random.choice(population) def fitness(individual,",
"''.join(['----' for _ in range(row_length)])) print('|' + ''.join([' X |' if i ==",
"not in child_2a] child_2 = child_2a + child_2b return child_1, child_2 def mutate(individual):",
"chessboard for row in range(num_of_rows): print_x_in_row(row_length, board_representation[row]) print_board_bottom(row_length) print('\\n') optimizer = ga.get_optimizer(data, population_size",
"create_individual = create_individual, crossover = crossover, mutate = mutate, fitness = fitness, selection",
"valid only if there are no collisions if res[0] == 0: print(res) print_board(res[1])",
"0.2, elitism = True, maximise_fitness = False) # define and set function to",
"item_index = individual.index(item) for elem in individual: elem_index = individual.index(elem) if item_index !=",
"def print_board_bottom(row_length): print('-' + ''.join(['----' for _ in range(row_length)])) num_of_rows = len(board_representation) row_length",
"def fitness(individual, data): collisions = 0 for item in individual: item_index = individual.index(item)",
"range(num_of_rows): print_x_in_row(row_length, board_representation[row]) print_board_bottom(row_length) print('\\n') optimizer = ga.get_optimizer(data, population_size = 200, generations =",
"crossover = crossover, mutate = mutate, fitness = fitness, selection = selection) res",
"from ingine import ga # setup seed data data = [0, 1, 2,",
"return individual def crossover(parent_1, parent_2): crossover_index = random.randrange(1, len(parent_1)) child_1a = parent_1[:crossover_index] child_1b",
"+ ''.join(['----' for _ in range(row_length)])) num_of_rows = len(board_representation) row_length = num_of_rows #rows",
"1, 2, 3, 4, 5, 6, 7] # initialise the GA gaa =",
"== elem: collisions += 1 return collisions def print_board(board_representation): def print_x_in_row(row_length, x_position): print('-'",
"child_2a = parent_2[crossover_index:] child_2b = [i for i in parent_1 if i not",
"parent_1 if i not in child_2a] child_2 = child_2a + child_2b return child_1,",
"crossover_probability = 0.8, mutation_probability = 0.2, elitism = True, maximise_fitness = False) #",
"= 0.8, mutation_probability = 0.2, elitism = True, maximise_fitness = False) # define",
"to create a candidate solution representation def create_individual(data): individual = data[:] random.shuffle(individual) return",
"not in child_1a] child_1 = child_1a + child_1b child_2a = parent_2[crossover_index:] child_2b =",
"in parent_1 if i not in child_2a] child_2 = child_2a + child_2b return",
"individual: elem_index = individual.index(elem) if item_index != elem_index: if item - (elem_index -",
"only if there are no collisions if res[0] == 0: print(res) print_board(res[1]) else:",
"i == x_position else ' |' for i in range(row_length)])), def print_board_bottom(row_length): print('-'",
"individual.index(elem) if item_index != elem_index: if item - (elem_index - item_index) == elem\\",
"_ in range(row_length)])) print('|' + ''.join([' X |' if i == x_position else",
"= parent_1[:crossover_index] child_1b = [i for i in parent_2 if i not in",
"parent_2[crossover_index:] child_2b = [i for i in parent_1 if i not in child_2a]",
"child_2 = child_2a + child_2b return child_1, child_2 def mutate(individual): mutate_index1 = random.randrange(len(individual))",
"return collisions def print_board(board_representation): def print_x_in_row(row_length, x_position): print('-' + ''.join(['----' for _ in",
"7] # initialise the GA gaa = pyeasyga.GeneticAlgorithm(data, population_size = 200, generations =",
"range(row_length)])), def print_board_bottom(row_length): print('-' + ''.join(['----' for _ in range(row_length)])) num_of_rows = len(board_representation)",
"function to create a candidate solution representation def create_individual(data): individual = data[:] random.shuffle(individual)",
"= ga.get_optimizer(data, population_size = 200, generations = 100, crossover_probability = 0.8, mutation_probability =",
"mutate, fitness = fitness, selection = selection) res = optimizer() # print the",
"child_2a] child_2 = child_2a + child_2b return child_1, child_2 def mutate(individual): mutate_index1 =",
"item_index) == elem\\ or (elem_index - item_index) + item == elem: collisions +=",
"for row in range(num_of_rows): print_x_in_row(row_length, board_representation[row]) print_board_bottom(row_length) print('\\n') optimizer = ga.get_optimizer(data, population_size =",
"the GA's best solution; a solution is valid only if there are no",
"data = [0, 1, 2, 3, 4, 5, 6, 7] # initialise the",
"- (elem_index - item_index) == elem\\ or (elem_index - item_index) + item ==",
"def mutate(individual): mutate_index1 = random.randrange(len(individual)) mutate_index2 = random.randrange(len(individual)) individual[mutate_index1], individual[mutate_index2] = individual[mutate_index2], individual[mutate_index1]",
"= selection) res = optimizer() # print the GA's best solution; a solution",
"solution is valid only if there are no collisions if res[0] == 0:",
"elem\\ or (elem_index - item_index) + item == elem: collisions += 1 return",
"initialise the GA gaa = pyeasyga.GeneticAlgorithm(data, population_size = 200, generations = 100, crossover_probability",
"= False, create_individual = create_individual, crossover = crossover, mutate = mutate, fitness =",
"== elem\\ or (elem_index - item_index) + item == elem: collisions += 1",
"child_1 = child_1a + child_1b child_2a = parent_2[crossover_index:] child_2b = [i for i",
"mutation_probability = 0.2, elitism = True, maximise_fitness = False) # define and set",
"random.randrange(1, len(parent_1)) child_1a = parent_1[:crossover_index] child_1b = [i for i in parent_2 if",
"X |' if i == x_position else ' |' for i in range(row_length)])),",
"and set function to create a candidate solution representation def create_individual(data): individual =",
"3, 4, 5, 6, 7] # initialise the GA gaa = pyeasyga.GeneticAlgorithm(data, population_size",
"= pyeasyga.GeneticAlgorithm(data, population_size = 200, generations = 100, crossover_probability = 0.8, mutation_probability =",
"child_1a = parent_1[:crossover_index] child_1b = [i for i in parent_2 if i not",
"= 200, generations = 100, crossover_probability = 0.8, mutation_probability = 0.2, elitism =",
"crossover_index = random.randrange(1, len(parent_1)) child_1a = parent_1[:crossover_index] child_1b = [i for i in",
"child_1, child_2 def mutate(individual): mutate_index1 = random.randrange(len(individual)) mutate_index2 = random.randrange(len(individual)) individual[mutate_index1], individual[mutate_index2] =",
"= [0, 1, 2, 3, 4, 5, 6, 7] # initialise the GA",
"GA gaa = pyeasyga.GeneticAlgorithm(data, population_size = 200, generations = 100, crossover_probability = 0.8,",
"ga # setup seed data data = [0, 1, 2, 3, 4, 5,",
"print('|' + ''.join([' X |' if i == x_position else ' |' for",
"= num_of_rows #rows == columns in a chessboard for row in range(num_of_rows): print_x_in_row(row_length,",
"row in range(num_of_rows): print_x_in_row(row_length, board_representation[row]) print_board_bottom(row_length) print('\\n') optimizer = ga.get_optimizer(data, population_size = 200,",
"False, create_individual = create_individual, crossover = crossover, mutate = mutate, fitness = fitness,",
"def print_board(board_representation): def print_x_in_row(row_length, x_position): print('-' + ''.join(['----' for _ in range(row_length)])) print('|'",
"is valid only if there are no collisions if res[0] == 0: print(res)",
"in individual: elem_index = individual.index(elem) if item_index != elem_index: if item - (elem_index",
"individual = data[:] random.shuffle(individual) return individual def crossover(parent_1, parent_2): crossover_index = random.randrange(1, len(parent_1))",
"selection(population): return random.choice(population) def fitness(individual, data): collisions = 0 for item in individual:",
"- item_index) == elem\\ or (elem_index - item_index) + item == elem: collisions",
"in a chessboard for row in range(num_of_rows): print_x_in_row(row_length, board_representation[row]) print_board_bottom(row_length) print('\\n') optimizer =",
"crossover, mutate = mutate, fitness = fitness, selection = selection) res = optimizer()",
"elitism = True, maximise_fitness = False, create_individual = create_individual, crossover = crossover, mutate",
"= 100, crossover_probability = 0.8, mutation_probability = 0.2, elitism = True, maximise_fitness =",
"row_length = num_of_rows #rows == columns in a chessboard for row in range(num_of_rows):",
"print_board_bottom(row_length) print('\\n') optimizer = ga.get_optimizer(data, population_size = 200, generations = 100, crossover_probability =",
"for _ in range(row_length)])) num_of_rows = len(board_representation) row_length = num_of_rows #rows == columns",
"in child_1a] child_1 = child_1a + child_1b child_2a = parent_2[crossover_index:] child_2b = [i",
"from pyeasyga import pyeasyga from ingine import ga # setup seed data data",
"def selection(population): return random.choice(population) def fitness(individual, data): collisions = 0 for item in",
"print_x_in_row(row_length, board_representation[row]) print_board_bottom(row_length) print('\\n') optimizer = ga.get_optimizer(data, population_size = 200, generations = 100,",
"# define and set function to create a candidate solution representation def create_individual(data):",
"a candidate solution representation def create_individual(data): individual = data[:] random.shuffle(individual) return individual def",
"representation def create_individual(data): individual = data[:] random.shuffle(individual) return individual def crossover(parent_1, parent_2): crossover_index",
"''.join([' X |' if i == x_position else ' |' for i in",
"= individual.index(item) for elem in individual: elem_index = individual.index(elem) if item_index != elem_index:",
"ga.get_optimizer(data, population_size = 200, generations = 100, crossover_probability = 0.8, mutation_probability = 0.2,",
"= random.randrange(len(individual)) mutate_index2 = random.randrange(len(individual)) individual[mutate_index1], individual[mutate_index2] = individual[mutate_index2], individual[mutate_index1] def selection(population): return",
"child_1a] child_1 = child_1a + child_1b child_2a = parent_2[crossover_index:] child_2b = [i for",
"|' if i == x_position else ' |' for i in range(row_length)])), def",
"True, maximise_fitness = False) # define and set function to create a candidate",
"import pyeasyga from ingine import ga # setup seed data data = [0,",
"[i for i in parent_2 if i not in child_1a] child_1 = child_1a",
"data[:] random.shuffle(individual) return individual def crossover(parent_1, parent_2): crossover_index = random.randrange(1, len(parent_1)) child_1a =",
"pyeasyga.GeneticAlgorithm(data, population_size = 200, generations = 100, crossover_probability = 0.8, mutation_probability = 0.2,",
"= create_individual, crossover = crossover, mutate = mutate, fitness = fitness, selection =",
"GA's best solution; a solution is valid only if there are no collisions",
"= crossover, mutate = mutate, fitness = fitness, selection = selection) res =",
"0.8, mutation_probability = 0.2, elitism = True, maximise_fitness = False) # define and",
"return child_1, child_2 def mutate(individual): mutate_index1 = random.randrange(len(individual)) mutate_index2 = random.randrange(len(individual)) individual[mutate_index1], individual[mutate_index2]",
"= [i for i in parent_1 if i not in child_2a] child_2 =",
"elem in individual: elem_index = individual.index(elem) if item_index != elem_index: if item -",
"item_index) + item == elem: collisions += 1 return collisions def print_board(board_representation): def",
"data data = [0, 1, 2, 3, 4, 5, 6, 7] # initialise",
"i in parent_2 if i not in child_1a] child_1 = child_1a + child_1b",
"maximise_fitness = False) # define and set function to create a candidate solution",
"2, 3, 4, 5, 6, 7] # initialise the GA gaa = pyeasyga.GeneticAlgorithm(data,",
"parent_2): crossover_index = random.randrange(1, len(parent_1)) child_1a = parent_1[:crossover_index] child_1b = [i for i",
"= parent_2[crossover_index:] child_2b = [i for i in parent_1 if i not in",
"collisions += 1 return collisions def print_board(board_representation): def print_x_in_row(row_length, x_position): print('-' + ''.join(['----'",
"crossover_probability = 0.8, mutation_probability = 0.2, elitism = True, maximise_fitness = False, create_individual",
"0.8, mutation_probability = 0.2, elitism = True, maximise_fitness = False, create_individual = create_individual,",
"maximise_fitness = False, create_individual = create_individual, crossover = crossover, mutate = mutate, fitness",
"res = optimizer() # print the GA's best solution; a solution is valid",
"a solution is valid only if there are no collisions if res[0] ==",
"= individual[mutate_index2], individual[mutate_index1] def selection(population): return random.choice(population) def fitness(individual, data): collisions = 0",
"collisions def print_board(board_representation): def print_x_in_row(row_length, x_position): print('-' + ''.join(['----' for _ in range(row_length)]))",
"fitness(individual, data): collisions = 0 for item in individual: item_index = individual.index(item) for",
"range(row_length)])) print('|' + ''.join([' X |' if i == x_position else ' |'",
"mutation_probability = 0.2, elitism = True, maximise_fitness = False, create_individual = create_individual, crossover",
"population_size = 200, generations = 100, crossover_probability = 0.8, mutation_probability = 0.2, elitism",
"if i == x_position else ' |' for i in range(row_length)])), def print_board_bottom(row_length):",
"mutate_index1 = random.randrange(len(individual)) mutate_index2 = random.randrange(len(individual)) individual[mutate_index1], individual[mutate_index2] = individual[mutate_index2], individual[mutate_index1] def selection(population):",
"True, maximise_fitness = False, create_individual = create_individual, crossover = crossover, mutate = mutate,",
"collisions = 0 for item in individual: item_index = individual.index(item) for elem in",
"i in parent_1 if i not in child_2a] child_2 = child_2a + child_2b",
"item - (elem_index - item_index) == elem\\ or (elem_index - item_index) + item",
"= random.randrange(1, len(parent_1)) child_1a = parent_1[:crossover_index] child_1b = [i for i in parent_2",
"mutate_index2 = random.randrange(len(individual)) individual[mutate_index1], individual[mutate_index2] = individual[mutate_index2], individual[mutate_index1] def selection(population): return random.choice(population) def",
"== x_position else ' |' for i in range(row_length)])), def print_board_bottom(row_length): print('-' +",
"num_of_rows #rows == columns in a chessboard for row in range(num_of_rows): print_x_in_row(row_length, board_representation[row])",
"parent_2 if i not in child_1a] child_1 = child_1a + child_1b child_2a =",
"optimizer() # print the GA's best solution; a solution is valid only if",
"_ in range(row_length)])) num_of_rows = len(board_representation) row_length = num_of_rows #rows == columns in",
"def print_x_in_row(row_length, x_position): print('-' + ''.join(['----' for _ in range(row_length)])) print('|' + ''.join(['",
"crossover(parent_1, parent_2): crossover_index = random.randrange(1, len(parent_1)) child_1a = parent_1[:crossover_index] child_1b = [i for",
"0 for item in individual: item_index = individual.index(item) for elem in individual: elem_index",
"5, 6, 7] # initialise the GA gaa = pyeasyga.GeneticAlgorithm(data, population_size = 200,",
"if item - (elem_index - item_index) == elem\\ or (elem_index - item_index) +",
"+ child_1b child_2a = parent_2[crossover_index:] child_2b = [i for i in parent_1 if",
"1 return collisions def print_board(board_representation): def print_x_in_row(row_length, x_position): print('-' + ''.join(['----' for _",
"seed data data = [0, 1, 2, 3, 4, 5, 6, 7] #",
"board_representation[row]) print_board_bottom(row_length) print('\\n') optimizer = ga.get_optimizer(data, population_size = 200, generations = 100, crossover_probability",
"= child_1a + child_1b child_2a = parent_2[crossover_index:] child_2b = [i for i in",
"print the GA's best solution; a solution is valid only if there are",
"gaa = pyeasyga.GeneticAlgorithm(data, population_size = 200, generations = 100, crossover_probability = 0.8, mutation_probability",
"item == elem: collisions += 1 return collisions def print_board(board_representation): def print_x_in_row(row_length, x_position):",
"child_2a + child_2b return child_1, child_2 def mutate(individual): mutate_index1 = random.randrange(len(individual)) mutate_index2 =",
"print_board(board_representation): def print_x_in_row(row_length, x_position): print('-' + ''.join(['----' for _ in range(row_length)])) print('|' +",
"child_1a + child_1b child_2a = parent_2[crossover_index:] child_2b = [i for i in parent_1",
"[0, 1, 2, 3, 4, 5, 6, 7] # initialise the GA gaa",
"for i in range(row_length)])), def print_board_bottom(row_length): print('-' + ''.join(['----' for _ in range(row_length)]))",
"+ child_2b return child_1, child_2 def mutate(individual): mutate_index1 = random.randrange(len(individual)) mutate_index2 = random.randrange(len(individual))",
"+ ''.join(['----' for _ in range(row_length)])) print('|' + ''.join([' X |' if i",
"individual def crossover(parent_1, parent_2): crossover_index = random.randrange(1, len(parent_1)) child_1a = parent_1[:crossover_index] child_1b =",
"pyeasyga import pyeasyga from ingine import ga # setup seed data data =",
"print_board_bottom(row_length): print('-' + ''.join(['----' for _ in range(row_length)])) num_of_rows = len(board_representation) row_length =",
"random.randrange(len(individual)) individual[mutate_index1], individual[mutate_index2] = individual[mutate_index2], individual[mutate_index1] def selection(population): return random.choice(population) def fitness(individual, data):",
"in range(row_length)])) num_of_rows = len(board_representation) row_length = num_of_rows #rows == columns in a",
"else ' |' for i in range(row_length)])), def print_board_bottom(row_length): print('-' + ''.join(['----' for",
"random.randrange(len(individual)) mutate_index2 = random.randrange(len(individual)) individual[mutate_index1], individual[mutate_index2] = individual[mutate_index2], individual[mutate_index1] def selection(population): return random.choice(population)",
"= 0.2, elitism = True, maximise_fitness = False, create_individual = create_individual, crossover =",
"solution; a solution is valid only if there are no collisions if res[0]",
"<filename>ingine/examples/eight_queens_puzzle.py import random from pyeasyga import pyeasyga from ingine import ga # setup",
"+ item == elem: collisions += 1 return collisions def print_board(board_representation): def print_x_in_row(row_length,",
"fitness = fitness, selection = selection) res = optimizer() # print the GA's",
"or (elem_index - item_index) + item == elem: collisions += 1 return collisions",
"= False) # define and set function to create a candidate solution representation",
"parent_1[:crossover_index] child_1b = [i for i in parent_2 if i not in child_1a]",
"generations = 100, crossover_probability = 0.8, mutation_probability = 0.2, elitism = True, maximise_fitness",
"i not in child_2a] child_2 = child_2a + child_2b return child_1, child_2 def",
"define and set function to create a candidate solution representation def create_individual(data): individual",
"elem_index = individual.index(elem) if item_index != elem_index: if item - (elem_index - item_index)",
"in range(row_length)])) print('|' + ''.join([' X |' if i == x_position else '",
"child_2 def mutate(individual): mutate_index1 = random.randrange(len(individual)) mutate_index2 = random.randrange(len(individual)) individual[mutate_index1], individual[mutate_index2] = individual[mutate_index2],",
"print('-' + ''.join(['----' for _ in range(row_length)])) num_of_rows = len(board_representation) row_length = num_of_rows",
"= True, maximise_fitness = False) # define and set function to create a",
"len(board_representation) row_length = num_of_rows #rows == columns in a chessboard for row in",
"for i in parent_2 if i not in child_1a] child_1 = child_1a +",
"i not in child_1a] child_1 = child_1a + child_1b child_2a = parent_2[crossover_index:] child_2b",
"= optimizer() # print the GA's best solution; a solution is valid only",
"child_2b = [i for i in parent_1 if i not in child_2a] child_2",
"elitism = True, maximise_fitness = False) # define and set function to create",
"individual.index(item) for elem in individual: elem_index = individual.index(elem) if item_index != elem_index: if",
"= True, maximise_fitness = False, create_individual = create_individual, crossover = crossover, mutate =",
"elem_index: if item - (elem_index - item_index) == elem\\ or (elem_index - item_index)",
"# setup seed data data = [0, 1, 2, 3, 4, 5, 6,",
"print('\\n') optimizer = ga.get_optimizer(data, population_size = 200, generations = 100, crossover_probability = 0.8,",
"individual[mutate_index2] = individual[mutate_index2], individual[mutate_index1] def selection(population): return random.choice(population) def fitness(individual, data): collisions =",
"for _ in range(row_length)])) print('|' + ''.join([' X |' if i == x_position",
"import random from pyeasyga import pyeasyga from ingine import ga # setup seed",
"individual[mutate_index2], individual[mutate_index1] def selection(population): return random.choice(population) def fitness(individual, data): collisions = 0 for",
"print_x_in_row(row_length, x_position): print('-' + ''.join(['----' for _ in range(row_length)])) print('|' + ''.join([' X",
"selection = selection) res = optimizer() # print the GA's best solution; a",
"random.choice(population) def fitness(individual, data): collisions = 0 for item in individual: item_index =",
"data): collisions = 0 for item in individual: item_index = individual.index(item) for elem",
"|' for i in range(row_length)])), def print_board_bottom(row_length): print('-' + ''.join(['----' for _ in",
"solution representation def create_individual(data): individual = data[:] random.shuffle(individual) return individual def crossover(parent_1, parent_2):",
"fitness, selection = selection) res = optimizer() # print the GA's best solution;",
"in child_2a] child_2 = child_2a + child_2b return child_1, child_2 def mutate(individual): mutate_index1",
"[i for i in parent_1 if i not in child_2a] child_2 = child_2a",
"individual[mutate_index1] def selection(population): return random.choice(population) def fitness(individual, data): collisions = 0 for item",
"child_1b child_2a = parent_2[crossover_index:] child_2b = [i for i in parent_1 if i",
"selection) res = optimizer() # print the GA's best solution; a solution is",
"print('-' + ''.join(['----' for _ in range(row_length)])) print('|' + ''.join([' X |' if",
"create_individual(data): individual = data[:] random.shuffle(individual) return individual def crossover(parent_1, parent_2): crossover_index = random.randrange(1,",
"== columns in a chessboard for row in range(num_of_rows): print_x_in_row(row_length, board_representation[row]) print_board_bottom(row_length) print('\\n')",
"random.shuffle(individual) return individual def crossover(parent_1, parent_2): crossover_index = random.randrange(1, len(parent_1)) child_1a = parent_1[:crossover_index]",
"def crossover(parent_1, parent_2): crossover_index = random.randrange(1, len(parent_1)) child_1a = parent_1[:crossover_index] child_1b = [i",
"x_position else ' |' for i in range(row_length)])), def print_board_bottom(row_length): print('-' + ''.join(['----'",
"#rows == columns in a chessboard for row in range(num_of_rows): print_x_in_row(row_length, board_representation[row]) print_board_bottom(row_length)",
"import ga # setup seed data data = [0, 1, 2, 3, 4,",
"candidate solution representation def create_individual(data): individual = data[:] random.shuffle(individual) return individual def crossover(parent_1,",
"child_1b = [i for i in parent_2 if i not in child_1a] child_1",
"if item_index != elem_index: if item - (elem_index - item_index) == elem\\ or",
"False) # define and set function to create a candidate solution representation def",
"setup seed data data = [0, 1, 2, 3, 4, 5, 6, 7]",
"= len(board_representation) row_length = num_of_rows #rows == columns in a chessboard for row",
"100, crossover_probability = 0.8, mutation_probability = 0.2, elitism = True, maximise_fitness = False,",
"individual[mutate_index1], individual[mutate_index2] = individual[mutate_index2], individual[mutate_index1] def selection(population): return random.choice(population) def fitness(individual, data): collisions",
"pyeasyga from ingine import ga # setup seed data data = [0, 1,",
"!= elem_index: if item - (elem_index - item_index) == elem\\ or (elem_index -",
"child_2b return child_1, child_2 def mutate(individual): mutate_index1 = random.randrange(len(individual)) mutate_index2 = random.randrange(len(individual)) individual[mutate_index1],",
"4, 5, 6, 7] # initialise the GA gaa = pyeasyga.GeneticAlgorithm(data, population_size =",
"the GA gaa = pyeasyga.GeneticAlgorithm(data, population_size = 200, generations = 100, crossover_probability =",
"mutate = mutate, fitness = fitness, selection = selection) res = optimizer() #",
"for i in parent_1 if i not in child_2a] child_2 = child_2a +",
"individual: item_index = individual.index(item) for elem in individual: elem_index = individual.index(elem) if item_index",
"def create_individual(data): individual = data[:] random.shuffle(individual) return individual def crossover(parent_1, parent_2): crossover_index =",
"if there are no collisions if res[0] == 0: print(res) print_board(res[1]) else: print(None)",
"in individual: item_index = individual.index(item) for elem in individual: elem_index = individual.index(elem) if",
"if i not in child_2a] child_2 = child_2a + child_2b return child_1, child_2",
"6, 7] # initialise the GA gaa = pyeasyga.GeneticAlgorithm(data, population_size = 200, generations",
"# initialise the GA gaa = pyeasyga.GeneticAlgorithm(data, population_size = 200, generations = 100,",
"create a candidate solution representation def create_individual(data): individual = data[:] random.shuffle(individual) return individual",
"in range(row_length)])), def print_board_bottom(row_length): print('-' + ''.join(['----' for _ in range(row_length)])) num_of_rows =",
"elem: collisions += 1 return collisions def print_board(board_representation): def print_x_in_row(row_length, x_position): print('-' +",
"i in range(row_length)])), def print_board_bottom(row_length): print('-' + ''.join(['----' for _ in range(row_length)])) num_of_rows",
"0.2, elitism = True, maximise_fitness = False, create_individual = create_individual, crossover = crossover,",
"create_individual, crossover = crossover, mutate = mutate, fitness = fitness, selection = selection)",
"200, generations = 100, crossover_probability = 0.8, mutation_probability = 0.2, elitism = True,",
"set function to create a candidate solution representation def create_individual(data): individual = data[:]",
"(elem_index - item_index) == elem\\ or (elem_index - item_index) + item == elem:",
"# print the GA's best solution; a solution is valid only if there",
"return random.choice(population) def fitness(individual, data): collisions = 0 for item in individual: item_index",
"in range(num_of_rows): print_x_in_row(row_length, board_representation[row]) print_board_bottom(row_length) print('\\n') optimizer = ga.get_optimizer(data, population_size = 200, generations",
"len(parent_1)) child_1a = parent_1[:crossover_index] child_1b = [i for i in parent_2 if i",
"range(row_length)])) num_of_rows = len(board_representation) row_length = num_of_rows #rows == columns in a chessboard",
"= fitness, selection = selection) res = optimizer() # print the GA's best",
"+ ''.join([' X |' if i == x_position else ' |' for i",
"= individual.index(elem) if item_index != elem_index: if item - (elem_index - item_index) =="
] |
[
"state_size self.action_size = action_size self.memory = deque(maxlen=2000) self.gamma = 0.95 # discount future",
"0.995 self.exploration_min = 0.01 self.model = self._build_model() def _build_model(self): model = Sequential() model.add(Dense(24,",
"import deque import random import numpy as np from collections import deque from",
"deque from keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam",
"= 0.995 self.exploration_min = 0.01 self.model = self._build_model() def _build_model(self): model = Sequential()",
"self.state_size = state_size self.action_size = action_size self.memory = deque(maxlen=2000) self.gamma = 0.95 #",
"rewards less self.exploration_rate = 1 self.exploration_decay = 0.995 self.exploration_min = 0.01 self.model =",
"def __init__(self, state_size, action_size): self.state_size = state_size self.action_size = action_size self.memory = deque(maxlen=2000)",
"less self.exploration_rate = 1 self.exploration_decay = 0.995 self.exploration_min = 0.01 self.model = self._build_model()",
"random import numpy as np from collections import deque from keras.models import Sequential",
"from keras.optimizers import Adam class DYNAgent: def __init__(self, state_size, action_size): self.state_size = state_size",
"= Sequential() model.add(Dense(24, input_dim=self.state_size, activation='relu')) model.add(Dense(24, activation='relu')) model.add(Dense(self.action_size, activation='linear')) model.compile(loss='mse', optimizer=Adam(lr=self.learning_rate)) return model",
"Sequential from keras.layers import Dense from keras.optimizers import Adam class DYNAgent: def __init__(self,",
"self.exploration_min = 0.01 self.model = self._build_model() def _build_model(self): model = Sequential() model.add(Dense(24, input_dim=self.state_size,",
"_build_model(self): model = Sequential() model.add(Dense(24, input_dim=self.state_size, activation='relu')) model.add(Dense(24, activation='relu')) model.add(Dense(self.action_size, activation='linear')) model.compile(loss='mse', optimizer=Adam(lr=self.learning_rate))",
"future rewards less self.exploration_rate = 1 self.exploration_decay = 0.995 self.exploration_min = 0.01 self.model",
"0.01 self.model = self._build_model() def _build_model(self): model = Sequential() model.add(Dense(24, input_dim=self.state_size, activation='relu')) model.add(Dense(24,",
"from collections import deque from keras.models import Sequential from keras.layers import Dense from",
"def _build_model(self): model = Sequential() model.add(Dense(24, input_dim=self.state_size, activation='relu')) model.add(Dense(24, activation='relu')) model.add(Dense(self.action_size, activation='linear')) model.compile(loss='mse',",
"0.95 # discount future rewards less self.exploration_rate = 1 self.exploration_decay = 0.995 self.exploration_min",
"Adam class DYNAgent: def __init__(self, state_size, action_size): self.state_size = state_size self.action_size = action_size",
"state_size, action_size): self.state_size = state_size self.action_size = action_size self.memory = deque(maxlen=2000) self.gamma =",
"self.exploration_rate = 1 self.exploration_decay = 0.995 self.exploration_min = 0.01 self.model = self._build_model() def",
"deque import random import numpy as np from collections import deque from keras.models",
"self.action_size = action_size self.memory = deque(maxlen=2000) self.gamma = 0.95 # discount future rewards",
"numpy as np from collections import deque from keras.models import Sequential from keras.layers",
"self.gamma = 0.95 # discount future rewards less self.exploration_rate = 1 self.exploration_decay =",
"action_size): self.state_size = state_size self.action_size = action_size self.memory = deque(maxlen=2000) self.gamma = 0.95",
"DYNAgent: def __init__(self, state_size, action_size): self.state_size = state_size self.action_size = action_size self.memory =",
"__init__(self, state_size, action_size): self.state_size = state_size self.action_size = action_size self.memory = deque(maxlen=2000) self.gamma",
"np from collections import deque from keras.models import Sequential from keras.layers import Dense",
"import Sequential from keras.layers import Dense from keras.optimizers import Adam class DYNAgent: def",
"action_size self.memory = deque(maxlen=2000) self.gamma = 0.95 # discount future rewards less self.exploration_rate",
"discount future rewards less self.exploration_rate = 1 self.exploration_decay = 0.995 self.exploration_min = 0.01",
"# discount future rewards less self.exploration_rate = 1 self.exploration_decay = 0.995 self.exploration_min =",
"= action_size self.memory = deque(maxlen=2000) self.gamma = 0.95 # discount future rewards less",
"= self._build_model() def _build_model(self): model = Sequential() model.add(Dense(24, input_dim=self.state_size, activation='relu')) model.add(Dense(24, activation='relu')) model.add(Dense(self.action_size,",
"model = Sequential() model.add(Dense(24, input_dim=self.state_size, activation='relu')) model.add(Dense(24, activation='relu')) model.add(Dense(self.action_size, activation='linear')) model.compile(loss='mse', optimizer=Adam(lr=self.learning_rate)) return",
"= 0.01 self.model = self._build_model() def _build_model(self): model = Sequential() model.add(Dense(24, input_dim=self.state_size, activation='relu'))",
"Dense from keras.optimizers import Adam class DYNAgent: def __init__(self, state_size, action_size): self.state_size =",
"from keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam class",
"= state_size self.action_size = action_size self.memory = deque(maxlen=2000) self.gamma = 0.95 # discount",
"from keras.layers import Dense from keras.optimizers import Adam class DYNAgent: def __init__(self, state_size,",
"self.exploration_decay = 0.995 self.exploration_min = 0.01 self.model = self._build_model() def _build_model(self): model =",
"import Dense from keras.optimizers import Adam class DYNAgent: def __init__(self, state_size, action_size): self.state_size",
"import random import numpy as np from collections import deque from keras.models import",
"collections import deque from keras.models import Sequential from keras.layers import Dense from keras.optimizers",
"keras.optimizers import Adam class DYNAgent: def __init__(self, state_size, action_size): self.state_size = state_size self.action_size",
"import Adam class DYNAgent: def __init__(self, state_size, action_size): self.state_size = state_size self.action_size =",
"deque(maxlen=2000) self.gamma = 0.95 # discount future rewards less self.exploration_rate = 1 self.exploration_decay",
"= deque(maxlen=2000) self.gamma = 0.95 # discount future rewards less self.exploration_rate = 1",
"= 1 self.exploration_decay = 0.995 self.exploration_min = 0.01 self.model = self._build_model() def _build_model(self):",
"from collections import deque import random import numpy as np from collections import",
"self._build_model() def _build_model(self): model = Sequential() model.add(Dense(24, input_dim=self.state_size, activation='relu')) model.add(Dense(24, activation='relu')) model.add(Dense(self.action_size, activation='linear'))",
"keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam class DYNAgent:",
"class DYNAgent: def __init__(self, state_size, action_size): self.state_size = state_size self.action_size = action_size self.memory",
"as np from collections import deque from keras.models import Sequential from keras.layers import",
"= 0.95 # discount future rewards less self.exploration_rate = 1 self.exploration_decay = 0.995",
"import deque from keras.models import Sequential from keras.layers import Dense from keras.optimizers import",
"keras.layers import Dense from keras.optimizers import Adam class DYNAgent: def __init__(self, state_size, action_size):",
"import numpy as np from collections import deque from keras.models import Sequential from",
"self.model = self._build_model() def _build_model(self): model = Sequential() model.add(Dense(24, input_dim=self.state_size, activation='relu')) model.add(Dense(24, activation='relu'))",
"1 self.exploration_decay = 0.995 self.exploration_min = 0.01 self.model = self._build_model() def _build_model(self): model",
"collections import deque import random import numpy as np from collections import deque",
"self.memory = deque(maxlen=2000) self.gamma = 0.95 # discount future rewards less self.exploration_rate ="
] |
[
"suite for pandas-marc.\"\"\" from pandas_marc import MARCDataFrame def test_instantiate_marcdataframe(dataframe): kwargs = { 'dataframe':",
"value def test_marcdataframe_produces_correct_marc_records(dataframe, records): mdf = MARCDataFrame(dataframe) output = [record.as_marc() for record in",
"replace backslashes in original dataframe with pipes dataframe = dataframe.replace(r'\\\\', '|', regex=True) mdf",
"regex=True) mdf = MARCDataFrame(dataframe, occurrence_delimiter='|') output = [record.as_marc() for record in mdf.records] expected",
"backslashes in original dataframe with pipes dataframe = dataframe.replace(r'\\\\', '|', regex=True) mdf =",
"'occurrence_delimiter': '|', 'subfield_delimiter': '‡' } mdf = MARCDataFrame(**kwargs) for key, value in kwargs.items():",
"MARCDataFrame(dataframe, subfield_delimiter='‡') output = [record.as_marc() for record in mdf.records] expected = [record.as_marc() for",
"for key, value in kwargs.items(): assert getattr(mdf, key) is value def test_marcdataframe_produces_correct_marc_records(dataframe, records):",
"record in records] assert output == expected def test_marcdataframe_with_other_occurrence_delimiter(dataframe, records): # Find and",
"subfield_delimiter='‡') output = [record.as_marc() for record in mdf.records] expected = [record.as_marc() for record",
"= MARCDataFrame(dataframe, occurrence_delimiter='|') output = [record.as_marc() for record in mdf.records] expected = [record.as_marc()",
"pandas-marc.\"\"\" from pandas_marc import MARCDataFrame def test_instantiate_marcdataframe(dataframe): kwargs = { 'dataframe': dataframe, 'occurrence_delimiter':",
"records): mdf = MARCDataFrame(dataframe) output = [record.as_marc() for record in mdf.records] expected =",
"= MARCDataFrame(dataframe, subfield_delimiter='‡') output = [record.as_marc() for record in mdf.records] expected = [record.as_marc()",
"= MARCDataFrame(**kwargs) for key, value in kwargs.items(): assert getattr(mdf, key) is value def",
"dataframe.replace(r'\\$', '‡', regex=True) mdf = MARCDataFrame(dataframe, subfield_delimiter='‡') output = [record.as_marc() for record in",
"records] assert output == expected def test_marcdataframe_with_other_subfield_delimiter(dataframe, records): # Find and replace double",
"MARCDataFrame(**kwargs) for key, value in kwargs.items(): assert getattr(mdf, key) is value def test_marcdataframe_produces_correct_marc_records(dataframe,",
"assert getattr(mdf, key) is value def test_marcdataframe_produces_correct_marc_records(dataframe, records): mdf = MARCDataFrame(dataframe) output =",
"'subfield_delimiter': '‡' } mdf = MARCDataFrame(**kwargs) for key, value in kwargs.items(): assert getattr(mdf,",
"= [record.as_marc() for record in records] assert output == expected def test_marcdataframe_with_other_subfield_delimiter(dataframe, records):",
"daggers in original dataframe with dollar signs dataframe = dataframe.replace(r'\\$', '‡', regex=True) mdf",
"records): # Find and replace backslashes in original dataframe with pipes dataframe =",
"key) is value def test_marcdataframe_produces_correct_marc_records(dataframe, records): mdf = MARCDataFrame(dataframe) output = [record.as_marc() for",
"pipes dataframe = dataframe.replace(r'\\\\', '|', regex=True) mdf = MARCDataFrame(dataframe, occurrence_delimiter='|') output = [record.as_marc()",
"} mdf = MARCDataFrame(**kwargs) for key, value in kwargs.items(): assert getattr(mdf, key) is",
"getattr(mdf, key) is value def test_marcdataframe_produces_correct_marc_records(dataframe, records): mdf = MARCDataFrame(dataframe) output = [record.as_marc()",
"== expected def test_marcdataframe_with_other_subfield_delimiter(dataframe, records): # Find and replace double daggers in original",
"value in kwargs.items(): assert getattr(mdf, key) is value def test_marcdataframe_produces_correct_marc_records(dataframe, records): mdf =",
"output = [record.as_marc() for record in mdf.records] expected = [record.as_marc() for record in",
"mdf = MARCDataFrame(dataframe, occurrence_delimiter='|') output = [record.as_marc() for record in mdf.records] expected =",
"in original dataframe with dollar signs dataframe = dataframe.replace(r'\\$', '‡', regex=True) mdf =",
"python3 \"\"\"Test suite for pandas-marc.\"\"\" from pandas_marc import MARCDataFrame def test_instantiate_marcdataframe(dataframe): kwargs =",
"in records] assert output == expected def test_marcdataframe_with_other_subfield_delimiter(dataframe, records): # Find and replace",
"kwargs.items(): assert getattr(mdf, key) is value def test_marcdataframe_produces_correct_marc_records(dataframe, records): mdf = MARCDataFrame(dataframe) output",
"test_marcdataframe_with_other_occurrence_delimiter(dataframe, records): # Find and replace backslashes in original dataframe with pipes dataframe",
"MARCDataFrame(dataframe) output = [record.as_marc() for record in mdf.records] expected = [record.as_marc() for record",
"mdf = MARCDataFrame(**kwargs) for key, value in kwargs.items(): assert getattr(mdf, key) is value",
"and replace backslashes in original dataframe with pipes dataframe = dataframe.replace(r'\\\\', '|', regex=True)",
"is value def test_marcdataframe_produces_correct_marc_records(dataframe, records): mdf = MARCDataFrame(dataframe) output = [record.as_marc() for record",
"dollar signs dataframe = dataframe.replace(r'\\$', '‡', regex=True) mdf = MARCDataFrame(dataframe, subfield_delimiter='‡') output =",
"kwargs = { 'dataframe': dataframe, 'occurrence_delimiter': '|', 'subfield_delimiter': '‡' } mdf = MARCDataFrame(**kwargs)",
"record in records] assert output == expected def test_marcdataframe_with_other_subfield_delimiter(dataframe, records): # Find and",
"test_instantiate_marcdataframe(dataframe): kwargs = { 'dataframe': dataframe, 'occurrence_delimiter': '|', 'subfield_delimiter': '‡' } mdf =",
"= [record.as_marc() for record in records] assert output == expected def test_marcdataframe_with_other_occurrence_delimiter(dataframe, records):",
"in records] assert output == expected def test_marcdataframe_with_other_occurrence_delimiter(dataframe, records): # Find and replace",
"# Find and replace double daggers in original dataframe with dollar signs dataframe",
"original dataframe with dollar signs dataframe = dataframe.replace(r'\\$', '‡', regex=True) mdf = MARCDataFrame(dataframe,",
"expected = [record.as_marc() for record in records] assert output == expected def test_marcdataframe_with_other_occurrence_delimiter(dataframe,",
"mdf = MARCDataFrame(dataframe, subfield_delimiter='‡') output = [record.as_marc() for record in mdf.records] expected =",
"in kwargs.items(): assert getattr(mdf, key) is value def test_marcdataframe_produces_correct_marc_records(dataframe, records): mdf = MARCDataFrame(dataframe)",
"replace double daggers in original dataframe with dollar signs dataframe = dataframe.replace(r'\\$', '‡',",
"expected def test_marcdataframe_with_other_occurrence_delimiter(dataframe, records): # Find and replace backslashes in original dataframe with",
"test_marcdataframe_produces_correct_marc_records(dataframe, records): mdf = MARCDataFrame(dataframe) output = [record.as_marc() for record in mdf.records] expected",
"for record in records] assert output == expected def test_marcdataframe_with_other_subfield_delimiter(dataframe, records): # Find",
"'|', 'subfield_delimiter': '‡' } mdf = MARCDataFrame(**kwargs) for key, value in kwargs.items(): assert",
"dataframe = dataframe.replace(r'\\\\', '|', regex=True) mdf = MARCDataFrame(dataframe, occurrence_delimiter='|') output = [record.as_marc() for",
"def test_marcdataframe_with_other_occurrence_delimiter(dataframe, records): # Find and replace backslashes in original dataframe with pipes",
"[record.as_marc() for record in records] assert output == expected def test_marcdataframe_with_other_subfield_delimiter(dataframe, records): #",
"{ 'dataframe': dataframe, 'occurrence_delimiter': '|', 'subfield_delimiter': '‡' } mdf = MARCDataFrame(**kwargs) for key,",
"from pandas_marc import MARCDataFrame def test_instantiate_marcdataframe(dataframe): kwargs = { 'dataframe': dataframe, 'occurrence_delimiter': '|',",
"occurrence_delimiter='|') output = [record.as_marc() for record in mdf.records] expected = [record.as_marc() for record",
"in mdf.records] expected = [record.as_marc() for record in records] assert output == expected",
"[record.as_marc() for record in mdf.records] expected = [record.as_marc() for record in records] assert",
"dataframe = dataframe.replace(r'\\$', '‡', regex=True) mdf = MARCDataFrame(dataframe, subfield_delimiter='‡') output = [record.as_marc() for",
"records] assert output == expected def test_marcdataframe_with_other_occurrence_delimiter(dataframe, records): # Find and replace backslashes",
"and replace double daggers in original dataframe with dollar signs dataframe = dataframe.replace(r'\\$',",
"import MARCDataFrame def test_instantiate_marcdataframe(dataframe): kwargs = { 'dataframe': dataframe, 'occurrence_delimiter': '|', 'subfield_delimiter': '‡'",
"MARCDataFrame def test_instantiate_marcdataframe(dataframe): kwargs = { 'dataframe': dataframe, 'occurrence_delimiter': '|', 'subfield_delimiter': '‡' }",
"double daggers in original dataframe with dollar signs dataframe = dataframe.replace(r'\\$', '‡', regex=True)",
"= dataframe.replace(r'\\\\', '|', regex=True) mdf = MARCDataFrame(dataframe, occurrence_delimiter='|') output = [record.as_marc() for record",
"mdf.records] expected = [record.as_marc() for record in records] assert output == expected def",
"dataframe, 'occurrence_delimiter': '|', 'subfield_delimiter': '‡' } mdf = MARCDataFrame(**kwargs) for key, value in",
"for record in mdf.records] expected = [record.as_marc() for record in records] assert output",
"== expected def test_marcdataframe_with_other_occurrence_delimiter(dataframe, records): # Find and replace backslashes in original dataframe",
"'‡', regex=True) mdf = MARCDataFrame(dataframe, subfield_delimiter='‡') output = [record.as_marc() for record in mdf.records]",
"= [record.as_marc() for record in mdf.records] expected = [record.as_marc() for record in records]",
"with pipes dataframe = dataframe.replace(r'\\\\', '|', regex=True) mdf = MARCDataFrame(dataframe, occurrence_delimiter='|') output =",
"signs dataframe = dataframe.replace(r'\\$', '‡', regex=True) mdf = MARCDataFrame(dataframe, subfield_delimiter='‡') output = [record.as_marc()",
"for record in records] assert output == expected def test_marcdataframe_with_other_occurrence_delimiter(dataframe, records): # Find",
"mdf = MARCDataFrame(dataframe) output = [record.as_marc() for record in mdf.records] expected = [record.as_marc()",
"'dataframe': dataframe, 'occurrence_delimiter': '|', 'subfield_delimiter': '‡' } mdf = MARCDataFrame(**kwargs) for key, value",
"#!/usr/bin/env python3 \"\"\"Test suite for pandas-marc.\"\"\" from pandas_marc import MARCDataFrame def test_instantiate_marcdataframe(dataframe): kwargs",
"record in mdf.records] expected = [record.as_marc() for record in records] assert output ==",
"regex=True) mdf = MARCDataFrame(dataframe, subfield_delimiter='‡') output = [record.as_marc() for record in mdf.records] expected",
"# Find and replace backslashes in original dataframe with pipes dataframe = dataframe.replace(r'\\\\',",
"dataframe with pipes dataframe = dataframe.replace(r'\\\\', '|', regex=True) mdf = MARCDataFrame(dataframe, occurrence_delimiter='|') output",
"'|', regex=True) mdf = MARCDataFrame(dataframe, occurrence_delimiter='|') output = [record.as_marc() for record in mdf.records]",
"with dollar signs dataframe = dataframe.replace(r'\\$', '‡', regex=True) mdf = MARCDataFrame(dataframe, subfield_delimiter='‡') output",
"output == expected def test_marcdataframe_with_other_occurrence_delimiter(dataframe, records): # Find and replace backslashes in original",
"dataframe.replace(r'\\\\', '|', regex=True) mdf = MARCDataFrame(dataframe, occurrence_delimiter='|') output = [record.as_marc() for record in",
"records): # Find and replace double daggers in original dataframe with dollar signs",
"pandas_marc import MARCDataFrame def test_instantiate_marcdataframe(dataframe): kwargs = { 'dataframe': dataframe, 'occurrence_delimiter': '|', 'subfield_delimiter':",
"key, value in kwargs.items(): assert getattr(mdf, key) is value def test_marcdataframe_produces_correct_marc_records(dataframe, records): mdf",
"def test_instantiate_marcdataframe(dataframe): kwargs = { 'dataframe': dataframe, 'occurrence_delimiter': '|', 'subfield_delimiter': '‡' } mdf",
"original dataframe with pipes dataframe = dataframe.replace(r'\\\\', '|', regex=True) mdf = MARCDataFrame(dataframe, occurrence_delimiter='|')",
"output == expected def test_marcdataframe_with_other_subfield_delimiter(dataframe, records): # Find and replace double daggers in",
"dataframe with dollar signs dataframe = dataframe.replace(r'\\$', '‡', regex=True) mdf = MARCDataFrame(dataframe, subfield_delimiter='‡')",
"MARCDataFrame(dataframe, occurrence_delimiter='|') output = [record.as_marc() for record in mdf.records] expected = [record.as_marc() for",
"in original dataframe with pipes dataframe = dataframe.replace(r'\\\\', '|', regex=True) mdf = MARCDataFrame(dataframe,",
"= dataframe.replace(r'\\$', '‡', regex=True) mdf = MARCDataFrame(dataframe, subfield_delimiter='‡') output = [record.as_marc() for record",
"for pandas-marc.\"\"\" from pandas_marc import MARCDataFrame def test_instantiate_marcdataframe(dataframe): kwargs = { 'dataframe': dataframe,",
"test_marcdataframe_with_other_subfield_delimiter(dataframe, records): # Find and replace double daggers in original dataframe with dollar",
"def test_marcdataframe_with_other_subfield_delimiter(dataframe, records): # Find and replace double daggers in original dataframe with",
"Find and replace double daggers in original dataframe with dollar signs dataframe =",
"= MARCDataFrame(dataframe) output = [record.as_marc() for record in mdf.records] expected = [record.as_marc() for",
"expected def test_marcdataframe_with_other_subfield_delimiter(dataframe, records): # Find and replace double daggers in original dataframe",
"'‡' } mdf = MARCDataFrame(**kwargs) for key, value in kwargs.items(): assert getattr(mdf, key)",
"[record.as_marc() for record in records] assert output == expected def test_marcdataframe_with_other_occurrence_delimiter(dataframe, records): #",
"\"\"\"Test suite for pandas-marc.\"\"\" from pandas_marc import MARCDataFrame def test_instantiate_marcdataframe(dataframe): kwargs = {",
"assert output == expected def test_marcdataframe_with_other_occurrence_delimiter(dataframe, records): # Find and replace backslashes in",
"expected = [record.as_marc() for record in records] assert output == expected def test_marcdataframe_with_other_subfield_delimiter(dataframe,",
"= { 'dataframe': dataframe, 'occurrence_delimiter': '|', 'subfield_delimiter': '‡' } mdf = MARCDataFrame(**kwargs) for",
"def test_marcdataframe_produces_correct_marc_records(dataframe, records): mdf = MARCDataFrame(dataframe) output = [record.as_marc() for record in mdf.records]",
"assert output == expected def test_marcdataframe_with_other_subfield_delimiter(dataframe, records): # Find and replace double daggers",
"Find and replace backslashes in original dataframe with pipes dataframe = dataframe.replace(r'\\\\', '|',"
] |