ngram
listlengths
0
67.8k
[]
[ "print(output) except Exception as e: print(f\"Error: {e}\\n\") raise except KeyboardInterrupt: print (\"Ctrl+C Pressed.", "cve_list = get_unprocessed_cves(WATCH_DIR) if len(cve_list) == 0: sys.exit() batches = process_cves(cve_list) # Assumes", "as error: print(f\"Error: Could not open a CSV. {error}\") print(f\"Found {len(cve_files)} file(s) to", "if response['id']: uploaded_batches[response['id']] = response upload_output = ( \"==============================\\n\" f\"BATCH ID: {response['id']}\\n\" f\"{response['source']}", "requests.request(\"POST\", url, headers=headers, files=files) response_data = response.json() if \"errors\" in response_data and len(response_data['errors'])", "{} task = \"patch\" url = f\"https://console.automox.com/api/orgs/{organization}/tasks/{task}/batches/upload\" filename = os.path.basename(file.name) try: headers =", "of CSV files to upload and process. Args: directory (str): Directory to look", "done processing!\") for batch_id, batch in batches.items(): output = ( \"==============================\\n\" f\"BATCH ID:", "Exception(msg) uploaded_batches[batch_id] = response_data except (requests.RequestException, Exception) as error: print(f\"Error: Unable to update", "\"awaiting_approval\": batches_complete = False time.sleep(10) print(\"Batches are done processing!\") for batch_id, batch in", "print(upload_output) path = os.path.realpath(file.name) directory = os.path.dirname(path) filename = os.path.basename(file.name) new_path = f\"{directory}/processed/{filename}\"", "headers=headers, files=files) response_data = response.json() if \"errors\" in response_data and len(response_data['errors']) > 0:", "the Automox API for the status of batches contained in this dictionary. When", "files to upload and process. Args: directory (str): Directory to look in for", "os import sys import time from getpass import getpass from io import FileIO", "the status of batches contained in this dictionary. When CSV files containing CVE", "still building... Checking for updates...\") batches = update_batches(batches) for batch_id, batch in batches.items():", "files containing CVE information is uploaded to the Automox Vulnerability Sync API, a", "to process. Returns: uploaded_batches (dict): Dictionary of batch ids correlated to API batch", "requests def upload_cve(file: FileIO) -> dict: \"\"\" Uploads vulnerability list to Automox Vulnerability", "\"patch\" url = f\"https://console.automox.com/api/orgs/{organization}/tasks/{task}/batches/upload\" filename = os.path.basename(file.name) try: headers = { \"Authorization\": f\"Bearer", "Exception as e: print(f\"Error: {e}\\n\") raise except KeyboardInterrupt: print (\"Ctrl+C Pressed. Shutting down.\")", "(dict): A dictionary of the latest responses from the Automox API about the", "been uploaded.\\n\" \"==============================\" ) print(upload_output) path = os.path.realpath(file.name) directory = os.path.dirname(path) filename =", "{new_path}\\n\") os.rename(path, new_path) except OSError as error: print(f\"Error processing CVE: {error}\") return uploaded_batches", "not open a CSV. {error}\") print(f\"Found {len(cve_files)} file(s) to upload.\") return cve_files def", "cve_files (list): List of files to be processed and uploaded. \"\"\" cve_files =", "\"\"\"Use case for automating the ingestion of CVE reports\"\"\" import glob import os", "new_path) except OSError as error: print(f\"Error processing CVE: {error}\") return uploaded_batches def update_batches(uploaded_batches:", "the Automox API about the status of a batch. Returns: uploaded_batches (dict): An", "CSV upload request. ({error})\") return response_data def get_unprocessed_cves(directory: str) -> list: \"\"\"Returns a", "vulnerability data. Returns: response_data (dict): API response from Automox Vulnerability Sync https://developer.automox.com/openapi/vulnsync/operation/UploadCSVBatch/ \"\"\"", "return uploaded_batches try: # Directory to watch for new CVE CSVs WATCH_DIR =", "def process_cves(unprocessed_cve_list: list) -> dict: \"\"\"Handles uploading and moving the CSV file to", "\"\" msg = msg.join(response_data['errors']) raise Exception(msg) uploaded_batches[batch_id] = response_data except (requests.RequestException, Exception) as", "uploaded_batches (dict): A dictionary of the latest responses from the Automox API about", "upload responses. \"\"\" uploaded_batches = {} for file in unprocessed_cve_list: try: # Make", "or input(\"Enter your Organization ID: \") cve_list = get_unprocessed_cves(WATCH_DIR) if len(cve_list) == 0:", "CSV files containing CVE information is uploaded to the Automox Vulnerability Sync API,", "os.getenv(\"WATCH_DIR\") or \"./cve_queue\" # Prompt for inputs api_secret = os.getenv('AUTOMOX_API_KEY') or getpass('Enter your", "= { \"Authorization\": f\"Bearer {api_secret}\", } files = [ ('file', (filename, file, 'text/csv'))", "FileIO) -> dict: \"\"\" Uploads vulnerability list to Automox Vulnerability Sync endpoint. Args:", "(str): Directory to look in for CSVs. Returns: cve_files (list): List of files", "of batches contained in this dictionary. When CSV files containing CVE information is", "this dictionary. When CSV files containing CVE information is uploaded to the Automox", "paths: try: cve_file = open(path, \"rb\") cve_files.append(cve_file) except (OSError, IOError) as error: print(f\"Error:", "Could not open a CSV. {error}\") print(f\"Found {len(cve_files)} file(s) to upload.\") return cve_files", "# Assumes the batches have not been built upon receipt. batches_complete = len(batches)", "Make the request to upload the batch file print(f\"Sending {os.path.basename(file.name)} to Automox Vulnerability", "dictionary. When CSV files containing CVE information is uploaded to the Automox Vulnerability", "Assumes the batches have not been built upon receipt. batches_complete = len(batches) ==", "updated dictionary of the latest responses from the Automox API about the status", "{batch['task_count']}\\n\" f\"Batch Issues: {batch['issue_count']}\\n\" f\"Unknown Hosts: {batch['unknown_host_count']}\\n\" \"==============================\" ) print(output) except Exception as", "0: sys.exit() batches = process_cves(cve_list) # Assumes the batches have not been built", "in response_data and len(response_data['errors']) > 0: msg = \"\" msg = msg.join(response_data['errors']) raise", "] response = requests.request(\"POST\", url, headers=headers, files=files) response_data = response.json() if \"errors\" in", "= os.path.basename(file.name) new_path = f\"{directory}/processed/{filename}\" print(f\"Moving {filename} to {new_path}\\n\") os.rename(path, new_path) except OSError", "file(s) to upload.\") return cve_files def process_cves(unprocessed_cve_list: list) -> dict: \"\"\"Handles uploading and", "correlated to API batch upload responses. \"\"\" uploaded_batches = {} for file in", "print(f\"Moving {filename} to {new_path}\\n\") os.rename(path, new_path) except OSError as error: print(f\"Error processing CVE:", "uploaded to the Automox Vulnerability Sync API, a task list is built Args:", "get_unprocessed_cves(directory: str) -> list: \"\"\"Returns a list of CSV files to upload and", "batches have not been built upon receipt. batches_complete = len(batches) == 0 while", "Checking for updates...\") batches = update_batches(batches) for batch_id, batch in batches.items(): batches_complete =", "uploaded. \"\"\" cve_files = [] paths = glob.glob(f\"{directory}/*.csv\") for path in paths: try:", "({error})\") return uploaded_batches try: # Directory to watch for new CVE CSVs WATCH_DIR", "= os.getenv('AUTOMOX_ORGANIZATION_ID') or input(\"Enter your Organization ID: \") cve_list = get_unprocessed_cves(WATCH_DIR) if len(cve_list)", "return response_data def get_unprocessed_cves(directory: str) -> list: \"\"\"Returns a list of CSV files", "') organization = os.getenv('AUTOMOX_ORGANIZATION_ID') or input(\"Enter your Organization ID: \") cve_list = get_unprocessed_cves(WATCH_DIR)", "False time.sleep(10) print(\"Batches are done processing!\") for batch_id, batch in batches.items(): output =", "batches contained in this dictionary. When CSV files containing CVE information is uploaded", "is uploaded to the Automox Vulnerability Sync API, a task list is built", "error: print(f\"Error: Unable to complete CSV upload request. ({error})\") return response_data def get_unprocessed_cves(directory:", "CSV file containing vulnerability data. Returns: response_data (dict): API response from Automox Vulnerability", "[] paths = glob.glob(f\"{directory}/*.csv\") for path in paths: try: cve_file = open(path, \"rb\")", "update_batches(batches) for batch_id, batch in batches.items(): batches_complete = True if not batches[batch_id]['status'] ==", "batches.items(): output = ( \"==============================\\n\" f\"BATCH ID: {batch['id']}\\n\" f\"{batch['source']} has been processed.\\n\" f\"Total", "\"\"\" Uploads vulnerability list to Automox Vulnerability Sync endpoint. Args: file (FileIO): A", "to update batch {batch_id} status. ({error})\") return uploaded_batches try: # Directory to watch", "print(f\"Error processing CVE: {error}\") return uploaded_batches def update_batches(uploaded_batches: dict) -> dict: \"\"\"Polls the", "cve_files = [] paths = glob.glob(f\"{directory}/*.csv\") for path in paths: try: cve_file =", "the ingestion of CVE reports\"\"\" import glob import os import sys import time", "\"\"\" cve_files = [] paths = glob.glob(f\"{directory}/*.csv\") for path in paths: try: cve_file", "Sync...\") response = upload_cve(file) if response['id']: uploaded_batches[response['id']] = response upload_output = ( \"==============================\\n\"", "new_path = f\"{directory}/processed/{filename}\" print(f\"Moving {filename} to {new_path}\\n\") os.rename(path, new_path) except OSError as error:", "os.path.basename(file.name) new_path = f\"{directory}/processed/{filename}\" print(f\"Moving {filename} to {new_path}\\n\") os.rename(path, new_path) except OSError as", "# Prompt for inputs api_secret = os.getenv('AUTOMOX_API_KEY') or getpass('Enter your API Key: ')", "f\"BATCH ID: {response['id']}\\n\" f\"{response['source']} has been uploaded.\\n\" \"==============================\" ) print(upload_output) path = os.path.realpath(file.name)", "Organization ID: \") cve_list = get_unprocessed_cves(WATCH_DIR) if len(cve_list) == 0: sys.exit() batches =", "to upload.\") return cve_files def process_cves(unprocessed_cve_list: list) -> dict: \"\"\"Handles uploading and moving", "try: if batch['status'] != \"awaiting_approval\": headers = { \"Authorization\": f\"Bearer {api_secret}\", } response", "os.getenv('AUTOMOX_API_KEY') or getpass('Enter your API Key: ') organization = os.getenv('AUTOMOX_ORGANIZATION_ID') or input(\"Enter your", "latest responses from the Automox API about the status of a batch. \"\"\"", "response.json() if \"errors\" in response_data and len(response_data['errors']) > 0: msg = \"\" msg", "to {new_path}\\n\") os.rename(path, new_path) except OSError as error: print(f\"Error processing CVE: {error}\") return", "getpass('Enter your API Key: ') organization = os.getenv('AUTOMOX_ORGANIZATION_ID') or input(\"Enter your Organization ID:", "file containing vulnerability data. Returns: response_data (dict): API response from Automox Vulnerability Sync", "as error: print(f\"Error: Unable to update batch {batch_id} status. ({error})\") return uploaded_batches try:", "not been built upon receipt. batches_complete = len(batches) == 0 while not batches_complete:", "upload.\") return cve_files def process_cves(unprocessed_cve_list: list) -> dict: \"\"\"Handles uploading and moving the", "if batch['status'] != \"awaiting_approval\": headers = { \"Authorization\": f\"Bearer {api_secret}\", } response =", "response = requests.get(f\"https://console.automox.com/api/orgs/{organization}/tasks/batches/{batch['id']}\", headers=headers) response_data = response.json() if \"errors\" in response_data and len(response_data['errors'])", "= False time.sleep(10) print(\"Batches are done processing!\") for batch_id, batch in batches.items(): output", "Args: uploaded_batches (dict): A dictionary of the latest responses from the Automox API", "\"==============================\" ) print(upload_output) path = os.path.realpath(file.name) directory = os.path.dirname(path) filename = os.path.basename(file.name) new_path", "{batch_id} status. ({error})\") return uploaded_batches try: # Directory to watch for new CVE", "list: \"\"\"Returns a list of CSV files to upload and process. Args: directory", "batches_complete = True if not batches[batch_id]['status'] == \"awaiting_approval\": batches_complete = False time.sleep(10) print(\"Batches", "-> dict: \"\"\" Uploads vulnerability list to Automox Vulnerability Sync endpoint. Args: file", "request. ({error})\") return response_data def get_unprocessed_cves(directory: str) -> list: \"\"\"Returns a list of", "Vulnerabilities: {batch['cve_count']}\\n\" f\"Devices Impacted: {batch['impacted_device_count']}\\n\" f\"Tasks Pending Creation: {batch['task_count']}\\n\" f\"Batch Issues: {batch['issue_count']}\\n\" f\"Unknown", "files=files) response_data = response.json() if \"errors\" in response_data and len(response_data['errors']) > 0: msg", "{} for file in unprocessed_cve_list: try: # Make the request to upload the", "uploaded_batches try: # Directory to watch for new CVE CSVs WATCH_DIR = os.getenv(\"WATCH_DIR\")", "batches_complete = False time.sleep(10) print(\"Batches are done processing!\") for batch_id, batch in batches.items():", "path in paths: try: cve_file = open(path, \"rb\") cve_files.append(cve_file) except (OSError, IOError) as", "{filename} to {new_path}\\n\") os.rename(path, new_path) except OSError as error: print(f\"Error processing CVE: {error}\")", "print(f\"Error: Unable to update batch {batch_id} status. ({error})\") return uploaded_batches try: # Directory", "ID: {batch['id']}\\n\" f\"{batch['source']} has been processed.\\n\" f\"Total Vulnerabilities: {batch['cve_count']}\\n\" f\"Devices Impacted: {batch['impacted_device_count']}\\n\" f\"Tasks", "Returns: response_data (dict): API response from Automox Vulnerability Sync https://developer.automox.com/openapi/vulnsync/operation/UploadCSVBatch/ \"\"\" response_data =", "to complete CSV upload request. ({error})\") return response_data def get_unprocessed_cves(directory: str) -> list:", "({error})\") return response_data def get_unprocessed_cves(directory: str) -> list: \"\"\"Returns a list of CSV", "str) -> list: \"\"\"Returns a list of CSV files to upload and process.", "CVE reports\"\"\" import glob import os import sys import time from getpass import", "contained in this dictionary. When CSV files containing CVE information is uploaded to", "been built upon receipt. batches_complete = len(batches) == 0 while not batches_complete: print(\"Batches", "ID: \") cve_list = get_unprocessed_cves(WATCH_DIR) if len(cve_list) == 0: sys.exit() batches = process_cves(cve_list)", "for CSVs. Returns: cve_files (list): List of files to be processed and uploaded.", "batch ids correlated to API batch upload responses. \"\"\" uploaded_batches = {} for", "api_secret = os.getenv('AUTOMOX_API_KEY') or getpass('Enter your API Key: ') organization = os.getenv('AUTOMOX_ORGANIZATION_ID') or", "filename = os.path.basename(file.name) new_path = f\"{directory}/processed/{filename}\" print(f\"Moving {filename} to {new_path}\\n\") os.rename(path, new_path) except", "os.getenv('AUTOMOX_ORGANIZATION_ID') or input(\"Enter your Organization ID: \") cve_list = get_unprocessed_cves(WATCH_DIR) if len(cve_list) ==", "been processed.\\n\" f\"Total Vulnerabilities: {batch['cve_count']}\\n\" f\"Devices Impacted: {batch['impacted_device_count']}\\n\" f\"Tasks Pending Creation: {batch['task_count']}\\n\" f\"Batch", "Sync endpoint. Args: file (FileIO): A CSV file containing vulnerability data. Returns: response_data", "Dictionary of batch ids correlated to API batch upload responses. \"\"\" uploaded_batches =", "of the latest responses from the Automox API about the status of a", "directory = os.path.dirname(path) filename = os.path.basename(file.name) new_path = f\"{directory}/processed/{filename}\" print(f\"Moving {filename} to {new_path}\\n\")", "f\"Unknown Hosts: {batch['unknown_host_count']}\\n\" \"==============================\" ) print(output) except Exception as e: print(f\"Error: {e}\\n\") raise", "print(f\"Error: Could not open a CSV. {error}\") print(f\"Found {len(cve_files)} file(s) to upload.\") return", "batches_complete = len(batches) == 0 while not batches_complete: print(\"Batches are still building... Checking", "batches[batch_id]['status'] == \"awaiting_approval\": batches_complete = False time.sleep(10) print(\"Batches are done processing!\") for batch_id,", "responses from the Automox API about the status of a batch. \"\"\" for", "moving the CSV file to the processed directory. Args: unprocessed_cve_list (list): List of", "batch in batches.items(): output = ( \"==============================\\n\" f\"BATCH ID: {batch['id']}\\n\" f\"{batch['source']} has been", "Unable to complete CSV upload request. ({error})\") return response_data def get_unprocessed_cves(directory: str) ->", "headers = { \"Authorization\": f\"Bearer {api_secret}\", } files = [ ('file', (filename, file,", "cve_files.append(cve_file) except (OSError, IOError) as error: print(f\"Error: Could not open a CSV. {error}\")", "raise Exception(msg) uploaded_batches[batch_id] = response_data except (requests.RequestException, Exception) as error: print(f\"Error: Unable to", "information is uploaded to the Automox Vulnerability Sync API, a task list is", "getpass from io import FileIO import requests def upload_cve(file: FileIO) -> dict: \"\"\"", "url, headers=headers, files=files) response_data = response.json() if \"errors\" in response_data and len(response_data['errors']) >", "upload_output = ( \"==============================\\n\" f\"BATCH ID: {response['id']}\\n\" f\"{response['source']} has been uploaded.\\n\" \"==============================\" )", "error: print(f\"Error: Unable to update batch {batch_id} status. ({error})\") return uploaded_batches try: #", "= f\"{directory}/processed/{filename}\" print(f\"Moving {filename} to {new_path}\\n\") os.rename(path, new_path) except OSError as error: print(f\"Error", "import sys import time from getpass import getpass from io import FileIO import", "endpoint. Args: file (FileIO): A CSV file containing vulnerability data. Returns: response_data (dict):", "dict: \"\"\" Uploads vulnerability list to Automox Vulnerability Sync endpoint. Args: file (FileIO):", "and len(response_data['errors']) > 0: msg = \"\" msg = msg.join(response_data['errors']) raise Exception(msg) uploaded_batches[batch_id]", "msg = \"\" msg = msg.join(response_data['errors']) raise Exception(msg) uploaded_batches[batch_id] = response_data except (requests.RequestException,", "print(f\"Error: Unable to complete CSV upload request. ({error})\") return response_data def get_unprocessed_cves(directory: str)", "file in unprocessed_cve_list: try: # Make the request to upload the batch file", "Impacted: {batch['impacted_device_count']}\\n\" f\"Tasks Pending Creation: {batch['task_count']}\\n\" f\"Batch Issues: {batch['issue_count']}\\n\" f\"Unknown Hosts: {batch['unknown_host_count']}\\n\" \"==============================\"", "def update_batches(uploaded_batches: dict) -> dict: \"\"\"Polls the Automox API for the status of", "open(path, \"rb\") cve_files.append(cve_file) except (OSError, IOError) as error: print(f\"Error: Could not open a", "== 0 while not batches_complete: print(\"Batches are still building... Checking for updates...\") batches", "of batch ids correlated to API batch upload responses. \"\"\" uploaded_batches = {}", "cve_file = open(path, \"rb\") cve_files.append(cve_file) except (OSError, IOError) as error: print(f\"Error: Could not", "Automox Vulnerability Sync https://developer.automox.com/openapi/vulnsync/operation/UploadCSVBatch/ \"\"\" response_data = {} task = \"patch\" url =", "= os.path.basename(file.name) try: headers = { \"Authorization\": f\"Bearer {api_secret}\", } files = [", "msg = \"\" msg = msg.join(response_data['errors']) raise Exception(msg) except (requests.RequestException, Exception) as error:", "path = os.path.realpath(file.name) directory = os.path.dirname(path) filename = os.path.basename(file.name) new_path = f\"{directory}/processed/{filename}\" print(f\"Moving", "Prompt for inputs api_secret = os.getenv('AUTOMOX_API_KEY') or getpass('Enter your API Key: ') organization", "to the processed directory. Args: unprocessed_cve_list (list): List of files to process. Returns:", "glob import os import sys import time from getpass import getpass from io", "glob.glob(f\"{directory}/*.csv\") for path in paths: try: cve_file = open(path, \"rb\") cve_files.append(cve_file) except (OSError,", "unprocessed_cve_list (list): List of files to process. Returns: uploaded_batches (dict): Dictionary of batch", "process_cves(unprocessed_cve_list: list) -> dict: \"\"\"Handles uploading and moving the CSV file to the", "Vulnerability Sync...\") response = upload_cve(file) if response['id']: uploaded_batches[response['id']] = response upload_output = (", "response = upload_cve(file) if response['id']: uploaded_batches[response['id']] = response upload_output = ( \"==============================\\n\" f\"BATCH", "automating the ingestion of CVE reports\"\"\" import glob import os import sys import", "except (requests.RequestException, Exception) as error: print(f\"Error: Unable to update batch {batch_id} status. ({error})\")", "A CSV file containing vulnerability data. Returns: response_data (dict): API response from Automox", "(dict): API response from Automox Vulnerability Sync https://developer.automox.com/openapi/vulnsync/operation/UploadCSVBatch/ \"\"\" response_data = {} task", "paths = glob.glob(f\"{directory}/*.csv\") for path in paths: try: cve_file = open(path, \"rb\") cve_files.append(cve_file)", "0: msg = \"\" msg = msg.join(response_data['errors']) raise Exception(msg) except (requests.RequestException, Exception) as", "When CSV files containing CVE information is uploaded to the Automox Vulnerability Sync", "= {} task = \"patch\" url = f\"https://console.automox.com/api/orgs/{organization}/tasks/{task}/batches/upload\" filename = os.path.basename(file.name) try: headers", "for batch_id, batch in batches.items(): output = ( \"==============================\\n\" f\"BATCH ID: {batch['id']}\\n\" f\"{batch['source']}", "a batch. \"\"\" for batch_id, batch in uploaded_batches.items(): try: if batch['status'] != \"awaiting_approval\":", "for batch_id, batch in uploaded_batches.items(): try: if batch['status'] != \"awaiting_approval\": headers = {", "status. ({error})\") return uploaded_batches try: # Directory to watch for new CVE CSVs", "new CVE CSVs WATCH_DIR = os.getenv(\"WATCH_DIR\") or \"./cve_queue\" # Prompt for inputs api_secret", "\"awaiting_approval\": headers = { \"Authorization\": f\"Bearer {api_secret}\", } response = requests.get(f\"https://console.automox.com/api/orgs/{organization}/tasks/batches/{batch['id']}\", headers=headers) response_data", "batches.items(): batches_complete = True if not batches[batch_id]['status'] == \"awaiting_approval\": batches_complete = False time.sleep(10)", "error: print(f\"Error: Could not open a CSV. {error}\") print(f\"Found {len(cve_files)} file(s) to upload.\")", "response from Automox Vulnerability Sync https://developer.automox.com/openapi/vulnsync/operation/UploadCSVBatch/ \"\"\" response_data = {} task = \"patch\"", "= [ ('file', (filename, file, 'text/csv')) ] response = requests.request(\"POST\", url, headers=headers, files=files)", "list) -> dict: \"\"\"Handles uploading and moving the CSV file to the processed", "receipt. batches_complete = len(batches) == 0 while not batches_complete: print(\"Batches are still building...", "{batch['id']}\\n\" f\"{batch['source']} has been processed.\\n\" f\"Total Vulnerabilities: {batch['cve_count']}\\n\" f\"Devices Impacted: {batch['impacted_device_count']}\\n\" f\"Tasks Pending", "your Organization ID: \") cve_list = get_unprocessed_cves(WATCH_DIR) if len(cve_list) == 0: sys.exit() batches", "uploaded_batches[batch_id] = response_data except (requests.RequestException, Exception) as error: print(f\"Error: Unable to update batch", "is built Args: uploaded_batches (dict): A dictionary of the latest responses from the", "Sync API, a task list is built Args: uploaded_batches (dict): A dictionary of", "uploaded.\\n\" \"==============================\" ) print(upload_output) path = os.path.realpath(file.name) directory = os.path.dirname(path) filename = os.path.basename(file.name)", "upload_cve(file: FileIO) -> dict: \"\"\" Uploads vulnerability list to Automox Vulnerability Sync endpoint.", "batch. \"\"\" for batch_id, batch in uploaded_batches.items(): try: if batch['status'] != \"awaiting_approval\": headers", "len(batches) == 0 while not batches_complete: print(\"Batches are still building... Checking for updates...\")", "== \"awaiting_approval\": batches_complete = False time.sleep(10) print(\"Batches are done processing!\") for batch_id, batch", "to the Automox Vulnerability Sync API, a task list is built Args: uploaded_batches", "process. Returns: uploaded_batches (dict): Dictionary of batch ids correlated to API batch upload", "batches = process_cves(cve_list) # Assumes the batches have not been built upon receipt.", "a list of CSV files to upload and process. Args: directory (str): Directory", "Key: ') organization = os.getenv('AUTOMOX_ORGANIZATION_ID') or input(\"Enter your Organization ID: \") cve_list =", "(list): List of files to process. Returns: uploaded_batches (dict): Dictionary of batch ids", "case for automating the ingestion of CVE reports\"\"\" import glob import os import", "print(f\"Found {len(cve_files)} file(s) to upload.\") return cve_files def process_cves(unprocessed_cve_list: list) -> dict: \"\"\"Handles", "Args: directory (str): Directory to look in for CSVs. Returns: cve_files (list): List", "data. Returns: response_data (dict): API response from Automox Vulnerability Sync https://developer.automox.com/openapi/vulnsync/operation/UploadCSVBatch/ \"\"\" response_data", "list of CSV files to upload and process. Args: directory (str): Directory to", "update_batches(uploaded_batches: dict) -> dict: \"\"\"Polls the Automox API for the status of batches", "uploaded_batches.items(): try: if batch['status'] != \"awaiting_approval\": headers = { \"Authorization\": f\"Bearer {api_secret}\", }", "output = ( \"==============================\\n\" f\"BATCH ID: {batch['id']}\\n\" f\"{batch['source']} has been processed.\\n\" f\"Total Vulnerabilities:", "-> list: \"\"\"Returns a list of CSV files to upload and process. Args:", "API response from Automox Vulnerability Sync https://developer.automox.com/openapi/vulnsync/operation/UploadCSVBatch/ \"\"\" response_data = {} task =", "CVE information is uploaded to the Automox Vulnerability Sync API, a task list", "try: headers = { \"Authorization\": f\"Bearer {api_secret}\", } files = [ ('file', (filename,", "= response.json() if \"errors\" in response_data and len(response_data['errors']) > 0: msg = \"\"", "not batches_complete: print(\"Batches are still building... Checking for updates...\") batches = update_batches(batches) for", ") print(upload_output) path = os.path.realpath(file.name) directory = os.path.dirname(path) filename = os.path.basename(file.name) new_path =", "[ ('file', (filename, file, 'text/csv')) ] response = requests.request(\"POST\", url, headers=headers, files=files) response_data", "\"\"\"Handles uploading and moving the CSV file to the processed directory. Args: unprocessed_cve_list", "f\"{response['source']} has been uploaded.\\n\" \"==============================\" ) print(upload_output) path = os.path.realpath(file.name) directory = os.path.dirname(path)", "except (requests.RequestException, Exception) as error: print(f\"Error: Unable to complete CSV upload request. ({error})\")", "for file in unprocessed_cve_list: try: # Make the request to upload the batch", "os.rename(path, new_path) except OSError as error: print(f\"Error processing CVE: {error}\") return uploaded_batches def", "f\"BATCH ID: {batch['id']}\\n\" f\"{batch['source']} has been processed.\\n\" f\"Total Vulnerabilities: {batch['cve_count']}\\n\" f\"Devices Impacted: {batch['impacted_device_count']}\\n\"", "\"\"\" response_data = {} task = \"patch\" url = f\"https://console.automox.com/api/orgs/{organization}/tasks/{task}/batches/upload\" filename = os.path.basename(file.name)", "dict: \"\"\"Polls the Automox API for the status of batches contained in this", "getpass import getpass from io import FileIO import requests def upload_cve(file: FileIO) ->", "Automox API for the status of batches contained in this dictionary. When CSV", "List of files to process. Returns: uploaded_batches (dict): Dictionary of batch ids correlated", "API batch upload responses. \"\"\" uploaded_batches = {} for file in unprocessed_cve_list: try:", "\"\"\"Returns a list of CSV files to upload and process. Args: directory (str):", "\"\"\" for batch_id, batch in uploaded_batches.items(): try: if batch['status'] != \"awaiting_approval\": headers =", "CSV files to upload and process. Args: directory (str): Directory to look in", "Exception) as error: print(f\"Error: Unable to update batch {batch_id} status. ({error})\") return uploaded_batches", "a CSV. {error}\") print(f\"Found {len(cve_files)} file(s) to upload.\") return cve_files def process_cves(unprocessed_cve_list: list)", "= os.path.realpath(file.name) directory = os.path.dirname(path) filename = os.path.basename(file.name) new_path = f\"{directory}/processed/{filename}\" print(f\"Moving {filename}", "about the status of a batch. Returns: uploaded_batches (dict): An updated dictionary of", "{api_secret}\", } files = [ ('file', (filename, file, 'text/csv')) ] response = requests.request(\"POST\",", "f\"{batch['source']} has been processed.\\n\" f\"Total Vulnerabilities: {batch['cve_count']}\\n\" f\"Devices Impacted: {batch['impacted_device_count']}\\n\" f\"Tasks Pending Creation:", "upload the batch file print(f\"Sending {os.path.basename(file.name)} to Automox Vulnerability Sync...\") response = upload_cve(file)", "msg = msg.join(response_data['errors']) raise Exception(msg) uploaded_batches[batch_id] = response_data except (requests.RequestException, Exception) as error:", "msg.join(response_data['errors']) raise Exception(msg) except (requests.RequestException, Exception) as error: print(f\"Error: Unable to complete CSV", "try: cve_file = open(path, \"rb\") cve_files.append(cve_file) except (OSError, IOError) as error: print(f\"Error: Could", "list is built Args: uploaded_batches (dict): A dictionary of the latest responses from", "= requests.get(f\"https://console.automox.com/api/orgs/{organization}/tasks/batches/{batch['id']}\", headers=headers) response_data = response.json() if \"errors\" in response_data and len(response_data['errors']) >", "f\"Bearer {api_secret}\", } response = requests.get(f\"https://console.automox.com/api/orgs/{organization}/tasks/batches/{batch['id']}\", headers=headers) response_data = response.json() if \"errors\" in", "def upload_cve(file: FileIO) -> dict: \"\"\" Uploads vulnerability list to Automox Vulnerability Sync", "> 0: msg = \"\" msg = msg.join(response_data['errors']) raise Exception(msg) uploaded_batches[batch_id] = response_data", "\") cve_list = get_unprocessed_cves(WATCH_DIR) if len(cve_list) == 0: sys.exit() batches = process_cves(cve_list) #", "> 0: msg = \"\" msg = msg.join(response_data['errors']) raise Exception(msg) except (requests.RequestException, Exception)", "f\"Tasks Pending Creation: {batch['task_count']}\\n\" f\"Batch Issues: {batch['issue_count']}\\n\" f\"Unknown Hosts: {batch['unknown_host_count']}\\n\" \"==============================\" ) print(output)", "import os import sys import time from getpass import getpass from io import", "files = [ ('file', (filename, file, 'text/csv')) ] response = requests.request(\"POST\", url, headers=headers,", "processing CVE: {error}\") return uploaded_batches def update_batches(uploaded_batches: dict) -> dict: \"\"\"Polls the Automox", "0: msg = \"\" msg = msg.join(response_data['errors']) raise Exception(msg) uploaded_batches[batch_id] = response_data except", "(requests.RequestException, Exception) as error: print(f\"Error: Unable to complete CSV upload request. ({error})\") return", "try: # Make the request to upload the batch file print(f\"Sending {os.path.basename(file.name)} to", "organization = os.getenv('AUTOMOX_ORGANIZATION_ID') or input(\"Enter your Organization ID: \") cve_list = get_unprocessed_cves(WATCH_DIR) if", "processing!\") for batch_id, batch in batches.items(): output = ( \"==============================\\n\" f\"BATCH ID: {batch['id']}\\n\"", "to watch for new CVE CSVs WATCH_DIR = os.getenv(\"WATCH_DIR\") or \"./cve_queue\" # Prompt", "response_data = response.json() if \"errors\" in response_data and len(response_data['errors']) > 0: msg =", "the latest responses from the Automox API about the status of a batch.", "\"==============================\" ) print(output) except Exception as e: print(f\"Error: {e}\\n\") raise except KeyboardInterrupt: print", "os.path.realpath(file.name) directory = os.path.dirname(path) filename = os.path.basename(file.name) new_path = f\"{directory}/processed/{filename}\" print(f\"Moving {filename} to", "API about the status of a batch. \"\"\" for batch_id, batch in uploaded_batches.items():", "Automox Vulnerability Sync API, a task list is built Args: uploaded_batches (dict): A", "!= \"awaiting_approval\": headers = { \"Authorization\": f\"Bearer {api_secret}\", } response = requests.get(f\"https://console.automox.com/api/orgs/{organization}/tasks/batches/{batch['id']}\", headers=headers)", "= requests.request(\"POST\", url, headers=headers, files=files) response_data = response.json() if \"errors\" in response_data and", "https://developer.automox.com/openapi/vulnsync/operation/UploadCSVBatch/ \"\"\" response_data = {} task = \"patch\" url = f\"https://console.automox.com/api/orgs/{organization}/tasks/{task}/batches/upload\" filename =", ") print(output) except Exception as e: print(f\"Error: {e}\\n\") raise except KeyboardInterrupt: print (\"Ctrl+C", "Args: file (FileIO): A CSV file containing vulnerability data. Returns: response_data (dict): API", "(dict): An updated dictionary of the latest responses from the Automox API about", "files to be processed and uploaded. \"\"\" cve_files = [] paths = glob.glob(f\"{directory}/*.csv\")", "input(\"Enter your Organization ID: \") cve_list = get_unprocessed_cves(WATCH_DIR) if len(cve_list) == 0: sys.exit()", "Creation: {batch['task_count']}\\n\" f\"Batch Issues: {batch['issue_count']}\\n\" f\"Unknown Hosts: {batch['unknown_host_count']}\\n\" \"==============================\" ) print(output) except Exception", "Pending Creation: {batch['task_count']}\\n\" f\"Batch Issues: {batch['issue_count']}\\n\" f\"Unknown Hosts: {batch['unknown_host_count']}\\n\" \"==============================\" ) print(output) except", "\"\" msg = msg.join(response_data['errors']) raise Exception(msg) except (requests.RequestException, Exception) as error: print(f\"Error: Unable", "of a batch. Returns: uploaded_batches (dict): An updated dictionary of the latest responses", "batch_id, batch in batches.items(): batches_complete = True if not batches[batch_id]['status'] == \"awaiting_approval\": batches_complete", "= [] paths = glob.glob(f\"{directory}/*.csv\") for path in paths: try: cve_file = open(path,", "status of batches contained in this dictionary. When CSV files containing CVE information", "response_data = {} task = \"patch\" url = f\"https://console.automox.com/api/orgs/{organization}/tasks/{task}/batches/upload\" filename = os.path.basename(file.name) try:", "= { \"Authorization\": f\"Bearer {api_secret}\", } response = requests.get(f\"https://console.automox.com/api/orgs/{organization}/tasks/batches/{batch['id']}\", headers=headers) response_data = response.json()", "for batch_id, batch in batches.items(): batches_complete = True if not batches[batch_id]['status'] == \"awaiting_approval\":", "Directory to look in for CSVs. Returns: cve_files (list): List of files to", "IOError) as error: print(f\"Error: Could not open a CSV. {error}\") print(f\"Found {len(cve_files)} file(s)", "files to process. Returns: uploaded_batches (dict): Dictionary of batch ids correlated to API", "{batch['issue_count']}\\n\" f\"Unknown Hosts: {batch['unknown_host_count']}\\n\" \"==============================\" ) print(output) except Exception as e: print(f\"Error: {e}\\n\")", "response_data (dict): API response from Automox Vulnerability Sync https://developer.automox.com/openapi/vulnsync/operation/UploadCSVBatch/ \"\"\" response_data = {}", "= upload_cve(file) if response['id']: uploaded_batches[response['id']] = response upload_output = ( \"==============================\\n\" f\"BATCH ID:", "to upload and process. Args: directory (str): Directory to look in for CSVs.", "sys.exit() batches = process_cves(cve_list) # Assumes the batches have not been built upon", "response upload_output = ( \"==============================\\n\" f\"BATCH ID: {response['id']}\\n\" f\"{response['source']} has been uploaded.\\n\" \"==============================\"", "for path in paths: try: cve_file = open(path, \"rb\") cve_files.append(cve_file) except (OSError, IOError)", "= len(batches) == 0 while not batches_complete: print(\"Batches are still building... Checking for", "{batch['impacted_device_count']}\\n\" f\"Tasks Pending Creation: {batch['task_count']}\\n\" f\"Batch Issues: {batch['issue_count']}\\n\" f\"Unknown Hosts: {batch['unknown_host_count']}\\n\" \"==============================\" )", "not batches[batch_id]['status'] == \"awaiting_approval\": batches_complete = False time.sleep(10) print(\"Batches are done processing!\") for", "batches = update_batches(batches) for batch_id, batch in batches.items(): batches_complete = True if not", "responses. \"\"\" uploaded_batches = {} for file in unprocessed_cve_list: try: # Make the", "CSVs. Returns: cve_files (list): List of files to be processed and uploaded. \"\"\"", "{ \"Authorization\": f\"Bearer {api_secret}\", } response = requests.get(f\"https://console.automox.com/api/orgs/{organization}/tasks/batches/{batch['id']}\", headers=headers) response_data = response.json() if", "def get_unprocessed_cves(directory: str) -> list: \"\"\"Returns a list of CSV files to upload", "response['id']: uploaded_batches[response['id']] = response upload_output = ( \"==============================\\n\" f\"BATCH ID: {response['id']}\\n\" f\"{response['source']} has", "unprocessed_cve_list: try: # Make the request to upload the batch file print(f\"Sending {os.path.basename(file.name)}", "as error: print(f\"Error processing CVE: {error}\") return uploaded_batches def update_batches(uploaded_batches: dict) -> dict:", "(FileIO): A CSV file containing vulnerability data. Returns: response_data (dict): API response from", "{api_secret}\", } response = requests.get(f\"https://console.automox.com/api/orgs/{organization}/tasks/batches/{batch['id']}\", headers=headers) response_data = response.json() if \"errors\" in response_data", "processed.\\n\" f\"Total Vulnerabilities: {batch['cve_count']}\\n\" f\"Devices Impacted: {batch['impacted_device_count']}\\n\" f\"Tasks Pending Creation: {batch['task_count']}\\n\" f\"Batch Issues:", "get_unprocessed_cves(WATCH_DIR) if len(cve_list) == 0: sys.exit() batches = process_cves(cve_list) # Assumes the batches", "are still building... Checking for updates...\") batches = update_batches(batches) for batch_id, batch in", "to Automox Vulnerability Sync...\") response = upload_cve(file) if response['id']: uploaded_batches[response['id']] = response upload_output", "= response_data except (requests.RequestException, Exception) as error: print(f\"Error: Unable to update batch {batch_id}", "to API batch upload responses. \"\"\" uploaded_batches = {} for file in unprocessed_cve_list:", "are done processing!\") for batch_id, batch in batches.items(): output = ( \"==============================\\n\" f\"BATCH", "dict) -> dict: \"\"\"Polls the Automox API for the status of batches contained", "import FileIO import requests def upload_cve(file: FileIO) -> dict: \"\"\" Uploads vulnerability list", "{response['id']}\\n\" f\"{response['source']} has been uploaded.\\n\" \"==============================\" ) print(upload_output) path = os.path.realpath(file.name) directory =", "= \"\" msg = msg.join(response_data['errors']) raise Exception(msg) except (requests.RequestException, Exception) as error: print(f\"Error:", "of files to be processed and uploaded. \"\"\" cve_files = [] paths =", "dict: \"\"\"Handles uploading and moving the CSV file to the processed directory. Args:", "dictionary of the latest responses from the Automox API about the status of", "a batch. Returns: uploaded_batches (dict): An updated dictionary of the latest responses from", "to upload the batch file print(f\"Sending {os.path.basename(file.name)} to Automox Vulnerability Sync...\") response =", "(dict): Dictionary of batch ids correlated to API batch upload responses. \"\"\" uploaded_batches", "file print(f\"Sending {os.path.basename(file.name)} to Automox Vulnerability Sync...\") response = upload_cve(file) if response['id']: uploaded_batches[response['id']]", "from io import FileIO import requests def upload_cve(file: FileIO) -> dict: \"\"\" Uploads", "import glob import os import sys import time from getpass import getpass from", "cve_files def process_cves(unprocessed_cve_list: list) -> dict: \"\"\"Handles uploading and moving the CSV file", "-> dict: \"\"\"Polls the Automox API for the status of batches contained in", "= update_batches(batches) for batch_id, batch in batches.items(): batches_complete = True if not batches[batch_id]['status']", "len(response_data['errors']) > 0: msg = \"\" msg = msg.join(response_data['errors']) raise Exception(msg) uploaded_batches[batch_id] =", "Vulnerability Sync API, a task list is built Args: uploaded_batches (dict): A dictionary", "CVE CSVs WATCH_DIR = os.getenv(\"WATCH_DIR\") or \"./cve_queue\" # Prompt for inputs api_secret =", "the batch file print(f\"Sending {os.path.basename(file.name)} to Automox Vulnerability Sync...\") response = upload_cve(file) if", "f\"{directory}/processed/{filename}\" print(f\"Moving {filename} to {new_path}\\n\") os.rename(path, new_path) except OSError as error: print(f\"Error processing", "= \"\" msg = msg.join(response_data['errors']) raise Exception(msg) uploaded_batches[batch_id] = response_data except (requests.RequestException, Exception)", "for new CVE CSVs WATCH_DIR = os.getenv(\"WATCH_DIR\") or \"./cve_queue\" # Prompt for inputs", "headers = { \"Authorization\": f\"Bearer {api_secret}\", } response = requests.get(f\"https://console.automox.com/api/orgs/{organization}/tasks/batches/{batch['id']}\", headers=headers) response_data =", "batch upload responses. \"\"\" uploaded_batches = {} for file in unprocessed_cve_list: try: #", "directory. Args: unprocessed_cve_list (list): List of files to process. Returns: uploaded_batches (dict): Dictionary", "in unprocessed_cve_list: try: # Make the request to upload the batch file print(f\"Sending", "( \"==============================\\n\" f\"BATCH ID: {batch['id']}\\n\" f\"{batch['source']} has been processed.\\n\" f\"Total Vulnerabilities: {batch['cve_count']}\\n\" f\"Devices", "Returns: cve_files (list): List of files to be processed and uploaded. \"\"\" cve_files", "OSError as error: print(f\"Error processing CVE: {error}\") return uploaded_batches def update_batches(uploaded_batches: dict) ->", "batch {batch_id} status. ({error})\") return uploaded_batches try: # Directory to watch for new", "about the status of a batch. \"\"\" for batch_id, batch in uploaded_batches.items(): try:", "{error}\") print(f\"Found {len(cve_files)} file(s) to upload.\") return cve_files def process_cves(unprocessed_cve_list: list) -> dict:", "status of a batch. Returns: uploaded_batches (dict): An updated dictionary of the latest", "be processed and uploaded. \"\"\" cve_files = [] paths = glob.glob(f\"{directory}/*.csv\") for path", "True if not batches[batch_id]['status'] == \"awaiting_approval\": batches_complete = False time.sleep(10) print(\"Batches are done", "FileIO import requests def upload_cve(file: FileIO) -> dict: \"\"\" Uploads vulnerability list to", "Uploads vulnerability list to Automox Vulnerability Sync endpoint. Args: file (FileIO): A CSV", "f\"Devices Impacted: {batch['impacted_device_count']}\\n\" f\"Tasks Pending Creation: {batch['task_count']}\\n\" f\"Batch Issues: {batch['issue_count']}\\n\" f\"Unknown Hosts: {batch['unknown_host_count']}\\n\"", "directory (str): Directory to look in for CSVs. Returns: cve_files (list): List of", "and process. Args: directory (str): Directory to look in for CSVs. Returns: cve_files", "response_data def get_unprocessed_cves(directory: str) -> list: \"\"\"Returns a list of CSV files to", "file, 'text/csv')) ] response = requests.request(\"POST\", url, headers=headers, files=files) response_data = response.json() if", "return uploaded_batches def update_batches(uploaded_batches: dict) -> dict: \"\"\"Polls the Automox API for the", "the status of a batch. Returns: uploaded_batches (dict): An updated dictionary of the", "CVE: {error}\") return uploaded_batches def update_batches(uploaded_batches: dict) -> dict: \"\"\"Polls the Automox API", "\"rb\") cve_files.append(cve_file) except (OSError, IOError) as error: print(f\"Error: Could not open a CSV.", "process. Args: directory (str): Directory to look in for CSVs. Returns: cve_files (list):", "Unable to update batch {batch_id} status. ({error})\") return uploaded_batches try: # Directory to", "in uploaded_batches.items(): try: if batch['status'] != \"awaiting_approval\": headers = { \"Authorization\": f\"Bearer {api_secret}\",", "(list): List of files to be processed and uploaded. \"\"\" cve_files = []", "in this dictionary. When CSV files containing CVE information is uploaded to the", "batch in uploaded_batches.items(): try: if batch['status'] != \"awaiting_approval\": headers = { \"Authorization\": f\"Bearer", "of CVE reports\"\"\" import glob import os import sys import time from getpass", "has been processed.\\n\" f\"Total Vulnerabilities: {batch['cve_count']}\\n\" f\"Devices Impacted: {batch['impacted_device_count']}\\n\" f\"Tasks Pending Creation: {batch['task_count']}\\n\"", "= {} for file in unprocessed_cve_list: try: # Make the request to upload", "ingestion of CVE reports\"\"\" import glob import os import sys import time from", "watch for new CVE CSVs WATCH_DIR = os.getenv(\"WATCH_DIR\") or \"./cve_queue\" # Prompt for", "and uploaded. \"\"\" cve_files = [] paths = glob.glob(f\"{directory}/*.csv\") for path in paths:", "while not batches_complete: print(\"Batches are still building... Checking for updates...\") batches = update_batches(batches)", "(requests.RequestException, Exception) as error: print(f\"Error: Unable to update batch {batch_id} status. ({error})\") return", "if not batches[batch_id]['status'] == \"awaiting_approval\": batches_complete = False time.sleep(10) print(\"Batches are done processing!\")", "Returns: uploaded_batches (dict): Dictionary of batch ids correlated to API batch upload responses.", "the status of a batch. \"\"\" for batch_id, batch in uploaded_batches.items(): try: if", "Vulnerability Sync https://developer.automox.com/openapi/vulnsync/operation/UploadCSVBatch/ \"\"\" response_data = {} task = \"patch\" url = f\"https://console.automox.com/api/orgs/{organization}/tasks/{task}/batches/upload\"", "\"\"\"Polls the Automox API for the status of batches contained in this dictionary.", "a task list is built Args: uploaded_batches (dict): A dictionary of the latest", "for inputs api_secret = os.getenv('AUTOMOX_API_KEY') or getpass('Enter your API Key: ') organization =", "f\"Bearer {api_secret}\", } files = [ ('file', (filename, file, 'text/csv')) ] response =", "msg.join(response_data['errors']) raise Exception(msg) uploaded_batches[batch_id] = response_data except (requests.RequestException, Exception) as error: print(f\"Error: Unable", "(OSError, IOError) as error: print(f\"Error: Could not open a CSV. {error}\") print(f\"Found {len(cve_files)}", "\"\"\" uploaded_batches = {} for file in unprocessed_cve_list: try: # Make the request", "update batch {batch_id} status. ({error})\") return uploaded_batches try: # Directory to watch for", "('file', (filename, file, 'text/csv')) ] response = requests.request(\"POST\", url, headers=headers, files=files) response_data =", "the processed directory. Args: unprocessed_cve_list (list): List of files to process. Returns: uploaded_batches", "your API Key: ') organization = os.getenv('AUTOMOX_ORGANIZATION_ID') or input(\"Enter your Organization ID: \")", "= msg.join(response_data['errors']) raise Exception(msg) uploaded_batches[batch_id] = response_data except (requests.RequestException, Exception) as error: print(f\"Error:", "len(cve_list) == 0: sys.exit() batches = process_cves(cve_list) # Assumes the batches have not", "the batches have not been built upon receipt. batches_complete = len(batches) == 0", "from the Automox API about the status of a batch. Returns: uploaded_batches (dict):", "and moving the CSV file to the processed directory. Args: unprocessed_cve_list (list): List", "= ( \"==============================\\n\" f\"BATCH ID: {response['id']}\\n\" f\"{response['source']} has been uploaded.\\n\" \"==============================\" ) print(upload_output)", "Automox Vulnerability Sync endpoint. Args: file (FileIO): A CSV file containing vulnerability data.", "status of a batch. \"\"\" for batch_id, batch in uploaded_batches.items(): try: if batch['status']", "built Args: uploaded_batches (dict): A dictionary of the latest responses from the Automox", "f\"Total Vulnerabilities: {batch['cve_count']}\\n\" f\"Devices Impacted: {batch['impacted_device_count']}\\n\" f\"Tasks Pending Creation: {batch['task_count']}\\n\" f\"Batch Issues: {batch['issue_count']}\\n\"", "{error}\") return uploaded_batches def update_batches(uploaded_batches: dict) -> dict: \"\"\"Polls the Automox API for", "url = f\"https://console.automox.com/api/orgs/{organization}/tasks/{task}/batches/upload\" filename = os.path.basename(file.name) try: headers = { \"Authorization\": f\"Bearer {api_secret}\",", "{batch['cve_count']}\\n\" f\"Devices Impacted: {batch['impacted_device_count']}\\n\" f\"Tasks Pending Creation: {batch['task_count']}\\n\" f\"Batch Issues: {batch['issue_count']}\\n\" f\"Unknown Hosts:", "batch. Returns: uploaded_batches (dict): An updated dictionary of the latest responses from the", "{len(cve_files)} file(s) to upload.\") return cve_files def process_cves(unprocessed_cve_list: list) -> dict: \"\"\"Handles uploading", "uploaded_batches def update_batches(uploaded_batches: dict) -> dict: \"\"\"Polls the Automox API for the status", "of a batch. \"\"\" for batch_id, batch in uploaded_batches.items(): try: if batch['status'] !=", "in paths: try: cve_file = open(path, \"rb\") cve_files.append(cve_file) except (OSError, IOError) as error:", "import time from getpass import getpass from io import FileIO import requests def", "= os.getenv('AUTOMOX_API_KEY') or getpass('Enter your API Key: ') organization = os.getenv('AUTOMOX_ORGANIZATION_ID') or input(\"Enter", "CSV. {error}\") print(f\"Found {len(cve_files)} file(s) to upload.\") return cve_files def process_cves(unprocessed_cve_list: list) ->", "except Exception as e: print(f\"Error: {e}\\n\") raise except KeyboardInterrupt: print (\"Ctrl+C Pressed. Shutting", "} response = requests.get(f\"https://console.automox.com/api/orgs/{organization}/tasks/batches/{batch['id']}\", headers=headers) response_data = response.json() if \"errors\" in response_data and", "= get_unprocessed_cves(WATCH_DIR) if len(cve_list) == 0: sys.exit() batches = process_cves(cve_list) # Assumes the", "for automating the ingestion of CVE reports\"\"\" import glob import os import sys", "= os.path.dirname(path) filename = os.path.basename(file.name) new_path = f\"{directory}/processed/{filename}\" print(f\"Moving {filename} to {new_path}\\n\") os.rename(path,", "API, a task list is built Args: uploaded_batches (dict): A dictionary of the", "time from getpass import getpass from io import FileIO import requests def upload_cve(file:", "import getpass from io import FileIO import requests def upload_cve(file: FileIO) -> dict:", "request to upload the batch file print(f\"Sending {os.path.basename(file.name)} to Automox Vulnerability Sync...\") response", "error: print(f\"Error processing CVE: {error}\") return uploaded_batches def update_batches(uploaded_batches: dict) -> dict: \"\"\"Polls", "uploaded_batches (dict): Dictionary of batch ids correlated to API batch upload responses. \"\"\"", "have not been built upon receipt. batches_complete = len(batches) == 0 while not", "f\"https://console.automox.com/api/orgs/{organization}/tasks/{task}/batches/upload\" filename = os.path.basename(file.name) try: headers = { \"Authorization\": f\"Bearer {api_secret}\", } files", "\"Authorization\": f\"Bearer {api_secret}\", } response = requests.get(f\"https://console.automox.com/api/orgs/{organization}/tasks/batches/{batch['id']}\", headers=headers) response_data = response.json() if \"errors\"", "response_data except (requests.RequestException, Exception) as error: print(f\"Error: Unable to update batch {batch_id} status.", "= open(path, \"rb\") cve_files.append(cve_file) except (OSError, IOError) as error: print(f\"Error: Could not open", "upload request. ({error})\") return response_data def get_unprocessed_cves(directory: str) -> list: \"\"\"Returns a list", "processed directory. Args: unprocessed_cve_list (list): List of files to process. Returns: uploaded_batches (dict):", "task list is built Args: uploaded_batches (dict): A dictionary of the latest responses", "An updated dictionary of the latest responses from the Automox API about the", "containing CVE information is uploaded to the Automox Vulnerability Sync API, a task", "API about the status of a batch. Returns: uploaded_batches (dict): An updated dictionary", "= msg.join(response_data['errors']) raise Exception(msg) except (requests.RequestException, Exception) as error: print(f\"Error: Unable to complete", "batch_id, batch in uploaded_batches.items(): try: if batch['status'] != \"awaiting_approval\": headers = { \"Authorization\":", "batches_complete: print(\"Batches are still building... Checking for updates...\") batches = update_batches(batches) for batch_id,", "in batches.items(): output = ( \"==============================\\n\" f\"BATCH ID: {batch['id']}\\n\" f\"{batch['source']} has been processed.\\n\"", "or \"./cve_queue\" # Prompt for inputs api_secret = os.getenv('AUTOMOX_API_KEY') or getpass('Enter your API", "inputs api_secret = os.getenv('AUTOMOX_API_KEY') or getpass('Enter your API Key: ') organization = os.getenv('AUTOMOX_ORGANIZATION_ID')", "containing vulnerability data. Returns: response_data (dict): API response from Automox Vulnerability Sync https://developer.automox.com/openapi/vulnsync/operation/UploadCSVBatch/", "built upon receipt. batches_complete = len(batches) == 0 while not batches_complete: print(\"Batches are", "\"==============================\\n\" f\"BATCH ID: {batch['id']}\\n\" f\"{batch['source']} has been processed.\\n\" f\"Total Vulnerabilities: {batch['cve_count']}\\n\" f\"Devices Impacted:", "io import FileIO import requests def upload_cve(file: FileIO) -> dict: \"\"\" Uploads vulnerability", "ids correlated to API batch upload responses. \"\"\" uploaded_batches = {} for file", "Sync https://developer.automox.com/openapi/vulnsync/operation/UploadCSVBatch/ \"\"\" response_data = {} task = \"patch\" url = f\"https://console.automox.com/api/orgs/{organization}/tasks/{task}/batches/upload\" filename", "Returns: uploaded_batches (dict): An updated dictionary of the latest responses from the Automox", "} files = [ ('file', (filename, file, 'text/csv')) ] response = requests.request(\"POST\", url,", "Hosts: {batch['unknown_host_count']}\\n\" \"==============================\" ) print(output) except Exception as e: print(f\"Error: {e}\\n\") raise except", "process_cves(cve_list) # Assumes the batches have not been built upon receipt. batches_complete =", "the Automox API about the status of a batch. \"\"\" for batch_id, batch", "as error: print(f\"Error: Unable to complete CSV upload request. ({error})\") return response_data def", "the Automox Vulnerability Sync API, a task list is built Args: uploaded_batches (dict):", "and len(response_data['errors']) > 0: msg = \"\" msg = msg.join(response_data['errors']) raise Exception(msg) except", "= True if not batches[batch_id]['status'] == \"awaiting_approval\": batches_complete = False time.sleep(10) print(\"Batches are", "CSVs WATCH_DIR = os.getenv(\"WATCH_DIR\") or \"./cve_queue\" # Prompt for inputs api_secret = os.getenv('AUTOMOX_API_KEY')", "= ( \"==============================\\n\" f\"BATCH ID: {batch['id']}\\n\" f\"{batch['source']} has been processed.\\n\" f\"Total Vulnerabilities: {batch['cve_count']}\\n\"", "Vulnerability Sync endpoint. Args: file (FileIO): A CSV file containing vulnerability data. Returns:", "\"./cve_queue\" # Prompt for inputs api_secret = os.getenv('AUTOMOX_API_KEY') or getpass('Enter your API Key:", "open a CSV. {error}\") print(f\"Found {len(cve_files)} file(s) to upload.\") return cve_files def process_cves(unprocessed_cve_list:", "uploaded_batches = {} for file in unprocessed_cve_list: try: # Make the request to", "A dictionary of the latest responses from the Automox API about the status", "os.path.basename(file.name) try: headers = { \"Authorization\": f\"Bearer {api_secret}\", } files = [ ('file',", "batch in batches.items(): batches_complete = True if not batches[batch_id]['status'] == \"awaiting_approval\": batches_complete =", "msg = msg.join(response_data['errors']) raise Exception(msg) except (requests.RequestException, Exception) as error: print(f\"Error: Unable to", "uploaded_batches[response['id']] = response upload_output = ( \"==============================\\n\" f\"BATCH ID: {response['id']}\\n\" f\"{response['source']} has been", "if len(cve_list) == 0: sys.exit() batches = process_cves(cve_list) # Assumes the batches have", "Directory to watch for new CVE CSVs WATCH_DIR = os.getenv(\"WATCH_DIR\") or \"./cve_queue\" #", "for updates...\") batches = update_batches(batches) for batch_id, batch in batches.items(): batches_complete = True", "len(response_data['errors']) > 0: msg = \"\" msg = msg.join(response_data['errors']) raise Exception(msg) except (requests.RequestException,", "CSV file to the processed directory. Args: unprocessed_cve_list (list): List of files to", "upload and process. Args: directory (str): Directory to look in for CSVs. Returns:", "batch file print(f\"Sending {os.path.basename(file.name)} to Automox Vulnerability Sync...\") response = upload_cve(file) if response['id']:", "the request to upload the batch file print(f\"Sending {os.path.basename(file.name)} to Automox Vulnerability Sync...\")", "of files to process. Returns: uploaded_batches (dict): Dictionary of batch ids correlated to", "Exception) as error: print(f\"Error: Unable to complete CSV upload request. ({error})\") return response_data", "raise Exception(msg) except (requests.RequestException, Exception) as error: print(f\"Error: Unable to complete CSV upload", "response_data and len(response_data['errors']) > 0: msg = \"\" msg = msg.join(response_data['errors']) raise Exception(msg)", "0 while not batches_complete: print(\"Batches are still building... Checking for updates...\") batches =", "print(\"Batches are done processing!\") for batch_id, batch in batches.items(): output = ( \"==============================\\n\"", "Issues: {batch['issue_count']}\\n\" f\"Unknown Hosts: {batch['unknown_host_count']}\\n\" \"==============================\" ) print(output) except Exception as e: print(f\"Error:", "ID: {response['id']}\\n\" f\"{response['source']} has been uploaded.\\n\" \"==============================\" ) print(upload_output) path = os.path.realpath(file.name) directory", "os.path.dirname(path) filename = os.path.basename(file.name) new_path = f\"{directory}/processed/{filename}\" print(f\"Moving {filename} to {new_path}\\n\") os.rename(path, new_path)", "API Key: ') organization = os.getenv('AUTOMOX_ORGANIZATION_ID') or input(\"Enter your Organization ID: \") cve_list", "in for CSVs. Returns: cve_files (list): List of files to be processed and", "filename = os.path.basename(file.name) try: headers = { \"Authorization\": f\"Bearer {api_secret}\", } files =", "headers=headers) response_data = response.json() if \"errors\" in response_data and len(response_data['errors']) > 0: msg", "updates...\") batches = update_batches(batches) for batch_id, batch in batches.items(): batches_complete = True if", "in batches.items(): batches_complete = True if not batches[batch_id]['status'] == \"awaiting_approval\": batches_complete = False", "latest responses from the Automox API about the status of a batch. Returns:", "batch['status'] != \"awaiting_approval\": headers = { \"Authorization\": f\"Bearer {api_secret}\", } response = requests.get(f\"https://console.automox.com/api/orgs/{organization}/tasks/batches/{batch['id']}\",", "(filename, file, 'text/csv')) ] response = requests.request(\"POST\", url, headers=headers, files=files) response_data = response.json()", "= glob.glob(f\"{directory}/*.csv\") for path in paths: try: cve_file = open(path, \"rb\") cve_files.append(cve_file) except", "batch_id, batch in batches.items(): output = ( \"==============================\\n\" f\"BATCH ID: {batch['id']}\\n\" f\"{batch['source']} has", "\"Authorization\": f\"Bearer {api_secret}\", } files = [ ('file', (filename, file, 'text/csv')) ] response", "has been uploaded.\\n\" \"==============================\" ) print(upload_output) path = os.path.realpath(file.name) directory = os.path.dirname(path) filename", "file to the processed directory. Args: unprocessed_cve_list (list): List of files to process.", "= response upload_output = ( \"==============================\\n\" f\"BATCH ID: {response['id']}\\n\" f\"{response['source']} has been uploaded.\\n\"", "uploaded_batches (dict): An updated dictionary of the latest responses from the Automox API", "print(f\"Sending {os.path.basename(file.name)} to Automox Vulnerability Sync...\") response = upload_cve(file) if response['id']: uploaded_batches[response['id']] =", "except OSError as error: print(f\"Error processing CVE: {error}\") return uploaded_batches def update_batches(uploaded_batches: dict)", "to be processed and uploaded. \"\"\" cve_files = [] paths = glob.glob(f\"{directory}/*.csv\") for", "# Directory to watch for new CVE CSVs WATCH_DIR = os.getenv(\"WATCH_DIR\") or \"./cve_queue\"", "vulnerability list to Automox Vulnerability Sync endpoint. Args: file (FileIO): A CSV file", "try: # Directory to watch for new CVE CSVs WATCH_DIR = os.getenv(\"WATCH_DIR\") or", "list to Automox Vulnerability Sync endpoint. Args: file (FileIO): A CSV file containing", "Exception(msg) except (requests.RequestException, Exception) as error: print(f\"Error: Unable to complete CSV upload request.", "{batch['unknown_host_count']}\\n\" \"==============================\" ) print(output) except Exception as e: print(f\"Error: {e}\\n\") raise except KeyboardInterrupt:", "{ \"Authorization\": f\"Bearer {api_secret}\", } files = [ ('file', (filename, file, 'text/csv')) ]", "Automox Vulnerability Sync...\") response = upload_cve(file) if response['id']: uploaded_batches[response['id']] = response upload_output =", "to look in for CSVs. Returns: cve_files (list): List of files to be", "WATCH_DIR = os.getenv(\"WATCH_DIR\") or \"./cve_queue\" # Prompt for inputs api_secret = os.getenv('AUTOMOX_API_KEY') or", "task = \"patch\" url = f\"https://console.automox.com/api/orgs/{organization}/tasks/{task}/batches/upload\" filename = os.path.basename(file.name) try: headers = {", "f\"Batch Issues: {batch['issue_count']}\\n\" f\"Unknown Hosts: {batch['unknown_host_count']}\\n\" \"==============================\" ) print(output) except Exception as e:", "processed and uploaded. \"\"\" cve_files = [] paths = glob.glob(f\"{directory}/*.csv\") for path in", "from the Automox API about the status of a batch. \"\"\" for batch_id,", "from getpass import getpass from io import FileIO import requests def upload_cve(file: FileIO)", "upon receipt. batches_complete = len(batches) == 0 while not batches_complete: print(\"Batches are still", "look in for CSVs. Returns: cve_files (list): List of files to be processed", "<reponame>AutomoxCommunity/automox-console-sdk-python \"\"\"Use case for automating the ingestion of CVE reports\"\"\" import glob import", "upload_cve(file) if response['id']: uploaded_batches[response['id']] = response upload_output = ( \"==============================\\n\" f\"BATCH ID: {response['id']}\\n\"", "time.sleep(10) print(\"Batches are done processing!\") for batch_id, batch in batches.items(): output = (", "\"==============================\\n\" f\"BATCH ID: {response['id']}\\n\" f\"{response['source']} has been uploaded.\\n\" \"==============================\" ) print(upload_output) path =", "complete CSV upload request. ({error})\") return response_data def get_unprocessed_cves(directory: str) -> list: \"\"\"Returns", "print(\"Batches are still building... Checking for updates...\") batches = update_batches(batches) for batch_id, batch", "Args: unprocessed_cve_list (list): List of files to process. Returns: uploaded_batches (dict): Dictionary of", "( \"==============================\\n\" f\"BATCH ID: {response['id']}\\n\" f\"{response['source']} has been uploaded.\\n\" \"==============================\" ) print(upload_output) path", "== 0: sys.exit() batches = process_cves(cve_list) # Assumes the batches have not been", "reports\"\"\" import glob import os import sys import time from getpass import getpass", "Automox API about the status of a batch. \"\"\" for batch_id, batch in", "\"errors\" in response_data and len(response_data['errors']) > 0: msg = \"\" msg = msg.join(response_data['errors'])", "API for the status of batches contained in this dictionary. When CSV files", "response = requests.request(\"POST\", url, headers=headers, files=files) response_data = response.json() if \"errors\" in response_data", "except (OSError, IOError) as error: print(f\"Error: Could not open a CSV. {error}\") print(f\"Found", "Automox API about the status of a batch. Returns: uploaded_batches (dict): An updated", "-> dict: \"\"\"Handles uploading and moving the CSV file to the processed directory.", "uploading and moving the CSV file to the processed directory. Args: unprocessed_cve_list (list):", "file (FileIO): A CSV file containing vulnerability data. Returns: response_data (dict): API response", "building... Checking for updates...\") batches = update_batches(batches) for batch_id, batch in batches.items(): batches_complete", "to Automox Vulnerability Sync endpoint. Args: file (FileIO): A CSV file containing vulnerability", "responses from the Automox API about the status of a batch. Returns: uploaded_batches", "sys import time from getpass import getpass from io import FileIO import requests", "{os.path.basename(file.name)} to Automox Vulnerability Sync...\") response = upload_cve(file) if response['id']: uploaded_batches[response['id']] = response", "'text/csv')) ] response = requests.request(\"POST\", url, headers=headers, files=files) response_data = response.json() if \"errors\"", "= os.getenv(\"WATCH_DIR\") or \"./cve_queue\" # Prompt for inputs api_secret = os.getenv('AUTOMOX_API_KEY') or getpass('Enter", "from Automox Vulnerability Sync https://developer.automox.com/openapi/vulnsync/operation/UploadCSVBatch/ \"\"\" response_data = {} task = \"patch\" url", "import requests def upload_cve(file: FileIO) -> dict: \"\"\" Uploads vulnerability list to Automox", "for the status of batches contained in this dictionary. When CSV files containing", "or getpass('Enter your API Key: ') organization = os.getenv('AUTOMOX_ORGANIZATION_ID') or input(\"Enter your Organization", "List of files to be processed and uploaded. \"\"\" cve_files = [] paths", "if \"errors\" in response_data and len(response_data['errors']) > 0: msg = \"\" msg =", "requests.get(f\"https://console.automox.com/api/orgs/{organization}/tasks/batches/{batch['id']}\", headers=headers) response_data = response.json() if \"errors\" in response_data and len(response_data['errors']) > 0:", "the CSV file to the processed directory. Args: unprocessed_cve_list (list): List of files", "= f\"https://console.automox.com/api/orgs/{organization}/tasks/{task}/batches/upload\" filename = os.path.basename(file.name) try: headers = { \"Authorization\": f\"Bearer {api_secret}\", }", "= process_cves(cve_list) # Assumes the batches have not been built upon receipt. batches_complete", "= \"patch\" url = f\"https://console.automox.com/api/orgs/{organization}/tasks/{task}/batches/upload\" filename = os.path.basename(file.name) try: headers = { \"Authorization\":", "return cve_files def process_cves(unprocessed_cve_list: list) -> dict: \"\"\"Handles uploading and moving the CSV", "# Make the request to upload the batch file print(f\"Sending {os.path.basename(file.name)} to Automox" ]
[ "from mean import mean import pytest def test_ints(): num_list = [1, 2, 3,", "[0, 2, 4, 6] assert mean(num_list) == 3 def test_empty(): assert mean([]) ==", "assert mean(num_list) == 3 def test_empty(): assert mean([]) == 0 def test_single_int(): with", "== 3 def test_empty(): assert mean([]) == 0 def test_single_int(): with pytest.raises(TypeError): mean(1)", "test_zero(): num_list = [0, 2, 4, 6] assert mean(num_list) == 3 def test_empty():", "num_list = [0, 2, 4, 6] assert mean(num_list) == 3 def test_empty(): assert", "obs = mean(num_list) assert obs == 3 def test_not_numbers(): values = [2, \"lolcats\"]", "def test_zero(): num_list = [0, 2, 4, 6] assert mean(num_list) == 3 def", "\"lolcats\"] with pytest.raises(TypeError): out = mean(values) def test_zero(): num_list = [0, 2, 4,", "3, 4, 5] obs = mean(num_list) assert obs == 3 def test_not_numbers(): values", "assert obs == 3 def test_not_numbers(): values = [2, \"lolcats\"] with pytest.raises(TypeError): out", "test_ints(): num_list = [1, 2, 3, 4, 5] obs = mean(num_list) assert obs", "import pytest def test_ints(): num_list = [1, 2, 3, 4, 5] obs =", "mean import mean import pytest def test_ints(): num_list = [1, 2, 3, 4,", "= [1, 2, 3, 4, 5] obs = mean(num_list) assert obs == 3", "== 3 def test_not_numbers(): values = [2, \"lolcats\"] with pytest.raises(TypeError): out = mean(values)", "pytest.raises(TypeError): out = mean(values) def test_zero(): num_list = [0, 2, 4, 6] assert", "2, 3, 4, 5] obs = mean(num_list) assert obs == 3 def test_not_numbers():", "5] obs = mean(num_list) assert obs == 3 def test_not_numbers(): values = [2,", "def test_ints(): num_list = [1, 2, 3, 4, 5] obs = mean(num_list) assert", "num_list = [1, 2, 3, 4, 5] obs = mean(num_list) assert obs ==", "mean import pytest def test_ints(): num_list = [1, 2, 3, 4, 5] obs", "pytest def test_ints(): num_list = [1, 2, 3, 4, 5] obs = mean(num_list)", "test_not_numbers(): values = [2, \"lolcats\"] with pytest.raises(TypeError): out = mean(values) def test_zero(): num_list", "6] assert mean(num_list) == 3 def test_empty(): assert mean([]) == 0 def test_single_int():", "with pytest.raises(TypeError): out = mean(values) def test_zero(): num_list = [0, 2, 4, 6]", "4, 5] obs = mean(num_list) assert obs == 3 def test_not_numbers(): values =", "[2, \"lolcats\"] with pytest.raises(TypeError): out = mean(values) def test_zero(): num_list = [0, 2,", "mean(values) def test_zero(): num_list = [0, 2, 4, 6] assert mean(num_list) == 3", "= mean(num_list) assert obs == 3 def test_not_numbers(): values = [2, \"lolcats\"] with", "2, 4, 6] assert mean(num_list) == 3 def test_empty(): assert mean([]) == 0", "= [2, \"lolcats\"] with pytest.raises(TypeError): out = mean(values) def test_zero(): num_list = [0,", "3 def test_not_numbers(): values = [2, \"lolcats\"] with pytest.raises(TypeError): out = mean(values) def", "def test_not_numbers(): values = [2, \"lolcats\"] with pytest.raises(TypeError): out = mean(values) def test_zero():", "[1, 2, 3, 4, 5] obs = mean(num_list) assert obs == 3 def", "mean(num_list) assert obs == 3 def test_not_numbers(): values = [2, \"lolcats\"] with pytest.raises(TypeError):", "= [0, 2, 4, 6] assert mean(num_list) == 3 def test_empty(): assert mean([])", "out = mean(values) def test_zero(): num_list = [0, 2, 4, 6] assert mean(num_list)", "= mean(values) def test_zero(): num_list = [0, 2, 4, 6] assert mean(num_list) ==", "obs == 3 def test_not_numbers(): values = [2, \"lolcats\"] with pytest.raises(TypeError): out =", "mean(num_list) == 3 def test_empty(): assert mean([]) == 0 def test_single_int(): with pytest.raises(TypeError):", "import mean import pytest def test_ints(): num_list = [1, 2, 3, 4, 5]", "4, 6] assert mean(num_list) == 3 def test_empty(): assert mean([]) == 0 def", "values = [2, \"lolcats\"] with pytest.raises(TypeError): out = mean(values) def test_zero(): num_list =" ]
[ "to a single group on another host ''' if src_group: src_group_id = glm._get_namespace_id(src_gitlab_url,", "archived projects) and write them to a (single-column) csv. WARNING: this will silently", "''' migrate group variables from 1+ groups on one host to a single", "target_group_id = glm._get_namespace_id(target_gitlab_url, target_group, target_token) for var in glm.get_group_vars(src_gitlab_url, src_token, src_group_id): glm.create_group_var(target_gitlab_url, target_token,", "glm.create_group_var(target_gitlab_url, target_token, var, target_group_id) if __name__ == \"__main__\": sys.exit(cli()) # pragma: no cover", "an API-level private token valid on the target server ''' for line in", "from a csv, migrate to target_base_url csv must contain two columns: source url", "gitlab_url, token): ''' get the SSH url for all projects (except archived projects)", "in repos to action from a csv, migrate to target_base_url csv must contain", "set_as_origin): for child_path in os.listdir(path): if os.path.isdir(child_path) and os.path.isdir(f\"{child_path}/.git\"): glm.update_local_repo(child_path, old_base_url, new_base_url, target_group,", "for string in line.split(',')] click.echo(f\"working on {old_url}...\") glm.migrate_repo(old_url, target_base_url, target_group, target_token) @projects.command() @click.argument('csv',", "''' get the SSH url for all projects (except archived projects) and write", "0 @variables.command() @click.option('src_group', '--source-group', default=None, type=click.STRING, help=\"Leave blank to migrate vars from all", "def cli(): pass @cli.group() def projects(): \"\"\"Commands for migrating projects.\"\"\" return 0 @projects.command()", "return 0 @projects.command() @click.argument('csv', type=click.File('r')) @click.argument('target_base_url', type=click.STRING) @click.argument('target_token', type=click.STRING) def from_csv(csv, target_base_url, target_token):", "utf-8 -*- \"\"\"Console script for gitlab_migration.\"\"\" import os import sys import click from", "var in glm.get_group_vars(src_gitlab_url, src_token, src_group_id): glm.create_group_var(target_gitlab_url, target_token, var, target_group_id) if __name__ == \"__main__\":", "''' click.echo(f\"Fetching all project SSH URLs from {gitlab_url}...\") csv.writelines([f\"{url},\\n\" for url in glm.get_project_urls(gitlab_url,", "if it already exists ''' click.echo(f\"Fetching all project SSH URLs from {gitlab_url}...\") csv.writelines([f\"{url},\\n\"", "target_group, src_gitlab_url, target_gitlab_url, src_token, target_token): ''' migrate group variables from 1+ groups on", "target_gitlab_url, src_token, target_token): ''' migrate group variables from 1+ groups on one host", "a single group on another host ''' if src_group: src_group_id = glm._get_namespace_id(src_gitlab_url, src_group,", "target base url in the second. target base url MUST be fleshed out.", "another host ''' if src_group: src_group_id = glm._get_namespace_id(src_gitlab_url, src_group, src_token) else: src_group_id =", "fleshed out. eg: `https://gitlab.example.com/` or `<EMAIL>:` target_token must be an API-level private token", "type=click.STRING) @click.argument('target_token', type=click.STRING) def from_csv(csv, target_base_url, target_token): ''' read in repos to action", "the target server ''' for line in csv.readlines(): old_url, target_group = [string.strip() for", "on {old_url}...\") glm.migrate_repo(old_url, target_base_url, target_group, target_token) @projects.command() @click.argument('csv', type=click.File('w')) @click.argument('gitlab_url', type=click.STRING) @click.argument('token', type=click.STRING)", "it already exists ''' click.echo(f\"Fetching all project SSH URLs from {gitlab_url}...\") csv.writelines([f\"{url},\\n\" for", "type=click.STRING) @click.argument('new_base_url', type=click.STRING) @click.argument('old_base_url', type=click.STRING) @click.argument('target_group', type=click.STRING) @click.option('set_as_origin', '--set-as-origin/--set-as-new', default=True) def update_local(path, new_base_url,", "child_path in os.listdir(path): if os.path.isdir(child_path) and os.path.isdir(f\"{child_path}/.git\"): glm.update_local_repo(child_path, old_base_url, new_base_url, target_group, set_as_origin) @cli.group()", "migrate vars from all groups\") @click.argument('target_group', type=click.STRING) @click.argument('src_gitlab_url', type=click.STRING) @click.argument('target_gitlab_url', type=click.STRING) @click.argument('src_token', type=click.STRING)", "silently overwrite the specified file if it already exists ''' click.echo(f\"Fetching all project", "@click.argument('src_gitlab_url', type=click.STRING) @click.argument('target_gitlab_url', type=click.STRING) @click.argument('src_token', type=click.STRING) @click.argument('target_token', type=click.STRING) def migrate(src_group, target_group, src_gitlab_url, target_gitlab_url,", "groups on one host to a single group on another host ''' if", "type=click.STRING) def to_csv(csv, gitlab_url, token): ''' get the SSH url for all projects", "API-level private token valid on the target server ''' for line in csv.readlines():", "host ''' if src_group: src_group_id = glm._get_namespace_id(src_gitlab_url, src_group, src_token) else: src_group_id = None", "for all projects (except archived projects) and write them to a (single-column) csv.", "SSH URLs from {gitlab_url}...\") csv.writelines([f\"{url},\\n\" for url in glm.get_project_urls(gitlab_url, token)]) click.echo(\"Done.\") @projects.command() @click.argument('path',", "projects(): \"\"\"Commands for migrating projects.\"\"\" return 0 @projects.command() @click.argument('csv', type=click.File('r')) @click.argument('target_base_url', type=click.STRING) @click.argument('target_token',", "and write them to a (single-column) csv. WARNING: this will silently overwrite the", "a csv, migrate to target_base_url csv must contain two columns: source url in", "@click.argument('target_gitlab_url', type=click.STRING) @click.argument('src_token', type=click.STRING) @click.argument('target_token', type=click.STRING) def migrate(src_group, target_group, src_gitlab_url, target_gitlab_url, src_token, target_token):", "target_token) @projects.command() @click.argument('csv', type=click.File('w')) @click.argument('gitlab_url', type=click.STRING) @click.argument('token', type=click.STRING) def to_csv(csv, gitlab_url, token): '''", "old_base_url, target_group, set_as_origin): for child_path in os.listdir(path): if os.path.isdir(child_path) and os.path.isdir(f\"{child_path}/.git\"): glm.update_local_repo(child_path, old_base_url,", "source url in the first, and target base url in the second. target", "click.echo(f\"working on {old_url}...\") glm.migrate_repo(old_url, target_base_url, target_group, target_token) @projects.command() @click.argument('csv', type=click.File('w')) @click.argument('gitlab_url', type=click.STRING) @click.argument('token',", "glm.migrate_repo(old_url, target_base_url, target_group, target_token) @projects.command() @click.argument('csv', type=click.File('w')) @click.argument('gitlab_url', type=click.STRING) @click.argument('token', type=click.STRING) def to_csv(csv,", "for url in glm.get_project_urls(gitlab_url, token)]) click.echo(\"Done.\") @projects.command() @click.argument('path', type=click.STRING) @click.argument('new_base_url', type=click.STRING) @click.argument('old_base_url', type=click.STRING)", "set_as_origin) @cli.group() def variables(): \"\"\"Commands for migrating group variables.\"\"\" return 0 @variables.command() @click.option('src_group',", "target_token): ''' migrate group variables from 1+ groups on one host to a", "None target_group_id = glm._get_namespace_id(target_gitlab_url, target_group, target_token) for var in glm.get_group_vars(src_gitlab_url, src_token, src_group_id): glm.create_group_var(target_gitlab_url,", "(single-column) csv. WARNING: this will silently overwrite the specified file if it already", "the SSH url for all projects (except archived projects) and write them to", "coding: utf-8 -*- \"\"\"Console script for gitlab_migration.\"\"\" import os import sys import click", "server ''' for line in csv.readlines(): old_url, target_group = [string.strip() for string in", "token): ''' get the SSH url for all projects (except archived projects) and", "will silently overwrite the specified file if it already exists ''' click.echo(f\"Fetching all", "project SSH URLs from {gitlab_url}...\") csv.writelines([f\"{url},\\n\" for url in glm.get_project_urls(gitlab_url, token)]) click.echo(\"Done.\") @projects.command()", "for gitlab_migration.\"\"\" import os import sys import click from gitlab_migration import gitlab_migration as", "\"\"\"Commands for migrating projects.\"\"\" return 0 @projects.command() @click.argument('csv', type=click.File('r')) @click.argument('target_base_url', type=click.STRING) @click.argument('target_token', type=click.STRING)", "{old_url}...\") glm.migrate_repo(old_url, target_base_url, target_group, target_token) @projects.command() @click.argument('csv', type=click.File('w')) @click.argument('gitlab_url', type=click.STRING) @click.argument('token', type=click.STRING) def", "WARNING: this will silently overwrite the specified file if it already exists '''", "type=click.STRING) @click.argument('target_group', type=click.STRING) @click.option('set_as_origin', '--set-as-origin/--set-as-new', default=True) def update_local(path, new_base_url, old_base_url, target_group, set_as_origin): for", "and os.path.isdir(f\"{child_path}/.git\"): glm.update_local_repo(child_path, old_base_url, new_base_url, target_group, set_as_origin) @cli.group() def variables(): \"\"\"Commands for migrating", "csv. WARNING: this will silently overwrite the specified file if it already exists", "@click.argument('target_base_url', type=click.STRING) @click.argument('target_token', type=click.STRING) def from_csv(csv, target_base_url, target_token): ''' read in repos to", "''' if src_group: src_group_id = glm._get_namespace_id(src_gitlab_url, src_group, src_token) else: src_group_id = None target_group_id", "already exists ''' click.echo(f\"Fetching all project SSH URLs from {gitlab_url}...\") csv.writelines([f\"{url},\\n\" for url", "csv must contain two columns: source url in the first, and target base", "@projects.command() @click.argument('csv', type=click.File('w')) @click.argument('gitlab_url', type=click.STRING) @click.argument('token', type=click.STRING) def to_csv(csv, gitlab_url, token): ''' get", "if os.path.isdir(child_path) and os.path.isdir(f\"{child_path}/.git\"): glm.update_local_repo(child_path, old_base_url, new_base_url, target_group, set_as_origin) @cli.group() def variables(): \"\"\"Commands", "all projects (except archived projects) and write them to a (single-column) csv. WARNING:", "variables from 1+ groups on one host to a single group on another", "base url in the second. target base url MUST be fleshed out. eg:", "MUST be fleshed out. eg: `https://gitlab.example.com/` or `<EMAIL>:` target_token must be an API-level", "@cli.group() def projects(): \"\"\"Commands for migrating projects.\"\"\" return 0 @projects.command() @click.argument('csv', type=click.File('r')) @click.argument('target_base_url',", "out. eg: `https://gitlab.example.com/` or `<EMAIL>:` target_token must be an API-level private token valid", "line in csv.readlines(): old_url, target_group = [string.strip() for string in line.split(',')] click.echo(f\"working on", "'--source-group', default=None, type=click.STRING, help=\"Leave blank to migrate vars from all groups\") @click.argument('target_group', type=click.STRING)", "group on another host ''' if src_group: src_group_id = glm._get_namespace_id(src_gitlab_url, src_group, src_token) else:", "gitlab_migration as glm @click.group() def cli(): pass @cli.group() def projects(): \"\"\"Commands for migrating", "type=click.STRING, help=\"Leave blank to migrate vars from all groups\") @click.argument('target_group', type=click.STRING) @click.argument('src_gitlab_url', type=click.STRING)", "\"\"\"Console script for gitlab_migration.\"\"\" import os import sys import click from gitlab_migration import", "variables(): \"\"\"Commands for migrating group variables.\"\"\" return 0 @variables.command() @click.option('src_group', '--source-group', default=None, type=click.STRING,", "''' for line in csv.readlines(): old_url, target_group = [string.strip() for string in line.split(',')]", "this will silently overwrite the specified file if it already exists ''' click.echo(f\"Fetching", "src_token, src_group_id): glm.create_group_var(target_gitlab_url, target_token, var, target_group_id) if __name__ == \"__main__\": sys.exit(cli()) # pragma:", "[string.strip() for string in line.split(',')] click.echo(f\"working on {old_url}...\") glm.migrate_repo(old_url, target_base_url, target_group, target_token) @projects.command()", "the first, and target base url in the second. target base url MUST", "sys import click from gitlab_migration import gitlab_migration as glm @click.group() def cli(): pass", "@projects.command() @click.argument('path', type=click.STRING) @click.argument('new_base_url', type=click.STRING) @click.argument('old_base_url', type=click.STRING) @click.argument('target_group', type=click.STRING) @click.option('set_as_origin', '--set-as-origin/--set-as-new', default=True) def", "url in the first, and target base url in the second. target base", "from {gitlab_url}...\") csv.writelines([f\"{url},\\n\" for url in glm.get_project_urls(gitlab_url, token)]) click.echo(\"Done.\") @projects.command() @click.argument('path', type=click.STRING) @click.argument('new_base_url',", "@click.argument('csv', type=click.File('w')) @click.argument('gitlab_url', type=click.STRING) @click.argument('token', type=click.STRING) def to_csv(csv, gitlab_url, token): ''' get the", "(except archived projects) and write them to a (single-column) csv. WARNING: this will", "url for all projects (except archived projects) and write them to a (single-column)", "all project SSH URLs from {gitlab_url}...\") csv.writelines([f\"{url},\\n\" for url in glm.get_project_urls(gitlab_url, token)]) click.echo(\"Done.\")", "glm._get_namespace_id(src_gitlab_url, src_group, src_token) else: src_group_id = None target_group_id = glm._get_namespace_id(target_gitlab_url, target_group, target_token) for", "specified file if it already exists ''' click.echo(f\"Fetching all project SSH URLs from", "token)]) click.echo(\"Done.\") @projects.command() @click.argument('path', type=click.STRING) @click.argument('new_base_url', type=click.STRING) @click.argument('old_base_url', type=click.STRING) @click.argument('target_group', type=click.STRING) @click.option('set_as_origin', '--set-as-origin/--set-as-new',", "be an API-level private token valid on the target server ''' for line", "must contain two columns: source url in the first, and target base url", "string in line.split(',')] click.echo(f\"working on {old_url}...\") glm.migrate_repo(old_url, target_base_url, target_group, target_token) @projects.command() @click.argument('csv', type=click.File('w'))", "else: src_group_id = None target_group_id = glm._get_namespace_id(target_gitlab_url, target_group, target_token) for var in glm.get_group_vars(src_gitlab_url,", "@click.argument('path', type=click.STRING) @click.argument('new_base_url', type=click.STRING) @click.argument('old_base_url', type=click.STRING) @click.argument('target_group', type=click.STRING) @click.option('set_as_origin', '--set-as-origin/--set-as-new', default=True) def update_local(path,", "contain two columns: source url in the first, and target base url in", "def projects(): \"\"\"Commands for migrating projects.\"\"\" return 0 @projects.command() @click.argument('csv', type=click.File('r')) @click.argument('target_base_url', type=click.STRING)", "action from a csv, migrate to target_base_url csv must contain two columns: source", "`<EMAIL>:` target_token must be an API-level private token valid on the target server", "migrating group variables.\"\"\" return 0 @variables.command() @click.option('src_group', '--source-group', default=None, type=click.STRING, help=\"Leave blank to", "glm.get_group_vars(src_gitlab_url, src_token, src_group_id): glm.create_group_var(target_gitlab_url, target_token, var, target_group_id) if __name__ == \"__main__\": sys.exit(cli()) #", "\"\"\"Commands for migrating group variables.\"\"\" return 0 @variables.command() @click.option('src_group', '--source-group', default=None, type=click.STRING, help=\"Leave", "''' read in repos to action from a csv, migrate to target_base_url csv", "@cli.group() def variables(): \"\"\"Commands for migrating group variables.\"\"\" return 0 @variables.command() @click.option('src_group', '--source-group',", "target_base_url, target_token): ''' read in repos to action from a csv, migrate to", "return 0 @variables.command() @click.option('src_group', '--source-group', default=None, type=click.STRING, help=\"Leave blank to migrate vars from", "from 1+ groups on one host to a single group on another host", "base url MUST be fleshed out. eg: `https://gitlab.example.com/` or `<EMAIL>:` target_token must be", "as glm @click.group() def cli(): pass @cli.group() def projects(): \"\"\"Commands for migrating projects.\"\"\"", "script for gitlab_migration.\"\"\" import os import sys import click from gitlab_migration import gitlab_migration", "gitlab_migration.\"\"\" import os import sys import click from gitlab_migration import gitlab_migration as glm", "must be an API-level private token valid on the target server ''' for", "@click.argument('new_base_url', type=click.STRING) @click.argument('old_base_url', type=click.STRING) @click.argument('target_group', type=click.STRING) @click.option('set_as_origin', '--set-as-origin/--set-as-new', default=True) def update_local(path, new_base_url, old_base_url,", "type=click.STRING) @click.argument('src_gitlab_url', type=click.STRING) @click.argument('target_gitlab_url', type=click.STRING) @click.argument('src_token', type=click.STRING) @click.argument('target_token', type=click.STRING) def migrate(src_group, target_group, src_gitlab_url,", "@projects.command() @click.argument('csv', type=click.File('r')) @click.argument('target_base_url', type=click.STRING) @click.argument('target_token', type=click.STRING) def from_csv(csv, target_base_url, target_token): ''' read", "if src_group: src_group_id = glm._get_namespace_id(src_gitlab_url, src_group, src_token) else: src_group_id = None target_group_id =", "SSH url for all projects (except archived projects) and write them to a", "vars from all groups\") @click.argument('target_group', type=click.STRING) @click.argument('src_gitlab_url', type=click.STRING) @click.argument('target_gitlab_url', type=click.STRING) @click.argument('src_token', type=click.STRING) @click.argument('target_token',", "type=click.STRING) @click.argument('src_token', type=click.STRING) @click.argument('target_token', type=click.STRING) def migrate(src_group, target_group, src_gitlab_url, target_gitlab_url, src_token, target_token): '''", "def from_csv(csv, target_base_url, target_token): ''' read in repos to action from a csv,", "for child_path in os.listdir(path): if os.path.isdir(child_path) and os.path.isdir(f\"{child_path}/.git\"): glm.update_local_repo(child_path, old_base_url, new_base_url, target_group, set_as_origin)", "= None target_group_id = glm._get_namespace_id(target_gitlab_url, target_group, target_token) for var in glm.get_group_vars(src_gitlab_url, src_token, src_group_id):", "src_group, src_token) else: src_group_id = None target_group_id = glm._get_namespace_id(target_gitlab_url, target_group, target_token) for var", "glm.get_project_urls(gitlab_url, token)]) click.echo(\"Done.\") @projects.command() @click.argument('path', type=click.STRING) @click.argument('new_base_url', type=click.STRING) @click.argument('old_base_url', type=click.STRING) @click.argument('target_group', type=click.STRING) @click.option('set_as_origin',", "glm @click.group() def cli(): pass @cli.group() def projects(): \"\"\"Commands for migrating projects.\"\"\" return", "= glm._get_namespace_id(src_gitlab_url, src_group, src_token) else: src_group_id = None target_group_id = glm._get_namespace_id(target_gitlab_url, target_group, target_token)", "for migrating projects.\"\"\" return 0 @projects.command() @click.argument('csv', type=click.File('r')) @click.argument('target_base_url', type=click.STRING) @click.argument('target_token', type=click.STRING) def", "in glm.get_project_urls(gitlab_url, token)]) click.echo(\"Done.\") @projects.command() @click.argument('path', type=click.STRING) @click.argument('new_base_url', type=click.STRING) @click.argument('old_base_url', type=click.STRING) @click.argument('target_group', type=click.STRING)", "type=click.STRING) @click.option('set_as_origin', '--set-as-origin/--set-as-new', default=True) def update_local(path, new_base_url, old_base_url, target_group, set_as_origin): for child_path in", "csv, migrate to target_base_url csv must contain two columns: source url in the", "@click.group() def cli(): pass @cli.group() def projects(): \"\"\"Commands for migrating projects.\"\"\" return 0", "default=True) def update_local(path, new_base_url, old_base_url, target_group, set_as_origin): for child_path in os.listdir(path): if os.path.isdir(child_path)", "cli(): pass @cli.group() def projects(): \"\"\"Commands for migrating projects.\"\"\" return 0 @projects.command() @click.argument('csv',", "target base url MUST be fleshed out. eg: `https://gitlab.example.com/` or `<EMAIL>:` target_token must", "target_base_url, target_group, target_token) @projects.command() @click.argument('csv', type=click.File('w')) @click.argument('gitlab_url', type=click.STRING) @click.argument('token', type=click.STRING) def to_csv(csv, gitlab_url,", "on one host to a single group on another host ''' if src_group:", "file if it already exists ''' click.echo(f\"Fetching all project SSH URLs from {gitlab_url}...\")", "`https://gitlab.example.com/` or `<EMAIL>:` target_token must be an API-level private token valid on the", "old_base_url, new_base_url, target_group, set_as_origin) @cli.group() def variables(): \"\"\"Commands for migrating group variables.\"\"\" return", "src_token, target_token): ''' migrate group variables from 1+ groups on one host to", "csv.readlines(): old_url, target_group = [string.strip() for string in line.split(',')] click.echo(f\"working on {old_url}...\") glm.migrate_repo(old_url,", "src_group: src_group_id = glm._get_namespace_id(src_gitlab_url, src_group, src_token) else: src_group_id = None target_group_id = glm._get_namespace_id(target_gitlab_url,", "target_group, target_token) @projects.command() @click.argument('csv', type=click.File('w')) @click.argument('gitlab_url', type=click.STRING) @click.argument('token', type=click.STRING) def to_csv(csv, gitlab_url, token):", "on another host ''' if src_group: src_group_id = glm._get_namespace_id(src_gitlab_url, src_group, src_token) else: src_group_id", "src_group_id): glm.create_group_var(target_gitlab_url, target_token, var, target_group_id) if __name__ == \"__main__\": sys.exit(cli()) # pragma: no", "host to a single group on another host ''' if src_group: src_group_id =", "url in the second. target base url MUST be fleshed out. eg: `https://gitlab.example.com/`", "group variables from 1+ groups on one host to a single group on", "csv.writelines([f\"{url},\\n\" for url in glm.get_project_urls(gitlab_url, token)]) click.echo(\"Done.\") @projects.command() @click.argument('path', type=click.STRING) @click.argument('new_base_url', type=click.STRING) @click.argument('old_base_url',", "from_csv(csv, target_base_url, target_token): ''' read in repos to action from a csv, migrate", "def variables(): \"\"\"Commands for migrating group variables.\"\"\" return 0 @variables.command() @click.option('src_group', '--source-group', default=None,", "all groups\") @click.argument('target_group', type=click.STRING) @click.argument('src_gitlab_url', type=click.STRING) @click.argument('target_gitlab_url', type=click.STRING) @click.argument('src_token', type=click.STRING) @click.argument('target_token', type=click.STRING) def", "@click.option('set_as_origin', '--set-as-origin/--set-as-new', default=True) def update_local(path, new_base_url, old_base_url, target_group, set_as_origin): for child_path in os.listdir(path):", "type=click.STRING) def migrate(src_group, target_group, src_gitlab_url, target_gitlab_url, src_token, target_token): ''' migrate group variables from", "= glm._get_namespace_id(target_gitlab_url, target_group, target_token) for var in glm.get_group_vars(src_gitlab_url, src_token, src_group_id): glm.create_group_var(target_gitlab_url, target_token, var,", "type=click.STRING) @click.argument('old_base_url', type=click.STRING) @click.argument('target_group', type=click.STRING) @click.option('set_as_origin', '--set-as-origin/--set-as-new', default=True) def update_local(path, new_base_url, old_base_url, target_group,", "target_token): ''' read in repos to action from a csv, migrate to target_base_url", "target_token) for var in glm.get_group_vars(src_gitlab_url, src_token, src_group_id): glm.create_group_var(target_gitlab_url, target_token, var, target_group_id) if __name__", "variables.\"\"\" return 0 @variables.command() @click.option('src_group', '--source-group', default=None, type=click.STRING, help=\"Leave blank to migrate vars", "@variables.command() @click.option('src_group', '--source-group', default=None, type=click.STRING, help=\"Leave blank to migrate vars from all groups\")", "# -*- coding: utf-8 -*- \"\"\"Console script for gitlab_migration.\"\"\" import os import sys", "to_csv(csv, gitlab_url, token): ''' get the SSH url for all projects (except archived", "exists ''' click.echo(f\"Fetching all project SSH URLs from {gitlab_url}...\") csv.writelines([f\"{url},\\n\" for url in", "for line in csv.readlines(): old_url, target_group = [string.strip() for string in line.split(',')] click.echo(f\"working", "import sys import click from gitlab_migration import gitlab_migration as glm @click.group() def cli():", "in os.listdir(path): if os.path.isdir(child_path) and os.path.isdir(f\"{child_path}/.git\"): glm.update_local_repo(child_path, old_base_url, new_base_url, target_group, set_as_origin) @cli.group() def", "token valid on the target server ''' for line in csv.readlines(): old_url, target_group", "os.path.isdir(child_path) and os.path.isdir(f\"{child_path}/.git\"): glm.update_local_repo(child_path, old_base_url, new_base_url, target_group, set_as_origin) @cli.group() def variables(): \"\"\"Commands for", "-*- coding: utf-8 -*- \"\"\"Console script for gitlab_migration.\"\"\" import os import sys import", "or `<EMAIL>:` target_token must be an API-level private token valid on the target", "to target_base_url csv must contain two columns: source url in the first, and", "0 @projects.command() @click.argument('csv', type=click.File('r')) @click.argument('target_base_url', type=click.STRING) @click.argument('target_token', type=click.STRING) def from_csv(csv, target_base_url, target_token): '''", "be fleshed out. eg: `https://gitlab.example.com/` or `<EMAIL>:` target_token must be an API-level private", "read in repos to action from a csv, migrate to target_base_url csv must", "in csv.readlines(): old_url, target_group = [string.strip() for string in line.split(',')] click.echo(f\"working on {old_url}...\")", "target server ''' for line in csv.readlines(): old_url, target_group = [string.strip() for string", "type=click.File('w')) @click.argument('gitlab_url', type=click.STRING) @click.argument('token', type=click.STRING) def to_csv(csv, gitlab_url, token): ''' get the SSH", "two columns: source url in the first, and target base url in the", "help=\"Leave blank to migrate vars from all groups\") @click.argument('target_group', type=click.STRING) @click.argument('src_gitlab_url', type=click.STRING) @click.argument('target_gitlab_url',", "overwrite the specified file if it already exists ''' click.echo(f\"Fetching all project SSH", "from all groups\") @click.argument('target_group', type=click.STRING) @click.argument('src_gitlab_url', type=click.STRING) @click.argument('target_gitlab_url', type=click.STRING) @click.argument('src_token', type=click.STRING) @click.argument('target_token', type=click.STRING)", "migrate to target_base_url csv must contain two columns: source url in the first,", "private token valid on the target server ''' for line in csv.readlines(): old_url,", "to a (single-column) csv. WARNING: this will silently overwrite the specified file if", "def migrate(src_group, target_group, src_gitlab_url, target_gitlab_url, src_token, target_token): ''' migrate group variables from 1+", "-*- \"\"\"Console script for gitlab_migration.\"\"\" import os import sys import click from gitlab_migration", "def to_csv(csv, gitlab_url, token): ''' get the SSH url for all projects (except", "target_token must be an API-level private token valid on the target server '''", "type=click.File('r')) @click.argument('target_base_url', type=click.STRING) @click.argument('target_token', type=click.STRING) def from_csv(csv, target_base_url, target_token): ''' read in repos", "valid on the target server ''' for line in csv.readlines(): old_url, target_group =", "target_group, set_as_origin) @cli.group() def variables(): \"\"\"Commands for migrating group variables.\"\"\" return 0 @variables.command()", "target_group, target_token) for var in glm.get_group_vars(src_gitlab_url, src_token, src_group_id): glm.create_group_var(target_gitlab_url, target_token, var, target_group_id) if", "type=click.STRING) @click.argument('target_token', type=click.STRING) def migrate(src_group, target_group, src_gitlab_url, target_gitlab_url, src_token, target_token): ''' migrate group", "glm._get_namespace_id(target_gitlab_url, target_group, target_token) for var in glm.get_group_vars(src_gitlab_url, src_token, src_group_id): glm.create_group_var(target_gitlab_url, target_token, var, target_group_id)", "1+ groups on one host to a single group on another host '''", "in glm.get_group_vars(src_gitlab_url, src_token, src_group_id): glm.create_group_var(target_gitlab_url, target_token, var, target_group_id) if __name__ == \"__main__\": sys.exit(cli())", "target_group, set_as_origin): for child_path in os.listdir(path): if os.path.isdir(child_path) and os.path.isdir(f\"{child_path}/.git\"): glm.update_local_repo(child_path, old_base_url, new_base_url,", "target_base_url csv must contain two columns: source url in the first, and target", "src_group_id = glm._get_namespace_id(src_gitlab_url, src_group, src_token) else: src_group_id = None target_group_id = glm._get_namespace_id(target_gitlab_url, target_group,", "src_token) else: src_group_id = None target_group_id = glm._get_namespace_id(target_gitlab_url, target_group, target_token) for var in", "projects (except archived projects) and write them to a (single-column) csv. WARNING: this", "projects) and write them to a (single-column) csv. WARNING: this will silently overwrite", "migrate(src_group, target_group, src_gitlab_url, target_gitlab_url, src_token, target_token): ''' migrate group variables from 1+ groups", "columns: source url in the first, and target base url in the second.", "for var in glm.get_group_vars(src_gitlab_url, src_token, src_group_id): glm.create_group_var(target_gitlab_url, target_token, var, target_group_id) if __name__ ==", "os.listdir(path): if os.path.isdir(child_path) and os.path.isdir(f\"{child_path}/.git\"): glm.update_local_repo(child_path, old_base_url, new_base_url, target_group, set_as_origin) @cli.group() def variables():", "old_url, target_group = [string.strip() for string in line.split(',')] click.echo(f\"working on {old_url}...\") glm.migrate_repo(old_url, target_base_url,", "= [string.strip() for string in line.split(',')] click.echo(f\"working on {old_url}...\") glm.migrate_repo(old_url, target_base_url, target_group, target_token)", "@click.argument('target_token', type=click.STRING) def migrate(src_group, target_group, src_gitlab_url, target_gitlab_url, src_token, target_token): ''' migrate group variables", "them to a (single-column) csv. WARNING: this will silently overwrite the specified file", "new_base_url, old_base_url, target_group, set_as_origin): for child_path in os.listdir(path): if os.path.isdir(child_path) and os.path.isdir(f\"{child_path}/.git\"): glm.update_local_repo(child_path,", "click from gitlab_migration import gitlab_migration as glm @click.group() def cli(): pass @cli.group() def", "eg: `https://gitlab.example.com/` or `<EMAIL>:` target_token must be an API-level private token valid on", "type=click.STRING) @click.argument('token', type=click.STRING) def to_csv(csv, gitlab_url, token): ''' get the SSH url for", "to migrate vars from all groups\") @click.argument('target_group', type=click.STRING) @click.argument('src_gitlab_url', type=click.STRING) @click.argument('target_gitlab_url', type=click.STRING) @click.argument('src_token',", "@click.argument('gitlab_url', type=click.STRING) @click.argument('token', type=click.STRING) def to_csv(csv, gitlab_url, token): ''' get the SSH url", "groups\") @click.argument('target_group', type=click.STRING) @click.argument('src_gitlab_url', type=click.STRING) @click.argument('target_gitlab_url', type=click.STRING) @click.argument('src_token', type=click.STRING) @click.argument('target_token', type=click.STRING) def migrate(src_group,", "@click.argument('target_group', type=click.STRING) @click.argument('src_gitlab_url', type=click.STRING) @click.argument('target_gitlab_url', type=click.STRING) @click.argument('src_token', type=click.STRING) @click.argument('target_token', type=click.STRING) def migrate(src_group, target_group,", "second. target base url MUST be fleshed out. eg: `https://gitlab.example.com/` or `<EMAIL>:` target_token", "get the SSH url for all projects (except archived projects) and write them", "new_base_url, target_group, set_as_origin) @cli.group() def variables(): \"\"\"Commands for migrating group variables.\"\"\" return 0", "src_group_id = None target_group_id = glm._get_namespace_id(target_gitlab_url, target_group, target_token) for var in glm.get_group_vars(src_gitlab_url, src_token,", "one host to a single group on another host ''' if src_group: src_group_id", "line.split(',')] click.echo(f\"working on {old_url}...\") glm.migrate_repo(old_url, target_base_url, target_group, target_token) @projects.command() @click.argument('csv', type=click.File('w')) @click.argument('gitlab_url', type=click.STRING)", "in line.split(',')] click.echo(f\"working on {old_url}...\") glm.migrate_repo(old_url, target_base_url, target_group, target_token) @projects.command() @click.argument('csv', type=click.File('w')) @click.argument('gitlab_url',", "import click from gitlab_migration import gitlab_migration as glm @click.group() def cli(): pass @cli.group()", "url in glm.get_project_urls(gitlab_url, token)]) click.echo(\"Done.\") @projects.command() @click.argument('path', type=click.STRING) @click.argument('new_base_url', type=click.STRING) @click.argument('old_base_url', type=click.STRING) @click.argument('target_group',", "in the first, and target base url in the second. target base url", "URLs from {gitlab_url}...\") csv.writelines([f\"{url},\\n\" for url in glm.get_project_urls(gitlab_url, token)]) click.echo(\"Done.\") @projects.command() @click.argument('path', type=click.STRING)", "@click.argument('target_group', type=click.STRING) @click.option('set_as_origin', '--set-as-origin/--set-as-new', default=True) def update_local(path, new_base_url, old_base_url, target_group, set_as_origin): for child_path", "the second. target base url MUST be fleshed out. eg: `https://gitlab.example.com/` or `<EMAIL>:`", "click.echo(\"Done.\") @projects.command() @click.argument('path', type=click.STRING) @click.argument('new_base_url', type=click.STRING) @click.argument('old_base_url', type=click.STRING) @click.argument('target_group', type=click.STRING) @click.option('set_as_origin', '--set-as-origin/--set-as-new', default=True)", "url MUST be fleshed out. eg: `https://gitlab.example.com/` or `<EMAIL>:` target_token must be an", "os.path.isdir(f\"{child_path}/.git\"): glm.update_local_repo(child_path, old_base_url, new_base_url, target_group, set_as_origin) @cli.group() def variables(): \"\"\"Commands for migrating group", "a (single-column) csv. WARNING: this will silently overwrite the specified file if it", "os import sys import click from gitlab_migration import gitlab_migration as glm @click.group() def", "@click.argument('old_base_url', type=click.STRING) @click.argument('target_group', type=click.STRING) @click.option('set_as_origin', '--set-as-origin/--set-as-new', default=True) def update_local(path, new_base_url, old_base_url, target_group, set_as_origin):", "migrate group variables from 1+ groups on one host to a single group", "import os import sys import click from gitlab_migration import gitlab_migration as glm @click.group()", "target_group = [string.strip() for string in line.split(',')] click.echo(f\"working on {old_url}...\") glm.migrate_repo(old_url, target_base_url, target_group,", "migrating projects.\"\"\" return 0 @projects.command() @click.argument('csv', type=click.File('r')) @click.argument('target_base_url', type=click.STRING) @click.argument('target_token', type=click.STRING) def from_csv(csv,", "'--set-as-origin/--set-as-new', default=True) def update_local(path, new_base_url, old_base_url, target_group, set_as_origin): for child_path in os.listdir(path): if", "type=click.STRING) @click.argument('target_gitlab_url', type=click.STRING) @click.argument('src_token', type=click.STRING) @click.argument('target_token', type=click.STRING) def migrate(src_group, target_group, src_gitlab_url, target_gitlab_url, src_token,", "in the second. target base url MUST be fleshed out. eg: `https://gitlab.example.com/` or", "def update_local(path, new_base_url, old_base_url, target_group, set_as_origin): for child_path in os.listdir(path): if os.path.isdir(child_path) and", "first, and target base url in the second. target base url MUST be", "gitlab_migration import gitlab_migration as glm @click.group() def cli(): pass @cli.group() def projects(): \"\"\"Commands", "type=click.STRING) def from_csv(csv, target_base_url, target_token): ''' read in repos to action from a", "for migrating group variables.\"\"\" return 0 @variables.command() @click.option('src_group', '--source-group', default=None, type=click.STRING, help=\"Leave blank", "pass @cli.group() def projects(): \"\"\"Commands for migrating projects.\"\"\" return 0 @projects.command() @click.argument('csv', type=click.File('r'))", "the specified file if it already exists ''' click.echo(f\"Fetching all project SSH URLs", "src_gitlab_url, target_gitlab_url, src_token, target_token): ''' migrate group variables from 1+ groups on one", "@click.argument('token', type=click.STRING) def to_csv(csv, gitlab_url, token): ''' get the SSH url for all", "import gitlab_migration as glm @click.group() def cli(): pass @cli.group() def projects(): \"\"\"Commands for", "to action from a csv, migrate to target_base_url csv must contain two columns:", "write them to a (single-column) csv. WARNING: this will silently overwrite the specified", "@click.option('src_group', '--source-group', default=None, type=click.STRING, help=\"Leave blank to migrate vars from all groups\") @click.argument('target_group',", "@click.argument('src_token', type=click.STRING) @click.argument('target_token', type=click.STRING) def migrate(src_group, target_group, src_gitlab_url, target_gitlab_url, src_token, target_token): ''' migrate", "default=None, type=click.STRING, help=\"Leave blank to migrate vars from all groups\") @click.argument('target_group', type=click.STRING) @click.argument('src_gitlab_url',", "click.echo(f\"Fetching all project SSH URLs from {gitlab_url}...\") csv.writelines([f\"{url},\\n\" for url in glm.get_project_urls(gitlab_url, token)])", "update_local(path, new_base_url, old_base_url, target_group, set_as_origin): for child_path in os.listdir(path): if os.path.isdir(child_path) and os.path.isdir(f\"{child_path}/.git\"):", "projects.\"\"\" return 0 @projects.command() @click.argument('csv', type=click.File('r')) @click.argument('target_base_url', type=click.STRING) @click.argument('target_token', type=click.STRING) def from_csv(csv, target_base_url,", "on the target server ''' for line in csv.readlines(): old_url, target_group = [string.strip()", "repos to action from a csv, migrate to target_base_url csv must contain two", "single group on another host ''' if src_group: src_group_id = glm._get_namespace_id(src_gitlab_url, src_group, src_token)", "from gitlab_migration import gitlab_migration as glm @click.group() def cli(): pass @cli.group() def projects():", "{gitlab_url}...\") csv.writelines([f\"{url},\\n\" for url in glm.get_project_urls(gitlab_url, token)]) click.echo(\"Done.\") @projects.command() @click.argument('path', type=click.STRING) @click.argument('new_base_url', type=click.STRING)", "glm.update_local_repo(child_path, old_base_url, new_base_url, target_group, set_as_origin) @cli.group() def variables(): \"\"\"Commands for migrating group variables.\"\"\"", "blank to migrate vars from all groups\") @click.argument('target_group', type=click.STRING) @click.argument('src_gitlab_url', type=click.STRING) @click.argument('target_gitlab_url', type=click.STRING)", "@click.argument('target_token', type=click.STRING) def from_csv(csv, target_base_url, target_token): ''' read in repos to action from", "group variables.\"\"\" return 0 @variables.command() @click.option('src_group', '--source-group', default=None, type=click.STRING, help=\"Leave blank to migrate", "@click.argument('csv', type=click.File('r')) @click.argument('target_base_url', type=click.STRING) @click.argument('target_token', type=click.STRING) def from_csv(csv, target_base_url, target_token): ''' read in", "and target base url in the second. target base url MUST be fleshed" ]
[ "from . import model log = logging.getLogger(__name__) class Relation(model.ModelEntity): async def destroy(self): raise", "= logging.getLogger(__name__) class Relation(model.ModelEntity): async def destroy(self): raise NotImplementedError() # TODO: destroy a", "import model log = logging.getLogger(__name__) class Relation(model.ModelEntity): async def destroy(self): raise NotImplementedError() #", "logging from . import model log = logging.getLogger(__name__) class Relation(model.ModelEntity): async def destroy(self):", "model log = logging.getLogger(__name__) class Relation(model.ModelEntity): async def destroy(self): raise NotImplementedError() # TODO:", "import logging from . import model log = logging.getLogger(__name__) class Relation(model.ModelEntity): async def", "<filename>juju/relation.py import logging from . import model log = logging.getLogger(__name__) class Relation(model.ModelEntity): async", "logging.getLogger(__name__) class Relation(model.ModelEntity): async def destroy(self): raise NotImplementedError() # TODO: destroy a relation", ". import model log = logging.getLogger(__name__) class Relation(model.ModelEntity): async def destroy(self): raise NotImplementedError()", "log = logging.getLogger(__name__) class Relation(model.ModelEntity): async def destroy(self): raise NotImplementedError() # TODO: destroy" ]
[ "\"\"\" Please note, this code is only for python 3+. If you are", "out_size])) biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, ) Wx_plus_b = tf.matmul(inputs, Weights) +", "this layer Weights = tf.Variable(tf.random_normal([in_size, out_size])) biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, )", "step sess.run(tf.initialize_all_variables()) for i in range(1000): pass if i % 50 == 0:", "note, this code is only for python 3+. If you are using python", "layer Weights = tf.Variable(tf.random_normal([in_size, out_size])) biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, ) Wx_plus_b", "between prediction and real data sess = tf.Session() # important step sess.run(tf.initialize_all_variables()) for", "return the output of this layer Weights = tf.Variable(tf.random_normal([in_size, out_size])) biases = tf.Variable(tf.zeros([1,", "import tensorflow as tf def add_layer(inputs, in_size, out_size, activation_function=None, ): # add one", "this code is only for python 3+. If you are using python 2+,", "the output of this layer Weights = tf.Variable(tf.random_normal([in_size, out_size])) biases = tf.Variable(tf.zeros([1, out_size])", "of this layer Weights = tf.Variable(tf.random_normal([in_size, out_size])) biases = tf.Variable(tf.zeros([1, out_size]) + 0.1,", "layer # the error between prediction and real data sess = tf.Session() #", ") return outputs # define placeholder for inputs to network # add output", "inputs to network # add output layer # the error between prediction and", "# important step sess.run(tf.initialize_all_variables()) for i in range(1000): pass if i % 50", "code accordingly. \"\"\" import tensorflow as tf def add_layer(inputs, in_size, out_size, activation_function=None, ):", "tf.Session() # important step sess.run(tf.initialize_all_variables()) for i in range(1000): pass if i %", "Weights = tf.Variable(tf.random_normal([in_size, out_size])) biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, ) Wx_plus_b =", "# define placeholder for inputs to network # add output layer # the", "in_size, out_size, activation_function=None, ): # add one more layer and return the output", "tf.Variable(tf.random_normal([in_size, out_size])) biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, ) Wx_plus_b = tf.matmul(inputs, Weights)", "= activation_function(Wx_plus_b, ) return outputs # define placeholder for inputs to network #", "network # add output layer # the error between prediction and real data", "+ 0.1, ) Wx_plus_b = tf.matmul(inputs, Weights) + biases if activation_function is None:", "Please note, this code is only for python 3+. If you are using", "# add one more layer and return the output of this layer Weights", "only for python 3+. If you are using python 2+, please modify the", "modify the code accordingly. \"\"\" import tensorflow as tf def add_layer(inputs, in_size, out_size,", "If you are using python 2+, please modify the code accordingly. \"\"\" import", ") Wx_plus_b = tf.matmul(inputs, Weights) + biases if activation_function is None: outputs =", "data sess = tf.Session() # important step sess.run(tf.initialize_all_variables()) for i in range(1000): pass", "tf def add_layer(inputs, in_size, out_size, activation_function=None, ): # add one more layer and", "Wx_plus_b = tf.matmul(inputs, Weights) + biases if activation_function is None: outputs = Wx_plus_b", "code is only for python 3+. If you are using python 2+, please", "the code accordingly. \"\"\" import tensorflow as tf def add_layer(inputs, in_size, out_size, activation_function=None,", "accordingly. \"\"\" import tensorflow as tf def add_layer(inputs, in_size, out_size, activation_function=None, ): #", "error between prediction and real data sess = tf.Session() # important step sess.run(tf.initialize_all_variables())", "output layer # the error between prediction and real data sess = tf.Session()", "if activation_function is None: outputs = Wx_plus_b else: outputs = activation_function(Wx_plus_b, ) return", "and return the output of this layer Weights = tf.Variable(tf.random_normal([in_size, out_size])) biases =", "using python 2+, please modify the code accordingly. \"\"\" import tensorflow as tf", "important step sess.run(tf.initialize_all_variables()) for i in range(1000): pass if i % 50 ==", "for inputs to network # add output layer # the error between prediction", "Wx_plus_b else: outputs = activation_function(Wx_plus_b, ) return outputs # define placeholder for inputs", "add output layer # the error between prediction and real data sess =", "2+, please modify the code accordingly. \"\"\" import tensorflow as tf def add_layer(inputs,", "python 2+, please modify the code accordingly. \"\"\" import tensorflow as tf def", "# add output layer # the error between prediction and real data sess", "more layer and return the output of this layer Weights = tf.Variable(tf.random_normal([in_size, out_size]))", "you are using python 2+, please modify the code accordingly. \"\"\" import tensorflow", "outputs # define placeholder for inputs to network # add output layer #", "and real data sess = tf.Session() # important step sess.run(tf.initialize_all_variables()) for i in", "return outputs # define placeholder for inputs to network # add output layer", "tf.Variable(tf.zeros([1, out_size]) + 0.1, ) Wx_plus_b = tf.matmul(inputs, Weights) + biases if activation_function", "3+. If you are using python 2+, please modify the code accordingly. \"\"\"", "Weights) + biases if activation_function is None: outputs = Wx_plus_b else: outputs =", "real data sess = tf.Session() # important step sess.run(tf.initialize_all_variables()) for i in range(1000):", "activation_function=None, ): # add one more layer and return the output of this", "prediction and real data sess = tf.Session() # important step sess.run(tf.initialize_all_variables()) for i", "output of this layer Weights = tf.Variable(tf.random_normal([in_size, out_size])) biases = tf.Variable(tf.zeros([1, out_size]) +", "else: outputs = activation_function(Wx_plus_b, ) return outputs # define placeholder for inputs to", "sess = tf.Session() # important step sess.run(tf.initialize_all_variables()) for i in range(1000): pass if", "one more layer and return the output of this layer Weights = tf.Variable(tf.random_normal([in_size,", "is only for python 3+. If you are using python 2+, please modify", "= Wx_plus_b else: outputs = activation_function(Wx_plus_b, ) return outputs # define placeholder for", "placeholder for inputs to network # add output layer # the error between", "the error between prediction and real data sess = tf.Session() # important step", "+ biases if activation_function is None: outputs = Wx_plus_b else: outputs = activation_function(Wx_plus_b,", "# the error between prediction and real data sess = tf.Session() # important", "biases if activation_function is None: outputs = Wx_plus_b else: outputs = activation_function(Wx_plus_b, )", "please modify the code accordingly. \"\"\" import tensorflow as tf def add_layer(inputs, in_size,", "= tf.matmul(inputs, Weights) + biases if activation_function is None: outputs = Wx_plus_b else:", "is None: outputs = Wx_plus_b else: outputs = activation_function(Wx_plus_b, ) return outputs #", "sess.run(tf.initialize_all_variables()) for i in range(1000): pass if i % 50 == 0: pass", "python 3+. If you are using python 2+, please modify the code accordingly.", "= tf.Variable(tf.random_normal([in_size, out_size])) biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, ) Wx_plus_b = tf.matmul(inputs,", "as tf def add_layer(inputs, in_size, out_size, activation_function=None, ): # add one more layer", "None: outputs = Wx_plus_b else: outputs = activation_function(Wx_plus_b, ) return outputs # define", "activation_function is None: outputs = Wx_plus_b else: outputs = activation_function(Wx_plus_b, ) return outputs", "out_size, activation_function=None, ): # add one more layer and return the output of", "add_layer(inputs, in_size, out_size, activation_function=None, ): # add one more layer and return the", "outputs = Wx_plus_b else: outputs = activation_function(Wx_plus_b, ) return outputs # define placeholder", "are using python 2+, please modify the code accordingly. \"\"\" import tensorflow as", "tf.matmul(inputs, Weights) + biases if activation_function is None: outputs = Wx_plus_b else: outputs", "to network # add output layer # the error between prediction and real", "for python 3+. If you are using python 2+, please modify the code", "= tf.Session() # important step sess.run(tf.initialize_all_variables()) for i in range(1000): pass if i", "define placeholder for inputs to network # add output layer # the error", "layer and return the output of this layer Weights = tf.Variable(tf.random_normal([in_size, out_size])) biases", "activation_function(Wx_plus_b, ) return outputs # define placeholder for inputs to network # add", "def add_layer(inputs, in_size, out_size, activation_function=None, ): # add one more layer and return", "biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, ) Wx_plus_b = tf.matmul(inputs, Weights) + biases", "outputs = activation_function(Wx_plus_b, ) return outputs # define placeholder for inputs to network", "\"\"\" import tensorflow as tf def add_layer(inputs, in_size, out_size, activation_function=None, ): # add", "): # add one more layer and return the output of this layer", "0.1, ) Wx_plus_b = tf.matmul(inputs, Weights) + biases if activation_function is None: outputs", "= tf.Variable(tf.zeros([1, out_size]) + 0.1, ) Wx_plus_b = tf.matmul(inputs, Weights) + biases if", "tensorflow as tf def add_layer(inputs, in_size, out_size, activation_function=None, ): # add one more", "add one more layer and return the output of this layer Weights =", "out_size]) + 0.1, ) Wx_plus_b = tf.matmul(inputs, Weights) + biases if activation_function is" ]
[ "# test commands without arguments info = agnid.rpc_command('getinfo') info_keys = [ 'blocks', 'connections',", "if line.startswith('testnet=1'): network = 'testnet' is_testnet = True genesis_hash = u'0000085e2ddad54c7313a28c2e96f7437e2ba9df1d5b2f3cdc3c554bf60dbe76' creds =", "os.path.normpath(os.path.join(os.path.dirname(__file__), '../test_sentinel.conf')) sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'lib')) sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..')) import config from agnid", "'test' os.environ['SENTINEL_CONFIG'] = os.path.normpath(os.path.join(os.path.dirname(__file__), '../test_sentinel.conf')) sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'lib')) sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..')) import", "= 'test' os.environ['SENTINEL_CONFIG'] = os.path.normpath(os.path.join(os.path.dirname(__file__), '../test_sentinel.conf')) sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'lib')) sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..'))", "'proxy', 'testnet', 'timeoffset', 'version', ] for key in info_keys: assert key in info", "'errors', 'protocolversion', 'proxy', 'testnet', 'timeoffset', 'version', ] for key in info_keys: assert key", "from agni_config import AgniConfig def test_agnid(): config_text = AgniConfig.slurp_config_file(config.agni_conf) network = 'mainnet' is_testnet", "network = 'mainnet' is_testnet = False genesis_hash = u'00000054f31397c25fd692a80391aa238da20c5638171b0e89a8bbf6bf7e4288' for line in config_text.split(\"\\n\"):", "'protocolversion', 'proxy', 'testnet', 'timeoffset', 'version', ] for key in info_keys: assert key in", "config from agnid import AgniDaemon from agni_config import AgniConfig def test_agnid(): config_text =", "test_agnid(): config_text = AgniConfig.slurp_config_file(config.agni_conf) network = 'mainnet' is_testnet = False genesis_hash = u'00000054f31397c25fd692a80391aa238da20c5638171b0e89a8bbf6bf7e4288'", "def test_agnid(): config_text = AgniConfig.slurp_config_file(config.agni_conf) network = 'mainnet' is_testnet = False genesis_hash =", "is_testnet = False genesis_hash = u'00000054f31397c25fd692a80391aa238da20c5638171b0e89a8bbf6bf7e4288' for line in config_text.split(\"\\n\"): if line.startswith('testnet=1'): network", "hasattr(agnid, 'rpc_connection') # Agni testnet block 0 hash == 0000085e2ddad54c7313a28c2e96f7437e2ba9df1d5b2f3cdc3c554bf60dbe76 # test commands", "] for key in info_keys: assert key in info assert info['testnet'] is is_testnet", "in info_keys: assert key in info assert info['testnet'] is is_testnet # test commands", "'rpc_connection') # Agni testnet block 0 hash == 0000085e2ddad54c7313a28c2e96f7437e2ba9df1d5b2f3cdc3c554bf60dbe76 # test commands without", "info = agnid.rpc_command('getinfo') info_keys = [ 'blocks', 'connections', 'difficulty', 'errors', 'protocolversion', 'proxy', 'testnet',", "'../test_sentinel.conf')) sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'lib')) sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..')) import config from agnid import", "block 0 hash == 0000085e2ddad54c7313a28c2e96f7437e2ba9df1d5b2f3cdc3c554bf60dbe76 # test commands without arguments info = agnid.rpc_command('getinfo')", "= agnid.rpc_command('getinfo') info_keys = [ 'blocks', 'connections', 'difficulty', 'errors', 'protocolversion', 'proxy', 'testnet', 'timeoffset',", "without arguments info = agnid.rpc_command('getinfo') info_keys = [ 'blocks', 'connections', 'difficulty', 'errors', 'protocolversion',", "os.environ['SENTINEL_ENV'] = 'test' os.environ['SENTINEL_CONFIG'] = os.path.normpath(os.path.join(os.path.dirname(__file__), '../test_sentinel.conf')) sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'lib')) sys.path.append(os.path.join(os.path.dirname(__file__), '..',", "= AgniConfig.get_rpc_creds(config_text, network) agnid = AgniDaemon(**creds) assert agnid.rpc_command is not None assert hasattr(agnid,", "commands without arguments info = agnid.rpc_command('getinfo') info_keys = [ 'blocks', 'connections', 'difficulty', 'errors',", "<gh_stars>0 import pytest import sys import os import re os.environ['SENTINEL_ENV'] = 'test' os.environ['SENTINEL_CONFIG']", "= False genesis_hash = u'00000054f31397c25fd692a80391aa238da20c5638171b0e89a8bbf6bf7e4288' for line in config_text.split(\"\\n\"): if line.startswith('testnet=1'): network =", "'timeoffset', 'version', ] for key in info_keys: assert key in info assert info['testnet']", "'blocks', 'connections', 'difficulty', 'errors', 'protocolversion', 'proxy', 'testnet', 'timeoffset', 'version', ] for key in", "import os import re os.environ['SENTINEL_ENV'] = 'test' os.environ['SENTINEL_CONFIG'] = os.path.normpath(os.path.join(os.path.dirname(__file__), '../test_sentinel.conf')) sys.path.append(os.path.join(os.path.dirname(__file__), '..',", "sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..')) import config from agnid import AgniDaemon from agni_config import AgniConfig", "'..', '..', 'lib')) sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..')) import config from agnid import AgniDaemon from", "assert agnid.rpc_command is not None assert hasattr(agnid, 'rpc_connection') # Agni testnet block 0", "agni_config import AgniConfig def test_agnid(): config_text = AgniConfig.slurp_config_file(config.agni_conf) network = 'mainnet' is_testnet =", "= u'0000085e2ddad54c7313a28c2e96f7437e2ba9df1d5b2f3cdc3c554bf60dbe76' creds = AgniConfig.get_rpc_creds(config_text, network) agnid = AgniDaemon(**creds) assert agnid.rpc_command is not", "AgniDaemon(**creds) assert agnid.rpc_command is not None assert hasattr(agnid, 'rpc_connection') # Agni testnet block", "= os.path.normpath(os.path.join(os.path.dirname(__file__), '../test_sentinel.conf')) sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'lib')) sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..')) import config from", "test commands without arguments info = agnid.rpc_command('getinfo') info_keys = [ 'blocks', 'connections', 'difficulty',", "'difficulty', 'errors', 'protocolversion', 'proxy', 'testnet', 'timeoffset', 'version', ] for key in info_keys: assert", "for line in config_text.split(\"\\n\"): if line.startswith('testnet=1'): network = 'testnet' is_testnet = True genesis_hash", "genesis_hash = u'00000054f31397c25fd692a80391aa238da20c5638171b0e89a8bbf6bf7e4288' for line in config_text.split(\"\\n\"): if line.startswith('testnet=1'): network = 'testnet' is_testnet", "in config_text.split(\"\\n\"): if line.startswith('testnet=1'): network = 'testnet' is_testnet = True genesis_hash = u'0000085e2ddad54c7313a28c2e96f7437e2ba9df1d5b2f3cdc3c554bf60dbe76'", "arguments info = agnid.rpc_command('getinfo') info_keys = [ 'blocks', 'connections', 'difficulty', 'errors', 'protocolversion', 'proxy',", "'lib')) sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..')) import config from agnid import AgniDaemon from agni_config import", "hash == 0000085e2ddad54c7313a28c2e96f7437e2ba9df1d5b2f3cdc3c554bf60dbe76 # test commands without arguments info = agnid.rpc_command('getinfo') info_keys =", "in info assert info['testnet'] is is_testnet # test commands with args assert agnid.rpc_command('getblockhash',", "from agnid import AgniDaemon from agni_config import AgniConfig def test_agnid(): config_text = AgniConfig.slurp_config_file(config.agni_conf)", "import re os.environ['SENTINEL_ENV'] = 'test' os.environ['SENTINEL_CONFIG'] = os.path.normpath(os.path.join(os.path.dirname(__file__), '../test_sentinel.conf')) sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'lib'))", "'connections', 'difficulty', 'errors', 'protocolversion', 'proxy', 'testnet', 'timeoffset', 'version', ] for key in info_keys:", "'version', ] for key in info_keys: assert key in info assert info['testnet'] is", "sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'lib')) sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..')) import config from agnid import AgniDaemon", "= True genesis_hash = u'0000085e2ddad54c7313a28c2e96f7437e2ba9df1d5b2f3cdc3c554bf60dbe76' creds = AgniConfig.get_rpc_creds(config_text, network) agnid = AgniDaemon(**creds) assert", "import pytest import sys import os import re os.environ['SENTINEL_ENV'] = 'test' os.environ['SENTINEL_CONFIG'] =", "agnid.rpc_command('getinfo') info_keys = [ 'blocks', 'connections', 'difficulty', 'errors', 'protocolversion', 'proxy', 'testnet', 'timeoffset', 'version',", "0000085e2ddad54c7313a28c2e96f7437e2ba9df1d5b2f3cdc3c554bf60dbe76 # test commands without arguments info = agnid.rpc_command('getinfo') info_keys = [ 'blocks',", "== 0000085e2ddad54c7313a28c2e96f7437e2ba9df1d5b2f3cdc3c554bf60dbe76 # test commands without arguments info = agnid.rpc_command('getinfo') info_keys = [", "u'0000085e2ddad54c7313a28c2e96f7437e2ba9df1d5b2f3cdc3c554bf60dbe76' creds = AgniConfig.get_rpc_creds(config_text, network) agnid = AgniDaemon(**creds) assert agnid.rpc_command is not None", "AgniDaemon from agni_config import AgniConfig def test_agnid(): config_text = AgniConfig.slurp_config_file(config.agni_conf) network = 'mainnet'", "assert key in info assert info['testnet'] is is_testnet # test commands with args", "genesis_hash = u'0000085e2ddad54c7313a28c2e96f7437e2ba9df1d5b2f3cdc3c554bf60dbe76' creds = AgniConfig.get_rpc_creds(config_text, network) agnid = AgniDaemon(**creds) assert agnid.rpc_command is", "'mainnet' is_testnet = False genesis_hash = u'00000054f31397c25fd692a80391aa238da20c5638171b0e89a8bbf6bf7e4288' for line in config_text.split(\"\\n\"): if line.startswith('testnet=1'):", "testnet block 0 hash == 0000085e2ddad54c7313a28c2e96f7437e2ba9df1d5b2f3cdc3c554bf60dbe76 # test commands without arguments info =", "info_keys: assert key in info assert info['testnet'] is is_testnet # test commands with", "= [ 'blocks', 'connections', 'difficulty', 'errors', 'protocolversion', 'proxy', 'testnet', 'timeoffset', 'version', ] for", "line in config_text.split(\"\\n\"): if line.startswith('testnet=1'): network = 'testnet' is_testnet = True genesis_hash =", "agnid import AgniDaemon from agni_config import AgniConfig def test_agnid(): config_text = AgniConfig.slurp_config_file(config.agni_conf) network", "= AgniDaemon(**creds) assert agnid.rpc_command is not None assert hasattr(agnid, 'rpc_connection') # Agni testnet", "# Agni testnet block 0 hash == 0000085e2ddad54c7313a28c2e96f7437e2ba9df1d5b2f3cdc3c554bf60dbe76 # test commands without arguments", "creds = AgniConfig.get_rpc_creds(config_text, network) agnid = AgniDaemon(**creds) assert agnid.rpc_command is not None assert", "network = 'testnet' is_testnet = True genesis_hash = u'0000085e2ddad54c7313a28c2e96f7437e2ba9df1d5b2f3cdc3c554bf60dbe76' creds = AgniConfig.get_rpc_creds(config_text, network)", "[ 'blocks', 'connections', 'difficulty', 'errors', 'protocolversion', 'proxy', 'testnet', 'timeoffset', 'version', ] for key", "AgniConfig def test_agnid(): config_text = AgniConfig.slurp_config_file(config.agni_conf) network = 'mainnet' is_testnet = False genesis_hash", "agnid = AgniDaemon(**creds) assert agnid.rpc_command is not None assert hasattr(agnid, 'rpc_connection') # Agni", "key in info assert info['testnet'] is is_testnet # test commands with args assert", "True genesis_hash = u'0000085e2ddad54c7313a28c2e96f7437e2ba9df1d5b2f3cdc3c554bf60dbe76' creds = AgniConfig.get_rpc_creds(config_text, network) agnid = AgniDaemon(**creds) assert agnid.rpc_command", "is not None assert hasattr(agnid, 'rpc_connection') # Agni testnet block 0 hash ==", "not None assert hasattr(agnid, 'rpc_connection') # Agni testnet block 0 hash == 0000085e2ddad54c7313a28c2e96f7437e2ba9df1d5b2f3cdc3c554bf60dbe76", "'testnet', 'timeoffset', 'version', ] for key in info_keys: assert key in info assert", "= AgniConfig.slurp_config_file(config.agni_conf) network = 'mainnet' is_testnet = False genesis_hash = u'00000054f31397c25fd692a80391aa238da20c5638171b0e89a8bbf6bf7e4288' for line", "config_text = AgniConfig.slurp_config_file(config.agni_conf) network = 'mainnet' is_testnet = False genesis_hash = u'00000054f31397c25fd692a80391aa238da20c5638171b0e89a8bbf6bf7e4288' for", "network) agnid = AgniDaemon(**creds) assert agnid.rpc_command is not None assert hasattr(agnid, 'rpc_connection') #", "0 hash == 0000085e2ddad54c7313a28c2e96f7437e2ba9df1d5b2f3cdc3c554bf60dbe76 # test commands without arguments info = agnid.rpc_command('getinfo') info_keys", "= 'mainnet' is_testnet = False genesis_hash = u'00000054f31397c25fd692a80391aa238da20c5638171b0e89a8bbf6bf7e4288' for line in config_text.split(\"\\n\"): if", "False genesis_hash = u'00000054f31397c25fd692a80391aa238da20c5638171b0e89a8bbf6bf7e4288' for line in config_text.split(\"\\n\"): if line.startswith('testnet=1'): network = 'testnet'", "pytest import sys import os import re os.environ['SENTINEL_ENV'] = 'test' os.environ['SENTINEL_CONFIG'] = os.path.normpath(os.path.join(os.path.dirname(__file__),", "= u'00000054f31397c25fd692a80391aa238da20c5638171b0e89a8bbf6bf7e4288' for line in config_text.split(\"\\n\"): if line.startswith('testnet=1'): network = 'testnet' is_testnet =", "config_text.split(\"\\n\"): if line.startswith('testnet=1'): network = 'testnet' is_testnet = True genesis_hash = u'0000085e2ddad54c7313a28c2e96f7437e2ba9df1d5b2f3cdc3c554bf60dbe76' creds", "re os.environ['SENTINEL_ENV'] = 'test' os.environ['SENTINEL_CONFIG'] = os.path.normpath(os.path.join(os.path.dirname(__file__), '../test_sentinel.conf')) sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'lib')) sys.path.append(os.path.join(os.path.dirname(__file__),", "'..', 'lib')) sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..')) import config from agnid import AgniDaemon from agni_config", "os.environ['SENTINEL_CONFIG'] = os.path.normpath(os.path.join(os.path.dirname(__file__), '../test_sentinel.conf')) sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'lib')) sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..')) import config", "AgniConfig.slurp_config_file(config.agni_conf) network = 'mainnet' is_testnet = False genesis_hash = u'00000054f31397c25fd692a80391aa238da20c5638171b0e89a8bbf6bf7e4288' for line in", "assert hasattr(agnid, 'rpc_connection') # Agni testnet block 0 hash == 0000085e2ddad54c7313a28c2e96f7437e2ba9df1d5b2f3cdc3c554bf60dbe76 # test", "'..')) import config from agnid import AgniDaemon from agni_config import AgniConfig def test_agnid():", "os import re os.environ['SENTINEL_ENV'] = 'test' os.environ['SENTINEL_CONFIG'] = os.path.normpath(os.path.join(os.path.dirname(__file__), '../test_sentinel.conf')) sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..',", "import AgniConfig def test_agnid(): config_text = AgniConfig.slurp_config_file(config.agni_conf) network = 'mainnet' is_testnet = False", "key in info_keys: assert key in info assert info['testnet'] is is_testnet # test", "sys import os import re os.environ['SENTINEL_ENV'] = 'test' os.environ['SENTINEL_CONFIG'] = os.path.normpath(os.path.join(os.path.dirname(__file__), '../test_sentinel.conf')) sys.path.append(os.path.join(os.path.dirname(__file__),", "u'00000054f31397c25fd692a80391aa238da20c5638171b0e89a8bbf6bf7e4288' for line in config_text.split(\"\\n\"): if line.startswith('testnet=1'): network = 'testnet' is_testnet = True", "info_keys = [ 'blocks', 'connections', 'difficulty', 'errors', 'protocolversion', 'proxy', 'testnet', 'timeoffset', 'version', ]", "None assert hasattr(agnid, 'rpc_connection') # Agni testnet block 0 hash == 0000085e2ddad54c7313a28c2e96f7437e2ba9df1d5b2f3cdc3c554bf60dbe76 #", "= 'testnet' is_testnet = True genesis_hash = u'0000085e2ddad54c7313a28c2e96f7437e2ba9df1d5b2f3cdc3c554bf60dbe76' creds = AgniConfig.get_rpc_creds(config_text, network) agnid", "for key in info_keys: assert key in info assert info['testnet'] is is_testnet #", "Agni testnet block 0 hash == 0000085e2ddad54c7313a28c2e96f7437e2ba9df1d5b2f3cdc3c554bf60dbe76 # test commands without arguments info", "is_testnet = True genesis_hash = u'0000085e2ddad54c7313a28c2e96f7437e2ba9df1d5b2f3cdc3c554bf60dbe76' creds = AgniConfig.get_rpc_creds(config_text, network) agnid = AgniDaemon(**creds)", "info assert info['testnet'] is is_testnet # test commands with args assert agnid.rpc_command('getblockhash', 0)", "'testnet' is_testnet = True genesis_hash = u'0000085e2ddad54c7313a28c2e96f7437e2ba9df1d5b2f3cdc3c554bf60dbe76' creds = AgniConfig.get_rpc_creds(config_text, network) agnid =", "'..', '..')) import config from agnid import AgniDaemon from agni_config import AgniConfig def", "AgniConfig.get_rpc_creds(config_text, network) agnid = AgniDaemon(**creds) assert agnid.rpc_command is not None assert hasattr(agnid, 'rpc_connection')", "import config from agnid import AgniDaemon from agni_config import AgniConfig def test_agnid(): config_text", "line.startswith('testnet=1'): network = 'testnet' is_testnet = True genesis_hash = u'0000085e2ddad54c7313a28c2e96f7437e2ba9df1d5b2f3cdc3c554bf60dbe76' creds = AgniConfig.get_rpc_creds(config_text,", "info['testnet'] is is_testnet # test commands with args assert agnid.rpc_command('getblockhash', 0) == genesis_hash", "agnid.rpc_command is not None assert hasattr(agnid, 'rpc_connection') # Agni testnet block 0 hash", "assert info['testnet'] is is_testnet # test commands with args assert agnid.rpc_command('getblockhash', 0) ==", "import sys import os import re os.environ['SENTINEL_ENV'] = 'test' os.environ['SENTINEL_CONFIG'] = os.path.normpath(os.path.join(os.path.dirname(__file__), '../test_sentinel.conf'))", "import AgniDaemon from agni_config import AgniConfig def test_agnid(): config_text = AgniConfig.slurp_config_file(config.agni_conf) network =" ]
[ "\"aggregation\") def testAddRelationshipNoSecondClass(self): collection = ClassCollection() collection.addClass(\"bar\") self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") def", "def testRenameRelationship(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"inheritance\") collection.renameRelationship(\"foo\", \"bar\", \"composition\")", "\"foo\", \"aggregation\") self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") def testRelationshipAddedSuccesfully(self): collection = ClassCollection() collection.addClass(\"foo\")", "relationship already exists (helper?) # if it does, error # if not, add", "ClassCollection() self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") # Adding a relationship that already exists", "def testAddRelationshipNeitherClassExist(self): collection = ClassCollection() self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") # Adding a", "\"aggregation\") def testRelationshipAddedSuccesfully(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"realization\") self.assertIsNotNone(collection.getRelationship(\"foo\", \"bar\"))", "ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"bar\", \"foo\", \"aggregation\") self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") def testRelationshipAddedSuccesfully(self):", "\"bar\") self.assertNotIn((\"foo\", \"bar\"), collection.relationshipDict) self.assertRaises(KeyError, collection.deleteRelationship, \"foo\", \"bar\") def testRenameRelationship(self): collection = ClassCollection()", "ClassCollection() self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\") def testRelationshipDeletedSuccesfully(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\",", "= ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"bar\", \"foo\", \"aggregation\") self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") def", "collection = ClassCollection() collection.addClass(\"bar\") self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") def testAddRelationshipNeitherClassExist(self): collection =", "testRelationshipAddedSuccesfully(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"realization\") self.assertIsNotNone(collection.getRelationship(\"foo\", \"bar\")) def testDeleteRelationshipNoFirstClass(self):", "in the classCollection (helper?) # Check if relationship already exists (helper?) # if", "ClassCollection # Todo # Check if the classes exist in the classCollection (helper?)", "= ClassCollection() collection.addClass(\"foo\") self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\") def testDeleteRelationshipNoSecondClass(self): collection = ClassCollection() collection.addClass(\"bar\")", "relationship that already exists def testAddRelationshipAlreadyExists(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"bar\", \"foo\",", "collection.addRelationship(\"foo\", \"bar\", \"realization\") self.assertIsNotNone(collection.getRelationship(\"foo\", \"bar\")) def testDeleteRelationshipNoFirstClass(self): collection = ClassCollection() collection.addClass(\"foo\") self.assertRaises(KeyError, collection.deleteRelationship,", "self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") def testAddRelationshipNoSecondClass(self): collection = ClassCollection() collection.addClass(\"bar\") self.assertRaises(KeyError, collection.addRelationship,", "collection.relationshipDict) self.assertRaises(KeyError, collection.deleteRelationship, \"foo\", \"bar\") def testRenameRelationship(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\",", "# Check if the classes exist in the classCollection (helper?) # Check if", "import ClassCollection # Todo # Check if the classes exist in the classCollection", "error # if not, add parameter pair to the relationshipCollection class RelationshipTest(unittest.TestCase): def", "parameter pair to the relationshipCollection class RelationshipTest(unittest.TestCase): def testAddRelationshipNoFirstClass(self): collection = ClassCollection() collection.addClass(\"foo\")", "collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"bar\", \"foo\", \"aggregation\") self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") def testRelationshipAddedSuccesfully(self): collection", "ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"realization\") self.assertIsNotNone(collection.getRelationship(\"foo\", \"bar\")) def testDeleteRelationshipNoFirstClass(self): collection = ClassCollection()", "\"aggregation\") def testAddRelationshipNeitherClassExist(self): collection = ClassCollection() self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") # Adding", "testDeleteRelationshipNeitherClassExist(self): collection = ClassCollection() self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\") def testRelationshipDeletedSuccesfully(self): collection = ClassCollection()", "\"bar\", \"foo\", \"aggregation\") def testRelationshipAddedSuccesfully(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"realization\")", "= ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"realization\") self.assertIsNotNone(collection.getRelationship(\"foo\", \"bar\")) def testDeleteRelationshipNoFirstClass(self): collection =", "\"bar\", \"foo\") def testDeleteRelationshipNoSecondClass(self): collection = ClassCollection() collection.addClass(\"bar\") self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\") def", "= ClassCollection() self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") # Adding a relationship that already", "add parameter pair to the relationshipCollection class RelationshipTest(unittest.TestCase): def testAddRelationshipNoFirstClass(self): collection = ClassCollection()", "testRenameRelationship(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"inheritance\") collection.renameRelationship(\"foo\", \"bar\", \"composition\") self.assertEquals(\"composition\",collection.relationshipDict[(\"foo\",", "collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"inheritance\") collection.renameRelationship(\"foo\", \"bar\", \"composition\") self.assertEquals(\"composition\",collection.relationshipDict[(\"foo\", \"bar\")].typ)", "testAddRelationshipAlreadyExists(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"bar\", \"foo\", \"aggregation\") self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\",", "collection.addClass(\"foo\") self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") def testAddRelationshipNoSecondClass(self): collection = ClassCollection() collection.addClass(\"bar\") self.assertRaises(KeyError,", "= ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"inheritance\") collection.renameRelationship(\"foo\", \"bar\", \"composition\") self.assertEquals(\"composition\",collection.relationshipDict[(\"foo\", \"bar\")].typ) if", "collection = ClassCollection() collection.addClass(\"foo\") self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\") def testDeleteRelationshipNoSecondClass(self): collection = ClassCollection()", "\"realization\") self.assertIsNotNone(collection.getRelationship(\"foo\", \"bar\")) def testDeleteRelationshipNoFirstClass(self): collection = ClassCollection() collection.addClass(\"foo\") self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\")", "# Todo # Check if the classes exist in the classCollection (helper?) #", "collection.addRelationship, \"bar\", \"foo\", \"aggregation\") def testRelationshipAddedSuccesfully(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\",", "\"bar\", \"inheritance\") collection.deleteRelationship(\"foo\", \"bar\") self.assertNotIn((\"foo\", \"bar\"), collection.relationshipDict) self.assertRaises(KeyError, collection.deleteRelationship, \"foo\", \"bar\") def testRenameRelationship(self):", "Todo # Check if the classes exist in the classCollection (helper?) # Check", "self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\") def testDeleteRelationshipNeitherClassExist(self): collection = ClassCollection() self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\")", "class RelationshipTest(unittest.TestCase): def testAddRelationshipNoFirstClass(self): collection = ClassCollection() collection.addClass(\"foo\") self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\")", "collection.deleteRelationship(\"foo\", \"bar\") self.assertNotIn((\"foo\", \"bar\"), collection.relationshipDict) self.assertRaises(KeyError, collection.deleteRelationship, \"foo\", \"bar\") def testRenameRelationship(self): collection =", "# if not, add parameter pair to the relationshipCollection class RelationshipTest(unittest.TestCase): def testAddRelationshipNoFirstClass(self):", "ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"inheritance\") collection.renameRelationship(\"foo\", \"bar\", \"composition\") self.assertEquals(\"composition\",collection.relationshipDict[(\"foo\", \"bar\")].typ) if __name__", "\"bar\", \"foo\") def testRelationshipDeletedSuccesfully(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"inheritance\") collection.deleteRelationship(\"foo\",", "\"foo\", \"aggregation\") def testAddRelationshipNoSecondClass(self): collection = ClassCollection() collection.addClass(\"bar\") self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\")", "\"foo\", \"bar\") def testRenameRelationship(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"inheritance\") collection.renameRelationship(\"foo\",", "Check if relationship already exists (helper?) # if it does, error # if", "def testAddRelationshipNoFirstClass(self): collection = ClassCollection() collection.addClass(\"foo\") self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") def testAddRelationshipNoSecondClass(self):", "collection.addRelationship, \"bar\", \"foo\", \"aggregation\") # Adding a relationship that already exists def testAddRelationshipAlreadyExists(self):", "exists def testAddRelationshipAlreadyExists(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"bar\", \"foo\", \"aggregation\") self.assertRaises(KeyError, collection.addRelationship,", "def testAddRelationshipAlreadyExists(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"bar\", \"foo\", \"aggregation\") self.assertRaises(KeyError, collection.addRelationship, \"bar\",", "\"foo\") def testDeleteRelationshipNoSecondClass(self): collection = ClassCollection() collection.addClass(\"bar\") self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\") def testDeleteRelationshipNeitherClassExist(self):", "collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"realization\") self.assertIsNotNone(collection.getRelationship(\"foo\", \"bar\")) def testDeleteRelationshipNoFirstClass(self): collection = ClassCollection() collection.addClass(\"foo\") self.assertRaises(KeyError,", "if the classes exist in the classCollection (helper?) # Check if relationship already", "testDeleteRelationshipNoSecondClass(self): collection = ClassCollection() collection.addClass(\"bar\") self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\") def testDeleteRelationshipNeitherClassExist(self): collection =", "ClassCollection() collection.addClass(\"bar\") self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\") def testDeleteRelationshipNeitherClassExist(self): collection = ClassCollection() self.assertRaises(KeyError, collection.deleteRelationship,", "def testRelationshipDeletedSuccesfully(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"inheritance\") collection.deleteRelationship(\"foo\", \"bar\") self.assertNotIn((\"foo\",", "\"bar\"), collection.relationshipDict) self.assertRaises(KeyError, collection.deleteRelationship, \"foo\", \"bar\") def testRenameRelationship(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\")", "ClassCollection() collection.addClass(\"bar\") self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") def testAddRelationshipNeitherClassExist(self): collection = ClassCollection() self.assertRaises(KeyError,", "that already exists def testAddRelationshipAlreadyExists(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"bar\", \"foo\", \"aggregation\")", "\"bar\", \"foo\") def testDeleteRelationshipNeitherClassExist(self): collection = ClassCollection() self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\") def testRelationshipDeletedSuccesfully(self):", "unittest from ClassCollection import ClassCollection # Todo # Check if the classes exist", "\"foo\") def testRelationshipDeletedSuccesfully(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"inheritance\") collection.deleteRelationship(\"foo\", \"bar\")", "\"bar\") def testRenameRelationship(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"inheritance\") collection.renameRelationship(\"foo\", \"bar\",", "collection.addRelationship(\"foo\", \"bar\", \"inheritance\") collection.renameRelationship(\"foo\", \"bar\", \"composition\") self.assertEquals(\"composition\",collection.relationshipDict[(\"foo\", \"bar\")].typ) if __name__ == '__main__': unittest.main()", "(helper?) # if it does, error # if not, add parameter pair to", "= ClassCollection() collection.addClass(\"bar\") self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") def testAddRelationshipNeitherClassExist(self): collection = ClassCollection()", "it does, error # if not, add parameter pair to the relationshipCollection class", "\"bar\")) def testDeleteRelationshipNoFirstClass(self): collection = ClassCollection() collection.addClass(\"foo\") self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\") def testDeleteRelationshipNoSecondClass(self):", "collection.addClass(\"bar\") self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") def testAddRelationshipNeitherClassExist(self): collection = ClassCollection() self.assertRaises(KeyError, collection.addRelationship,", "a relationship that already exists def testAddRelationshipAlreadyExists(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"bar\",", "import unittest from ClassCollection import ClassCollection # Todo # Check if the classes", "def testDeleteRelationshipNoFirstClass(self): collection = ClassCollection() collection.addClass(\"foo\") self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\") def testDeleteRelationshipNoSecondClass(self): collection", "collection.addRelationship(\"bar\", \"foo\", \"aggregation\") self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") def testRelationshipAddedSuccesfully(self): collection = ClassCollection()", "collection.addRelationship, \"bar\", \"foo\", \"aggregation\") def testAddRelationshipNeitherClassExist(self): collection = ClassCollection() self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\",", "\"inheritance\") collection.deleteRelationship(\"foo\", \"bar\") self.assertNotIn((\"foo\", \"bar\"), collection.relationshipDict) self.assertRaises(KeyError, collection.deleteRelationship, \"foo\", \"bar\") def testRenameRelationship(self): collection", "# Check if relationship already exists (helper?) # if it does, error #", "testRelationshipDeletedSuccesfully(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"inheritance\") collection.deleteRelationship(\"foo\", \"bar\") self.assertNotIn((\"foo\", \"bar\"),", "ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"inheritance\") collection.deleteRelationship(\"foo\", \"bar\") self.assertNotIn((\"foo\", \"bar\"), collection.relationshipDict) self.assertRaises(KeyError, collection.deleteRelationship,", "testDeleteRelationshipNoFirstClass(self): collection = ClassCollection() collection.addClass(\"foo\") self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\") def testDeleteRelationshipNoSecondClass(self): collection =", "collection.addClass(\"foo\") self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\") def testDeleteRelationshipNoSecondClass(self): collection = ClassCollection() collection.addClass(\"bar\") self.assertRaises(KeyError, collection.deleteRelationship,", "if relationship already exists (helper?) # if it does, error # if not,", "collection.deleteRelationship, \"bar\", \"foo\") def testDeleteRelationshipNoSecondClass(self): collection = ClassCollection() collection.addClass(\"bar\") self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\")", "def testDeleteRelationshipNeitherClassExist(self): collection = ClassCollection() self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\") def testRelationshipDeletedSuccesfully(self): collection =", "= ClassCollection() collection.addClass(\"bar\") self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\") def testDeleteRelationshipNeitherClassExist(self): collection = ClassCollection() self.assertRaises(KeyError,", "def testAddRelationshipNoSecondClass(self): collection = ClassCollection() collection.addClass(\"bar\") self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") def testAddRelationshipNeitherClassExist(self):", "self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") def testRelationshipAddedSuccesfully(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\",", "pair to the relationshipCollection class RelationshipTest(unittest.TestCase): def testAddRelationshipNoFirstClass(self): collection = ClassCollection() collection.addClass(\"foo\") self.assertRaises(KeyError,", "exist in the classCollection (helper?) # Check if relationship already exists (helper?) #", "= ClassCollection() self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\") def testRelationshipDeletedSuccesfully(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\")", "collection = ClassCollection() self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\") def testRelationshipDeletedSuccesfully(self): collection = ClassCollection() collection.addClass(\"foo\")", "= ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"inheritance\") collection.deleteRelationship(\"foo\", \"bar\") self.assertNotIn((\"foo\", \"bar\"), collection.relationshipDict) self.assertRaises(KeyError,", "\"bar\", \"foo\", \"aggregation\") def testAddRelationshipNeitherClassExist(self): collection = ClassCollection() self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\")", "# Adding a relationship that already exists def testAddRelationshipAlreadyExists(self): collection = ClassCollection() collection.addClass(\"foo\")", "already exists def testAddRelationshipAlreadyExists(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"bar\", \"foo\", \"aggregation\") self.assertRaises(KeyError,", "relationshipCollection class RelationshipTest(unittest.TestCase): def testAddRelationshipNoFirstClass(self): collection = ClassCollection() collection.addClass(\"foo\") self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\",", "collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"inheritance\") collection.deleteRelationship(\"foo\", \"bar\") self.assertNotIn((\"foo\", \"bar\"), collection.relationshipDict)", "(helper?) # Check if relationship already exists (helper?) # if it does, error", "collection.addRelationship, \"bar\", \"foo\", \"aggregation\") def testAddRelationshipNoSecondClass(self): collection = ClassCollection() collection.addClass(\"bar\") self.assertRaises(KeyError, collection.addRelationship, \"bar\",", "exists (helper?) # if it does, error # if not, add parameter pair", "if not, add parameter pair to the relationshipCollection class RelationshipTest(unittest.TestCase): def testAddRelationshipNoFirstClass(self): collection", "\"aggregation\") # Adding a relationship that already exists def testAddRelationshipAlreadyExists(self): collection = ClassCollection()", "if it does, error # if not, add parameter pair to the relationshipCollection", "\"foo\", \"aggregation\") # Adding a relationship that already exists def testAddRelationshipAlreadyExists(self): collection =", "collection.addRelationship(\"foo\", \"bar\", \"inheritance\") collection.deleteRelationship(\"foo\", \"bar\") self.assertNotIn((\"foo\", \"bar\"), collection.relationshipDict) self.assertRaises(KeyError, collection.deleteRelationship, \"foo\", \"bar\") def", "Adding a relationship that already exists def testAddRelationshipAlreadyExists(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\")", "the relationshipCollection class RelationshipTest(unittest.TestCase): def testAddRelationshipNoFirstClass(self): collection = ClassCollection() collection.addClass(\"foo\") self.assertRaises(KeyError, collection.addRelationship, \"bar\",", "collection.deleteRelationship, \"bar\", \"foo\") def testRelationshipDeletedSuccesfully(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"inheritance\")", "Check if the classes exist in the classCollection (helper?) # Check if relationship", "collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"inheritance\") collection.renameRelationship(\"foo\", \"bar\", \"composition\") self.assertEquals(\"composition\",collection.relationshipDict[(\"foo\", \"bar\")].typ) if __name__ ==", "self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\") def testDeleteRelationshipNoSecondClass(self): collection = ClassCollection() collection.addClass(\"bar\") self.assertRaises(KeyError, collection.deleteRelationship, \"bar\",", "\"bar\", \"realization\") self.assertIsNotNone(collection.getRelationship(\"foo\", \"bar\")) def testDeleteRelationshipNoFirstClass(self): collection = ClassCollection() collection.addClass(\"foo\") self.assertRaises(KeyError, collection.deleteRelationship, \"bar\",", "not, add parameter pair to the relationshipCollection class RelationshipTest(unittest.TestCase): def testAddRelationshipNoFirstClass(self): collection =", "ClassCollection() collection.addClass(\"foo\") self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") def testAddRelationshipNoSecondClass(self): collection = ClassCollection() collection.addClass(\"bar\")", "collection.addClass(\"bar\") self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\") def testDeleteRelationshipNeitherClassExist(self): collection = ClassCollection() self.assertRaises(KeyError, collection.deleteRelationship, \"bar\",", "classes exist in the classCollection (helper?) # Check if relationship already exists (helper?)", "self.assertRaises(KeyError, collection.deleteRelationship, \"foo\", \"bar\") def testRenameRelationship(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\",", "from ClassCollection import ClassCollection # Todo # Check if the classes exist in", "def testRelationshipAddedSuccesfully(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"realization\") self.assertIsNotNone(collection.getRelationship(\"foo\", \"bar\")) def", "ClassCollection() collection.addClass(\"foo\") self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\") def testDeleteRelationshipNoSecondClass(self): collection = ClassCollection() collection.addClass(\"bar\") self.assertRaises(KeyError,", "\"bar\", \"foo\", \"aggregation\") # Adding a relationship that already exists def testAddRelationshipAlreadyExists(self): collection", "\"aggregation\") self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") def testRelationshipAddedSuccesfully(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\")", "collection.addClass(\"bar\") collection.addRelationship(\"bar\", \"foo\", \"aggregation\") self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") def testRelationshipAddedSuccesfully(self): collection =", "collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"inheritance\") collection.renameRelationship(\"foo\", \"bar\", \"composition\") self.assertEquals(\"composition\",collection.relationshipDict[(\"foo\", \"bar\")].typ) if __name__ == '__main__':", "self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") def testAddRelationshipNeitherClassExist(self): collection = ClassCollection() self.assertRaises(KeyError, collection.addRelationship, \"bar\",", "collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"realization\") self.assertIsNotNone(collection.getRelationship(\"foo\", \"bar\")) def testDeleteRelationshipNoFirstClass(self): collection = ClassCollection() collection.addClass(\"foo\")", "# if it does, error # if not, add parameter pair to the", "already exists (helper?) # if it does, error # if not, add parameter", "RelationshipTest(unittest.TestCase): def testAddRelationshipNoFirstClass(self): collection = ClassCollection() collection.addClass(\"foo\") self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") def", "collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"bar\", \"foo\", \"aggregation\") self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\")", "\"foo\", \"aggregation\") def testAddRelationshipNeitherClassExist(self): collection = ClassCollection() self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") #", "collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"realization\") self.assertIsNotNone(collection.getRelationship(\"foo\", \"bar\")) def testDeleteRelationshipNoFirstClass(self): collection", "testAddRelationshipNeitherClassExist(self): collection = ClassCollection() self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") # Adding a relationship", "self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") # Adding a relationship that already exists def", "collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"inheritance\") collection.deleteRelationship(\"foo\", \"bar\") self.assertNotIn((\"foo\", \"bar\"), collection.relationshipDict) self.assertRaises(KeyError, collection.deleteRelationship, \"foo\",", "ClassCollection import ClassCollection # Todo # Check if the classes exist in the", "testAddRelationshipNoSecondClass(self): collection = ClassCollection() collection.addClass(\"bar\") self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") def testAddRelationshipNeitherClassExist(self): collection", "\"foo\", \"aggregation\") def testRelationshipAddedSuccesfully(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"realization\") self.assertIsNotNone(collection.getRelationship(\"foo\",", "self.assertNotIn((\"foo\", \"bar\"), collection.relationshipDict) self.assertRaises(KeyError, collection.deleteRelationship, \"foo\", \"bar\") def testRenameRelationship(self): collection = ClassCollection() collection.addClass(\"foo\")", "collection = ClassCollection() collection.addClass(\"foo\") self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") def testAddRelationshipNoSecondClass(self): collection =", "collection.deleteRelationship, \"foo\", \"bar\") def testRenameRelationship(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"inheritance\")", "testAddRelationshipNoFirstClass(self): collection = ClassCollection() collection.addClass(\"foo\") self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") def testAddRelationshipNoSecondClass(self): collection", "self.assertIsNotNone(collection.getRelationship(\"foo\", \"bar\")) def testDeleteRelationshipNoFirstClass(self): collection = ClassCollection() collection.addClass(\"foo\") self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\") def", "def testDeleteRelationshipNoSecondClass(self): collection = ClassCollection() collection.addClass(\"bar\") self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\") def testDeleteRelationshipNeitherClassExist(self): collection", "collection.deleteRelationship, \"bar\", \"foo\") def testDeleteRelationshipNeitherClassExist(self): collection = ClassCollection() self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\") def", "collection = ClassCollection() collection.addClass(\"bar\") self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\") def testDeleteRelationshipNeitherClassExist(self): collection = ClassCollection()", "= ClassCollection() collection.addClass(\"foo\") self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") def testAddRelationshipNoSecondClass(self): collection = ClassCollection()", "classCollection (helper?) # Check if relationship already exists (helper?) # if it does,", "the classCollection (helper?) # Check if relationship already exists (helper?) # if it", "does, error # if not, add parameter pair to the relationshipCollection class RelationshipTest(unittest.TestCase):", "the classes exist in the classCollection (helper?) # Check if relationship already exists", "\"foo\") def testDeleteRelationshipNeitherClassExist(self): collection = ClassCollection() self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\") def testRelationshipDeletedSuccesfully(self): collection", "\"bar\", \"foo\", \"aggregation\") def testAddRelationshipNoSecondClass(self): collection = ClassCollection() collection.addClass(\"bar\") self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\",", "collection = ClassCollection() self.assertRaises(KeyError, collection.addRelationship, \"bar\", \"foo\", \"aggregation\") # Adding a relationship that", "collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\", \"inheritance\") collection.deleteRelationship(\"foo\", \"bar\") self.assertNotIn((\"foo\", \"bar\"), collection.relationshipDict) self.assertRaises(KeyError, collection.deleteRelationship, \"foo\", \"bar\")", "self.assertRaises(KeyError, collection.deleteRelationship, \"bar\", \"foo\") def testRelationshipDeletedSuccesfully(self): collection = ClassCollection() collection.addClass(\"foo\") collection.addClass(\"bar\") collection.addRelationship(\"foo\", \"bar\",", "to the relationshipCollection class RelationshipTest(unittest.TestCase): def testAddRelationshipNoFirstClass(self): collection = ClassCollection() collection.addClass(\"foo\") self.assertRaises(KeyError, collection.addRelationship," ]
[ "# -*- coding: utf-8 -*- \"\"\" greenbyteapi This file was automatically generated by", "@staticmethod def apply(http_request): \"\"\" Add custom authentication to the request. Args: http_request (HttpRequest):", "CustomHeaderAuth: @staticmethod def apply(http_request): \"\"\" Add custom authentication to the request. Args: http_request", "to the request. Args: http_request (HttpRequest): The HttpRequest object to which authentication will", "class CustomHeaderAuth: @staticmethod def apply(http_request): \"\"\" Add custom authentication to the request. Args:", "def apply(http_request): \"\"\" Add custom authentication to the request. Args: http_request (HttpRequest): The", "). \"\"\" from greenbyteapi.configuration import Configuration class CustomHeaderAuth: @staticmethod def apply(http_request): \"\"\" Add", "was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). \"\"\" from greenbyteapi.configuration import", "(HttpRequest): The HttpRequest object to which authentication will be added. \"\"\" http_request.add_header(\"X-Api-Key\", Configuration.x_api_key)", "utf-8 -*- \"\"\" greenbyteapi This file was automatically generated by APIMATIC v2.0 (", "from greenbyteapi.configuration import Configuration class CustomHeaderAuth: @staticmethod def apply(http_request): \"\"\" Add custom authentication", "greenbyteapi This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). \"\"\"", "( https://apimatic.io ). \"\"\" from greenbyteapi.configuration import Configuration class CustomHeaderAuth: @staticmethod def apply(http_request):", "<reponame>charlie9578/greenbyte-api-sdk<filename>greenbyteapi/http/auth/custom_header_auth.py # -*- coding: utf-8 -*- \"\"\" greenbyteapi This file was automatically generated", "\"\"\" greenbyteapi This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).", "generated by APIMATIC v2.0 ( https://apimatic.io ). \"\"\" from greenbyteapi.configuration import Configuration class", "http_request (HttpRequest): The HttpRequest object to which authentication will be added. \"\"\" http_request.add_header(\"X-Api-Key\",", "the request. Args: http_request (HttpRequest): The HttpRequest object to which authentication will be", "apply(http_request): \"\"\" Add custom authentication to the request. Args: http_request (HttpRequest): The HttpRequest", "Configuration class CustomHeaderAuth: @staticmethod def apply(http_request): \"\"\" Add custom authentication to the request.", "coding: utf-8 -*- \"\"\" greenbyteapi This file was automatically generated by APIMATIC v2.0", "file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). \"\"\" from greenbyteapi.configuration", "Add custom authentication to the request. Args: http_request (HttpRequest): The HttpRequest object to", "\"\"\" from greenbyteapi.configuration import Configuration class CustomHeaderAuth: @staticmethod def apply(http_request): \"\"\" Add custom", "-*- \"\"\" greenbyteapi This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io", "This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). \"\"\" from", "APIMATIC v2.0 ( https://apimatic.io ). \"\"\" from greenbyteapi.configuration import Configuration class CustomHeaderAuth: @staticmethod", "authentication to the request. Args: http_request (HttpRequest): The HttpRequest object to which authentication", "greenbyteapi.configuration import Configuration class CustomHeaderAuth: @staticmethod def apply(http_request): \"\"\" Add custom authentication to", "by APIMATIC v2.0 ( https://apimatic.io ). \"\"\" from greenbyteapi.configuration import Configuration class CustomHeaderAuth:", "automatically generated by APIMATIC v2.0 ( https://apimatic.io ). \"\"\" from greenbyteapi.configuration import Configuration", "import Configuration class CustomHeaderAuth: @staticmethod def apply(http_request): \"\"\" Add custom authentication to the", "custom authentication to the request. Args: http_request (HttpRequest): The HttpRequest object to which", "https://apimatic.io ). \"\"\" from greenbyteapi.configuration import Configuration class CustomHeaderAuth: @staticmethod def apply(http_request): \"\"\"", "request. Args: http_request (HttpRequest): The HttpRequest object to which authentication will be added.", "v2.0 ( https://apimatic.io ). \"\"\" from greenbyteapi.configuration import Configuration class CustomHeaderAuth: @staticmethod def", "Args: http_request (HttpRequest): The HttpRequest object to which authentication will be added. \"\"\"", "-*- coding: utf-8 -*- \"\"\" greenbyteapi This file was automatically generated by APIMATIC", "\"\"\" Add custom authentication to the request. Args: http_request (HttpRequest): The HttpRequest object" ]
[ "time, subtract 2 seconds from the start time updated_time = inital_time - 2", "return 499.5 @property def ephemeris_start_time(self): inital_time = spice.utc2et(self.utc_start_time.isoformat()) # To get shutter end", "1)[0] @property def detector_center_sample(self): return 499.5 @property def detector_center_line(self): return 499.5 @property def", "ale.base.base import Driver class Hayabusa2IsisLabelNaifSpiceDriver(Framer, IsisLabel, NaifSpice, Driver): @property def sensor_model_version(self): return 1", "end time. start_time = updated_time - self.exposure_duration return start_time @property def ephemeris_stop_time(self): return", "To get shutter end (close) time, subtract 2 seconds from the start time", "import ale from ale.base.data_naif import NaifSpice from ale.base.label_isis import IsisLabel from ale.base.type_sensor import", "from the start time updated_time = inital_time - 2 # To get shutter", "as spice import ale from ale.base.data_naif import NaifSpice from ale.base.label_isis import IsisLabel from", "@property def pixel_size(self): return spice.gdpool('INS{}_PIXEL_PITCH'.format(self.ikid), 0, 1)[0] @property def detector_center_sample(self): return 499.5 @property", "' ') @property def pixel_size(self): return spice.gdpool('INS{}_PIXEL_PITCH'.format(self.ikid), 0, 1)[0] @property def detector_center_sample(self): return", "2 seconds from the start time updated_time = inital_time - 2 # To", "spiceypy as spice import ale from ale.base.data_naif import NaifSpice from ale.base.label_isis import IsisLabel", "time, take off the exposure duration from the end time. start_time = updated_time", "return super().spacecraft_name.replace('_', ' ') @property def pixel_size(self): return spice.gdpool('INS{}_PIXEL_PITCH'.format(self.ikid), 0, 1)[0] @property def", "off the exposure duration from the end time. start_time = updated_time - self.exposure_duration", "time. start_time = updated_time - self.exposure_duration return start_time @property def ephemeris_stop_time(self): return self.ephemeris_start_time", "@property def sensor_model_version(self): return 1 @property def ikid(self): return self.label['IsisCube']['Kernels']['NaifFrameCode'] @property def spacecraft_name(self):", "super().spacecraft_name.replace('_', ' ') @property def pixel_size(self): return spice.gdpool('INS{}_PIXEL_PITCH'.format(self.ikid), 0, 1)[0] @property def detector_center_sample(self):", "def spacecraft_name(self): return super().spacecraft_name.replace('_', ' ') @property def pixel_size(self): return spice.gdpool('INS{}_PIXEL_PITCH'.format(self.ikid), 0, 1)[0]", "subtract 2 seconds from the start time updated_time = inital_time - 2 #", "2 # To get shutter start (open) time, take off the exposure duration", "ale from ale.base.data_naif import NaifSpice from ale.base.label_isis import IsisLabel from ale.base.type_sensor import Framer", "from ale.base.label_isis import IsisLabel from ale.base.type_sensor import Framer from ale.base.base import Driver class", "sensor_model_version(self): return 1 @property def ikid(self): return self.label['IsisCube']['Kernels']['NaifFrameCode'] @property def spacecraft_name(self): return super().spacecraft_name.replace('_',", "ikid(self): return self.label['IsisCube']['Kernels']['NaifFrameCode'] @property def spacecraft_name(self): return super().spacecraft_name.replace('_', ' ') @property def pixel_size(self):", "return 1 @property def ikid(self): return self.label['IsisCube']['Kernels']['NaifFrameCode'] @property def spacecraft_name(self): return super().spacecraft_name.replace('_', '", "0, 1)[0] @property def detector_center_sample(self): return 499.5 @property def detector_center_line(self): return 499.5 @property", "import Driver class Hayabusa2IsisLabelNaifSpiceDriver(Framer, IsisLabel, NaifSpice, Driver): @property def sensor_model_version(self): return 1 @property", "exposure duration from the end time. start_time = updated_time - self.exposure_duration return start_time", "spice.utc2et(self.utc_start_time.isoformat()) # To get shutter end (close) time, subtract 2 seconds from the", "inital_time - 2 # To get shutter start (open) time, take off the", "def pixel_size(self): return spice.gdpool('INS{}_PIXEL_PITCH'.format(self.ikid), 0, 1)[0] @property def detector_center_sample(self): return 499.5 @property def", "Driver): @property def sensor_model_version(self): return 1 @property def ikid(self): return self.label['IsisCube']['Kernels']['NaifFrameCode'] @property def", "start (open) time, take off the exposure duration from the end time. start_time", "class Hayabusa2IsisLabelNaifSpiceDriver(Framer, IsisLabel, NaifSpice, Driver): @property def sensor_model_version(self): return 1 @property def ikid(self):", "= updated_time - self.exposure_duration return start_time @property def ephemeris_stop_time(self): return self.ephemeris_start_time + self.exposure_duration", "@property def ikid(self): return self.label['IsisCube']['Kernels']['NaifFrameCode'] @property def spacecraft_name(self): return super().spacecraft_name.replace('_', ' ') @property", "Hayabusa2IsisLabelNaifSpiceDriver(Framer, IsisLabel, NaifSpice, Driver): @property def sensor_model_version(self): return 1 @property def ikid(self): return", "def detector_center_sample(self): return 499.5 @property def detector_center_line(self): return 499.5 @property def ephemeris_start_time(self): inital_time", "seconds from the start time updated_time = inital_time - 2 # To get", "return self.label['IsisCube']['Kernels']['NaifFrameCode'] @property def spacecraft_name(self): return super().spacecraft_name.replace('_', ' ') @property def pixel_size(self): return", "NaifSpice from ale.base.label_isis import IsisLabel from ale.base.type_sensor import Framer from ale.base.base import Driver", "spice.gdpool('INS{}_PIXEL_PITCH'.format(self.ikid), 0, 1)[0] @property def detector_center_sample(self): return 499.5 @property def detector_center_line(self): return 499.5", "499.5 @property def ephemeris_start_time(self): inital_time = spice.utc2et(self.utc_start_time.isoformat()) # To get shutter end (close)", "spice import ale from ale.base.data_naif import NaifSpice from ale.base.label_isis import IsisLabel from ale.base.type_sensor", "from ale.base.type_sensor import Framer from ale.base.base import Driver class Hayabusa2IsisLabelNaifSpiceDriver(Framer, IsisLabel, NaifSpice, Driver):", "(open) time, take off the exposure duration from the end time. start_time =", "the start time updated_time = inital_time - 2 # To get shutter start", "') @property def pixel_size(self): return spice.gdpool('INS{}_PIXEL_PITCH'.format(self.ikid), 0, 1)[0] @property def detector_center_sample(self): return 499.5", "= inital_time - 2 # To get shutter start (open) time, take off", "1 @property def ikid(self): return self.label['IsisCube']['Kernels']['NaifFrameCode'] @property def spacecraft_name(self): return super().spacecraft_name.replace('_', ' ')", "return spice.gdpool('INS{}_PIXEL_PITCH'.format(self.ikid), 0, 1)[0] @property def detector_center_sample(self): return 499.5 @property def detector_center_line(self): return", "get shutter end (close) time, subtract 2 seconds from the start time updated_time", "take off the exposure duration from the end time. start_time = updated_time -", "import IsisLabel from ale.base.type_sensor import Framer from ale.base.base import Driver class Hayabusa2IsisLabelNaifSpiceDriver(Framer, IsisLabel,", "import Framer from ale.base.base import Driver class Hayabusa2IsisLabelNaifSpiceDriver(Framer, IsisLabel, NaifSpice, Driver): @property def", "@property def detector_center_sample(self): return 499.5 @property def detector_center_line(self): return 499.5 @property def ephemeris_start_time(self):", "self.label['IsisCube']['Kernels']['NaifFrameCode'] @property def spacecraft_name(self): return super().spacecraft_name.replace('_', ' ') @property def pixel_size(self): return spice.gdpool('INS{}_PIXEL_PITCH'.format(self.ikid),", "# To get shutter end (close) time, subtract 2 seconds from the start", "import NaifSpice from ale.base.label_isis import IsisLabel from ale.base.type_sensor import Framer from ale.base.base import", "@property def spacecraft_name(self): return super().spacecraft_name.replace('_', ' ') @property def pixel_size(self): return spice.gdpool('INS{}_PIXEL_PITCH'.format(self.ikid), 0,", "the exposure duration from the end time. start_time = updated_time - self.exposure_duration return", "start_time = updated_time - self.exposure_duration return start_time @property def ephemeris_stop_time(self): return self.ephemeris_start_time +", "updated_time = inital_time - 2 # To get shutter start (open) time, take", "end (close) time, subtract 2 seconds from the start time updated_time = inital_time", "ale.base.data_naif import NaifSpice from ale.base.label_isis import IsisLabel from ale.base.type_sensor import Framer from ale.base.base", "Framer from ale.base.base import Driver class Hayabusa2IsisLabelNaifSpiceDriver(Framer, IsisLabel, NaifSpice, Driver): @property def sensor_model_version(self):", "duration from the end time. start_time = updated_time - self.exposure_duration return start_time @property", "@property def detector_center_line(self): return 499.5 @property def ephemeris_start_time(self): inital_time = spice.utc2et(self.utc_start_time.isoformat()) # To", "shutter start (open) time, take off the exposure duration from the end time.", "IsisLabel, NaifSpice, Driver): @property def sensor_model_version(self): return 1 @property def ikid(self): return self.label['IsisCube']['Kernels']['NaifFrameCode']", "499.5 @property def detector_center_line(self): return 499.5 @property def ephemeris_start_time(self): inital_time = spice.utc2et(self.utc_start_time.isoformat()) #", "from ale.base.data_naif import NaifSpice from ale.base.label_isis import IsisLabel from ale.base.type_sensor import Framer from", "def ephemeris_start_time(self): inital_time = spice.utc2et(self.utc_start_time.isoformat()) # To get shutter end (close) time, subtract", "from ale.base.base import Driver class Hayabusa2IsisLabelNaifSpiceDriver(Framer, IsisLabel, NaifSpice, Driver): @property def sensor_model_version(self): return", "detector_center_sample(self): return 499.5 @property def detector_center_line(self): return 499.5 @property def ephemeris_start_time(self): inital_time =", "import spiceypy as spice import ale from ale.base.data_naif import NaifSpice from ale.base.label_isis import", "spacecraft_name(self): return super().spacecraft_name.replace('_', ' ') @property def pixel_size(self): return spice.gdpool('INS{}_PIXEL_PITCH'.format(self.ikid), 0, 1)[0] @property", "def ikid(self): return self.label['IsisCube']['Kernels']['NaifFrameCode'] @property def spacecraft_name(self): return super().spacecraft_name.replace('_', ' ') @property def", "To get shutter start (open) time, take off the exposure duration from the", "get shutter start (open) time, take off the exposure duration from the end", "NaifSpice, Driver): @property def sensor_model_version(self): return 1 @property def ikid(self): return self.label['IsisCube']['Kernels']['NaifFrameCode'] @property", "def sensor_model_version(self): return 1 @property def ikid(self): return self.label['IsisCube']['Kernels']['NaifFrameCode'] @property def spacecraft_name(self): return", "inital_time = spice.utc2et(self.utc_start_time.isoformat()) # To get shutter end (close) time, subtract 2 seconds", "pixel_size(self): return spice.gdpool('INS{}_PIXEL_PITCH'.format(self.ikid), 0, 1)[0] @property def detector_center_sample(self): return 499.5 @property def detector_center_line(self):", "= spice.utc2et(self.utc_start_time.isoformat()) # To get shutter end (close) time, subtract 2 seconds from", "- 2 # To get shutter start (open) time, take off the exposure", "time updated_time = inital_time - 2 # To get shutter start (open) time,", "start time updated_time = inital_time - 2 # To get shutter start (open)", "the end time. start_time = updated_time - self.exposure_duration return start_time @property def ephemeris_stop_time(self):", "(close) time, subtract 2 seconds from the start time updated_time = inital_time -", "shutter end (close) time, subtract 2 seconds from the start time updated_time =", "return 499.5 @property def detector_center_line(self): return 499.5 @property def ephemeris_start_time(self): inital_time = spice.utc2et(self.utc_start_time.isoformat())", "# To get shutter start (open) time, take off the exposure duration from", "Driver class Hayabusa2IsisLabelNaifSpiceDriver(Framer, IsisLabel, NaifSpice, Driver): @property def sensor_model_version(self): return 1 @property def", "ephemeris_start_time(self): inital_time = spice.utc2et(self.utc_start_time.isoformat()) # To get shutter end (close) time, subtract 2", "def detector_center_line(self): return 499.5 @property def ephemeris_start_time(self): inital_time = spice.utc2et(self.utc_start_time.isoformat()) # To get", "ale.base.label_isis import IsisLabel from ale.base.type_sensor import Framer from ale.base.base import Driver class Hayabusa2IsisLabelNaifSpiceDriver(Framer,", "<filename>ale/drivers/hyb2_drivers.py import spiceypy as spice import ale from ale.base.data_naif import NaifSpice from ale.base.label_isis", "@property def ephemeris_start_time(self): inital_time = spice.utc2et(self.utc_start_time.isoformat()) # To get shutter end (close) time,", "detector_center_line(self): return 499.5 @property def ephemeris_start_time(self): inital_time = spice.utc2et(self.utc_start_time.isoformat()) # To get shutter", "ale.base.type_sensor import Framer from ale.base.base import Driver class Hayabusa2IsisLabelNaifSpiceDriver(Framer, IsisLabel, NaifSpice, Driver): @property", "from the end time. start_time = updated_time - self.exposure_duration return start_time @property def", "IsisLabel from ale.base.type_sensor import Framer from ale.base.base import Driver class Hayabusa2IsisLabelNaifSpiceDriver(Framer, IsisLabel, NaifSpice," ]
[ "for i in lookup: anslist = [int(char) for char in str(i)] answer.append(sum(anslist)) t", "char in str(i)] answer.append(sum(anslist)) t = int(input()) while t: t -= 1 n", "i in range((10**4)+1): lookup.append(lookup[i]*2) answer = [] for i in lookup: anslist =", "for char in str(i)] answer.append(sum(anslist)) t = int(input()) while t: t -= 1", "lookup: anslist = [int(char) for char in str(i)] answer.append(sum(anslist)) t = int(input()) while", "lookup.append(lookup[i]*2) answer = [] for i in lookup: anslist = [int(char) for char", "range((10**4)+1): lookup.append(lookup[i]*2) answer = [] for i in lookup: anslist = [int(char) for", "answer.append(sum(anslist)) t = int(input()) while t: t -= 1 n = int(input()) print(answer[n])", "in lookup: anslist = [int(char) for char in str(i)] answer.append(sum(anslist)) t = int(input())", "i in lookup: anslist = [int(char) for char in str(i)] answer.append(sum(anslist)) t =", "in range((10**4)+1): lookup.append(lookup[i]*2) answer = [] for i in lookup: anslist = [int(char)", "= [] for i in lookup: anslist = [int(char) for char in str(i)]", "[] for i in lookup: anslist = [int(char) for char in str(i)] answer.append(sum(anslist))", "= [int(char) for char in str(i)] answer.append(sum(anslist)) t = int(input()) while t: t", "str(i)] answer.append(sum(anslist)) t = int(input()) while t: t -= 1 n = int(input())", "for i in range((10**4)+1): lookup.append(lookup[i]*2) answer = [] for i in lookup: anslist", "lookup.append(1); for i in range((10**4)+1): lookup.append(lookup[i]*2) answer = [] for i in lookup:", "answer = [] for i in lookup: anslist = [int(char) for char in", "= [] lookup.append(1); for i in range((10**4)+1): lookup.append(lookup[i]*2) answer = [] for i", "[] lookup.append(1); for i in range((10**4)+1): lookup.append(lookup[i]*2) answer = [] for i in", "in str(i)] answer.append(sum(anslist)) t = int(input()) while t: t -= 1 n =", "lookup = [] lookup.append(1); for i in range((10**4)+1): lookup.append(lookup[i]*2) answer = [] for", "[int(char) for char in str(i)] answer.append(sum(anslist)) t = int(input()) while t: t -=", "anslist = [int(char) for char in str(i)] answer.append(sum(anslist)) t = int(input()) while t:" ]
[ "a minimal successful configuration # \"\"\" # for proxy in vcc_proxies: # proxy.Init()", "1].rfiFlaggingMask == \"{}\" # # check configured attributes of search windows # #", "of the configured attributes of VCCs # # first for VCC belonging to", "fsp_2_proxies.subarray[1].corrBandwidth == 0 # # assert fsp_2_proxies.subarray[1].integrationTime == 1400 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[0][0]", "command assert proxies.subarray[subarr_index].obsState == ObsState.SCANNING assert proxies.vcc[vcc_ids[0]].obsState == ObsState.SCANNING assert proxies.vcc[vcc_ids[num_receptors-1]].obsState == ObsState.SCANNING", "+ 1].subarrayMembership == 0 for i in range(4)]) # add some receptors to", "abort from IDLE ########################### # add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE,", "1][0].State() == DevState.ON assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].searchWindowTuning == 6000000000 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcEnable", "fspSubarrays to fsp_id in conftest; currently works for fsps 1 and 2 assert", "1, 1) assert len(proxies.subarray[1].receptors) == 0 assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 0 for i in", "obsStates BEFORE the EndScan() command assert proxies.subarray[subarr_index].obsState == ObsState.SCANNING assert proxies.vcc[vcc_ids[0]].obsState == ObsState.SCANNING", "10... assert proxies.vcc[proxies.receptor_to_vcc[4]].subarrayMembership == 1 assert proxies.vcc[proxies.receptor_to_vcc[4]].band5Tuning[0] == 5.85 assert proxies.vcc[proxies.receptor_to_vcc[4]].band5Tuning[1] == 7.25", "assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBandOffsetStream2 == 0 assert proxies.vcc[proxies.receptor_to_vcc[2]].rfiFlaggingMask == \"{}\" # check configured attributes of", "if fsp[\"function_mode\"] == \"CORR\": assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.READY elif fsp[\"function_mode\"] == \"PSS-BF\": assert", "assert fsp_1_proxies.subarray[1].channelAveragingMap[7][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[8][0] == 5952 # # assert", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[12][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[13][0] == 9672 # #", "== () # assert all([proxy.subarrayMembership == 0 for proxy in vcc_proxies]) # assert", "str(int(time.time()) + 10) # update Jones Matrix proxies.tm.jonesMatrix = json.dumps(jones_matrix) time.sleep(5) for receptor", "band capabilities # assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand == 4 # assert vcc_proxies[receptor_to_vcc[1] -", "3, 1) proxies.clean_proxies() # turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On() proxies.wait_timeout_dev([proxies.subarray[1]],", "assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch == 25 # TODO - re-enable and debug! #", "epoch {}, VCC {}, i = {}, jonesMatrix[{}] = {}\".format( jones_matrix[\"jonesMatrix\"][1][\"epoch\"], vcc_id, index,", "configured attributes of CBF subarray assert proxies.subarray[1].configID == \"sbi-mvp01-20200325-00001-science_A\" assert proxies.subarray[1].frequencyBand == 0", "e: proxies.clean_proxies() raise e #TODO: fix; currently tests break if multiple scan configurations", "vcc_proxies, vcc_band_proxies, vcc_tdc_proxies, fsp_1_proxy, fsp_2_proxy, fsp_1_function_mode_proxy, fsp_2_function_mode_proxy, fsp_3_proxies.subarray[1], tm_telstate_proxy ): \"\"\" Test a", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].obsState == ObsState.IDLE # abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED,", "first for VCC belonging to receptor 2... assert proxies.vcc[proxies.receptor_to_vcc[2]].subarrayMembership == 1 assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBandOffsetStream1", "for jj in range(4): logging.info((\" proxies.vcc[{}].receptorID = {}\". format(jj+1, proxies.vcc[jj+1].receptorID))) logging.info( (\"Vcc, receptor", "fsp[\"zoom_factor\"] > 0: assert proxies.fspSubarray[fsp_id].zoomWindowTuning == fsp[\"zoom_window_tuning\"] assert proxies.fspSubarray[fsp_id].fspChannelOffset == fsp[\"channel_offset\"] for i", "== 2.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 2.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 2.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] ==", "vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].tdcEnable == False assert fsp_3_proxies.subarray[1].receptors[0] == 3 assert fsp_3_proxies.subarray[1].receptors[1] == 1", "201 assert fsp_1_proxies.subarray[1].outputLinkMap[1][1] == 1 proxies.subarray[1].GoToIdle() time.sleep(3) assert proxies.subarray[1].obsState == ObsState.IDLE proxies.subarray[1].RemoveAllReceptors() time.sleep(1)", "assert fsp_2_proxies.subarray[1].channelAveragingMap[11][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[12][0] == 8929 # # assert", "== j for i, j in zip(range(1), [2])]) assert all([proxies.fspSubarray[6].timingBeamID[i] == j for", "error proxies.subarray[1].RemoveReceptors([2]) assert proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1] == 3 proxies.subarray[1].RemoveAllReceptors() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY,", "Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.ON, 3, 1) for proxy in", "False # # add receptors # proxies.subarray[1].RemoveAllReceptors() # proxies.subarray[1].AddReceptors([1, 3, 4]) # time.sleep(1)", "import json import logging # Path file_path = os.path.dirname(os.path.abspath(__file__)) # Tango imports import", "4]]) # assert subarray_2_proxy.State() == DevState.ON def test_RemoveAllReceptors(self, proxies): \"\"\" Test RemoveAllReceptors command", "json.loads(f.read().replace(\"\\n\", \"\")) f.close() aa = delay_model[\"delayModel\"][0][\"delayDetails\"][0][\"receptorDelayDetails\"] num_fsp_IDs = len(aa) for jj in range(num_fsp_IDs):", "assert proxies.subarray[1].receptors[2] == 4 # configure scan f = open(file_path + \"/test_json/data_model_confluence.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\",", "belonging to receptor 2... assert proxies.vcc[proxies.receptor_to_vcc[2]].subarrayMembership == 1 assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBandOffsetStream1 == 0 assert", "- 1] # turn on Subarray if proxies.subarray[sub_id].State() != DevState.ON: proxies.subarray[sub_id].On() proxies.wait_timeout_dev([proxies.subarray[sub_id]], DevState.ON,", "+ 10) # update delay model proxies.tm.beamWeights = json.dumps(timing_beam_weights) time.sleep(1) for weights in", "successful configuration \"\"\" for proxy in vcc_proxies: proxy.Init() fsp_1_proxies.subarray[1].Init() fsp_2_proxies.subarray[1].Init() fsp_3_proxies.subarray[1].Init() fsp_1_proxy.Init() fsp_2_proxy.Init()", "[[0, 9000, 1], [8184, 9000, 1]]}).replace('\"',\"'\") # Clean Up proxies.clean_proxies() except AssertionError as", "assert proxies.fspSubarray[fsp_id].receptors == test_receptor_ids[0] assert proxies.fspSubarray[fsp_id].frequencyBand == band_index assert proxies.fspSubarray[fsp_id].frequencySliceID == fsp[\"frequency_slice_id\"] assert", "Test a minimal successful configuration \"\"\" for proxy in vcc_proxies: proxy.Init() fsp_3_proxies.subarray[1].Init() fsp_1_proxy.Init()", "3) # assert all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership == 1 for i in [1, 3]])", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[2][0] == 1489 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[2][1] == 0 # #", "jones matrices from tm emulator f = open(file_path + \"/../data/jonesmatrix_fsp.json\") jones_matrix = json.loads(f.read().replace(\"\\n\",", "configured attributes of FSPs, including states of function mode capabilities # assert fsp_1_proxy.functionMode", "# # assert fsp_2_proxies.subarray[1].integrationTime == 1400 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[0][0] == 1 #", "json @pytest.mark.skip(reason=\"test needs to be refactored\") def test_ConfigureScan_delayModel(self, proxies): \"\"\" Test the reception", "1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] assert [proxy.State() for proxy in proxies.vccBand[proxies.receptor_to_vcc[1]", "\"10.05.1.1\" # assert searchBeam400[\"searchBeamID\"] == 400 # assert searchBeam400[\"receptors\"][0] == 1 # assert", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 3.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 3.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 4.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2]", "check configured attributes of VCC search windows # # first for search window", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[1].receptors[i] == j for i, j in zip(range(4),", "subarray_2_proxy.AddReceptors([1, 2, 4]) # time.sleep(1) # assert \"already in use\" in str(df.value.args[0].desc) #", "raise ae except Exception as e: proxies.clean_proxies() raise e def test_AddRemoveReceptors_invalid_single(self, proxies): \"\"\"", "via attribute 'searchBeams'); # this has to be updated in FspPssSubarray # to", "== DevState.DISABLE assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].searchWindowTuning == 7000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].tdcEnable ==", "== 0 # # assert fsp_2_proxies.subarray[1].frequencySliceID == 20 # # assert fsp_2_proxies.subarray[1].corrBandwidth ==", "fsp[\"function_mode\"] == \"PSS-BF\": assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.SCANNING # TODO: this check does not", "== \"fsp\": for receptor in matrix[\"matrixDetails\"]: rec_id = int(receptor[\"receptor\"]) fs_id = receptor[\"receptorMatrix\"][0][\"fsid\"] for", "proxies.fspSubarray[6].obsState == ObsState.READY assert all([proxies.fspSubarray[6].receptors[i] == j for i, j in zip(range(1), [2])])", "pytest # SKA specific imports from ska_mid_cbf_mcs.commons.global_enum import freq_band_dict from ska_tango_base.control_model import LoggingLevel,", "+ 10) # update Jones Matrix proxies.tm.jonesMatrix = json.dumps(jones_matrix) time.sleep(5) for receptor in", "proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e def test_ConfigureScan_jonesMatrix(self, proxies):", "single subarray, this test is currently broken.\") def test_AddRemoveReceptors_invalid_multiple(self, proxies): \"\"\" Test invalid", "cbf_master_proxy, proxies.subarray[1], sw_1_proxy, sw_2_proxy, vcc_proxies, vcc_band_proxies, vcc_tdc_proxies, fsp_1_proxy, fsp_2_proxy, fsp_1_function_mode_proxy, fsp_2_function_mode_proxy, fsp_1_proxies.subarray[1], fsp_2_proxies.subarray[1],", "as e: proxies.clean_proxies() raise e @pytest.mark.skip(reason=\"pst not currently supported\") def test_ConfigureScan_onlyPst_basic(self, proxies): \"\"\"", "check scanID on VCC and FSP assert proxies.fspSubarray[1].scanID == 1 assert proxies.vcc[proxies.receptor_to_vcc[4]].scanID ==1", "proxies.subarray[1].configID == 0 assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState.value == ObsState.IDLE.value # assert", "- 1].band5Tuning[1] == 7.25 # assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream1 == 0 # assert", "== ObsState.IDLE ############################# abort from SCANNING ########################### # add receptors proxies.subarray[1].AddReceptors([1, 3, 4,", "proxies.fsp1FunctionMode] == [ DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ] # TODO - # assert", "# # check configured attributes of VCC search windows # # first for", "0-based scan_index = int(input_scan_dict[\"scan_id\"]) - 1 logging.info( \"proxies.fspCorrSubarray[subarr_index-1].obsState = {}\". format(proxies.fspCorrSubarray[subarr_index-1].obsState) ) logging.info(", "assert \"already in use\" in str(df.value.args[0].desc) # assert subarray_2_proxy.receptors == (2, 4) #", "assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[1].receptors == 4 assert proxies.fspSubarray[1].frequencyBand == 4 assert", "capabilities assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand == 0 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand == 0", "= input_config_dict[\"common\"][\"frequency_band\"] input_band_index = freq_band_dict()[frequency_band] assert proxies.subarray[subarr_index].configID == input_config_dict[\"common\"][\"config_id\"] assert proxies.subarray[subarr_index].frequencyBand == input_band_index", "receptor in jones_matrix[\"jonesMatrix\"][0][\"matrixDetails\"]: for frequency_slice in receptor[\"receptorMatrix\"]: for index, value in enumerate(frequency_slice[\"matrix\"]): vcc_id", "assert proxies.subarray[1].State() == DevState.ON assert proxies.subarray[1].obsState == ObsState.EMPTY # receptor list should be", "in range(4)]) input_receptors = [1, 3, 4] # add some receptors proxies.subarray[1].AddReceptors(input_receptors) proxies.wait_timeout_obs([proxies.subarray[1]],", "searchBeam300[\"averagingInterval\"] == 4 # assert searchBeam300[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" # assert searchBeam400[\"searchBeamID\"] == 400", "\"\"\" # for proxy in vcc_proxies: # proxy.Init() # proxies.subarray[1].set_timeout_millis(60000) # subarray_2_proxy.set_timeout_millis(60000) #", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 1.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 1.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 1.3 assert", "frequency band capabilities logging.info( (\"proxies.vcc[vcc_index].frequencyBand = {}\". format( proxies.vcc[vcc_index].frequencyBand)) ) vcc_band_proxies = proxies.vccBand[vcc_index", "fsp_1_proxies.subarray[1].band5Tuning[1] == 7.25 # assert fsp_1_proxies.subarray[1].frequencyBandOffsetStream1 == 0 # assert fsp_1_proxies.subarray[1].frequencyBandOffsetStream2 == 0", "+ \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f1.read().replace(\"\\n\", \"\")) f1.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) # check initial states", "e: raise e time.sleep(10) # Clean Up proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies()", "VCC belonging to receptor 1... # assert vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership == 1 #", "== 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[7][0] == 5209 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[7][1] ==", "= 4 assert proxies.fsp[fsp_id].functionMode == function_mode assert sub_id in proxies.fsp[fsp_id].subarrayMembership assert [proxy.State() for", "time.sleep(1) # receptor_to_vcc = dict([*map(int, pair.split(\":\"))] for pair in # cbf_master_proxy.receptorToVcc) # cbf_master_proxy.On()", "proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) assert proxies.subarray[1].obsState == ObsState.SCANNING time.sleep(10) assert", "involving multiple subarrays: - when a receptor to be added is already in", "fix these tests; issue with VccBand devices either not reconfiguring in between #", "3.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 3.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 3.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 3.4", "VCC belonging to receptor 10... # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].State() == DevState.ON #", "proxies.tm.jonesMatrix = json.dumps(jones_matrix) time.sleep(1) for matrix in jones_matrix[\"jonesMatrix\"]: if matrix[\"destinationType\"] == \"fsp\": for", "== ObsState.IDLE proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae except Exception as", "the BSD-3-Clause license. # See LICENSE.txt for more info. \"\"\"Contain the tests for", "assert proxies.fspSubarray[1].channelAveragingMap[4][0] == 2976 assert proxies.fspSubarray[1].outputLinkMap[0][0] == 0 assert proxies.fspSubarray[1].outputLinkMap[0][1] == 4 assert", "== 5 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch == 25 # assert vcc_tdc_proxies[receptor_to_vcc[4] -", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert len(proxies.subarray[1].receptors) == 0 assert proxies.fspSubarray[1].obsState == ObsState.IDLE assert", "re-enable and debug! # assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcDestinationAddress == ( # \"fizz\", \"buzz\",", "# Standard imports import sys import os import time from datetime import datetime", "== ObsState.SCANNING assert proxies.vcc[vcc_ids[0]].obsState == ObsState.SCANNING assert proxies.vcc[vcc_ids[num_receptors-1]].obsState == ObsState.SCANNING for fsp in", "proxies.subarray[1].state() == tango.DevState.OFFequency band capabilities assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand == 4 assert vcc_proxies[receptor_to_vcc[1]", "with VccBand devices either not reconfiguring in between # configurations or causing a", "the EndScan() command assert proxies.subarray[subarr_index].obsState == ObsState.SCANNING assert proxies.vcc[vcc_ids[0]].obsState == ObsState.SCANNING assert proxies.vcc[vcc_ids[num_receptors-1]].obsState", "== 6000000000 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcEnable == True # assert vcc_tdc_proxies[receptor_to_vcc[1] -", "ae except Exception as e: proxies.clean_proxies() raise e #TODO refactor to verify delay", "0 assert proxies.vcc[proxies.receptor_to_vcc[2]].rfiFlaggingMask == \"{}\" # check configured attributes of FSPs, including states", "str(int(epoch) + 10) # update Jones Matrix proxies.tm.jonesMatrix = json.dumps(jones_matrix) time.sleep(1) for matrix", "proxies.wait_timeout_dev([proxies.controller], DevState.STANDBY, 3, 1) proxies.controller.On() proxies.wait_timeout_dev([proxies.controller], DevState.ON, 3, 1) proxies.clean_proxies() # turn on", "for proxy in fsp_1_function_mode_proxy] == [ DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ] # assert", "proxies.subarray[1].ObsReset() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].obsState == ObsState.IDLE assert all([proxies.subarray[1].receptors[i] == j", "300 assert proxies.fspSubarray[3].searchBeamID[1] == 400 # TODO: currently searchBeams is stored by the", "except Exception as e: raise e # transition to obsState == SCANNING f2", "# # check configured attributes of CBF subarray # assert proxies.subarray[1].configID == \"band:5a,", "# assert 1 in fsp_1_proxy.subarrayMembership # # assert 1 in fsp_2_proxy.subarrayMembership # assert", "\"8080\" ) # then for search window 1 of VCC belonging to receptor", "for more info. \"\"\"Contain the tests for the CbfSubarray.\"\"\" # Standard imports import", "== ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.SCANNING # abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1)", "vcc_proxies: proxy.Init() fsp_1_proxies.subarray[1].Init() fsp_2_proxies.subarray[1].Init() fsp_3_proxies.subarray[1].Init() fsp_1_proxy.Init() fsp_2_proxy.Init() time.sleep(3) cbf_master_proxy.set_timeout_millis(60000) cbf_master_proxy.Init() time.sleep(60) # takes", "DevState.DISABLE, DevState.DISABLE ] # assert [proxy.State() for proxy in fsp_2_function_mode_proxy] == [ #", "# assert fsp_2_proxies.subarray[1].frequencyBandOffsetStream2 == 0 # # assert fsp_2_proxies.subarray[1].frequencySliceID == 20 # #", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[18][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[19][0] == 14136 # #", "f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) assert proxies.subarray[1].obsState == ObsState.READY # create a delay", "assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].State() == DevState.ON assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].searchWindowTuning == 6000000000 assert", "i, j in zip(range(1), [10])]) # Clean Up proxies.clean_proxies() except AssertionError as ae:", "3 assert proxies.subarray[1].receptors[2] == 4 # configure scan f = open(file_path + \"/test_json/data_model_confluence.json\")", "proxies.fsp[1].functionMode == 1 assert 1 in proxies.fsp[1].subarrayMembership assert [proxy.State() for proxy in proxies.fsp1FunctionMode]", "DevState.ON, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY ############################# abort from READY ########################### #", "# assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.SCANNING proxies.subarray[subarr_index].EndScan() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.READY, 1, 1) # Check obsStates", "as e: proxies.clean_proxies() raise e ''' def test_ConfigureScan_onlyPss_basic( self, cbf_master_proxy, proxies.subarray[1], sw_1_proxy, sw_2_proxy,", "matrix in jones_matrix[\"jonesMatrix\"]: if matrix[\"destinationType\"] == \"fsp\": for receptor in matrix[\"matrixDetails\"]: rec_id =", "e: raise e time.sleep(10) for receptor in jones_matrix[\"jonesMatrix\"][0][\"matrixDetails\"]: for frequency_slice in receptor[\"receptorMatrix\"]: for", "ObsState.SCANNING proxies.subarray[subarr_index].EndScan() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.READY, 1, 1) # Check obsStates AFTER the EndScan() command", "assert proxies.subarray[1].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.SCANNING assert", ") try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.ON,", "assert len(proxies.subarray[1].receptors) == 0 assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 0 for i in [1, 3,", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[7][0] == 5209 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[7][1] == 0 # #", "2 of VCC belonging to receptor 1... assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].State() == DevState.DISABLE", "windows # first for search window 1... # TODO - SearchWidow device test", "command assert proxies.subarray[subarr_index].obsState == ObsState.READY assert proxies.vcc[vcc_ids[0]].obsState == ObsState.READY assert proxies.vcc[vcc_ids[num_receptors -1]].obsState ==", "assert fsp_2_proxies.subarray[1].channelAveragingMap[1][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[2][0] == 1489 # # assert", "1], [8184, 9000, 1]]}).replace('\"',\"'\") # Clean Up proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies()", "== 5 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch == 25 # TODO - re-enable and", "CBF subarray # assert len(proxies.subarray[1].receptors) == 0 # assert proxies.subarray[1].configID == 0 #", "assert fsp_1_proxies.subarray[1].channelAveragingMap[11][0] == 8184 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[11][1] == 8 # # assert", "fsp_2_proxies.subarray[1].channelAveragingMap[4][0] == 2977 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[4][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[5][0]", "\"/test_json/test_ConfigureScan_onlyPss_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() time.sleep(15) # check configured attributes of CBF subarray #", "LICENSE.txt for more info. \"\"\"Contain the tests for the CbfSubarray.\"\"\" # Standard imports", "from file f = open(file_path + \"/../data/delaymodel.json\") delay_model = json.loads(f.read().replace(\"\\n\", \"\")) f.close() aa", "fsp_2_proxy.subarrayMembership # assert [proxy.State() for proxy in fsp_1_function_mode_proxy] == [ # DevState.ON, DevState.DISABLE,", "\"192.168.0.2\"]], \"outputMac\": [[0, \"06-00-00-00-00-01\"]], \"outputPort\": [[0, 9000, 1], [8184, 9000, 1]]}).replace('\"',\"'\") # Clean", "try: assert proxies.fsp[fs_id].jonesMatrix[rec_id - 1][index] == value except AssertionError as ae: raise ae", "attributes of CBF subarray assert proxies.subarray[1].configID == \"band:5a, fsp1, 744 channels average factor", "assert sw_2_proxy.tdcEnable == False # # check configured attributes of VCC search windows", "] # check configured attributes of FSP subarrays # FSP 2 assert proxies.fspSubarray[6].obsState", "5 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch == 25 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcDestinationAddress", "PST-BF parameters to FSP \"\"\" try: # turn on Subarray if proxies.subarray[1].State() !=", "0 assert proxies.subarray[1].obsState == ObsState.EMPTY # add receptors proxies.subarray[1].AddReceptors([4, 1, 3, 2]) proxies.wait_timeout_obs([proxies.subarray[1]],", "# for i in range(4): # if (i == 0 and band_index ==", "be updated in FspPssSubarray # to read/write individual members searchBeam = proxies.fspSubarray[3].searchBeams searchBeam0", "obsState AFTER ConfigureScan = {}\". format(proxies.vcc[vcc_ids[0]].obsState) ) # check some configured attributes of", "- 1][0].searchWindowTuning == 6000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcEnable == True assert proxies.vccTdc[proxies.receptor_to_vcc[4] -", "proxies.fspSubarray[fsp_id].integrationTime == fsp[\"integration_factor\"] assert proxies.fspSubarray[fsp_id].corrBandwidth == fsp[\"zoom_factor\"] if fsp[\"zoom_factor\"] > 0: assert proxies.fspSubarray[fsp_id].zoomWindowTuning", ") num_receptors = len(input_receptors) vcc_ids = [None for _ in range(num_receptors)] for receptor_id,", "3]]) # assert all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership == 2 for i in [2, 4]])", "subarray assert proxies.subarray[1].configID == \"sbi-mvp01-20200325-00001-science_A\" assert proxies.subarray[1].frequencyBand == 0 # means 1 assert", "# assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].searchWindowTuning == 7000000000 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].tdcEnable ==", "str(int(epoch) + 10) # update delay model proxies.tm.beamWeights = json.dumps(timing_beam_weights) time.sleep(1) for weights", "True # assert searchBeam400[\"averagingInterval\"] == 2 # assert searchBeam400[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" # proxies.subarray[1].GoToIdle()", "\"outputPort\": [[0, 9000, 1], [8184, 9000, 1]]}).replace('\"',\"'\") # Clean Up proxies.clean_proxies() except AssertionError", "# ObsReset proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert len(proxies.subarray[1].receptors) == 0 assert proxies.fspSubarray[1].obsState", "for model in delay_model[\"delayModel\"]: model[\"epoch\"] = epoch if model[\"destinationType\"] == \"fsp\": epoch =", "as ae: proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e #TODO", "== ObsState.EMPTY # assert fsp_1_proxies.subarray[1].receptors == 4 # assert fsp_1_proxies.subarray[1].frequencyBand == 4 #", "len(proxies.subarray[1].receptors) == 0 assert proxies.fspSubarray[1].obsState == ObsState.IDLE assert proxies.fspSubarray[3].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState", "assert proxies.vcc[proxies.receptor_to_vcc[2]].subarrayMembership == 1 # remove some receptors proxies.subarray[1].RemoveReceptors([2, 1, 4]) time.sleep(1) assert", "vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcDestinationAddress == ( # \"foo\", \"bar\", \"8080\" # ) # #", "assert fsp_1_proxies.subarray[1].channelAveragingMap[14][0] == 10416 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[14][1] == 8 # # assert", "def test_ConfigureScan_minimal(self, proxies): try: sub_id = 1 #TODO currently only support for 1", "\"fizz\", \"buzz\", \"80\" ) # then for search window 2 of VCC belonging", "== ObsState.SCANNING proxies.subarray[subarr_index].EndScan() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.READY, 1, 1) # Check obsStates AFTER the EndScan()", "= open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 15, 1) # update", "assert proxies.vcc[proxies.receptor_to_vcc[3]].subarrayMembership == 1 # remove remaining receptors proxies.subarray[1].RemoveReceptors([3]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1)", "1 of VCC belonging to receptor 10... # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].State() ==", "fsp_1_proxy.functionMode == 1 assert 1 in fsp_1_proxy.subarrayMembership # assert 1 in fsp_2_proxy.subarrayMembership assert", "ska_tango_base.base_device import _DEBUGGER_PORT @pytest.mark.usefixtures(\"proxies\", \"input_test_data\") class TestCbfSubarray: def test_AddRemoveReceptors_valid(self, proxies): \"\"\" Test valid", "== 6000000000 assert sw_1_proxy.tdcEnable == True assert sw_1_proxy.tdcNumBits == 8 assert sw_1_proxy.tdcPeriodBeforeEpoch ==", "doing this doesn't actually throw an error proxies.subarray[1].RemoveReceptors([2]) assert proxies.subarray[1].receptors[0] == 1 assert", "to receptor 2... assert proxies.vcc[proxies.receptor_to_vcc[2]].subarrayMembership == 1 assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBandOffsetStream1 == 0 assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBandOffsetStream2", "+ \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) # check scanID on", "\"fsp\": epoch = str(int(epoch) + 10) # update Jones Matrix proxies.tm.jonesMatrix = json.dumps(jones_matrix)", "open(file_path + config_file_name) proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 15, 1) # check configured", "- 1].subarrayMembership == 1 for i in [1, 3]]) # assert proxies.subarray[1].State() ==", "# assert proxies.sw[1].tdcPeriodAfterEpoch == 25 # assert \"\".join(proxies.sw[1].tdcDestinationAddress.split()) in [ # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", #", "# update delay model proxies.tm.beamWeights = json.dumps(timing_beam_weights) time.sleep(1) for weights in timing_beam_weights[\"beamWeights\"]: for", "1, 1) assert proxies.subarray[1].State() == DevState.ON assert proxies.subarray[1].obsState == ObsState.EMPTY # receptor list", "in fsp_function_mode_proxies[fsp_id-1]] == [ DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ] # check configured attributes", "== 0 assert fsp_1_proxies.subarray[1].integrationTime == 1400 assert fsp_1_proxies.subarray[1].outputLinkMap[0][0] == 1 assert fsp_1_proxies.subarray[1].outputLinkMap[0][1] ==", "of FSP subarrays # FSP 2 assert proxies.fspSubarray[6].obsState == ObsState.READY assert all([proxies.fspSubarray[6].receptors[i] ==", "== 6000000000 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcEnable == True assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcNumBits ==", "Exception as e: proxies.clean_proxies() raise e @pytest.mark.skip(reason=\"pst not currently supported\") def test_ConfigureScan_onlyPst_basic_FSP_scan_parameters(self, proxies):", "########################### # add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert", "CBF subarray assert len(proxies.subarray[1].receptors) == 0 assert proxies.subarray[1].configID == '' assert proxies.subarray[1].frequencyBand ==", "search windows # first for search window 1 of VCC belonging to receptor", "invalid AddReceptors commands involving multiple subarrays: - when a receptor to be added", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 3.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 3.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 4.0 assert", "in delay_model[\"delayModel\"]: model[\"epoch\"] = epoch if model[\"destinationType\"] == \"fsp\": epoch = str(int(epoch) +", "input_config_dict[\"common\"][\"config_id\"] assert proxies.subarray[subarr_index].frequencyBand == input_band_index assert proxies.subarray[subarr_index].obsState == ObsState.READY # Send the Scan", "to receptor 1... # assert vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership == 1 # assert vcc_proxies[receptor_to_vcc[1]", "fsp_1_proxies.subarray[1].channelAveragingMap[14][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[15][0] == 11160 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[15][1]", "10... assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].State() == DevState.ON assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].searchWindowTuning == 6000000000", "= open(file_path + \"/../data/delaymodel_fsp.json\") delay_model = json.loads(f.read().replace(\"\\n\", \"\")) epoch = str(int(time.time())) for model", "proxies.sw[2].State() == DevState.DISABLE # assert proxies.sw[2].searchWindowTuning == 7000000000 # assert proxies.sw[2].tdcEnable == False", "RemoveAllReceptors command \"\"\" try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On()", "receptor 10... assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].State() == DevState.ON assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].searchWindowTuning ==", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[3][0] == 2232 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[3][1] == 8 # #", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 1.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 1.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 1.6 assert", "== ObsState.READY proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae except Exception as", "states assert proxies.subarray[1].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.SCANNING", "FSPs, including states of function mode capabilities # assert fsp_1_proxy.functionMode == 1 #", "== 0 assert proxies.vcc[proxies.receptor_to_vcc[3]].subarrayMembership == 0 assert proxies.subarray[1].obsState == ObsState.EMPTY proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.OFF,", "== \"10.05.1.1\" assert searchBeam1[\"search_beam_id\"] == 400 assert searchBeam1[\"receptor_ids\"][0] == 1 assert searchBeam1[\"enable_output\"] ==", "== 4 assert proxies.fspSubarray[1].frequencyBand == 4 assert proxies.fspSubarray[1].band5Tuning[0] == 5.85 assert proxies.fspSubarray[1].band5Tuning[1] ==", "+ \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 15, 1) # update jones matrices", "check some configured attributes of CBF subarray frequency_band = input_config_dict[\"common\"][\"frequency_band\"] input_band_index = freq_band_dict()[frequency_band]", "# DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # # check the rest of the configured", "== j for i, j in zip(range(3), [1, 3, 4])]) assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership ==", "1 # assert fsp_1_proxies.subarray[1].corrBandwidth == 1 # assert fsp_1_proxies.subarray[1].zoomWindowTuning == 4700000 # assert", "not pass - to debug & fix #assert searchBeam0[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" assert searchBeam1[\"search_beam_id\"]", "fsp_2_proxies.subarray[1].channelAveragingMap[12][0] == 8929 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[12][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[13][0]", "lastly for search window 2 of VCC belonging to receptor 1... # assert", "1, 1) assert proxies.subarray[1].obsState == ObsState.IDLE assert all([proxies.subarray[1].receptors[i] == j for i, j", "== 1.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 1.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 1.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] ==", "assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch == 5 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch == 25 assert", "# # then for search window 2 of VCC belonging to receptor 10...", "assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY # ObsReset proxies.subarray[1].ObsReset() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].obsState", "ae except Exception as e: proxies.clean_proxies() raise e @pytest.mark.skip(reason=\"Since there's only a single", "DevState.DISABLE, DevState.DISABLE, DevState.ON, DevState.DISABLE ] # check configured attributes of FSP subarrays #", "window 1... # TODO - SearchWidow device test is disabled since the same", "# ObsReset proxies.subarray[1].ObsReset() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].obsState == ObsState.IDLE assert proxies.subarray[1].scanID", "== fsp[\"output_link_map\"][i][j] proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae except Exception as", "= int(receptor[\"receptor\"]) fs_id = receptor[\"receptorMatrix\"][0][\"fsid\"] for index, value in enumerate(receptor[\"receptorMatrix\"][0][\"matrix\"]): try: assert proxies.fsp[fs_id].jonesMatrix[rec_id", "proxy in proxies.vccBand[proxies.receptor_to_vcc[2] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # check", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[1][0] == 745 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[1][1] == 0 # #", "assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState.value == ObsState.IDLE.value # assert tm_telstate_proxy.visDestinationAddress == \"{}\"", "# add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].obsState", "== 0 # check the rest of the configured attributes of VCCs #", "successful configuration \"\"\" for proxy in vcc_proxies: proxy.Init() fsp_3_proxies.subarray[1].Init() fsp_1_proxy.Init() fsp_2_proxy.Init() proxies.subarray[1].set_timeout_millis(60000) #", "proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch == 5 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch == 25 # TODO", "be decide which one to keep. # print(\"proxies.sw[1].State() = {}\".format(proxies.sw[1].State())) # print(\"proxies.sw[2].State() =", "input_config_dict[\"cbf\"][\"fsp\"]: if fsp[\"function_mode\"] == \"CORR\": assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.READY elif fsp[\"function_mode\"] == \"PSS-BF\":", "# assert fsp_1_proxies.subarray[1].frequencySliceID == 1 # assert fsp_1_proxies.subarray[1].corrBandwidth == 1 # assert fsp_1_proxies.subarray[1].zoomWindowTuning", "for proxy in proxies.fsp1FunctionMode] == [ DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ] # TODO", "proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState == ObsState.EMPTY # add receptors proxies.subarray[1].AddReceptors([1, 3, 4,", "proxy in proxies.vccBand[proxies.receptor_to_vcc[4] - 1]: logging.info(\"VCC proxy.State() = {}\".format(proxy.State())) assert [proxy.State() for proxy", "15, 1) # update jones matrices from tm emulator f = open(file_path +", "] # assert [proxy.State() for proxy in fsp_2_function_mode_proxy] == [ # DevState.ON, DevState.DISABLE,", "4) # assert all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership == 1 for i in [1, 3]])", "0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[2][0] == 1489 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[2][1] == 0", "DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) # check initial value of attributes of", "proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e def test_Abort_Restart(self, proxies):", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 2.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 2.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 2.3 assert", "fsp_function_mode_proxies = [proxies.fsp1FunctionMode, proxies.fsp2FunctionMode, proxies.fsp3FunctionMode, proxies.fsp4FunctionMode] for fsp in configuration[\"cbf\"][\"fsp\"]: fsp_id = fsp[\"fsp_id\"]", "for the CbfSubarray.\"\"\" # Standard imports import sys import os import time from", "== 3721 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[5][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[6][0] ==", "1, 1) proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.OFF, 3, 1) except AssertionError as ae: proxies.clean_proxies() raise", "== 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[15][0] == 11160 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[15][1] ==", "5.85 # assert fsp_1_proxies.subarray[1].band5Tuning[1] == 7.25 # assert fsp_1_proxies.subarray[1].frequencyBandOffsetStream1 == 0 # assert", "time.sleep(1) for jj in range(4): logging.info((\" proxies.vcc[{}].receptorID = {}\". format(jj+1, proxies.vcc[jj+1].receptorID))) logging.info( (\"Vcc,", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[18][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[19][0] == 14136 #", "\"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 15, 1) # check configured attributes of", "2.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 2.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 2.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 2.6", "== ObsState.READY for fsp in input_config_dict[\"cbf\"][\"fsp\"]: if fsp[\"function_mode\"] == \"CORR\": assert proxies.fspCorrSubarray[subarr_index-1].obsState ==", "# assert proxies.subarray[1].frequencyBand == 4 # means 5a? # assert proxies.subarray[1].obsState.value == ObsState.READY.value", "== 4 # assert fsp_1_proxies.subarray[1].frequencyBand == 4 # assert fsp_1_proxies.subarray[1].band5Tuning[0] == 5.85 #", "FSP subarrays # FSP 2 assert proxies.fspSubarray[6].obsState == ObsState.READY assert all([proxies.fspSubarray[6].receptors[i] == j", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 0.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 0.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 0.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1]", "# # assert [proxy.State() for proxy in fsp_2_function_mode_proxy] == [ # # DevState.ON,", "1) assert proxies.subarray[1].obsState == ObsState.IDLE assert proxies.subarray[1].scanID == 0 assert proxies.fspSubarray[1].obsState == ObsState.IDLE", "0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[14][0] == 10417 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[14][1] == 0", "proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[3].obsState == ObsState.READY # send the Scan command f2", "0 assert proxies.subarray[1].obsState.value == ObsState.IDLE.value # assert tm_telstate_proxy.visDestinationAddress == \"{}\" assert tm_telstate_proxy.receivedOutputLinks ==", "= proxies.vccBand[vcc_index - 1] assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBand == 4 assert proxies.vcc[proxies.receptor_to_vcc[1]].frequencyBand == 4 for", "ObsState.READY assert all([proxies.fspSubarray[6].receptors[i] == j for i, j in zip(range(1), [2])]) assert all([proxies.fspSubarray[6].timingBeamID[i]", "ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[3].obsState", "i in range(len(fsp[\"output_link_map\"])): for j in range(len(fsp[\"output_link_map\"][i])): assert proxies.fspSubarray[fsp_id].outputLinkMap[i][j] == fsp[\"output_link_map\"][i][j] proxies.clean_proxies() except", "ObsState.ABORTED assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[3].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY", "# Path file_path = os.path.dirname(os.path.abspath(__file__)) # Tango imports import tango from tango import", "4 # means 5a assert proxies.subarray[1].obsState == ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i + 1] for i", "function mode capabilities # assert fsp_1_proxy.functionMode == 1 # assert 1 in fsp_1_proxy.subarrayMembership", "ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE # Clean Up proxies.clean_proxies() except AssertionError as ae:", "delay_model[\"delayModel\"]: if model[\"destinationType\"] == \"fsp\": for receptor in model[\"delayDetails\"]: rec_id = int(receptor[\"receptor\"]) fs_id", "of VCC search windows # # first for search window 1 of VCC", "initialize # tm_telstate_proxy.Init() # time.sleep(1) # receptor_to_vcc = dict([*map(int, pair.split(\":\"))] for pair in", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[15][0] == 11160 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[15][1] == 8 #", "0 assert proxies.fspSubarray[1].obsState == ObsState.IDLE assert proxies.fspSubarray[3].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.IDLE", "# frequency band capabilities logging.info( (\"proxies.vcc[vcc_index].frequencyBand = {}\". format( proxies.vcc[vcc_index].frequencyBand)) ) assert proxies.vcc[vcc_index].configID", "== 0 assert proxies.subarray[1].obsState.value == ObsState.IDLE.value # assert tm_telstate_proxy.visDestinationAddress == \"{}\" assert tm_telstate_proxy.receivedOutputLinks", "== 2.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 2.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 2.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] ==", "proxies.subarray[1].obsState == ObsState.EMPTY ############################# abort from READY ########################### # add receptors proxies.subarray[1].AddReceptors([1, 3,", "in range(4)]) # add some receptors to subarray 1 proxies.subarray[1].AddReceptors([1, 3]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE,", "0.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 0.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 0.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 0.7", "assert fsp_1_proxies.subarray[1].corrBandwidth == 1 # assert fsp_1_proxies.subarray[1].zoomWindowTuning == 4700000 # assert fsp_1_proxies.subarray[1].integrationTime ==", "ae: proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e def test_ConfigureScan_jonesMatrix(self,", "f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) assert proxies.subarray[1].obsState == ObsState.READY #create a Jones matrix", "fsp_3_proxies.subarray[1].Init() # fsp_1_proxy.Init() # fsp_2_proxy.Init() # proxies.subarray[1].set_timeout_millis(60000) # since the command takes a", "subarray_2_proxy.receptors == (2, 4) # assert all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership == 1 for i", "# update Jones Matrix proxies.tm.jonesMatrix = json.dumps(jones_matrix) time.sleep(1) for matrix in jones_matrix[\"jonesMatrix\"]: if", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) assert proxies.subarray[1].obsState == ObsState.SCANNING time.sleep(10) assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 2.1", "== 0.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 0.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 0.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] ==", "= proxies.subarray[1].get_timeout_millis() log_msg = \"timeout_millis = {} \".format(timeout_millis) #logging.info(log_msg) #logging.info(\"start_time = {}\".format(time.time())) logging.info(\"start", "DevState.ON: proxies.subarray[1].On() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.ON, 3, 1) for proxy in [proxies.vcc[i + 1] for", "= json.loads(json_string) proxies.subarray[subarr_index].Scan(json_string) f2.close() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.SCANNING, 1, 1) # Note: scan_id is 1-based", "VCC belonging to receptor 10... assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].State() == DevState.DISABLE assert proxies.vccTdc[proxies.receptor_to_vcc[4]", "read/write individual members searchBeam = proxies.fspSubarray[3].searchBeams searchBeam0 = json.loads(searchBeam[0]) searchBeam1 = json.loads(searchBeam[1]) assert", "len(proxies.subarray[1].receptors) == 0 assert all([proxies.vcc[i + 1].subarrayMembership == 0 for i in range(4)])", "tests for the CbfSubarray.\"\"\" # Standard imports import sys import os import time", "abort from SCANNING ########################### # add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE,", "as df: # subarray_2_proxy.AddReceptors([1, 2, 4]) # time.sleep(1) # assert \"already in use\"", "in FspPssSubarray # to read/write individual members searchBeam = proxies.fspSubarray[3].searchBeams searchBeam0 = json.loads(searchBeam[0])", "== 0 assert proxies.subarray[1].obsState == ObsState.EMPTY proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.OFF, 3, 1) except AssertionError", "to be added is already in use by a different subarray \"\"\" #", "assert proxies.sw[1].tdcPeriodBeforeEpoch == 5 # assert proxies.sw[1].tdcPeriodAfterEpoch == 25 # assert \"\".join(proxies.sw[1].tdcDestinationAddress.split()) in", "Restart: receptors should be empty proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert proxies.subarray[1].obsState ==", "vcc_band_proxies, vcc_tdc_proxies, fsp_1_proxy, fsp_2_proxy, fsp_1_function_mode_proxy, fsp_2_function_mode_proxy, fsp_1_proxies.subarray[1], fsp_2_proxies.subarray[1], fsp_3_proxies.subarray[1], tm_telstate_proxy ): \"\"\" Test", "for i in [1, 3]]) # assert all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership == 2 for", "all([proxies.fspSubarray[6].receptors[i] == j for i, j in zip(range(1), [2])]) assert all([proxies.fspSubarray[6].timingBeamID[i] == j", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[4][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[5][0] == 3721 # #", "logging.info(\"{}\".format(fsp_id)) #TODO add function mode to enum or edit attribute to accept string", "\"PSS-BF\": function_mode = 2 elif fsp[\"function_mode\"] == \"PST-BF\": function_mode = 3 elif fsp[\"function_mode\"]", "for VCC belonging to receptor 1... assert vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership == 1 assert", "fix #elif fsp[\"function_mode\"] == \"PST-BF\": # assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.READY proxies.clean_proxies() except AssertionError", "1.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 1.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 1.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 1.4", "as e: raise e time.sleep(10) # update timing beam weights from tm emulator", "1 # assert 1 in fsp_1_proxy.subarrayMembership # # assert 1 in fsp_2_proxy.subarrayMembership #", "4 # assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[4] - 1]] == [ #", "EndScan command \"\"\" try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On()", "assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.READY elif fsp[\"function_mode\"] == \"PSS-BF\": assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.READY #", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert len(proxies.subarray[1].receptors) == 0 assert proxies.vcc[proxies.receptor_to_vcc[3]].subarrayMembership == 0 assert", "proxies.clean_proxies() raise e @pytest.mark.skip(reason=\"pst not currently supported\") def test_ConfigureScan_onlyPst_basic(self, proxies): \"\"\" Test a", "proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) assert proxies.subarray[1].obsState == ObsState.READY # create", "== 1.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 1.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 1.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] ==", "the reception of Jones matrices \"\"\" try: # turn on Subarray if proxies.subarray[1].State()", "proxies.fspSubarray[1].channelAveragingMap[2][0] == 1488 assert proxies.fspSubarray[1].channelAveragingMap[2][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[3][0] == 2232 assert proxies.fspSubarray[1].channelAveragingMap[3][1]", "# ObsReset proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY assert len(proxies.subarray[1].receptors)", "== ObsState.READY # ObsReset proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert len(proxies.subarray[1].receptors) == 0", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[3][0] == 2232 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[3][1] == 8 #", "7000000000 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].tdcEnable == False # # check configured attributes", "be removed is not assigned to the subarray \"\"\" try: # turn on", "1 assert proxies.subarray[1].receptors[1] == 3 assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for i in [1,", "# cbf_master_proxy, # proxies.subarray[1], # sw_1_proxy, # sw_2_proxy, # vcc_proxies, # vcc_band_proxies, #", "# check initial value of attributes of CBF subarray assert len(proxies.subarray[1].receptors) == 0", "# # DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE # # ] # # check configured", "assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].searchWindowTuning == 6000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcEnable == True assert", "num_fsp_IDs = len(aa) for jj in range(num_fsp_IDs): logging.info( \"delayCoeff = {}\".format( aa[jj][\"delayCoeff\"]) )", "vcc_index = proxies.receptor_to_vcc[4] logging.info(\"vcc_index = {}\".format( vcc_index )) assert len(proxies.subarray[1].receptors) == 0 assert", "fsp_1_proxies.subarray[1].channelAveragingMap[14][0] == 10416 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[14][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[15][0]", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[17][0] == 12649 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[17][1] == 0 # #", "400 # TODO: currently searchBeams is stored by the device # as a", ") # # then for search window 2 of VCC belonging to receptor", "input_band_index = freq_band_dict()[frequency_band] assert proxies.subarray[subarr_index].configID == input_config_dict[\"common\"][\"config_id\"] assert proxies.subarray[subarr_index].frequencyBand == input_band_index assert proxies.subarray[subarr_index].obsState", "rest of the configured attributes of VCCs # # first for VCC belonging", "14880 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[0][0] == 0 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[0][1] == 8", "f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) # check scanID on VCC and FSP assert", "assert fsp_2_proxies.subarray[1].channelAveragingMap[7][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[8][0] == 5953 # # assert", "== 2.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 2.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 2.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] ==", "proxies.subarray[1].State() == DevState.ON # assert proxies.subarray[1].ObsState == ObsState.EMPTY # # assert tm_telstate_proxy.visDestinationAddress ==", "except Exception as e: proxies.clean_proxies() raise e ''' def test_ConfigureScan_onlyPss_basic( self, cbf_master_proxy, proxies.subarray[1],", "# time.sleep(1) # assert \"already in use\" in str(df.value.args[0].desc) # assert subarray_2_proxy.receptors ==", "assert fsp_1_proxies.subarray[1].obsState == ObsState.EMPTY # assert fsp_1_proxies.subarray[1].receptors == 4 # assert fsp_1_proxies.subarray[1].frequencyBand ==", "400 assert searchBeam1[\"receptor_ids\"][0] == 1 assert searchBeam1[\"enable_output\"] == True assert searchBeam1[\"averaging_interval\"] == 2", "- 1].subarrayMembership == 1 # check configured attributes of FSPs, including states of", "# scan_index is an index into an array, therefore 0-based scan_index = int(input_scan_dict[\"scan_id\"])", "fsp_2_proxies.subarray[1], # fsp_3_proxies.subarray[1], # tm_telstate_proxy # ): # \"\"\" # Test a minimal", "assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE # Clean Up proxies.clean_proxies() except", "check frequency band of VCCs, including states of frequency band capabilities # assert", "fsp[\"function_mode\"] == \"PST-BF\": # assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.READY proxies.clean_proxies() except AssertionError as ae:", "== 0 # assert vcc_proxies[receptor_to_vcc[4] - 1].rfiFlaggingMask == \"{}\" # # then for", "# check some configured attributes of CBF subarray frequency_band = input_config_dict[\"common\"][\"frequency_band\"] input_band_index =", "range(4)]) # add some receptors to subarray 1 proxies.subarray[1].AddReceptors([1, 3]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1,", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[16][0] == 11905 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[16][1] == 0 # #", "\"/../data/delaymodel_fsp.json\") delay_model = json.loads(f.read().replace(\"\\n\", \"\")) epoch = str(int(time.time())) for model in delay_model[\"delayModel\"]: model[\"epoch\"]", "== 2232 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[3][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[4][0] ==", "7.25 # assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream1 == 0 # assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream2", "#test_receptor_ids = [1] vcc_index = proxies.receptor_to_vcc[test_receptor_ids[0]] logging.info(\"vcc_index = {}\".format(vcc_index)) vcc_band_proxies = proxies.vccBand[vcc_index -", "0 assert fsp_1_proxies.subarray[1].outputLinkMap[1][0] == 201 assert fsp_1_proxies.subarray[1].outputLinkMap[1][1] == 1 proxies.subarray[1].GoToIdle() time.sleep(3) assert proxies.subarray[1].obsState", "14880 assert proxies.fspSubarray[1].channelAveragingMap[0][0] == 0 assert proxies.fspSubarray[1].channelAveragingMap[0][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[1][0] == 744", "2 of VCC belonging to receptor 1... assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].State() == DevState.DISABLE", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1, 1) assert proxies.subarray[1].obsState == ObsState.READY # Clean Up proxies.clean_proxies() except", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[8][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[9][0] == 6697 # #", "fsp_2_proxies.subarray[1].channelAveragingMap[5][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[6][0] == 4465 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[6][1]", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[5][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[6][0] == 4464 # #", "== 1 # assert fsp_3_proxies.subarray[1].searchWindowID == 2 # assert fsp_3_proxies.subarray[1].searchBeamID[0] == 300 #", "fsp1, 744 channels average factor 8\" assert proxies.subarray[1].frequencyBand == 4 # means 5a", "assert fsp_1_proxies.subarray[1].integrationTime == 140 # assert fsp_1_proxies.subarray[1].fspChannelOffset == 14880 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[0][0]", "# then for FSP 3... # assert fsp_3_proxies.subarray[1].receptors[0] == 3 # assert fsp_3_proxies.subarray[1].receptors[1]", "to receptor 1... # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].State() == DevState.DISABLE # assert vcc_tdc_proxies[receptor_to_vcc[1]", "( via attribute 'searchBeams'); # this has to be updated in FspPssSubarray #", "# assert fsp_1_proxies.subarray[1].zoomWindowTuning == 4700000 # assert fsp_1_proxies.subarray[1].integrationTime == 140 # assert fsp_1_proxies.subarray[1].fspChannelOffset", "== 1.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 1.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 1.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] ==", "proxies.subarray[subarr_index].obsState == ObsState.IDLE # Check fsp obsState BEFORE scan configuration: assert proxies.fspCorrSubarray[subarr_index-1].obsState ==", "Exception as e: proxies.clean_proxies() raise e #TODO refactor to verify delay model values", "1... # TODO - SearchWidow device test is disabled since the same #", "in configuration[\"cbf\"][\"fsp\"]: fsp_id = fsp[\"fsp_id\"] logging.info(\"{}\".format(fsp_id)) #TODO add function mode to enum or", "\"\")) f.close() time.sleep(15) # check configured attributes of CBF subarray # def test_ConfigureScan_basic(", "assert fsp_1_proxies.subarray[1].channelAveragingMap[8][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[9][0] == 6696 # # assert", "assert all([proxies.subarray[1].receptors[i] == j for i, j in zip(range(3), [1, 3, 4])]) #", "assert fsp_1_proxies.subarray[1].channelAveragingMap[14][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[15][0] == 11160 # # assert", "- 1][0].tdcEnable == True # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcNumBits == 8 # assert", "ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[3].obsState == ObsState.READY", "proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].searchWindowTuning == 7000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].tdcEnable == False # check", "as a json string ( via attribute 'searchBeams'); # this has to be", "# assert fsp_1_proxies.subarray[1].outputLinkMap[0][1] == 4 # assert fsp_1_proxies.subarray[1].outputLinkMap[1][0] == 744 # assert fsp_1_proxies.subarray[1].outputLinkMap[1][1]", "1) # check initial value of attributes of CBF subarray vcc_index = proxies.receptor_to_vcc[4]", "0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[19][0] == 14137 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[19][1] == 0", "epoch = str(int(epoch) + 10) # update delay model proxies.tm.delayModel = json.dumps(delay_model) time.sleep(1)", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[8][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[9][0] == 6696 # #", "zip(range(3), [1, 3, 4])]) assert proxies.fspSubarray[1].obsState == ObsState.IDLE assert proxies.fspSubarray[3].obsState == ObsState.IDLE assert", "== 2977 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[4][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[5][0] ==", "ae: proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e ''' def", "1][0].tdcDestinationAddress == ( # \"foo\", \"bar\", \"8080\" # ) # # then for", "to receptor 1... assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].State() == DevState.DISABLE assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].searchWindowTuning", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[3][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[4][0] == 2977 #", "1.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 1.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 1.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 1.6", "right after initialization # assert proxies.subarray[1].receptors == () # assert subarray_2_proxy.receptors == ()", "index, fs_id-1, proxies.vcc[vcc_id].jonesMatrix[fs_id-1]) ) raise ae except Exception as e: raise e proxies.subarray[1].EndScan()", "[8184, 9000, 1]]}).replace('\"',\"'\") # Clean Up proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise", "searchBeam300[\"outputEnable\"] == True assert searchBeam300[\"averagingInterval\"] == 4 assert searchBeam300[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" assert searchBeam400[\"searchBeamID\"]", "Exception as e: proxies.clean_proxies() raise e def test_AddRemoveReceptors_invalid_single(self, proxies): \"\"\" Test invalid AddReceptors", "BEFORE ConfigureScan = {}\". format(proxies.vcc[vcc_ids[0]].obsState) ) f = open(file_path + config_file_name) json_string =", "only support for 1 receptor per fsp test_receptor_ids = [4, 1] #test_receptor_ids =", "1... # assert sw_1_proxy.State() == DevState.ON # assert sw_1_proxy.searchWindowTuning == 6000000000 # assert", "proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) # scan f2 = open(file_path +", "range(4): # if (i == 0 and band_index == 0) or (i ==", "3721 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[5][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[6][0] == 4465", "proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.READY # TODO: this check does not pass, to fix #elif", "time.sleep(10) # update delay models from tm emulator f = open(file_path + \"/../data/delaymodel_fsp.json\")", "assert proxies.subarray[1].scanID == 2 assert proxies.fspSubarray[1].obsState == ObsState.SCANNING assert proxies.fspSubarray[3].obsState == ObsState.SCANNING assert", "fsp_3_proxies.subarray[1].searchBeamID[1] == 400 searchBeam = fsp_3_proxies.subarray[1].searchBeams searchBeam300 = json.loads(searchBeam[0]) searchBeam400 = json.loads(searchBeam[1]) assert", "def test_ConfigureScan_onlyPst_basic_FSP_scan_parameters(self, proxies): \"\"\" Test a successful transmission of PST-BF parameters to FSP", "= str(int(time.time()) + 20) jones_matrix[\"jonesMatrix\"][1][\"epoch\"] = \"0\" jones_matrix[\"jonesMatrix\"][2][\"epoch\"] = str(int(time.time()) + 10) #", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 1.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 1.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 1.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4]", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[10][0] == 7440 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[10][1] == 8 # #", "assert proxies.subarray[1].obsState == ObsState.IDLE # remove all receptors proxies.subarray[1].RemoveAllReceptors() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1)", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 0.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 0.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 1.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4]", "in zip(range(3), [1, 3, 4])]) assert proxies.fspSubarray[1].obsState == ObsState.IDLE assert proxies.fspSubarray[3].obsState == ObsState.IDLE", "input_test_data): \"\"\" Test the EndScan command \"\"\" try: # turn on Subarray if", "# time.sleep(60) # # turn on Subarray # assert proxies.subarray[1].state()==DevState.OFF # proxies.subarray[1].On() #", "- 1][0].tdcPeriodBeforeEpoch == 5 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch == 25 assert vcc_tdc_proxies[receptor_to_vcc[1] -", "subarray 1 proxies.subarray[1].AddReceptors([1, 3]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].receptors[0] == 1 assert", "# assert fsp_1_proxies.subarray[1].frequencyBandOffsetStream2 == 0 # assert fsp_1_proxies.subarray[1].frequencySliceID == 1 # assert fsp_1_proxies.subarray[1].corrBandwidth", "8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[5][0] == 3720 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[5][1] == 8", "# assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream1 == 0 # assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream2 ==", "of VCC belonging to receptor 10... # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].State() == DevState.ON", "# searchBeam = fsp_3_proxies.subarray[1].searchBeams # searchBeam300 = json.loads(searchBeam[0]) # searchBeam400 = json.loads(searchBeam[1]) #", "False # check configured attributes of VCC search windows # first for search", "fsp_2_proxies.subarray[1].channelAveragingMap[18][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[19][0] == 14137 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[19][1]", "Exception as e: proxies.clean_proxies() raise e @pytest.mark.skip(reason=\"pst not currently supported\") def test_ConfigureScan_onlyPst_basic(self, proxies):", "== 400 assert searchBeam400[\"receptors\"][0] == 1 assert searchBeam400[\"outputEnable\"] == True assert searchBeam400[\"averagingInterval\"] ==", "== 1 for i in [1, 3, 4]]) assert proxies.subarray[1].obsState == ObsState.IDLE #", "some configured attributes of CBF subarray frequency_band = input_config_dict[\"common\"][\"frequency_band\"] input_band_index = freq_band_dict()[frequency_band] assert", "scan configuration \"\"\" try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On()", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 3.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 3.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 3.4 #", "4])]) # configure scan f = open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]],", "format(proxies.fspCorrSubarray[subarr_index-1].obsState) ) logging.info( \"proxies.fspPssSubarray[subarr_index-1].obsState = {}\". format(proxies.fspPssSubarray[subarr_index-1].obsState) ) logging.info( \"proxies.fspPstSubarray[subarr_index-1].obsState = {}\". format(proxies.fspPstSubarray[subarr_index-1].obsState)", "vcc_band_proxies, vcc_tdc_proxies, fsp_1_proxy, fsp_2_proxy, fsp_1_function_mode_proxy, fsp_2_function_mode_proxy, fsp_3_proxies.subarray[1], tm_telstate_proxy ): \"\"\" Test a minimal", "assert fsp_1_proxies.subarray[1].channelAveragingMap[2][0] == 1488 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[2][1] == 8 # # assert", "DevState.DISABLE # ] # check configured attributes of FSP subarrays # first for", "add receptors proxies.subarray[1].AddReceptors([4, 1, 3, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[1].receptors[i] ==", "proxies.subarray[1].GoToIdle() time.sleep(3) assert proxies.subarray[1].obsState == ObsState.IDLE proxies.subarray[1].RemoveAllReceptors() time.sleep(1) proxies.subarray[1].Off() assert proxies.subarray[1].state() == tango.DevState.OFF", "= input_test_data[0] config_file_name = input_test_data[1] subarr_index = 1; logging.info( \"input_receptors = {}\".format(input_receptors) )", "== 6000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcEnable == True assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcNumBits ==", "_DEBUGGER_PORT @pytest.mark.usefixtures(\"proxies\", \"input_test_data\") class TestCbfSubarray: def test_AddRemoveReceptors_valid(self, proxies): \"\"\" Test valid AddReceptors and", "f.close() aa = delay_model[\"delayModel\"][0][\"delayDetails\"][0][\"receptorDelayDetails\"] num_fsp_IDs = len(aa) for jj in range(num_fsp_IDs): logging.info( \"delayCoeff", "e def test_ConfigureScan_minimal(self, proxies): try: sub_id = 1 #TODO currently only support for", "- 1][0].tdcNumBits == 8 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch == 5 # assert", "# assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand == 4 # assert [proxy.State() for proxy in", "== 7000000000 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].tdcEnable == False # and lastly for search", "vcc_id = proxies.receptor_to_vcc[receptor[\"receptor\"]] fs_id = frequency_slice[\"fsid\"] try: assert proxies.vcc[vcc_id].jonesMatrix[fs_id-1][index] == value except AssertionError", "ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY # ObsReset proxies.subarray[1].ObsReset() proxies.wait_timeout_obs([proxies.subarray[1]],", "1].subarrayMembership == 1 # assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[0] == 5.85 # assert vcc_proxies[receptor_to_vcc[1]", "in input_receptors]) assert proxies.subarray[1].obsState == ObsState.IDLE # add more receptors... proxies.subarray[1].AddReceptors([2]) time.sleep(1) assert", "fsp_id = fsp[\"fsp_id\"] logging.info(\"{}\".format(fsp_id)) #TODO add function mode to enum or edit attribute", "assert searchBeam300[\"receptors\"][0] == 3 assert searchBeam300[\"outputEnable\"] == True assert searchBeam300[\"averagingInterval\"] == 4 assert", "sw_2_proxy.searchWindowTuning == 7000000000 assert sw_2_proxy.tdcEnable == False # check configured attributes of VCC", "for FSP 1... (this is a CORR fsp device) assert proxies.fspSubarray[1].obsState == ObsState.READY", "4 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand == 4 assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[4]", "assert proxies.fspSubarray[1].channelAveragingMap[3][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[4][0] == 2976 assert proxies.fspSubarray[1].outputLinkMap[0][0] == 0 assert", "8 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch == 5 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch == 25", "f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 15, 1) # update jones matrices from tm emulator f", "assert proxies.subarray[1].frequencyBand == 0 # assert proxies.subarray[1].State() == DevState.ON # assert proxies.subarray[1].ObsState ==", "coding: utf-8 -*- # # This file is part of the csp-lmc-prototype project", "== 2.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 2.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 2.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] ==", "vcc_proxies: proxy.Init() fsp_3_proxies.subarray[1].Init() fsp_1_proxy.Init() fsp_2_proxy.Init() proxies.subarray[1].set_timeout_millis(60000) # since the command takes a while", "for proxy in proxies.vccBand[proxies.receptor_to_vcc[4] - 1]: logging.info(\"VCC proxy.State() = {}\".format(proxy.State())) assert [proxy.State() for", "for proxy in [proxies.fsp[i + 1] for i in range(4)]: if proxy.State() ==", "proxies.subarray[1].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.SCANNING assert proxies.fspSubarray[1].obsState", "assert [proxy.State() for proxy in fsp_1_function_mode_proxy] == [ DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ]", "== 1 # check configured attributes of FSPs, including states of function mode", "assert fsp_1_proxies.subarray[1].channelAveragingMap[12][0] == 8928 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[12][1] == 8 # # assert", "pair in # cbf_controller_proxy.receptorToVcc) # cbf_controller_proxy.On() # time.sleep(3) # # receptor list should", "== 0.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 0.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 0.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] ==", "proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].State() == DevState.DISABLE assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].searchWindowTuning == 7000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[4]", "tm emulator f = open(file_path + \"/../data/timingbeamweights.json\") timing_beam_weights = json.loads(f.read().replace(\"\\n\", \"\")) epoch =", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert [proxies.subarray[1].receptors[i] for i in range(3)] == input_receptors assert", "1.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 1.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 1.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 1.4", "assert searchBeam300[\"searchBeamID\"] == 300 assert searchBeam300[\"receptors\"][0] == 3 assert searchBeam300[\"outputEnable\"] == True assert", "# searchBeam400 = json.loads(searchBeam[1]) # assert searchBeam300[\"searchBeamID\"] == 300 # assert searchBeam300[\"receptors\"][0] ==", "test_Abort_Reset(self, proxies): \"\"\" Test abort reset \"\"\" try: # turn on Subarray if", "as e: proxies.clean_proxies() raise e def test_Abort_Restart(self, proxies): \"\"\" Test abort restart \"\"\"", "1) assert proxies.subarray[1].obsState == ObsState.ABORTED # Restart: receptors should be empty proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]],", "== 5209 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[7][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[8][0] ==", "fsp_3_proxies.subarray[1], # tm_telstate_proxy # ): # \"\"\" # Test a minimal successful configuration", "except Exception as e: proxies.clean_proxies() raise e @pytest.mark.skip(reason=\"pst not currently supported\") def test_ConfigureScan_onlyPst_basic(self,", "i in [1, 3]]) # assert all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership == 2 for i", "== ObsState.READY elif fsp[\"function_mode\"] == \"PSS-BF\": assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.READY # TODO: this", "# # first for search window 1... # assert sw_1_proxy.State() == DevState.ON #", "\"\"\" Test RemoveAllReceptors command \"\"\" try: # turn on Subarray if proxies.subarray[1].State() !=", "== 1.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 1.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 1.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] ==", "== ObsState.IDLE # proxies.subarray[1].RemoveAllReceptors() # time.sleep(3) # assert proxies.subarray[1].state() == tango.DevState.OFFequency band capabilities", "to receptor 10... # assert vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership == 1 # assert vcc_proxies[receptor_to_vcc[4]", "== 2.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 2.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 2.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] ==", "# assert proxies.sw[1].State() == DevState.ON # assert proxies.sw[1].searchWindowTuning == 6000000000 # assert proxies.sw[1].tdcEnable", "proxies.fspSubarray[fsp_id].corrBandwidth == fsp[\"zoom_factor\"] if fsp[\"zoom_factor\"] > 0: assert proxies.fspSubarray[fsp_id].zoomWindowTuning == fsp[\"zoom_window_tuning\"] assert proxies.fspSubarray[fsp_id].fspChannelOffset", "fsps 1 and 2 assert proxies.fspSubarray[fsp_id].obsState == ObsState.READY assert proxies.fspSubarray[fsp_id].receptors == test_receptor_ids[0] assert", "for proxy in vcc_band_proxies[receptor_to_vcc[1] - 1]] == [ # DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON]", "remove remaining receptors proxies.subarray[1].RemoveReceptors([3]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert len(proxies.subarray[1].receptors) == 0 assert", "== 4 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand == 4 assert [proxy.State() for proxy in", "- 1][0].searchWindowTuning == 6000000000 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcEnable == True assert vcc_tdc_proxies[receptor_to_vcc[4] -", "proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[subarr_index].receptors[i] == j for i, j in zip(range(num_receptors),", "pass - to debug & fix #assert searchBeam0[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" assert searchBeam1[\"search_beam_id\"] ==", "# assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].State() == DevState.DISABLE # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].searchWindowTuning ==", "in proxies.fsp[1].subarrayMembership assert [proxy.State() for proxy in proxies.fsp1FunctionMode] == [ DevState.ON, DevState.DISABLE, DevState.DISABLE,", "a successful PST-BF scan configuration \"\"\" try: # turn on Subarray if proxies.subarray[1].State()", "terms of the BSD-3-Clause license. # See LICENSE.txt for more info. \"\"\"Contain the", "DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE # ] # # assert [proxy.State() for proxy in", "#TODO add function mode to enum or edit attribute to accept string in", "time.sleep(3) assert proxies.subarray[1].obsState == ObsState.IDLE proxies.subarray[1].RemoveAllReceptors() time.sleep(1) proxies.subarray[1].Off() assert proxies.subarray[1].state() == tango.DevState.OFF '''", "\"First vcc obsState BEFORE ConfigureScan = {}\". format(proxies.vcc[vcc_ids[0]].obsState) ) f = open(file_path +", "proxies.subarray[subarr_index].EndScan() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.READY, 1, 1) # Check obsStates AFTER the EndScan() command assert", "proxies.subarray[1].receptors[1] == 3 proxies.subarray[1].RemoveAllReceptors() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.OFF, 3, 1)", "proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED assert proxies.fspSubarray[1].obsState == ObsState.READY", "fsp_2_proxy.Init() time.sleep(3) cbf_master_proxy.set_timeout_millis(60000) cbf_master_proxy.Init() time.sleep(60) # takes pretty long for CBF Master to", "== 8 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch == 5 # assert vcc_tdc_proxies[receptor_to_vcc[1] -", "fsp_1_proxies.subarray[1].outputLinkMap[3][0] == 2232 # assert fsp_1_subarray_1_proroxy.receptors[2] == 4 # # assert fsp_2_proxies.subarray[1].frequencyBand ==", "fsp in input_config_dict[\"cbf\"][\"fsp\"]: if fsp[\"function_mode\"] == \"CORR\": assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.READY elif fsp[\"function_mode\"]", "for proxy in vcc_band_proxies[receptor_to_vcc[4] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] assert", "== 4 assert [proxy.State() for proxy in proxies.vccBand[proxies.receptor_to_vcc[2] - 1]] == [ DevState.DISABLE,", "scan, clear all private data #assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState == ObsState.EMPTY", "private data #assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState == ObsState.EMPTY # add receptors", "== 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[14][0] == 10416 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[14][1] ==", "test_AddRemoveReceptors_invalid_single(self, proxies): \"\"\" Test invalid AddReceptors commands involving a single subarray: - when", "assert proxies.fspSubarray[1].zoomWindowTuning == 4700000 assert proxies.fspSubarray[1].integrationTime == 1 assert proxies.fspSubarray[1].fspChannelOffset == 14880 assert", "successful configuration # \"\"\" # for proxy in vcc_proxies: # proxy.Init() # fsp_1_proxies.subarray[1].Init()", "1... assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].State() == DevState.ON assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].searchWindowTuning == 6000000000", "== 1488 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[2][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[3][0] ==", "on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.ON, 3, 1) for proxy", "band_index == 0) or (i == (band_index - 1)): # assert vcc_band_proxies[i].State() ==", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[9][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[10][0] == 7441 #", "configure scan f = open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 15,", "proxies.subarray[subarr_index].frequencyBand == input_band_index assert proxies.subarray[subarr_index].obsState == ObsState.READY # Send the Scan command f2", "VCC belonging to receptor 1... assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].State() == DevState.ON assert vcc_tdc_proxies[receptor_to_vcc[1]", "4]) time.sleep(1) assert proxies.subarray[1].receptors == ([3]) assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 0 for i in", "proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY ############################# abort from READY", "window 1 of VCC belonging to receptor 1... # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].State()", "assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[0] == 5.85 # assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[1] == 7.25", "i in range(4)]: if proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) #", "assert proxies.subarray[1].State() == DevState.ON # assert proxies.subarray[1].ObsState == ObsState.EMPTY # # assert tm_telstate_proxy.visDestinationAddress", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 2.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 2.4 proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1, 1)", "== 3.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 3.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 4.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] ==", "proxies.subarray[1].RemoveAllReceptors() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert len(proxies.subarray[1].receptors) == 0 assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 0", "proxies.sw[1].tdcPeriodAfterEpoch == 25 # assert \"\".join(proxies.sw[1].tdcDestinationAddress.split()) in [ # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", #", "therefore 0-based scan_index = int(input_scan_dict[\"scan_id\"]) - 1 logging.info( \"proxies.fspCorrSubarray[subarr_index-1].obsState = {}\". format(proxies.fspCorrSubarray[subarr_index-1].obsState) )", "assert fsp_2_proxies.subarray[1].channelAveragingMap[3][0] == 2233 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[3][1] == 0 # # assert", "== DevState.ON # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].searchWindowTuning == 6000000000 # assert vcc_tdc_proxies[receptor_to_vcc[1] -", "3, 4, 2] assert proxies.vcc[proxies.receptor_to_vcc[2]].subarrayMembership == 1 # remove some receptors proxies.subarray[1].RemoveReceptors([2, 1,", "2.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 2.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 2.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 2.3", "1].subarrayMembership == 1 assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[0] == 5.85 assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[1]", "\"foo\", \"bar\", \"8080\" # ) # then for search window 1 of VCC", "proxies.clean_proxies() raise e def test_Abort_Restart(self, proxies): \"\"\" Test abort restart \"\"\" try: #", "\"\") input_config_dict = json.loads(json_string) proxies.subarray[subarr_index].ConfigureScan(json_string) f.close() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.READY, 15, 1) logging.info( \"First vcc", "proxies.subarray[1].obsState == ObsState.ABORTED # ObsReset proxies.subarray[1].ObsReset() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].obsState ==", "enum or edit attribute to accept string in FSP if fsp[\"function_mode\"] == \"CORR\":", "scan f = open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1)", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 0.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 1.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 1.1 assert", "fsp_1_proxies.subarray[1].frequencyBand == 0 assert fsp_1_proxies.subarray[1].frequencySliceID == 1 assert fsp_1_proxies.subarray[1].corrBandwidth == 0 assert fsp_1_proxies.subarray[1].integrationTime", "assert fsp_1_proxies.subarray[1].channelAveragingMap[8][0] == 5952 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[8][1] == 8 # # assert", "a PSS fsp device) assert proxies.fspSubarray[3].receptors[0] == 3 assert proxies.fspSubarray[3].receptors[1] == 1 assert", "\"\"\" Test the reception of delay models \"\"\" # Read delay model data", "- 1][1].searchWindowTuning == 7000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].tdcEnable == False # check configured", "for i in range(4)]) # add some receptors to subarray 1 proxies.subarray[1].AddReceptors([1, 3])", "ObsState.IDLE proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae except Exception as e:", "# time.sleep(3) # # receptor list should be empty right after initialization #", "a different subarray \"\"\" # for proxy in vcc_proxies: # proxy.Init() # proxies.subarray[1].set_timeout_millis(60000)", "is stored by the device # as a json string ( via attribute", "assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcEnable == True assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcNumBits == 8 assert", "1) assert proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1] == 3 assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1", "epoch if model[\"destinationType\"] == \"fsp\": epoch = str(int(epoch) + 10) # update delay", "clear all private data #assert proxies.subarray[sub_id].frequencyBand == 0 assert proxies.subarray[sub_id].obsState == ObsState.EMPTY #", "empty right after initialization assert len(proxies.subarray[1].receptors) == 0 assert all([proxies.vcc[i + 1].subarrayMembership ==", "time.sleep(1) for weights in timing_beam_weights[\"beamWeights\"]: for receptor in weights[\"beamWeightsDetails\"]: rec_id = int(receptor[\"receptor\"]) fs_id", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[12][0] == 8929 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[12][1] == 0 #", "proxies.subarray[1].obsState == ObsState.SCANNING time.sleep(10) for receptor in jones_matrix[\"jonesMatrix\"][2][\"matrixDetails\"]: for frequency_slice in receptor[\"receptorMatrix\"]: for", "belonging to receptor 1... assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].State() == DevState.DISABLE assert vcc_tdc_proxies[receptor_to_vcc[1] -", "# receptor_to_vcc = dict([*map(int, pair.split(\":\"))] for pair in # cbf_master_proxy.receptorToVcc) # cbf_master_proxy.On() #", "== (2, 4) # assert all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership == 1 for i in", "fsp_1_proxy.subarrayMembership # assert 1 in fsp_2_proxy.subarrayMembership assert [proxy.State() for proxy in fsp_1_function_mode_proxy] ==", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[10][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[11][0] == 8185 #", "configured attributes of VCCs # # first for VCC belonging to receptor 10...", "configured attributes of VCCs # first for VCC belonging to receptor 10... assert", "for search window 2 of VCC belonging to receptor 1... # assert vcc_tdc_proxies[receptor_to_vcc[1]", "3]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1] == 3", "== 3 assert 1 in proxies.fsp[2].subarrayMembership assert [proxy.State() for proxy in proxies.fsp2FunctionMode] ==", "json.loads(f.read().replace(\"\\n\", \"\")) epoch = str(int(time.time())) for model in delay_model[\"delayModel\"]: model[\"epoch\"] = epoch if", "# assert proxies.subarray[1].State() == DevState.OFF # assert subarray_2_proxy.State() == DevState.OFF # # add", "input_config_dict[\"cbf\"][\"fsp\"]: if fsp[\"function_mode\"] == \"CORR\": assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.SCANNING elif fsp[\"function_mode\"] == \"PSS-BF\":", "== 7000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].tdcEnable == False # and lastly for search", "8185 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[11][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[12][0] == 8929", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[19][0] == 14137 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[19][1] == 0 # #", "1 assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[0] == 5.85 assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[1] == 7.25", "valid AddReceptors and RemoveReceptors commands \"\"\" timeout_millis = proxies.subarray[1].get_timeout_millis() log_msg = \"timeout_millis =", "== 1.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 1.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 1.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] ==", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[6][0] == 4465 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[6][1] == 0 #", "10... assert vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership == 1 assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[0] == 5.85", "assert len(proxies.subarray[1].receptors) == 0 assert proxies.subarray[1].configID == '' # TODO in CbfSubarray, at", "in vcc_proxies: # proxy.Init() # proxies.subarray[1].set_timeout_millis(60000) # subarray_2_proxy.set_timeout_millis(60000) # proxies.subarray[1].Init() # subarray_2_proxy.Init() #", "proxies.subarray[1].configID == \"band:5a, fsp1, 744 channels average factor 8\" assert proxies.subarray[1].frequencyBand == 4", "= {}\".format(time.time())) logging.info(\"start datetime = {}\".format(datetime.now())) if proxies.debug_device_is_on: port = proxies.subarray[1].DebugDevice() try: proxies.clean_proxies()", "== [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[1] -", "\"CORR\": assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.SCANNING elif fsp[\"function_mode\"] == \"PSS-BF\": assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.SCANNING", "from tm emulator f = open(file_path + \"/../data/jonesmatrix_fsp.json\") jones_matrix = json.loads(f.read().replace(\"\\n\", \"\")) epoch", "from READY ########################### # add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1,", "assert str(proxies.fspSubarray[1].visDestinationAddress).replace('\"',\"'\") == \\ str({\"outputHost\": [[0, \"192.168.0.1\"], [8184, \"192.168.0.2\"]], \"outputMac\": [[0, \"06-00-00-00-00-01\"]], \"outputPort\":", "issue with VccBand devices either not reconfiguring in between # configurations or causing", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 2.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 2.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 2.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3]", "# assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].State() == DevState.ON # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].searchWindowTuning ==", "assert proxies.sw[1].tdcNumBits == 8 # assert proxies.sw[1].tdcPeriodBeforeEpoch == 5 # assert proxies.sw[1].tdcPeriodAfterEpoch ==", "# add receptors proxies.subarray[1].RemoveAllReceptors() proxies.subarray[1].AddReceptors([1, 3, 4]) time.sleep(1) assert proxies.subarray[1].receptors[0] == 1 assert", "# # receptor list should be empty right after initialization # assert proxies.subarray[1].receptors", "the rest of the configured attributes of VCCs # # first for VCC", "assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream1 == 0 assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream2 == 0 assert", "): # \"\"\" # Test a minimal successful configuration # \"\"\" # for", "AFTER ConfigureScan = {}\". format(proxies.vcc[vcc_ids[0]].obsState) ) # check some configured attributes of CBF", "time.sleep(3) # check initial value of attributes of CBF subarray # assert proxies.subarray[1].receptors", "all([proxies.subarray[1].receptors[i] == j for i, j in zip(range(3), [1, 3, 4])]) assert proxies.fspSubarray[1].obsState", "out of range) - when a receptor to be removed is not assigned", "test_AddRemoveReceptors_valid(self, proxies): \"\"\" Test valid AddReceptors and RemoveReceptors commands \"\"\" timeout_millis = proxies.subarray[1].get_timeout_millis()", "import LoggingLevel, HealthState from ska_tango_base.control_model import AdminMode, ObsState from ska_tango_base.base_device import _DEBUGGER_PORT @pytest.mark.usefixtures(\"proxies\",", "7.25 assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBandOffsetStream1 == 0 assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBandOffsetStream2 == 0 assert proxies.vcc[proxies.receptor_to_vcc[4]].rfiFlaggingMask == \"{}\"", "command f2 = open(file_path + \"/../data/Scan1_basic.json\") json_string = f2.read().replace(\"\\n\", \"\") input_scan_dict = json.loads(json_string)", "] # TODO - # assert [proxy.State() for proxy in fsp_2_function_mode_proxy] == [", "fsp_1_proxies.subarray[1].channelAveragingMap[7][0] == 5208 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[7][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[8][0]", "8 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch == 5 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch == 25", "== 1 assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBandOffsetStream1 == 0 assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBandOffsetStream2 == 0 assert proxies.vcc[proxies.receptor_to_vcc[2]].rfiFlaggingMask ==", "attributes of search windows # first for search window 1... assert sw_1_proxy.State() ==", "broken.\") def test_AddRemoveReceptors_invalid_multiple(self, proxies): \"\"\" Test invalid AddReceptors commands involving multiple subarrays: -", "for weights in timing_beam_weights[\"beamWeights\"]: weights[\"epoch\"] = epoch epoch = str(int(epoch) + 10) #", "[ # DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[1]", "assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcEnable == True # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcNumBits == 8", "VCC belonging to receptor 1... assert vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership == 1 # check", "zip(range(3), [1, 3, 4])]) # configure scan f1 = open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f1.read().replace(\"\\n\",", "assert searchBeam300[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" # assert searchBeam400[\"searchBeamID\"] == 400 # assert searchBeam400[\"receptors\"][0] ==", "searchBeam1[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" # check configured attributes of FSP subarrays # first for", "proxy in fsp_1_function_mode_proxy] == [ DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ] # assert [proxy.State()", "-*- coding: utf-8 -*- # # This file is part of the csp-lmc-prototype", "proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE ############################# abort from READY ########################### #", "in proxies.vccBand[proxies.receptor_to_vcc[4] - 1]: logging.info(\"VCC proxy.State() = {}\".format(proxy.State())) assert [proxy.State() for proxy in", "for pair in # cbf_master_proxy.receptorToVcc) # cbf_master_proxy.On() # time.sleep(60) # # turn on", "vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand == 0 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand == 0 # check", "proxies.subarray[1].receptors[0] == 1 # assert proxies.subarray[1].receptors[1] == 3 # assert proxies.subarray[1].receptors[2] == 4", "# first for search window 1... # assert sw_1_proxy.State() == DevState.ON # assert", "\"{}\" # # check configured attributes of search windows # # first for", "of FSP subarrays # # first for FSP 1... # assert fsp_1_proxies.subarray[1].obsState ==", "fix this # try adding an invalid receptor ID # with pytest.raises(tango.DevFailed) as", "this doesn't actually throw an error proxies.subarray[1].RemoveReceptors([2]) assert proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1]", ")) assert len(proxies.subarray[1].receptors) == 0 assert proxies.subarray[1].configID == '' # TODO in CbfSubarray,", "proxies.vcc[vcc_ids[num_receptors -1]].obsState == ObsState.READY assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.READY for fsp in input_config_dict[\"cbf\"][\"fsp\"]: if", "fsp_1_proxy, fsp_2_proxy, fsp_1_function_mode_proxy, fsp_2_function_mode_proxy, fsp_1_proxies.subarray[1], fsp_2_proxies.subarray[1], fsp_3_proxies.subarray[1], tm_telstate_proxy ): \"\"\" Test a minimal", "2... # assert proxies.sw[2].State() == DevState.DISABLE # assert proxies.sw[2].searchWindowTuning == 7000000000 # assert", "== 4.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 4.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 4.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] ==", "an invalid one) to subarray 2 # with pytest.raises(tango.DevFailed) as df: # subarray_2_proxy.AddReceptors([1,", "model values against input json @pytest.mark.skip(reason=\"test needs to be refactored\") def test_ConfigureScan_delayModel(self, proxies):", "assert sub_id == int(configuration[\"common\"][\"subarray_id\"]) assert proxies.subarray[sub_id].configID == configuration[\"common\"][\"config_id\"] assert proxies.subarray[sub_id].frequencyBand == band_index assert", "proxies.clean_proxies() raise e def test_AddRemoveReceptors_invalid_single(self, proxies): \"\"\" Test invalid AddReceptors commands involving a", "string ( via attribute 'searchBeams'); # this has to be updated in FspPssSubarray", "== 2.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 2.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 2.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] ==", "== DevState.DISABLE # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].searchWindowTuning == 7000000000 # assert vcc_tdc_proxies[receptor_to_vcc[4] -", "== DevState.ON assert sw_1_proxy.searchWindowTuning == 6000000000 assert sw_1_proxy.tdcEnable == True assert sw_1_proxy.tdcNumBits ==", "1 # assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[0] == 5.85 # assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[1]", "== input_band_index assert proxies.subarray[subarr_index].obsState == ObsState.READY # Send the Scan command f2 =", "raise e @pytest.mark.skip(reason=\"pst not currently supported\") def test_ConfigureScan_onlyPst_basic(self, proxies): \"\"\" Test a successful", "== 4.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 4.4 time.sleep(10) assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 0.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1]", "1... assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].State() == DevState.DISABLE assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].searchWindowTuning == 7000000000", "== 2.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 2.4 proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1, 1) proxies.clean_proxies() except", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[8][0] == 5952 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[8][1] == 8 # #", "== ObsState.IDLE logging.info( \"First vcc obsState BEFORE ConfigureScan = {}\". format(proxies.vcc[vcc_ids[0]].obsState) ) f", "which one to keep. # print(\"proxies.sw[1].State() = {}\".format(proxies.sw[1].State())) # print(\"proxies.sw[2].State() = {}\".format(proxies.sw[2].State())) #", "proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].searchWindowTuning == 6000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcEnable == True assert proxies.vccTdc[proxies.receptor_to_vcc[4]", "assert [proxy.State() for proxy in proxies.vccBand[proxies.receptor_to_vcc[2] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE,", "proxies.fspSubarray[3].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY # ObsReset", "12649 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[17][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[18][0] == 13393", "ObsState.IDLE, 1, 1) assert proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1] == 3 assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership", "1][0].searchWindowTuning == 6000000000 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcEnable == True assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcNumBits", "1) for proxy in [proxies.fsp[i + 1] for i in range(4)]: if proxy.State()", "to initialize # receptor_to_vcc = dict([*map(int, pair.split(\":\"))] for pair in # cbf_controller_proxy.receptorToVcc) #", "attributes of search windows # first for search window 1... # TODO -", "proxies.sw[1].tdcNumBits == 8 # assert proxies.sw[1].tdcPeriodBeforeEpoch == 5 # assert proxies.sw[1].tdcPeriodAfterEpoch == 25", "range(4)]) # add some receptors proxies.subarray[1].AddReceptors([1, 3, 4]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert", "of PST-BF parameters to FSP \"\"\" try: # turn on Subarray if proxies.subarray[1].State()", "input_receptors = input_test_data[0] config_file_name = input_test_data[1] subarr_index = 1; logging.info( \"input_receptors = {}\".format(input_receptors)", "1][0].State() == DevState.ON assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].searchWindowTuning == 6000000000 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcEnable", "assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].searchWindowTuning == 6000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcEnable == True assert", "ObsState.IDLE logging.info( \"First vcc obsState BEFORE ConfigureScan = {}\". format(proxies.vcc[vcc_ids[0]].obsState) ) f =", "# proxies.subarray[1].Init() # subarray_2_proxy.Init() # time.sleep(3) # cbf_controller_proxy.set_timeout_millis(60000) # cbf_controller_proxy.Init() # time.sleep(60) #", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 2.4 proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1, 1) proxies.clean_proxies() except AssertionError as ae:", "receptor in jones_matrix[\"jonesMatrix\"][2][\"matrixDetails\"]: for frequency_slice in receptor[\"receptorMatrix\"]: for index, value in enumerate(frequency_slice[\"matrix\"]): vcc_id", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[2][0] == 1488 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[2][1] == 8 #", "all private data #assert proxies.subarray[sub_id].frequencyBand == 0 assert proxies.subarray[sub_id].obsState == ObsState.EMPTY # add", "fsp_2_proxy, # fsp_1_function_mode_proxy, # fsp_2_function_mode_proxy, # fsp_1_proxies.subarray[1], # fsp_2_proxies.subarray[1], # fsp_3_proxies.subarray[1], # tm_telstate_proxy", "i, j in zip(range(4), [4, 1, 3, 2])]) # configure scan f =", "for FSP 1... assert fsp_1_proxies.subarray[1].obsState == ObsState.READY assert fsp_1_proxies.subarray[1].frequencyBand == 0 assert fsp_1_proxies.subarray[1].frequencySliceID", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[19][1] == 0 # # then for FSP 3... #", "fsp in input_config_dict[\"cbf\"][\"fsp\"]: if fsp[\"function_mode\"] == \"CORR\": assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.SCANNING elif fsp[\"function_mode\"]", "assert fsp_2_proxies.subarray[1].channelAveragingMap[10][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[11][0] == 8185 # # assert", "proxies.subarray[1].RemoveReceptors([2, 1, 4]) time.sleep(1) assert proxies.subarray[1].receptors == ([3]) assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 0 for", "assert proxies.fspSubarray[1].channelAveragingMap[1][0] == 744 assert proxies.fspSubarray[1].channelAveragingMap[1][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[2][0] == 1488 assert", "proxies.subarray[1].obsState == ObsState.EMPTY ############################# abort from IDLE ########################### # add receptors proxies.subarray[1].AddReceptors([1, 3,", "# assert fsp_1_subarray_1_proroxy.receptors[2] == 4 # # assert fsp_2_proxies.subarray[1].frequencyBand == 4 # #", "vcc_proxies: # proxy.Init() # fsp_1_proxies.subarray[1].Init() # fsp_2_proxies.subarray[1].Init() # fsp_3_proxies.subarray[1].Init() # fsp_1_proxy.Init() # fsp_2_proxy.Init()", "DevState.STANDBY, 3, 1) proxies.controller.On() proxies.wait_timeout_dev([proxies.controller], DevState.ON, 3, 1) proxies.clean_proxies() # turn on Subarray", "_ in range(num_receptors)] for receptor_id, ii in zip(input_receptors, range(num_receptors)): vcc_ids[ii] = proxies.receptor_to_vcc[receptor_id] proxies.subarray[subarr_index].AddReceptors(input_receptors)", "# assert vcc_band_proxies[i].State() == DevState.DISABLE # check configured attributes of FSPs, including states", "# assert sw_1_proxy.tdcPeriodBeforeEpoch == 5 # assert sw_1_proxy.tdcPeriodAfterEpoch == 25 # assert \"\".join(sw_1_proxy.tdcDestinationAddress.split())", "proxies.clean_proxies() raise e #TODO: fix; currently tests break if multiple scan configurations are", "assert proxies.subarray[1].obsState == ObsState.EMPTY ############################# abort from READY ########################### # add receptors proxies.subarray[1].AddReceptors([1,", "for VCC belonging to receptor 10... # assert vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership == 1", "or causing a fault within the Vcc device # for proxy in vcc_band_proxies:", "of VCC belonging to receptor 10... # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].State() == DevState.DISABLE", "Subarray # assert proxies.subarray[1].state()==DevState.OFF # proxies.subarray[1].On() # time.sleep(10) # # check initial value", "2 assert searchBeam400[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" proxies.subarray[1].GoToIdle() time.sleep(3) assert proxies.subarray[1].obsState == ObsState.IDLE proxies.subarray[1].RemoveAllReceptors() time.sleep(3)", "# # check frequency band of VCCs, including states of frequency band capabilities", "assert searchBeam400[\"averagingInterval\"] == 2 assert searchBeam400[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" proxies.subarray[1].GoToIdle() time.sleep(3) assert proxies.subarray[1].obsState ==", "fsp_2_proxies.subarray[1].channelAveragingMap[10][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[11][0] == 8185 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[11][1]", "check configured attributes of FSPs, including states of function mode capabilities fsp_function_mode_proxies =", "== 25 # assert \"\".join(sw_1_proxy.tdcDestinationAddress.split()) in [ # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\",", "receptor_id, ii in zip(input_receptors, range(num_receptors)): vcc_ids[ii] = proxies.receptor_to_vcc[receptor_id] proxies.subarray[subarr_index].AddReceptors(input_receptors) proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.IDLE, 1, 1)", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 2.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 2.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 3.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2]", "receptor 10... # assert vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership == 1 # assert vcc_proxies[receptor_to_vcc[4] -", "1][0].tdcNumBits == 8 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch == 5 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch", "# update delay model proxies.tm.delayModel = json.dumps(delay_model) time.sleep(1) for model in delay_model[\"delayModel\"]: if", "= os.path.dirname(os.path.abspath(__file__)) # Tango imports import tango from tango import DevState import pytest", "proxies.subarray[1].obsState == ObsState.READY # Clean Up proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise", "fsp_1_proxy, # fsp_2_proxy, # fsp_1_function_mode_proxy, # fsp_2_function_mode_proxy, # fsp_1_proxies.subarray[1], # fsp_2_proxies.subarray[1], # fsp_3_proxies.subarray[1],", "windows # # first for search window 1 of VCC belonging to receptor", "if multiple scan configurations are tested def test_ConfigureScan_basic(self, proxies): \"\"\" Test a successful", "# proxies.subarray[1].GoToIdle() # time.sleep(3) # assert proxies.subarray[1].obsState == ObsState.IDLE # proxies.subarray[1].RemoveAllReceptors() # time.sleep(3)", "[1, 3, 4])]) assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for i in [1, 3, 4]])", "assert sw_2_proxy.searchWindowTuning == 7000000000 assert sw_2_proxy.tdcEnable == False # check configured attributes of", "\"\")) f.close() time.sleep(15) # check configured attributes of CBF subarray assert proxies.subarray[1].configID ==", "EndScan() command assert proxies.subarray[subarr_index].obsState == ObsState.SCANNING assert proxies.vcc[vcc_ids[0]].obsState == ObsState.SCANNING assert proxies.vcc[vcc_ids[num_receptors-1]].obsState ==", "decide which one to keep. # print(\"proxies.sw[1].State() = {}\".format(proxies.sw[1].State())) # print(\"proxies.sw[2].State() = {}\".format(proxies.sw[2].State()))", "VCC {}, i = {}, jonesMatrix[{}] = {}\".format( jones_matrix[\"jonesMatrix\"][1][\"epoch\"], vcc_id, index, fs_id-1, proxies.vcc[vcc_id].jonesMatrix[fs_id-1])", "fsp device) assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[1].receptors == 4 assert proxies.fspSubarray[1].frequencyBand ==", "== ObsState.ABORTED # Restart: receptors should be empty proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1)", "CBF subarray assert proxies.subarray[1].configID == \"sbi-mvp01-20200325-00001-science_A\" assert proxies.subarray[1].frequencyBand == 0 # means 1", "proxy in proxies.vccBand[proxies.receptor_to_vcc[4] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] assert [proxy.State()", "sw_1_proxy, sw_2_proxy, vcc_proxies, vcc_band_proxies, vcc_tdc_proxies, fsp_1_proxy, fsp_2_proxy, fsp_1_function_mode_proxy, fsp_2_function_mode_proxy, fsp_3_proxies.subarray[1], tm_telstate_proxy ): \"\"\"", "if (i == 0 and band_index == 0) or (i == (band_index -", "proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) # configure scan f =", "1, 4]) time.sleep(1) assert proxies.subarray[1].receptors == ([3]) assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 0 for i", "== value except AssertionError as ae: logging.error(\"AssertionError; incorrect Jones matrix entry: epoch {},", "# proxies.subarray[1].Init() # time.sleep(3) # cbf_master_proxy.set_timeout_millis(60000) # cbf_master_proxy.Init() # time.sleep(60) # takes pretty", "first for search window 1... assert sw_1_proxy.State() == DevState.ON assert sw_1_proxy.searchWindowTuning == 6000000000", "\"config_file_name = {}\".format(config_file_name) ) num_receptors = len(input_receptors) vcc_ids = [None for _ in", "# add receptors proxies.subarray[sub_id].AddReceptors(test_receptor_ids) proxies.wait_timeout_obs([proxies.subarray[sub_id]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[sub_id].receptors[i] == j for", "== 300 assert proxies.fspSubarray[3].searchBeamID[1] == 400 # TODO: currently searchBeams is stored by", "\"buzz\", \"80\" # ) # # then for search window 2 of VCC", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[3][0] == 2233 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[3][1] == 0 #", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 0.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 0.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 0.3 assert", "# add receptors proxies.subarray[1].AddReceptors([1, 3, 4]) time.sleep(1) assert proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1]", "1][0].tdcPeriodAfterEpoch == 25 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcDestinationAddress == ( # \"fizz\", \"buzz\",", "subarray 1 # doing this doesn't actually throw an error proxies.subarray[1].RemoveReceptors([2]) assert proxies.subarray[1].receptors[0]", "10) # update delay model proxies.tm.delayModel = json.dumps(delay_model) time.sleep(1) for model in delay_model[\"delayModel\"]:", "logging.info( \"input_receptors = {}\".format(input_receptors) ) logging.info( \"config_file_name = {}\".format(config_file_name) ) num_receptors = len(input_receptors)", "subarray # assert len(proxies.subarray[1].receptors) == 0 # assert proxies.subarray[1].configID == 0 # assert", "proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 15, 1) # update jones matrices from tm", "in range(len(fsp[\"channel_averaging_map\"])): for j in range(len(fsp[\"channel_averaging_map\"][i])): assert proxies.fspSubarray[fsp_id].channelAveragingMap[i][j] == fsp[\"channel_averaging_map\"][i][j] for i in", "+ \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) # scan f2 =", "744 channels average factor 8\" assert proxies.subarray[1].frequencyBand == 4 assert proxies.subarray[1].obsState == ObsState.READY", "proxies.subarray[1].obsState == ObsState.EMPTY # add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1,", "== 1400 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[0][0] == 1 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[0][1] ==", "[1, 3]]) assert proxies.subarray[1].obsState == ObsState.IDLE # TODO: fix this # try adding", "models from tm emulator f = open(file_path + \"/../data/delaymodel_fsp.json\") delay_model = json.loads(f.read().replace(\"\\n\", \"\"))", "input_config_dict = json.loads(json_string) proxies.subarray[subarr_index].ConfigureScan(json_string) f.close() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.READY, 15, 1) logging.info( \"First vcc obsState", "1][1].tdcEnable == False # # and lastly for search window 2 of VCC", "assert proxies.vcc[vcc_ids[num_receptors -1]].obsState == ObsState.READY assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.READY for fsp in input_config_dict[\"cbf\"][\"fsp\"]:", "in proxies.vccBand[proxies.receptor_to_vcc[1] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # check the", "== 0 for i in [1, 2, 4]]) assert proxies.vcc[proxies.receptor_to_vcc[3]].subarrayMembership == 1 #", "tm_telstate_proxy.Init() # time.sleep(1) # receptor_to_vcc = dict([*map(int, pair.split(\":\"))] for pair in # cbf_master_proxy.receptorToVcc)", "assert fsp_1_proxies.subarray[1].outputLinkMap[0][0] == 1 assert fsp_1_proxies.subarray[1].outputLinkMap[0][1] == 0 assert fsp_1_proxies.subarray[1].outputLinkMap[1][0] == 201 assert", "device) assert proxies.fspSubarray[3].receptors[0] == 3 assert proxies.fspSubarray[3].receptors[1] == 1 assert proxies.fspSubarray[3].searchWindowID == 2", "4])]) # configure scan f1 = open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f1.read().replace(\"\\n\", \"\")) f1.close() proxies.wait_timeout_obs([proxies.subarray[1]],", "# assert searchBeam400[\"outputEnable\"] == True # assert searchBeam400[\"averagingInterval\"] == 2 # assert searchBeam400[\"searchBeamDestinationAddress\"]", "4.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 4.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 4.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 4.4", "& fix #assert searchBeam0[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" assert searchBeam1[\"search_beam_id\"] == 400 assert searchBeam1[\"receptor_ids\"][0] ==", "proxies.subarray[1].obsState == ObsState.IDLE # remove all receptors proxies.subarray[1].RemoveAllReceptors() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert", "a receptor to be added is already in use by a different subarray", "#assert searchBeam0[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" assert searchBeam1[\"search_beam_id\"] == 400 assert searchBeam1[\"receptor_ids\"][0] == 1 assert", "- 1][0].tdcDestinationAddress == ( # \"fizz\", \"buzz\", \"80\" # ) # # then", "assert proxies.fspSubarray[1].frequencyBandOffsetStream2 == 0 assert proxies.fspSubarray[1].frequencySliceID == 1 assert proxies.fspSubarray[1].corrBandwidth == 1 assert", "0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[17][0] == 12649 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[17][1] == 0", "receptor 1... assert vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership == 1 assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[0] ==", "takes a while # proxies.subarray[1].Init() # time.sleep(3) # cbf_master_proxy.set_timeout_millis(60000) # cbf_master_proxy.Init() # time.sleep(60)", "proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.SCANNING assert proxies.fspSubarray[1].obsState == ObsState.SCANNING assert proxies.fspSubarray[3].obsState == ObsState.SCANNING proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]],", "= proxies.vccBand[vcc_index - 1] # turn on Subarray if proxies.subarray[sub_id].State() != DevState.ON: proxies.subarray[sub_id].On()", "VCCs, including states of frequency band capabilities assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBand == 4 assert [proxy.State()", "0) or (i == (band_index - 1)): # assert vcc_band_proxies[i].State() == DevState.ON #", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[7][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[8][0] == 5952 #", "fsp_1_proxies.subarray[1].outputLinkMap[2][1] == 12 # assert fsp_1_proxies.subarray[1].outputLinkMap[3][0] == 2232 # assert fsp_1_subarray_1_proroxy.receptors[2] == 4", "check does not pass, to fix #elif fsp[\"function_mode\"] == \"PST-BF\": # assert proxies.fspPstSubarray[subarr_index-1].obsState", "= json.dumps(timing_beam_weights) time.sleep(1) for weights in timing_beam_weights[\"beamWeights\"]: for receptor in weights[\"beamWeightsDetails\"]: rec_id =", "removed is not assigned to the subarray \"\"\" try: # turn on Subarray", "capabilities assert proxies.fsp[1].functionMode == 1 assert 1 in proxies.fsp[1].subarrayMembership assert [proxy.State() for proxy", "3, 4])]) # configure scan f1 = open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f1.read().replace(\"\\n\", \"\")) f1.close()", "proxies.subarray[1].obsState == ObsState.EMPTY # receptor list should be empty right after initialization assert", "be empty proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY assert len(proxies.subarray[1].receptors)", "in [ \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", ] # then for search window 2...", "and lastly for search window 2 of VCC belonging to receptor 1... #", "check initial value of attributes of CBF subarray # assert len(proxies.subarray[1].receptors) == 0", "[1, 3, 4]]) assert proxies.subarray[1].obsState == ObsState.IDLE # remove all receptors proxies.subarray[1].RemoveAllReceptors() proxies.wait_timeout_obs([proxies.subarray[1]],", "+ 20) jones_matrix[\"jonesMatrix\"][1][\"epoch\"] = \"0\" jones_matrix[\"jonesMatrix\"][2][\"epoch\"] = str(int(time.time()) + 10) # update Jones", "configured attributes of FSP subarrays # first for FSP 1... assert fsp_1_proxies.subarray[1].obsState ==", "fsp_3_proxies.subarray[1].Init() fsp_1_proxy.Init() fsp_2_proxy.Init() time.sleep(3) cbf_master_proxy.set_timeout_millis(60000) cbf_master_proxy.Init() time.sleep(60) # takes pretty long for CBF", "json.loads(searchBeam[0]) # searchBeam400 = json.loads(searchBeam[1]) # assert searchBeam300[\"searchBeamID\"] == 300 # assert searchBeam300[\"receptors\"][0]", "raise e time.sleep(10) # update delay models from tm emulator f = open(file_path", "4, 2] assert proxies.vcc[proxies.receptor_to_vcc[2]].subarrayMembership == 1 # remove some receptors proxies.subarray[1].RemoveReceptors([2, 1, 4])", "band capabilities assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand == 0 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand ==", "== 4700000 # assert fsp_1_proxies.subarray[1].integrationTime == 140 # assert fsp_1_proxies.subarray[1].fspChannelOffset == 14880 #", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 3.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 3.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 3.6 assert", "assert proxies.subarray[1].obsState == ObsState.READY assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[3].obsState == ObsState.READY assert", "for search window 1 of VCC belonging to receptor 1... assert proxies.vccTdc[proxies.receptor_to_vcc[1] -", "== False # and lastly for search window 2 of VCC belonging to", "proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY ############################# abort from IDLE", "== '' assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState.value == ObsState.IDLE.value # assert tm_telstate_proxy.visDestinationAddress", "1) # check frequency band of VCCs, including states of frequency band capabilities", "[proxy.State() for proxy in fsp_function_mode_proxies[fsp_id-1]] == [ DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ] #", "+ \"/../data/jonesmatrix.json\") jones_matrix = json.loads(f.read().replace(\"\\n\", \"\")) f.close() jones_matrix[\"jonesMatrix\"][0][\"epoch\"] = str(int(time.time()) + 20) jones_matrix[\"jonesMatrix\"][1][\"epoch\"]", "window 2 of VCC belonging to receptor 1... assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].State() ==", "\"/../data/Configure_TM-CSP_v2.json\") configuration = f.read().replace(\"\\n\", \"\") f.close() proxies.subarray[sub_id].ConfigureScan(configuration) proxies.wait_timeout_obs([proxies.subarray[sub_id]], ObsState.READY, 15, 1) configuration =", "single subarray: - when a receptor ID is invalid (e.g. out of range)", "empty proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY assert len(proxies.subarray[1].receptors) ==", "mode to enum or edit attribute to accept string in FSP if fsp[\"function_mode\"]", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[2][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[3][0] == 2233 # #", "check frequency band of VCCs, including states of frequency band capabilities assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBand", "1 in proxies.fsp[1].subarrayMembership assert [proxy.State() for proxy in proxies.fsp1FunctionMode] == [ DevState.ON, DevState.DISABLE,", "== ObsState.EMPTY # Input test data: input_receptors = input_test_data[0] config_file_name = input_test_data[1] subarr_index", "11160 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[15][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[16][0] == 11904", "assert proxies.subarray[1].obsState == ObsState.EMPTY # receptor list should be empty right after initialization", "of search windows # first for search window 1... # TODO - SearchWidow", "for i in [1, 3, 4]]) assert proxies.subarray[1].obsState == ObsState.IDLE # remove all", "== 3 # assert fsp_3_proxies.subarray[1].receptors[1] == 1 # assert fsp_3_proxies.subarray[1].searchWindowID == 2 #", "for i in [1, 3, 4]]) assert proxies.subarray[1].obsState == ObsState.EMPTY proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.OFF,", "DevState.ON assert sw_1_proxy.searchWindowTuning == 6000000000 assert sw_1_proxy.tdcEnable == True assert sw_1_proxy.tdcNumBits == 8", "2 # assert searchBeam400[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" # proxies.subarray[1].GoToIdle() # time.sleep(3) # assert proxies.subarray[1].obsState", "== 1.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 1.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 1.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] ==", "4 assert searchBeam300[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" assert searchBeam400[\"searchBeamID\"] == 400 assert searchBeam400[\"receptors\"][0] == 1", "= {}\".format(proxies.sw[1].State())) # print(\"proxies.sw[2].State() = {}\".format(proxies.sw[2].State())) # assert proxies.sw[1].State() == DevState.ON # assert", "for matrix in jones_matrix[\"jonesMatrix\"]: matrix[\"epoch\"] = epoch if matrix[\"destinationType\"] == \"fsp\": epoch =", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[18][0] == 13393 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[18][1] == 0 # #", "proxies.wait_timeout_dev([proxies.controller], DevState.ON, 3, 1) proxies.clean_proxies() # turn on Subarray if proxies.subarray[1].State() != DevState.ON:", "check configured attributes of FSP subarrays # first for FSP 1... assert fsp_1_proxies.subarray[1].obsState", "== ObsState.SCANNING time.sleep(10) for receptor in jones_matrix[\"jonesMatrix\"][2][\"matrixDetails\"]: for frequency_slice in receptor[\"receptorMatrix\"]: for index,", "== 4 assert proxies.subarray[1].obsState == ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i + 1] for i in range(4)],", "3, 4]) # time.sleep(1) # assert proxies.subarray[1].receptors[0] == 1 # assert proxies.subarray[1].receptors[1] ==", "[ # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", # ] # #", "assert searchBeam1[\"enable_output\"] == True assert searchBeam1[\"averaging_interval\"] == 2 # TODO - this does", "assert proxies.subarray[1].frequencyBand == 4 # means 5a? # assert proxies.subarray[1].obsState.value == ObsState.READY.value #", "Input test data: input_receptors = input_test_data[0] config_file_name = input_test_data[1] subarr_index = 1; logging.info(", "proxies.fspSubarray[1].scanID == 1 assert proxies.vcc[proxies.receptor_to_vcc[4]].scanID ==1 # check states assert proxies.subarray[1].obsState == ObsState.SCANNING", "# check configured attributes of FSP subarrays # FSP 2 assert proxies.fspSubarray[6].obsState ==", "assert sw_1_proxy.tdcEnable == True # assert sw_1_proxy.tdcNumBits == 8 # assert sw_1_proxy.tdcPeriodBeforeEpoch ==", "# assert searchBeam300[\"receptors\"][0] == 3 # assert searchBeam300[\"outputEnable\"] == True # assert searchBeam300[\"averagingInterval\"]", "searchBeam400 = json.loads(searchBeam[1]) assert searchBeam300[\"searchBeamID\"] == 300 assert searchBeam300[\"receptors\"][0] == 3 assert searchBeam300[\"outputEnable\"]", "vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch == 25 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcDestinationAddress == ( \"foo\", \"bar\",", "1 assert searchBeam1[\"enable_output\"] == True assert searchBeam1[\"averaging_interval\"] == 2 # TODO - this", "2977 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[4][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[5][0] == 3721", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[3][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[4][0] == 2976 # #", "1... # assert fsp_1_proxies.subarray[1].obsState == ObsState.EMPTY # assert fsp_1_proxies.subarray[1].receptors == 4 # assert", "receptor[\"receptorMatrix\"]: for index, value in enumerate(frequency_slice[\"matrix\"]): vcc_id = proxies.receptor_to_vcc[receptor[\"receptor\"]] fs_id = frequency_slice[\"fsid\"] try:", "proxies.fspSubarray[1].obsState == ObsState.IDLE assert proxies.fspSubarray[3].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 3.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 3.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 3.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1]", "controller to initialize # receptor_to_vcc = dict([*map(int, pair.split(\":\"))] for pair in # cbf_controller_proxy.receptorToVcc)", "== 0 # # assert fsp_2_proxies.subarray[1].integrationTime == 1400 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[0][0] ==", "assert proxies.vcc[proxies.receptor_to_vcc[2]].rfiFlaggingMask == \"{}\" # check configured attributes of FSPs, including states of", "assert proxies.subarray[1].obsState == ObsState.READY # Clean Up proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies()", "initialization # assert proxies.subarray[1].receptors == () # assert subarray_2_proxy.receptors == () # assert", "([3]) assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 0 for i in [1, 2, 4]]) assert proxies.vcc[proxies.receptor_to_vcc[3]].subarrayMembership", "== 1400 assert fsp_1_proxies.subarray[1].outputLinkMap[0][0] == 1 assert fsp_1_proxies.subarray[1].outputLinkMap[0][1] == 0 assert fsp_1_proxies.subarray[1].outputLinkMap[1][0] ==", "== 5953 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[8][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[9][0] ==", "proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e def test_Abort_Reset(self, proxies):", "attributes of VCCs # first for VCC belonging to receptor 2... assert proxies.vcc[proxies.receptor_to_vcc[2]].subarrayMembership", "4]) # time.sleep(1) # assert \"already in use\" in str(df.value.args[0].desc) # assert subarray_2_proxy.receptors", "device) assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[1].receptors == 4 assert proxies.fspSubarray[1].frequencyBand == 4", "vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcNumBits == 8 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch == 5 assert vcc_tdc_proxies[receptor_to_vcc[4]", "receptors proxies.subarray[1].RemoveAllReceptors() proxies.subarray[1].AddReceptors([1, 3, 4]) time.sleep(1) assert proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1] ==", "doesn't actually throw an error proxies.subarray[1].RemoveReceptors([2]) assert proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1] ==", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[0][0] == 0 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[0][1] == 8 #", "1]] == [ # DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # # check the rest", "fsp_2_function_mode_proxy] == [ # # DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE # # ] #", "assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE ############################# abort from READY ########################### # add receptors proxies.subarray[1].AddReceptors([1,", "fsp_1_proxies.subarray[1].channelAveragingMap[0][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[1][0] == 744 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[1][1]", "of search windows # first for search window 1... assert sw_1_proxy.State() == DevState.ON", "# configure scan f = open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY,", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 0.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 0.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 0.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4]", "ObsState.READY assert proxies.vcc[vcc_ids[0]].obsState == ObsState.READY assert proxies.vcc[vcc_ids[num_receptors -1]].obsState == ObsState.READY assert proxies.fspCorrSubarray[subarr_index-1].obsState ==", "(\"proxies.vcc[vcc_index].frequencyBand = {}\". format( proxies.vcc[vcc_index].frequencyBand)) ) assert proxies.vcc[vcc_index].configID == configuration[\"common\"][\"config_id\"] assert proxies.vcc[vcc_index].frequencyBand ==", "while # proxies.subarray[1].Init() # time.sleep(3) # cbf_master_proxy.set_timeout_millis(60000) # cbf_master_proxy.Init() # time.sleep(60) # takes", "of CBF subarray # assert proxies.subarray[1].receptors == () # assert proxies.subarray[1].configID == 0", "ska_tango_base.control_model import LoggingLevel, HealthState from ska_tango_base.control_model import AdminMode, ObsState from ska_tango_base.base_device import _DEBUGGER_PORT", "== 6000000000 # assert sw_1_proxy.tdcEnable == True # assert sw_1_proxy.tdcNumBits == 8 #", "== 744 assert proxies.fspSubarray[1].channelAveragingMap[1][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[2][0] == 1488 assert proxies.fspSubarray[1].channelAveragingMap[2][1] ==", "# assert searchBeam300[\"outputEnable\"] == True # assert searchBeam300[\"averagingInterval\"] == 4 # assert searchBeam300[\"searchBeamDestinationAddress\"]", "i in [1, 3, 4]]) assert proxies.subarray[1].obsState == ObsState.EMPTY proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.OFF, 3,", "states of # frequency band capabilities logging.info( (\"proxies.vcc[vcc_index].frequencyBand = {}\". format( proxies.vcc[vcc_index].frequencyBand)) )", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 15, 1) # update jones matrices from tm emulator f =", "# then for search window 2... # assert proxies.sw[2].State() == DevState.DISABLE # assert", "assert fsp_2_proxies.subarray[1].channelAveragingMap[12][0] == 8929 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[12][1] == 0 # # assert", "== 2.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 3.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 3.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] ==", "[proxy.State() for proxy in proxies.fsp1FunctionMode] == [ DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ] #", "assert fsp_3_proxies.subarray[1].receptors[0] == 3 # assert fsp_3_proxies.subarray[1].receptors[1] == 1 # assert fsp_3_proxies.subarray[1].searchWindowID ==", "25 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcDestinationAddress == ( \"fizz\", \"buzz\", \"80\" ) # then", "check configured attributes of search windows # first for search window 1... assert", "# # first for FSP 1... # assert fsp_1_proxies.subarray[1].obsState == ObsState.EMPTY # assert", "fsp_1_proxies.subarray[1].frequencySliceID == 1 assert fsp_1_proxies.subarray[1].corrBandwidth == 0 assert fsp_1_proxies.subarray[1].integrationTime == 1400 assert fsp_1_proxies.subarray[1].outputLinkMap[0][0]", "e @pytest.mark.skip(reason=\"pst not currently supported\") def test_ConfigureScan_onlyPst_basic_FSP_scan_parameters(self, proxies): \"\"\" Test a successful transmission", "#TODO fix these tests; issue with VccBand devices either not reconfiguring in between", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[16][0] == 11904 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[16][1] == 8 #", "# TODO - SearchWidow device test is disabled since the same # functionality", "receptors proxies.subarray[1].RemoveAllReceptors() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert len(proxies.subarray[1].receptors) == 0 assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership ==", "json.loads(f.read().replace(\"\\n\", \"\")) epoch = str(int(time.time())) for weights in timing_beam_weights[\"beamWeights\"]: weights[\"epoch\"] = epoch epoch", "j in zip(range(3), [1, 3, 4])]) assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for i in", "- 1][0].tdcDestinationAddress == ( # \"fizz\", \"buzz\", \"80\" # ) # then for", "DevState.DISABLE, DevState.ON] # assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[1] - 1]] == [", "+ 1].subarrayMembership == 0 for i in range(4)]) input_receptors = [1, 3, 4]", "== DevState.ON def test_RemoveAllReceptors(self, proxies): \"\"\" Test RemoveAllReceptors command \"\"\" try: # turn", "2 # assert fsp_3_proxies.subarray[1].searchBeamID[0] == 300 # assert fsp_3_proxies.subarray[1].searchBeamID[1] == 400 # searchBeam", "proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY #############################", "data #assert proxies.subarray[sub_id].frequencyBand == 0 assert proxies.subarray[sub_id].obsState == ObsState.EMPTY # add receptors proxies.subarray[sub_id].AddReceptors(test_receptor_ids)", "assert fsp_1_proxies.subarray[1].corrBandwidth == 0 assert fsp_1_proxies.subarray[1].integrationTime == 1400 assert fsp_1_proxies.subarray[1].outputLinkMap[0][0] == 1 assert", "window 2 of VCC belonging to receptor 1... assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].State() ==", "== value except AssertionError as ae: raise ae except Exception as e: raise", "1].band5Tuning[0] == 5.85 # assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[1] == 7.25 # assert vcc_proxies[receptor_to_vcc[4]", "search windows # first for search window 1... assert sw_1_proxy.State() == DevState.ON assert", "proxies.subarray[1], sw_1_proxy, sw_2_proxy, vcc_proxies, vcc_band_proxies, vcc_tdc_proxies, fsp_1_proxy, fsp_2_proxy, fsp_1_function_mode_proxy, fsp_2_function_mode_proxy, fsp_1_proxies.subarray[1], fsp_2_proxies.subarray[1], fsp_3_proxies.subarray[1],", "== DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY # add", "DevState.DISABLE ] # assert [proxy.State() for proxy in fsp_2_function_mode_proxy] == [ # DevState.ON,", "4.4 time.sleep(10) assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 0.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 0.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] ==", "j in range(len(fsp[\"channel_averaging_map\"][i])): assert proxies.fspSubarray[fsp_id].channelAveragingMap[i][j] == fsp[\"channel_averaging_map\"][i][j] for i in range(len(fsp[\"output_link_map\"])): for j", "delay model values against input json @pytest.mark.skip(reason=\"test needs to be refactored\") def test_ConfigureScan_delayModel(self,", "of # frequency band capabilities logging.info( (\"proxies.vcc[vcc_index].frequencyBand = {}\". format( proxies.vcc[vcc_index].frequencyBand)) ) assert", "== 0 assert proxies.subarray[sub_id].configID == '' # TODO in CbfSubarray, at end of", "assert proxies.subarray[1].receptors == (1, 3) # assert all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership == 1 for", "in range(4): logging.info((\" proxies.vcc[{}].receptorID = {}\". format(jj+1, proxies.vcc[jj+1].receptorID))) logging.info( (\"Vcc, receptor 1, ObsState", "5.85 # assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[1] == 7.25 # assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream1", "proxies.vccBand[vcc_index - 1] assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBand == 4 assert proxies.vcc[proxies.receptor_to_vcc[1]].frequencyBand == 4 for proxy", "# first for FSP 1... assert fsp_1_proxies.subarray[1].obsState == ObsState.READY assert fsp_1_proxies.subarray[1].frequencyBand == 0", "+ 1] for i in range(4)], ObsState.READY, 1, 1) # check frequency band", "== ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i + 1] for i in range(4)], ObsState.READY, 1, 1) #", "== ObsState.SCANNING time.sleep(10) assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 2.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 2.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2]", "scan configuration \"\"\" proxies.subarray[1].loggingLevel = LoggingLevel.DEBUG try: # turn on Subarray if proxies.subarray[1].State()", "assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.READY proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae except", "including states of # frequency band capabilities logging.info( (\"proxies.vcc[vcc_index].frequencyBand = {}\". format( proxies.vcc[vcc_index].frequencyBand))", "subarray vcc_index = proxies.receptor_to_vcc[4] logging.info(\"vcc_index = {}\".format( vcc_index )) assert len(proxies.subarray[1].receptors) == 0", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[14][0] == 10417 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[14][1] == 0 # #", "ObsState.READY.value # check frequency band of VCCs, including states of frequency band capabilities", "0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[16][0] == 11905 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[16][1] == 0", "1][1].State() == DevState.DISABLE assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].searchWindowTuning == 7000000000 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].tdcEnable", "== 1.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 1.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 1.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] ==", "[proxy.State() for proxy in fsp_2_function_mode_proxy] == [ # # DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE", "fsp_1_proxies.subarray[1].channelAveragingMap[5][0] == 3720 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[5][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[6][0]", "then for VCC belonging to receptor 1... assert vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership == 1", "- 1][1].searchWindowTuning == 7000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].tdcEnable == False # and lastly", "1 assert fsp_1_proxies.subarray[1].outputLinkMap[0][1] == 0 assert fsp_1_proxies.subarray[1].outputLinkMap[1][0] == 201 assert fsp_1_proxies.subarray[1].outputLinkMap[1][1] == 1", "print(\"proxies.sw[2].State() = {}\".format(proxies.sw[2].State())) # assert proxies.sw[1].State() == DevState.ON # assert proxies.sw[1].searchWindowTuning == 6000000000", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[18][0] == 13392 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[18][1] == 8 #", "assert proxies.vcc[proxies.receptor_to_vcc[4]].rfiFlaggingMask == \"{}\" # then for VCC belonging to receptor 1... assert", "proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBandOffsetStream2 == 0 assert proxies.vcc[proxies.receptor_to_vcc[4]].rfiFlaggingMask == \"{}\" # then for VCC belonging to", "proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[1].receptors == 4 assert proxies.fspSubarray[1].frequencyBand == 4 assert proxies.fspSubarray[1].band5Tuning[0]", "fsp[\"output_link_map\"][i][j] proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae except Exception as e:", "# # check configured attributes of search windows # # first for search", "receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].obsState == ObsState.IDLE", "ObsState.READY, 1, 1) # check frequency band of VCCs, including states of #", "ObsState.IDLE, 1, 1) assert proxies.subarray[1].obsState == ObsState.IDLE assert all([proxies.subarray[1].receptors[i] == j for i,", "assert fsp_2_proxies.subarray[1].frequencyBandOffsetStream1 == 0 # # assert fsp_2_proxies.subarray[1].frequencyBandOffsetStream2 == 0 # # assert", "for proxy in vcc_proxies]) # assert proxies.subarray[1].State() == DevState.OFF # assert subarray_2_proxy.State() ==", "if matrix[\"destinationType\"] == \"fsp\": for receptor in matrix[\"matrixDetails\"]: rec_id = int(receptor[\"receptor\"]) fs_id =", "for 1 receptor per fsp test_receptor_ids = [4, 1] #test_receptor_ids = [1] vcc_index", "SCANNING ########################### # add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1)", "# # try adding some receptors (including an invalid one) to subarray 2", "# assert vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership == 1 # assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[0] ==", "# check initial value of attributes of CBF subarray # assert proxies.subarray[1].receptors ==", "lastly for search window 2 of VCC belonging to receptor 1... assert vcc_tdc_proxies[receptor_to_vcc[1]", "raise e def test_Abort_Restart(self, proxies): \"\"\" Test abort restart \"\"\" try: # turn", "epoch = str(int(time.time())) for model in delay_model[\"delayModel\"]: model[\"epoch\"] = epoch if model[\"destinationType\"] ==", "assert proxies.subarray[subarr_index].configID == input_config_dict[\"common\"][\"config_id\"] assert proxies.subarray[subarr_index].frequencyBand == input_band_index assert proxies.subarray[subarr_index].obsState == ObsState.READY #", "8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[14][0] == 10416 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[14][1] == 8", "in str(df.value.args[0].desc) # try removing a receptor not assigned to subarray 1 #", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 2.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 2.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 2.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0]", "== 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[14][0] == 10417 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[14][1] ==", "receptor 10... assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].State() == DevState.DISABLE assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].searchWindowTuning ==", "utf-8 -*- # # This file is part of the csp-lmc-prototype project #", "assert searchBeam0[\"search_beam_id\"] == 300 assert searchBeam0[\"receptor_ids\"][0] == 3 assert searchBeam0[\"enable_output\"] == True assert", "#!/usr/bin/env python # -*- coding: utf-8 -*- # # This file is part", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[0][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[1][0] == 745 #", "assert proxies.fspSubarray[1].band5Tuning[0] == 5.85 assert proxies.fspSubarray[1].band5Tuning[1] == 7.25 assert proxies.fspSubarray[1].frequencyBandOffsetStream1 == 0 assert", "0 assert vcc_proxies[receptor_to_vcc[1] - 1].rfiFlaggingMask == \"{}\" # check configured attributes of search", "7.25 # check configured attributes of search windows # first for search window", "of CBF subarray assert len(proxies.subarray[1].receptors) == 0 assert proxies.subarray[1].configID == '' assert proxies.subarray[1].frequencyBand", "1 assert proxies.fspSubarray[1].corrBandwidth == 1 assert proxies.fspSubarray[1].zoomWindowTuning == 4700000 assert proxies.fspSubarray[1].integrationTime == 1", "DevState.ON # else: # assert vcc_band_proxies[i].State() == DevState.DISABLE # check configured attributes of", "== 8 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch == 5 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch ==", "10) # update Jones Matrix proxies.tm.jonesMatrix = json.dumps(jones_matrix) time.sleep(5) for receptor in jones_matrix[\"jonesMatrix\"][1][\"matrixDetails\"]:", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 15, 1) # check configured attributes of CBF subarray assert proxies.subarray[1].configID", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[9][0] == 6696 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[9][1] == 8 #", "1, 1) # Note: scan_id is 1-based and of 'string' type # scan_index", "parameters to FSP \"\"\" try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON:", "# time.sleep(60) # takes pretty long for CBF Master to initialize # tm_telstate_proxy.Init()", "1][0].tdcEnable == True assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcNumBits == 8 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch", "= {}\". format(proxies.vcc[vcc_ids[0]].obsState) ) # check some configured attributes of CBF subarray frequency_band", "fsp_1_proxies.subarray[1].channelAveragingMap[0][0] == 0 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[0][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[1][0]", "ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.SCANNING assert proxies.fspSubarray[1].obsState == ObsState.SCANNING assert proxies.fspSubarray[3].obsState == ObsState.SCANNING", "# print(\"proxies.sw[1].State() = {}\".format(proxies.sw[1].State())) # print(\"proxies.sw[2].State() = {}\".format(proxies.sw[2].State())) # assert proxies.sw[1].State() == DevState.ON", "assert fsp_2_proxies.subarray[1].channelAveragingMap[5][0] == 3721 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[5][1] == 0 # # assert", "proxies.fspSubarray[1].channelAveragingMap[1][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[2][0] == 1488 assert proxies.fspSubarray[1].channelAveragingMap[2][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[3][0]", "+ 1].subarrayMembership == 0 for i in range(4)]) # add some receptors proxies.subarray[1].AddReceptors([1,", "for i, j in zip(range(1), [10])]) # Clean Up proxies.clean_proxies() except AssertionError as", "\"\"\" Test invalid AddReceptors commands involving a single subarray: - when a receptor", "proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.SCANNING, 1, 1) # Note: scan_id is 1-based and of 'string' type", "successful transmission of PST-BF parameters to FSP \"\"\" try: # turn on Subarray", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[10][0] == 7440 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[10][1] == 8 #", "] # check configured attributes of FSP subarrays # first for FSP 1...", "proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) assert proxies.subarray[1].obsState == ObsState.SCANNING assert proxies.subarray[1].scanID", "== 5 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch == 25 # TODO - re-enable and", "1][0].searchWindowTuning == 6000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcEnable == True assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcNumBits", "== ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY assert proxies.fspSubarray[1].obsState ==", "logging.info( \"First vcc obsState BEFORE ConfigureScan = {}\". format(proxies.vcc[vcc_ids[0]].obsState) ) f = open(file_path", "and 2 assert proxies.fspSubarray[fsp_id].obsState == ObsState.READY assert proxies.fspSubarray[fsp_id].receptors == test_receptor_ids[0] assert proxies.fspSubarray[fsp_id].frequencyBand ==", "check configured attributes of VCC search windows # first for search window 1", "ObsState.IDLE # TODO: fix this # try adding an invalid receptor ID #", "e: raise e # transition to obsState == SCANNING f2 = open(file_path +", "8 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch == 5 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch == 25", "== 1.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 2.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 2.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] ==", "RemoveReceptors commands \"\"\" timeout_millis = proxies.subarray[1].get_timeout_millis() log_msg = \"timeout_millis = {} \".format(timeout_millis) #logging.info(log_msg)", "in enumerate(receptor[\"receptorWeightsDetails\"][0][\"weights\"]): try: assert proxies.fsp[fs_id].timingBeamWeights[rec_id - 1][index] == value except AssertionError as ae:", "[ # # DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE # # ] # # check", "format(proxies.vcc[proxies.receptor_to_vcc[1]].ObsState)) ) #proxies.vcc[0].receptorID assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 1.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 1.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2]", "== \"10.05.2.1\" # proxies.subarray[1].GoToIdle() # time.sleep(3) # assert proxies.subarray[1].obsState == ObsState.IDLE # proxies.subarray[1].RemoveAllReceptors()", "== \"{}\" # then for VCC belonging to receptor 1... assert vcc_proxies[receptor_to_vcc[1] -", "proxies.subarray[1].obsState == ObsState.SCANNING time.sleep(10) assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 2.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 2.2 assert", "fsp[\"fsp_id\"] logging.info(\"{}\".format(fsp_id)) #TODO add function mode to enum or edit attribute to accept", "TODO - this does not pass - to debug & fix #assert searchBeam0[\"searchBeamDestinationAddress\"]", "proxy in proxies.vccBand[proxies.receptor_to_vcc[1] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # check", "== 2 assert fsp_3_proxies.subarray[1].searchBeamID[0] == 300 assert fsp_3_proxies.subarray[1].searchBeamID[1] == 400 searchBeam = fsp_3_proxies.subarray[1].searchBeams", "Matrix proxies.tm.jonesMatrix = json.dumps(jones_matrix) time.sleep(5) for receptor in jones_matrix[\"jonesMatrix\"][1][\"matrixDetails\"]: for frequency_slice in receptor[\"receptorMatrix\"]:", "\"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f1.read().replace(\"\\n\", \"\")) f1.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) # check initial states assert", "== ObsState.EMPTY proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.OFF, 3, 1) except AssertionError as ae: proxies.clean_proxies() raise", "# turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.ON, 3, 1)", "\"192.168.0.1\"], [8184, \"192.168.0.2\"]], \"outputMac\": [[0, \"06-00-00-00-00-01\"]], \"outputPort\": [[0, 9000, 1], [8184, 9000, 1]]}).replace('\"',\"'\")", "time.sleep(1) # assert proxies.subarray[1].receptors[0] == 1 # assert proxies.subarray[1].receptors[1] == 3 # assert", "- 1][1].State() == DevState.DISABLE assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].searchWindowTuning == 7000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[1] -", "fsp_2_proxies.subarray[1].channelAveragingMap[1][0] == 745 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[1][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[2][0]", "= open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) assert proxies.subarray[1].obsState", "assert proxies.fspSubarray[3].obsState == ObsState.READY # send the Scan command f2 = open(file_path +", "== 1.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 1.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 1.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] ==", "assert proxies.vcc[proxies.receptor_to_vcc[4]].scanID ==1 # check states assert proxies.subarray[1].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState ==", "fsp_1_proxies.subarray[1].channelAveragingMap[12][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[13][0] == 9672 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[13][1]", "all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 0 for i in [1, 3, 4]]) assert proxies.subarray[1].obsState == ObsState.EMPTY", "ae except Exception as e: proxies.clean_proxies() raise e def test_Abort_Reset(self, proxies): \"\"\" Test", "16 assert str(proxies.fspSubarray[1].visDestinationAddress).replace('\"',\"'\") == \\ str({\"outputHost\": [[0, \"192.168.0.1\"], [8184, \"192.168.0.2\"]], \"outputMac\": [[0, \"06-00-00-00-00-01\"]],", "# configure scan f1 = open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f1.read().replace(\"\\n\", \"\")) f1.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY,", "= [1, 3, 4] # add some receptors proxies.subarray[1].AddReceptors(input_receptors) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1)", "== 5 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch == 25 # assert vcc_tdc_proxies[receptor_to_vcc[1] -", "assert fsp_1_proxies.subarray[1].channelAveragingMap[6][0] == 4464 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[6][1] == 8 # # assert", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED assert proxies.fspSubarray[1].obsState == ObsState.READY assert", "proxies.subarray[1], # sw_1_proxy, # sw_2_proxy, # vcc_proxies, # vcc_band_proxies, # vcc_tdc_proxies, # fsp_1_proxy,", "logging.info( \"proxies.fspPstSubarray[subarr_index-1].obsState = {}\". format(proxies.fspPstSubarray[subarr_index-1].obsState) ) # Check obsStates BEFORE the EndScan() command", "assert fsp_1_proxies.subarray[1].outputLinkMap[0][1] == 4 # assert fsp_1_proxies.subarray[1].outputLinkMap[1][0] == 744 # assert fsp_1_proxies.subarray[1].outputLinkMap[1][1] ==", "searchBeam300 = json.loads(searchBeam[0]) searchBeam400 = json.loads(searchBeam[1]) assert searchBeam300[\"searchBeamID\"] == 300 assert searchBeam300[\"receptors\"][0] ==", "a successful transmission of PST-BF parameters to FSP \"\"\" try: # turn on", "== 0.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 0.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 0.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] ==", "assert proxies.fspSubarray[1].channelAveragingMap[1][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[2][0] == 1488 assert proxies.fspSubarray[1].channelAveragingMap[2][1] == 8 assert", "7440 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[10][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[11][0] == 8184", "DevState.ON assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].searchWindowTuning == 6000000000 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcEnable == True", "1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY ############################# abort from READY ########################### # add", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 1.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 1.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 2.0 assert", "5952 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[8][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[9][0] == 6696", "ObsState.SCANNING assert proxies.vcc[vcc_ids[0]].obsState == ObsState.SCANNING assert proxies.vcc[vcc_ids[num_receptors-1]].obsState == ObsState.SCANNING for fsp in input_config_dict[\"cbf\"][\"fsp\"]:", "ObsState.IDLE, 1, 1) assert all([proxies.subarray[subarr_index].receptors[i] == j for i, j in zip(range(num_receptors), input_receptors)])", "== int(configuration[\"common\"][\"subarray_id\"]) assert proxies.subarray[sub_id].configID == configuration[\"common\"][\"config_id\"] assert proxies.subarray[sub_id].frequencyBand == band_index assert proxies.subarray[sub_id].obsState ==", "== [ # DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE # ] # # assert [proxy.State()", "ae: proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e def test_Abort_Restart(self,", "fsp_2_proxies.subarray[1].channelAveragingMap[8][0] == 5953 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[8][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[9][0]", "j for i, j in zip(range(1), [2])]) assert all([proxies.fspSubarray[6].timingBeamID[i] == j for i,", "BEFORE scan configuration: assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.IDLE assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.IDLE assert proxies.fspPstSubarray[subarr_index-1].obsState", "states of frequency band capabilities # assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand == 4 #", "time.sleep(3) assert proxies.subarray[1].obsState == ObsState.IDLE proxies.subarray[1].RemoveAllReceptors() time.sleep(3) assert proxies.subarray[1].state() == tango.DevState.OFF def test_band1(", "assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.SCANNING # abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED,", "1].band5Tuning[1] == 7.25 assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream1 == 0 assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream2", "test_ConfigureScan_jonesMatrix(self, proxies): \"\"\" Test the reception of Jones matrices \"\"\" try: # turn", "proxies.subarray[1].set_timeout_millis(60000) # since the command takes a while proxies.subarray[1].Init() time.sleep(3) cbf_master_proxy.set_timeout_millis(60000) cbf_master_proxy.Init() time.sleep(60)", "assert fsp_1_proxies.subarray[1].channelAveragingMap[1][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[2][0] == 1488 # # assert", "vcc_index )) assert len(proxies.subarray[1].receptors) == 0 assert proxies.subarray[1].configID == '' # TODO in", "for _ in range(num_receptors)] for receptor_id, ii in zip(input_receptors, range(num_receptors)): vcc_ids[ii] = proxies.receptor_to_vcc[receptor_id]", "if matrix[\"destinationType\"] == \"fsp\": epoch = str(int(epoch) + 10) # update Jones Matrix", "== ObsState.IDLE.value # assert tm_telstate_proxy.visDestinationAddress == \"{}\" assert tm_telstate_proxy.receivedOutputLinks == False # add", "== 4 # assert fsp_1_proxies.subarray[1].outputLinkMap[1][0] == 744 # assert fsp_1_proxies.subarray[1].outputLinkMap[1][1] == 8 #", "for CBF Master to initialize # tm_telstate_proxy.Init() # time.sleep(1) # receptor_to_vcc = dict([*map(int,", "j in zip(range(3), [1, 3, 4])]) # configure scan config_file_name = \"/../data/ConfigureScan_basic.json\" f", "1][0].tdcPeriodAfterEpoch == 25 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcDestinationAddress == ( # \"foo\", \"bar\",", "== 2.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 2.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 3.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] ==", "= dict([*map(int, pair.split(\":\"))] for pair in # cbf_controller_proxy.receptorToVcc) # cbf_controller_proxy.On() # time.sleep(3) #", "== 25 # TODO - re-enable and debug! # assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcDestinationAddress", "proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies()", "f1.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) # check initial states assert proxies.subarray[1].obsState == ObsState.READY", "ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE ############################# abort from SCANNING", "proxies.controller.On() proxies.wait_timeout_dev([proxies.controller], DevState.ON, 3, 1) proxies.clean_proxies() # turn on Subarray if proxies.subarray[1].State() !=", "scan f1 = open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f1.read().replace(\"\\n\", \"\")) f1.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1)", "== DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) for proxy in [proxies.fsp[i + 1]", "proxies.subarray[1].GoToIdle() time.sleep(3) assert proxies.subarray[1].obsState == ObsState.IDLE proxies.subarray[1].RemoveAllReceptors() time.sleep(3) assert proxies.subarray[1].state() == tango.DevState.OFF def", "proxies.subarray[1].DebugDevice() try: proxies.clean_proxies() if proxies.controller.State() == DevState.OFF: proxies.controller.Init() proxies.wait_timeout_dev([proxies.controller], DevState.STANDBY, 3, 1) proxies.controller.On()", "ObsState.IDLE assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.IDLE assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.IDLE logging.info( \"First vcc obsState", "== j for i, j in zip(range(4), [4, 1, 3, 2])]) # configure", "fsp_2_proxies.subarray[1].channelAveragingMap[14][0] == 10417 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[14][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[15][0]", "def test_Abort_Reset(self, proxies): \"\"\" Test abort reset \"\"\" try: # turn on Subarray", "0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[11][0] == 8185 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[11][1] == 0", "1, 1) assert proxies.subarray[1].obsState == ObsState.SCANNING time.sleep(10) for receptor in jones_matrix[\"jonesMatrix\"][2][\"matrixDetails\"]: for frequency_slice", "= open(file_path + \"/../data/jonesmatrix_fsp.json\") jones_matrix = json.loads(f.read().replace(\"\\n\", \"\")) epoch = str(int(time.time())) for matrix", "== 0 assert proxies.fspSubarray[1].obsState == ObsState.IDLE assert proxies.fspSubarray[3].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState ==", "== 0 assert proxies.subarray[sub_id].obsState == ObsState.EMPTY # add receptors proxies.subarray[sub_id].AddReceptors(test_receptor_ids) proxies.wait_timeout_obs([proxies.subarray[sub_id]], ObsState.IDLE, 1,", "for proxy in fsp_2_function_mode_proxy] == [ # DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE # ]", "1 assert searchBeam400[\"outputEnable\"] == True assert searchBeam400[\"averagingInterval\"] == 2 assert searchBeam400[\"searchBeamDestinationAddress\"] == \"10.05.2.1\"", "assert fsp_3_proxies.subarray[1].receptors[1] == 1 assert fsp_3_proxies.subarray[1].searchWindowID == 2 assert fsp_3_proxies.subarray[1].searchBeamID[0] == 300 assert", "9000, 1], [8184, 9000, 1]]}).replace('\"',\"'\") # Clean Up proxies.clean_proxies() except AssertionError as ae:", "i in [2, 4]]) # assert subarray_2_proxy.State() == DevState.ON def test_RemoveAllReceptors(self, proxies): \"\"\"", "proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY # add receptors proxies.subarray[1].AddReceptors([1,", "a fault within the Vcc device # for proxy in vcc_band_proxies: # logging.info(\"VCC", "EndScan() command assert proxies.subarray[subarr_index].obsState == ObsState.READY assert proxies.vcc[vcc_ids[0]].obsState == ObsState.READY assert proxies.vcc[vcc_ids[num_receptors -1]].obsState", "proxies.wait_timeout_dev([proxies.subarray[1]], DevState.OFF, 3, 1) except AssertionError as ae: proxies.clean_proxies() raise ae except Exception", "for i in [1, 3]]) # assert proxies.subarray[1].State() == DevState.ON # # try", "assert proxies.fspSubarray[1].fspChannelOffset == 14880 assert proxies.fspSubarray[1].channelAveragingMap[0][0] == 0 assert proxies.fspSubarray[1].channelAveragingMap[0][1] == 8 assert", "raise ae except Exception as e: proxies.clean_proxies() raise e def test_Scan(self, proxies): \"\"\"", "DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) assert proxies.subarray[1].State() == DevState.ON assert proxies.subarray[1].obsState ==", "1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[3].obsState ==", "+ \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 15, 1) # check configured attributes", "proxies.vccBand[proxies.receptor_to_vcc[4] - 1]: logging.info(\"VCC proxy.State() = {}\".format(proxy.State())) assert [proxy.State() for proxy in proxies.vccBand[proxies.receptor_to_vcc[4]", "# DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE # # ] # # check configured attributes", "searchBeam = fsp_3_proxies.subarray[1].searchBeams # searchBeam300 = json.loads(searchBeam[0]) # searchBeam400 = json.loads(searchBeam[1]) # assert", "1.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 1.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 1.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 1.5", "# for proxy in vcc_proxies: # proxy.Init() # fsp_1_proxies.subarray[1].Init() # fsp_2_proxies.subarray[1].Init() # fsp_3_proxies.subarray[1].Init()", "# Check obsStates BEFORE the EndScan() command assert proxies.subarray[subarr_index].obsState == ObsState.SCANNING assert proxies.vcc[vcc_ids[0]].obsState", "ObsState.SCANNING assert proxies.fspSubarray[1].obsState == ObsState.SCANNING assert proxies.fspSubarray[3].obsState == ObsState.SCANNING proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1,", "fsp_1_function_mode_proxy] == [ DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ] # assert [proxy.State() for proxy", "5.85 assert proxies.vcc[proxies.receptor_to_vcc[4]].band5Tuning[1] == 7.25 assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBandOffsetStream1 == 0 assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBandOffsetStream2 == 0", "1][1].searchWindowTuning == 7000000000 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].tdcEnable == False # # and", "3720 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[5][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[6][0] == 4464", "# scan f2 = open(file_path + \"/../data/Scan2_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1,", "1) # Check obsStates AFTER the EndScan() command assert proxies.subarray[subarr_index].obsState == ObsState.READY assert", "abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED assert proxies.fspSubarray[1].obsState ==", "7.25 # assert fsp_1_proxies.subarray[1].frequencyBandOffsetStream1 == 0 # assert fsp_1_proxies.subarray[1].frequencyBandOffsetStream2 == 0 # assert", "config_file_name = \"/../data/ConfigureScan_basic.json\" f = open(file_path + config_file_name) proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY,", "8 # assert proxies.sw[1].tdcPeriodBeforeEpoch == 5 # assert proxies.sw[1].tdcPeriodAfterEpoch == 25 # assert", "3.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 3.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 3.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 3.9", "\"\")) f.close() aa = delay_model[\"delayModel\"][0][\"delayDetails\"][0][\"receptorDelayDetails\"] num_fsp_IDs = len(aa) for jj in range(num_fsp_IDs): logging.info(", "scan f = open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 15, 1)", "assert proxies.fspSubarray[1].channelAveragingMap[3][0] == 2232 assert proxies.fspSubarray[1].channelAveragingMap[3][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[4][0] == 2976 assert", "1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED # ObsReset proxies.subarray[1].ObsReset() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1)", "# assert proxies.subarray[1].ObsState == ObsState.EMPTY # # assert tm_telstate_proxy.visDestinationAddress == \"{}\" # assert", "receptors (including an invalid one) to subarray 2 # with pytest.raises(tango.DevFailed) as df:", "fsp_2_proxies.subarray[1].channelAveragingMap[11][0] == 8185 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[11][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[12][0]", "\"\"\" Test a successful scan configuration \"\"\" proxies.subarray[1].loggingLevel = LoggingLevel.DEBUG try: # turn", "== 744 # assert fsp_1_proxies.subarray[1].outputLinkMap[1][1] == 8 # assert fsp_1_proxies.subarray[1].outputLinkMap[2][0] == 1488 #", "# cbf_controller_proxy.On() # time.sleep(3) # # receptor list should be empty right after", "all([proxies.subarray[1].receptors[i] == j for i, j in zip(range(3), [1, 3, 4])]) assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership", "assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.SCANNING proxies.subarray[subarr_index].EndScan() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.READY, 1, 1) # Check obsStates AFTER", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[19][0] == 14136 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[19][1] == 8 #", "timing beam weights from tm emulator f = open(file_path + \"/../data/timingbeamweights.json\") timing_beam_weights =", "in input_config_dict[\"cbf\"][\"fsp\"]: if fsp[\"function_mode\"] == \"CORR\": assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.SCANNING elif fsp[\"function_mode\"] ==", "j in range(len(fsp[\"output_link_map\"][i])): assert proxies.fspSubarray[fsp_id].outputLinkMap[i][j] == fsp[\"output_link_map\"][i][j] proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies()", "proxies.tm.jonesMatrix = json.dumps(jones_matrix) time.sleep(5) for receptor in jones_matrix[\"jonesMatrix\"][1][\"matrixDetails\"]: for frequency_slice in receptor[\"receptorMatrix\"]: for", "assert tm_telstate_proxy.visDestinationAddress == \"{}\" assert tm_telstate_proxy.receivedOutputLinks == False # add receptors proxies.subarray[1].AddReceptors([1, 3,", "== 3.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 3.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 3.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] ==", "FSP if fsp[\"function_mode\"] == \"CORR\": function_mode = 1 elif fsp[\"function_mode\"] == \"PSS-BF\": function_mode", "- 1][0].tdcPeriodBeforeEpoch == 5 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch == 25 # TODO -", "fsp_1_proxies.subarray[1].channelAveragingMap[12][0] == 8928 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[12][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[13][0]", "configured attributes of search windows # first for search window 1... assert sw_1_proxy.State()", "= \"timeout_millis = {} \".format(timeout_millis) #logging.info(log_msg) #logging.info(\"start_time = {}\".format(time.time())) logging.info(\"start datetime = {}\".format(datetime.now()))", "vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].tdcEnable == False # # and lastly for search window 2", "1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY # add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2])", "= open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) # scan", "in fsp_1_function_mode_proxy] == [ # DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE # ] # #", "vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch == 5 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch == 25 assert vcc_tdc_proxies[receptor_to_vcc[1]", "proxies.sw[1].State() == DevState.ON # assert proxies.sw[1].searchWindowTuning == 6000000000 # assert proxies.sw[1].tdcEnable == True", "e @pytest.mark.skip(reason=\"Since there's only a single subarray, this test is currently broken.\") def", "ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.SCANNING # abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert", "in zip(range(3), [1, 3, 4])]) # configure scan f1 = open(file_path + \"/../data/ConfigureScan_basic.json\")", "emulator f = open(file_path + \"/../data/delaymodel_fsp.json\") delay_model = json.loads(f.read().replace(\"\\n\", \"\")) epoch = str(int(time.time()))", "True assert sw_1_proxy.tdcNumBits == 8 assert sw_1_proxy.tdcPeriodBeforeEpoch == 5 assert sw_1_proxy.tdcPeriodAfterEpoch == 25", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.OFF, 3, 1) except AssertionError as ae:", "of FSP subarray #TODO align IDs of fspSubarrays to fsp_id in conftest; currently", "== True assert sw_1_proxy.tdcNumBits == 8 assert sw_1_proxy.tdcPeriodBeforeEpoch == 5 assert sw_1_proxy.tdcPeriodAfterEpoch ==", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[1][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[2][0] == 1489 #", "== 2 for i in [2, 4]]) # assert subarray_2_proxy.State() == DevState.ON def", "ObsState.READY, 30, 1) assert proxies.subarray[1].obsState == ObsState.READY # create a delay model #", "# assert \"\".join(sw_1_proxy.tdcDestinationAddress.split()) in [ # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\",", "ID # with pytest.raises(tango.DevFailed) as df: # proxies.subarray[1].AddReceptors([5]) # time.sleep(1) # assert \"Invalid", "1]: logging.info(\"VCC proxy.State() = {}\".format(proxy.State())) assert [proxy.State() for proxy in proxies.vccBand[proxies.receptor_to_vcc[4] - 1]]", "len(proxies.subarray[1].receptors) == 0 # assert proxies.subarray[1].configID == 0 # assert proxies.subarray[1].frequencyBand == 0", "states of frequency band capabilities assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBand == 4 assert [proxy.State() for proxy", "vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].searchWindowTuning == 7000000000 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].tdcEnable == False assert fsp_3_proxies.subarray[1].receptors[0]", "proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1, 1) assert proxies.subarray[1].obsState == ObsState.READY # Clean Up proxies.clean_proxies()", "str(df.value.args[0].desc) # try removing a receptor not assigned to subarray 1 # doing", "raise e def test_EndScan(self, proxies, input_test_data): \"\"\" Test the EndScan command \"\"\" try:", "update delay models from tm emulator f = open(file_path + \"/../data/delaymodel_fsp.json\") delay_model =", "proxies.fspSubarray[3].searchBeams searchBeam0 = json.loads(searchBeam[0]) searchBeam1 = json.loads(searchBeam[1]) assert searchBeam0[\"search_beam_id\"] == 300 assert searchBeam0[\"receptor_ids\"][0]", "configured attributes of CBF subarray # def test_ConfigureScan_basic( # self, # cbf_master_proxy, #", "vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream1 == 0 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream2 == 0 assert vcc_proxies[receptor_to_vcc[1]", "configuration \"\"\" for proxy in vcc_proxies: proxy.Init() fsp_1_proxies.subarray[1].Init() fsp_2_proxies.subarray[1].Init() fsp_3_proxies.subarray[1].Init() fsp_1_proxy.Init() fsp_2_proxy.Init() time.sleep(3)", "proxies.subarray[1].receptors == ([3]) assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 0 for i in [1, 2, 4]])", "range) - when a receptor to be removed is not assigned to the", "assert proxies.subarray[1].receptors[2] == 4 # # configure scan # f = open(file_path +", "Master to initialize # tm_telstate_proxy.Init() # time.sleep(1) # receptor_to_vcc = dict([*map(int, pair.split(\":\"))] for", "CBF subarray # assert proxies.subarray[1].receptors == () # assert proxies.subarray[1].configID == 0 assert", "input_band_index assert proxies.subarray[subarr_index].obsState == ObsState.READY # Send the Scan command f2 = open(file_path", "configured attributes of FSPs, including states of function mode capabilities assert proxies.fsp[2].State() ==", "proxies.vccBand[proxies.receptor_to_vcc[1] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # check the rest", "debug & fix #assert searchBeam1[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" # check configured attributes of FSP", "len(aa) for jj in range(num_fsp_IDs): logging.info( \"delayCoeff = {}\".format( aa[jj][\"delayCoeff\"]) ) try: #", "vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream2 == 0 assert vcc_proxies[receptor_to_vcc[1] - 1].rfiFlaggingMask == \"{}\" # check", "except Exception as e: raise e time.sleep(10) # update timing beam weights from", "searchBeam1[\"enable_output\"] == True assert searchBeam1[\"averaging_interval\"] == 2 # TODO - this does not", "for FSP 1... # assert fsp_1_proxies.subarray[1].obsState == ObsState.EMPTY # assert fsp_1_proxies.subarray[1].receptors == 4", "= \"/../data/ConfigureScan_basic.json\" f = open(file_path + config_file_name) proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 15,", "# assert fsp_1_proxies.subarray[1].outputLinkMap[2][1] == 12 # assert fsp_1_proxies.subarray[1].outputLinkMap[3][0] == 2232 # assert fsp_1_subarray_1_proroxy.receptors[2]", "assert searchBeam400[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" # proxies.subarray[1].GoToIdle() # time.sleep(3) # assert proxies.subarray[1].obsState == ObsState.IDLE", "or (i == (band_index - 1)): # assert vcc_band_proxies[i].State() == DevState.ON # else:", "# takes pretty long for CBF Master to initialize # tm_telstate_proxy.Init() # time.sleep(1)", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 2.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 2.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 2.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5]", "assert sw_1_proxy.searchWindowTuning == 6000000000 # assert sw_1_proxy.tdcEnable == True # assert sw_1_proxy.tdcNumBits ==", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[14][0] == 10417 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[14][1] == 0 #", "cbf_master_proxy, # proxies.subarray[1], # sw_1_proxy, # sw_2_proxy, # vcc_proxies, # vcc_band_proxies, # vcc_tdc_proxies,", "== 0 for i in range(4)]) # add some receptors proxies.subarray[1].AddReceptors([1, 3, 4])", "(\"proxies.vcc[vcc_index].frequencyBand = {}\". format( proxies.vcc[vcc_index].frequencyBand)) ) vcc_band_proxies = proxies.vccBand[vcc_index - 1] assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBand", "\"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 15, 1) # update jones matrices from", "== ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE ############################# abort from SCANNING ########################### # add", "assert fsp_2_proxies.subarray[1].channelAveragingMap[5][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[6][0] == 4465 # # assert", "imports import tango from tango import DevState import pytest # SKA specific imports", "assert vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership == 1 # assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[0] == 5.85", "== 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[19][0] == 14137 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[19][1] ==", "belonging to receptor 1... # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].State() == DevState.ON # assert", "the csp-lmc-prototype project # # # # Distributed under the terms of the", "of CBF subarray # def test_ConfigureScan_basic( # self, # cbf_master_proxy, # proxies.subarray[1], #", "assert tm_telstate_proxy.receivedOutputLinks == False # add receptors proxies.subarray[1].RemoveAllReceptors() proxies.subarray[1].AddReceptors([1, 3, 4]) time.sleep(1) assert", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[14][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[15][0] == 11161 #", "proxies.vcc[vcc_index].configID == configuration[\"common\"][\"config_id\"] assert proxies.vcc[vcc_index].frequencyBand == band_index assert proxies.vcc[vcc_index].subarrayMembership == sub_id #TODO fix", "== fsp[\"frequency_slice_id\"] assert proxies.fspSubarray[fsp_id].integrationTime == fsp[\"integration_factor\"] assert proxies.fspSubarray[fsp_id].corrBandwidth == fsp[\"zoom_factor\"] if fsp[\"zoom_factor\"] >", "{}\". format(proxies.fspPstSubarray[subarr_index-1].obsState) ) # Check obsStates BEFORE the EndScan() command assert proxies.subarray[subarr_index].obsState ==", "= receptor[\"receptorWeightsDetails\"][0][\"fsid\"] for index, value in enumerate(receptor[\"receptorWeightsDetails\"][0][\"weights\"]): try: assert proxies.fsp[fs_id].timingBeamWeights[rec_id - 1][index] ==", "\"/../data/jonesmatrix.json\") jones_matrix = json.loads(f.read().replace(\"\\n\", \"\")) f.close() jones_matrix[\"jonesMatrix\"][0][\"epoch\"] = str(int(time.time()) + 20) jones_matrix[\"jonesMatrix\"][1][\"epoch\"] =", "== 3 assert fsp_3_proxies.subarray[1].receptors[1] == 1 assert fsp_3_proxies.subarray[1].searchWindowID == 2 assert fsp_3_proxies.subarray[1].searchBeamID[0] ==", "DevState.ON] # assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[1] - 1]] == [ #", "assert fsp_1_proxies.subarray[1].obsState == ObsState.READY assert fsp_1_proxies.subarray[1].frequencyBand == 0 assert fsp_1_proxies.subarray[1].frequencySliceID == 1 assert", "assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.SCANNING elif fsp[\"function_mode\"] == \"PSS-BF\": assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.SCANNING #", "tango import DevState import pytest # SKA specific imports from ska_mid_cbf_mcs.commons.global_enum import freq_band_dict", "8 assert proxies.fspSubarray[1].channelAveragingMap[3][0] == 2232 assert proxies.fspSubarray[1].channelAveragingMap[3][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[4][0] == 2976", "for receptor in jones_matrix[\"jonesMatrix\"][2][\"matrixDetails\"]: for frequency_slice in receptor[\"receptorMatrix\"]: for index, value in enumerate(frequency_slice[\"matrix\"]):", "assert fsp_1_proxies.subarray[1].channelAveragingMap[17][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[18][0] == 13392 # # assert", "some receptors (including an invalid one) to subarray 2 # with pytest.raises(tango.DevFailed) as", "int(receptor[\"receptor\"]) fs_id = receptor[\"receptorMatrix\"][0][\"fsid\"] for index, value in enumerate(receptor[\"receptorMatrix\"][0][\"matrix\"]): try: assert proxies.fsp[fs_id].jonesMatrix[rec_id -", "== 744 assert proxies.fspSubarray[1].outputLinkMap[1][1] == 8 assert proxies.fspSubarray[1].outputLinkMap[2][0] == 1488 assert proxies.fspSubarray[1].outputLinkMap[2][1] ==", "10... assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].State() == DevState.DISABLE assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].searchWindowTuning == 7000000000", "test_ConfigureScan_onlyPss_basic( self, cbf_master_proxy, proxies.subarray[1], sw_1_proxy, sw_2_proxy, vcc_proxies, vcc_band_proxies, vcc_tdc_proxies, fsp_1_proxy, fsp_2_proxy, fsp_1_function_mode_proxy, fsp_2_function_mode_proxy,", "= str(int(time.time()) + 20) delay_model[\"delayModel\"][1][\"epoch\"] = \"0\" delay_model[\"delayModel\"][2][\"epoch\"] = str(int(time.time()) + 10) #", "proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].State() == DevState.ON assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].searchWindowTuning == 6000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[4]", "proxies.fspSubarray[3].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE ############################# abort", "{}\". format(proxies.fspCorrSubarray[subarr_index-1].obsState) ) logging.info( \"proxies.fspPssSubarray[subarr_index-1].obsState = {}\". format(proxies.fspPssSubarray[subarr_index-1].obsState) ) logging.info( \"proxies.fspPstSubarray[subarr_index-1].obsState = {}\".", "== \"PSS-BF\": function_mode = 2 elif fsp[\"function_mode\"] == \"PST-BF\": function_mode = 3 elif", "ae: proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e def test_EndScan(self,", "1) assert proxies.subarray[1].State() == DevState.ON assert proxies.subarray[1].obsState == ObsState.EMPTY # receptor list should", "== input_receptors assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for i in input_receptors]) assert proxies.subarray[1].obsState ==", "adding some receptors (including an invalid one) to subarray 2 # with pytest.raises(tango.DevFailed)", "time.sleep(1) assert [proxies.subarray[1].receptors[i] for i in range(4)] == [1, 3, 4, 2] assert", "proxies): \"\"\" Test a successful PST-BF scan configuration \"\"\" try: # turn on", "proxies.fsp[fsp_id].subarrayMembership assert [proxy.State() for proxy in fsp_function_mode_proxies[fsp_id-1]] == [ DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE", "attributes of FSP subarrays # # first for FSP 1... # assert fsp_1_proxies.subarray[1].obsState", "# \"fizz\", \"buzz\", \"80\" # ) # # then for search window 2", "subarray # def test_ConfigureScan_basic( # self, # cbf_master_proxy, # proxies.subarray[1], # sw_1_proxy, #", "False # check configured attributes of FSPs, including states of function mode capabilities", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) assert proxies.subarray[1].obsState == ObsState.READY assert proxies.fspSubarray[1].obsState == ObsState.READY assert", "[proxy.State() for proxy in proxies.vccBand[proxies.receptor_to_vcc[1] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON]", "capabilities assert fsp_1_proxy.functionMode == 1 assert 1 in fsp_1_proxy.subarrayMembership # assert 1 in", "assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBandOffsetStream1 == 0 assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBandOffsetStream2 == 0 assert proxies.vcc[proxies.receptor_to_vcc[4]].rfiFlaggingMask == \"{}\" #", "- 1][1].searchWindowTuning == 7000000000 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].tdcEnable == False # #", "1][1].State() == DevState.DISABLE # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].searchWindowTuning == 7000000000 # assert vcc_tdc_proxies[receptor_to_vcc[4]", "== ( \"fizz\", \"buzz\", \"80\" ) # then for search window 2 of", "proxy in [proxies.vcc[i + 1] for i in range(4)]: if proxy.State() == DevState.OFF:", "pair.split(\":\"))] for pair in cbf_master_proxy.receptorToVcc) cbf_master_proxy.On() time.sleep(3) # check initial value of attributes", "This file is part of the csp-lmc-prototype project # # # # Distributed", "1) proxies.clean_proxies() # turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.ON,", "\"8080\" # ) # # then for search window 1 of VCC belonging", "a Jones matrix f = open(file_path + \"/../data/jonesmatrix.json\") jones_matrix = json.loads(f.read().replace(\"\\n\", \"\")) f.close()", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY assert len(proxies.subarray[1].receptors) == 0 assert", "searchBeam400 = json.loads(searchBeam[1]) # assert searchBeam300[\"searchBeamID\"] == 300 # assert searchBeam300[\"receptors\"][0] == 3", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 4.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 4.4 time.sleep(10) assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 0.1 assert", "attributes of FSPs, including states of function mode capabilities assert proxies.fsp[2].State() == DevState.ON", "== True # assert searchBeam400[\"averagingInterval\"] == 2 # assert searchBeam400[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" #", "range(4): logging.info((\" proxies.vcc[{}].receptorID = {}\". format(jj+1, proxies.vcc[jj+1].receptorID))) logging.info( (\"Vcc, receptor 1, ObsState =", "== 300 assert fsp_3_proxies.subarray[1].searchBeamID[1] == 400 searchBeam = fsp_3_proxies.subarray[1].searchBeams searchBeam300 = json.loads(searchBeam[0]) searchBeam400", "time.sleep(10) for receptor in jones_matrix[\"jonesMatrix\"][2][\"matrixDetails\"]: for frequency_slice in receptor[\"receptorMatrix\"]: for index, value in", "time.sleep(10) # update timing beam weights from tm emulator f = open(file_path +", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[6][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[7][0] == 5209 # #", "== 12649 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[17][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[18][0] ==", "search windows # # first for search window 1... # assert sw_1_proxy.State() ==", "\"Invalid receptor ID\" in str(df.value.args[0].desc) # try removing a receptor not assigned to", "== DevState.DISABLE # assert proxies.sw[2].searchWindowTuning == 7000000000 # assert proxies.sw[2].tdcEnable == False time.sleep(1)", "3... # assert fsp_3_proxies.subarray[1].receptors[0] == 3 # assert fsp_3_proxies.subarray[1].receptors[1] == 1 # assert", "this does not pass - to debug & fix #assert searchBeam1[\"searchBeamDestinationAddress\"] == \"10.05.2.1\"", "== 2.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 2.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 2.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] ==", "# TODO - # assert [proxy.State() for proxy in fsp_2_function_mode_proxy] == [ #", "# then for VCC belonging to receptor 1... assert vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership ==", "# then for search window 1 of VCC belonging to receptor 1... #", "# assert tm_telstate_proxy.visDestinationAddress == \"{}\" # assert tm_telstate_proxy.receivedOutputLinks == False # # add", "proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) # check initial value of attributes of CBF subarray", "ObsState.READY # create a delay model # Insert the epoch delay_model[\"delayModel\"][0][\"epoch\"] = str(int(time.time())", "# as a json string ( via attribute 'searchBeams'); # this has to", "fsp_1_subarray_1_proroxy.receptors[2] == 4 # # assert fsp_2_proxies.subarray[1].frequencyBand == 4 # # assert fsp_2_proxies.subarray[1].band5Tuning[0]", "1) assert proxies.subarray[1].obsState == ObsState.READY #create a Jones matrix f = open(file_path +", "ObsState.SCANNING # abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED assert", "0 assert proxies.subarray[1].configID == '' assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState == ObsState.EMPTY", "removing a receptor not assigned to subarray 1 # doing this doesn't actually", "proxies.clean_proxies() raise e def test_ConfigureScan_minimal(self, proxies): try: sub_id = 1 #TODO currently only", "# ] # # assert [proxy.State() for proxy in fsp_2_function_mode_proxy] == [ #", "= 1 elif fsp[\"function_mode\"] == \"PSS-BF\": function_mode = 2 elif fsp[\"function_mode\"] == \"PST-BF\":", "\"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) assert proxies.subarray[1].obsState == ObsState.READY assert proxies.fspSubarray[1].obsState ==", "{}, jonesMatrix[{}] = {}\".format( jones_matrix[\"jonesMatrix\"][1][\"epoch\"], vcc_id, index, fs_id-1, proxies.vcc[vcc_id].jonesMatrix[fs_id-1]) ) raise ae except", "# # then for search window 2... # assert sw_2_proxy.State() == DevState.DISABLE #", "1) assert len(proxies.subarray[1].receptors) == 0 assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 0 for i in [1,", "== ObsState.SCANNING elif fsp[\"function_mode\"] == \"PSS-BF\": assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.SCANNING # TODO: this", "# assert subarray_2_proxy.State() == DevState.ON def test_RemoveAllReceptors(self, proxies): \"\"\" Test RemoveAllReceptors command \"\"\"", "receptors should be empty proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY", "f = open(file_path + \"/test_json/test_ConfigureScan_basic.json\") # proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) # f.close() # time.sleep(15) #", "# Input test data: input_receptors = input_test_data[0] config_file_name = input_test_data[1] subarr_index = 1;", "== 4 # # assert fsp_2_proxies.subarray[1].frequencyBand == 4 # # assert fsp_2_proxies.subarray[1].band5Tuning[0] ==", "proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) assert proxies.subarray[1].obsState == ObsState.READY assert proxies.fspSubarray[1].obsState", "in [1, 3, 4]]) assert proxies.subarray[1].obsState == ObsState.EMPTY proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.OFF, 3, 1)", "2.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 2.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 3.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 3.1", "e #TODO: fix; currently tests break if multiple scan configurations are tested def", "proxy in vcc_band_proxies: # logging.info(\"VCC proxy.State() = {}\".format(proxy.State())) # for i in range(4):", "== 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[4][0] == 2976 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[4][1] ==", "2.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 2.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 2.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 2.3", "should be empty right after initialization # assert proxies.subarray[1].receptors == () # assert", "# assert len(proxies.subarray[1].receptors) == 0 # assert proxies.subarray[1].configID == 0 # assert proxies.subarray[1].frequencyBand", "in proxies.fsp[2].subarrayMembership assert [proxy.State() for proxy in proxies.fsp2FunctionMode] == [ DevState.DISABLE, DevState.DISABLE, DevState.ON,", "{}\". format(proxies.vcc[vcc_ids[0]].obsState) ) # check some configured attributes of CBF subarray frequency_band =", "assert all([proxies.subarray[1].receptors[i] == j for i, j in zip(range(4), [4, 1, 3, 2])])", "assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand == 4 # assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand == 4", "belonging to receptor 1... assert vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership == 1 # check configured", "DevState.ON # assert proxies.sw[1].searchWindowTuning == 6000000000 # assert proxies.sw[1].tdcEnable == True # assert", "== 8185 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[11][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[12][0] ==", "import tango from tango import DevState import pytest # SKA specific imports from", "for search window 2 of VCC belonging to receptor 1... assert vcc_tdc_proxies[receptor_to_vcc[1] -", "proxies.subarray[1].AddReceptors([5]) # time.sleep(1) # assert \"Invalid receptor ID\" in str(df.value.args[0].desc) # try removing", "searchBeam0[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" assert searchBeam1[\"search_beam_id\"] == 400 assert searchBeam1[\"receptor_ids\"][0] == 1 assert searchBeam1[\"enable_output\"]", "proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() time.sleep(15) # check configured attributes of CBF subarray assert proxies.subarray[1].configID", "cbf_controller_proxy.Init() # time.sleep(60) # takes pretty long for CBF controller to initialize #", "receptors... proxies.subarray[1].AddReceptors([2]) time.sleep(1) assert [proxies.subarray[1].receptors[i] for i in range(4)] == [1, 3, 4,", "proxies.vcc[proxies.receptor_to_vcc[2]].subarrayMembership == 1 # remove some receptors proxies.subarray[1].RemoveReceptors([2, 1, 4]) time.sleep(1) assert proxies.subarray[1].receptors", "[1, 3, 4])]) # configure scan f1 = open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f1.read().replace(\"\\n\", \"\"))", "e def test_ConfigureScan_jonesMatrix(self, proxies): \"\"\" Test the reception of Jones matrices \"\"\" try:", "i in range(4)]: if proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) assert", "fsp_1_proxy.Init() # fsp_2_proxy.Init() # proxies.subarray[1].set_timeout_millis(60000) # since the command takes a while #", "in vcc_band_proxies[receptor_to_vcc[4] - 1]] == [ # DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # assert", "channels average factor 8\" # assert proxies.subarray[1].frequencyBand == 4 # means 5a? #", "2 of VCC belonging to receptor 10... # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].State() ==", "update jones matrices from tm emulator f = open(file_path + \"/../data/jonesmatrix_fsp.json\") jones_matrix =", "subarr_index = 1; logging.info( \"input_receptors = {}\".format(input_receptors) ) logging.info( \"config_file_name = {}\".format(config_file_name) )", "delay models from tm emulator f = open(file_path + \"/../data/delaymodel_fsp.json\") delay_model = json.loads(f.read().replace(\"\\n\",", "time.sleep(1) # assert \"Invalid receptor ID\" in str(df.value.args[0].desc) # try removing a receptor", "== ([3]) assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 0 for i in [1, 2, 4]]) assert", "# assert fsp_3_proxies.subarray[1].searchWindowID == 2 # assert fsp_3_proxies.subarray[1].searchBeamID[0] == 300 # assert fsp_3_proxies.subarray[1].searchBeamID[1]", "1.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 1.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 1.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 1.3", "assert sub_id in proxies.fsp[fsp_id].subarrayMembership assert [proxy.State() for proxy in fsp_function_mode_proxies[fsp_id-1]] == [ DevState.ON,", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[12][0] == 8928 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[12][1] == 8 #", "= json.dumps(delay_model) time.sleep(1) for jj in range(4): logging.info((\" proxies.vcc[{}].receptorID = {}\". format(jj+1, proxies.vcc[jj+1].receptorID)))", "proxies.fsp[2].State() == DevState.ON assert proxies.fsp[2].functionMode == 3 assert 1 in proxies.fsp[2].subarrayMembership assert [proxy.State()", "False # # and lastly for search window 2 of VCC belonging to", "configure scan config_file_name = \"/../data/ConfigureScan_basic.json\" f = open(file_path + config_file_name) proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close()", "if model[\"destinationType\"] == \"fsp\": for receptor in model[\"delayDetails\"]: rec_id = int(receptor[\"receptor\"]) fs_id =", "745 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[1][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[2][0] == 1489", "assert proxies.subarray[1].obsState == ObsState.SCANNING time.sleep(10) assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 2.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 2.2", "per fsp test_receptor_ids = [4, 1] #test_receptor_ids = [1] vcc_index = proxies.receptor_to_vcc[test_receptor_ids[0]] logging.info(\"vcc_index", "# doing this doesn't actually throw an error proxies.subarray[1].RemoveReceptors([2]) assert proxies.subarray[1].receptors[0] == 1", "assert sw_1_proxy.tdcPeriodAfterEpoch == 25 # assert \"\".join(sw_1_proxy.tdcDestinationAddress.split()) in [ # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\",", "== [ # DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE # ] # check configured attributes", "except AssertionError as ae: logging.error(\"AssertionError; incorrect Jones matrix entry: epoch {}, VCC {},", "5 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch == 25 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcDestinationAddress", "all([proxies.subarray[1].receptors[i] == j for i, j in zip(range(4), [4, 1, 3, 2])]) #", "assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE ############################# abort from SCANNING ########################### # add receptors proxies.subarray[1].AddReceptors([1,", "in vcc_proxies: # proxy.Init() # fsp_1_proxies.subarray[1].Init() # fsp_2_proxies.subarray[1].Init() # fsp_3_proxies.subarray[1].Init() # fsp_1_proxy.Init() #", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[5][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[6][0] == 4465 # #", "test_ConfigureScan_onlyPst_basic_FSP_scan_parameters(self, proxies): \"\"\" Test a successful transmission of PST-BF parameters to FSP \"\"\"", "ska_tango_base.control_model import AdminMode, ObsState from ska_tango_base.base_device import _DEBUGGER_PORT @pytest.mark.usefixtures(\"proxies\", \"input_test_data\") class TestCbfSubarray: def", "assert proxies.subarray[1].obsState == ObsState.EMPTY # Input test data: input_receptors = input_test_data[0] config_file_name =", "an invalid receptor ID # with pytest.raises(tango.DevFailed) as df: # proxies.subarray[1].AddReceptors([5]) # time.sleep(1)", "proxies.vcc[proxies.receptor_to_vcc[4]].band5Tuning[0] == 5.85 assert proxies.vcc[proxies.receptor_to_vcc[4]].band5Tuning[1] == 7.25 assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBandOffsetStream1 == 0 assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBandOffsetStream2", "except Exception as e: proxies.clean_proxies() raise e def test_Scan(self, proxies): \"\"\" Test the", "assert proxies.fspSubarray[3].searchWindowID == 2 assert proxies.fspSubarray[3].searchBeamID[0] == 300 assert proxies.fspSubarray[3].searchBeamID[1] == 400 #", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 1.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 1.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 1.6 assert", "== 14137 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[19][1] == 0 # # then for FSP", "assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream2 == 0 # assert vcc_proxies[receptor_to_vcc[4] - 1].rfiFlaggingMask == \"{}\"", "2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) # configure scan f = open(file_path + \"/../data/ConfigureScan_basic.json\")", "# vcc_tdc_proxies, # fsp_1_proxy, # fsp_2_proxy, # fsp_1_function_mode_proxy, # fsp_2_function_mode_proxy, # fsp_1_proxies.subarray[1], #", "AFTER the EndScan() command assert proxies.subarray[subarr_index].obsState == ObsState.READY assert proxies.vcc[vcc_ids[0]].obsState == ObsState.READY assert", "open(file_path + \"/../data/delaymodel.json\") delay_model = json.loads(f.read().replace(\"\\n\", \"\")) f.close() aa = delay_model[\"delayModel\"][0][\"delayDetails\"][0][\"receptorDelayDetails\"] num_fsp_IDs =", "receptor in jones_matrix[\"jonesMatrix\"][1][\"matrixDetails\"]: for frequency_slice in receptor[\"receptorMatrix\"]: for index, value in enumerate(frequency_slice[\"matrix\"]): vcc_id", "5953 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[8][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[9][0] == 6697", "FSP 2 assert proxies.fspSubarray[6].obsState == ObsState.READY assert all([proxies.fspSubarray[6].receptors[i] == j for i, j", "needs to be refactored\") def test_ConfigureScan_delayModel(self, proxies): \"\"\" Test the reception of delay", "# first for FSP 3 ... (this is a PSS fsp device) assert", "update delay model proxies.tm.delayModel = json.dumps(delay_model) time.sleep(1) for jj in range(4): logging.info((\" proxies.vcc[{}].receptorID", "proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e def test_ConfigureScan_minimal(self, proxies):", "ObsState.IDLE # Check fsp obsState BEFORE scan configuration: assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.IDLE assert", "ObsState.READY assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.READY for fsp in input_config_dict[\"cbf\"][\"fsp\"]: if fsp[\"function_mode\"] == \"CORR\":", "proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[3].obsState", "for weights in timing_beam_weights[\"beamWeights\"]: for receptor in weights[\"beamWeightsDetails\"]: rec_id = int(receptor[\"receptor\"]) fs_id =", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 1.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 1.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 1.3 assert", "DevState.ON assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].searchWindowTuning == 6000000000 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcEnable == True", "ObsReset proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY assert len(proxies.subarray[1].receptors) ==", "tested def test_ConfigureScan_basic(self, proxies): \"\"\" Test a successful scan configuration \"\"\" proxies.subarray[1].loggingLevel =", "8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[10][0] == 7440 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[10][1] == 8", "3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) # configure scan f = open(file_path", "proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcEnable == True assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcNumBits == 8 assert proxies.vccTdc[proxies.receptor_to_vcc[1]", "as e: proxies.clean_proxies() raise e def test_Scan(self, proxies): \"\"\" Test the Scan command", "25 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcDestinationAddress == ( \"foo\", \"bar\", \"8080\" ) # then", "f.close() jones_matrix[\"jonesMatrix\"][0][\"epoch\"] = str(int(time.time()) + 20) jones_matrix[\"jonesMatrix\"][1][\"epoch\"] = \"0\" jones_matrix[\"jonesMatrix\"][2][\"epoch\"] = str(int(time.time()) +", "epoch = str(int(epoch) + 10) # update Jones Matrix proxies.tm.jonesMatrix = json.dumps(jones_matrix) time.sleep(1)", "proxies.subarray[1].configID == '' # TODO in CbfSubarray, at end of scan, clear all", "to receptor 1... assert proxies.vcc[proxies.receptor_to_vcc[1]].subarrayMembership == 1 assert proxies.vcc[proxies.receptor_to_vcc[1]].band5Tuning[0] == 5.85 assert proxies.vcc[proxies.receptor_to_vcc[1]].band5Tuning[1]", "f = open(file_path + \"/test_json/data_model_confluence.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() time.sleep(15) # check configured attributes", "== ObsState.EMPTY ############################# abort from READY ########################### # add receptors proxies.subarray[1].AddReceptors([1, 3, 4,", "ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE ############################# abort from READY", "Jones Matrix proxies.tm.jonesMatrix = json.dumps(jones_matrix) time.sleep(5) for receptor in jones_matrix[\"jonesMatrix\"][1][\"matrixDetails\"]: for frequency_slice in", "6000000000 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcEnable == True # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcNumBits", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[1][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[2][0] == 1488 #", "# Note: scan_id is 1-based and of 'string' type # scan_index is an", "in jones_matrix[\"jonesMatrix\"]: matrix[\"epoch\"] = epoch if matrix[\"destinationType\"] == \"fsp\": epoch = str(int(epoch) +", "SKA specific imports from ska_mid_cbf_mcs.commons.global_enum import freq_band_dict from ska_tango_base.control_model import LoggingLevel, HealthState from", "assert proxies.vcc[vcc_ids[0]].obsState == ObsState.READY assert proxies.vcc[vcc_ids[num_receptors -1]].obsState == ObsState.READY assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.READY", "[10])]) # Clean Up proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae except", "proxies.subarray[1].State() == DevState.OFF # assert subarray_2_proxy.State() == DevState.OFF # # add some receptors", "format(proxies.fspPssSubarray[subarr_index-1].obsState) ) logging.info( \"proxies.fspPstSubarray[subarr_index-1].obsState = {}\". format(proxies.fspPstSubarray[subarr_index-1].obsState) ) # Check obsStates BEFORE the", "- 1][0].searchWindowTuning == 6000000000 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcEnable == True assert vcc_tdc_proxies[receptor_to_vcc[1] -", "DevState.DISABLE, DevState.DISABLE # ] # check configured attributes of FSP subarrays # first", "\"\"\" # for proxy in vcc_proxies: # proxy.Init() # fsp_1_proxies.subarray[1].Init() # fsp_2_proxies.subarray[1].Init() #", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[16][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[17][0] == 12649 #", "1 assert proxies.subarray[1].receptors[1] == 3 proxies.subarray[1].RemoveAllReceptors() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.OFF,", "See LICENSE.txt for more info. \"\"\"Contain the tests for the CbfSubarray.\"\"\" # Standard", "band_index assert proxies.vcc[vcc_index].subarrayMembership == sub_id #TODO fix these tests; issue with VccBand devices", "tests break if multiple scan configurations are tested def test_ConfigureScan_basic(self, proxies): \"\"\" Test", "# ] # check configured attributes of FSP subarrays # first for FSP", "as ae: proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e @pytest.mark.skip(reason=\"Since", "fsp_1_proxies.subarray[1].outputLinkMap[0][0] == 1 assert fsp_1_proxies.subarray[1].outputLinkMap[0][1] == 0 assert fsp_1_proxies.subarray[1].outputLinkMap[1][0] == 201 assert fsp_1_proxies.subarray[1].outputLinkMap[1][1]", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[4][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[5][0] == 3720 #", "assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].searchWindowTuning == 6000000000 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcEnable == True", "- re-enable and debug! # assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcDestinationAddress == ( # \"fizz\",", "== ( # \"foo\", \"bar\", \"8080\" # ) # # then for search", "VCCs, including states of frequency band capabilities # assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand ==", "in enumerate(receptor[\"receptorDelayDetails\"][0][\"delayCoeff\"]): try: assert proxies.fsp[fs_id].delayModel[rec_id - 1][index] == value except AssertionError as ae:", "assert sw_1_proxy.tdcPeriodAfterEpoch == 25 assert \"\".join(sw_1_proxy.tdcDestinationAddress.split()) in [ \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", ]", "12 assert proxies.fspSubarray[1].outputLinkMap[3][0] == 2232 assert proxies.fspSubarray[1].outputLinkMap[3][1] == 16 assert str(proxies.fspSubarray[1].visDestinationAddress).replace('\"',\"'\") == \\", "means 1 assert proxies.subarray[1].obsState.value == ObsState.READY.value # check frequency band of VCCs, including", "index, value in enumerate(receptor[\"receptorDelayDetails\"][0][\"delayCoeff\"]): try: assert proxies.fsp[fs_id].delayModel[rec_id - 1][index] == value except AssertionError", "== DevState.ON # # try adding some receptors (including an invalid one) to", "[ DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ] # assert [proxy.State() for proxy in fsp_2_function_mode_proxy]", "proxies.fspSubarray[1].channelAveragingMap[3][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[4][0] == 2976 assert proxies.fspSubarray[1].outputLinkMap[0][0] == 0 assert proxies.fspSubarray[1].outputLinkMap[0][1]", "\"\"\" Test abort restart \"\"\" try: # turn on Subarray if proxies.subarray[1].State() !=", "fsp_3_proxies.subarray[1].receptors[0] == 3 assert fsp_3_proxies.subarray[1].receptors[1] == 1 assert fsp_3_proxies.subarray[1].searchWindowID == 2 assert fsp_3_proxies.subarray[1].searchBeamID[0]", "DevState.DISABLE, DevState.ON, DevState.DISABLE ] # check configured attributes of FSP subarrays # FSP", "SCANNING f2 = open(file_path + \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1)", "receptor 1... # assert vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership == 1 # assert vcc_proxies[receptor_to_vcc[1] -", "except AssertionError as ae: raise ae except Exception as e: raise e time.sleep(10)", "for search window 1... assert sw_1_proxy.State() == DevState.ON assert sw_1_proxy.searchWindowTuning == 6000000000 assert", "has to be updated in FspPssSubarray # to read/write individual members searchBeam =", "fsp_2_proxies.subarray[1].channelAveragingMap[14][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[15][0] == 11161 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[15][1]", "test_EndScan(self, proxies, input_test_data): \"\"\" Test the EndScan command \"\"\" try: # turn on", "Exception as e: proxies.clean_proxies() raise e def test_ConfigureScan_jonesMatrix(self, proxies): \"\"\" Test the reception", "# assert sw_1_proxy.searchWindowTuning == 6000000000 # assert sw_1_proxy.tdcEnable == True # assert sw_1_proxy.tdcNumBits", "receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) # configure scan f", "VCCs # first for VCC belonging to receptor 10... assert proxies.vcc[proxies.receptor_to_vcc[4]].subarrayMembership == 1", "{}\". format(proxies.vcc[vcc_ids[0]].obsState) ) f = open(file_path + config_file_name) json_string = f.read().replace(\"\\n\", \"\") input_config_dict", "1400 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[0][0] == 1 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[0][1] == 0", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 0.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 0.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 0.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3]", "# assert sw_1_proxy.tdcPeriodAfterEpoch == 25 # assert \"\".join(sw_1_proxy.tdcDestinationAddress.split()) in [ # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", #", "Test RemoveAllReceptors command \"\"\" try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON:", "Jones matrix entry: epoch {}, VCC {}, i = {}, jonesMatrix[{}] = {}\".format(", "check the rest of the configured attributes of VCCs # # first for", "= open(file_path + \"/test_json/data_model_confluence.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() time.sleep(15) # check configured attributes of", "except Exception as e: proxies.clean_proxies() raise e def test_EndScan(self, proxies, input_test_data): \"\"\" Test", "jones_matrix[\"jonesMatrix\"][0][\"matrixDetails\"]: for frequency_slice in receptor[\"receptorMatrix\"]: for index, value in enumerate(frequency_slice[\"matrix\"]): vcc_id = proxies.receptor_to_vcc[receptor[\"receptor\"]]", "fsp_1_function_mode_proxy, fsp_2_function_mode_proxy, fsp_1_proxies.subarray[1], fsp_2_proxies.subarray[1], fsp_3_proxies.subarray[1], tm_telstate_proxy ): \"\"\" Test a minimal successful configuration", "vcc_tdc_proxies, # fsp_1_proxy, # fsp_2_proxy, # fsp_1_function_mode_proxy, # fsp_2_function_mode_proxy, # fsp_1_proxies.subarray[1], # fsp_2_proxies.subarray[1],", "fsp_3_proxies.subarray[1].searchBeamID[0] == 300 assert fsp_3_proxies.subarray[1].searchBeamID[1] == 400 searchBeam = fsp_3_proxies.subarray[1].searchBeams searchBeam300 = json.loads(searchBeam[0])", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 2.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 2.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 2.9 assert", "# abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED assert proxies.fspSubarray[1].obsState", "\"\"\" # Test a minimal successful configuration # \"\"\" # for proxy in", "6697 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[9][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[10][0] == 7441", "updated in FspPssSubarray # to read/write individual members searchBeam = proxies.fspSubarray[3].searchBeams searchBeam0 =", "DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # check the rest of the configured attributes of", "# # Distributed under the terms of the BSD-3-Clause license. # See LICENSE.txt", "1][0].tdcDestinationAddress == ( \"fizz\", \"buzz\", \"80\" ) # then for search window 2", "== 7000000000 assert sw_2_proxy.tdcEnable == False # check configured attributes of VCC search", "assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].State() == DevState.DISABLE # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].searchWindowTuning == 7000000000", "fsp_2_proxies.subarray[1].channelAveragingMap[4][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[5][0] == 3721 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[5][1]", "vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[1] == 7.25 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream1 == 0 assert vcc_proxies[receptor_to_vcc[1]", "test_receptor_ids)]) # configure scan f = open(file_path + \"/../data/Configure_TM-CSP_v2.json\") configuration = f.read().replace(\"\\n\", \"\")", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert len(proxies.subarray[1].receptors) == 0 assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 0 for", "# assert fsp_1_proxies.subarray[1].integrationTime == 140 # assert fsp_1_proxies.subarray[1].fspChannelOffset == 14880 # # assert", "json.loads(f.read().replace(\"\\n\", \"\")) epoch = str(int(time.time())) for matrix in jones_matrix[\"jonesMatrix\"]: matrix[\"epoch\"] = epoch if", "fsp_1_proxies.subarray[1].outputLinkMap[0][1] == 4 # assert fsp_1_proxies.subarray[1].outputLinkMap[1][0] == 744 # assert fsp_1_proxies.subarray[1].outputLinkMap[1][1] == 8", "scan f = open(file_path + \"/test_json/data_model_confluence.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() time.sleep(15) # check configured", "be added is already in use by a different subarray \"\"\" # for", "== 0 assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream2 == 0 assert vcc_proxies[receptor_to_vcc[4] - 1].rfiFlaggingMask ==", "2232 # assert fsp_1_subarray_1_proroxy.receptors[2] == 4 # # assert fsp_2_proxies.subarray[1].frequencyBand == 4 #", "for proxy in [proxies.fsp[i + 1] for i in range(4)]: proxy.loggingLevel = \"DEBUG\"", "# time.sleep(3) # assert proxies.subarray[1].obsState == ObsState.IDLE # proxies.subarray[1].RemoveAllReceptors() # time.sleep(3) # assert", "searchBeam300[\"averagingInterval\"] == 4 assert searchBeam300[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" assert searchBeam400[\"searchBeamID\"] == 400 assert searchBeam400[\"receptors\"][0]", "ObsState.EMPTY, 1, 1) assert len(proxies.subarray[1].receptors) == 0 assert proxies.vcc[proxies.receptor_to_vcc[3]].subarrayMembership == 0 assert proxies.subarray[1].obsState", "value in enumerate(receptor[\"receptorDelayDetails\"][0][\"delayCoeff\"]): try: assert proxies.fsp[fs_id].delayModel[rec_id - 1][index] == value except AssertionError as", "0.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 0.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 0.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 0.8", "== 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[10][0] == 7440 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[10][1] ==", "7000000000 # assert sw_2_proxy.tdcEnable == False # # check configured attributes of VCC", "#logging.info(\"start_time = {}\".format(time.time())) logging.info(\"start datetime = {}\".format(datetime.now())) if proxies.debug_device_is_on: port = proxies.subarray[1].DebugDevice() try:", "# assert proxies.subarray[1].receptors[2] == 4 # # configure scan # f = open(file_path", "subarray_2_proxy.State() == DevState.ON def test_RemoveAllReceptors(self, proxies): \"\"\" Test RemoveAllReceptors command \"\"\" try: #", "as e: proxies.clean_proxies() raise e #TODO refactor to verify delay model values against", "== ObsState.IDLE assert all([proxies.subarray[1].receptors[i] == j for i, j in zip(range(3), [1, 3,", "# # assert fsp_2_proxies.subarray[1].corrBandwidth == 0 # # assert fsp_2_proxies.subarray[1].integrationTime == 1400 #", "searchBeam300[\"searchBeamID\"] == 300 # assert searchBeam300[\"receptors\"][0] == 3 # assert searchBeam300[\"outputEnable\"] == True", "3]]) # assert proxies.subarray[1].State() == DevState.ON # # try adding some receptors (including", "assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].State() == DevState.DISABLE assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].searchWindowTuning == 7000000000 assert", "receptors proxies.subarray[1].RemoveReceptors([2, 1, 4]) time.sleep(1) assert proxies.subarray[1].receptors == ([3]) assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 0", "f.close() # time.sleep(15) # # check configured attributes of CBF subarray # assert", "logging.info((\" proxies.vcc[{}].receptorID = {}\". format(jj+1, proxies.vcc[jj+1].receptorID))) logging.info( (\"Vcc, receptor 1, ObsState = {}\".", "# \"fizz\", \"buzz\", \"80\" # ) # then for search window 2 of", "sw_1_proxy.tdcPeriodBeforeEpoch == 5 assert sw_1_proxy.tdcPeriodAfterEpoch == 25 assert \"\".join(sw_1_proxy.tdcDestinationAddress.split()) in [ \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\",", "capabilities logging.info( (\"proxies.vcc[vcc_index].frequencyBand = {}\". format( proxies.vcc[vcc_index].frequencyBand)) ) assert proxies.vcc[vcc_index].configID == configuration[\"common\"][\"config_id\"] assert", "vcc_proxies[receptor_to_vcc[4] - 1].rfiFlaggingMask == \"{}\" # # then for VCC belonging to receptor", "# check configured attributes of CBF subarray assert sub_id == int(configuration[\"common\"][\"subarray_id\"]) assert proxies.subarray[sub_id].configID", "- 1][0].tdcNumBits == 8 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch == 5 assert vcc_tdc_proxies[receptor_to_vcc[4] -", "assert proxies.sw[1].tdcEnable == True # assert proxies.sw[1].tdcNumBits == 8 # assert proxies.sw[1].tdcPeriodBeforeEpoch ==", "0 for i in [1, 2, 4]]) assert proxies.vcc[proxies.receptor_to_vcc[3]].subarrayMembership == 1 # remove", "== 1 assert proxies.subarray[1].receptors[1] == 3 assert proxies.subarray[1].receptors[2] == 4 # configure scan", "+ 1] for i in range(4)]: if proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON,", "# assert proxies.sw[2].State() == DevState.DISABLE # assert proxies.sw[2].searchWindowTuning == 7000000000 # assert proxies.sw[2].tdcEnable", "except Exception as e: proxies.clean_proxies() raise e def test_ConfigureScan_minimal(self, proxies): try: sub_id =", "== 6696 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[9][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[10][0] ==", "ObsState.READY, 15, 1) configuration = json.loads(configuration) band_index = freq_band_dict()[configuration[\"common\"][\"frequency_band\"]] # check configured attributes", "f2.close() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.SCANNING, 1, 1) # Note: scan_id is 1-based and of 'string'", "== 2232 assert proxies.fspSubarray[1].outputLinkMap[3][1] == 16 assert str(proxies.fspSubarray[1].visDestinationAddress).replace('\"',\"'\") == \\ str({\"outputHost\": [[0, \"192.168.0.1\"],", "vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcEnable == True assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcNumBits == 8 assert vcc_tdc_proxies[receptor_to_vcc[1]", "BEFORE the EndScan() command assert proxies.subarray[subarr_index].obsState == ObsState.SCANNING assert proxies.vcc[vcc_ids[0]].obsState == ObsState.SCANNING assert", "vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[0] == 5.85 # assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[1] == 7.25 #", "DevState.ON, 1, 1) for proxy in [proxies.fsp[i + 1] for i in range(4)]:", "fsp_1_proxies.subarray[1].frequencyBand == 4 # assert fsp_1_proxies.subarray[1].band5Tuning[0] == 5.85 # assert fsp_1_proxies.subarray[1].band5Tuning[1] == 7.25", "fsp_1_proxies.subarray[1].channelAveragingMap[10][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[11][0] == 8184 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[11][1]", "assert fsp_2_proxies.subarray[1].channelAveragingMap[19][1] == 0 # # then for FSP 3... # assert fsp_3_proxies.subarray[1].receptors[0]", "assert \"\".join(sw_1_proxy.tdcDestinationAddress.split()) in [ # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", #", "tm_telstate_proxy.receivedOutputLinks == False # add receptors proxies.subarray[1].RemoveAllReceptors() proxies.subarray[1].AddReceptors([1, 3, 4]) time.sleep(1) assert proxies.subarray[1].receptors[0]", "VCC belonging to receptor 10... # assert vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership == 1 #", "proxy in vcc_proxies]) # assert proxies.subarray[1].State() == DevState.OFF # assert subarray_2_proxy.State() == DevState.OFF", "== 7.25 # assert fsp_1_proxies.subarray[1].frequencyBandOffsetStream1 == 0 # assert fsp_1_proxies.subarray[1].frequencyBandOffsetStream2 == 0 #", "assert proxies.subarray[subarr_index].obsState == ObsState.READY assert proxies.vcc[vcc_ids[0]].obsState == ObsState.READY assert proxies.vcc[vcc_ids[num_receptors -1]].obsState == ObsState.READY", "assert all([proxies.vcc[i + 1].subarrayMembership == 0 for i in range(4)]) input_receptors = [1,", "0 # assert proxies.subarray[1].frequencyBand == 0 # assert proxies.subarray[1].State() == DevState.ON # assert", "\"80\" ) # then for search window 2 of VCC belonging to receptor", "\"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) # check scanID on VCC and FSP", "to enum or edit attribute to accept string in FSP if fsp[\"function_mode\"] ==", "receptor 1, ObsState = {}\". format(proxies.vcc[proxies.receptor_to_vcc[1]].ObsState)) ) #proxies.vcc[0].receptorID assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 1.1 assert", "# assert proxies.subarray[1].frequencyBand == 0 # assert proxies.subarray[1].State() == DevState.ON # assert proxies.subarray[1].ObsState", "== False assert fsp_3_proxies.subarray[1].receptors[0] == 3 assert fsp_3_proxies.subarray[1].receptors[1] == 1 assert fsp_3_proxies.subarray[1].searchWindowID ==", "# if (i == 0 and band_index == 0) or (i == (band_index", "== ObsState.IDLE assert proxies.fspSubarray[3].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState ==", "searchBeam400[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" proxies.subarray[1].GoToIdle() time.sleep(3) assert proxies.subarray[1].obsState == ObsState.IDLE proxies.subarray[1].RemoveAllReceptors() time.sleep(3) assert proxies.subarray[1].state()", "check configured attributes of FSP subarrays # # first for FSP 1... #", "\"/../data/Scan2_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) assert proxies.subarray[1].obsState == ObsState.SCANNING assert", "proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBandOffsetStream2 == 0 assert proxies.vcc[proxies.receptor_to_vcc[2]].rfiFlaggingMask == \"{}\" # check configured attributes of FSPs,", "def test_band1( self, cbf_master_proxy, proxies.subarray[1], sw_1_proxy, sw_2_proxy, vcc_proxies, vcc_band_proxies, vcc_tdc_proxies, fsp_1_proxy, fsp_2_proxy, fsp_1_function_mode_proxy,", "8 assert proxies.fspSubarray[1].channelAveragingMap[4][0] == 2976 assert proxies.fspSubarray[1].outputLinkMap[0][0] == 0 assert proxies.fspSubarray[1].outputLinkMap[0][1] == 4", "rec_id = int(receptor[\"receptor\"]) fs_id = receptor[\"receptorDelayDetails\"][0][\"fsid\"] for index, value in enumerate(receptor[\"receptorDelayDetails\"][0][\"delayCoeff\"]): try: assert", "vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[0] == 5.85 assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[1] == 7.25 assert vcc_proxies[receptor_to_vcc[1]", "i in range(4)]) # add some receptors proxies.subarray[1].AddReceptors([1, 3, 4]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1,", "1][0].tdcNumBits == 8 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch == 5 # assert vcc_tdc_proxies[receptor_to_vcc[4]", "CbfSubarray, at end of scan, clear all private data #assert proxies.subarray[sub_id].frequencyBand == 0", "== [ # DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # assert [proxy.State() for proxy in", "1... assert proxies.vcc[proxies.receptor_to_vcc[1]].subarrayMembership == 1 assert proxies.vcc[proxies.receptor_to_vcc[1]].band5Tuning[0] == 5.85 assert proxies.vcc[proxies.receptor_to_vcc[1]].band5Tuning[1] == 7.25", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 3.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 3.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 3.4 assert", "== 0 for i in range(4)]) # add some receptors to subarray 1", "ae except Exception as e: raise e proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1, 1) proxies.clean_proxies()", "0 assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBandOffsetStream2 == 0 assert proxies.vcc[proxies.receptor_to_vcc[4]].rfiFlaggingMask == \"{}\" # then for VCC", "FSP \"\"\" try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On() proxies.wait_timeout_dev([proxies.subarray[1]],", "1 in fsp_1_proxy.subarrayMembership # # assert 1 in fsp_2_proxy.subarrayMembership # assert [proxy.State() for", "json.loads(searchBeam[1]) assert searchBeam0[\"search_beam_id\"] == 300 assert searchBeam0[\"receptor_ids\"][0] == 3 assert searchBeam0[\"enable_output\"] == True", "== \"band:5a, fsp1, 744 channels average factor 8\" assert proxies.subarray[1].frequencyBand == 4 #", ") logging.info( \"config_file_name = {}\".format(config_file_name) ) num_receptors = len(input_receptors) vcc_ids = [None for", "epoch epoch = str(int(epoch) + 10) # update delay model proxies.tm.beamWeights = json.dumps(timing_beam_weights)", "of search windows # # first for search window 1... # assert sw_1_proxy.State()", "a json string ( via attribute 'searchBeams'); # this has to be updated", "assert [proxy.State() for proxy in proxies.vccBand[proxies.receptor_to_vcc[4] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE,", "windows # # first for search window 1... # assert sw_1_proxy.State() == DevState.ON", ") raise ae except Exception as e: raise e # transition to obsState", "in use by a different subarray \"\"\" # for proxy in vcc_proxies: #", "# assert [proxy.State() for proxy in fsp_2_function_mode_proxy] == [ # DevState.ON, DevState.DISABLE, DevState.DISABLE,", "str(df.value.args[0].desc) # assert subarray_2_proxy.receptors == (2, 4) # assert all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership ==", "1... assert vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership == 1 assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[0] == 5.85", "to receptor 10... assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].State() == DevState.DISABLE assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].searchWindowTuning", "ObsState.ABORTED # Restart: receptors should be empty proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert", "1].frequencyBandOffsetStream2 == 0 assert vcc_proxies[receptor_to_vcc[1] - 1].rfiFlaggingMask == \"{}\" # check configured attributes", "i, j in zip(range(num_receptors), input_receptors)]) assert proxies.subarray[subarr_index].obsState == ObsState.IDLE # Check fsp obsState", "proxies.subarray[sub_id].configID == '' # TODO in CbfSubarray, at end of scan, clear all", "proxy in vcc_band_proxies[receptor_to_vcc[4] - 1]] == [ # DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] #", "DevState.DISABLE assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].searchWindowTuning == 7000000000 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].tdcEnable == False", "== \"{}\" assert tm_telstate_proxy.receivedOutputLinks == False # add receptors proxies.subarray[1].RemoveAllReceptors() proxies.subarray[1].AddReceptors([1, 3, 4])", "4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].obsState == ObsState.IDLE # abort proxies.subarray[1].Abort()", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 3.4 # transition to obsState=SCANNING f2 = open(file_path + \"/../data/Scan1_basic.json\")", "proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.SCANNING elif fsp[\"function_mode\"] == \"PSS-BF\": assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.SCANNING # TODO:", "of the configured attributes of VCCs # first for VCC belonging to receptor", "matrix in jones_matrix[\"jonesMatrix\"]: matrix[\"epoch\"] = epoch if matrix[\"destinationType\"] == \"fsp\": epoch = str(int(epoch)", "assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].searchWindowTuning == 7000000000 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].tdcEnable == False", "# assert fsp_1_proxy.functionMode == 1 # assert 1 in fsp_1_proxy.subarrayMembership # # assert", "assert proxies.subarray[1].frequencyBand == 4 assert proxies.subarray[1].obsState == ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i + 1] for i", "True # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcNumBits == 8 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch", "== ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY # ObsReset proxies.subarray[1].ObsReset() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1)", "= open(file_path + \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) # check", "assert 1 in fsp_2_proxy.subarrayMembership # assert [proxy.State() for proxy in fsp_1_function_mode_proxy] == [", "fsp_1_proxies.subarray[1].outputLinkMap[0][1] == 0 assert fsp_1_proxies.subarray[1].outputLinkMap[1][0] == 201 assert fsp_1_proxies.subarray[1].outputLinkMap[1][1] == 1 proxies.subarray[1].GoToIdle() time.sleep(3)", "1) assert all([proxies.subarray[1].receptors[i] == j for i, j in zip(range(4), [4, 1, 3,", "== DevState.ON assert proxies.subarray[1].obsState == ObsState.EMPTY # receptor list should be empty right", "some receptors to subarray 1 # proxies.subarray[1].AddReceptors([1, 3]) # time.sleep(1) # assert proxies.subarray[1].receptors", "DevState.ON] assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[1] - 1]] == [ DevState.DISABLE, DevState.DISABLE,", "6000000000 # assert proxies.sw[1].tdcEnable == True # assert proxies.sw[1].tdcNumBits == 8 # assert", "# assert fsp_2_proxies.subarray[1].corrBandwidth == 0 # # assert fsp_2_proxies.subarray[1].integrationTime == 1400 # #", "# time.sleep(60) # takes pretty long for CBF controller to initialize # receptor_to_vcc", "8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[4][0] == 2976 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[4][1] == 8", "DevState.DISABLE, DevState.DISABLE ] # TODO - # assert [proxy.State() for proxy in fsp_2_function_mode_proxy]", "== 2976 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[4][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[5][0] ==", "raise ae except Exception as e: raise e time.sleep(10) # Clean Up proxies.clean_proxies()", "- 1][1].State() == DevState.DISABLE # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].searchWindowTuning == 7000000000 # assert", "== 5.85 assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[1] == 7.25 assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream1 ==", "proxies.fspSubarray[fsp_id].outputLinkMap[i][j] == fsp[\"output_link_map\"][i][j] proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae except Exception", "proxies.subarray[1].AddReceptors([4, 1, 3, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[1].receptors[i] == j for", "searchBeam400[\"searchBeamID\"] == 400 # assert searchBeam400[\"receptors\"][0] == 1 # assert searchBeam400[\"outputEnable\"] == True", "{}\". format(jj+1, proxies.vcc[jj+1].receptorID))) logging.info( (\"Vcc, receptor 1, ObsState = {}\". format(proxies.vcc[proxies.receptor_to_vcc[1]].ObsState)) ) #proxies.vcc[0].receptorID", "search window 1... # TODO - SearchWidow device test is disabled since the", "== DevState.ON # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].searchWindowTuning == 6000000000 # assert vcc_tdc_proxies[receptor_to_vcc[4] -", "jones_matrix[\"jonesMatrix\"][1][\"epoch\"] = \"0\" jones_matrix[\"jonesMatrix\"][2][\"epoch\"] = str(int(time.time()) + 10) # update Jones Matrix proxies.tm.jonesMatrix", "delay model data from file f = open(file_path + \"/../data/delaymodel.json\") delay_model = json.loads(f.read().replace(\"\\n\",", "assert proxies.fspSubarray[fsp_id].fspChannelOffset == fsp[\"channel_offset\"] for i in range(len(fsp[\"channel_averaging_map\"])): for j in range(len(fsp[\"channel_averaging_map\"][i])): assert", "long for CBF Master to initialize # tm_telstate_proxy.Init() # time.sleep(1) # receptor_to_vcc =", "== ObsState.READY # Send the Scan command f2 = open(file_path + \"/../data/Scan1_basic.json\") json_string", "raise e time.sleep(10) # update timing beam weights from tm emulator f =", "== 2 # assert searchBeam400[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" # proxies.subarray[1].GoToIdle() # time.sleep(3) # assert", "== 3.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 3.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 3.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] ==", "vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream1 == 0 # assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream2 == 0 #", "- 1].frequencyBand == 4 assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[4] - 1]] ==", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[15][0] == 11161 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[15][1] == 0 #", "= json.loads(searchBeam[1]) assert searchBeam0[\"search_beam_id\"] == 300 assert searchBeam0[\"receptor_ids\"][0] == 3 assert searchBeam0[\"enable_output\"] ==", "1488 assert proxies.fspSubarray[1].channelAveragingMap[2][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[3][0] == 2232 assert proxies.fspSubarray[1].channelAveragingMap[3][1] == 8", "30, 1) # check initial states assert proxies.subarray[1].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState ==", "== tango.DevState.OFFequency band capabilities assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand == 4 assert vcc_proxies[receptor_to_vcc[1] -", "fsp[\"function_mode\"] == \"PST-BF\": function_mode = 3 elif fsp[\"function_mode\"] == \"VLBI\": function_mode = 4", "attributes of CBF subarray # assert proxies.subarray[1].configID == \"band:5a, fsp1, 744 channels average", "e time.sleep(10) # update delay models from tm emulator f = open(file_path +", "Test abort restart \"\"\" try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON:", "5209 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[7][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[8][0] == 5953", "[4, 1] #test_receptor_ids = [1] vcc_index = proxies.receptor_to_vcc[test_receptor_ids[0]] logging.info(\"vcc_index = {}\".format(vcc_index)) vcc_band_proxies =", "\"/../data/ConfigureScan_basic.json\" f = open(file_path + config_file_name) proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 15, 1)", "== 3 # assert searchBeam300[\"outputEnable\"] == True # assert searchBeam300[\"averagingInterval\"] == 4 #", "25 assert \"\".join(sw_1_proxy.tdcDestinationAddress.split()) in [ \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", ] # then for", "search window 1 of VCC belonging to receptor 10... # assert vcc_tdc_proxies[receptor_to_vcc[4] -", "assert proxies.subarray[1].obsState == ObsState.SCANNING time.sleep(10) for receptor in jones_matrix[\"jonesMatrix\"][2][\"matrixDetails\"]: for frequency_slice in receptor[\"receptorMatrix\"]:", "for index, value in enumerate(receptor[\"receptorMatrix\"][0][\"matrix\"]): try: assert proxies.fsp[fs_id].jonesMatrix[rec_id - 1][index] == value except", "300 assert searchBeam0[\"receptor_ids\"][0] == 3 assert searchBeam0[\"enable_output\"] == True assert searchBeam0[\"averaging_interval\"] == 4", "= proxies.subarray[1].DebugDevice() try: proxies.clean_proxies() if proxies.controller.State() == DevState.OFF: proxies.controller.Init() proxies.wait_timeout_dev([proxies.controller], DevState.STANDBY, 3, 1)", "search window 2... # assert proxies.sw[2].State() == DevState.DISABLE # assert proxies.sw[2].searchWindowTuning == 7000000000", "== ObsState.READY assert proxies.fspSubarray[3].obsState == ObsState.READY # send the Scan command f2 =", "1 assert proxies.vcc[proxies.receptor_to_vcc[4]].scanID ==1 # check states assert proxies.subarray[1].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState", "configured attributes of FSPs, including states of function mode capabilities assert fsp_1_proxy.functionMode ==", "assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch == 25 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcDestinationAddress == ( \"fizz\",", "proxies.clean_proxies() raise e #TODO refactor to verify delay model values against input json", "== DevState.DISABLE # assert sw_2_proxy.searchWindowTuning == 7000000000 # assert sw_2_proxy.tdcEnable == False #", "since the command takes a while # proxies.subarray[1].Init() # time.sleep(3) # cbf_master_proxy.set_timeout_millis(60000) #", "0.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 1.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 1.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 1.2", "in range(4)]: if proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) # check", "device # for proxy in vcc_band_proxies: # logging.info(\"VCC proxy.State() = {}\".format(proxy.State())) # for", "@pytest.mark.skip(reason=\"test needs to be refactored\") def test_ConfigureScan_delayModel(self, proxies): \"\"\" Test the reception of", "\"\")) f1.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) # check initial states assert proxies.subarray[1].obsState ==", "== 20 # # assert fsp_2_proxies.subarray[1].corrBandwidth == 0 # # assert fsp_2_proxies.subarray[1].integrationTime ==", "# check scanID on VCC and FSP assert proxies.fspSubarray[1].scanID == 1 assert proxies.vcc[proxies.receptor_to_vcc[4]].scanID", "proxies.vcc[vcc_id].jonesMatrix[fs_id-1]) ) raise ae except Exception as e: raise e proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY,", "format(jj+1, proxies.vcc[jj+1].receptorID))) logging.info( (\"Vcc, receptor 1, ObsState = {}\". format(proxies.vcc[proxies.receptor_to_vcc[1]].ObsState)) ) #proxies.vcc[0].receptorID assert", "= json.loads(json_string) proxies.subarray[subarr_index].ConfigureScan(json_string) f.close() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.READY, 15, 1) logging.info( \"First vcc obsState AFTER", "# \"foo\", \"bar\", \"8080\" # ) # then for search window 1 of", "\"0\" delay_model[\"delayModel\"][2][\"epoch\"] = str(int(time.time()) + 10) # update delay model proxies.tm.delayModel = json.dumps(delay_model)", "proxies.vcc[proxies.receptor_to_vcc[1]].band5Tuning[0] == 5.85 assert proxies.vcc[proxies.receptor_to_vcc[1]].band5Tuning[1] == 7.25 # check configured attributes of search", "VCC search windows # first for search window 1 of VCC belonging to", "== 25 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcDestinationAddress == ( \"foo\", \"bar\", \"8080\" ) #", "== ( # \"fizz\", \"buzz\", \"80\" # ) # then for search window", "1... assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].State() == DevState.ON assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].searchWindowTuning == 6000000000", "- SearchWidow device test is disabled since the same # functionality is implemented", "# try adding some receptors (including an invalid one) to subarray 2 #", "assert fsp_3_proxies.subarray[1].searchWindowID == 2 assert fsp_3_proxies.subarray[1].searchBeamID[0] == 300 assert fsp_3_proxies.subarray[1].searchBeamID[1] == 400 searchBeam", "is not assigned to the subarray \"\"\" try: # turn on Subarray if", "then for search window 1 of VCC belonging to receptor 1... assert vcc_tdc_proxies[receptor_to_vcc[1]", "assert fsp_2_proxies.subarray[1].channelAveragingMap[17][0] == 12649 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[17][1] == 0 # # assert", "i, j in zip(range(3), [1, 3, 4])]) # configure scan f1 = open(file_path", "df: # proxies.subarray[1].AddReceptors([5]) # time.sleep(1) # assert \"Invalid receptor ID\" in str(df.value.args[0].desc) #", "ObsState.EMPTY # add receptors proxies.subarray[sub_id].AddReceptors(test_receptor_ids) proxies.wait_timeout_obs([proxies.subarray[sub_id]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[sub_id].receptors[i] == j", "assert all([proxies.subarray[1].receptors[i] == j for i, j in zip(range(3), [1, 3, 4])]) assert", "== 0 # assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream2 == 0 # assert vcc_proxies[receptor_to_vcc[4] -", "assert proxies.sw[1].searchWindowTuning == 6000000000 # assert proxies.sw[1].tdcEnable == True # assert proxies.sw[1].tdcNumBits ==", "\"delayCoeff = {}\".format( aa[jj][\"delayCoeff\"]) ) try: # turn on Subarray if proxies.subarray[1].State() !=", "assert [proxy.State() for proxy in fsp_2_function_mode_proxy] == [ # DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE", "attributes of FSPs, including states of function mode capabilities assert proxies.fsp[1].functionMode == 1", "fsp_1_proxies.subarray[1].fspChannelOffset == 14880 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[0][0] == 0 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[0][1]", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[17][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[18][0] == 13393 # #", "assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].searchWindowTuning == 7000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].tdcEnable == False #", "in proxies.vccBand[proxies.receptor_to_vcc[2] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # check the", "def test_ConfigureScan_basic(self, proxies): \"\"\" Test a successful scan configuration \"\"\" proxies.subarray[1].loggingLevel = LoggingLevel.DEBUG", "open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 15, 1) # update jones", "raise e @pytest.mark.skip(reason=\"Since there's only a single subarray, this test is currently broken.\")", "# remove some receptors proxies.subarray[1].RemoveReceptors([2, 1, 4]) time.sleep(1) assert proxies.subarray[1].receptors == ([3]) assert", "== DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY # Input", "proxies.receptor_to_vcc[test_receptor_ids[0]] logging.info(\"vcc_index = {}\".format(vcc_index)) vcc_band_proxies = proxies.vccBand[vcc_index - 1] # turn on Subarray", "DevState.DISABLE # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].searchWindowTuning == 7000000000 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].tdcEnable", "j in zip(range(4), [4, 1, 3, 2])]) # configure scan f = open(file_path", "\"10.05.1.1\" assert searchBeam1[\"search_beam_id\"] == 400 assert searchBeam1[\"receptor_ids\"][0] == 1 assert searchBeam1[\"enable_output\"] == True", "# check configured attributes of FSP subarray #TODO align IDs of fspSubarrays to", "== True # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcNumBits == 8 # assert vcc_tdc_proxies[receptor_to_vcc[1] -", "(e.g. out of range) - when a receptor to be removed is not", "frequency band of VCCs, including states of # frequency band capabilities logging.info( (\"proxies.vcc[vcc_index].frequencyBand", "receptor 1... assert vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership == 1 # check configured attributes of", "= epoch if model[\"destinationType\"] == \"fsp\": epoch = str(int(epoch) + 10) # update", "== 4 assert proxies.fspSubarray[1].outputLinkMap[1][0] == 744 assert proxies.fspSubarray[1].outputLinkMap[1][1] == 8 assert proxies.fspSubarray[1].outputLinkMap[2][0] ==", "# functionality is implemented by the VccSearchWindow device; # to be decide which", "fsp_1_proxies.subarray[1].channelAveragingMap[3][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[4][0] == 2976 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[4][1]", "assert fsp_2_proxies.subarray[1].channelAveragingMap[6][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[7][0] == 5209 # # assert", "1, 1) assert proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1] == 3 assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership ==", "window 2... # assert proxies.sw[2].State() == DevState.DISABLE # assert proxies.sw[2].searchWindowTuning == 7000000000 #", "all([proxies.subarray[sub_id].receptors[i] == j for i, j in zip(range(len(test_receptor_ids)), test_receptor_ids)]) # configure scan f", "for search window 2 of VCC belonging to receptor 1... assert proxies.vccTdc[proxies.receptor_to_vcc[1] -", "#TODO currently only support for 1 receptor per fsp test_receptor_ids = [4, 1]", "assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.SCANNING # TODO: this check does not pass, to fix", "f = open(file_path + \"/../data/jonesmatrix.json\") jones_matrix = json.loads(f.read().replace(\"\\n\", \"\")) f.close() jones_matrix[\"jonesMatrix\"][0][\"epoch\"] = str(int(time.time())", "fsp_3_proxies.subarray[1].searchWindowID == 2 assert fsp_3_proxies.subarray[1].searchBeamID[0] == 300 assert fsp_3_proxies.subarray[1].searchBeamID[1] == 400 searchBeam =", "... (this is a PSS fsp device) assert proxies.fspSubarray[3].receptors[0] == 3 assert proxies.fspSubarray[3].receptors[1]", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[11][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[12][0] == 8929 #", "assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand == 0 # check the rest of the configured", "== 2232 # assert fsp_1_subarray_1_proroxy.receptors[2] == 4 # # assert fsp_2_proxies.subarray[1].frequencyBand == 4", "causing a fault within the Vcc device # for proxy in vcc_band_proxies: #", "i in range(4)]: if proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) for", "attributes of FSP subarray #TODO align IDs of fspSubarrays to fsp_id in conftest;", "assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand == 4 # assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[4]", "assert proxies.vcc[proxies.receptor_to_vcc[4]].band5Tuning[0] == 5.85 assert proxies.vcc[proxies.receptor_to_vcc[4]].band5Tuning[1] == 7.25 assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBandOffsetStream1 == 0 assert", "epoch = str(int(time.time())) for weights in timing_beam_weights[\"beamWeights\"]: weights[\"epoch\"] = epoch epoch = str(int(epoch)", "assert proxies.vcc[vcc_ids[0]].obsState == ObsState.SCANNING assert proxies.vcc[vcc_ids[num_receptors-1]].obsState == ObsState.SCANNING for fsp in input_config_dict[\"cbf\"][\"fsp\"]: if", "# first for search window 1... assert sw_1_proxy.State() == DevState.ON assert sw_1_proxy.searchWindowTuning ==", "] # then for search window 2... assert sw_2_proxy.State() == DevState.DISABLE assert sw_2_proxy.searchWindowTuning", "assert proxies.fspSubarray[3].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.SCANNING #", "assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae except", "0 assert proxies.subarray[1].configID == '' assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState.value == ObsState.IDLE.value", "== 8 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch == 5 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch ==", "0.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 0.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 0.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 0.9", "proxies): \"\"\" Test RemoveAllReceptors command \"\"\" try: # turn on Subarray if proxies.subarray[1].State()", "mode capabilities assert proxies.fsp[2].State() == DevState.ON assert proxies.fsp[2].functionMode == 3 assert 1 in", "+ \"/../data/jonesmatrix_fsp.json\") jones_matrix = json.loads(f.read().replace(\"\\n\", \"\")) epoch = str(int(time.time())) for matrix in jones_matrix[\"jonesMatrix\"]:", "a minimal successful configuration \"\"\" for proxy in vcc_proxies: proxy.Init() fsp_1_proxies.subarray[1].Init() fsp_2_proxies.subarray[1].Init() fsp_3_proxies.subarray[1].Init()", "== j for i, j in zip(range(len(test_receptor_ids)), test_receptor_ids)]) # configure scan f =", "== ObsState.IDLE # Check fsp obsState BEFORE scan configuration: assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.IDLE", "of attributes of CBF subarray # assert len(proxies.subarray[1].receptors) == 0 # assert proxies.subarray[1].configID", "f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) assert proxies.subarray[1].obsState == ObsState.SCANNING time.sleep(10) assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] ==", "in range(4)], ObsState.READY, 1, 1) # check frequency band of VCCs, including states", "str(int(time.time()) + 10) # update delay model proxies.tm.delayModel = json.dumps(delay_model) time.sleep(1) for jj", "Exception as e: proxies.clean_proxies() raise e def test_ConfigureScan_minimal(self, proxies): try: sub_id = 1", "not assigned to subarray 1 # doing this doesn't actually throw an error", "first for search window 1... # TODO - SearchWidow device test is disabled", "on Subarray if proxies.subarray[sub_id].State() != DevState.ON: proxies.subarray[sub_id].On() proxies.wait_timeout_dev([proxies.subarray[sub_id]], DevState.ON, 3, 1) for proxy", "belonging to receptor 10... assert vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership == 1 # then for", "3, 4]]) assert proxies.subarray[1].obsState == ObsState.IDLE # remove all receptors proxies.subarray[1].RemoveAllReceptors() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY,", "vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].searchWindowTuning == 6000000000 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcEnable == True #", "\"\")) epoch = str(int(time.time())) for weights in timing_beam_weights[\"beamWeights\"]: weights[\"epoch\"] = epoch epoch =", "(2, 4) # assert all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership == 1 for i in [1,", "assert fsp_1_proxies.subarray[1].channelAveragingMap[19][1] == 8 # assert fsp_1_proxies.subarray[1].outputLinkMap[0][0] == 0 # assert fsp_1_proxies.subarray[1].outputLinkMap[0][1] ==", "# proxies.subarray[1].RemoveAllReceptors() # time.sleep(3) # assert proxies.subarray[1].state() == tango.DevState.OFFequency band capabilities assert vcc_proxies[receptor_to_vcc[4]", "== 8 assert proxies.fspSubarray[1].outputLinkMap[2][0] == 1488 assert proxies.fspSubarray[1].outputLinkMap[2][1] == 12 assert proxies.fspSubarray[1].outputLinkMap[3][0] ==", "subarray 1 # proxies.subarray[1].AddReceptors([1, 3]) # time.sleep(1) # assert proxies.subarray[1].receptors == (1, 3)", "function mode capabilities assert fsp_1_proxy.functionMode == 1 assert 1 in fsp_1_proxy.subarrayMembership # assert", "== False # check configured attributes of FSPs, including states of function mode", "0 assert all([proxies.vcc[i + 1].subarrayMembership == 0 for i in range(4)]) input_receptors =", "assert proxies.fspSubarray[fsp_id].integrationTime == fsp[\"integration_factor\"] assert proxies.fspSubarray[fsp_id].corrBandwidth == fsp[\"zoom_factor\"] if fsp[\"zoom_factor\"] > 0: assert", "400 # searchBeam = fsp_3_proxies.subarray[1].searchBeams # searchBeam300 = json.loads(searchBeam[0]) # searchBeam400 = json.loads(searchBeam[1])", "== 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[2][0] == 1488 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[2][1] ==", "# # check configured attributes of FSPs, including states of function mode capabilities", "the Vcc device # for proxy in vcc_band_proxies: # logging.info(\"VCC proxy.State() = {}\".format(proxy.State()))", "\"\"\" Test the Scan command \"\"\" try: # turn on Subarray if proxies.subarray[1].State()", "4 assert proxies.subarray[1].obsState == ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i + 1] for i in range(4)], ObsState.READY,", "configurations are tested def test_ConfigureScan_basic(self, proxies): \"\"\" Test a successful scan configuration \"\"\"", "== '' assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState == ObsState.EMPTY # add receptors", "to verify delay model values against input json @pytest.mark.skip(reason=\"test needs to be refactored\")", "initialize tm_telstate_proxy.Init() time.sleep(1) receptor_to_vcc = dict([*map(int, pair.split(\":\"))] for pair in cbf_master_proxy.receptorToVcc) cbf_master_proxy.On() time.sleep(3)", "restart \"\"\" try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On() proxies.wait_timeout_dev([proxies.subarray[1]],", "band capabilities logging.info( (\"proxies.vcc[vcc_index].frequencyBand = {}\". format( proxies.vcc[vcc_index].frequencyBand)) ) assert proxies.vcc[vcc_index].configID == configuration[\"common\"][\"config_id\"]", "\"\".join(sw_1_proxy.tdcDestinationAddress.split()) in [ # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", # ]", "i in [1, 2, 4]]) assert proxies.vcc[proxies.receptor_to_vcc[3]].subarrayMembership == 1 # remove remaining receptors", "# proxies.subarray[1].AddReceptors([5]) # time.sleep(1) # assert \"Invalid receptor ID\" in str(df.value.args[0].desc) # try", "# check frequency band of VCCs, including states of # frequency band capabilities", "= epoch epoch = str(int(epoch) + 10) # update delay model proxies.tm.beamWeights =", "assert proxies.vcc[proxies.receptor_to_vcc[4]].band5Tuning[1] == 7.25 assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBandOffsetStream1 == 0 assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBandOffsetStream2 == 0 assert", "freq_band_dict()[frequency_band] assert proxies.subarray[subarr_index].configID == input_config_dict[\"common\"][\"config_id\"] assert proxies.subarray[subarr_index].frequencyBand == input_band_index assert proxies.subarray[subarr_index].obsState == ObsState.READY", "== 2.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 2.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 2.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] ==", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[9][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[10][0] == 7440 # #", "== DevState.ON # assert proxies.sw[1].searchWindowTuning == 6000000000 # assert proxies.sw[1].tdcEnable == True #", "== 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[1][0] == 744 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[1][1] ==", "proxies.fspSubarray[3].searchWindowID == 2 assert proxies.fspSubarray[3].searchBeamID[0] == 300 assert proxies.fspSubarray[3].searchBeamID[1] == 400 # TODO:", "configuration # \"\"\" # for proxy in vcc_proxies: # proxy.Init() # fsp_1_proxies.subarray[1].Init() #", "== 3.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 3.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 3.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] ==", "proxies.subarray[1].ObsState == ObsState.EMPTY # # assert tm_telstate_proxy.visDestinationAddress == \"{}\" # assert tm_telstate_proxy.receivedOutputLinks ==", "proxies.fsp[2].functionMode == 3 assert 1 in proxies.fsp[2].subarrayMembership assert [proxy.State() for proxy in proxies.fsp2FunctionMode]", "30, 1) assert proxies.subarray[1].obsState == ObsState.READY # create a delay model # Insert", "== 1.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 1.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 1.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] ==", "fsp_1_proxies.subarray[1].outputLinkMap[2][0] == 1488 # assert fsp_1_proxies.subarray[1].outputLinkMap[2][1] == 12 # assert fsp_1_proxies.subarray[1].outputLinkMap[3][0] == 2232", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].obsState == ObsState.IDLE assert proxies.subarray[1].scanID == 0 assert", "# assert fsp_1_proxies.subarray[1].band5Tuning[1] == 7.25 # assert fsp_1_proxies.subarray[1].frequencyBandOffsetStream1 == 0 # assert fsp_1_proxies.subarray[1].frequencyBandOffsetStream2", "assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcNumBits == 8 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch == 5 assert", "1... (this is a CORR fsp device) assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[1].receptors", "fsp_2_proxies.subarray[1].channelAveragingMap[10][0] == 7441 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[10][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[11][0]", "a while # proxies.subarray[1].Init() # time.sleep(3) # cbf_master_proxy.set_timeout_millis(60000) # cbf_master_proxy.Init() # time.sleep(60) #", "proxy.Init() # proxies.subarray[1].set_timeout_millis(60000) # subarray_2_proxy.set_timeout_millis(60000) # proxies.subarray[1].Init() # subarray_2_proxy.Init() # time.sleep(3) # cbf_controller_proxy.set_timeout_millis(60000)", "then for search window 2 of VCC belonging to receptor 10... # assert", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[17][0] == 12649 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[17][1] == 0 #", "{}\".format(proxy.State())) assert [proxy.State() for proxy in proxies.vccBand[proxies.receptor_to_vcc[4] - 1]] == [ DevState.DISABLE, DevState.DISABLE,", "= proxies.receptor_to_vcc[4] logging.info(\"vcc_index = {}\".format( vcc_index )) assert len(proxies.subarray[1].receptors) == 0 assert proxies.subarray[1].configID", "1 # assert fsp_1_proxies.subarray[1].zoomWindowTuning == 4700000 # assert fsp_1_proxies.subarray[1].integrationTime == 140 # assert", "proxies.vcc[proxies.receptor_to_vcc[2]].rfiFlaggingMask == \"{}\" # check configured attributes of FSPs, including states of function", "time.sleep(1) # check configured attributes of VCC search windows # first for search", "to receptor 10... # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].State() == DevState.ON # assert vcc_tdc_proxies[receptor_to_vcc[4]", "to receptor 10... assert vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership == 1 assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[0]", "e time.sleep(10) for receptor in jones_matrix[\"jonesMatrix\"][0][\"matrixDetails\"]: for frequency_slice in receptor[\"receptorMatrix\"]: for index, value", "assert searchBeam300[\"searchBeamID\"] == 300 # assert searchBeam300[\"receptors\"][0] == 3 # assert searchBeam300[\"outputEnable\"] ==", "by a different subarray \"\"\" # for proxy in vcc_proxies: # proxy.Init() #", "json.loads(searchBeam[0]) searchBeam400 = json.loads(searchBeam[1]) assert searchBeam300[\"searchBeamID\"] == 300 assert searchBeam300[\"receptors\"][0] == 3 assert", "logging.info( \"proxies.fspCorrSubarray[subarr_index-1].obsState = {}\". format(proxies.fspCorrSubarray[subarr_index-1].obsState) ) logging.info( \"proxies.fspPssSubarray[subarr_index-1].obsState = {}\". format(proxies.fspPssSubarray[subarr_index-1].obsState) ) logging.info(", "#TODO refactor to verify delay model values against input json @pytest.mark.skip(reason=\"test needs to", "\"\"\" # Read delay model data from file f = open(file_path + \"/../data/delaymodel.json\")", "proxies.subarray[1].obsState == ObsState.READY # create a delay model # Insert the epoch delay_model[\"delayModel\"][0][\"epoch\"]", "\"80\" # ) # # then for search window 2 of VCC belonging", "vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcDestinationAddress == ( \"fizz\", \"buzz\", \"80\" ) # then for search", "is part of the csp-lmc-prototype project # # # # Distributed under the", "# DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[1] -", "i, j in zip(range(1), [2])]) assert all([proxies.fspSubarray[6].timingBeamID[i] == j for i, j in", "== 0 assert proxies.fspSubarray[1].frequencySliceID == 1 assert proxies.fspSubarray[1].corrBandwidth == 1 assert proxies.fspSubarray[1].zoomWindowTuning ==", "\"PST-BF\": # assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.SCANNING proxies.subarray[subarr_index].EndScan() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.READY, 1, 1) # Check", "[None for _ in range(num_receptors)] for receptor_id, ii in zip(input_receptors, range(num_receptors)): vcc_ids[ii] =", "# check frequency band of VCCs, including states of frequency band capabilities #", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[13][0] == 9672 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[13][1] == 8 #", "1].subarrayMembership == 1 for i in [1, 3]]) # assert proxies.subarray[1].State() == DevState.ON", "== 14880 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[0][0] == 0 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[0][1] ==", "assert fsp_1_subarray_1_proroxy.receptors[2] == 4 # # assert fsp_2_proxies.subarray[1].frequencyBand == 4 # # assert", "vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].State() == DevState.DISABLE # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].searchWindowTuning == 7000000000 #", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[1][0] == 745 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[1][1] == 0 #", "# check states assert proxies.subarray[1].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState", "for search window 2... assert sw_2_proxy.State() == DevState.DISABLE assert sw_2_proxy.searchWindowTuning == 7000000000 assert", "proxies.subarray[1].configID == \"sbi-mvp01-20200325-00001-science_A\" assert proxies.subarray[1].frequencyBand == 0 # means 1 assert proxies.subarray[1].obsState.value ==", "searchBeam1 = json.loads(searchBeam[1]) assert searchBeam0[\"search_beam_id\"] == 300 assert searchBeam0[\"receptor_ids\"][0] == 3 assert searchBeam0[\"enable_output\"]", "assert proxies.subarray[1].obsState == ObsState.IDLE assert proxies.subarray[1].scanID == 0 assert proxies.fspSubarray[1].obsState == ObsState.IDLE assert", "assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[0] == 5.85 assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[1] == 7.25 assert", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[8][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[9][0] == 6697 #", "== () # assert proxies.subarray[1].configID == 0 assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState.value", "proxies.subarray[1].On() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.ON, 3, 1) for proxy in [proxies.vcc[i + 1] for i", "proxies.subarray[1].State() == DevState.ON assert proxies.subarray[1].obsState == ObsState.EMPTY # receptor list should be empty", "BSD-3-Clause license. # See LICENSE.txt for more info. \"\"\"Contain the tests for the", "pretty long for CBF Master to initialize # tm_telstate_proxy.Init() # time.sleep(1) # receptor_to_vcc", "+ 20) delay_model[\"delayModel\"][1][\"epoch\"] = \"0\" delay_model[\"delayModel\"][2][\"epoch\"] = str(int(time.time()) + 10) # update delay", "True assert searchBeam0[\"averaging_interval\"] == 4 # TODO - this does not pass -", "proxies.fspSubarray[1].corrBandwidth == 1 assert proxies.fspSubarray[1].zoomWindowTuning == 4700000 assert proxies.fspSubarray[1].integrationTime == 1 assert proxies.fspSubarray[1].fspChannelOffset", "fsp_2_function_mode_proxy, fsp_3_proxies.subarray[1], tm_telstate_proxy ): \"\"\" Test a minimal successful configuration \"\"\" for proxy", "open(file_path + \"/test_json/data_model_confluence.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() time.sleep(15) # check configured attributes of CBF", "1][1].tdcEnable == False # and lastly for search window 2 of VCC belonging", "jones_matrix[\"jonesMatrix\"][0][\"epoch\"] = str(int(time.time()) + 20) jones_matrix[\"jonesMatrix\"][1][\"epoch\"] = \"0\" jones_matrix[\"jonesMatrix\"][2][\"epoch\"] = str(int(time.time()) + 10)", "of VCCs # # first for VCC belonging to receptor 10... # assert", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[8][0] == 5953 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[8][1] == 0 #", "== 6697 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[9][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[10][0] ==", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 1.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 1.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 1.2 assert", "1][0].State() == DevState.ON assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].searchWindowTuning == 6000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcEnable", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 1.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 1.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 1.7 assert", "first for FSP 1... assert fsp_1_proxies.subarray[1].obsState == ObsState.READY assert fsp_1_proxies.subarray[1].frequencyBand == 0 assert", "CbfSubarray.\"\"\" # Standard imports import sys import os import time from datetime import", "range(4)]: if proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) # check initial", "Jones Matrix proxies.tm.jonesMatrix = json.dumps(jones_matrix) time.sleep(1) for matrix in jones_matrix[\"jonesMatrix\"]: if matrix[\"destinationType\"] ==", "== \"PSS-BF\": assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.READY # TODO: this check does not pass,", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[16][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[17][0] == 12648 #", "input_receptors assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for i in input_receptors]) assert proxies.subarray[1].obsState == ObsState.IDLE", "proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcEnable == True assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcNumBits == 8 assert proxies.vccTdc[proxies.receptor_to_vcc[4]", "DevState.ON, DevState.DISABLE ] # check configured attributes of FSP subarrays # FSP 2", "1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED # ObsReset proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1)", "receptors to subarray 1 proxies.subarray[1].AddReceptors([1, 3]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].receptors[0] ==", "sw_1_proxy, # sw_2_proxy, # vcc_proxies, # vcc_band_proxies, # vcc_tdc_proxies, # fsp_1_proxy, # fsp_2_proxy,", "fsp_2_proxies.subarray[1].channelAveragingMap[8][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[9][0] == 6697 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[9][1]", "[proxies.subarray[1].receptors[i] for i in range(3)] == input_receptors assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for i", "ae except Exception as e: proxies.clean_proxies() raise e def test_EndScan(self, proxies, input_test_data): \"\"\"", "== 1 for i in [1, 3]]) # assert all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership ==", "search window 1 of VCC belonging to receptor 1... assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].State()", "import pytest # SKA specific imports from ska_mid_cbf_mcs.commons.global_enum import freq_band_dict from ska_tango_base.control_model import", "== \"PSS-BF\": assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.SCANNING # TODO: this check does not pass,", "in zip(range(1), [10])]) # Clean Up proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise", "assert 1 in fsp_1_proxy.subarrayMembership # assert 1 in fsp_2_proxy.subarrayMembership assert [proxy.State() for proxy", "ae: raise ae except Exception as e: raise e time.sleep(10) # Clean Up", "ObsState.READY assert fsp_1_proxies.subarray[1].frequencyBand == 0 assert fsp_1_proxies.subarray[1].frequencySliceID == 1 assert fsp_1_proxies.subarray[1].corrBandwidth == 0", "\".format(timeout_millis) #logging.info(log_msg) #logging.info(\"start_time = {}\".format(time.time())) logging.info(\"start datetime = {}\".format(datetime.now())) if proxies.debug_device_is_on: port =", "== True assert searchBeam300[\"averagingInterval\"] == 4 assert searchBeam300[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" assert searchBeam400[\"searchBeamID\"] ==", "fsp_1_proxies.subarray[1].corrBandwidth == 0 assert fsp_1_proxies.subarray[1].integrationTime == 1400 assert fsp_1_proxies.subarray[1].outputLinkMap[0][0] == 1 assert fsp_1_proxies.subarray[1].outputLinkMap[0][1]", "in [proxies.fsp[i + 1] for i in range(4)]: proxy.loggingLevel = \"DEBUG\" if proxy.State()", "+ 10) # update Jones Matrix proxies.tm.jonesMatrix = json.dumps(jones_matrix) time.sleep(1) for matrix in", "# this has to be updated in FspPssSubarray # to read/write individual members", "== 1 assert proxies.fspSubarray[1].corrBandwidth == 1 assert proxies.fspSubarray[1].zoomWindowTuning == 4700000 assert proxies.fspSubarray[1].integrationTime ==", "e: raise e proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1, 1) proxies.clean_proxies() except AssertionError as ae:", "8 # assert fsp_1_proxies.subarray[1].outputLinkMap[2][0] == 1488 # assert fsp_1_proxies.subarray[1].outputLinkMap[2][1] == 12 # assert", "vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership == 1 # check configured attributes of FSPs, including states", "ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE # Clean Up proxies.clean_proxies()", "enumerate(receptor[\"receptorDelayDetails\"][0][\"delayCoeff\"]): try: assert proxies.fsp[fs_id].delayModel[rec_id - 1][index] == value except AssertionError as ae: raise", "1) assert proxies.subarray[1].obsState == ObsState.ABORTED # ObsReset proxies.subarray[1].ObsReset() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert", "frequency band capabilities logging.info( (\"proxies.vcc[vcc_index].frequencyBand = {}\". format( proxies.vcc[vcc_index].frequencyBand)) ) assert proxies.vcc[vcc_index].configID ==", "= fsp[\"fsp_id\"] logging.info(\"{}\".format(fsp_id)) #TODO add function mode to enum or edit attribute to", "proxies.subarray[1].AddReceptors([1, 3, 4]) # time.sleep(1) # assert proxies.subarray[1].receptors[0] == 1 # assert proxies.subarray[1].receptors[1]", "send the Scan command f2 = open(file_path + \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]],", "obsState=SCANNING f2 = open(file_path + \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1)", "2232 assert proxies.fspSubarray[1].outputLinkMap[3][1] == 16 assert str(proxies.fspSubarray[1].visDestinationAddress).replace('\"',\"'\") == \\ str({\"outputHost\": [[0, \"192.168.0.1\"], [8184,", "multiple scan configurations are tested def test_ConfigureScan_basic(self, proxies): \"\"\" Test a successful scan", "1... assert fsp_1_proxies.subarray[1].obsState == ObsState.READY assert fsp_1_proxies.subarray[1].frequencyBand == 0 assert fsp_1_proxies.subarray[1].frequencySliceID == 1", "ObsState.IDLE ############################# abort from SCANNING ########################### # add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2])", "invalid AddReceptors commands involving a single subarray: - when a receptor ID is", "receptors to subarray 1 # proxies.subarray[1].AddReceptors([1, 3]) # time.sleep(1) # assert proxies.subarray[1].receptors ==", "a CORR fsp device) assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[1].receptors == 4 assert", "e: proxies.clean_proxies() raise e def test_ConfigureScan_jonesMatrix(self, proxies): \"\"\" Test the reception of Jones", "# time.sleep(10) # # check initial value of attributes of CBF subarray #", "ObsState.READY assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[3].obsState == ObsState.READY # send the Scan", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 1.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 1.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 1.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2]", "list should be empty right after initialization assert len(proxies.subarray[1].receptors) == 0 assert all([proxies.vcc[i", "proxies): \"\"\" Test valid AddReceptors and RemoveReceptors commands \"\"\" timeout_millis = proxies.subarray[1].get_timeout_millis() log_msg", "1 in fsp_2_proxy.subarrayMembership # assert [proxy.State() for proxy in fsp_1_function_mode_proxy] == [ #", "json.loads(searchBeam[1]) assert searchBeam300[\"searchBeamID\"] == 300 assert searchBeam300[\"receptors\"][0] == 3 assert searchBeam300[\"outputEnable\"] == True", "assert proxies.fspSubarray[1].corrBandwidth == 1 assert proxies.fspSubarray[1].zoomWindowTuning == 4700000 assert proxies.fspSubarray[1].integrationTime == 1 assert", "proxies.controller.State() == DevState.OFF: proxies.controller.Init() proxies.wait_timeout_dev([proxies.controller], DevState.STANDBY, 3, 1) proxies.controller.On() proxies.wait_timeout_dev([proxies.controller], DevState.ON, 3, 1)", "1] #test_receptor_ids = [1] vcc_index = proxies.receptor_to_vcc[test_receptor_ids[0]] logging.info(\"vcc_index = {}\".format(vcc_index)) vcc_band_proxies = proxies.vccBand[vcc_index", "proxies.fspSubarray[fsp_id].zoomWindowTuning == fsp[\"zoom_window_tuning\"] assert proxies.fspSubarray[fsp_id].fspChannelOffset == fsp[\"channel_offset\"] for i in range(len(fsp[\"channel_averaging_map\"])): for j", "AddReceptors commands involving a single subarray: - when a receptor ID is invalid", "fsp_1_proxy.functionMode == 1 # assert 1 in fsp_1_proxy.subarrayMembership # # assert 1 in", "all receptors proxies.subarray[1].RemoveAllReceptors() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert len(proxies.subarray[1].receptors) == 0 assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership", "elif fsp[\"function_mode\"] == \"PST-BF\": function_mode = 3 elif fsp[\"function_mode\"] == \"VLBI\": function_mode =", "== 400 # searchBeam = fsp_3_proxies.subarray[1].searchBeams # searchBeam300 = json.loads(searchBeam[0]) # searchBeam400 =", "== 5.85 assert proxies.fspSubarray[1].band5Tuning[1] == 7.25 assert proxies.fspSubarray[1].frequencyBandOffsetStream1 == 0 assert proxies.fspSubarray[1].frequencyBandOffsetStream2 ==", "- 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # check the rest of", "# Clean Up proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae except Exception", "== 1488 assert proxies.fspSubarray[1].outputLinkMap[2][1] == 12 assert proxies.fspSubarray[1].outputLinkMap[3][0] == 2232 assert proxies.fspSubarray[1].outputLinkMap[3][1] ==", "vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].searchWindowTuning == 6000000000 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcEnable == True assert vcc_tdc_proxies[receptor_to_vcc[4]", "0 and band_index == 0) or (i == (band_index - 1)): # assert", "1) assert all([proxies.subarray[sub_id].receptors[i] == j for i, j in zip(range(len(test_receptor_ids)), test_receptor_ids)]) # configure", "fsp[\"integration_factor\"] assert proxies.fspSubarray[fsp_id].corrBandwidth == fsp[\"zoom_factor\"] if fsp[\"zoom_factor\"] > 0: assert proxies.fspSubarray[fsp_id].zoomWindowTuning == fsp[\"zoom_window_tuning\"]", "assert proxies.subarray[1].obsState == ObsState.ABORTED # Restart: receptors should be empty proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY,", "some receptors proxies.subarray[1].AddReceptors(input_receptors) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert [proxies.subarray[1].receptors[i] for i in range(3)]", "- 1].frequencyBandOffsetStream2 == 0 assert vcc_proxies[receptor_to_vcc[4] - 1].rfiFlaggingMask == \"{}\" # then for", "if proxies.controller.State() == DevState.OFF: proxies.controller.Init() proxies.wait_timeout_dev([proxies.controller], DevState.STANDBY, 3, 1) proxies.controller.On() proxies.wait_timeout_dev([proxies.controller], DevState.ON, 3,", "FSP 1... assert fsp_1_proxies.subarray[1].obsState == ObsState.READY assert fsp_1_proxies.subarray[1].frequencyBand == 0 assert fsp_1_proxies.subarray[1].frequencySliceID ==", "for pair in # cbf_controller_proxy.receptorToVcc) # cbf_controller_proxy.On() # time.sleep(3) # # receptor list", "assert searchBeam300[\"outputEnable\"] == True assert searchBeam300[\"averagingInterval\"] == 4 assert searchBeam300[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" assert", "1) # check initial value of attributes of CBF subarray assert len(proxies.subarray[sub_id].receptors) ==", "jones_matrix[\"jonesMatrix\"]: if matrix[\"destinationType\"] == \"fsp\": for receptor in matrix[\"matrixDetails\"]: rec_id = int(receptor[\"receptor\"]) fs_id", "fsp_1_proxies.subarray[1].channelAveragingMap[6][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[7][0] == 5208 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[7][1]", "proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.SCANNING # abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState ==", "CbfSubarray, at end of scan, clear all private data #assert proxies.subarray[1].frequencyBand == 0", "# first for VCC belonging to receptor 2... assert proxies.vcc[proxies.receptor_to_vcc[2]].subarrayMembership == 1 assert", "test_ConfigureScan_delayModel(self, proxies): \"\"\" Test the reception of delay models \"\"\" # Read delay", "configure scan f1 = open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f1.read().replace(\"\\n\", \"\")) f1.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30,", "DevState.ON] assert [proxy.State() for proxy in proxies.vccBand[proxies.receptor_to_vcc[1] - 1]] == [ DevState.DISABLE, DevState.DISABLE,", "as ae: proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e '''", "ae: proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e def test_Scan(self,", "assert searchBeam0[\"receptor_ids\"][0] == 3 assert searchBeam0[\"enable_output\"] == True assert searchBeam0[\"averaging_interval\"] == 4 #", "# # add receptors # proxies.subarray[1].RemoveAllReceptors() # proxies.subarray[1].AddReceptors([1, 3, 4]) # time.sleep(1) #", "FSP 3 ... (this is a PSS fsp device) assert proxies.fspSubarray[3].receptors[0] == 3", "j in zip(range(1), [2])]) assert all([proxies.fspSubarray[6].timingBeamID[i] == j for i, j in zip(range(1),", "+ \"/../data/Scan2_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) assert proxies.subarray[1].obsState == ObsState.SCANNING", "ObsState.READY.value # # check frequency band of VCCs, including states of frequency band", "i in [1, 3]]) # assert proxies.subarray[1].State() == DevState.ON # # try adding", "# assert fsp_1_proxies.subarray[1].receptors == 4 # assert fsp_1_proxies.subarray[1].frequencyBand == 4 # assert fsp_1_proxies.subarray[1].band5Tuning[0]", "== 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[6][0] == 4464 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[6][1] ==", "assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream2 == 0 assert vcc_proxies[receptor_to_vcc[4] - 1].rfiFlaggingMask == \"{}\" #", "assert proxies.fsp[1].functionMode == 1 assert 1 in proxies.fsp[1].subarrayMembership assert [proxy.State() for proxy in", "entry: epoch {}, VCC {}, i = {}, jonesMatrix[{}] = {}\".format( jones_matrix[\"jonesMatrix\"][1][\"epoch\"], vcc_id,", "vcc_tdc_proxies, fsp_1_proxy, fsp_2_proxy, fsp_1_function_mode_proxy, fsp_2_function_mode_proxy, fsp_3_proxies.subarray[1], tm_telstate_proxy ): \"\"\" Test a minimal successful", "ObsState.IDLE ############################# abort from READY ########################### # add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2])", "== 0 assert proxies.fspSubarray[1].outputLinkMap[0][1] == 4 assert proxies.fspSubarray[1].outputLinkMap[1][0] == 744 assert proxies.fspSubarray[1].outputLinkMap[1][1] ==", "1].rfiFlaggingMask == \"{}\" # # then for VCC belonging to receptor 1... #", "for receptor in jones_matrix[\"jonesMatrix\"][1][\"matrixDetails\"]: for frequency_slice in receptor[\"receptorMatrix\"]: for index, value in enumerate(frequency_slice[\"matrix\"]):", "ObsState.EMPTY ############################# abort from IDLE ########################### # add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2])", "initial states assert proxies.subarray[1].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState ==", "DevState.OFF, 3, 1) except AssertionError as ae: proxies.clean_proxies() raise ae except Exception as", "== ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE proxies.clean_proxies() except AssertionError", "assert proxies.fspSubarray[3].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE #", "3 ... (this is a PSS fsp device) assert proxies.fspSubarray[3].receptors[0] == 3 assert", "the epoch delay_model[\"delayModel\"][0][\"epoch\"] = str(int(time.time()) + 20) delay_model[\"delayModel\"][1][\"epoch\"] = \"0\" delay_model[\"delayModel\"][2][\"epoch\"] = str(int(time.time())", "1 elif fsp[\"function_mode\"] == \"PSS-BF\": function_mode = 2 elif fsp[\"function_mode\"] == \"PST-BF\": function_mode", "proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) for proxy in [proxies.fsp[i +", "e time.sleep(10) # Clean Up proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae", "ObsState.READY assert proxies.fspSubarray[1].receptors == 4 assert proxies.fspSubarray[1].frequencyBand == 4 assert proxies.fspSubarray[1].band5Tuning[0] == 5.85", "[[0, \"192.168.0.1\"], [8184, \"192.168.0.2\"]], \"outputMac\": [[0, \"06-00-00-00-00-01\"]], \"outputPort\": [[0, 9000, 1], [8184, 9000,", "- 1][1].State() == DevState.DISABLE assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].searchWindowTuning == 7000000000 assert vcc_tdc_proxies[receptor_to_vcc[1] -", "4 assert proxies.fsp[fsp_id].functionMode == function_mode assert sub_id in proxies.fsp[fsp_id].subarrayMembership assert [proxy.State() for proxy", "3, 4]) time.sleep(1) assert proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1] == 3 assert proxies.subarray[1].receptors[2]", "proxies.subarray[sub_id].On() proxies.wait_timeout_dev([proxies.subarray[sub_id]], DevState.ON, 3, 1) for proxy in [proxies.vcc[i + 1] for i", "- 1][0].tdcEnable == True assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcNumBits == 8 assert vcc_tdc_proxies[receptor_to_vcc[1] -", "proxies.subarray[1].RemoveAllReceptors() proxies.subarray[1].AddReceptors([1, 3, 4]) time.sleep(1) assert proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1] == 3", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[10][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[11][0] == 8185 # #", "window 2 of VCC belonging to receptor 10... assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].State() ==", "== False # check configured attributes of VCC search windows # first for", "# # assert fsp_2_proxies.subarray[1].frequencyBandOffsetStream2 == 0 # # assert fsp_2_proxies.subarray[1].frequencySliceID == 20 #", "== band_index assert proxies.vcc[vcc_index].subarrayMembership == sub_id #TODO fix these tests; issue with VccBand", "test_Scan(self, proxies): \"\"\" Test the Scan command \"\"\" try: # turn on Subarray", "# first for VCC belonging to receptor 10... assert proxies.vcc[proxies.receptor_to_vcc[4]].subarrayMembership == 1 assert", "assert proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1] == 3 assert proxies.subarray[1].receptors[2] == 4 #", "proxies.subarray[1].set_timeout_millis(60000) # subarray_2_proxy.set_timeout_millis(60000) # proxies.subarray[1].Init() # subarray_2_proxy.Init() # time.sleep(3) # cbf_controller_proxy.set_timeout_millis(60000) # cbf_controller_proxy.Init()", "pair in cbf_master_proxy.receptorToVcc) cbf_master_proxy.On() time.sleep(3) # check initial value of attributes of CBF", "fsp_2_proxies.subarray[1].channelAveragingMap[15][0] == 11161 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[15][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[16][0]", "1, 1) # check frequency band of VCCs, including states of # frequency", "assert fsp_2_proxies.subarray[1].channelAveragingMap[15][0] == 11161 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[15][1] == 0 # # assert", "ObsState.EMPTY # Input test data: input_receptors = input_test_data[0] config_file_name = input_test_data[1] subarr_index =", "assert searchBeam400[\"receptors\"][0] == 1 # assert searchBeam400[\"outputEnable\"] == True # assert searchBeam400[\"averagingInterval\"] ==", "0 # assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream2 == 0 # assert vcc_proxies[receptor_to_vcc[4] - 1].rfiFlaggingMask", "proxies.subarray[1].configID == \"band:5a, fsp1, 744 channels average factor 8\" # assert proxies.subarray[1].frequencyBand ==", "- 1][1].searchWindowTuning == 7000000000 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].tdcEnable == False # and lastly", "# # turn on Subarray # assert proxies.subarray[1].state()==DevState.OFF # proxies.subarray[1].On() # time.sleep(10) #", "fsp_2_proxies.subarray[1].frequencyBandOffsetStream2 == 0 # # assert fsp_2_proxies.subarray[1].frequencySliceID == 20 # # assert fsp_2_proxies.subarray[1].corrBandwidth", "delay model proxies.tm.delayModel = json.dumps(delay_model) time.sleep(1) for model in delay_model[\"delayModel\"]: if model[\"destinationType\"] ==", "scan_index = int(input_scan_dict[\"scan_id\"]) - 1 logging.info( \"proxies.fspCorrSubarray[subarr_index-1].obsState = {}\". format(proxies.fspCorrSubarray[subarr_index-1].obsState) ) logging.info( \"proxies.fspPssSubarray[subarr_index-1].obsState", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 2.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 2.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 2.7 assert", "1.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 1.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 2.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 2.1", "receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[1].receptors[i] == j", "value except AssertionError as ae: raise ae except Exception as e: raise e", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 1.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 1.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 1.4 assert", "] # # check configured attributes of FSP subarrays # # first for", "# cbf_master_proxy.Init() # time.sleep(60) # takes pretty long for CBF Master to initialize", "== fsp[\"channel_averaging_map\"][i][j] for i in range(len(fsp[\"output_link_map\"])): for j in range(len(fsp[\"output_link_map\"][i])): assert proxies.fspSubarray[fsp_id].outputLinkMap[i][j] ==", "Up proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae except Exception as e:", "proxies.fspSubarray[1].outputLinkMap[2][0] == 1488 assert proxies.fspSubarray[1].outputLinkMap[2][1] == 12 assert proxies.fspSubarray[1].outputLinkMap[3][0] == 2232 assert proxies.fspSubarray[1].outputLinkMap[3][1]", "1 assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBandOffsetStream1 == 0 assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBandOffsetStream2 == 0 assert proxies.vcc[proxies.receptor_to_vcc[2]].rfiFlaggingMask == \"{}\"", "# proxy.Init() # proxies.subarray[1].set_timeout_millis(60000) # subarray_2_proxy.set_timeout_millis(60000) # proxies.subarray[1].Init() # subarray_2_proxy.Init() # time.sleep(3) #", "proxies.fsp[fsp_id].functionMode == function_mode assert sub_id in proxies.fsp[fsp_id].subarrayMembership assert [proxy.State() for proxy in fsp_function_mode_proxies[fsp_id-1]]", "index, value in enumerate(receptor[\"receptorWeightsDetails\"][0][\"weights\"]): try: assert proxies.fsp[fs_id].timingBeamWeights[rec_id - 1][index] == value except AssertionError", "assert sw_1_proxy.State() == DevState.ON assert sw_1_proxy.searchWindowTuning == 6000000000 assert sw_1_proxy.tdcEnable == True assert", "including states of frequency band capabilities assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBand == 4 assert [proxy.State() for", "DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ] # check configured attributes of FSP subarray #TODO align", "assert proxies.subarray[1].State() == DevState.ON # # try adding some receptors (including an invalid", "all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for i in input_receptors]) assert proxies.subarray[1].obsState == ObsState.IDLE # add", "search window 2 of VCC belonging to receptor 10... assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].State()", "vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch == 5 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch == 25 #", "- 1][index] == value except AssertionError as ae: raise ae except Exception as", "- 1][0].tdcPeriodBeforeEpoch == 5 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch == 25 # TODO -", "to subarray 1 # proxies.subarray[1].AddReceptors([1, 3]) # time.sleep(1) # assert proxies.subarray[1].receptors == (1,", "by the device # as a json string ( via attribute 'searchBeams'); #", "json.dumps(jones_matrix) time.sleep(5) for receptor in jones_matrix[\"jonesMatrix\"][1][\"matrixDetails\"]: for frequency_slice in receptor[\"receptorMatrix\"]: for index, value", "supported\") def test_ConfigureScan_onlyPst_basic_FSP_scan_parameters(self, proxies): \"\"\" Test a successful transmission of PST-BF parameters to", "AddReceptors and RemoveReceptors commands \"\"\" timeout_millis = proxies.subarray[1].get_timeout_millis() log_msg = \"timeout_millis = {}", "for VCC belonging to receptor 2... assert proxies.vcc[proxies.receptor_to_vcc[2]].subarrayMembership == 1 assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBandOffsetStream1 ==", "== \"10.05.2.1\" proxies.subarray[1].GoToIdle() time.sleep(3) assert proxies.subarray[1].obsState == ObsState.IDLE proxies.subarray[1].RemoveAllReceptors() time.sleep(3) assert proxies.subarray[1].state() ==", "== ObsState.IDLE assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.IDLE assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.IDLE logging.info( \"First vcc", "DevState.ON assert proxies.fsp[2].functionMode == 3 assert 1 in proxies.fsp[2].subarrayMembership assert [proxy.State() for proxy", "2 of VCC belonging to receptor 10... assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].State() == DevState.DISABLE", "== 25 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcDestinationAddress == ( # \"foo\", \"bar\", \"8080\"", "# first for search window 1 of VCC belonging to receptor 10... #", "proxies.fspSubarray[3].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE # Clean", "4 assert proxies.vcc[proxies.receptor_to_vcc[1]].frequencyBand == 4 for proxy in proxies.vccBand[proxies.receptor_to_vcc[4] - 1]: logging.info(\"VCC proxy.State()", "the device # as a json string ( via attribute 'searchBeams'); # this", "assert all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership == 2 for i in [2, 4]]) # assert", "proxies.fspSubarray[1].channelAveragingMap[4][0] == 2976 assert proxies.fspSubarray[1].outputLinkMap[0][0] == 0 assert proxies.fspSubarray[1].outputLinkMap[0][1] == 4 assert proxies.fspSubarray[1].outputLinkMap[1][0]", "Tango imports import tango from tango import DevState import pytest # SKA specific", "fsp_1_proxies.subarray[1].channelAveragingMap[19][1] == 8 # assert fsp_1_proxies.subarray[1].outputLinkMap[0][0] == 0 # assert fsp_1_proxies.subarray[1].outputLinkMap[0][1] == 4", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[7][0] == 5208 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[7][1] == 8 # #", "belonging to receptor 10... # assert vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership == 1 # assert", "3 # assert searchBeam300[\"outputEnable\"] == True # assert searchBeam300[\"averagingInterval\"] == 4 # assert", "receptor in matrix[\"matrixDetails\"]: rec_id = int(receptor[\"receptor\"]) fs_id = receptor[\"receptorMatrix\"][0][\"fsid\"] for index, value in", "- 1].band5Tuning[0] == 5.85 assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[1] == 7.25 assert vcc_proxies[receptor_to_vcc[1] -", "for proxy in vcc_band_proxies: # logging.info(\"VCC proxy.State() = {}\".format(proxy.State())) # for i in", "== DevState.ON # assert proxies.subarray[1].ObsState == ObsState.EMPTY # # assert tm_telstate_proxy.visDestinationAddress == \"{}\"", "- 1][0].State() == DevState.ON # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].searchWindowTuning == 6000000000 # assert", "] # # then for search window 2... # assert sw_2_proxy.State() == DevState.DISABLE", "assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand == 0 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand == 0 #", "assert proxies.subarray[1].obsState == ObsState.IDLE # add more receptors... proxies.subarray[1].AddReceptors([2]) time.sleep(1) assert [proxies.subarray[1].receptors[i] for", "# cbf_controller_proxy.receptorToVcc) # cbf_controller_proxy.On() # time.sleep(3) # # receptor list should be empty", "1][1].searchWindowTuning == 7000000000 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].tdcEnable == False # # check", "# proxies.subarray[1].On() # time.sleep(10) # # check initial value of attributes of CBF", "\"proxies.fspCorrSubarray[subarr_index-1].obsState = {}\". format(proxies.fspCorrSubarray[subarr_index-1].obsState) ) logging.info( \"proxies.fspPssSubarray[subarr_index-1].obsState = {}\". format(proxies.fspPssSubarray[subarr_index-1].obsState) ) logging.info( \"proxies.fspPstSubarray[subarr_index-1].obsState", "jones_matrix[\"jonesMatrix\"][2][\"matrixDetails\"]: for frequency_slice in receptor[\"receptorMatrix\"]: for index, value in enumerate(frequency_slice[\"matrix\"]): vcc_id = proxies.receptor_to_vcc[receptor[\"receptor\"]]", "proxies.vcc[proxies.receptor_to_vcc[4]].scanID ==1 # check states assert proxies.subarray[1].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.SCANNING", "for i, j in zip(range(4), [4, 1, 3, 2])]) # configure scan f", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[7][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[8][0] == 5953 # #", "== ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE # Clean Up", "proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) # check scanID on VCC and", "# sw_1_proxy, # sw_2_proxy, # vcc_proxies, # vcc_band_proxies, # vcc_tdc_proxies, # fsp_1_proxy, #", "\"\"\" for proxy in vcc_proxies: proxy.Init() fsp_3_proxies.subarray[1].Init() fsp_1_proxy.Init() fsp_2_proxy.Init() proxies.subarray[1].set_timeout_millis(60000) # since the", "12 # assert fsp_1_proxies.subarray[1].outputLinkMap[3][0] == 2232 # assert fsp_1_subarray_1_proroxy.receptors[2] == 4 # #", "pretty long for CBF controller to initialize # receptor_to_vcc = dict([*map(int, pair.split(\":\"))] for", "e def test_Abort_Reset(self, proxies): \"\"\" Test abort reset \"\"\" try: # turn on", "proxies.clean_proxies() raise e @pytest.mark.skip(reason=\"Since there's only a single subarray, this test is currently", "\"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", ] # then for search window 2... assert sw_2_proxy.State()", "== 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[16][0] == 11905 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[16][1] ==", "proxies.vcc[vcc_index].frequencyBand)) ) vcc_band_proxies = proxies.vccBand[vcc_index - 1] assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBand == 4 assert proxies.vcc[proxies.receptor_to_vcc[1]].frequencyBand", "fsp[\"function_mode\"] == \"CORR\": assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.SCANNING elif fsp[\"function_mode\"] == \"PSS-BF\": assert proxies.fspPssSubarray[subarr_index-1].obsState", "fsp_1_proxies.subarray[1].channelAveragingMap[9][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[10][0] == 7440 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[10][1]", "\"10.05.2.1\" proxies.subarray[1].GoToIdle() time.sleep(3) assert proxies.subarray[1].obsState == ObsState.IDLE proxies.subarray[1].RemoveAllReceptors() time.sleep(3) assert proxies.subarray[1].state() == tango.DevState.OFF", "1, 1) # check frequency band of VCCs, including states of frequency band", "including states of function mode capabilities fsp_function_mode_proxies = [proxies.fsp1FunctionMode, proxies.fsp2FunctionMode, proxies.fsp3FunctionMode, proxies.fsp4FunctionMode] for", "from ska_tango_base.control_model import LoggingLevel, HealthState from ska_tango_base.control_model import AdminMode, ObsState from ska_tango_base.base_device import", "logging.info( \"First vcc obsState AFTER ConfigureScan = {}\". format(proxies.vcc[vcc_ids[0]].obsState) ) # check some", "11905 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[16][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[17][0] == 12649", "DevState.ON, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY ############################# abort from IDLE ########################### #", "== \\ str({\"outputHost\": [[0, \"192.168.0.1\"], [8184, \"192.168.0.2\"]], \"outputMac\": [[0, \"06-00-00-00-00-01\"]], \"outputPort\": [[0, 9000,", "of 'string' type # scan_index is an index into an array, therefore 0-based", "== ObsState.READY # TODO: this check does not pass, to fix #elif fsp[\"function_mode\"]", "assert proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1] == 3 proxies.subarray[1].RemoveAllReceptors() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1)", "== DevState.ON assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].searchWindowTuning == 6000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcEnable ==", "e: proxies.clean_proxies() raise e def test_Scan(self, proxies): \"\"\" Test the Scan command \"\"\"", "configuration \"\"\" for proxy in vcc_proxies: proxy.Init() fsp_3_proxies.subarray[1].Init() fsp_1_proxy.Init() fsp_2_proxy.Init() proxies.subarray[1].set_timeout_millis(60000) # since", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 2.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 3.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 3.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3]", "proxies.fspSubarray[3].searchBeamID[1] == 400 # TODO: currently searchBeams is stored by the device #", "# subarray_2_proxy.AddReceptors([1, 2, 4]) # time.sleep(1) # assert \"already in use\" in str(df.value.args[0].desc)", "proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY # ObsReset proxies.subarray[1].ObsReset() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].obsState ==", "0 # assert vcc_proxies[receptor_to_vcc[1] - 1].rfiFlaggingMask == \"{}\" # # check configured attributes", "assert fsp_2_proxies.subarray[1].channelAveragingMap[2][0] == 1489 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[2][1] == 0 # # assert", "assert fsp_2_proxies.subarray[1].channelAveragingMap[14][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[15][0] == 11161 # # assert", "True assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcNumBits == 8 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch == 5", "cbf_master_proxy.receptorToVcc) cbf_master_proxy.On() time.sleep(3) # check initial value of attributes of CBF subarray #", "vcc_proxies, vcc_band_proxies, vcc_tdc_proxies, fsp_1_proxy, fsp_2_proxy, fsp_1_function_mode_proxy, fsp_2_function_mode_proxy, fsp_1_proxies.subarray[1], fsp_2_proxies.subarray[1], fsp_3_proxies.subarray[1], tm_telstate_proxy ): \"\"\"", "Read delay model data from file f = open(file_path + \"/../data/delaymodel.json\") delay_model =", "searchBeams is stored by the device # as a json string ( via", "assert proxies.fspSubarray[1].obsState == ObsState.SCANNING assert proxies.fspSubarray[3].obsState == ObsState.SCANNING proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1, 1)", "== 0 assert vcc_proxies[receptor_to_vcc[1] - 1].rfiFlaggingMask == \"{}\" # check configured attributes of", "assert proxies.subarray[1].receptors[1] == 3 assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for i in [1, 3]])", "for i in range(4)]: proxy.loggingLevel = \"DEBUG\" if proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy],", "time.sleep(10) assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 0.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 0.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 0.3", "does not pass - to debug & fix #assert searchBeam1[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" #", "proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.READY for fsp in input_config_dict[\"cbf\"][\"fsp\"]: if fsp[\"function_mode\"] == \"CORR\": assert proxies.fspCorrSubarray[subarr_index-1].obsState", "of VCCs, including states of frequency band capabilities # assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand", "when a receptor to be removed is not assigned to the subarray \"\"\"", "proxies.fspSubarray[3].searchBeamID[0] == 300 assert proxies.fspSubarray[3].searchBeamID[1] == 400 # TODO: currently searchBeams is stored", "8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[17][0] == 12648 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[17][1] == 8", "actually throw an error proxies.subarray[1].RemoveReceptors([2]) assert proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1] == 3", "# TODO - re-enable and debug! # assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcDestinationAddress == (", "assert searchBeam300[\"averagingInterval\"] == 4 # assert searchBeam300[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" # assert searchBeam400[\"searchBeamID\"] ==", "proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].searchWindowTuning == 7000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].tdcEnable == False # and", "including states of function mode capabilities assert proxies.fsp[2].State() == DevState.ON assert proxies.fsp[2].functionMode ==", "assert fsp_1_proxies.subarray[1].channelAveragingMap[17][0] == 12648 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[17][1] == 8 # # assert", "\"already in use\" in str(df.value.args[0].desc) # assert subarray_2_proxy.receptors == (2, 4) # assert", "vcc_band_proxies[i].State() == DevState.ON # else: # assert vcc_band_proxies[i].State() == DevState.DISABLE # check configured", "for search window 2 of VCC belonging to receptor 10... assert vcc_tdc_proxies[receptor_to_vcc[4] -", "delay_model[\"delayModel\"][2][\"epoch\"] = str(int(time.time()) + 10) # update delay model proxies.tm.delayModel = json.dumps(delay_model) time.sleep(1)", "in fsp_1_proxy.subarrayMembership # assert 1 in fsp_2_proxy.subarrayMembership assert [proxy.State() for proxy in fsp_1_function_mode_proxy]", "proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY # abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1,", "device # as a json string ( via attribute 'searchBeams'); # this has", "fsp[\"function_mode\"] == \"CORR\": assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.READY elif fsp[\"function_mode\"] == \"PSS-BF\": assert proxies.fspPssSubarray[subarr_index-1].obsState", "assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].State() == DevState.DISABLE assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].searchWindowTuning == 7000000000 assert", "the same # functionality is implemented by the VccSearchWindow device; # to be", "successful PST-BF scan configuration \"\"\" try: # turn on Subarray if proxies.subarray[1].State() !=", "# assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].State() == DevState.DISABLE # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].searchWindowTuning ==", "- 1][0].tdcPeriodAfterEpoch == 25 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcDestinationAddress == ( \"fizz\", \"buzz\", \"80\"", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 1.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 1.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 1.9 assert", "7.25 assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream1 == 0 assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream2 == 0", "9672 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[13][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[14][0] == 10416", "assert proxies.vcc[proxies.receptor_to_vcc[2]].subarrayMembership == 1 assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBandOffsetStream1 == 0 assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBandOffsetStream2 == 0 assert", "# check configured attributes of FSPs, including states of function mode capabilities fsp_function_mode_proxies", "matrix[\"destinationType\"] == \"fsp\": epoch = str(int(epoch) + 10) # update Jones Matrix proxies.tm.jonesMatrix", "#assert proxies.subarray[sub_id].frequencyBand == 0 assert proxies.subarray[sub_id].obsState == ObsState.EMPTY # add receptors proxies.subarray[sub_id].AddReceptors(test_receptor_ids) proxies.wait_timeout_obs([proxies.subarray[sub_id]],", "\"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) # scan f2 = open(file_path", "== 9672 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[13][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[14][0] ==", "configured attributes of FSP subarrays # first for FSP 1... (this is a", "index into an array, therefore 0-based scan_index = int(input_scan_dict[\"scan_id\"]) - 1 logging.info( \"proxies.fspCorrSubarray[subarr_index-1].obsState", "1) assert proxies.subarray[1].obsState == ObsState.READY # create a delay model # Insert the", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1] == 3 assert", "proxies.subarray[sub_id].configID == configuration[\"common\"][\"config_id\"] assert proxies.subarray[sub_id].frequencyBand == band_index assert proxies.subarray[sub_id].obsState == ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i +", "search window 2 of VCC belonging to receptor 10... # assert vcc_tdc_proxies[receptor_to_vcc[4] -", "first for FSP 1... # assert fsp_1_proxies.subarray[1].obsState == ObsState.EMPTY # assert fsp_1_proxies.subarray[1].receptors ==", "# check configured attributes of FSP subarrays # first for FSP 1... (this", "== 2.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 2.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 2.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] ==", "num_receptors = len(input_receptors) vcc_ids = [None for _ in range(num_receptors)] for receptor_id, ii", "raise e # transition to obsState == SCANNING f2 = open(file_path + \"/../data/Scan1_basic.json\")", "sw_1_proxy.tdcPeriodAfterEpoch == 25 assert \"\".join(sw_1_proxy.tdcDestinationAddress.split()) in [ \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", ] #", "# cbf_controller_proxy.Init() # time.sleep(60) # takes pretty long for CBF controller to initialize", "# assert searchBeam300[\"averagingInterval\"] == 4 # assert searchBeam300[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" # assert searchBeam400[\"searchBeamID\"]", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[17][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[18][0] == 13393 #", "file f = open(file_path + \"/../data/delaymodel.json\") delay_model = json.loads(f.read().replace(\"\\n\", \"\")) f.close() aa =", "proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcNumBits == 8 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch == 5 assert proxies.vccTdc[proxies.receptor_to_vcc[1]", "assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch == 25 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcDestinationAddress == ( \"foo\",", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 4.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 4.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 4.2 assert", "- to debug & fix #assert searchBeam0[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" assert searchBeam1[\"search_beam_id\"] == 400", "proxies.subarray[1].obsState == ObsState.IDLE assert all([proxies.subarray[1].receptors[i] == j for i, j in zip(range(3), [1,", "proxies.fspSubarray[3].obsState == ObsState.SCANNING proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1, 1) assert proxies.subarray[1].obsState == ObsState.READY #", "= open(file_path + \"/../data/timingbeamweights.json\") timing_beam_weights = json.loads(f.read().replace(\"\\n\", \"\")) epoch = str(int(time.time())) for weights", "== \"CORR\": assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.READY elif fsp[\"function_mode\"] == \"PSS-BF\": assert proxies.fspPssSubarray[subarr_index-1].obsState ==", "fix #assert searchBeam0[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" assert searchBeam1[\"search_beam_id\"] == 400 assert searchBeam1[\"receptor_ids\"][0] == 1", "assert sw_1_proxy.searchWindowTuning == 6000000000 assert sw_1_proxy.tdcEnable == True assert sw_1_proxy.tdcNumBits == 8 assert", "format( proxies.vcc[vcc_index].frequencyBand)) ) assert proxies.vcc[vcc_index].configID == configuration[\"common\"][\"config_id\"] assert proxies.vcc[vcc_index].frequencyBand == band_index assert proxies.vcc[vcc_index].subarrayMembership", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[7][0] == 5209 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[7][1] == 0 #", "raise e def test_ConfigureScan_minimal(self, proxies): try: sub_id = 1 #TODO currently only support", "3.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 4.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 4.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 4.2", "# # ] # # check configured attributes of FSP subarrays # #", "== ObsState.READY assert proxies.vcc[vcc_ids[num_receptors -1]].obsState == ObsState.READY assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.READY for fsp", "== \"PST-BF\": # assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.SCANNING proxies.subarray[subarr_index].EndScan() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.READY, 1, 1) #", "= proxies.receptor_to_vcc[receptor[\"receptor\"]] fs_id = frequency_slice[\"fsid\"] try: assert proxies.vcc[vcc_id].jonesMatrix[fs_id-1][index] == value except AssertionError as", "# with pytest.raises(tango.DevFailed) as df: # proxies.subarray[1].AddReceptors([5]) # time.sleep(1) # assert \"Invalid receptor", "ae: proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e @pytest.mark.skip(reason=\"pst not", "= {}\".format(config_file_name) ) num_receptors = len(input_receptors) vcc_ids = [None for _ in range(num_receptors)]", "for receptor in weights[\"beamWeightsDetails\"]: rec_id = int(receptor[\"receptor\"]) fs_id = receptor[\"receptorWeightsDetails\"][0][\"fsid\"] for index, value", "license. # See LICENSE.txt for more info. \"\"\"Contain the tests for the CbfSubarray.\"\"\"", "proxies.subarray[1].obsState == ObsState.IDLE # abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState ==", "1, 1) assert proxies.subarray[1].obsState == ObsState.SCANNING assert proxies.subarray[1].scanID == 2 assert proxies.fspSubarray[1].obsState ==", "# check the rest of the configured attributes of VCCs # first for", "searchBeam1[\"receptor_ids\"][0] == 1 assert searchBeam1[\"enable_output\"] == True assert searchBeam1[\"averaging_interval\"] == 2 # TODO", "fsp in configuration[\"cbf\"][\"fsp\"]: fsp_id = fsp[\"fsp_id\"] logging.info(\"{}\".format(fsp_id)) #TODO add function mode to enum", "\"{}\" # check configured attributes of search windows # first for search window", "invalid (e.g. out of range) - when a receptor to be removed is", "proxies.fspSubarray[fsp_id].frequencySliceID == fsp[\"frequency_slice_id\"] assert proxies.fspSubarray[fsp_id].integrationTime == fsp[\"integration_factor\"] assert proxies.fspSubarray[fsp_id].corrBandwidth == fsp[\"zoom_factor\"] if fsp[\"zoom_factor\"]", "3.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 3.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 3.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 3.6", "[ \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", ] # then for search window 2... assert", "proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE # Clean Up proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise", "# assert fsp_1_proxies.subarray[1].band5Tuning[0] == 5.85 # assert fsp_1_proxies.subarray[1].band5Tuning[1] == 7.25 # assert fsp_1_proxies.subarray[1].frequencyBandOffsetStream1", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 3.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 3.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 3.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1]", "ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE ############################# abort from SCANNING ########################### # add receptors", "assert subarray_2_proxy.State() == DevState.ON def test_RemoveAllReceptors(self, proxies): \"\"\" Test RemoveAllReceptors command \"\"\" try:", "assert proxies.fspSubarray[fsp_id].outputLinkMap[i][j] == fsp[\"output_link_map\"][i][j] proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae except", "raise e proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1, 1) proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies()", "assert proxies.fsp[fsp_id].functionMode == function_mode assert sub_id in proxies.fsp[fsp_id].subarrayMembership assert [proxy.State() for proxy in", "if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.ON, 3, 1) for proxy in [proxies.vcc[i", "!= DevState.ON: proxies.subarray[1].On() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.ON, 3, 1) for proxy in [proxies.vcc[i + 1]", "assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY # ObsReset proxies.subarray[1].ObsReset() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE,", "function mode capabilities fsp_function_mode_proxies = [proxies.fsp1FunctionMode, proxies.fsp2FunctionMode, proxies.fsp3FunctionMode, proxies.fsp4FunctionMode] for fsp in configuration[\"cbf\"][\"fsp\"]:", "ObsState.READY assert proxies.fspSubarray[3].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY", "DevState import pytest # SKA specific imports from ska_mid_cbf_mcs.commons.global_enum import freq_band_dict from ska_tango_base.control_model", "5 # assert proxies.sw[1].tdcPeriodAfterEpoch == 25 # assert \"\".join(proxies.sw[1].tdcDestinationAddress.split()) in [ # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\",", "vcc_band_proxies[receptor_to_vcc[1] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # check the rest", "== 4 assert searchBeam300[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" assert searchBeam400[\"searchBeamID\"] == 400 assert searchBeam400[\"receptors\"][0] ==", "proxies.fspSubarray[1].outputLinkMap[2][1] == 12 assert proxies.fspSubarray[1].outputLinkMap[3][0] == 2232 assert proxies.fspSubarray[1].outputLinkMap[3][1] == 16 assert str(proxies.fspSubarray[1].visDestinationAddress).replace('\"',\"'\")", "mode capabilities # assert fsp_1_proxy.functionMode == 1 # assert 1 in fsp_1_proxy.subarrayMembership #", "== 2.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 2.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 2.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] ==", "DevState.ON assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].searchWindowTuning == 6000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcEnable == True", "1.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 1.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 1.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 1.9", "( # \"foo\", \"bar\", \"8080\" # ) # then for search window 1", "# fsp_2_proxies.subarray[1].Init() # fsp_3_proxies.subarray[1].Init() # fsp_1_proxy.Init() # fsp_2_proxy.Init() # proxies.subarray[1].set_timeout_millis(60000) # since the", "to receptor 10... assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].State() == DevState.ON assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].searchWindowTuning", "range(4)]: if proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) for proxy in", "3, 4] # add some receptors proxies.subarray[1].AddReceptors(input_receptors) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert [proxies.subarray[1].receptors[i]", "assert proxies.fspSubarray[1].integrationTime == 1 assert proxies.fspSubarray[1].fspChannelOffset == 14880 assert proxies.fspSubarray[1].channelAveragingMap[0][0] == 0 assert", "# assert proxies.subarray[1].receptors[0] == 1 # assert proxies.subarray[1].receptors[1] == 3 # assert proxies.subarray[1].receptors[2]", "assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch == 25 # TODO - re-enable and debug! #", "proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.SCANNING # abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1,", "all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for i in [1, 3]]) assert proxies.subarray[1].obsState == ObsState.IDLE #", "searchBeam1[\"averaging_interval\"] == 2 # TODO - this does not pass - to debug", "== 2.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 2.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 2.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] ==", "== DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) assert proxies.subarray[1].State() == DevState.ON assert proxies.subarray[1].obsState", "1, 1) assert proxies.subarray[1].obsState == ObsState.IDLE # abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1)", "== 25 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcDestinationAddress == ( \"fizz\", \"buzz\", \"80\" ) #", "8 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch == 5 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch == 25", "1, 1) for proxy in [proxies.fsp[i + 1] for i in range(4)]: proxy.loggingLevel", "for proxy in vcc_band_proxies[receptor_to_vcc[1] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] #", "1 # assert searchBeam400[\"outputEnable\"] == True # assert searchBeam400[\"averagingInterval\"] == 2 # assert", "of VCCs # first for VCC belonging to receptor 10... assert vcc_proxies[receptor_to_vcc[4] -", "ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED # Restart: receptors should be empty", "# # check initial value of attributes of CBF subarray # assert len(proxies.subarray[1].receptors)", "members searchBeam = proxies.fspSubarray[3].searchBeams searchBeam0 = json.loads(searchBeam[0]) searchBeam1 = json.loads(searchBeam[1]) assert searchBeam0[\"search_beam_id\"] ==", "744 assert proxies.fspSubarray[1].outputLinkMap[1][1] == 8 assert proxies.fspSubarray[1].outputLinkMap[2][0] == 1488 assert proxies.fspSubarray[1].outputLinkMap[2][1] == 12", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 1.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 1.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 1.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3]", ") vcc_band_proxies = proxies.vccBand[vcc_index - 1] assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBand == 4 assert proxies.vcc[proxies.receptor_to_vcc[1]].frequencyBand ==", "assert fsp_1_proxies.subarray[1].channelAveragingMap[3][0] == 2232 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[3][1] == 8 # # assert", "if proxies.debug_device_is_on: port = proxies.subarray[1].DebugDevice() try: proxies.clean_proxies() if proxies.controller.State() == DevState.OFF: proxies.controller.Init() proxies.wait_timeout_dev([proxies.controller],", "a single subarray: - when a receptor ID is invalid (e.g. out of", "# assert fsp_1_proxies.subarray[1].outputLinkMap[3][0] == 2232 # assert fsp_1_subarray_1_proroxy.receptors[2] == 4 # # assert", "assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].State() == DevState.ON assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].searchWindowTuning == 6000000000 assert", "== 4 assert proxies.fspSubarray[1].band5Tuning[0] == 5.85 assert proxies.fspSubarray[1].band5Tuning[1] == 7.25 assert proxies.fspSubarray[1].frequencyBandOffsetStream1 ==", "== 4 for proxy in proxies.vccBand[proxies.receptor_to_vcc[4] - 1]: logging.info(\"VCC proxy.State() = {}\".format(proxy.State())) assert", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 2.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 2.4 proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1, 1) proxies.clean_proxies()", "DevState.ON, 3, 1) for proxy in [proxies.vcc[i + 1] for i in range(4)]:", "assert proxies.fspSubarray[1].scanID == 1 assert proxies.vcc[proxies.receptor_to_vcc[4]].scanID ==1 # check states assert proxies.subarray[1].obsState ==", "i, j in zip(range(3), [1, 3, 4])]) # configure scan config_file_name = \"/../data/ConfigureScan_basic.json\"", "some receptors proxies.subarray[1].RemoveReceptors([2, 1, 4]) time.sleep(1) assert proxies.subarray[1].receptors == ([3]) assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership ==", "j in zip(range(3), [1, 3, 4])]) assert proxies.fspSubarray[1].obsState == ObsState.IDLE assert proxies.fspSubarray[3].obsState ==", "to obsState == SCANNING f2 = open(file_path + \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]],", "assert 1 in fsp_1_proxy.subarrayMembership # # assert 1 in fsp_2_proxy.subarrayMembership # assert [proxy.State()", "the subarray \"\"\" try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On()", "searchBeam0[\"search_beam_id\"] == 300 assert searchBeam0[\"receptor_ids\"][0] == 3 assert searchBeam0[\"enable_output\"] == True assert searchBeam0[\"averaging_interval\"]", "== 25 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcDestinationAddress == ( # \"fizz\", \"buzz\", \"80\"", "vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand == 4 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand == 4 assert [proxy.State()", "== configuration[\"common\"][\"config_id\"] assert proxies.vcc[vcc_index].frequencyBand == band_index assert proxies.vcc[vcc_index].subarrayMembership == sub_id #TODO fix these", "# searchBeam300 = json.loads(searchBeam[0]) # searchBeam400 = json.loads(searchBeam[1]) # assert searchBeam300[\"searchBeamID\"] == 300", "assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].searchWindowTuning == 7000000000 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].tdcEnable == False", "proxies.fsp2FunctionMode] == [ DevState.DISABLE, DevState.DISABLE, DevState.ON, DevState.DISABLE ] # check configured attributes of", "# logging.info(\"VCC proxy.State() = {}\".format(proxy.State())) # for i in range(4): # if (i", "# fsp_1_proxies.subarray[1], # fsp_2_proxies.subarray[1], # fsp_3_proxies.subarray[1], # tm_telstate_proxy # ): # \"\"\" #", "4 # assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand == 4 # assert [proxy.State() for proxy", "raise ae except Exception as e: proxies.clean_proxies() raise e def test_Abort_Reset(self, proxies): \"\"\"", "8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[15][0] == 11160 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[15][1] == 8", "fsp_1_proxies.subarray[1].corrBandwidth == 1 # assert fsp_1_proxies.subarray[1].zoomWindowTuning == 4700000 # assert fsp_1_proxies.subarray[1].integrationTime == 140", "in range(4)]: if proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) assert proxies.subarray[1].obsState", "vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[1] == 7.25 # assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream1 == 0 #", "== [ # DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # # check the rest of", "in vcc_band_proxies[receptor_to_vcc[1] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # check the", "in range(3)] == input_receptors assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for i in input_receptors]) assert", "{}\". format(proxies.fspPssSubarray[subarr_index-1].obsState) ) logging.info( \"proxies.fspPstSubarray[subarr_index-1].obsState = {}\". format(proxies.fspPstSubarray[subarr_index-1].obsState) ) # Check obsStates BEFORE", "== 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[13][0] == 9673 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[13][1] ==", "raise e def test_AddRemoveReceptors_invalid_single(self, proxies): \"\"\" Test invalid AddReceptors commands involving a single", "delay models \"\"\" # Read delay model data from file f = open(file_path", "ObsState.EMPTY # add receptors proxies.subarray[1].AddReceptors([4, 1, 3, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert", "all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership == 1 for i in [1, 3]]) # assert all([vcc_proxies[receptor_to_vcc[i]", "assert proxies.fspSubarray[1].outputLinkMap[3][0] == 2232 assert proxies.fspSubarray[1].outputLinkMap[3][1] == 16 assert str(proxies.fspSubarray[1].visDestinationAddress).replace('\"',\"'\") == \\ str({\"outputHost\":", "== 1.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 1.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 1.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] ==", "1][0].tdcNumBits == 8 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch == 5 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch", "pair in # cbf_master_proxy.receptorToVcc) # cbf_master_proxy.On() # time.sleep(60) # # turn on Subarray", "e: proxies.clean_proxies() raise e ''' def test_ConfigureScan_onlyPss_basic( self, cbf_master_proxy, proxies.subarray[1], sw_1_proxy, sw_2_proxy, vcc_proxies,", "2976 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[4][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[5][0] == 3720", "assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.SCANNING # abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState", "8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[16][0] == 11904 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[16][1] == 8", "= str(int(epoch) + 10) # update delay model proxies.tm.delayModel = json.dumps(delay_model) time.sleep(1) for", "jones_matrix[\"jonesMatrix\"][2][\"epoch\"] = str(int(time.time()) + 10) # update Jones Matrix proxies.tm.jonesMatrix = json.dumps(jones_matrix) time.sleep(5)", "- 1][0].tdcPeriodAfterEpoch == 25 # TODO - re-enable and debug! # assert proxies.vccTdc[proxies.receptor_to_vcc[4]", "== 2233 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[3][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[4][0] ==", "\"proxies.fspPssSubarray[subarr_index-1].obsState = {}\". format(proxies.fspPssSubarray[subarr_index-1].obsState) ) logging.info( \"proxies.fspPstSubarray[subarr_index-1].obsState = {}\". format(proxies.fspPstSubarray[subarr_index-1].obsState) ) # Check", "commands involving a single subarray: - when a receptor ID is invalid (e.g.", "check initial states assert proxies.subarray[1].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState", "300 assert searchBeam300[\"receptors\"][0] == 3 assert searchBeam300[\"outputEnable\"] == True assert searchBeam300[\"averagingInterval\"] == 4", "some receptors proxies.subarray[1].AddReceptors([1, 3, 4]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[1].receptors[i] == j", "== ObsState.SCANNING # TODO: this check does not pass, to fix #elif fsp[\"function_mode\"]", "1][1].State() == DevState.DISABLE # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].searchWindowTuning == 7000000000 # assert vcc_tdc_proxies[receptor_to_vcc[1]", "# assert tm_telstate_proxy.visDestinationAddress == \"{}\" assert tm_telstate_proxy.receivedOutputLinks == False # add receptors proxies.subarray[1].RemoveAllReceptors()", "# abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED # Restart:", "import logging # Path file_path = os.path.dirname(os.path.abspath(__file__)) # Tango imports import tango from", "= epoch if matrix[\"destinationType\"] == \"fsp\": epoch = str(int(epoch) + 10) # update", "== 3 assert searchBeam300[\"outputEnable\"] == True assert searchBeam300[\"averagingInterval\"] == 4 assert searchBeam300[\"searchBeamDestinationAddress\"] ==", "== ObsState.READY.value # check frequency band of VCCs, including states of frequency band", "1) # check initial states assert proxies.subarray[1].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY", "index, fs_id-1, proxies.vcc[vcc_id].jonesMatrix[fs_id-1]) ) raise ae except Exception as e: raise e #", "is an index into an array, therefore 0-based scan_index = int(input_scan_dict[\"scan_id\"]) - 1", "\"/test_json/data_model_confluence.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() time.sleep(15) # check configured attributes of CBF subarray assert", "# tm_telstate_proxy.Init() # time.sleep(1) # receptor_to_vcc = dict([*map(int, pair.split(\":\"))] for pair in #", "configured attributes of FSP subarrays # FSP 2 assert proxies.fspSubarray[6].obsState == ObsState.READY assert", "1) # check initial value of attributes of CBF subarray assert len(proxies.subarray[1].receptors) ==", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[18][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[19][0] == 14137 # #", "searchBeam400[\"receptors\"][0] == 1 # assert searchBeam400[\"outputEnable\"] == True # assert searchBeam400[\"averagingInterval\"] == 2", "# assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[0] == 5.85 # assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[1] ==", "string in FSP if fsp[\"function_mode\"] == \"CORR\": function_mode = 1 elif fsp[\"function_mode\"] ==", "# takes pretty long for CBF Master to initialize tm_telstate_proxy.Init() time.sleep(1) receptor_to_vcc =", "8928 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[12][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[13][0] == 9672", "== 8 # assert fsp_1_proxies.subarray[1].outputLinkMap[0][0] == 0 # assert fsp_1_proxies.subarray[1].outputLinkMap[0][1] == 4 #", "1][0].tdcPeriodAfterEpoch == 25 # TODO - re-enable and debug! # assert proxies.vccTdc[proxies.receptor_to_vcc[1] -", "then for search window 1 of VCC belonging to receptor 1... # assert", "1 #TODO currently only support for 1 receptor per fsp test_receptor_ids = [4,", "DevState.DISABLE, DevState.ON] assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[1] - 1]] == [ DevState.DISABLE,", "except Exception as e: proxies.clean_proxies() raise e #TODO refactor to verify delay model", "1 assert proxies.fspSubarray[3].searchWindowID == 2 assert proxies.fspSubarray[3].searchBeamID[0] == 300 assert proxies.fspSubarray[3].searchBeamID[1] == 400", "400 # assert searchBeam400[\"receptors\"][0] == 1 # assert searchBeam400[\"outputEnable\"] == True # assert", "of attributes of CBF subarray assert len(proxies.subarray[sub_id].receptors) == 0 assert proxies.subarray[sub_id].configID == ''", "minimal successful configuration \"\"\" for proxy in vcc_proxies: proxy.Init() fsp_3_proxies.subarray[1].Init() fsp_1_proxy.Init() fsp_2_proxy.Init() proxies.subarray[1].set_timeout_millis(60000)", "proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e #TODO: fix; currently", "beam weights from tm emulator f = open(file_path + \"/../data/timingbeamweights.json\") timing_beam_weights = json.loads(f.read().replace(\"\\n\",", "range(len(fsp[\"channel_averaging_map\"])): for j in range(len(fsp[\"channel_averaging_map\"][i])): assert proxies.fspSubarray[fsp_id].channelAveragingMap[i][j] == fsp[\"channel_averaging_map\"][i][j] for i in range(len(fsp[\"output_link_map\"])):", "in zip(range(3), [1, 3, 4])]) # configure scan f = open(file_path + \"/../data/ConfigureScan_basic.json\")", "== 2.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 2.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 2.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] ==", "in zip(input_receptors, range(num_receptors)): vcc_ids[ii] = proxies.receptor_to_vcc[receptor_id] proxies.subarray[subarr_index].AddReceptors(input_receptors) proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[subarr_index].receptors[i]", "assert fsp_1_proxies.subarray[1].outputLinkMap[2][1] == 12 # assert fsp_1_proxies.subarray[1].outputLinkMap[3][0] == 2232 # assert fsp_1_subarray_1_proroxy.receptors[2] ==", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 2.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 3.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 3.1 assert", "== ObsState.SCANNING assert proxies.fspSubarray[3].obsState == ObsState.SCANNING proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1, 1) assert proxies.subarray[1].obsState", "ae except Exception as e: proxies.clean_proxies() raise e def test_ConfigureScan_jonesMatrix(self, proxies): \"\"\" Test", "8\" assert proxies.subarray[1].frequencyBand == 4 # means 5a assert proxies.subarray[1].obsState == ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i", "== DevState.ON assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].searchWindowTuning == 6000000000 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcEnable ==", "2.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 2.4 proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1, 1) proxies.clean_proxies() except AssertionError", "== 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[2][0] == 1489 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[2][1] ==", "index, fs_id-1, proxies.vcc[vcc_id].jonesMatrix[fs_id-1]) ) raise ae except Exception as e: raise e time.sleep(10)", "receptor in weights[\"beamWeightsDetails\"]: rec_id = int(receptor[\"receptor\"]) fs_id = receptor[\"receptorWeightsDetails\"][0][\"fsid\"] for index, value in", "DevState.DISABLE # assert proxies.sw[2].searchWindowTuning == 7000000000 # assert proxies.sw[2].tdcEnable == False time.sleep(1) #", "# update Jones Matrix proxies.tm.jonesMatrix = json.dumps(jones_matrix) time.sleep(5) for receptor in jones_matrix[\"jonesMatrix\"][1][\"matrixDetails\"]: for", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) # check scanID on VCC and FSP assert proxies.fspSubarray[1].scanID", "10416 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[14][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[15][0] == 11160", "in conftest; currently works for fsps 1 and 2 assert proxies.fspSubarray[fsp_id].obsState == ObsState.READY", "except Exception as e: raise e proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1, 1) proxies.clean_proxies() except", "# def test_ConfigureScan_basic( # self, # cbf_master_proxy, # proxies.subarray[1], # sw_1_proxy, # sw_2_proxy,", "function mode capabilities assert proxies.fsp[1].functionMode == 1 assert 1 in proxies.fsp[1].subarrayMembership assert [proxy.State()", "check configured attributes of FSPs, including states of function mode capabilities assert proxies.fsp[2].State()", "except Exception as e: proxies.clean_proxies() raise e @pytest.mark.skip(reason=\"Since there's only a single subarray,", "assert proxies.subarray[1].obsState == ObsState.ABORTED # ObsReset proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert proxies.subarray[1].obsState", "receptor ID is invalid (e.g. out of range) - when a receptor to", "= json.loads(searchBeam[1]) assert searchBeam300[\"searchBeamID\"] == 300 assert searchBeam300[\"receptors\"][0] == 3 assert searchBeam300[\"outputEnable\"] ==", "== 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[3][0] == 2233 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[3][1] ==", "e proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1, 1) proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise", "== ObsState.EMPTY ############################# abort from IDLE ########################### # add receptors proxies.subarray[1].AddReceptors([1, 3, 4,", "2 of VCC belonging to receptor 1... # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].State() ==", "f = open(file_path + config_file_name) proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 15, 1) #", "raise e def test_ConfigureScan_jonesMatrix(self, proxies): \"\"\" Test the reception of Jones matrices \"\"\"", "ObsState.SCANNING assert proxies.fspSubarray[3].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.SCANNING", "- 1][0].State() == DevState.ON assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].searchWindowTuning == 6000000000 assert vcc_tdc_proxies[receptor_to_vcc[4] -", "1] for i in range(4)]: proxy.loggingLevel = \"DEBUG\" if proxy.State() == DevState.OFF: proxy.On()", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 0.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 0.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 0.7 assert", "5a assert proxies.subarray[1].obsState == ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i + 1] for i in range(4)], ObsState.READY,", "# assert fsp_2_proxies.subarray[1].band5Tuning[0] == 5.85 # # assert fsp_2_proxies.subarray[1].band5Tuning[1] == 7.25 # #", "proxies.subarray[1].state()==DevState.OFF # proxies.subarray[1].On() # time.sleep(10) # # check initial value of attributes of", "== ObsState.READY assert proxies.fspSubarray[fsp_id].receptors == test_receptor_ids[0] assert proxies.fspSubarray[fsp_id].frequencyBand == band_index assert proxies.fspSubarray[fsp_id].frequencySliceID ==", "0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[5][0] == 3721 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[5][1] == 0", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[13][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[14][0] == 10417 #", "the EndScan command \"\"\" try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON:", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 2.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 2.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 2.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4]", "searchBeam400[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" # proxies.subarray[1].GoToIdle() # time.sleep(3) # assert proxies.subarray[1].obsState == ObsState.IDLE #", "fsp_1_proxies.subarray[1], # fsp_2_proxies.subarray[1], # fsp_3_proxies.subarray[1], # tm_telstate_proxy # ): # \"\"\" # Test", "proxies.subarray[1].obsState == ObsState.IDLE # TODO: fix this # try adding an invalid receptor", "5 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch == 25 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcDestinationAddress == (", "ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.SCANNING # abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]],", "assert proxies.subarray[1].receptors == () # assert subarray_2_proxy.receptors == () # assert all([proxy.subarrayMembership ==", "for CBF controller to initialize # receptor_to_vcc = dict([*map(int, pair.split(\":\"))] for pair in", "#elif fsp[\"function_mode\"] == \"PST-BF\": # assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.READY proxies.clean_proxies() except AssertionError as", "be empty right after initialization # assert proxies.subarray[1].receptors == () # assert subarray_2_proxy.receptors", "value except AssertionError as ae: logging.error(\"AssertionError; incorrect Jones matrix entry: epoch {}, VCC", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 3.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 3.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 3.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4]", "assert \"\".join(proxies.sw[1].tdcDestinationAddress.split()) in [ # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", #", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 2.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 2.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 2.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3]", "proxies): \"\"\" Test the reception of delay models \"\"\" # Read delay model", "= open(file_path + \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) assert proxies.subarray[1].obsState", "\"\")) epoch = str(int(time.time())) for model in delay_model[\"delayModel\"]: model[\"epoch\"] = epoch if model[\"destinationType\"]", "DevState.DISABLE ] # check configured attributes of FSP subarrays # FSP 2 assert", "proxies.subarray[1].Init() # time.sleep(3) # cbf_master_proxy.set_timeout_millis(60000) # cbf_master_proxy.Init() # time.sleep(60) # takes pretty long", "a while proxies.subarray[1].Init() time.sleep(3) cbf_master_proxy.set_timeout_millis(60000) cbf_master_proxy.Init() time.sleep(60) # takes pretty long for CBF", "assert subarray_2_proxy.receptors == () # assert all([proxy.subarrayMembership == 0 for proxy in vcc_proxies])", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[6][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[7][0] == 5208 # #", "vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].searchWindowTuning == 7000000000 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].tdcEnable == False #", "proxies.subarray[1].receptors[2] == 4 # configure scan f = open(file_path + \"/test_json/data_model_confluence.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\"))", "in jones_matrix[\"jonesMatrix\"][0][\"matrixDetails\"]: for frequency_slice in receptor[\"receptorMatrix\"]: for index, value in enumerate(frequency_slice[\"matrix\"]): vcc_id =", "DevState.DISABLE, DevState.ON] assert [proxy.State() for proxy in proxies.vccBand[proxies.receptor_to_vcc[1] - 1]] == [ DevState.DISABLE,", "# assert sw_2_proxy.tdcEnable == False # # check configured attributes of VCC search", "# add some receptors proxies.subarray[1].AddReceptors(input_receptors) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert [proxies.subarray[1].receptors[i] for i", "subarray # assert proxies.subarray[1].configID == \"band:5a, fsp1, 744 channels average factor 8\" #", "- 1][0].State() == DevState.ON # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].searchWindowTuning == 6000000000 # assert", "in range(4): # if (i == 0 and band_index == 0) or (i", "== 11904 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[16][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[17][0] ==", "DevState.ON, 1, 1) assert proxies.subarray[1].State() == DevState.ON assert proxies.subarray[1].obsState == ObsState.EMPTY # receptor", "8929 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[12][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[13][0] == 9673", "Scan command \"\"\" try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On()", "vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch == 5 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch == 25 assert vcc_tdc_proxies[receptor_to_vcc[4]", "assigned to the subarray \"\"\" try: # turn on Subarray if proxies.subarray[1].State() !=", "fsp_1_proxies.subarray[1].channelAveragingMap[1][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[2][0] == 1488 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[2][1]", "- 1][1].tdcEnable == False # and lastly for search window 2 of VCC", "2232 assert proxies.fspSubarray[1].channelAveragingMap[3][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[4][0] == 2976 assert proxies.fspSubarray[1].outputLinkMap[0][0] == 0", "i, j in zip(range(3), [1, 3, 4])]) assert proxies.fspSubarray[1].obsState == ObsState.IDLE assert proxies.fspSubarray[3].obsState", "subarray \"\"\" try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On() proxies.wait_timeout_dev([proxies.subarray[1]],", "1][0].tdcDestinationAddress == ( # \"fizz\", \"buzz\", \"80\" # ) # then for search", "assert proxies.subarray[1].obsState == ObsState.IDLE # proxies.subarray[1].RemoveAllReceptors() # time.sleep(3) # assert proxies.subarray[1].state() == tango.DevState.OFFequency", "13392 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[18][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[19][0] == 14136", "cbf_master_proxy.Init() time.sleep(60) # takes pretty long for CBF Master to initialize tm_telstate_proxy.Init() time.sleep(1)", "# # assert tm_telstate_proxy.visDestinationAddress == \"{}\" # assert tm_telstate_proxy.receivedOutputLinks == False # #", "== DevState.DISABLE assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].searchWindowTuning == 7000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].tdcEnable ==", "1 in fsp_1_proxy.subarrayMembership # assert 1 in fsp_2_proxy.subarrayMembership assert [proxy.State() for proxy in", "value of attributes of CBF subarray # assert len(proxies.subarray[1].receptors) == 0 # assert", "ObsState.IDLE proxies.subarray[1].RemoveAllReceptors() time.sleep(3) assert proxies.subarray[1].state() == tango.DevState.OFF def test_band1( self, cbf_master_proxy, proxies.subarray[1], sw_1_proxy,", "- 1][1].State() == DevState.DISABLE # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].searchWindowTuning == 7000000000 # assert", "== 13392 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[18][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[19][0] ==", "rec_id = int(receptor[\"receptor\"]) fs_id = receptor[\"receptorMatrix\"][0][\"fsid\"] for index, value in enumerate(receptor[\"receptorMatrix\"][0][\"matrix\"]): try: assert", "== 1488 assert proxies.fspSubarray[1].channelAveragingMap[2][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[3][0] == 2232 assert proxies.fspSubarray[1].channelAveragingMap[3][1] ==", "assert proxies.subarray[1].obsState.value == ObsState.IDLE.value # assert tm_telstate_proxy.visDestinationAddress == \"{}\" assert tm_telstate_proxy.receivedOutputLinks == False", "as ae: proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e def", "all([proxies.subarray[subarr_index].receptors[i] == j for i, j in zip(range(num_receptors), input_receptors)]) assert proxies.subarray[subarr_index].obsState == ObsState.IDLE", "e: raise e time.sleep(10) # update timing beam weights from tm emulator f", "== 8 assert proxies.fspSubarray[1].channelAveragingMap[3][0] == 2232 assert proxies.fspSubarray[1].channelAveragingMap[3][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[4][0] ==", "long for CBF controller to initialize # receptor_to_vcc = dict([*map(int, pair.split(\":\"))] for pair", "assert fsp_2_proxies.subarray[1].channelAveragingMap[9][0] == 6697 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[9][1] == 0 # # assert", "ObsState.IDLE assert all([proxies.subarray[1].receptors[i] == j for i, j in zip(range(3), [1, 3, 4])])", "logging.info( (\"Vcc, receptor 1, ObsState = {}\". format(proxies.vcc[proxies.receptor_to_vcc[1]].ObsState)) ) #proxies.vcc[0].receptorID assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] ==", "currently supported\") def test_ConfigureScan_onlyPst_basic(self, proxies): \"\"\" Test a successful PST-BF scan configuration \"\"\"", "proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState == ObsState.EMPTY # add receptors proxies.subarray[1].AddReceptors([4, 1, 3,", "== 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[9][0] == 6697 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[9][1] ==", "assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand == 4 assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[4] -", "all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership == 2 for i in [2, 4]]) # assert subarray_2_proxy.State()", "ObsState.READY, 15, 1) logging.info( \"First vcc obsState AFTER ConfigureScan = {}\". format(proxies.vcc[vcc_ids[0]].obsState) )", "with pytest.raises(tango.DevFailed) as df: # proxies.subarray[1].AddReceptors([5]) # time.sleep(1) # assert \"Invalid receptor ID\"", "VCCs, including states of frequency band capabilities assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand == 0", "proxies.fspSubarray[fsp_id].obsState == ObsState.READY assert proxies.fspSubarray[fsp_id].receptors == test_receptor_ids[0] assert proxies.fspSubarray[fsp_id].frequencyBand == band_index assert proxies.fspSubarray[fsp_id].frequencySliceID", "CBF subarray assert proxies.subarray[1].configID == \"band:5a, fsp1, 744 channels average factor 8\" assert", "True assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcNumBits == 8 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch == 5", "first for search window 1 of VCC belonging to receptor 10... assert proxies.vccTdc[proxies.receptor_to_vcc[4]", "proxies.fsp[fs_id].timingBeamWeights[rec_id - 1][index] == value except AssertionError as ae: raise ae except Exception", "# # assert fsp_2_proxies.subarray[1].band5Tuning[1] == 7.25 # # assert fsp_2_proxies.subarray[1].frequencyBandOffsetStream1 == 0 #", "assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream1 == 0 # assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream2 == 0", "1 of VCC belonging to receptor 1... assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].State() == DevState.ON", "tango from tango import DevState import pytest # SKA specific imports from ska_mid_cbf_mcs.commons.global_enum", "== 25 # TODO - re-enable and debug! # assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcDestinationAddress", "function mode to enum or edit attribute to accept string in FSP if", "ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae", "i in range(len(fsp[\"channel_averaging_map\"])): for j in range(len(fsp[\"channel_averaging_map\"][i])): assert proxies.fspSubarray[fsp_id].channelAveragingMap[i][j] == fsp[\"channel_averaging_map\"][i][j] for i", "# assert proxies.sw[1].tdcEnable == True # assert proxies.sw[1].tdcNumBits == 8 # assert proxies.sw[1].tdcPeriodBeforeEpoch", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[19][1] == 8 # assert fsp_1_proxies.subarray[1].outputLinkMap[0][0] == 0 # assert", "proxies.receptor_to_vcc[receptor_id] proxies.subarray[subarr_index].AddReceptors(input_receptors) proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[subarr_index].receptors[i] == j for i, j", "assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState == ObsState.EMPTY # add receptors proxies.subarray[1].AddReceptors([4, 1,", "= [1] vcc_index = proxies.receptor_to_vcc[test_receptor_ids[0]] logging.info(\"vcc_index = {}\".format(vcc_index)) vcc_band_proxies = proxies.vccBand[vcc_index - 1]", "False # add receptors proxies.subarray[1].AddReceptors([1, 3, 4]) time.sleep(1) assert proxies.subarray[1].receptors[0] == 1 assert", ") # check some configured attributes of CBF subarray frequency_band = input_config_dict[\"common\"][\"frequency_band\"] input_band_index", "f = open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) assert", "vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand == 4 assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[4] - 1]]", "for jj in range(num_fsp_IDs): logging.info( \"delayCoeff = {}\".format( aa[jj][\"delayCoeff\"]) ) try: # turn", "vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcEnable == True # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcNumBits == 8 #", "1.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 1.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 1.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 1.7", "{}\". format( proxies.vcc[vcc_index].frequencyBand)) ) assert proxies.vcc[vcc_index].configID == configuration[\"common\"][\"config_id\"] assert proxies.vcc[vcc_index].frequencyBand == band_index assert", "subarrays # FSP 2 assert proxies.fspSubarray[6].obsState == ObsState.READY assert all([proxies.fspSubarray[6].receptors[i] == j for", "fsp_1_proxies.subarray[1].outputLinkMap[1][1] == 8 # assert fsp_1_proxies.subarray[1].outputLinkMap[2][0] == 1488 # assert fsp_1_proxies.subarray[1].outputLinkMap[2][1] == 12", "for proxy in vcc_proxies: proxy.Init() fsp_1_proxies.subarray[1].Init() fsp_2_proxies.subarray[1].Init() fsp_3_proxies.subarray[1].Init() fsp_1_proxy.Init() fsp_2_proxy.Init() time.sleep(3) cbf_master_proxy.set_timeout_millis(60000) cbf_master_proxy.Init()", "for i in [2, 4]]) # assert subarray_2_proxy.State() == DevState.ON def test_RemoveAllReceptors(self, proxies):", "e # transition to obsState == SCANNING f2 = open(file_path + \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\",", "- 1].band5Tuning[0] == 5.85 # assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[1] == 7.25 # assert", "try: proxies.clean_proxies() if proxies.controller.State() == DevState.OFF: proxies.controller.Init() proxies.wait_timeout_dev([proxies.controller], DevState.STANDBY, 3, 1) proxies.controller.On() proxies.wait_timeout_dev([proxies.controller],", "= 1; logging.info( \"input_receptors = {}\".format(input_receptors) ) logging.info( \"config_file_name = {}\".format(config_file_name) ) num_receptors", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) assert proxies.subarray[1].obsState == ObsState.READY # create a delay model", "for i, j in zip(range(3), [1, 3, 4])]) # configure scan f =", "reception of delay models \"\"\" # Read delay model data from file f", "# check configured attributes of CBF subarray assert proxies.subarray[1].configID == \"sbi-mvp01-20200325-00001-science_A\" assert proxies.subarray[1].frequencyBand", "== 11905 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[16][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[17][0] ==", "proxy in fsp_1_function_mode_proxy] == [ # DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE # ] #", "currently only support for 1 receptor per fsp test_receptor_ids = [4, 1] #test_receptor_ids", "proxies.subarray[sub_id].AddReceptors(test_receptor_ids) proxies.wait_timeout_obs([proxies.subarray[sub_id]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[sub_id].receptors[i] == j for i, j in", "- 1].subarrayMembership == 1 assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[0] == 5.85 assert vcc_proxies[receptor_to_vcc[4] -", "all([proxies.vcc[i + 1].subarrayMembership == 0 for i in range(4)]) input_receptors = [1, 3,", "proxies.subarray[1].receptors == () # assert proxies.subarray[1].configID == 0 assert proxies.subarray[1].frequencyBand == 0 assert", "== 4 assert proxies.vcc[proxies.receptor_to_vcc[1]].frequencyBand == 4 for proxy in proxies.vccBand[proxies.receptor_to_vcc[4] - 1]: logging.info(\"VCC", "1 of VCC belonging to receptor 1... assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].State() == DevState.ON", "value in enumerate(receptor[\"receptorWeightsDetails\"][0][\"weights\"]): try: assert proxies.fsp[fs_id].timingBeamWeights[rec_id - 1][index] == value except AssertionError as", "proxies.subarray[1], sw_1_proxy, sw_2_proxy, vcc_proxies, vcc_band_proxies, vcc_tdc_proxies, fsp_1_proxy, fsp_2_proxy, fsp_1_function_mode_proxy, fsp_2_function_mode_proxy, fsp_3_proxies.subarray[1], tm_telstate_proxy ):", "i, j in zip(range(3), [1, 3, 4])]) assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for i", "\"\"\" Test the EndScan command \"\"\" try: # turn on Subarray if proxies.subarray[1].State()", "\"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) assert proxies.subarray[1].obsState == ObsState.READY #", "the reception of delay models \"\"\" # Read delay model data from file", "3, 4])]) assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for i in [1, 3, 4]]) assert", "ae except Exception as e: proxies.clean_proxies() raise e def test_Scan(self, proxies): \"\"\" Test", "# assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream2 == 0 # assert vcc_proxies[receptor_to_vcc[4] - 1].rfiFlaggingMask ==", "1][0].tdcDestinationAddress == ( # \"fizz\", \"buzz\", \"80\" # ) # # then for", "== configuration[\"common\"][\"config_id\"] assert proxies.subarray[sub_id].frequencyBand == band_index assert proxies.subarray[sub_id].obsState == ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i + 1]", "1400 assert fsp_1_proxies.subarray[1].outputLinkMap[0][0] == 1 assert fsp_1_proxies.subarray[1].outputLinkMap[0][1] == 0 assert fsp_1_proxies.subarray[1].outputLinkMap[1][0] == 201", "== 1 assert fsp_1_proxies.subarray[1].corrBandwidth == 0 assert fsp_1_proxies.subarray[1].integrationTime == 1400 assert fsp_1_proxies.subarray[1].outputLinkMap[0][0] ==", "try: assert proxies.fsp[fs_id].timingBeamWeights[rec_id - 1][index] == value except AssertionError as ae: raise ae", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 2.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 2.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 2.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2]", "== \"sbi-mvp01-20200325-00001-science_A\" assert proxies.subarray[1].frequencyBand == 0 # means 1 assert proxies.subarray[1].obsState.value == ObsState.READY.value", "1) assert proxies.subarray[1].obsState == ObsState.SCANNING time.sleep(10) assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 2.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] ==", "3 # assert fsp_3_proxies.subarray[1].receptors[1] == 1 # assert fsp_3_proxies.subarray[1].searchWindowID == 2 # assert", "8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[1][0] == 744 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[1][1] == 8", "window 2 of VCC belonging to receptor 10... # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].State()", "test_RemoveAllReceptors(self, proxies): \"\"\" Test RemoveAllReceptors command \"\"\" try: # turn on Subarray if", "1 proxies.subarray[1].AddReceptors([1, 3]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1]", "assert fsp_1_proxies.subarray[1].integrationTime == 1400 assert fsp_1_proxies.subarray[1].outputLinkMap[0][0] == 1 assert fsp_1_proxies.subarray[1].outputLinkMap[0][1] == 0 assert", "this has to be updated in FspPssSubarray # to read/write individual members searchBeam", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 1.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 1.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 1.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0]", "14137 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[19][1] == 0 # # then for FSP 3...", "check configured attributes of FSPs, including states of function mode capabilities assert fsp_1_proxy.functionMode", "for VCC belonging to receptor 10... assert vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership == 1 assert", "== 1 # remove remaining receptors proxies.subarray[1].RemoveReceptors([3]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert len(proxies.subarray[1].receptors)", "proxy in vcc_band_proxies[receptor_to_vcc[1] - 1]] == [ # DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] #", "[ DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ] # TODO - # assert [proxy.State() for", "works for fsps 1 and 2 assert proxies.fspSubarray[fsp_id].obsState == ObsState.READY assert proxies.fspSubarray[fsp_id].receptors ==", "searchBeam300[\"searchBeamID\"] == 300 assert searchBeam300[\"receptors\"][0] == 3 assert searchBeam300[\"outputEnable\"] == True assert searchBeam300[\"averagingInterval\"]", "2.4 proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1, 1) proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise", "all([proxies.subarray[1].receptors[i] == j for i, j in zip(range(3), [1, 3, 4])]) # configure", "assert sw_1_proxy.tdcEnable == True assert sw_1_proxy.tdcNumBits == 8 assert sw_1_proxy.tdcPeriodBeforeEpoch == 5 assert", "1][1].searchWindowTuning == 7000000000 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].tdcEnable == False assert fsp_3_proxies.subarray[1].receptors[0] == 3", "receptor 1... assert proxies.vcc[proxies.receptor_to_vcc[1]].subarrayMembership == 1 assert proxies.vcc[proxies.receptor_to_vcc[1]].band5Tuning[0] == 5.85 assert proxies.vcc[proxies.receptor_to_vcc[1]].band5Tuning[1] ==", "- when a receptor to be added is already in use by a", "proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.SCANNING assert proxies.fspSubarray[1].obsState == ObsState.SCANNING assert proxies.fspSubarray[3].obsState", "from ska_tango_base.base_device import _DEBUGGER_PORT @pytest.mark.usefixtures(\"proxies\", \"input_test_data\") class TestCbfSubarray: def test_AddRemoveReceptors_valid(self, proxies): \"\"\" Test", "values against input json @pytest.mark.skip(reason=\"test needs to be refactored\") def test_ConfigureScan_delayModel(self, proxies): \"\"\"", "- 1].frequencyBandOffsetStream1 == 0 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream2 == 0 assert vcc_proxies[receptor_to_vcc[1] -", "assert fsp_3_proxies.subarray[1].searchWindowID == 2 # assert fsp_3_proxies.subarray[1].searchBeamID[0] == 300 # assert fsp_3_proxies.subarray[1].searchBeamID[1] ==", "[proxy.State() for proxy in fsp_2_function_mode_proxy] == [ # DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE #", "== 3 assert proxies.subarray[1].receptors[2] == 4 # configure scan f = open(file_path +", "True assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcNumBits == 8 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch == 5", "vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].tdcEnable == False # # check configured attributes of FSPs, including", "proxies.fspSubarray[1].fspChannelOffset == 14880 assert proxies.fspSubarray[1].channelAveragingMap[0][0] == 0 assert proxies.fspSubarray[1].channelAveragingMap[0][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[1][0]", "assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].tdcEnable == False # check configured attributes of FSPs, including", "- this does not pass - to debug & fix #assert searchBeam0[\"searchBeamDestinationAddress\"] ==", "json_string = f2.read().replace(\"\\n\", \"\") input_scan_dict = json.loads(json_string) proxies.subarray[subarr_index].Scan(json_string) f2.close() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.SCANNING, 1, 1)", "Test invalid AddReceptors commands involving a single subarray: - when a receptor ID", "test_Abort_Restart(self, proxies): \"\"\" Test abort restart \"\"\" try: # turn on Subarray if", "Check obsStates BEFORE the EndScan() command assert proxies.subarray[subarr_index].obsState == ObsState.SCANNING assert proxies.vcc[vcc_ids[0]].obsState ==", "subarray_2_proxy.State() == DevState.OFF # # add some receptors to subarray 1 # proxies.subarray[1].AddReceptors([1,", "== [1, 3, 4, 2] assert proxies.vcc[proxies.receptor_to_vcc[2]].subarrayMembership == 1 # remove some receptors", "fsp_1_proxies.subarray[1].channelAveragingMap[5][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[6][0] == 4464 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[6][1]", "assert proxies.fspSubarray[fsp_id].obsState == ObsState.READY assert proxies.fspSubarray[fsp_id].receptors == test_receptor_ids[0] assert proxies.fspSubarray[fsp_id].frequencyBand == band_index assert", "int(receptor[\"receptor\"]) fs_id = receptor[\"receptorDelayDetails\"][0][\"fsid\"] for index, value in enumerate(receptor[\"receptorDelayDetails\"][0][\"delayCoeff\"]): try: assert proxies.fsp[fs_id].delayModel[rec_id -", "f.close() time.sleep(15) # check configured attributes of CBF subarray # def test_ConfigureScan_basic( #", "# assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[4] - 1]] == [ # DevState.DISABLE,", "# \"foo\", \"bar\", \"8080\" # ) # # then for search window 1", "- 1][0].tdcPeriodAfterEpoch == 25 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcDestinationAddress == ( # \"foo\",", "1][0].searchWindowTuning == 6000000000 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcEnable == True assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcNumBits", "not currently supported\") def test_ConfigureScan_onlyPst_basic_FSP_scan_parameters(self, proxies): \"\"\" Test a successful transmission of PST-BF", "8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[3][0] == 2232 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[3][1] == 8", "# first for FSP 1... (this is a CORR fsp device) assert proxies.fspSubarray[1].obsState", "in zip(range(len(test_receptor_ids)), test_receptor_ids)]) # configure scan f = open(file_path + \"/../data/Configure_TM-CSP_v2.json\") configuration =", "== [ # # DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE # # ] # #", "delay_model = json.loads(f.read().replace(\"\\n\", \"\")) f.close() aa = delay_model[\"delayModel\"][0][\"delayDetails\"][0][\"receptorDelayDetails\"] num_fsp_IDs = len(aa) for jj", "False # # check configured attributes of FSPs, including states of function mode", "proxies.subarray[1].RemoveReceptors([3]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert len(proxies.subarray[1].receptors) == 0 assert proxies.vcc[proxies.receptor_to_vcc[3]].subarrayMembership == 0", "3]]) assert proxies.subarray[1].obsState == ObsState.IDLE # TODO: fix this # try adding an", "already in use by a different subarray \"\"\" # for proxy in vcc_proxies:", "to fix #elif fsp[\"function_mode\"] == \"PST-BF\": # assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.SCANNING proxies.subarray[subarr_index].EndScan() proxies.wait_timeout_obs([proxies.subarray[subarr_index]],", "1 # check configured attributes of FSPs, including states of function mode capabilities", "fsp_2_proxies.subarray[1].channelAveragingMap[9][0] == 6697 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[9][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[10][0]", "1 of VCC belonging to receptor 1... # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].State() ==", "2.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 2.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 2.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 2.8", "j for i, j in zip(range(4), [4, 1, 3, 2])]) # configure scan", "HealthState from ska_tango_base.control_model import AdminMode, ObsState from ska_tango_base.base_device import _DEBUGGER_PORT @pytest.mark.usefixtures(\"proxies\", \"input_test_data\") class", "# frequency band capabilities logging.info( (\"proxies.vcc[vcc_index].frequencyBand = {}\". format( proxies.vcc[vcc_index].frequencyBand)) ) vcc_band_proxies =", "def test_ConfigureScan_basic( # self, # cbf_master_proxy, # proxies.subarray[1], # sw_1_proxy, # sw_2_proxy, #", "[1, 3]]) # assert all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership == 2 for i in [2,", "zip(range(len(test_receptor_ids)), test_receptor_ids)]) # configure scan f = open(file_path + \"/../data/Configure_TM-CSP_v2.json\") configuration = f.read().replace(\"\\n\",", "fsp_1_proxy.Init() fsp_2_proxy.Init() proxies.subarray[1].set_timeout_millis(60000) # since the command takes a while proxies.subarray[1].Init() time.sleep(3) cbf_master_proxy.set_timeout_millis(60000)", "check configured attributes of FSP subarray #TODO align IDs of fspSubarrays to fsp_id", "of the BSD-3-Clause license. # See LICENSE.txt for more info. \"\"\"Contain the tests", "proxies.subarray[1].obsState == ObsState.IDLE assert proxies.subarray[1].scanID == 0 assert proxies.fspSubarray[1].obsState == ObsState.IDLE assert proxies.fspSubarray[3].obsState", "searchBeam400[\"outputEnable\"] == True assert searchBeam400[\"averagingInterval\"] == 2 assert searchBeam400[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" proxies.subarray[1].GoToIdle() time.sleep(3)", "== ObsState.IDLE assert proxies.subarray[1].scanID == 0 assert proxies.fspSubarray[1].obsState == ObsState.IDLE assert proxies.fspSubarray[3].obsState ==", "log_msg = \"timeout_millis = {} \".format(timeout_millis) #logging.info(log_msg) #logging.info(\"start_time = {}\".format(time.time())) logging.info(\"start datetime =", "- 1].frequencyBandOffsetStream2 == 0 # assert vcc_proxies[receptor_to_vcc[1] - 1].rfiFlaggingMask == \"{}\" # #", "states assert proxies.subarray[1].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY", "assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].State() == DevState.ON assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].searchWindowTuning == 6000000000 assert", "fs_id = receptor[\"receptorWeightsDetails\"][0][\"fsid\"] for index, value in enumerate(receptor[\"receptorWeightsDetails\"][0][\"weights\"]): try: assert proxies.fsp[fs_id].timingBeamWeights[rec_id - 1][index]", "assert fsp_3_proxies.subarray[1].receptors[1] == 1 # assert fsp_3_proxies.subarray[1].searchWindowID == 2 # assert fsp_3_proxies.subarray[1].searchBeamID[0] ==", "receptor ID\" in str(df.value.args[0].desc) # try removing a receptor not assigned to subarray", "str(int(time.time())) for matrix in jones_matrix[\"jonesMatrix\"]: matrix[\"epoch\"] = epoch if matrix[\"destinationType\"] == \"fsp\": epoch", "proxies.clean_proxies() raise e @pytest.mark.skip(reason=\"pst not currently supported\") def test_ConfigureScan_onlyPst_basic_FSP_scan_parameters(self, proxies): \"\"\" Test a", "time.sleep(3) # check initial value of attributes of CBF subarray assert len(proxies.subarray[1].receptors) ==", "assert subarray_2_proxy.receptors == (2, 4) # assert all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership == 1 for", "== tango.DevState.OFF def test_band1( self, cbf_master_proxy, proxies.subarray[1], sw_1_proxy, sw_2_proxy, vcc_proxies, vcc_band_proxies, vcc_tdc_proxies, fsp_1_proxy,", "\"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 15, 1) # check configured attributes of CBF subarray", "in timing_beam_weights[\"beamWeights\"]: weights[\"epoch\"] = epoch epoch = str(int(epoch) + 10) # update delay", "(1, 3) # assert all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership == 1 for i in [1,", "assert fsp_2_proxies.subarray[1].channelAveragingMap[15][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[16][0] == 11905 # # assert", "proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert len(proxies.subarray[1].receptors) == 0 assert proxies.fspSubarray[1].obsState == ObsState.IDLE", "attributes of FSP subarrays # first for FSP 1... assert fsp_1_proxies.subarray[1].obsState == ObsState.READY", "== 2.4 proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1, 1) proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies()", "assert fsp_1_proxies.subarray[1].band5Tuning[1] == 7.25 # assert fsp_1_proxies.subarray[1].frequencyBandOffsetStream1 == 0 # assert fsp_1_proxies.subarray[1].frequencyBandOffsetStream2 ==", "proxies.sw[1].searchWindowTuning == 6000000000 # assert proxies.sw[1].tdcEnable == True # assert proxies.sw[1].tdcNumBits == 8", "end of scan, clear all private data #assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState", "# assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.READY proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae", "of VCC belonging to receptor 1... # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].State() == DevState.DISABLE", "searchBeam300[\"outputEnable\"] == True # assert searchBeam300[\"averagingInterval\"] == 4 # assert searchBeam300[\"searchBeamDestinationAddress\"] == \"10.05.1.1\"", "== 0 for proxy in vcc_proxies]) # assert proxies.subarray[1].State() == DevState.OFF # assert", "FspPssSubarray # to read/write individual members searchBeam = proxies.fspSubarray[3].searchBeams searchBeam0 = json.loads(searchBeam[0]) searchBeam1", "Exception as e: proxies.clean_proxies() raise e def test_Scan(self, proxies): \"\"\" Test the Scan", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 0.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 0.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 0.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5]", "10... # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].State() == DevState.DISABLE # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].searchWindowTuning", "except Exception as e: proxies.clean_proxies() raise e @pytest.mark.skip(reason=\"pst not currently supported\") def test_ConfigureScan_onlyPst_basic_FSP_scan_parameters(self,", "time.sleep(1) assert proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1] == 3 assert proxies.subarray[1].receptors[2] == 4", "+ \"/test_json/test_ConfigureScan_onlyPss_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() time.sleep(15) # check configured attributes of CBF subarray", "fsp_3_proxies.subarray[1], tm_telstate_proxy ): \"\"\" Test a minimal successful configuration \"\"\" for proxy in", "e: proxies.clean_proxies() raise e def test_ConfigureScan_minimal(self, proxies): try: sub_id = 1 #TODO currently", "self, cbf_master_proxy, proxies.subarray[1], sw_1_proxy, sw_2_proxy, vcc_proxies, vcc_band_proxies, vcc_tdc_proxies, fsp_1_proxy, fsp_2_proxy, fsp_1_function_mode_proxy, fsp_2_function_mode_proxy, fsp_1_proxies.subarray[1],", "delay model # Insert the epoch delay_model[\"delayModel\"][0][\"epoch\"] = str(int(time.time()) + 20) delay_model[\"delayModel\"][1][\"epoch\"] =", "assert fsp_1_proxies.subarray[1].channelAveragingMap[5][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[6][0] == 4464 # # assert", "# check configured attributes of search windows # # first for search window", "ObsState.EMPTY # # assert tm_telstate_proxy.visDestinationAddress == \"{}\" # assert tm_telstate_proxy.receivedOutputLinks == False #", "[ DevState.DISABLE, DevState.DISABLE, DevState.ON, DevState.DISABLE ] # check configured attributes of FSP subarrays", "frequency band capabilities # assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand == 4 # assert vcc_proxies[receptor_to_vcc[1]", "0 assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream2 == 0 assert vcc_proxies[receptor_to_vcc[4] - 1].rfiFlaggingMask == \"{}\"", "configurations or causing a fault within the Vcc device # for proxy in", "first for FSP 1... (this is a CORR fsp device) assert proxies.fspSubarray[1].obsState ==", "vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].searchWindowTuning == 7000000000 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].tdcEnable == False # and", "+ \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) assert proxies.subarray[1].obsState == ObsState.READY", "== j for i, j in zip(range(1), [10])]) # Clean Up proxies.clean_proxies() except", "\"sbi-mvp01-20200325-00001-science_A\" assert proxies.subarray[1].frequencyBand == 0 # means 1 assert proxies.subarray[1].obsState.value == ObsState.READY.value #", "\"input_test_data\") class TestCbfSubarray: def test_AddRemoveReceptors_valid(self, proxies): \"\"\" Test valid AddReceptors and RemoveReceptors commands", "== 8928 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[12][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[13][0] ==", "1.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 2.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 2.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 2.2", "for search window 1... # TODO - SearchWidow device test is disabled since", "== True assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcNumBits == 8 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch ==", "11161 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[15][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[16][0] == 11905", "of VCC belonging to receptor 1... assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].State() == DevState.DISABLE assert", "f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) assert proxies.subarray[1].obsState == ObsState.SCANNING time.sleep(10) for receptor in", "== 4 # assert fsp_1_proxies.subarray[1].band5Tuning[0] == 5.85 # assert fsp_1_proxies.subarray[1].band5Tuning[1] == 7.25 #", "\"8080\" # ) # then for search window 1 of VCC belonging to", "+ \"/../data/Configure_TM-CSP_v2.json\") configuration = f.read().replace(\"\\n\", \"\") f.close() proxies.subarray[sub_id].ConfigureScan(configuration) proxies.wait_timeout_obs([proxies.subarray[sub_id]], ObsState.READY, 15, 1) configuration", "proxies.wait_timeout_obs([proxies.vcc[i + 1] for i in range(4)], ObsState.READY, 1, 1) # check frequency", "test_receptor_ids = [4, 1] #test_receptor_ids = [1] vcc_index = proxies.receptor_to_vcc[test_receptor_ids[0]] logging.info(\"vcc_index = {}\".format(vcc_index))", "= [None for _ in range(num_receptors)] for receptor_id, ii in zip(input_receptors, range(num_receptors)): vcc_ids[ii]", "== 5952 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[8][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[9][0] ==", "# ] # # then for search window 2... # assert proxies.sw[2].State() ==", "receptor_to_vcc = dict([*map(int, pair.split(\":\"))] for pair in cbf_master_proxy.receptorToVcc) cbf_master_proxy.On() time.sleep(3) # check initial", "# assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch == 5 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch ==", "and of 'string' type # scan_index is an index into an array, therefore", "- this does not pass - to debug & fix #assert searchBeam1[\"searchBeamDestinationAddress\"] ==", "assert proxies.fspSubarray[1].outputLinkMap[1][0] == 744 assert proxies.fspSubarray[1].outputLinkMap[1][1] == 8 assert proxies.fspSubarray[1].outputLinkMap[2][0] == 1488 assert", "format(proxies.fspPstSubarray[subarr_index-1].obsState) ) # Check obsStates BEFORE the EndScan() command assert proxies.subarray[subarr_index].obsState == ObsState.SCANNING", "DevState.ON # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].searchWindowTuning == 6000000000 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcEnable", "ObsReset proxies.subarray[1].ObsReset() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].obsState == ObsState.IDLE assert proxies.subarray[1].scanID ==", "== 5.85 # # assert fsp_2_proxies.subarray[1].band5Tuning[1] == 7.25 # # assert fsp_2_proxies.subarray[1].frequencyBandOffsetStream1 ==", "fsp_2_proxies.subarray[1].Init() # fsp_3_proxies.subarray[1].Init() # fsp_1_proxy.Init() # fsp_2_proxy.Init() # proxies.subarray[1].set_timeout_millis(60000) # since the command", "fsp[\"function_mode\"] == \"PSS-BF\": function_mode = 2 elif fsp[\"function_mode\"] == \"PST-BF\": function_mode = 3", "states of frequency band capabilities assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand == 0 assert vcc_proxies[receptor_to_vcc[1]", "- 1][0].tdcPeriodAfterEpoch == 25 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcDestinationAddress == ( # \"fizz\",", "== j for i, j in zip(range(3), [1, 3, 4])]) assert proxies.fspSubarray[1].obsState ==", "1 for i in [1, 3]]) assert proxies.subarray[1].obsState == ObsState.IDLE # TODO: fix", "ObsState.IDLE # remove all receptors proxies.subarray[1].RemoveAllReceptors() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert len(proxies.subarray[1].receptors) ==", "elif fsp[\"function_mode\"] == \"PSS-BF\": assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.SCANNING # TODO: this check does", "in delay_model[\"delayModel\"]: if model[\"destinationType\"] == \"fsp\": for receptor in model[\"delayDetails\"]: rec_id = int(receptor[\"receptor\"])", "an error proxies.subarray[1].RemoveReceptors([2]) assert proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1] == 3 proxies.subarray[1].RemoveAllReceptors() proxies.wait_timeout_obs([proxies.subarray[1]],", "2.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 2.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 2.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 2.5", "DevState.ON # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].searchWindowTuning == 6000000000 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcEnable", "assert fsp_1_proxies.subarray[1].channelAveragingMap[6][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[7][0] == 5208 # # assert", "searchBeam300[\"receptors\"][0] == 3 # assert searchBeam300[\"outputEnable\"] == True # assert searchBeam300[\"averagingInterval\"] == 4", "logging.info(\"vcc_index = {}\".format( vcc_index )) assert len(proxies.subarray[1].receptors) == 0 assert proxies.subarray[1].configID == ''", "vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch == 25 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcDestinationAddress == ( \"fizz\", \"buzz\",", "\"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", ] # then for search window 2... assert sw_2_proxy.State() == DevState.DISABLE", "vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch == 25 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcDestinationAddress == ( #", "1, 1) # check initial value of attributes of CBF subarray assert len(proxies.subarray[1].receptors)", "DevState.ON # assert proxies.subarray[1].ObsState == ObsState.EMPTY # # assert tm_telstate_proxy.visDestinationAddress == \"{}\" #", "import _DEBUGGER_PORT @pytest.mark.usefixtures(\"proxies\", \"input_test_data\") class TestCbfSubarray: def test_AddRemoveReceptors_valid(self, proxies): \"\"\" Test valid AddReceptors", "0 # assert fsp_1_proxies.subarray[1].frequencyBandOffsetStream2 == 0 # assert fsp_1_proxies.subarray[1].frequencySliceID == 1 # assert", "- to debug & fix #assert searchBeam1[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" # check configured attributes", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 0.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 0.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 0.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2]", "proxies.fspSubarray[1].channelAveragingMap[2][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[3][0] == 2232 assert proxies.fspSubarray[1].channelAveragingMap[3][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[4][0]", "[proxies.fsp[i + 1] for i in range(4)]: if proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy],", "assert searchBeam400[\"outputEnable\"] == True assert searchBeam400[\"averagingInterval\"] == 2 assert searchBeam400[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" proxies.subarray[1].GoToIdle()", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 1.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 1.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 1.4 assert", "== ObsState.IDLE # TODO: fix this # try adding an invalid receptor ID", "== 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[11][0] == 8185 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[11][1] ==", "= json.loads(searchBeam[0]) searchBeam400 = json.loads(searchBeam[1]) assert searchBeam300[\"searchBeamID\"] == 300 assert searchBeam300[\"receptors\"][0] == 3", "[proxy.State() for proxy in proxies.vccBand[proxies.receptor_to_vcc[4] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON]", "within the Vcc device # for proxy in vcc_band_proxies: # logging.info(\"VCC proxy.State() =", "while proxies.subarray[1].Init() time.sleep(3) cbf_master_proxy.set_timeout_millis(60000) cbf_master_proxy.Init() time.sleep(60) # takes pretty long for CBF Master", "proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.IDLE assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.IDLE logging.info( \"First vcc obsState BEFORE ConfigureScan", "== 7.25 assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBandOffsetStream1 == 0 assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBandOffsetStream2 == 0 assert proxies.vcc[proxies.receptor_to_vcc[4]].rfiFlaggingMask ==", "ObsState.READY, 30, 1) assert proxies.subarray[1].obsState == ObsState.READY #create a Jones matrix f =", "in CbfSubarray, at end of scan, clear all private data #assert proxies.subarray[sub_id].frequencyBand ==", "vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand == 4 # assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand == 4 #", "proxy in fsp_2_function_mode_proxy] == [ # DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE # ] #", "test_ConfigureScan_onlyPst_basic(self, proxies): \"\"\" Test a successful PST-BF scan configuration \"\"\" try: # turn", "for fsp in input_config_dict[\"cbf\"][\"fsp\"]: if fsp[\"function_mode\"] == \"CORR\": assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.SCANNING elif", "proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcNumBits == 8 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch == 5 assert proxies.vccTdc[proxies.receptor_to_vcc[4]", "): \"\"\" Test a minimal successful configuration \"\"\" for proxy in vcc_proxies: proxy.Init()", "== 0 # # then for FSP 3... # assert fsp_3_proxies.subarray[1].receptors[0] == 3", "for proxy in proxies.vccBand[proxies.receptor_to_vcc[4] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] assert", "10... assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].State() == DevState.ON assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].searchWindowTuning == 6000000000", "tests; issue with VccBand devices either not reconfiguring in between # configurations or", "raise ae except Exception as e: proxies.clean_proxies() raise e ''' def test_ConfigureScan_onlyPss_basic( self,", "1.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 1.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 1.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 1.8", "receptors proxies.subarray[1].AddReceptors([4, 1, 3, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[1].receptors[i] == j", "assert proxies.subarray[1].configID == '' assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState.value == ObsState.IDLE.value #", "assert all([proxies.subarray[subarr_index].receptors[i] == j for i, j in zip(range(num_receptors), input_receptors)]) assert proxies.subarray[subarr_index].obsState ==", "fsp test_receptor_ids = [4, 1] #test_receptor_ids = [1] vcc_index = proxies.receptor_to_vcc[test_receptor_ids[0]] logging.info(\"vcc_index =", "assert fsp_1_proxies.subarray[1].frequencyBandOffsetStream2 == 0 # assert fsp_1_proxies.subarray[1].frequencySliceID == 1 # assert fsp_1_proxies.subarray[1].corrBandwidth ==", "command takes a while proxies.subarray[1].Init() time.sleep(3) cbf_master_proxy.set_timeout_millis(60000) cbf_master_proxy.Init() time.sleep(60) # takes pretty long", "of delay models \"\"\" # Read delay model data from file f =", "== 1.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 1.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 1.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] ==", "= str(int(time.time())) for model in delay_model[\"delayModel\"]: model[\"epoch\"] = epoch if model[\"destinationType\"] == \"fsp\":", "[[0, \"06-00-00-00-00-01\"]], \"outputPort\": [[0, 9000, 1], [8184, 9000, 1]]}).replace('\"',\"'\") # Clean Up proxies.clean_proxies()", "ObsState.SCANNING, 1, 1) # Note: scan_id is 1-based and of 'string' type #", "== 1 assert proxies.vcc[proxies.receptor_to_vcc[1]].band5Tuning[0] == 5.85 assert proxies.vcc[proxies.receptor_to_vcc[1]].band5Tuning[1] == 7.25 # check configured", "== 7.25 # # assert fsp_2_proxies.subarray[1].frequencyBandOffsetStream1 == 0 # # assert fsp_2_proxies.subarray[1].frequencyBandOffsetStream2 ==", "1) assert proxies.subarray[1].obsState == ObsState.EMPTY ############################# abort from IDLE ########################### # add receptors", "for FSP 3... # assert fsp_3_proxies.subarray[1].receptors[0] == 3 # assert fsp_3_proxies.subarray[1].receptors[1] == 1", "== DevState.ON # else: # assert vcc_band_proxies[i].State() == DevState.DISABLE # check configured attributes", "proxy in vcc_proxies: proxy.Init() fsp_3_proxies.subarray[1].Init() fsp_1_proxy.Init() fsp_2_proxy.Init() proxies.subarray[1].set_timeout_millis(60000) # since the command takes", "assert fsp_1_proxies.subarray[1].frequencyBandOffsetStream1 == 0 # assert fsp_1_proxies.subarray[1].frequencyBandOffsetStream2 == 0 # assert fsp_1_proxies.subarray[1].frequencySliceID ==", "value of attributes of CBF subarray vcc_index = proxies.receptor_to_vcc[4] logging.info(\"vcc_index = {}\".format( vcc_index", "1) assert all([proxies.subarray[1].receptors[i] == j for i, j in zip(range(3), [1, 3, 4])])", "ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY # ObsReset proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert", "assert vcc_proxies[receptor_to_vcc[1] - 1].rfiFlaggingMask == \"{}\" # # check configured attributes of search", "capabilities # assert fsp_1_proxy.functionMode == 1 # assert 1 in fsp_1_proxy.subarrayMembership # #", "== 1 assert proxies.subarray[1].receptors[1] == 3 assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for i in", "7.25 # assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream1 == 0 # assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream2", "update delay model proxies.tm.beamWeights = json.dumps(timing_beam_weights) time.sleep(1) for weights in timing_beam_weights[\"beamWeights\"]: for receptor", "ObsState.SCANNING assert proxies.fspSubarray[3].obsState == ObsState.SCANNING proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1, 1) assert proxies.subarray[1].obsState ==", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[14][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[15][0] == 11160 # #", "all([proxies.vcc[i + 1].subarrayMembership == 0 for i in range(4)]) # add some receptors", "# check initial value of attributes of CBF subarray # assert len(proxies.subarray[1].receptors) ==", "assert fsp_3_proxies.subarray[1].searchBeamID[0] == 300 # assert fsp_3_proxies.subarray[1].searchBeamID[1] == 400 # searchBeam = fsp_3_proxies.subarray[1].searchBeams", "1... assert sw_1_proxy.State() == DevState.ON assert sw_1_proxy.searchWindowTuning == 6000000000 assert sw_1_proxy.tdcEnable == True", "6000000000 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcEnable == True # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcNumBits", "3, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[1].receptors[i] == j for i, j", "proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY # ObsReset proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert len(proxies.subarray[1].receptors) ==", "1 logging.info( \"proxies.fspCorrSubarray[subarr_index-1].obsState = {}\". format(proxies.fspCorrSubarray[subarr_index-1].obsState) ) logging.info( \"proxies.fspPssSubarray[subarr_index-1].obsState = {}\". format(proxies.fspPssSubarray[subarr_index-1].obsState) )", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 1.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 1.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 1.5 assert", "= json.loads(searchBeam[1]) # assert searchBeam300[\"searchBeamID\"] == 300 # assert searchBeam300[\"receptors\"][0] == 3 #", "attribute 'searchBeams'); # this has to be updated in FspPssSubarray # to read/write", "assert proxies.fspSubarray[3].searchBeamID[0] == 300 assert proxies.fspSubarray[3].searchBeamID[1] == 400 # TODO: currently searchBeams is", "for index, value in enumerate(receptor[\"receptorWeightsDetails\"][0][\"weights\"]): try: assert proxies.fsp[fs_id].timingBeamWeights[rec_id - 1][index] == value except", "{}\".format(proxies.sw[1].State())) # print(\"proxies.sw[2].State() = {}\".format(proxies.sw[2].State())) # assert proxies.sw[1].State() == DevState.ON # assert proxies.sw[1].searchWindowTuning", "# DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE # ] # # assert [proxy.State() for proxy", "assert fsp_1_proxies.subarray[1].channelAveragingMap[4][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[5][0] == 3720 # # assert", "############################# abort from READY ########################### # add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]],", "mode capabilities assert proxies.fsp[1].functionMode == 1 assert 1 in proxies.fsp[1].subarrayMembership assert [proxy.State() for", "open(file_path + \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) assert proxies.subarray[1].obsState ==", "fs_id-1, proxies.vcc[vcc_id].jonesMatrix[fs_id-1]) ) raise ae except Exception as e: raise e proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]],", "model proxies.tm.delayModel = json.dumps(delay_model) time.sleep(1) for jj in range(4): logging.info((\" proxies.vcc[{}].receptorID = {}\".", "(this is a CORR fsp device) assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[1].receptors ==", "assert proxies.fspSubarray[1].outputLinkMap[2][1] == 12 assert proxies.fspSubarray[1].outputLinkMap[3][0] == 2232 assert proxies.fspSubarray[1].outputLinkMap[3][1] == 16 assert", "proxies.sw[1].tdcEnable == True # assert proxies.sw[1].tdcNumBits == 8 # assert proxies.sw[1].tdcPeriodBeforeEpoch == 5", "raise ae except Exception as e: raise e time.sleep(10) for receptor in jones_matrix[\"jonesMatrix\"][0][\"matrixDetails\"]:", "fsp[\"function_mode\"] == \"CORR\": function_mode = 1 elif fsp[\"function_mode\"] == \"PSS-BF\": function_mode = 2", "assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].State() == DevState.ON # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].searchWindowTuning == 6000000000", "# assert subarray_2_proxy.receptors == (2, 4) # assert all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership == 1", "attributes of FSP subarrays # first for FSP 1... (this is a CORR", "DevState.DISABLE, DevState.DISABLE, DevState.ON] assert [proxy.State() for proxy in proxies.vccBand[proxies.receptor_to_vcc[1] - 1]] == [", "ObsState.READY elif fsp[\"function_mode\"] == \"PSS-BF\": assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.READY # TODO: this check", "f = open(file_path + \"/test_json/test_ConfigureScan_onlyPss_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() time.sleep(15) # check configured attributes", "in [1, 3]]) # assert all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership == 2 for i in", "# assert sw_1_proxy.tdcNumBits == 8 # assert sw_1_proxy.tdcPeriodBeforeEpoch == 5 # assert sw_1_proxy.tdcPeriodAfterEpoch", "== '' # TODO in CbfSubarray, at end of scan, clear all private", "True assert searchBeam300[\"averagingInterval\"] == 4 assert searchBeam300[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" assert searchBeam400[\"searchBeamID\"] == 400", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[15][0] == 11160 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[15][1] == 8 # #", "assert fsp_2_proxies.subarray[1].channelAveragingMap[6][0] == 4465 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[6][1] == 0 # # assert", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 2.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 3.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 3.1 assert", "proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[3].obsState == ObsState.READY # send", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[13][0] == 9673 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[13][1] == 0 # #", "proxies.subarray[1].AddReceptors([1, 3, 4]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[1].receptors[i] == j for i,", "Matrix proxies.tm.jonesMatrix = json.dumps(jones_matrix) time.sleep(1) for matrix in jones_matrix[\"jonesMatrix\"]: if matrix[\"destinationType\"] == \"fsp\":", "= int(receptor[\"receptor\"]) fs_id = receptor[\"receptorWeightsDetails\"][0][\"fsid\"] for index, value in enumerate(receptor[\"receptorWeightsDetails\"][0][\"weights\"]): try: assert proxies.fsp[fs_id].timingBeamWeights[rec_id", "the configured attributes of VCCs # first for VCC belonging to receptor 2...", "\"outputMac\": [[0, \"06-00-00-00-00-01\"]], \"outputPort\": [[0, 9000, 1], [8184, 9000, 1]]}).replace('\"',\"'\") # Clean Up", "7000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].tdcEnable == False # and lastly for search window", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[6][0] == 4464 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[6][1] == 8 # #", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[10][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[11][0] == 8184 # #", "# turn on Subarray if proxies.subarray[sub_id].State() != DevState.ON: proxies.subarray[sub_id].On() proxies.wait_timeout_dev([proxies.subarray[sub_id]], DevState.ON, 3, 1)", "assert fsp_2_proxies.subarray[1].channelAveragingMap[18][0] == 13393 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[18][1] == 0 # # assert", "1) # check configured attributes of CBF subarray assert proxies.subarray[1].configID == \"band:5a, fsp1,", "# sw_2_proxy, # vcc_proxies, # vcc_band_proxies, # vcc_tdc_proxies, # fsp_1_proxy, # fsp_2_proxy, #", "\"\"\" proxies.subarray[1].loggingLevel = LoggingLevel.DEBUG try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON:", "then for search window 2... assert sw_2_proxy.State() == DevState.DISABLE assert sw_2_proxy.searchWindowTuning == 7000000000", "assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE ############################# abort from READY ###########################", "== True assert searchBeam1[\"averaging_interval\"] == 2 # TODO - this does not pass", "raise ae except Exception as e: raise e # transition to obsState ==", "== 2.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 3.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 3.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] ==", "vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream2 == 0 # assert vcc_proxies[receptor_to_vcc[1] - 1].rfiFlaggingMask == \"{}\" #", "attributes of FSPs, including states of function mode capabilities assert fsp_1_proxy.functionMode == 1", "window 1 of VCC belonging to receptor 10... assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].State() ==", "== 1 # assert 1 in fsp_1_proxy.subarrayMembership # # assert 1 in fsp_2_proxy.subarrayMembership", "# -*- coding: utf-8 -*- # # This file is part of the", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 3.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 3.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 3.2 assert", "self, cbf_master_proxy, proxies.subarray[1], sw_1_proxy, sw_2_proxy, vcc_proxies, vcc_band_proxies, vcc_tdc_proxies, fsp_1_proxy, fsp_2_proxy, fsp_1_function_mode_proxy, fsp_2_function_mode_proxy, fsp_3_proxies.subarray[1],", "receptor 10... assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].State() == DevState.ON assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].searchWindowTuning ==", "@pytest.mark.skip(reason=\"Since there's only a single subarray, this test is currently broken.\") def test_AddRemoveReceptors_invalid_multiple(self,", "4465 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[6][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[7][0] == 5209", "{}\".format( vcc_index )) assert len(proxies.subarray[1].receptors) == 0 assert proxies.subarray[1].configID == '' # TODO", "assert fsp_1_proxy.functionMode == 1 # assert 1 in fsp_1_proxy.subarrayMembership # # assert 1", "cbf_controller_proxy.On() # time.sleep(3) # # receptor list should be empty right after initialization", "== ObsState.READY # Clean Up proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae", "assert all([proxies.vcc[i + 1].subarrayMembership == 0 for i in range(4)]) # add some", "# create a delay model # Insert the epoch delay_model[\"delayModel\"][0][\"epoch\"] = str(int(time.time()) +", "= open(file_path + \"/../data/Scan2_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) assert proxies.subarray[1].obsState", "attributes of VCC search windows # first for search window 1 of VCC", "of FSP subarrays # first for FSP 3 ... (this is a PSS", "#proxies.vcc[0].receptorID assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 1.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 1.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 1.3", "fsp_1_proxies.subarray[1].channelAveragingMap[1][0] == 744 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[1][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[2][0]", "vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership == 1 # assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[0] == 5.85 #", "format(proxies.vcc[vcc_ids[0]].obsState) ) # check some configured attributes of CBF subarray frequency_band = input_config_dict[\"common\"][\"frequency_band\"]", "logging.info( \"config_file_name = {}\".format(config_file_name) ) num_receptors = len(input_receptors) vcc_ids = [None for _", "means 5a assert proxies.subarray[1].obsState == ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i + 1] for i in range(4)],", "proxies.fspSubarray[1].channelAveragingMap[3][0] == 2232 assert proxies.fspSubarray[1].channelAveragingMap[3][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[4][0] == 2976 assert proxies.fspSubarray[1].outputLinkMap[0][0]", "2] assert proxies.vcc[proxies.receptor_to_vcc[2]].subarrayMembership == 1 # remove some receptors proxies.subarray[1].RemoveReceptors([2, 1, 4]) time.sleep(1)", "band capabilities assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBand == 4 assert [proxy.State() for proxy in proxies.vccBand[proxies.receptor_to_vcc[2] -", "= [4, 1] #test_receptor_ids = [1] vcc_index = proxies.receptor_to_vcc[test_receptor_ids[0]] logging.info(\"vcc_index = {}\".format(vcc_index)) vcc_band_proxies", "open(file_path + \"/../data/jonesmatrix_fsp.json\") jones_matrix = json.loads(f.read().replace(\"\\n\", \"\")) epoch = str(int(time.time())) for matrix in", "imports import sys import os import time from datetime import datetime import json", "== \"band:5a, fsp1, 744 channels average factor 8\" # assert proxies.subarray[1].frequencyBand == 4", "proxies.fspSubarray[1].outputLinkMap[1][1] == 8 assert proxies.fspSubarray[1].outputLinkMap[2][0] == 1488 assert proxies.fspSubarray[1].outputLinkMap[2][1] == 12 assert proxies.fspSubarray[1].outputLinkMap[3][0]", "== 7000000000 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].tdcEnable == False # # check configured", "scan # f = open(file_path + \"/test_json/test_ConfigureScan_basic.json\") # proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) # f.close() #", "# then for search window 2... # assert sw_2_proxy.State() == DevState.DISABLE # assert", "ObsState.EMPTY # assert fsp_1_proxies.subarray[1].receptors == 4 # assert fsp_1_proxies.subarray[1].frequencyBand == 4 # assert", "open(file_path + \"/../data/Scan2_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) assert proxies.subarray[1].obsState ==", "test is disabled since the same # functionality is implemented by the VccSearchWindow", "proxies.subarray[1].frequencyBand == 0 # means 1 assert proxies.subarray[1].obsState.value == ObsState.READY.value # check frequency", "1][1].tdcEnable == False # check configured attributes of FSPs, including states of function", "to debug & fix #assert searchBeam1[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" # check configured attributes of", "subarray \"\"\" # for proxy in vcc_proxies: # proxy.Init() # proxies.subarray[1].set_timeout_millis(60000) # subarray_2_proxy.set_timeout_millis(60000)", "rec_id = int(receptor[\"receptor\"]) fs_id = receptor[\"receptorWeightsDetails\"][0][\"fsid\"] for index, value in enumerate(receptor[\"receptorWeightsDetails\"][0][\"weights\"]): try: assert", "in fsp_2_function_mode_proxy] == [ # # DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE # # ]", "1, 1) assert [proxies.subarray[1].receptors[i] for i in range(3)] == input_receptors assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership ==", "assert fsp_1_proxies.subarray[1].outputLinkMap[1][1] == 8 # assert fsp_1_proxies.subarray[1].outputLinkMap[2][0] == 1488 # assert fsp_1_proxies.subarray[1].outputLinkMap[2][1] ==", "Test abort reset \"\"\" try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON:", "== 2.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 2.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 2.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] ==", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[2][0] == 1488 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[2][1] == 8 # #", "add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) # configure scan", "belonging to receptor 10... # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].State() == DevState.ON # assert", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) assert proxies.subarray[1].obsState == ObsState.READY #create a Jones matrix f", "fsp_1_proxies.subarray[1].channelAveragingMap[9][0] == 6696 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[9][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[10][0]", "f = open(file_path + \"/../data/Configure_TM-CSP_v2.json\") configuration = f.read().replace(\"\\n\", \"\") f.close() proxies.subarray[sub_id].ConfigureScan(configuration) proxies.wait_timeout_obs([proxies.subarray[sub_id]], ObsState.READY,", "[1, 3, 4])]) # configure scan f = open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\"))", "= json.loads(f.read().replace(\"\\n\", \"\")) epoch = str(int(time.time())) for model in delay_model[\"delayModel\"]: model[\"epoch\"] = epoch", "ObsState.EMPTY assert len(proxies.subarray[1].receptors) == 0 assert proxies.fspSubarray[1].obsState == ObsState.IDLE assert proxies.fspSubarray[3].obsState == ObsState.IDLE", "AdminMode, ObsState from ska_tango_base.base_device import _DEBUGGER_PORT @pytest.mark.usefixtures(\"proxies\", \"input_test_data\") class TestCbfSubarray: def test_AddRemoveReceptors_valid(self, proxies):", "fsp[\"function_mode\"] == \"PSS-BF\": assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.READY # TODO: this check does not", "proxies.vcc[proxies.receptor_to_vcc[1]].subarrayMembership == 1 assert proxies.vcc[proxies.receptor_to_vcc[1]].band5Tuning[0] == 5.85 assert proxies.vcc[proxies.receptor_to_vcc[1]].band5Tuning[1] == 7.25 # check", "# assert searchBeam400[\"receptors\"][0] == 1 # assert searchBeam400[\"outputEnable\"] == True # assert searchBeam400[\"averagingInterval\"]", "0 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[0][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[1][0] == 744", "[proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[4] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON]", "then for search window 2 of VCC belonging to receptor 10... assert vcc_tdc_proxies[receptor_to_vcc[4]", "2.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 2.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 2.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 2.7", "for search window 2... # assert proxies.sw[2].State() == DevState.DISABLE # assert proxies.sw[2].searchWindowTuning ==", "Test a successful scan configuration \"\"\" proxies.subarray[1].loggingLevel = LoggingLevel.DEBUG try: # turn on", "fsp_2_proxy.Init() # proxies.subarray[1].set_timeout_millis(60000) # since the command takes a while # proxies.subarray[1].Init() #", "assert proxies.subarray[1].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY assert", "matrix[\"matrixDetails\"]: rec_id = int(receptor[\"receptor\"]) fs_id = receptor[\"receptorMatrix\"][0][\"fsid\"] for index, value in enumerate(receptor[\"receptorMatrix\"][0][\"matrix\"]): try:", "== False # # add receptors # proxies.subarray[1].RemoveAllReceptors() # proxies.subarray[1].AddReceptors([1, 3, 4]) #", "0.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 0.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 0.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 0.4", "use by a different subarray \"\"\" # for proxy in vcc_proxies: # proxy.Init()", "[proxies.subarray[1].receptors[i] for i in range(4)] == [1, 3, 4, 2] assert proxies.vcc[proxies.receptor_to_vcc[2]].subarrayMembership ==", "int(receptor[\"receptor\"]) fs_id = receptor[\"receptorWeightsDetails\"][0][\"fsid\"] for index, value in enumerate(receptor[\"receptorWeightsDetails\"][0][\"weights\"]): try: assert proxies.fsp[fs_id].timingBeamWeights[rec_id -", "proxies.subarray[1].AddReceptors([1, 3, 4]) time.sleep(1) assert proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1] == 3 assert", "assert proxies.subarray[1].obsState == ObsState.ABORTED assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[3].obsState == ObsState.READY assert", "1].subarrayMembership == 1 assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[0] == 5.85 assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[1]", "to receptor 1... assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].State() == DevState.ON assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].searchWindowTuning", "command f2 = open(file_path + \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1)", "time.sleep(15) # # check configured attributes of CBF subarray # assert proxies.subarray[1].configID ==", "ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY # abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert", "try: assert proxies.fsp[fs_id].delayModel[rec_id - 1][index] == value except AssertionError as ae: raise ae", "import os import time from datetime import datetime import json import logging #", "def test_ConfigureScan_onlyPst_basic(self, proxies): \"\"\" Test a successful PST-BF scan configuration \"\"\" try: #", "== 7.25 assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream1 == 0 assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream2 ==", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[5][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[6][0] == 4465 #", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[9][0] == 6696 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[9][1] == 8 # #", "4 # # assert fsp_2_proxies.subarray[1].band5Tuning[0] == 5.85 # # assert fsp_2_proxies.subarray[1].band5Tuning[1] == 7.25", "check initial value of attributes of CBF subarray assert len(proxies.subarray[1].receptors) == 0 assert", "fsp_1_proxies.subarray[1].outputLinkMap[1][0] == 744 # assert fsp_1_proxies.subarray[1].outputLinkMap[1][1] == 8 # assert fsp_1_proxies.subarray[1].outputLinkMap[2][0] == 1488", "debug! # assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcDestinationAddress == ( # \"foo\", \"bar\", \"8080\" #", "# Read delay model data from file f = open(file_path + \"/../data/delaymodel.json\") delay_model", "== 7441 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[10][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[11][0] ==", "1) assert proxies.subarray[1].obsState == ObsState.ABORTED # ObsReset proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert", "- 1][0].tdcDestinationAddress == ( \"foo\", \"bar\", \"8080\" ) # then for search window", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 2.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 2.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 2.6 assert", "VCC belonging to receptor 10... assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].State() == DevState.DISABLE assert vcc_tdc_proxies[receptor_to_vcc[4]", "DevState.OFF # assert subarray_2_proxy.State() == DevState.OFF # # add some receptors to subarray", "proxies.subarray[1].ConfigureScan(f1.read().replace(\"\\n\", \"\")) f1.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) # check initial states assert proxies.subarray[1].obsState", "# # then for search window 1 of VCC belonging to receptor 1...", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 4.4 time.sleep(10) assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 0.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 0.2", "assert fsp_1_proxies.subarray[1].channelAveragingMap[4][0] == 2976 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[4][1] == 8 # # assert", "[1] vcc_index = proxies.receptor_to_vcc[test_receptor_ids[0]] logging.info(\"vcc_index = {}\".format(vcc_index)) vcc_band_proxies = proxies.vccBand[vcc_index - 1] #", "sw_2_proxy.tdcEnable == False # # check configured attributes of VCC search windows #", "search window 1 of VCC belonging to receptor 1... # assert vcc_tdc_proxies[receptor_to_vcc[1] -", "ObsState.READY proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae except Exception as e:", "the Scan command f2 = open(file_path + \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING,", "e: proxies.clean_proxies() raise e #TODO refactor to verify delay model values against input", "== 0.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 0.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 1.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] ==", "\"06-00-00-00-00-01\"]], \"outputPort\": [[0, 9000, 1], [8184, 9000, 1]]}).replace('\"',\"'\") # Clean Up proxies.clean_proxies() except", "DevState.DISABLE ] # TODO - # assert [proxy.State() for proxy in fsp_2_function_mode_proxy] ==", "== \"CORR\": assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.SCANNING elif fsp[\"function_mode\"] == \"PSS-BF\": assert proxies.fspPssSubarray[subarr_index-1].obsState ==", "= {}\". format(proxies.fspPssSubarray[subarr_index-1].obsState) ) logging.info( \"proxies.fspPstSubarray[subarr_index-1].obsState = {}\". format(proxies.fspPstSubarray[subarr_index-1].obsState) ) # Check obsStates", "assert fsp_1_proxies.subarray[1].channelAveragingMap[5][0] == 3720 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[5][1] == 8 # # assert", "assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcEnable == True assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcNumBits == 8 assert", "+ \"/test_json/data_model_confluence.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() time.sleep(15) # check configured attributes of CBF subarray", "including states of frequency band capabilities # assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand == 4", "proxy.Init() fsp_3_proxies.subarray[1].Init() fsp_1_proxy.Init() fsp_2_proxy.Init() proxies.subarray[1].set_timeout_millis(60000) # since the command takes a while proxies.subarray[1].Init()", "fsp_id in conftest; currently works for fsps 1 and 2 assert proxies.fspSubarray[fsp_id].obsState ==", "states of function mode capabilities assert proxies.fsp[2].State() == DevState.ON assert proxies.fsp[2].functionMode == 3", "proxies.subarray[sub_id].obsState == ObsState.EMPTY # add receptors proxies.subarray[sub_id].AddReceptors(test_receptor_ids) proxies.wait_timeout_obs([proxies.subarray[sub_id]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[sub_id].receptors[i]", "1][0].tdcNumBits == 8 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch == 5 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch", "1.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 1.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 2.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 2.1", "assert proxies.fsp[fs_id].delayModel[rec_id - 1][index] == value except AssertionError as ae: raise ae except", "400 searchBeam = fsp_3_proxies.subarray[1].searchBeams searchBeam300 = json.loads(searchBeam[0]) searchBeam400 = json.loads(searchBeam[1]) assert searchBeam300[\"searchBeamID\"] ==", "for receptor in jones_matrix[\"jonesMatrix\"][0][\"matrixDetails\"]: for frequency_slice in receptor[\"receptorMatrix\"]: for index, value in enumerate(frequency_slice[\"matrix\"]):", "assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].State() == DevState.DISABLE assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].searchWindowTuning == 7000000000 assert", "band of VCCs, including states of frequency band capabilities assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand", "# TODO: currently searchBeams is stored by the device # as a json", "assert fsp_2_proxies.subarray[1].channelAveragingMap[8][0] == 5953 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[8][1] == 0 # # assert", "[ DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ] # check configured attributes of FSP subarray", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[19][0] == 14136 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[19][1] == 8 # assert", "# TODO - re-enable and debug! # assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcDestinationAddress == (", "= {}\".format(datetime.now())) if proxies.debug_device_is_on: port = proxies.subarray[1].DebugDevice() try: proxies.clean_proxies() if proxies.controller.State() == DevState.OFF:", "receptor_to_vcc = dict([*map(int, pair.split(\":\"))] for pair in # cbf_master_proxy.receptorToVcc) # cbf_master_proxy.On() # time.sleep(60)", "i in range(4)]) input_receptors = [1, 3, 4] # add some receptors proxies.subarray[1].AddReceptors(input_receptors)", "== False # # check configured attributes of VCC search windows # #", "def test_Scan(self, proxies): \"\"\" Test the Scan command \"\"\" try: # turn on", "\"fsp\": for receptor in model[\"delayDetails\"]: rec_id = int(receptor[\"receptor\"]) fs_id = receptor[\"receptorDelayDetails\"][0][\"fsid\"] for index,", "# assert searchBeam300[\"searchBeamID\"] == 300 # assert searchBeam300[\"receptors\"][0] == 3 # assert searchBeam300[\"outputEnable\"]", "try removing a receptor not assigned to subarray 1 # doing this doesn't", "= str(int(epoch) + 10) # update Jones Matrix proxies.tm.jonesMatrix = json.dumps(jones_matrix) time.sleep(1) for", "- 1][1].searchWindowTuning == 7000000000 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].tdcEnable == False assert fsp_3_proxies.subarray[1].receptors[0] ==", "assert proxies.fspSubarray[fsp_id].channelAveragingMap[i][j] == fsp[\"channel_averaging_map\"][i][j] for i in range(len(fsp[\"output_link_map\"])): for j in range(len(fsp[\"output_link_map\"][i])): assert", "except AssertionError as ae: proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise", "assert proxies.subarray[1].obsState == ObsState.READY # create a delay model # Insert the epoch", "# check configured attributes of VCC search windows # # first for search", "# assert 1 in fsp_2_proxy.subarrayMembership # assert [proxy.State() for proxy in fsp_1_function_mode_proxy] ==", "# add more receptors... proxies.subarray[1].AddReceptors([2]) time.sleep(1) assert [proxies.subarray[1].receptors[i] for i in range(4)] ==", "initialize # receptor_to_vcc = dict([*map(int, pair.split(\":\"))] for pair in # cbf_controller_proxy.receptorToVcc) # cbf_controller_proxy.On()", "to receptor 10... assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].State() == DevState.ON assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].searchWindowTuning", "- 1].frequencyBandOffsetStream2 == 0 # assert vcc_proxies[receptor_to_vcc[4] - 1].rfiFlaggingMask == \"{}\" # #", "more receptors... proxies.subarray[1].AddReceptors([2]) time.sleep(1) assert [proxies.subarray[1].receptors[i] for i in range(4)] == [1, 3,", "== 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[17][0] == 12648 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[17][1] ==", "proxies.subarray[1].receptors == () # assert subarray_2_proxy.receptors == () # assert all([proxy.subarrayMembership == 0", "to be updated in FspPssSubarray # to read/write individual members searchBeam = proxies.fspSubarray[3].searchBeams", "cbf_controller_proxy.set_timeout_millis(60000) # cbf_controller_proxy.Init() # time.sleep(60) # takes pretty long for CBF controller to", "#TODO align IDs of fspSubarrays to fsp_id in conftest; currently works for fsps", "raise e #TODO: fix; currently tests break if multiple scan configurations are tested", "25 # TODO - re-enable and debug! # assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcDestinationAddress ==", "time.sleep(1) for model in delay_model[\"delayModel\"]: if model[\"destinationType\"] == \"fsp\": for receptor in model[\"delayDetails\"]:", "DevState.OFF # # add some receptors to subarray 1 # proxies.subarray[1].AddReceptors([1, 3]) #", "proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE ############################# abort from SCANNING ########################### # add receptors proxies.subarray[1].AddReceptors([1, 3,", "in str(df.value.args[0].desc) # assert subarray_2_proxy.receptors == (2, 4) # assert all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership", "== 3.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 4.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 4.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] ==", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[6][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[7][0] == 5208 #", "proxies.fspSubarray[1].channelAveragingMap[0][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[1][0] == 744 assert proxies.fspSubarray[1].channelAveragingMap[1][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[2][0]", "receptor 1... assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].State() == DevState.ON assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].searchWindowTuning ==", "Exception as e: proxies.clean_proxies() raise e def test_Abort_Reset(self, proxies): \"\"\" Test abort reset", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[0][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[1][0] == 744 # #", "input_receptors = [1, 3, 4] # add some receptors proxies.subarray[1].AddReceptors(input_receptors) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1,", "# proxies.subarray[1].set_timeout_millis(60000) # subarray_2_proxy.set_timeout_millis(60000) # proxies.subarray[1].Init() # subarray_2_proxy.Init() # time.sleep(3) # cbf_controller_proxy.set_timeout_millis(60000) #", "== 4 # # configure scan # f = open(file_path + \"/test_json/test_ConfigureScan_basic.json\") #", "proxies.fsp2FunctionMode, proxies.fsp3FunctionMode, proxies.fsp4FunctionMode] for fsp in configuration[\"cbf\"][\"fsp\"]: fsp_id = fsp[\"fsp_id\"] logging.info(\"{}\".format(fsp_id)) #TODO add", "1489 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[2][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[3][0] == 2233", "between # configurations or causing a fault within the Vcc device # for", "subarray assert proxies.subarray[1].configID == \"band:5a, fsp1, 744 channels average factor 8\" assert proxies.subarray[1].frequencyBand", "receptor 10... assert proxies.vcc[proxies.receptor_to_vcc[4]].subarrayMembership == 1 assert proxies.vcc[proxies.receptor_to_vcc[4]].band5Tuning[0] == 5.85 assert proxies.vcc[proxies.receptor_to_vcc[4]].band5Tuning[1] ==", "1].frequencyBandOffsetStream1 == 0 # assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream2 == 0 # assert vcc_proxies[receptor_to_vcc[4]", "744 assert proxies.fspSubarray[1].channelAveragingMap[1][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[2][0] == 1488 assert proxies.fspSubarray[1].channelAveragingMap[2][1] == 8", "13393 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[18][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[19][0] == 14137", "0 # assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream2 == 0 # assert vcc_proxies[receptor_to_vcc[1] - 1].rfiFlaggingMask", "assert 1 in proxies.fsp[2].subarrayMembership assert [proxy.State() for proxy in proxies.fsp2FunctionMode] == [ DevState.DISABLE,", "proxies.clean_proxies() # turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.ON, 3,", "== ObsState.READY assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.READY for fsp in input_config_dict[\"cbf\"][\"fsp\"]: if fsp[\"function_mode\"] ==", "] # # then for search window 2... # assert proxies.sw[2].State() == DevState.DISABLE", "= {}\". format(proxies.fspCorrSubarray[subarr_index-1].obsState) ) logging.info( \"proxies.fspPssSubarray[subarr_index-1].obsState = {}\". format(proxies.fspPssSubarray[subarr_index-1].obsState) ) logging.info( \"proxies.fspPstSubarray[subarr_index-1].obsState =", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 2.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 2.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 3.0 assert", "== 10416 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[14][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[15][0] ==", "== ObsState.SCANNING assert proxies.vcc[vcc_ids[num_receptors-1]].obsState == ObsState.SCANNING for fsp in input_config_dict[\"cbf\"][\"fsp\"]: if fsp[\"function_mode\"] ==", "model[\"destinationType\"] == \"fsp\": for receptor in model[\"delayDetails\"]: rec_id = int(receptor[\"receptor\"]) fs_id = receptor[\"receptorDelayDetails\"][0][\"fsid\"]", "== True assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcNumBits == 8 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch ==", "assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].State() == DevState.ON assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].searchWindowTuning == 6000000000 assert", "assert fsp_1_proxies.subarray[1].receptors == 4 # assert fsp_1_proxies.subarray[1].frequencyBand == 4 # assert fsp_1_proxies.subarray[1].band5Tuning[0] ==", "of FSPs, including states of function mode capabilities assert proxies.fsp[1].functionMode == 1 assert", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[12][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[13][0] == 9673 # #", "- 1][0].tdcPeriodBeforeEpoch == 5 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch == 25 assert vcc_tdc_proxies[receptor_to_vcc[4] -", "(\"Vcc, receptor 1, ObsState = {}\". format(proxies.vcc[proxies.receptor_to_vcc[1]].ObsState)) ) #proxies.vcc[0].receptorID assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 1.1", "model in delay_model[\"delayModel\"]: model[\"epoch\"] = epoch if model[\"destinationType\"] == \"fsp\": epoch = str(int(epoch)", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[19][1] == 8 # assert fsp_1_proxies.subarray[1].outputLinkMap[0][0] == 0 # assert fsp_1_proxies.subarray[1].outputLinkMap[0][1]", "== [ DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ] # assert [proxy.State() for proxy in", "update timing beam weights from tm emulator f = open(file_path + \"/../data/timingbeamweights.json\") timing_beam_weights", "# add some receptors proxies.subarray[1].AddReceptors([1, 3, 4]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[1].receptors[i]", "vcc_proxies: # proxy.Init() # proxies.subarray[1].set_timeout_millis(60000) # subarray_2_proxy.set_timeout_millis(60000) # proxies.subarray[1].Init() # subarray_2_proxy.Init() # time.sleep(3)", "FSP subarrays # first for FSP 3 ... (this is a PSS fsp", "proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) # check initial value of", "supported\") def test_ConfigureScan_onlyPst_basic(self, proxies): \"\"\" Test a successful PST-BF scan configuration \"\"\" try:", "assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBand == 4 assert proxies.vcc[proxies.receptor_to_vcc[1]].frequencyBand == 4 for proxy in proxies.vccBand[proxies.receptor_to_vcc[4] -", "proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1] == 3 assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for i", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 1.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 1.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 1.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5]", "== \"fsp\": for receptor in model[\"delayDetails\"]: rec_id = int(receptor[\"receptor\"]) fs_id = receptor[\"receptorDelayDetails\"][0][\"fsid\"] for", "assert proxies.fspSubarray[1].outputLinkMap[0][1] == 4 assert proxies.fspSubarray[1].outputLinkMap[1][0] == 744 assert proxies.fspSubarray[1].outputLinkMap[1][1] == 8 assert", "in fsp_2_proxy.subarrayMembership # assert [proxy.State() for proxy in fsp_1_function_mode_proxy] == [ # DevState.ON,", "3, 1) except AssertionError as ae: proxies.clean_proxies() raise ae except Exception as e:", "time.sleep(10) for receptor in jones_matrix[\"jonesMatrix\"][0][\"matrixDetails\"]: for frequency_slice in receptor[\"receptorMatrix\"]: for index, value in", "assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY # abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED,", "0 for i in range(4)]) input_receptors = [1, 3, 4] # add some", "vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].searchWindowTuning == 7000000000 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].tdcEnable == False #", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 2.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 2.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 2.5 assert", "# then for VCC belonging to receptor 1... assert proxies.vcc[proxies.receptor_to_vcc[1]].subarrayMembership == 1 assert", "import datetime import json import logging # Path file_path = os.path.dirname(os.path.abspath(__file__)) # Tango", "fsp_2_proxies.subarray[1].channelAveragingMap[9][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[10][0] == 7441 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[10][1]", "== 2.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 2.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 2.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] ==", "ObsReset proxies.subarray[1].ObsReset() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].obsState == ObsState.IDLE assert all([proxies.subarray[1].receptors[i] ==", "assert len(proxies.subarray[1].receptors) == 0 assert all([proxies.vcc[i + 1].subarrayMembership == 0 for i in", "cbf_master_proxy.On() time.sleep(3) # check initial value of attributes of CBF subarray # assert", "assert sw_1_proxy.tdcNumBits == 8 # assert sw_1_proxy.tdcPeriodBeforeEpoch == 5 # assert sw_1_proxy.tdcPeriodAfterEpoch ==", "proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].State() == DevState.DISABLE assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].searchWindowTuning == 7000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[1]", "proxies.subarray[1].frequencyBand == 4 assert proxies.subarray[1].obsState == ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i + 1] for i in", "function_mode = 4 assert proxies.fsp[fsp_id].functionMode == function_mode assert sub_id in proxies.fsp[fsp_id].subarrayMembership assert [proxy.State()", "# cbf_controller_proxy.set_timeout_millis(60000) # cbf_controller_proxy.Init() # time.sleep(60) # takes pretty long for CBF controller", "# first for VCC belonging to receptor 10... # assert vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership", "== ObsState.EMPTY # add receptors proxies.subarray[sub_id].AddReceptors(test_receptor_ids) proxies.wait_timeout_obs([proxies.subarray[sub_id]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[sub_id].receptors[i] ==", "2 elif fsp[\"function_mode\"] == \"PST-BF\": function_mode = 3 elif fsp[\"function_mode\"] == \"VLBI\": function_mode", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 2.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 2.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 2.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1]", "not pass, to fix #elif fsp[\"function_mode\"] == \"PST-BF\": # assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.SCANNING", "assert vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership == 1 # then for VCC belonging to receptor", "proxies.wait_timeout_obs([proxies.subarray[sub_id]], ObsState.READY, 15, 1) configuration = json.loads(configuration) band_index = freq_band_dict()[configuration[\"common\"][\"frequency_band\"]] # check configured", "search windows # # first for search window 1 of VCC belonging to", "# f = open(file_path + \"/test_json/test_ConfigureScan_basic.json\") # proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) # f.close() # time.sleep(15)", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[4][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[5][0] == 3721 #", "proxy.Init() # fsp_1_proxies.subarray[1].Init() # fsp_2_proxies.subarray[1].Init() # fsp_3_proxies.subarray[1].Init() # fsp_1_proxy.Init() # fsp_2_proxy.Init() # proxies.subarray[1].set_timeout_millis(60000)", "== 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[12][0] == 8929 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[12][1] ==", "3, 4]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[1].receptors[i] == j for i, j", "proxies.fspSubarray[1].channelAveragingMap[1][0] == 744 assert proxies.fspSubarray[1].channelAveragingMap[1][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[2][0] == 1488 assert proxies.fspSubarray[1].channelAveragingMap[2][1]", "== 4.4 time.sleep(10) assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 0.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 0.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2]", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].obsState == ObsState.IDLE assert all([proxies.subarray[1].receptors[i] == j for", "1)): # assert vcc_band_proxies[i].State() == DevState.ON # else: # assert vcc_band_proxies[i].State() == DevState.DISABLE", "# assert fsp_2_proxies.subarray[1].band5Tuning[1] == 7.25 # # assert fsp_2_proxies.subarray[1].frequencyBandOffsetStream1 == 0 # #", "belonging to receptor 1... # assert vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership == 1 # assert", "abort from READY ########################### # add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE,", "add receptors proxies.subarray[sub_id].AddReceptors(test_receptor_ids) proxies.wait_timeout_obs([proxies.subarray[sub_id]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[sub_id].receptors[i] == j for i,", "to read/write individual members searchBeam = proxies.fspSubarray[3].searchBeams searchBeam0 = json.loads(searchBeam[0]) searchBeam1 = json.loads(searchBeam[1])", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[5][0] == 3721 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[5][1] == 0 #", "belonging to receptor 1... assert vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership == 1 assert vcc_proxies[receptor_to_vcc[1] -", "DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] assert [proxy.State() for proxy in proxies.vccBand[proxies.receptor_to_vcc[1] - 1]] ==", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[16][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[17][0] == 12648 # #", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[4][0] == 2977 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[4][1] == 0 # #", "15, 1) logging.info( \"First vcc obsState AFTER ConfigureScan = {}\". format(proxies.vcc[vcc_ids[0]].obsState) ) #", "1][0].searchWindowTuning == 6000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcEnable == True assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcNumBits", "proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcDestinationAddress == ( # \"fizz\", \"buzz\", \"80\" # ) # then", "@pytest.mark.usefixtures(\"proxies\", \"input_test_data\") class TestCbfSubarray: def test_AddRemoveReceptors_valid(self, proxies): \"\"\" Test valid AddReceptors and RemoveReceptors", "time.sleep(3) # assert proxies.subarray[1].state() == tango.DevState.OFFequency band capabilities assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand ==", "# See LICENSE.txt for more info. \"\"\"Contain the tests for the CbfSubarray.\"\"\" #", "1, 1) assert len(proxies.subarray[1].receptors) == 0 assert proxies.vcc[proxies.receptor_to_vcc[3]].subarrayMembership == 0 assert proxies.subarray[1].obsState ==", "# TODO in CbfSubarray, at end of scan, clear all private data #assert", "== 0 assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBandOffsetStream2 == 0 assert proxies.vcc[proxies.receptor_to_vcc[2]].rfiFlaggingMask == \"{}\" # check configured", "of fspSubarrays to fsp_id in conftest; currently works for fsps 1 and 2", "2... # assert sw_2_proxy.State() == DevState.DISABLE # assert sw_2_proxy.searchWindowTuning == 7000000000 # assert", "for proxy in [proxies.vcc[i + 1] for i in range(4)]: if proxy.State() ==", "i in [1, 3, 4]]) assert proxies.subarray[1].obsState == ObsState.IDLE # remove all receptors", "\"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", # ] # # then for search window 2... # assert sw_2_proxy.State()", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[9][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[10][0] == 7440 #", "as e: proxies.clean_proxies() raise e #TODO: fix; currently tests break if multiple scan", "by the VccSearchWindow device; # to be decide which one to keep. #", "VCC belonging to receptor 1... assert vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership == 1 assert vcc_proxies[receptor_to_vcc[1]", "vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcDestinationAddress == ( \"foo\", \"bar\", \"8080\" ) # then for search", "e: proxies.clean_proxies() raise e def test_AddRemoveReceptors_invalid_single(self, proxies): \"\"\" Test invalid AddReceptors commands involving", "# then for search window 2... assert sw_2_proxy.State() == DevState.DISABLE assert sw_2_proxy.searchWindowTuning ==", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 1.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 1.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 2.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2]", "after initialization # assert proxies.subarray[1].receptors == () # assert subarray_2_proxy.receptors == () #", "== ObsState.IDLE proxies.subarray[1].RemoveAllReceptors() time.sleep(3) assert proxies.subarray[1].state() == tango.DevState.OFF def test_band1( self, cbf_master_proxy, proxies.subarray[1],", "== 5.85 assert proxies.vcc[proxies.receptor_to_vcc[4]].band5Tuning[1] == 7.25 assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBandOffsetStream1 == 0 assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBandOffsetStream2 ==", "8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[12][0] == 8928 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[12][1] == 8", "1 # then for VCC belonging to receptor 1... assert vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership", "f2 = open(file_path + \"/../data/Scan2_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) assert", "fsp_1_proxies.subarray[1].channelAveragingMap[6][0] == 4464 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[6][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[7][0]", "0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[6][0] == 4465 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[6][1] == 0", "i, j in zip(range(len(test_receptor_ids)), test_receptor_ids)]) # configure scan f = open(file_path + \"/../data/Configure_TM-CSP_v2.json\")", "Test a successful PST-BF scan configuration \"\"\" try: # turn on Subarray if", "os.path.dirname(os.path.abspath(__file__)) # Tango imports import tango from tango import DevState import pytest #", "frequency band of VCCs, including states of frequency band capabilities # assert vcc_proxies[receptor_to_vcc[4]", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 1.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 1.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 1.8 assert", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) assert proxies.subarray[1].obsState == ObsState.SCANNING assert proxies.subarray[1].scanID == 2 assert", "fsp_2_proxies.subarray[1].channelAveragingMap[0][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[1][0] == 745 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[1][1]", "against input json @pytest.mark.skip(reason=\"test needs to be refactored\") def test_ConfigureScan_delayModel(self, proxies): \"\"\" Test", "belonging to receptor 1... # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].State() == DevState.DISABLE # assert", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[6][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[7][0] == 5209 #", "# assert proxies.subarray[1].receptors == () # assert proxies.subarray[1].configID == 0 assert proxies.subarray[1].frequencyBand ==", "proxies.subarray[1].obsState.value == ObsState.IDLE.value # assert tm_telstate_proxy.visDestinationAddress == \"{}\" assert tm_telstate_proxy.receivedOutputLinks == False #", "receptor[\"receptorMatrix\"][0][\"fsid\"] for index, value in enumerate(receptor[\"receptorMatrix\"][0][\"matrix\"]): try: assert proxies.fsp[fs_id].jonesMatrix[rec_id - 1][index] == value", "proxies.debug_device_is_on: port = proxies.subarray[1].DebugDevice() try: proxies.clean_proxies() if proxies.controller.State() == DevState.OFF: proxies.controller.Init() proxies.wait_timeout_dev([proxies.controller], DevState.STANDBY,", "takes pretty long for CBF Master to initialize # tm_telstate_proxy.Init() # time.sleep(1) #", "proxies.subarray[1].AddReceptors([1, 3]) # time.sleep(1) # assert proxies.subarray[1].receptors == (1, 3) # assert all([vcc_proxies[receptor_to_vcc[i]", "Test a successful transmission of PST-BF parameters to FSP \"\"\" try: # turn", "1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY # Input test data: input_receptors = input_test_data[0]", "rest of the configured attributes of VCCs # first for VCC belonging to", "matrices from tm emulator f = open(file_path + \"/../data/jonesmatrix_fsp.json\") jones_matrix = json.loads(f.read().replace(\"\\n\", \"\"))", "== 4 # configure scan f = open(file_path + \"/test_json/data_model_confluence.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close()", "== ObsState.READY assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[3].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState ==", "# assert searchBeam400[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" # proxies.subarray[1].GoToIdle() # time.sleep(3) # assert proxies.subarray[1].obsState ==", "\"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) # check scanID on VCC", "first for VCC belonging to receptor 10... # assert vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership ==", "+ \"/test_json/test_ConfigureScan_basic.json\") # proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) # f.close() # time.sleep(15) # # check configured", "belonging to receptor 1... assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].State() == DevState.DISABLE assert proxies.vccTdc[proxies.receptor_to_vcc[1] -", "== j for i, j in zip(range(3), [1, 3, 4])]) # configure scan", "# assert fsp_1_proxies.subarray[1].obsState == ObsState.EMPTY # assert fsp_1_proxies.subarray[1].receptors == 4 # assert fsp_1_proxies.subarray[1].frequencyBand", "delay_model[\"delayModel\"][1][\"epoch\"] = \"0\" delay_model[\"delayModel\"][2][\"epoch\"] = str(int(time.time()) + 10) # update delay model proxies.tm.delayModel", "== ObsState.SCANNING assert proxies.subarray[1].scanID == 2 assert proxies.fspSubarray[1].obsState == ObsState.SCANNING assert proxies.fspSubarray[3].obsState ==", "# configure scan f = open(file_path + \"/test_json/test_ConfigureScan_onlyPss_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() time.sleep(15) #", "== False # # check configured attributes of FSPs, including states of function", "= [proxies.fsp1FunctionMode, proxies.fsp2FunctionMode, proxies.fsp3FunctionMode, proxies.fsp4FunctionMode] for fsp in configuration[\"cbf\"][\"fsp\"]: fsp_id = fsp[\"fsp_id\"] logging.info(\"{}\".format(fsp_id))", "# \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", # ] # # then for search window 2...", "\"proxies.fspPstSubarray[subarr_index-1].obsState = {}\". format(proxies.fspPstSubarray[subarr_index-1].obsState) ) # Check obsStates BEFORE the EndScan() command assert", "sw_1_proxy.searchWindowTuning == 6000000000 assert sw_1_proxy.tdcEnable == True assert sw_1_proxy.tdcNumBits == 8 assert sw_1_proxy.tdcPeriodBeforeEpoch", "fsp_3_proxies.subarray[1].searchWindowID == 2 # assert fsp_3_proxies.subarray[1].searchBeamID[0] == 300 # assert fsp_3_proxies.subarray[1].searchBeamID[1] == 400", "ObsState.READY # Clean Up proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae except", "remove all receptors proxies.subarray[1].RemoveAllReceptors() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert len(proxies.subarray[1].receptors) == 0 assert", "= \"0\" delay_model[\"delayModel\"][2][\"epoch\"] = str(int(time.time()) + 10) # update delay model proxies.tm.delayModel =", "== 5 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch == 25 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcDestinationAddress ==", "search window 1... assert sw_1_proxy.State() == DevState.ON assert sw_1_proxy.searchWindowTuning == 6000000000 assert sw_1_proxy.tdcEnable", "proxies.subarray[1].receptors[1] == 3 assert proxies.subarray[1].receptors[2] == 4 # configure scan f = open(file_path", "0 assert proxies.fspSubarray[1].outputLinkMap[0][1] == 4 assert proxies.fspSubarray[1].outputLinkMap[1][0] == 744 assert proxies.fspSubarray[1].outputLinkMap[1][1] == 8", "receptor[\"receptorWeightsDetails\"][0][\"fsid\"] for index, value in enumerate(receptor[\"receptorWeightsDetails\"][0][\"weights\"]): try: assert proxies.fsp[fs_id].timingBeamWeights[rec_id - 1][index] == value", "1 assert 1 in fsp_1_proxy.subarrayMembership # assert 1 in fsp_2_proxy.subarrayMembership assert [proxy.State() for", "4 # assert fsp_1_proxies.subarray[1].frequencyBand == 4 # assert fsp_1_proxies.subarray[1].band5Tuning[0] == 5.85 # assert", "5 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch == 25 # TODO - re-enable and debug!", "currently tests break if multiple scan configurations are tested def test_ConfigureScan_basic(self, proxies): \"\"\"", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 2.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 2.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 2.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5]", "1) for proxy in [proxies.vcc[i + 1] for i in range(4)]: if proxy.State()", "TODO - SearchWidow device test is disabled since the same # functionality is", "ObsState.READY, 30, 1) # check initial states assert proxies.subarray[1].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState", "\"{}\" # assert tm_telstate_proxy.receivedOutputLinks == False # # add receptors # proxies.subarray[1].RemoveAllReceptors() #", "1]] == [ # DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # assert [proxy.State() for proxy", "transition to obsState == SCANNING f2 = open(file_path + \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close()", "# assert proxies.subarray[1].receptors == () # assert subarray_2_proxy.receptors == () # assert all([proxy.subarrayMembership", "add receptors proxies.subarray[1].RemoveAllReceptors() proxies.subarray[1].AddReceptors([1, 3, 4]) time.sleep(1) assert proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1]", "searchBeam300[\"receptors\"][0] == 3 assert searchBeam300[\"outputEnable\"] == True assert searchBeam300[\"averagingInterval\"] == 4 assert searchBeam300[\"searchBeamDestinationAddress\"]", "proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].obsState == ObsState.IDLE #", "# check initial value of attributes of CBF subarray assert len(proxies.subarray[sub_id].receptors) == 0", "== ObsState.READY # ObsReset proxies.subarray[1].ObsReset() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].obsState == ObsState.IDLE", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[17][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[18][0] == 13392 #", "1 in fsp_2_proxy.subarrayMembership assert [proxy.State() for proxy in fsp_1_function_mode_proxy] == [ DevState.ON, DevState.DISABLE,", "of function mode capabilities assert proxies.fsp[1].functionMode == 1 assert 1 in proxies.fsp[1].subarrayMembership assert", "= {}\".format( vcc_index )) assert len(proxies.subarray[1].receptors) == 0 assert proxies.subarray[1].configID == '' #", "sys import os import time from datetime import datetime import json import logging", "remove some receptors proxies.subarray[1].RemoveReceptors([2, 1, 4]) time.sleep(1) assert proxies.subarray[1].receptors == ([3]) assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership", "# transition to obsState=SCANNING f2 = open(file_path + \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]],", "ObsState.READY, 15, 1) # check configured attributes of CBF subarray assert proxies.subarray[1].configID ==", "# This file is part of the csp-lmc-prototype project # # # #", "len(proxies.subarray[1].receptors) == 0 assert proxies.subarray[1].configID == '' # TODO in CbfSubarray, at end", "currently supported\") def test_ConfigureScan_onlyPst_basic_FSP_scan_parameters(self, proxies): \"\"\" Test a successful transmission of PST-BF parameters", "proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE ############################# abort from SCANNING ########################### #", "1) assert proxies.subarray[1].obsState == ObsState.SCANNING time.sleep(10) for receptor in jones_matrix[\"jonesMatrix\"][2][\"matrixDetails\"]: for frequency_slice in", "4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) # configure scan f = open(file_path +", "on Subarray # assert proxies.subarray[1].state()==DevState.OFF # proxies.subarray[1].On() # time.sleep(10) # # check initial", "assert searchBeam300[\"receptors\"][0] == 3 # assert searchBeam300[\"outputEnable\"] == True # assert searchBeam300[\"averagingInterval\"] ==", "def test_RemoveAllReceptors(self, proxies): \"\"\" Test RemoveAllReceptors command \"\"\" try: # turn on Subarray", "vcc_band_proxies[i].State() == DevState.DISABLE # check configured attributes of FSPs, including states of function", "model[\"destinationType\"] == \"fsp\": epoch = str(int(epoch) + 10) # update delay model proxies.tm.delayModel", "devices either not reconfiguring in between # configurations or causing a fault within", "vcc_proxies[receptor_to_vcc[4] - 1].rfiFlaggingMask == \"{}\" # then for VCC belonging to receptor 1...", "proxies.clean_proxies() raise e def test_EndScan(self, proxies, input_test_data): \"\"\" Test the EndScan command \"\"\"", "\"fsp\": for receptor in matrix[\"matrixDetails\"]: rec_id = int(receptor[\"receptor\"]) fs_id = receptor[\"receptorMatrix\"][0][\"fsid\"] for index,", "proxy in vcc_proxies: # proxy.Init() # fsp_1_proxies.subarray[1].Init() # fsp_2_proxies.subarray[1].Init() # fsp_3_proxies.subarray[1].Init() # fsp_1_proxy.Init()", "0 # # assert fsp_2_proxies.subarray[1].integrationTime == 1400 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[0][0] == 1", "range(4)] == [1, 3, 4, 2] assert proxies.vcc[proxies.receptor_to_vcc[2]].subarrayMembership == 1 # remove some", "pass, to fix #elif fsp[\"function_mode\"] == \"PST-BF\": # assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.SCANNING proxies.subarray[subarr_index].EndScan()", "assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch == 5 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch == 25 assert", "attribute to accept string in FSP if fsp[\"function_mode\"] == \"CORR\": function_mode = 1", "0 assert fsp_1_proxies.subarray[1].frequencySliceID == 1 assert fsp_1_proxies.subarray[1].corrBandwidth == 0 assert fsp_1_proxies.subarray[1].integrationTime == 1400", "\"\"\" Test a minimal successful configuration \"\"\" for proxy in vcc_proxies: proxy.Init() fsp_3_proxies.subarray[1].Init()", "proxies.subarray[subarr_index].obsState == ObsState.SCANNING assert proxies.vcc[vcc_ids[0]].obsState == ObsState.SCANNING assert proxies.vcc[vcc_ids[num_receptors-1]].obsState == ObsState.SCANNING for fsp", "Check fsp obsState BEFORE scan configuration: assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.IDLE assert proxies.fspPssSubarray[subarr_index-1].obsState ==", "right after initialization assert len(proxies.subarray[1].receptors) == 0 assert all([proxies.vcc[i + 1].subarrayMembership == 0", "assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY # abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState", "1][1].tdcEnable == False assert fsp_3_proxies.subarray[1].receptors[0] == 3 assert fsp_3_proxies.subarray[1].receptors[1] == 1 assert fsp_3_proxies.subarray[1].searchWindowID", "0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[10][0] == 7441 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[10][1] == 0", "scan, clear all private data #assert proxies.subarray[sub_id].frequencyBand == 0 assert proxies.subarray[sub_id].obsState == ObsState.EMPTY", "== DevState.OFF # assert subarray_2_proxy.State() == DevState.OFF # # add some receptors to", "== ObsState.READY # create a delay model # Insert the epoch delay_model[\"delayModel\"][0][\"epoch\"] =", "== ObsState.READY assert proxies.vcc[vcc_ids[0]].obsState == ObsState.READY assert proxies.vcc[vcc_ids[num_receptors -1]].obsState == ObsState.READY assert proxies.fspCorrSubarray[subarr_index-1].obsState", "2 assert fsp_3_proxies.subarray[1].searchBeamID[0] == 300 assert fsp_3_proxies.subarray[1].searchBeamID[1] == 400 searchBeam = fsp_3_proxies.subarray[1].searchBeams searchBeam300", "4 # assert fsp_1_proxies.subarray[1].band5Tuning[0] == 5.85 # assert fsp_1_proxies.subarray[1].band5Tuning[1] == 7.25 # assert", "3.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 3.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 3.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 3.7", "j in zip(range(1), [10])]) # Clean Up proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies()", "to fix #elif fsp[\"function_mode\"] == \"PST-BF\": # assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.READY proxies.clean_proxies() except", "first for search window 1 of VCC belonging to receptor 10... assert vcc_tdc_proxies[receptor_to_vcc[4]", "then for search window 1 of VCC belonging to receptor 1... assert proxies.vccTdc[proxies.receptor_to_vcc[1]", "in fsp_1_proxy.subarrayMembership # # assert 1 in fsp_2_proxy.subarrayMembership # assert [proxy.State() for proxy", "DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ] # TODO - # assert [proxy.State() for proxy", "4.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 4.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 4.4 time.sleep(10) assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] ==", "for proxy in proxies.vccBand[proxies.receptor_to_vcc[1] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] #", "for i in range(4)] == [1, 3, 4, 2] assert proxies.vcc[proxies.receptor_to_vcc[2]].subarrayMembership == 1", "1 assert proxies.vcc[proxies.receptor_to_vcc[4]].band5Tuning[0] == 5.85 assert proxies.vcc[proxies.receptor_to_vcc[4]].band5Tuning[1] == 7.25 assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBandOffsetStream1 == 0", "vcc_proxies]) # assert proxies.subarray[1].State() == DevState.OFF # assert subarray_2_proxy.State() == DevState.OFF # #", "1][0].tdcEnable == True assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcNumBits == 8 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch", "[1, 2, 4]]) assert proxies.vcc[proxies.receptor_to_vcc[3]].subarrayMembership == 1 # remove remaining receptors proxies.subarray[1].RemoveReceptors([3]) proxies.wait_timeout_obs([proxies.subarray[1]],", "== 300 # assert fsp_3_proxies.subarray[1].searchBeamID[1] == 400 # searchBeam = fsp_3_proxies.subarray[1].searchBeams # searchBeam300", "else: # assert vcc_band_proxies[i].State() == DevState.DISABLE # check configured attributes of FSPs, including", "PSS fsp device) assert proxies.fspSubarray[3].receptors[0] == 3 assert proxies.fspSubarray[3].receptors[1] == 1 assert proxies.fspSubarray[3].searchWindowID", "assert fsp_2_proxies.subarray[1].channelAveragingMap[1][0] == 745 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[1][1] == 0 # # assert", "proxies.subarray[1].obsState == ObsState.ABORTED assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[3].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState", "assert proxies.subarray[1].obsState == ObsState.SCANNING assert proxies.subarray[1].scanID == 2 assert proxies.fspSubarray[1].obsState == ObsState.SCANNING assert", "# # This file is part of the csp-lmc-prototype project # # #", "assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.IDLE assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.IDLE assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.IDLE logging.info(", "# assert vcc_proxies[receptor_to_vcc[1] - 1].rfiFlaggingMask == \"{}\" # # check configured attributes of", "ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY # ObsReset proxies.subarray[1].ObsReset() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[1][0] == 744 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[1][1] == 8 # #", "assert fsp_3_proxies.subarray[1].receptors[0] == 3 assert fsp_3_proxies.subarray[1].receptors[1] == 1 assert fsp_3_proxies.subarray[1].searchWindowID == 2 assert", "# assert fsp_3_proxies.subarray[1].receptors[1] == 1 # assert fsp_3_proxies.subarray[1].searchWindowID == 2 # assert fsp_3_proxies.subarray[1].searchBeamID[0]", "freq_band_dict()[configuration[\"common\"][\"frequency_band\"]] # check configured attributes of CBF subarray assert sub_id == int(configuration[\"common\"][\"subarray_id\"]) assert", "as ae: proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e #TODO:", "1].frequencyBandOffsetStream2 == 0 # assert vcc_proxies[receptor_to_vcc[1] - 1].rfiFlaggingMask == \"{}\" # # check", "2 assert proxies.fspSubarray[6].obsState == ObsState.READY assert all([proxies.fspSubarray[6].receptors[i] == j for i, j in", "incorrect Jones matrix entry: epoch {}, VCC {}, i = {}, jonesMatrix[{}] =", "proxies.vcc[vcc_index].frequencyBand == band_index assert proxies.vcc[vcc_index].subarrayMembership == sub_id #TODO fix these tests; issue with", "proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.READY, 15, 1) logging.info( \"First vcc obsState AFTER ConfigureScan = {}\". format(proxies.vcc[vcc_ids[0]].obsState)", "turn on Subarray if proxies.subarray[sub_id].State() != DevState.ON: proxies.subarray[sub_id].On() proxies.wait_timeout_dev([proxies.subarray[sub_id]], DevState.ON, 3, 1) for", "add receptors # proxies.subarray[1].RemoveAllReceptors() # proxies.subarray[1].AddReceptors([1, 3, 4]) # time.sleep(1) # assert proxies.subarray[1].receptors[0]", "band capabilities logging.info( (\"proxies.vcc[vcc_index].frequencyBand = {}\". format( proxies.vcc[vcc_index].frequencyBand)) ) vcc_band_proxies = proxies.vccBand[vcc_index -", "0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[12][0] == 8929 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[12][1] == 0", "vcc obsState BEFORE ConfigureScan = {}\". format(proxies.vcc[vcc_ids[0]].obsState) ) f = open(file_path + config_file_name)", "window 2... assert sw_2_proxy.State() == DevState.DISABLE assert sw_2_proxy.searchWindowTuning == 7000000000 assert sw_2_proxy.tdcEnable ==", "2.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 2.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 2.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 2.9", "vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream1 == 0 # assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream2 == 0 #", "== function_mode assert sub_id in proxies.fsp[fsp_id].subarrayMembership assert [proxy.State() for proxy in fsp_function_mode_proxies[fsp_id-1]] ==", "open(file_path + \"/../data/timingbeamweights.json\") timing_beam_weights = json.loads(f.read().replace(\"\\n\", \"\")) epoch = str(int(time.time())) for weights in", "# ): # \"\"\" # Test a minimal successful configuration # \"\"\" #", "ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY assert proxies.fspSubarray[1].obsState == ObsState.READY", "== 4.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 4.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 4.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] ==", "7000000000 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].tdcEnable == False # and lastly for search window", "fix #assert searchBeam1[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" # check configured attributes of FSP subarrays #", "proxies.vcc[vcc_index].subarrayMembership == sub_id #TODO fix these tests; issue with VccBand devices either not", "# add receptors # proxies.subarray[1].RemoveAllReceptors() # proxies.subarray[1].AddReceptors([1, 3, 4]) # time.sleep(1) # assert", "== True assert searchBeam400[\"averagingInterval\"] == 2 assert searchBeam400[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" proxies.subarray[1].GoToIdle() time.sleep(3) assert", "sw_2_proxy.searchWindowTuning == 7000000000 # assert sw_2_proxy.tdcEnable == False # # check configured attributes", "Subarray if proxies.subarray[sub_id].State() != DevState.ON: proxies.subarray[sub_id].On() proxies.wait_timeout_dev([proxies.subarray[sub_id]], DevState.ON, 3, 1) for proxy in", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 0.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 0.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 0.4 assert", "a successful scan configuration \"\"\" proxies.subarray[1].loggingLevel = LoggingLevel.DEBUG try: # turn on Subarray", "fsp_2_proxies.subarray[1].channelAveragingMap[6][0] == 4465 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[6][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[7][0]", "- 1][0].tdcNumBits == 8 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch == 5 assert proxies.vccTdc[proxies.receptor_to_vcc[1] -", "subarray frequency_band = input_config_dict[\"common\"][\"frequency_band\"] input_band_index = freq_band_dict()[frequency_band] assert proxies.subarray[subarr_index].configID == input_config_dict[\"common\"][\"config_id\"] assert proxies.subarray[subarr_index].frequencyBand", "= open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f1.read().replace(\"\\n\", \"\")) f1.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) # check", "DevState.ON def test_RemoveAllReceptors(self, proxies): \"\"\" Test RemoveAllReceptors command \"\"\" try: # turn on", "receptors proxies.subarray[1].RemoveReceptors([3]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert len(proxies.subarray[1].receptors) == 0 assert proxies.vcc[proxies.receptor_to_vcc[3]].subarrayMembership ==", "== ObsState.READY assert proxies.fspSubarray[3].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState ==", "cbf_master_proxy.On() time.sleep(3) # check initial value of attributes of CBF subarray assert len(proxies.subarray[1].receptors)", "configure scan f = open(file_path + \"/../data/Configure_TM-CSP_v2.json\") configuration = f.read().replace(\"\\n\", \"\") f.close() proxies.subarray[sub_id].ConfigureScan(configuration)", "== 8929 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[12][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[13][0] ==", "{}, i = {}, jonesMatrix[{}] = {}\".format( jones_matrix[\"jonesMatrix\"][1][\"epoch\"], vcc_id, index, fs_id-1, proxies.vcc[vcc_id].jonesMatrix[fs_id-1]) )", "- when a receptor to be removed is not assigned to the subarray", "states of function mode capabilities assert proxies.fsp[1].functionMode == 1 assert 1 in proxies.fsp[1].subarrayMembership", "== DevState.ON assert proxies.fsp[2].functionMode == 3 assert 1 in proxies.fsp[2].subarrayMembership assert [proxy.State() for", "receptor 10... assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].State() == DevState.DISABLE assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].searchWindowTuning ==", "AssertionError as ae: raise ae except Exception as e: raise e time.sleep(10) #", "assert [proxies.subarray[1].receptors[i] for i in range(4)] == [1, 3, 4, 2] assert proxies.vcc[proxies.receptor_to_vcc[2]].subarrayMembership", "\"foo\", \"bar\", \"8080\" # ) # # then for search window 1 of", "20) jones_matrix[\"jonesMatrix\"][1][\"epoch\"] = \"0\" jones_matrix[\"jonesMatrix\"][2][\"epoch\"] = str(int(time.time()) + 10) # update Jones Matrix", "== 2.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 2.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 2.4 proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY,", "proxies.subarray[1].receptors == (1, 3) # assert all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership == 1 for i", "in proxies.fsp[fsp_id].subarrayMembership assert [proxy.State() for proxy in fsp_function_mode_proxies[fsp_id-1]] == [ DevState.ON, DevState.DISABLE, DevState.DISABLE,", "- 1][0].tdcPeriodBeforeEpoch == 5 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch == 25 # assert", "- 1]] == [ # DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # assert [proxy.State() for", "ObsState.READY # ObsReset proxies.subarray[1].ObsReset() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].obsState == ObsState.IDLE assert", "# else: # assert vcc_band_proxies[i].State() == DevState.DISABLE # check configured attributes of FSPs,", "receptors proxies.subarray[1].AddReceptors([1, 3, 4]) time.sleep(1) assert proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1] == 3", "== 5.85 assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[1] == 7.25 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream1 ==", "- 1].band5Tuning[1] == 7.25 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream1 == 0 assert vcc_proxies[receptor_to_vcc[1] -", "assert proxies.vcc[proxies.receptor_to_vcc[1]].frequencyBand == 4 for proxy in proxies.vccBand[proxies.receptor_to_vcc[4] - 1]: logging.info(\"VCC proxy.State() =", "# Check fsp obsState BEFORE scan configuration: assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.IDLE assert proxies.fspPssSubarray[subarr_index-1].obsState", "False # add receptors proxies.subarray[1].RemoveAllReceptors() proxies.subarray[1].AddReceptors([1, 3, 4]) time.sleep(1) assert proxies.subarray[1].receptors[0] == 1", "# assert vcc_proxies[receptor_to_vcc[4] - 1].rfiFlaggingMask == \"{}\" # # then for VCC belonging", "proxies.subarray[1].obsState == ObsState.IDLE # proxies.subarray[1].RemoveAllReceptors() # time.sleep(3) # assert proxies.subarray[1].state() == tango.DevState.OFFequency band", "\"VLBI\": function_mode = 4 assert proxies.fsp[fsp_id].functionMode == function_mode assert sub_id in proxies.fsp[fsp_id].subarrayMembership assert", "== 8184 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[11][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[12][0] ==", "raise e time.sleep(10) # Clean Up proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise", "f = open(file_path + \"/../data/delaymodel_fsp.json\") delay_model = json.loads(f.read().replace(\"\\n\", \"\")) epoch = str(int(time.time())) for", "vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].State() == DevState.DISABLE assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].searchWindowTuning == 7000000000 assert vcc_tdc_proxies[receptor_to_vcc[4]", "assert proxies.subarray[1].obsState.value == ObsState.READY.value # check frequency band of VCCs, including states of", "# assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch == 5 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch ==", "assert proxies.fsp[fs_id].timingBeamWeights[rec_id - 1][index] == value except AssertionError as ae: raise ae except", "fsp_1_proxies.subarray[1].Init() fsp_2_proxies.subarray[1].Init() fsp_3_proxies.subarray[1].Init() fsp_1_proxy.Init() fsp_2_proxy.Init() time.sleep(3) cbf_master_proxy.set_timeout_millis(60000) cbf_master_proxy.Init() time.sleep(60) # takes pretty long", "time.sleep(3) # assert proxies.subarray[1].obsState == ObsState.IDLE # proxies.subarray[1].RemoveAllReceptors() # time.sleep(3) # assert proxies.subarray[1].state()", "assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcDestinationAddress == ( # \"fizz\", \"buzz\", \"80\" # ) #", "for VCC belonging to receptor 1... # assert vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership == 1", "json.loads(json_string) proxies.subarray[subarr_index].ConfigureScan(json_string) f.close() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.READY, 15, 1) logging.info( \"First vcc obsState AFTER ConfigureScan", "except Exception as e: proxies.clean_proxies() raise e #TODO: fix; currently tests break if", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) # check initial states assert proxies.subarray[1].obsState == ObsState.READY assert", "assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream1 == 0 # assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream2 == 0", "\"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", ] # then for search window 2... assert sw_2_proxy.State() ==", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[16][0] == 11905 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[16][1] == 0 #", "ObsState.READY, 30, 1) assert proxies.subarray[1].obsState == ObsState.READY assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[3].obsState", "== 2 assert searchBeam400[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" proxies.subarray[1].GoToIdle() time.sleep(3) assert proxies.subarray[1].obsState == ObsState.IDLE proxies.subarray[1].RemoveAllReceptors()", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[17][0] == 12648 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[17][1] == 8 # #", "add more receptors... proxies.subarray[1].AddReceptors([2]) time.sleep(1) assert [proxies.subarray[1].receptors[i] for i in range(4)] == [1,", "# assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream1 == 0 # assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream2 ==", "minimal successful configuration \"\"\" for proxy in vcc_proxies: proxy.Init() fsp_1_proxies.subarray[1].Init() fsp_2_proxies.subarray[1].Init() fsp_3_proxies.subarray[1].Init() fsp_1_proxy.Init()", "== 0 assert proxies.vcc[proxies.receptor_to_vcc[2]].rfiFlaggingMask == \"{}\" # check configured attributes of FSPs, including", "for proxy in fsp_2_function_mode_proxy] == [ # # DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE #", "3, 4])]) # configure scan config_file_name = \"/../data/ConfigureScan_basic.json\" f = open(file_path + config_file_name)", "windows # first for search window 1 of VCC belonging to receptor 10...", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[0][0] == 1 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[0][1] == 0 #", "- re-enable and debug! # assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcDestinationAddress == ( # \"foo\",", "assert proxies.subarray[1].receptors == ([3]) assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 0 for i in [1, 2,", "assert fsp_1_proxies.subarray[1].channelAveragingMap[13][0] == 9672 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[13][1] == 8 # # assert", "proxy in fsp_function_mode_proxies[fsp_id-1]] == [ DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ] # check configured", "assert fsp_1_proxies.subarray[1].channelAveragingMap[19][0] == 14136 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[19][1] == 8 # assert fsp_1_proxies.subarray[1].outputLinkMap[0][0]", "== 8 assert proxies.fspSubarray[1].channelAveragingMap[1][0] == 744 assert proxies.fspSubarray[1].channelAveragingMap[1][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[2][0] ==", "proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcDestinationAddress == ( # \"foo\", \"bar\", \"8080\" # ) # then", "# assert vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership == 1 # assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[0] ==", "assert fsp_2_proxies.subarray[1].channelAveragingMap[3][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[4][0] == 2977 # # assert", "7.25 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream1 == 0 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream2 == 0", "currently works for fsps 1 and 2 assert proxies.fspSubarray[fsp_id].obsState == ObsState.READY assert proxies.fspSubarray[fsp_id].receptors", "assert [proxy.State() for proxy in fsp_2_function_mode_proxy] == [ # # DevState.ON, DevState.DISABLE, DevState.DISABLE,", "of VCC belonging to receptor 1... assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].State() == DevState.ON assert", "assert searchBeam300[\"averagingInterval\"] == 4 assert searchBeam300[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" assert searchBeam400[\"searchBeamID\"] == 400 assert", "assert [proxy.State() for proxy in proxies.fsp2FunctionMode] == [ DevState.DISABLE, DevState.DISABLE, DevState.ON, DevState.DISABLE ]", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED # Restart: receptors should be", "as e: proxies.clean_proxies() raise e @pytest.mark.skip(reason=\"pst not currently supported\") def test_ConfigureScan_onlyPst_basic_FSP_scan_parameters(self, proxies): \"\"\"", "- 1].subarrayMembership == 1 # assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[0] == 5.85 # assert", "= str(int(time.time()) + 10) # update delay model proxies.tm.delayModel = json.dumps(delay_model) time.sleep(1) for", "belonging to receptor 1... assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].State() == DevState.ON assert proxies.vccTdc[proxies.receptor_to_vcc[1] -", "add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].obsState ==", "fsp_1_proxies.subarray[1].channelAveragingMap[18][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[19][0] == 14136 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[19][1]", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 2.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 2.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 2.7 assert", "logging # Path file_path = os.path.dirname(os.path.abspath(__file__)) # Tango imports import tango from tango", "== 1 # assert fsp_1_proxies.subarray[1].corrBandwidth == 1 # assert fsp_1_proxies.subarray[1].zoomWindowTuning == 4700000 #", "8\" # assert proxies.subarray[1].frequencyBand == 4 # means 5a? # assert proxies.subarray[1].obsState.value ==", "== 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[10][0] == 7441 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[10][1] ==", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 3.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 3.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 3.3 assert", "proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.IDLE assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.IDLE assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.IDLE logging.info( \"First", "assert proxies.subarray[1].receptors[0] == 1 # assert proxies.subarray[1].receptors[1] == 3 # assert proxies.subarray[1].receptors[2] ==", "ae: proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e def test_Abort_Reset(self,", "'' assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState == ObsState.EMPTY # add receptors proxies.subarray[1].AddReceptors([4,", "4 # assert searchBeam300[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" # assert searchBeam400[\"searchBeamID\"] == 400 # assert", "cbf_master_proxy.set_timeout_millis(60000) cbf_master_proxy.Init() time.sleep(60) # takes pretty long for CBF Master to initialize tm_telstate_proxy.Init()", "not reconfiguring in between # configurations or causing a fault within the Vcc", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[11][0] == 8185 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[11][1] == 0 #", "# check frequency band of VCCs, including states of frequency band capabilities assert", "== 1 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[0][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[1][0] ==", "4]) # time.sleep(1) # assert proxies.subarray[1].receptors[0] == 1 # assert proxies.subarray[1].receptors[1] == 3", "does not pass, to fix #elif fsp[\"function_mode\"] == \"PST-BF\": # assert proxies.fspPstSubarray[subarr_index-1].obsState ==", "4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[1].receptors[i] == j for i, j", "DevState.ON, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY # add receptors proxies.subarray[1].AddReceptors([1, 3, 4,", "== \"10.05.1.1\" # assert searchBeam400[\"searchBeamID\"] == 400 # assert searchBeam400[\"receptors\"][0] == 1 #", "vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcNumBits == 8 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch == 5 assert vcc_tdc_proxies[receptor_to_vcc[1]", "# ) # then for search window 2 of VCC belonging to receptor", "assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcNumBits == 8 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch == 5 assert", "- 1].rfiFlaggingMask == \"{}\" # check configured attributes of search windows # first", "configured attributes of FSPs, including states of function mode capabilities assert proxies.fsp[1].functionMode ==", "# subarray_2_proxy.set_timeout_millis(60000) # proxies.subarray[1].Init() # subarray_2_proxy.Init() # time.sleep(3) # cbf_controller_proxy.set_timeout_millis(60000) # cbf_controller_proxy.Init() #", "proxies.subarray[sub_id].State() != DevState.ON: proxies.subarray[sub_id].On() proxies.wait_timeout_dev([proxies.subarray[sub_id]], DevState.ON, 3, 1) for proxy in [proxies.vcc[i +", "DevState.DISABLE, DevState.DISABLE, DevState.ON] # assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[1] - 1]] ==", "# assert sw_1_proxy.tdcEnable == True # assert sw_1_proxy.tdcNumBits == 8 # assert sw_1_proxy.tdcPeriodBeforeEpoch", "searchBeam400[\"searchBeamID\"] == 400 assert searchBeam400[\"receptors\"][0] == 1 assert searchBeam400[\"outputEnable\"] == True assert searchBeam400[\"averagingInterval\"]", "assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcDestinationAddress == ( # \"foo\", \"bar\", \"8080\" # ) #", "vcc_band_proxies[receptor_to_vcc[4] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] assert [proxy.State() for proxy", "2.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 2.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 2.4 proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1,", "time from datetime import datetime import json import logging # Path file_path =", "== 0 assert proxies.subarray[1].obsState == ObsState.EMPTY # add receptors proxies.subarray[1].AddReceptors([4, 1, 3, 2])", "assert proxies.sw[2].State() == DevState.DISABLE # assert proxies.sw[2].searchWindowTuning == 7000000000 # assert proxies.sw[2].tdcEnable ==", "== 14880 assert proxies.fspSubarray[1].channelAveragingMap[0][0] == 0 assert proxies.fspSubarray[1].channelAveragingMap[0][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[1][0] ==", "# # first for search window 1 of VCC belonging to receptor 10...", "f = open(file_path + \"/../data/jonesmatrix_fsp.json\") jones_matrix = json.loads(f.read().replace(\"\\n\", \"\")) epoch = str(int(time.time())) for", "raise ae except Exception as e: proxies.clean_proxies() raise e def test_EndScan(self, proxies, input_test_data):", "initial value of attributes of CBF subarray assert len(proxies.subarray[sub_id].receptors) == 0 assert proxies.subarray[sub_id].configID", "fsp_2_proxies.subarray[1].channelAveragingMap[12][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[13][0] == 9673 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[13][1]", "== 5.85 assert proxies.vcc[proxies.receptor_to_vcc[1]].band5Tuning[1] == 7.25 # check configured attributes of search windows", "[proxies.fsp[i + 1] for i in range(4)]: proxy.loggingLevel = \"DEBUG\" if proxy.State() ==", "FSP assert proxies.fspSubarray[1].scanID == 1 assert proxies.vcc[proxies.receptor_to_vcc[4]].scanID ==1 # check states assert proxies.subarray[1].obsState", "subarrays # # first for FSP 1... # assert fsp_1_proxies.subarray[1].obsState == ObsState.EMPTY #", "specific imports from ska_mid_cbf_mcs.commons.global_enum import freq_band_dict from ska_tango_base.control_model import LoggingLevel, HealthState from ska_tango_base.control_model", "# assert proxies.sw[1].tdcPeriodBeforeEpoch == 5 # assert proxies.sw[1].tdcPeriodAfterEpoch == 25 # assert \"\".join(proxies.sw[1].tdcDestinationAddress.split())", "= {}\". format(jj+1, proxies.vcc[jj+1].receptorID))) logging.info( (\"Vcc, receptor 1, ObsState = {}\". format(proxies.vcc[proxies.receptor_to_vcc[1]].ObsState)) )", "fsp_3_proxies.subarray[1].searchBeams # searchBeam300 = json.loads(searchBeam[0]) # searchBeam400 = json.loads(searchBeam[1]) # assert searchBeam300[\"searchBeamID\"] ==", "vcc_ids = [None for _ in range(num_receptors)] for receptor_id, ii in zip(input_receptors, range(num_receptors)):", "f = open(file_path + config_file_name) json_string = f.read().replace(\"\\n\", \"\") input_config_dict = json.loads(json_string) proxies.subarray[subarr_index].ConfigureScan(json_string)", "# Tango imports import tango from tango import DevState import pytest # SKA", "assert proxies.subarray[1].receptors == () # assert proxies.subarray[1].configID == 0 assert proxies.subarray[1].frequencyBand == 0", "[ # DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE # ] # check configured attributes of", "to receptor 1... assert vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership == 1 # check configured attributes", "== 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[1][0] == 745 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[1][1] ==", "== 7000000000 # assert proxies.sw[2].tdcEnable == False time.sleep(1) # check configured attributes of", "== 0 assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState.value == ObsState.IDLE.value # assert tm_telstate_proxy.visDestinationAddress", "- 1][0].tdcNumBits == 8 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch == 5 assert vcc_tdc_proxies[receptor_to_vcc[1] -", "1].subarrayMembership == 0 for i in range(4)]) # add some receptors to subarray", "3.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 3.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 3.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 3.8", "Jones matrix f = open(file_path + \"/../data/jonesmatrix.json\") jones_matrix = json.loads(f.read().replace(\"\\n\", \"\")) f.close() jones_matrix[\"jonesMatrix\"][0][\"epoch\"]", "assert fsp_1_proxies.subarray[1].outputLinkMap[0][0] == 0 # assert fsp_1_proxies.subarray[1].outputLinkMap[0][1] == 4 # assert fsp_1_proxies.subarray[1].outputLinkMap[1][0] ==", "8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[2][0] == 1488 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[2][1] == 8", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[12][0] == 8929 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[12][1] == 0 # #", "== 0 assert vcc_proxies[receptor_to_vcc[4] - 1].rfiFlaggingMask == \"{}\" # then for VCC belonging", "searchBeam400[\"averagingInterval\"] == 2 # assert searchBeam400[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" # proxies.subarray[1].GoToIdle() # time.sleep(3) #", "'' # TODO in CbfSubarray, at end of scan, clear all private data", "==1 # check states assert proxies.subarray[1].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.SCANNING assert", "0 assert proxies.fspSubarray[1].frequencyBandOffsetStream2 == 0 assert proxies.fspSubarray[1].frequencySliceID == 1 assert proxies.fspSubarray[1].corrBandwidth == 1", "6696 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[9][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[10][0] == 7440", "# check configured attributes of FSP subarrays # # first for FSP 1...", "try: assert proxies.vcc[vcc_id].jonesMatrix[fs_id-1][index] == value except AssertionError as ae: logging.error(\"AssertionError; incorrect Jones matrix", "[ # DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # # check the rest of the", "assert searchBeam400[\"searchBeamID\"] == 400 # assert searchBeam400[\"receptors\"][0] == 1 # assert searchBeam400[\"outputEnable\"] ==", "assert searchBeam400[\"outputEnable\"] == True # assert searchBeam400[\"averagingInterval\"] == 2 # assert searchBeam400[\"searchBeamDestinationAddress\"] ==", "assert fsp_1_proxies.subarray[1].outputLinkMap[1][1] == 1 proxies.subarray[1].GoToIdle() time.sleep(3) assert proxies.subarray[1].obsState == ObsState.IDLE proxies.subarray[1].RemoveAllReceptors() time.sleep(1) proxies.subarray[1].Off()", "ConfigureScan = {}\". format(proxies.vcc[vcc_ids[0]].obsState) ) # check some configured attributes of CBF subarray", "logging.error(\"AssertionError; incorrect Jones matrix entry: epoch {}, VCC {}, i = {}, jonesMatrix[{}]", "1 assert 1 in proxies.fsp[1].subarrayMembership assert [proxy.State() for proxy in proxies.fsp1FunctionMode] == [", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[10][0] == 7441 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[10][1] == 0 # #", "== ObsState.ABORTED # ObsReset proxies.subarray[1].ObsReset() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].obsState == ObsState.IDLE", "# time.sleep(3) # assert proxies.subarray[1].state() == tango.DevState.OFFequency band capabilities assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand", "fsp_2_proxy, fsp_1_function_mode_proxy, fsp_2_function_mode_proxy, fsp_1_proxies.subarray[1], fsp_2_proxies.subarray[1], fsp_3_proxies.subarray[1], tm_telstate_proxy ): \"\"\" Test a minimal successful", "3, 4]]) assert proxies.subarray[1].obsState == ObsState.EMPTY proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.OFF, 3, 1) except AssertionError", "reconfiguring in between # configurations or causing a fault within the Vcc device", "states of function mode capabilities fsp_function_mode_proxies = [proxies.fsp1FunctionMode, proxies.fsp2FunctionMode, proxies.fsp3FunctionMode, proxies.fsp4FunctionMode] for fsp", "a receptor not assigned to subarray 1 # doing this doesn't actually throw", "then for search window 2... # assert sw_2_proxy.State() == DevState.DISABLE # assert sw_2_proxy.searchWindowTuning", "for model in delay_model[\"delayModel\"]: if model[\"destinationType\"] == \"fsp\": for receptor in model[\"delayDetails\"]: rec_id", "== True # assert searchBeam300[\"averagingInterval\"] == 4 # assert searchBeam300[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" #", "time.sleep(60) # takes pretty long for CBF Master to initialize # tm_telstate_proxy.Init() #", "= freq_band_dict()[frequency_band] assert proxies.subarray[subarr_index].configID == input_config_dict[\"common\"][\"config_id\"] assert proxies.subarray[subarr_index].frequencyBand == input_band_index assert proxies.subarray[subarr_index].obsState ==", "for frequency_slice in receptor[\"receptorMatrix\"]: for index, value in enumerate(frequency_slice[\"matrix\"]): vcc_id = proxies.receptor_to_vcc[receptor[\"receptor\"]] fs_id", "== 0 # assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream2 == 0 # assert vcc_proxies[receptor_to_vcc[1] -", "== 300 # assert searchBeam300[\"receptors\"][0] == 3 # assert searchBeam300[\"outputEnable\"] == True #", "# # # Distributed under the terms of the BSD-3-Clause license. # See", "test is currently broken.\") def test_AddRemoveReceptors_invalid_multiple(self, proxies): \"\"\" Test invalid AddReceptors commands involving", "# time.sleep(1) # assert \"Invalid receptor ID\" in str(df.value.args[0].desc) # try removing a", "subarray_2_proxy.receptors == () # assert all([proxy.subarrayMembership == 0 for proxy in vcc_proxies]) #", "attributes of FSPs, including states of function mode capabilities fsp_function_mode_proxies = [proxies.fsp1FunctionMode, proxies.fsp2FunctionMode,", "= {}\". format( proxies.vcc[vcc_index].frequencyBand)) ) vcc_band_proxies = proxies.vccBand[vcc_index - 1] assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBand ==", "window 2 of VCC belonging to receptor 10... assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].State() ==", "only a single subarray, this test is currently broken.\") def test_AddRemoveReceptors_invalid_multiple(self, proxies): \"\"\"", "in vcc_band_proxies: # logging.info(\"VCC proxy.State() = {}\".format(proxy.State())) # for i in range(4): #", "\"PST-BF\": function_mode = 3 elif fsp[\"function_mode\"] == \"VLBI\": function_mode = 4 assert proxies.fsp[fsp_id].functionMode", "# fsp_1_proxy, # fsp_2_proxy, # fsp_1_function_mode_proxy, # fsp_2_function_mode_proxy, # fsp_1_proxies.subarray[1], # fsp_2_proxies.subarray[1], #", "assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[4] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE,", "3.4 # transition to obsState=SCANNING f2 = open(file_path + \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close()", "assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].State() == DevState.ON # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].searchWindowTuning == 6000000000", "2.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 2.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 2.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 2.6", "of range) - when a receptor to be removed is not assigned to", "proxies.subarray[sub_id].obsState == ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i + 1] for i in range(4)], ObsState.READY, 1, 1)", "assert fsp_1_proxies.subarray[1].zoomWindowTuning == 4700000 # assert fsp_1_proxies.subarray[1].integrationTime == 140 # assert fsp_1_proxies.subarray[1].fspChannelOffset ==", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[9][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[10][0] == 7441 # #", "range(4)]) input_receptors = [1, 3, 4] # add some receptors proxies.subarray[1].AddReceptors(input_receptors) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE,", "of attributes of CBF subarray vcc_index = proxies.receptor_to_vcc[4] logging.info(\"vcc_index = {}\".format( vcc_index ))", "assert proxies.fspSubarray[1].outputLinkMap[0][0] == 0 assert proxies.fspSubarray[1].outputLinkMap[0][1] == 4 assert proxies.fspSubarray[1].outputLinkMap[1][0] == 744 assert", "proxies.subarray[1].obsState == ObsState.READY #create a Jones matrix f = open(file_path + \"/../data/jonesmatrix.json\") jones_matrix", "+ 1] for i in range(4)]: proxy.loggingLevel = \"DEBUG\" if proxy.State() == DevState.OFF:", "on VCC and FSP assert proxies.fspSubarray[1].scanID == 1 assert proxies.vcc[proxies.receptor_to_vcc[4]].scanID ==1 # check", "ObsState.READY # abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED #", "14136 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[19][1] == 8 # assert fsp_1_proxies.subarray[1].outputLinkMap[0][0] == 0 #", "# # assert fsp_2_proxies.subarray[1].frequencyBandOffsetStream1 == 0 # # assert fsp_2_proxies.subarray[1].frequencyBandOffsetStream2 == 0 #", "proxies): \"\"\" Test invalid AddReceptors commands involving multiple subarrays: - when a receptor", "0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[3][0] == 2233 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[3][1] == 0", "1.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 2.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 2.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 2.2", "assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].tdcEnable == False assert fsp_3_proxies.subarray[1].receptors[0] == 3 assert fsp_3_proxies.subarray[1].receptors[1] ==", "[1, 3, 4, 2] assert proxies.vcc[proxies.receptor_to_vcc[2]].subarrayMembership == 1 # remove some receptors proxies.subarray[1].RemoveReceptors([2,", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[3][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[4][0] == 2977 # #", "# # add some receptors to subarray 1 # proxies.subarray[1].AddReceptors([1, 3]) # time.sleep(1)", "in # cbf_controller_proxy.receptorToVcc) # cbf_controller_proxy.On() # time.sleep(3) # # receptor list should be", "e: proxies.clean_proxies() raise e @pytest.mark.skip(reason=\"pst not currently supported\") def test_ConfigureScan_onlyPst_basic_FSP_scan_parameters(self, proxies): \"\"\" Test", "Exception as e: proxies.clean_proxies() raise e def test_Abort_Restart(self, proxies): \"\"\" Test abort restart", "proxies.vcc[proxies.receptor_to_vcc[4]].band5Tuning[1] == 7.25 assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBandOffsetStream1 == 0 assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBandOffsetStream2 == 0 assert proxies.vcc[proxies.receptor_to_vcc[4]].rfiFlaggingMask", "datetime = {}\".format(datetime.now())) if proxies.debug_device_is_on: port = proxies.subarray[1].DebugDevice() try: proxies.clean_proxies() if proxies.controller.State() ==", "str(int(time.time()) + 20) delay_model[\"delayModel\"][1][\"epoch\"] = \"0\" delay_model[\"delayModel\"][2][\"epoch\"] = str(int(time.time()) + 10) # update", "== 0 assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBandOffsetStream2 == 0 assert proxies.vcc[proxies.receptor_to_vcc[4]].rfiFlaggingMask == \"{}\" # then for", "str({\"outputHost\": [[0, \"192.168.0.1\"], [8184, \"192.168.0.2\"]], \"outputMac\": [[0, \"06-00-00-00-00-01\"]], \"outputPort\": [[0, 9000, 1], [8184,", "proxies.fspSubarray[1].integrationTime == 1 assert proxies.fspSubarray[1].fspChannelOffset == 14880 assert proxies.fspSubarray[1].channelAveragingMap[0][0] == 0 assert proxies.fspSubarray[1].channelAveragingMap[0][1]", ") logging.info( \"proxies.fspPssSubarray[subarr_index-1].obsState = {}\". format(proxies.fspPssSubarray[subarr_index-1].obsState) ) logging.info( \"proxies.fspPstSubarray[subarr_index-1].obsState = {}\". format(proxies.fspPstSubarray[subarr_index-1].obsState) )", "== 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[7][0] == 5208 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[7][1] ==", "assert proxies.sw[2].searchWindowTuning == 7000000000 # assert proxies.sw[2].tdcEnable == False time.sleep(1) # check configured", "import time from datetime import datetime import json import logging # Path file_path", "== 12 assert proxies.fspSubarray[1].outputLinkMap[3][0] == 2232 assert proxies.fspSubarray[1].outputLinkMap[3][1] == 16 assert str(proxies.fspSubarray[1].visDestinationAddress).replace('\"',\"'\") ==", "1][1].State() == DevState.DISABLE assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].searchWindowTuning == 7000000000 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].tdcEnable", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[15][0] == 11161 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[15][1] == 0 # #", "fsp_2_proxy.Init() proxies.subarray[1].set_timeout_millis(60000) # since the command takes a while proxies.subarray[1].Init() time.sleep(3) cbf_master_proxy.set_timeout_millis(60000) cbf_master_proxy.Init()", "fsp_2_function_mode_proxy, # fsp_1_proxies.subarray[1], # fsp_2_proxies.subarray[1], # fsp_3_proxies.subarray[1], # tm_telstate_proxy # ): # \"\"\"", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 0.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 0.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 1.0 assert", "== ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY # ObsReset proxies.subarray[1].Restart()", "proxies.subarray[1].scanID == 2 assert proxies.fspSubarray[1].obsState == ObsState.SCANNING assert proxies.fspSubarray[3].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState", "# assert fsp_1_proxies.subarray[1].corrBandwidth == 1 # assert fsp_1_proxies.subarray[1].zoomWindowTuning == 4700000 # assert fsp_1_proxies.subarray[1].integrationTime", "receptor[\"receptorDelayDetails\"][0][\"fsid\"] for index, value in enumerate(receptor[\"receptorDelayDetails\"][0][\"delayCoeff\"]): try: assert proxies.fsp[fs_id].delayModel[rec_id - 1][index] == value", "jones_matrix[\"jonesMatrix\"][1][\"epoch\"], vcc_id, index, fs_id-1, proxies.vcc[vcc_id].jonesMatrix[fs_id-1]) ) raise ae except Exception as e: raise", "proxies.fspSubarray[3].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE proxies.clean_proxies() except", "for i in range(4)]) # add some receptors proxies.subarray[1].AddReceptors([1, 3, 4]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE,", "4 # means 5a? # assert proxies.subarray[1].obsState.value == ObsState.READY.value # # check frequency", "== 2 # assert fsp_3_proxies.subarray[1].searchBeamID[0] == 300 # assert fsp_3_proxies.subarray[1].searchBeamID[1] == 400 #", "3, 1) proxies.controller.On() proxies.wait_timeout_dev([proxies.controller], DevState.ON, 3, 1) proxies.clean_proxies() # turn on Subarray if", "= {}\". format(proxies.vcc[proxies.receptor_to_vcc[1]].ObsState)) ) #proxies.vcc[0].receptorID assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 1.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 1.2", "= {}\".format( aa[jj][\"delayCoeff\"]) ) try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON:", "logging.info(\"vcc_index = {}\".format(vcc_index)) vcc_band_proxies = proxies.vccBand[vcc_index - 1] # turn on Subarray if", "DevState.ON # assert sw_1_proxy.searchWindowTuning == 6000000000 # assert sw_1_proxy.tdcEnable == True # assert", "1, 3, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[1].receptors[i] == j for i,", "1][0].tdcEnable == True assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcNumBits == 8 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch", "1][0].tdcDestinationAddress == ( \"foo\", \"bar\", \"8080\" ) # then for search window 1", "== ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[3].obsState ==", "add some receptors proxies.subarray[1].AddReceptors(input_receptors) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert [proxies.subarray[1].receptors[i] for i in", "# assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[1] - 1]] == [ # DevState.DISABLE,", "proxies.fsp[2].subarrayMembership assert [proxy.State() for proxy in proxies.fsp2FunctionMode] == [ DevState.DISABLE, DevState.DISABLE, DevState.ON, DevState.DISABLE", "+ 10) # update delay model proxies.tm.delayModel = json.dumps(delay_model) time.sleep(1) for jj in", "in use\" in str(df.value.args[0].desc) # assert subarray_2_proxy.receptors == (2, 4) # assert all([vcc_proxies[receptor_to_vcc[i]", "proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].tdcEnable == False # and lastly for search window 2 of", "ObsState.IDLE, 1, 1) assert [proxies.subarray[1].receptors[i] for i in range(3)] == input_receptors assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership", "# assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcDestinationAddress == ( # \"fizz\", \"buzz\", \"80\" # )", "assert [proxy.State() for proxy in proxies.fsp1FunctionMode] == [ DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ]", "time.sleep(10) assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 2.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 2.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 2.3", "3.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 3.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 3.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 4.0", "add receptors proxies.subarray[1].AddReceptors([1, 3, 4]) time.sleep(1) assert proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1] ==", "in range(4)]: if proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) for proxy", "== 6000000000 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcEnable == True assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcNumBits ==", "\"\"\" timeout_millis = proxies.subarray[1].get_timeout_millis() log_msg = \"timeout_millis = {} \".format(timeout_millis) #logging.info(log_msg) #logging.info(\"start_time =", "= proxies.receptor_to_vcc[test_receptor_ids[0]] logging.info(\"vcc_index = {}\".format(vcc_index)) vcc_band_proxies = proxies.vccBand[vcc_index - 1] # turn on", "proxies.subarray[1].obsState == ObsState.IDLE proxies.subarray[1].RemoveAllReceptors() time.sleep(3) assert proxies.subarray[1].state() == tango.DevState.OFF def test_band1( self, cbf_master_proxy,", "== \"fsp\": epoch = str(int(epoch) + 10) # update delay model proxies.tm.delayModel =", "proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.READY proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae except Exception", "1) assert proxies.subarray[1].obsState == ObsState.EMPTY assert len(proxies.subarray[1].receptors) == 0 assert proxies.fspSubarray[1].obsState == ObsState.IDLE", "== 1 assert proxies.fspSubarray[1].zoomWindowTuning == 4700000 assert proxies.fspSubarray[1].integrationTime == 1 assert proxies.fspSubarray[1].fspChannelOffset ==", "\"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", # ] # # then for search window 2... #", "vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership == 1 # then for VCC belonging to receptor 1...", "f.read().replace(\"\\n\", \"\") f.close() proxies.subarray[sub_id].ConfigureScan(configuration) proxies.wait_timeout_obs([proxies.subarray[sub_id]], ObsState.READY, 15, 1) configuration = json.loads(configuration) band_index =", "== 1 assert 1 in fsp_1_proxy.subarrayMembership # assert 1 in fsp_2_proxy.subarrayMembership assert [proxy.State()", "DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY ############################# abort from", "proxies.fspSubarray[1].frequencyBandOffsetStream2 == 0 assert proxies.fspSubarray[1].frequencySliceID == 1 assert proxies.fspSubarray[1].corrBandwidth == 1 assert proxies.fspSubarray[1].zoomWindowTuning", "for search window 1 of VCC belonging to receptor 1... # assert vcc_tdc_proxies[receptor_to_vcc[1]", "ObsState.READY, 30, 1) # scan f2 = open(file_path + \"/../data/Scan2_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close()", "jones_matrix[\"jonesMatrix\"][1][\"matrixDetails\"]: for frequency_slice in receptor[\"receptorMatrix\"]: for index, value in enumerate(frequency_slice[\"matrix\"]): vcc_id = proxies.receptor_to_vcc[receptor[\"receptor\"]]", "Exception as e: raise e time.sleep(10) for receptor in jones_matrix[\"jonesMatrix\"][0][\"matrixDetails\"]: for frequency_slice in", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 2.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 2.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 2.4 proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]],", "proxies.vcc[vcc_ids[0]].obsState == ObsState.READY assert proxies.vcc[vcc_ids[num_receptors -1]].obsState == ObsState.READY assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.READY for", "- 1].frequencyBand == 0 # check the rest of the configured attributes of", "1.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 1.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 1.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 1.9", "raise ae except Exception as e: raise e time.sleep(10) # update timing beam", "\\ str({\"outputHost\": [[0, \"192.168.0.1\"], [8184, \"192.168.0.2\"]], \"outputMac\": [[0, \"06-00-00-00-00-01\"]], \"outputPort\": [[0, 9000, 1],", "means 5a? # assert proxies.subarray[1].obsState.value == ObsState.READY.value # # check frequency band of", "8 # assert sw_1_proxy.tdcPeriodBeforeEpoch == 5 # assert sw_1_proxy.tdcPeriodAfterEpoch == 25 # assert", "assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcEnable == True # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcNumBits == 8", "assert len(proxies.subarray[sub_id].receptors) == 0 assert proxies.subarray[sub_id].configID == '' # TODO in CbfSubarray, at", "zip(range(4), [4, 1, 3, 2])]) # configure scan f = open(file_path + \"/../data/ConfigureScan_basic.json\")", "# assert fsp_3_proxies.subarray[1].searchBeamID[1] == 400 # searchBeam = fsp_3_proxies.subarray[1].searchBeams # searchBeam300 = json.loads(searchBeam[0])", "fsp[\"function_mode\"] == \"PST-BF\": # assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.SCANNING proxies.subarray[subarr_index].EndScan() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.READY, 1, 1)", "def test_AddRemoveReceptors_valid(self, proxies): \"\"\" Test valid AddReceptors and RemoveReceptors commands \"\"\" timeout_millis =", "Test a minimal successful configuration \"\"\" for proxy in vcc_proxies: proxy.Init() fsp_1_proxies.subarray[1].Init() fsp_2_proxies.subarray[1].Init()", "j in zip(range(3), [1, 3, 4])]) # configure scan f1 = open(file_path +", "8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[18][0] == 13392 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[18][1] == 8", "1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # check the rest of the", "in vcc_proxies: proxy.Init() fsp_1_proxies.subarray[1].Init() fsp_2_proxies.subarray[1].Init() fsp_3_proxies.subarray[1].Init() fsp_1_proxy.Init() fsp_2_proxy.Init() time.sleep(3) cbf_master_proxy.set_timeout_millis(60000) cbf_master_proxy.Init() time.sleep(60) #", "2 # TODO - this does not pass - to debug & fix", "Scan command f2 = open(file_path + \"/../data/Scan1_basic.json\") json_string = f2.read().replace(\"\\n\", \"\") input_scan_dict =", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[19][0] == 14137 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[19][1] == 0 #", "input_config_dict[\"common\"][\"frequency_band\"] input_band_index = freq_band_dict()[frequency_band] assert proxies.subarray[subarr_index].configID == input_config_dict[\"common\"][\"config_id\"] assert proxies.subarray[subarr_index].frequencyBand == input_band_index assert", "1][0].tdcPeriodBeforeEpoch == 5 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch == 25 # assert vcc_tdc_proxies[receptor_to_vcc[4]", "factor 8\" # assert proxies.subarray[1].frequencyBand == 4 # means 5a? # assert proxies.subarray[1].obsState.value", "0 assert all([proxies.vcc[i + 1].subarrayMembership == 0 for i in range(4)]) # add", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[12][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[13][0] == 9672 #", "# Insert the epoch delay_model[\"delayModel\"][0][\"epoch\"] = str(int(time.time()) + 20) delay_model[\"delayModel\"][1][\"epoch\"] = \"0\" delay_model[\"delayModel\"][2][\"epoch\"]", "vcc_id, index, fs_id-1, proxies.vcc[vcc_id].jonesMatrix[fs_id-1]) ) raise ae except Exception as e: raise e", "to accept string in FSP if fsp[\"function_mode\"] == \"CORR\": function_mode = 1 elif", "fsp1, 744 channels average factor 8\" # assert proxies.subarray[1].frequencyBand == 4 # means", "4 # configure scan f = open(file_path + \"/test_json/test_ConfigureScan_onlyPss_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() time.sleep(15)", "raise ae except Exception as e: proxies.clean_proxies() raise e def test_Abort_Restart(self, proxies): \"\"\"", "update Jones Matrix proxies.tm.jonesMatrix = json.dumps(jones_matrix) time.sleep(5) for receptor in jones_matrix[\"jonesMatrix\"][1][\"matrixDetails\"]: for frequency_slice", "== 7.25 assert proxies.fspSubarray[1].frequencyBandOffsetStream1 == 0 assert proxies.fspSubarray[1].frequencyBandOffsetStream2 == 0 assert proxies.fspSubarray[1].frequencySliceID ==", "1) proxies.controller.On() proxies.wait_timeout_dev([proxies.controller], DevState.ON, 3, 1) proxies.clean_proxies() # turn on Subarray if proxies.subarray[1].State()", "searchBeam0 = json.loads(searchBeam[0]) searchBeam1 = json.loads(searchBeam[1]) assert searchBeam0[\"search_beam_id\"] == 300 assert searchBeam0[\"receptor_ids\"][0] ==", "== 400 assert searchBeam1[\"receptor_ids\"][0] == 1 assert searchBeam1[\"enable_output\"] == True assert searchBeam1[\"averaging_interval\"] ==", "= open(file_path + \"/../data/delaymodel.json\") delay_model = json.loads(f.read().replace(\"\\n\", \"\")) f.close() aa = delay_model[\"delayModel\"][0][\"delayDetails\"][0][\"receptorDelayDetails\"] num_fsp_IDs", "in range(len(fsp[\"output_link_map\"][i])): assert proxies.fspSubarray[fsp_id].outputLinkMap[i][j] == fsp[\"output_link_map\"][i][j] proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise", "time.sleep(1) receptor_to_vcc = dict([*map(int, pair.split(\":\"))] for pair in cbf_master_proxy.receptorToVcc) cbf_master_proxy.On() time.sleep(3) # check", "json.dumps(delay_model) time.sleep(1) for model in delay_model[\"delayModel\"]: if model[\"destinationType\"] == \"fsp\": for receptor in", "attributes of CBF subarray frequency_band = input_config_dict[\"common\"][\"frequency_band\"] input_band_index = freq_band_dict()[frequency_band] assert proxies.subarray[subarr_index].configID ==", "vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcNumBits == 8 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch == 5 #", "fsp_2_function_mode_proxy] == [ # DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE # ] # check configured", "epoch if matrix[\"destinationType\"] == \"fsp\": epoch = str(int(epoch) + 10) # update Jones", "the terms of the BSD-3-Clause license. # See LICENSE.txt for more info. \"\"\"Contain", "fsp_2_proxies.subarray[1].channelAveragingMap[1][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[2][0] == 1489 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[2][1]", "assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].tdcEnable == False # and lastly for search window 2", "'string' type # scan_index is an index into an array, therefore 0-based scan_index", "for i in range(4): # if (i == 0 and band_index == 0)", "assert fsp_1_proxies.subarray[1].channelAveragingMap[13][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[14][0] == 10416 # # assert", "# assert fsp_2_proxies.subarray[1].frequencyBand == 4 # # assert fsp_2_proxies.subarray[1].band5Tuning[0] == 5.85 # #", "# assert proxies.subarray[1].configID == 0 assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState.value == ObsState.IDLE.value", "5.85 assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[1] == 7.25 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream1 == 0", "json.loads(f.read().replace(\"\\n\", \"\")) f.close() jones_matrix[\"jonesMatrix\"][0][\"epoch\"] = str(int(time.time()) + 20) jones_matrix[\"jonesMatrix\"][1][\"epoch\"] = \"0\" jones_matrix[\"jonesMatrix\"][2][\"epoch\"] =", "DevState.DISABLE # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].searchWindowTuning == 7000000000 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].tdcEnable", "to initialize tm_telstate_proxy.Init() time.sleep(1) receptor_to_vcc = dict([*map(int, pair.split(\":\"))] for pair in cbf_master_proxy.receptorToVcc) cbf_master_proxy.On()", "assert searchBeam1[\"averaging_interval\"] == 2 # TODO - this does not pass - to", "- 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] assert [proxy.State() for proxy in", "in jones_matrix[\"jonesMatrix\"][2][\"matrixDetails\"]: for frequency_slice in receptor[\"receptorMatrix\"]: for index, value in enumerate(frequency_slice[\"matrix\"]): vcc_id =", "- 1].frequencyBandOffsetStream1 == 0 # assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream2 == 0 # assert", "raise ae except Exception as e: raise e proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1, 1)", "- 1][0].searchWindowTuning == 6000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcEnable == True assert proxies.vccTdc[proxies.receptor_to_vcc[1] -", "1][0].State() == DevState.ON # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].searchWindowTuning == 6000000000 # assert vcc_tdc_proxies[receptor_to_vcc[4]", "cbf_master_proxy.On() # time.sleep(60) # # turn on Subarray # assert proxies.subarray[1].state()==DevState.OFF # proxies.subarray[1].On()", "proxy in proxies.fsp2FunctionMode] == [ DevState.DISABLE, DevState.DISABLE, DevState.ON, DevState.DISABLE ] # check configured", "== True assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcNumBits == 8 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch ==", "band of VCCs, including states of # frequency band capabilities logging.info( (\"proxies.vcc[vcc_index].frequencyBand =", "== 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[19][0] == 14136 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[19][1] ==", "as e: raise e time.sleep(10) # update delay models from tm emulator f", "vcc_band_proxies[receptor_to_vcc[1] - 1]] == [ # DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # # check", "1 for i in [1, 3]]) # assert proxies.subarray[1].State() == DevState.ON # #", "== 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[18][0] == 13393 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[18][1] ==", "== ( \"foo\", \"bar\", \"8080\" ) # then for search window 1 of", "pair.split(\":\"))] for pair in # cbf_master_proxy.receptorToVcc) # cbf_master_proxy.On() # time.sleep(60) # # turn", "== 4 # # assert fsp_2_proxies.subarray[1].band5Tuning[0] == 5.85 # # assert fsp_2_proxies.subarray[1].band5Tuning[1] ==", "2233 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[3][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[4][0] == 2977", "[1, 3, 4] # add some receptors proxies.subarray[1].AddReceptors(input_receptors) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert", "(i == (band_index - 1)): # assert vcc_band_proxies[i].State() == DevState.ON # else: #", "added is already in use by a different subarray \"\"\" # for proxy", "fsp_2_proxies.subarray[1].channelAveragingMap[6][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[7][0] == 5209 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[7][1]", "4])]) assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for i in [1, 3, 4]]) assert proxies.subarray[1].obsState", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 3.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 3.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 3.3 assert", "ConfigureScan = {}\". format(proxies.vcc[vcc_ids[0]].obsState) ) f = open(file_path + config_file_name) json_string = f.read().replace(\"\\n\",", "proxies.subarray[1].On() # time.sleep(10) # # check initial value of attributes of CBF subarray", "belonging to receptor 10... assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].State() == DevState.ON assert vcc_tdc_proxies[receptor_to_vcc[4] -", "index, value in enumerate(frequency_slice[\"matrix\"]): vcc_id = proxies.receptor_to_vcc[receptor[\"receptor\"]] fs_id = frequency_slice[\"fsid\"] try: assert proxies.vcc[vcc_id].jonesMatrix[fs_id-1][index]", "proxies.subarray[1].RemoveReceptors([2]) assert proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1] == 3 proxies.subarray[1].RemoveAllReceptors() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1,", "VCC and FSP assert proxies.fspSubarray[1].scanID == 1 assert proxies.vcc[proxies.receptor_to_vcc[4]].scanID ==1 # check states", "CBF subarray assert sub_id == int(configuration[\"common\"][\"subarray_id\"]) assert proxies.subarray[sub_id].configID == configuration[\"common\"][\"config_id\"] assert proxies.subarray[sub_id].frequencyBand ==", "weights from tm emulator f = open(file_path + \"/../data/timingbeamweights.json\") timing_beam_weights = json.loads(f.read().replace(\"\\n\", \"\"))", "check configured attributes of search windows # first for search window 1... #", "data #assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState == ObsState.EMPTY # add receptors proxies.subarray[1].AddReceptors([1,", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 3.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 3.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 3.2 assert", "assert proxies.fspSubarray[fsp_id].frequencySliceID == fsp[\"frequency_slice_id\"] assert proxies.fspSubarray[fsp_id].integrationTime == fsp[\"integration_factor\"] assert proxies.fspSubarray[fsp_id].corrBandwidth == fsp[\"zoom_factor\"] if", "assert fsp_1_proxies.subarray[1].frequencyBand == 0 assert fsp_1_proxies.subarray[1].frequencySliceID == 1 assert fsp_1_proxies.subarray[1].corrBandwidth == 0 assert", "== 400 # assert searchBeam400[\"receptors\"][0] == 1 # assert searchBeam400[\"outputEnable\"] == True #", "= open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 15, 1) # check", "1 # assert proxies.subarray[1].receptors[1] == 3 # assert proxies.subarray[1].receptors[2] == 4 # #", "== ObsState.SCANNING for fsp in input_config_dict[\"cbf\"][\"fsp\"]: if fsp[\"function_mode\"] == \"CORR\": assert proxies.fspCorrSubarray[subarr_index-1].obsState ==", "VccSearchWindow device; # to be decide which one to keep. # print(\"proxies.sw[1].State() =", "search window 2 of VCC belonging to receptor 1... # assert vcc_tdc_proxies[receptor_to_vcc[1] -", "for fsps 1 and 2 assert proxies.fspSubarray[fsp_id].obsState == ObsState.READY assert proxies.fspSubarray[fsp_id].receptors == test_receptor_ids[0]", "matrices \"\"\" try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On() proxies.wait_timeout_dev([proxies.subarray[1]],", "assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].State() == DevState.DISABLE assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].searchWindowTuning == 7000000000 assert", "searchBeam400[\"receptors\"][0] == 1 assert searchBeam400[\"outputEnable\"] == True assert searchBeam400[\"averagingInterval\"] == 2 assert searchBeam400[\"searchBeamDestinationAddress\"]", "4 assert proxies.fspSubarray[1].outputLinkMap[1][0] == 744 assert proxies.fspSubarray[1].outputLinkMap[1][1] == 8 assert proxies.fspSubarray[1].outputLinkMap[2][0] == 1488", "one to keep. # print(\"proxies.sw[1].State() = {}\".format(proxies.sw[1].State())) # print(\"proxies.sw[2].State() = {}\".format(proxies.sw[2].State())) # assert", "in input_config_dict[\"cbf\"][\"fsp\"]: if fsp[\"function_mode\"] == \"CORR\": assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.READY elif fsp[\"function_mode\"] ==", "# add receptors proxies.subarray[1].AddReceptors([4, 1, 3, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[1].receptors[i]", "\"10.05.2.1\" # proxies.subarray[1].GoToIdle() # time.sleep(3) # assert proxies.subarray[1].obsState == ObsState.IDLE # proxies.subarray[1].RemoveAllReceptors() #", "assert fsp_1_proxies.subarray[1].channelAveragingMap[18][0] == 13392 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[18][1] == 8 # # assert", "1) proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae except Exception as e:", "receptor to be added is already in use by a different subarray \"\"\"", "== 1.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 2.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 2.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] ==", "delay model proxies.tm.delayModel = json.dumps(delay_model) time.sleep(1) for jj in range(4): logging.info((\" proxies.vcc[{}].receptorID =", "# assert all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership == 2 for i in [2, 4]]) #", "in enumerate(frequency_slice[\"matrix\"]): vcc_id = proxies.receptor_to_vcc[receptor[\"receptor\"]] fs_id = frequency_slice[\"fsid\"] try: assert proxies.vcc[vcc_id].jonesMatrix[fs_id-1][index] == value", "receptor 10... # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].State() == DevState.ON # assert vcc_tdc_proxies[receptor_to_vcc[4] -", "== 1 # assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[0] == 5.85 # assert vcc_proxies[receptor_to_vcc[4] -", "1) logging.info( \"First vcc obsState AFTER ConfigureScan = {}\". format(proxies.vcc[vcc_ids[0]].obsState) ) # check", "\"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", # ] # # then for search window 2... # assert proxies.sw[2].State()", "== \"{}\" # # check configured attributes of search windows # # first", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[11][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[12][0] == 8928 # #", "elif fsp[\"function_mode\"] == \"PSS-BF\": function_mode = 2 elif fsp[\"function_mode\"] == \"PST-BF\": function_mode =", "proxies.fsp[1].subarrayMembership assert [proxy.State() for proxy in proxies.fsp1FunctionMode] == [ DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE", "proxies.subarray[1].receptors[1] == 3 # assert proxies.subarray[1].receptors[2] == 4 # # configure scan #", "if proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) assert proxies.subarray[1].State() == DevState.ON", "fsp_2_proxies.subarray[1].channelAveragingMap[15][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[16][0] == 11905 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[16][1]", "1 assert proxies.subarray[1].obsState.value == ObsState.READY.value # check frequency band of VCCs, including states", "to be removed is not assigned to the subarray \"\"\" try: # turn", "- 1][1].searchWindowTuning == 7000000000 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].tdcEnable == False # #", "is currently broken.\") def test_AddRemoveReceptors_invalid_multiple(self, proxies): \"\"\" Test invalid AddReceptors commands involving multiple", "check frequency band of VCCs, including states of # frequency band capabilities logging.info(", "proxies.fspSubarray[1].band5Tuning[1] == 7.25 assert proxies.fspSubarray[1].frequencyBandOffsetStream1 == 0 assert proxies.fspSubarray[1].frequencyBandOffsetStream2 == 0 assert proxies.fspSubarray[1].frequencySliceID", "for i in input_receptors]) assert proxies.subarray[1].obsState == ObsState.IDLE # add more receptors... proxies.subarray[1].AddReceptors([2])", "proxies.subarray[1].AddReceptors(input_receptors) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert [proxies.subarray[1].receptors[i] for i in range(3)] == input_receptors", "[1, 3, 4])]) # configure scan config_file_name = \"/../data/ConfigureScan_basic.json\" f = open(file_path +", "# time.sleep(3) # cbf_master_proxy.set_timeout_millis(60000) # cbf_master_proxy.Init() # time.sleep(60) # takes pretty long for", "Exception as e: raise e proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1, 1) proxies.clean_proxies() except AssertionError", "assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].searchWindowTuning == 7000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].tdcEnable == False #", "an index into an array, therefore 0-based scan_index = int(input_scan_dict[\"scan_id\"]) - 1 logging.info(", "proxies.subarray[1].obsState == ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i + 1] for i in range(4)], ObsState.READY, 1, 1)", "1) assert all([proxies.subarray[subarr_index].receptors[i] == j for i, j in zip(range(num_receptors), input_receptors)]) assert proxies.subarray[subarr_index].obsState", "windows # first for search window 1... assert sw_1_proxy.State() == DevState.ON assert sw_1_proxy.searchWindowTuning", "range(4)]: if proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) assert proxies.subarray[1].obsState ==", "searchBeam0[\"receptor_ids\"][0] == 3 assert searchBeam0[\"enable_output\"] == True assert searchBeam0[\"averaging_interval\"] == 4 # TODO", "ObsState.SCANNING, 1, 1) assert proxies.subarray[1].obsState == ObsState.SCANNING time.sleep(10) for receptor in jones_matrix[\"jonesMatrix\"][2][\"matrixDetails\"]: for", "== 1 proxies.subarray[1].GoToIdle() time.sleep(3) assert proxies.subarray[1].obsState == ObsState.IDLE proxies.subarray[1].RemoveAllReceptors() time.sleep(1) proxies.subarray[1].Off() assert proxies.subarray[1].state()", "check configured attributes of FSP subarrays # FSP 2 assert proxies.fspSubarray[6].obsState == ObsState.READY", "READY ########################### # add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1)", "== ObsState.IDLE # add more receptors... proxies.subarray[1].AddReceptors([2]) time.sleep(1) assert [proxies.subarray[1].receptors[i] for i in", "# assert searchBeam400[\"averagingInterval\"] == 2 # assert searchBeam400[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" # proxies.subarray[1].GoToIdle() #", "proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch == 5 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch == 25 # TODO", "4 assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[4] - 1]] == [ DevState.DISABLE, DevState.DISABLE,", "proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.READY elif fsp[\"function_mode\"] == \"PSS-BF\": assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.READY # TODO:", "# assert fsp_3_proxies.subarray[1].receptors[0] == 3 # assert fsp_3_proxies.subarray[1].receptors[1] == 1 # assert fsp_3_proxies.subarray[1].searchWindowID", "after initialization assert len(proxies.subarray[1].receptors) == 0 assert all([proxies.vcc[i + 1].subarrayMembership == 0 for", "proxies.fspSubarray[fsp_id].receptors == test_receptor_ids[0] assert proxies.fspSubarray[fsp_id].frequencyBand == band_index assert proxies.fspSubarray[fsp_id].frequencySliceID == fsp[\"frequency_slice_id\"] assert proxies.fspSubarray[fsp_id].integrationTime", "4])]) assert proxies.fspSubarray[1].obsState == ObsState.IDLE assert proxies.fspSubarray[3].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.IDLE", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[13][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[14][0] == 10416 # #", "proxies.subarray[1].RemoveAllReceptors() # proxies.subarray[1].AddReceptors([1, 3, 4]) # time.sleep(1) # assert proxies.subarray[1].receptors[0] == 1 #", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 2.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 2.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 2.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2]", "in receptor[\"receptorMatrix\"]: for index, value in enumerate(frequency_slice[\"matrix\"]): vcc_id = proxies.receptor_to_vcc[receptor[\"receptor\"]] fs_id = frequency_slice[\"fsid\"]", "pytest.raises(tango.DevFailed) as df: # proxies.subarray[1].AddReceptors([5]) # time.sleep(1) # assert \"Invalid receptor ID\" in", "configured attributes of VCC search windows # first for search window 1 of", "proxies.fspSubarray[fsp_id].fspChannelOffset == fsp[\"channel_offset\"] for i in range(len(fsp[\"channel_averaging_map\"])): for j in range(len(fsp[\"channel_averaging_map\"][i])): assert proxies.fspSubarray[fsp_id].channelAveragingMap[i][j]", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 4.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 4.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 4.4 time.sleep(10)", "of VCC belonging to receptor 1... assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].State() == DevState.DISABLE assert", "1][1].State() == DevState.DISABLE assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].searchWindowTuning == 7000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].tdcEnable", "12648 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[17][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[18][0] == 13392", "the command takes a while proxies.subarray[1].Init() time.sleep(3) cbf_master_proxy.set_timeout_millis(60000) cbf_master_proxy.Init() time.sleep(60) # takes pretty", "== 7000000000 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].tdcEnable == False assert fsp_3_proxies.subarray[1].receptors[0] == 3 assert", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[5][0] == 3720 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[5][1] == 8 # #", "# for proxy in vcc_proxies: # proxy.Init() # proxies.subarray[1].set_timeout_millis(60000) # subarray_2_proxy.set_timeout_millis(60000) # proxies.subarray[1].Init()", "ObsState.READY # ObsReset proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert len(proxies.subarray[1].receptors) == 0 assert", "ae except Exception as e: proxies.clean_proxies() raise e ''' def test_ConfigureScan_onlyPss_basic( self, cbf_master_proxy,", "0 assert proxies.subarray[1].configID == '' # TODO in CbfSubarray, at end of scan,", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 2.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 2.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 3.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4]", "1][0].tdcEnable == True # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcNumBits == 8 # assert vcc_tdc_proxies[receptor_to_vcc[1]", "proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBandOffsetStream1 == 0 assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBandOffsetStream2 == 0 assert proxies.vcc[proxies.receptor_to_vcc[4]].rfiFlaggingMask == \"{}\" # then", "== [ DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ] # check configured attributes of FSP", "- 1].subarrayMembership == 2 for i in [2, 4]]) # assert subarray_2_proxy.State() ==", "7000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].tdcEnable == False # check configured attributes of FSPs,", "assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcDestinationAddress == ( # \"fizz\", \"buzz\", \"80\" # ) #", "ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE ############################# abort from READY ########################### # add receptors", "20 # # assert fsp_2_proxies.subarray[1].corrBandwidth == 0 # # assert fsp_2_proxies.subarray[1].integrationTime == 1400", "1][0].State() == DevState.ON assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].searchWindowTuning == 6000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcEnable", "is invalid (e.g. out of range) - when a receptor to be removed", "assert proxies.fspSubarray[3].obsState == ObsState.SCANNING proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1, 1) assert proxies.subarray[1].obsState == ObsState.READY", "in weights[\"beamWeightsDetails\"]: rec_id = int(receptor[\"receptor\"]) fs_id = receptor[\"receptorWeightsDetails\"][0][\"fsid\"] for index, value in enumerate(receptor[\"receptorWeightsDetails\"][0][\"weights\"]):", "receptors # proxies.subarray[1].RemoveAllReceptors() # proxies.subarray[1].AddReceptors([1, 3, 4]) # time.sleep(1) # assert proxies.subarray[1].receptors[0] ==", "# with pytest.raises(tango.DevFailed) as df: # subarray_2_proxy.AddReceptors([1, 2, 4]) # time.sleep(1) # assert", "0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[9][0] == 6697 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[9][1] == 0", "as ae: raise ae except Exception as e: raise e time.sleep(10) # update", "ae except Exception as e: raise e time.sleep(10) # update timing beam weights", "subarray assert len(proxies.subarray[1].receptors) == 0 assert proxies.subarray[1].configID == '' assert proxies.subarray[1].frequencyBand == 0", "1].subarrayMembership == 0 for i in range(4)]) # add some receptors proxies.subarray[1].AddReceptors([1, 3,", "== True # assert sw_1_proxy.tdcNumBits == 8 # assert sw_1_proxy.tdcPeriodBeforeEpoch == 5 #", "# assert vcc_band_proxies[i].State() == DevState.ON # else: # assert vcc_band_proxies[i].State() == DevState.DISABLE #", "for j in range(len(fsp[\"output_link_map\"][i])): assert proxies.fspSubarray[fsp_id].outputLinkMap[i][j] == fsp[\"output_link_map\"][i][j] proxies.clean_proxies() except AssertionError as ae:", "model proxies.tm.beamWeights = json.dumps(timing_beam_weights) time.sleep(1) for weights in timing_beam_weights[\"beamWeights\"]: for receptor in weights[\"beamWeightsDetails\"]:", "== \"{}\" # assert tm_telstate_proxy.receivedOutputLinks == False # # add receptors # proxies.subarray[1].RemoveAllReceptors()", "7.25 # # assert fsp_2_proxies.subarray[1].frequencyBandOffsetStream1 == 0 # # assert fsp_2_proxies.subarray[1].frequencyBandOffsetStream2 == 0", "= open(file_path + config_file_name) json_string = f.read().replace(\"\\n\", \"\") input_config_dict = json.loads(json_string) proxies.subarray[subarr_index].ConfigureScan(json_string) f.close()", "vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcEnable == True # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcNumBits == 8 #", "in zip(range(num_receptors), input_receptors)]) assert proxies.subarray[subarr_index].obsState == ObsState.IDLE # Check fsp obsState BEFORE scan", "3.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 3.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 3.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 3.3", "1 assert fsp_1_proxies.subarray[1].corrBandwidth == 0 assert fsp_1_proxies.subarray[1].integrationTime == 1400 assert fsp_1_proxies.subarray[1].outputLinkMap[0][0] == 1", "# ) # then for search window 1 of VCC belonging to receptor", "VCC belonging to receptor 1... assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].State() == DevState.ON assert proxies.vccTdc[proxies.receptor_to_vcc[1]", "data from file f = open(file_path + \"/../data/delaymodel.json\") delay_model = json.loads(f.read().replace(\"\\n\", \"\")) f.close()", "== fsp[\"zoom_factor\"] if fsp[\"zoom_factor\"] > 0: assert proxies.fspSubarray[fsp_id].zoomWindowTuning == fsp[\"zoom_window_tuning\"] assert proxies.fspSubarray[fsp_id].fspChannelOffset ==", "ObsState.IDLE, 1, 1) assert len(proxies.subarray[1].receptors) == 0 assert proxies.fspSubarray[1].obsState == ObsState.IDLE assert proxies.fspSubarray[3].obsState", "7.25 assert proxies.fspSubarray[1].frequencyBandOffsetStream1 == 0 assert proxies.fspSubarray[1].frequencyBandOffsetStream2 == 0 assert proxies.fspSubarray[1].frequencySliceID == 1", "VCCs, including states of # frequency band capabilities logging.info( (\"proxies.vcc[vcc_index].frequencyBand = {}\". format(", "ObsState.READY assert proxies.fspSubarray[fsp_id].receptors == test_receptor_ids[0] assert proxies.fspSubarray[fsp_id].frequencyBand == band_index assert proxies.fspSubarray[fsp_id].frequencySliceID == fsp[\"frequency_slice_id\"]", "== 744 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[1][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[2][0] ==", "as e: raise e # transition to obsState == SCANNING f2 = open(file_path", "proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) # f.close() # time.sleep(15) # # check configured attributes of CBF", "# check configured attributes of CBF subarray # assert proxies.subarray[1].configID == \"band:5a, fsp1,", "for proxy in vcc_proxies: # proxy.Init() # fsp_1_proxies.subarray[1].Init() # fsp_2_proxies.subarray[1].Init() # fsp_3_proxies.subarray[1].Init() #", "proxies.controller.Init() proxies.wait_timeout_dev([proxies.controller], DevState.STANDBY, 3, 1) proxies.controller.On() proxies.wait_timeout_dev([proxies.controller], DevState.ON, 3, 1) proxies.clean_proxies() # turn", "in range(4)]: if proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) assert proxies.subarray[1].State()", "ae except Exception as e: raise e time.sleep(10) # Clean Up proxies.clean_proxies() except", "assert all([proxies.subarray[sub_id].receptors[i] == j for i, j in zip(range(len(test_receptor_ids)), test_receptor_ids)]) # configure scan", "fsp_2_proxies.subarray[1].channelAveragingMap[16][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[17][0] == 12649 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[17][1]", "fsp_1_proxies.subarray[1].outputLinkMap[1][0] == 201 assert fsp_1_proxies.subarray[1].outputLinkMap[1][1] == 1 proxies.subarray[1].GoToIdle() time.sleep(3) assert proxies.subarray[1].obsState == ObsState.IDLE", "assert fsp_1_proxies.subarray[1].channelAveragingMap[10][0] == 7440 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[10][1] == 8 # # assert", "dict([*map(int, pair.split(\":\"))] for pair in # cbf_controller_proxy.receptorToVcc) # cbf_controller_proxy.On() # time.sleep(3) # #", "8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[8][0] == 5952 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[8][1] == 8", "== 2976 assert proxies.fspSubarray[1].outputLinkMap[0][0] == 0 assert proxies.fspSubarray[1].outputLinkMap[0][1] == 4 assert proxies.fspSubarray[1].outputLinkMap[1][0] ==", "in range(len(fsp[\"output_link_map\"])): for j in range(len(fsp[\"output_link_map\"][i])): assert proxies.fspSubarray[fsp_id].outputLinkMap[i][j] == fsp[\"output_link_map\"][i][j] proxies.clean_proxies() except AssertionError", "== 0 # assert proxies.subarray[1].configID == 0 # assert proxies.subarray[1].frequencyBand == 0 #", "fsp_1_proxy.subarrayMembership # # assert 1 in fsp_2_proxy.subarrayMembership # assert [proxy.State() for proxy in", "def test_AddRemoveReceptors_invalid_multiple(self, proxies): \"\"\" Test invalid AddReceptors commands involving multiple subarrays: - when", "vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[0] == 5.85 assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[1] == 7.25 assert vcc_proxies[receptor_to_vcc[4]", "= {}\".format(vcc_index)) vcc_band_proxies = proxies.vccBand[vcc_index - 1] # turn on Subarray if proxies.subarray[sub_id].State()", "assert fsp_1_proxies.subarray[1].outputLinkMap[1][0] == 201 assert fsp_1_proxies.subarray[1].outputLinkMap[1][1] == 1 proxies.subarray[1].GoToIdle() time.sleep(3) assert proxies.subarray[1].obsState ==", "== 8 # assert fsp_1_proxies.subarray[1].outputLinkMap[2][0] == 1488 # assert fsp_1_proxies.subarray[1].outputLinkMap[2][1] == 12 #", "assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream2 == 0 # assert vcc_proxies[receptor_to_vcc[1] - 1].rfiFlaggingMask == \"{}\"", "as e: proxies.clean_proxies() raise e def test_Abort_Reset(self, proxies): \"\"\" Test abort reset \"\"\"", "Exception as e: proxies.clean_proxies() raise e def test_EndScan(self, proxies, input_test_data): \"\"\" Test the", "vcc_index = proxies.receptor_to_vcc[test_receptor_ids[0]] logging.info(\"vcc_index = {}\".format(vcc_index)) vcc_band_proxies = proxies.vccBand[vcc_index - 1] # turn", "in fsp_1_function_mode_proxy] == [ DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ] # assert [proxy.State() for", "for proxy in vcc_band_proxies[receptor_to_vcc[4] - 1]] == [ # DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON]", "== ObsState.READY assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[3].obsState == ObsState.READY # send the", "proxies.vcc[{}].receptorID = {}\". format(jj+1, proxies.vcc[jj+1].receptorID))) logging.info( (\"Vcc, receptor 1, ObsState = {}\". format(proxies.vcc[proxies.receptor_to_vcc[1]].ObsState))", "vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership == 1 # assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[0] == 5.85 #", "weights in timing_beam_weights[\"beamWeights\"]: for receptor in weights[\"beamWeightsDetails\"]: rec_id = int(receptor[\"receptor\"]) fs_id = receptor[\"receptorWeightsDetails\"][0][\"fsid\"]", "from ska_tango_base.control_model import AdminMode, ObsState from ska_tango_base.base_device import _DEBUGGER_PORT @pytest.mark.usefixtures(\"proxies\", \"input_test_data\") class TestCbfSubarray:", "the configured attributes of VCCs # # first for VCC belonging to receptor", "int(input_scan_dict[\"scan_id\"]) - 1 logging.info( \"proxies.fspCorrSubarray[subarr_index-1].obsState = {}\". format(proxies.fspCorrSubarray[subarr_index-1].obsState) ) logging.info( \"proxies.fspPssSubarray[subarr_index-1].obsState = {}\".", "except Exception as e: proxies.clean_proxies() raise e def test_ConfigureScan_jonesMatrix(self, proxies): \"\"\" Test the", "int(configuration[\"common\"][\"subarray_id\"]) assert proxies.subarray[sub_id].configID == configuration[\"common\"][\"config_id\"] assert proxies.subarray[sub_id].frequencyBand == band_index assert proxies.subarray[sub_id].obsState == ObsState.READY", "check configured attributes of FSP subarrays # first for FSP 1... (this is", "fsp_2_proxies.subarray[1].integrationTime == 1400 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[0][0] == 1 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[0][1]", "or edit attribute to accept string in FSP if fsp[\"function_mode\"] == \"CORR\": function_mode", "config_file_name) proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 15, 1) # check configured attributes of", "assert proxies.subarray[1].obsState == ObsState.EMPTY proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.OFF, 3, 1) except AssertionError as ae:", "== 2 assert proxies.fspSubarray[1].obsState == ObsState.SCANNING assert proxies.fspSubarray[3].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState ==", "== 0 # # assert fsp_2_proxies.subarray[1].frequencyBandOffsetStream2 == 0 # # assert fsp_2_proxies.subarray[1].frequencySliceID ==", "configured attributes of search windows # # first for search window 1... #", "== \"VLBI\": function_mode = 4 assert proxies.fsp[fsp_id].functionMode == function_mode assert sub_id in proxies.fsp[fsp_id].subarrayMembership", "4 # # assert fsp_2_proxies.subarray[1].frequencyBand == 4 # # assert fsp_2_proxies.subarray[1].band5Tuning[0] == 5.85", "obsState BEFORE scan configuration: assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.IDLE assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.IDLE assert", "input_test_data[1] subarr_index = 1; logging.info( \"input_receptors = {}\".format(input_receptors) ) logging.info( \"config_file_name = {}\".format(config_file_name)", "FSPs, including states of function mode capabilities assert proxies.fsp[1].functionMode == 1 assert 1", "3 assert proxies.subarray[1].receptors[2] == 4 # configure scan f = open(file_path + \"/test_json/test_ConfigureScan_onlyPss_basic.json\")", "assert fsp_2_proxies.subarray[1].channelAveragingMap[0][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[1][0] == 745 # # assert", "fsp_1_proxy, fsp_2_proxy, fsp_1_function_mode_proxy, fsp_2_function_mode_proxy, fsp_3_proxies.subarray[1], tm_telstate_proxy ): \"\"\" Test a minimal successful configuration", "receptor to be removed is not assigned to the subarray \"\"\" try: #", "# # # # Distributed under the terms of the BSD-3-Clause license. #", "= str(int(time.time()) + 10) # update Jones Matrix proxies.tm.jonesMatrix = json.dumps(jones_matrix) time.sleep(5) for", "# since the command takes a while # proxies.subarray[1].Init() # time.sleep(3) # cbf_master_proxy.set_timeout_millis(60000)", "== DevState.DISABLE # check configured attributes of FSPs, including states of function mode", ") raise ae except Exception as e: raise e time.sleep(10) for receptor in", "check configured attributes of CBF subarray assert proxies.subarray[1].configID == \"band:5a, fsp1, 744 channels", "# ] # # then for search window 2... # assert sw_2_proxy.State() ==", "proxies.subarray[1].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY assert proxies.fspSubarray[1].obsState", "fsp_1_proxies.subarray[1].channelAveragingMap[15][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[16][0] == 11904 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[16][1]", "11904 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[16][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[17][0] == 12648", "1][1].searchWindowTuning == 7000000000 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].tdcEnable == False # and lastly for", "raise ae except Exception as e: proxies.clean_proxies() raise e @pytest.mark.skip(reason=\"pst not currently supported\")", "of scan, clear all private data #assert proxies.subarray[sub_id].frequencyBand == 0 assert proxies.subarray[sub_id].obsState ==", "0 assert proxies.fspSubarray[1].channelAveragingMap[0][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[1][0] == 744 assert proxies.fspSubarray[1].channelAveragingMap[1][1] == 8", "first for FSP 3 ... (this is a PSS fsp device) assert proxies.fspSubarray[3].receptors[0]", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[1][0] == 744 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[1][1] == 8 #", "1].frequencyBandOffsetStream2 == 0 # assert vcc_proxies[receptor_to_vcc[4] - 1].rfiFlaggingMask == \"{}\" # # then", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[14][0] == 10416 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[14][1] == 8 # #", "time.sleep(1) for matrix in jones_matrix[\"jonesMatrix\"]: if matrix[\"destinationType\"] == \"fsp\": for receptor in matrix[\"matrixDetails\"]:", "assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand == 4 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand == 4 assert", "# assert proxies.subarray[1].configID == \"band:5a, fsp1, 744 channels average factor 8\" # assert", "mode capabilities assert fsp_1_proxy.functionMode == 1 assert 1 in fsp_1_proxy.subarrayMembership # assert 1", "proxies.subarray[sub_id].ConfigureScan(configuration) proxies.wait_timeout_obs([proxies.subarray[sub_id]], ObsState.READY, 15, 1) configuration = json.loads(configuration) band_index = freq_band_dict()[configuration[\"common\"][\"frequency_band\"]] # check", "cbf_master_proxy.set_timeout_millis(60000) # cbf_master_proxy.Init() # time.sleep(60) # takes pretty long for CBF Master to", "VCC belonging to receptor 10... # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].State() == DevState.DISABLE #", "sw_1_proxy.tdcNumBits == 8 # assert sw_1_proxy.tdcPeriodBeforeEpoch == 5 # assert sw_1_proxy.tdcPeriodAfterEpoch == 25", "\"/../data/jonesmatrix_fsp.json\") jones_matrix = json.loads(f.read().replace(\"\\n\", \"\")) epoch = str(int(time.time())) for matrix in jones_matrix[\"jonesMatrix\"]: matrix[\"epoch\"]", "1) assert len(proxies.subarray[1].receptors) == 0 assert proxies.fspSubarray[1].obsState == ObsState.IDLE assert proxies.fspSubarray[3].obsState == ObsState.IDLE", "ae except Exception as e: proxies.clean_proxies() raise e def test_ConfigureScan_minimal(self, proxies): try: sub_id", "1].subarrayMembership == 2 for i in [2, 4]]) # assert subarray_2_proxy.State() == DevState.ON", "proxies.tm.beamWeights = json.dumps(timing_beam_weights) time.sleep(1) for weights in timing_beam_weights[\"beamWeights\"]: for receptor in weights[\"beamWeightsDetails\"]: rec_id", "== 10417 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[14][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[15][0] ==", "assert fsp_1_proxies.subarray[1].channelAveragingMap[9][0] == 6696 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[9][1] == 8 # # assert", "subarrays: - when a receptor to be added is already in use by", "== ObsState.READY.value # # check frequency band of VCCs, including states of frequency", "fsp_1_proxies.subarray[1].channelAveragingMap[17][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[18][0] == 13392 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[18][1]", "- 1].frequencyBandOffsetStream1 == 0 assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream2 == 0 assert vcc_proxies[receptor_to_vcc[4] -", "proxies.subarray[1].receptors[2] == 4 # # configure scan # f = open(file_path + \"/test_json/test_ConfigureScan_basic.json\")", "proxies.vcc[proxies.receptor_to_vcc[1]].band5Tuning[1] == 7.25 # check configured attributes of search windows # first for", "1, 1) assert all([proxies.subarray[sub_id].receptors[i] == j for i, j in zip(range(len(test_receptor_ids)), test_receptor_ids)]) #", "j in zip(range(3), [1, 3, 4])]) # configure scan f = open(file_path +", "== 8 assert sw_1_proxy.tdcPeriodBeforeEpoch == 5 assert sw_1_proxy.tdcPeriodAfterEpoch == 25 assert \"\".join(sw_1_proxy.tdcDestinationAddress.split()) in", "== 5.85 # assert fsp_1_proxies.subarray[1].band5Tuning[1] == 7.25 # assert fsp_1_proxies.subarray[1].frequencyBandOffsetStream1 == 0 #", "= receptor[\"receptorDelayDetails\"][0][\"fsid\"] for index, value in enumerate(receptor[\"receptorDelayDetails\"][0][\"delayCoeff\"]): try: assert proxies.fsp[fs_id].delayModel[rec_id - 1][index] ==", "\"PST-BF\": # assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.READY proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise", "= {}\".format(proxy.State())) # for i in range(4): # if (i == 0 and", "= int(receptor[\"receptor\"]) fs_id = receptor[\"receptorDelayDetails\"][0][\"fsid\"] for index, value in enumerate(receptor[\"receptorDelayDetails\"][0][\"delayCoeff\"]): try: assert proxies.fsp[fs_id].delayModel[rec_id", "1 assert proxies.subarray[1].receptors[1] == 3 assert proxies.subarray[1].receptors[2] == 4 # configure scan f", "for proxy in fsp_1_function_mode_proxy] == [ # DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE # ]", "DevState.DISABLE, DevState.DISABLE # # ] # # check configured attributes of FSP subarrays", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[13][0] == 9673 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[13][1] == 0 #", "str(proxies.fspSubarray[1].visDestinationAddress).replace('\"',\"'\") == \\ str({\"outputHost\": [[0, \"192.168.0.1\"], [8184, \"192.168.0.2\"]], \"outputMac\": [[0, \"06-00-00-00-00-01\"]], \"outputPort\": [[0,", "4]]) assert proxies.vcc[proxies.receptor_to_vcc[3]].subarrayMembership == 1 # remove remaining receptors proxies.subarray[1].RemoveReceptors([3]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1,", "f2.read().replace(\"\\n\", \"\") input_scan_dict = json.loads(json_string) proxies.subarray[subarr_index].Scan(json_string) f2.close() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.SCANNING, 1, 1) # Note:", "proxies.clean_proxies() raise e def test_Abort_Reset(self, proxies): \"\"\" Test abort reset \"\"\" try: #", "turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.ON, 3, 1) for", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 2.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 2.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 2.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1]", "assert searchBeam400[\"searchBeamID\"] == 400 assert searchBeam400[\"receptors\"][0] == 1 assert searchBeam400[\"outputEnable\"] == True assert", "for matrix in jones_matrix[\"jonesMatrix\"]: if matrix[\"destinationType\"] == \"fsp\": for receptor in matrix[\"matrixDetails\"]: rec_id", "proxies.subarray[1].frequencyBand == 4 # means 5a? # assert proxies.subarray[1].obsState.value == ObsState.READY.value # #", "== ObsState.SCANNING assert proxies.fspSubarray[1].obsState == ObsState.SCANNING assert proxies.fspSubarray[3].obsState == ObsState.SCANNING proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY,", "assert proxies.fspSubarray[1].frequencySliceID == 1 assert proxies.fspSubarray[1].corrBandwidth == 1 assert proxies.fspSubarray[1].zoomWindowTuning == 4700000 assert", "for index, value in enumerate(receptor[\"receptorDelayDetails\"][0][\"delayCoeff\"]): try: assert proxies.fsp[fs_id].delayModel[rec_id - 1][index] == value except", "= receptor[\"receptorMatrix\"][0][\"fsid\"] for index, value in enumerate(receptor[\"receptorMatrix\"][0][\"matrix\"]): try: assert proxies.fsp[fs_id].jonesMatrix[rec_id - 1][index] ==", "check initial value of attributes of CBF subarray vcc_index = proxies.receptor_to_vcc[4] logging.info(\"vcc_index =", "########################### # add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) #", "- 1].subarrayMembership == 1 for i in [1, 3]]) # assert all([vcc_proxies[receptor_to_vcc[i] -", "== 4 # TODO - this does not pass - to debug &", "0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[1][0] == 745 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[1][1] == 0", "of VCC belonging to receptor 10... assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].State() == DevState.DISABLE assert", "proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBand == 4 assert proxies.vcc[proxies.receptor_to_vcc[1]].frequencyBand == 4 for proxy in proxies.vccBand[proxies.receptor_to_vcc[4] - 1]:", "== 1.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 1.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 2.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] ==", "for receptor in matrix[\"matrixDetails\"]: rec_id = int(receptor[\"receptor\"]) fs_id = receptor[\"receptorMatrix\"][0][\"fsid\"] for index, value", "assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcNumBits == 8 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch == 5 assert", "fsp[\"channel_offset\"] for i in range(len(fsp[\"channel_averaging_map\"])): for j in range(len(fsp[\"channel_averaging_map\"][i])): assert proxies.fspSubarray[fsp_id].channelAveragingMap[i][j] == fsp[\"channel_averaging_map\"][i][j]", "2976 assert proxies.fspSubarray[1].outputLinkMap[0][0] == 0 assert proxies.fspSubarray[1].outputLinkMap[0][1] == 4 assert proxies.fspSubarray[1].outputLinkMap[1][0] == 744", "proxies.subarray[1].State() == DevState.ON # # try adding some receptors (including an invalid one)", "update delay model proxies.tm.delayModel = json.dumps(delay_model) time.sleep(1) for model in delay_model[\"delayModel\"]: if model[\"destinationType\"]", "fsp_1_proxies.subarray[1].channelAveragingMap[11][0] == 8184 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[11][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[12][0]", "assert len(proxies.subarray[1].receptors) == 0 # assert proxies.subarray[1].configID == 0 # assert proxies.subarray[1].frequencyBand ==", "assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].searchWindowTuning == 7000000000 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].tdcEnable == False #", "== ObsState.IDLE ############################# abort from READY ########################### # add receptors proxies.subarray[1].AddReceptors([1, 3, 4,", "0 assert fsp_1_proxies.subarray[1].integrationTime == 1400 assert fsp_1_proxies.subarray[1].outputLinkMap[0][0] == 1 assert fsp_1_proxies.subarray[1].outputLinkMap[0][1] == 0", "1) # configure scan f = open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]],", "assert fsp_1_proxy.functionMode == 1 assert 1 in fsp_1_proxy.subarrayMembership # assert 1 in fsp_2_proxy.subarrayMembership", "\"First vcc obsState AFTER ConfigureScan = {}\". format(proxies.vcc[vcc_ids[0]].obsState) ) # check some configured", "2.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 3.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 3.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 3.2", "fsp[\"function_mode\"] == \"VLBI\": function_mode = 4 assert proxies.fsp[fsp_id].functionMode == function_mode assert sub_id in", "stored by the device # as a json string ( via attribute 'searchBeams');", "window 1 of VCC belonging to receptor 1... assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].State() ==", "assert vcc_band_proxies[i].State() == DevState.ON # else: # assert vcc_band_proxies[i].State() == DevState.DISABLE # check", "proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch == 25 # TODO - re-enable and debug! # assert", "== 0 assert proxies.subarray[1].configID == '' assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState ==", "ObsState.EMPTY, 1, 1) assert len(proxies.subarray[1].receptors) == 0 assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 0 for i", "attributes of search windows # # first for search window 1... # assert", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[2][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[3][0] == 2232 #", "except Exception as e: raise e time.sleep(10) for receptor in jones_matrix[\"jonesMatrix\"][0][\"matrixDetails\"]: for frequency_slice", "fsp_1_function_mode_proxy] == [ # DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE # ] # # assert", "frequency_band = input_config_dict[\"common\"][\"frequency_band\"] input_band_index = freq_band_dict()[frequency_band] assert proxies.subarray[subarr_index].configID == input_config_dict[\"common\"][\"config_id\"] assert proxies.subarray[subarr_index].frequencyBand ==", "proxies.vcc[vcc_id].jonesMatrix[fs_id-1]) ) raise ae except Exception as e: raise e # transition to", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[16][0] == 11904 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[16][1] == 8 # #", "in between # configurations or causing a fault within the Vcc device #", "= proxies.fspSubarray[3].searchBeams searchBeam0 = json.loads(searchBeam[0]) searchBeam1 = json.loads(searchBeam[1]) assert searchBeam0[\"search_beam_id\"] == 300 assert", "model in delay_model[\"delayModel\"]: if model[\"destinationType\"] == \"fsp\": for receptor in model[\"delayDetails\"]: rec_id =", "\"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", # ] # # then for search window", "# assert fsp_1_proxies.subarray[1].outputLinkMap[1][1] == 8 # assert fsp_1_proxies.subarray[1].outputLinkMap[2][0] == 1488 # assert fsp_1_proxies.subarray[1].outputLinkMap[2][1]", "assert [proxy.State() for proxy in fsp_function_mode_proxies[fsp_id-1]] == [ DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ]", "in zip(range(3), [1, 3, 4])]) assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for i in [1,", "assert [proxies.subarray[1].receptors[i] for i in range(3)] == input_receptors assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for", "receptor 1... assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].State() == DevState.DISABLE assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].searchWindowTuning ==", "0 for i in range(4)]) # add some receptors to subarray 1 proxies.subarray[1].AddReceptors([1,", "of CBF subarray assert proxies.subarray[1].configID == \"band:5a, fsp1, 744 channels average factor 8\"", "== 4.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 4.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 4.4 time.sleep(10) assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0]", "0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[7][0] == 5209 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[7][1] == 0", "== 2 # TODO - this does not pass - to debug &", "receptor 1... # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].State() == DevState.ON # assert vcc_tdc_proxies[receptor_to_vcc[1] -", "proxies.fspSubarray[1].zoomWindowTuning == 4700000 assert proxies.fspSubarray[1].integrationTime == 1 assert proxies.fspSubarray[1].fspChannelOffset == 14880 assert proxies.fspSubarray[1].channelAveragingMap[0][0]", "== ObsState.EMPTY # # assert tm_telstate_proxy.visDestinationAddress == \"{}\" # assert tm_telstate_proxy.receivedOutputLinks == False", "8\" assert proxies.subarray[1].frequencyBand == 4 assert proxies.subarray[1].obsState == ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i + 1] for", "1 for i in input_receptors]) assert proxies.subarray[1].obsState == ObsState.IDLE # add more receptors...", "scan f2 = open(file_path + \"/../data/Scan2_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1)", "[2])]) assert all([proxies.fspSubarray[6].timingBeamID[i] == j for i, j in zip(range(1), [10])]) # Clean", "if proxies.subarray[sub_id].State() != DevState.ON: proxies.subarray[sub_id].On() proxies.wait_timeout_dev([proxies.subarray[sub_id]], DevState.ON, 3, 1) for proxy in [proxies.vcc[i", "enumerate(receptor[\"receptorMatrix\"][0][\"matrix\"]): try: assert proxies.fsp[fs_id].jonesMatrix[rec_id - 1][index] == value except AssertionError as ae: raise", "proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.ON, 3, 1) for proxy in [proxies.vcc[i +", "logging.info( \"proxies.fspPssSubarray[subarr_index-1].obsState = {}\". format(proxies.fspPssSubarray[subarr_index-1].obsState) ) logging.info( \"proxies.fspPstSubarray[subarr_index-1].obsState = {}\". format(proxies.fspPstSubarray[subarr_index-1].obsState) ) #", "of CBF subarray # assert len(proxies.subarray[1].receptors) == 0 # assert proxies.subarray[1].configID == 0", "assert fsp_1_proxies.subarray[1].band5Tuning[0] == 5.85 # assert fsp_1_proxies.subarray[1].band5Tuning[1] == 7.25 # assert fsp_1_proxies.subarray[1].frequencyBandOffsetStream1 ==", "len(proxies.subarray[sub_id].receptors) == 0 assert proxies.subarray[sub_id].configID == '' # TODO in CbfSubarray, at end", "configured attributes of CBF subarray frequency_band = input_config_dict[\"common\"][\"frequency_band\"] input_band_index = freq_band_dict()[frequency_band] assert proxies.subarray[subarr_index].configID", "assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch == 5 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch == 25", "assert proxies.subarray[1].receptors[1] == 3 # assert proxies.subarray[1].receptors[2] == 4 # # configure scan", "in zip(range(3), [1, 3, 4])]) # configure scan config_file_name = \"/../data/ConfigureScan_basic.json\" f =", "- 1][1].tdcEnable == False # check configured attributes of FSPs, including states of", "of VCC search windows # first for search window 1 of VCC belonging", "8 assert proxies.fspSubarray[1].outputLinkMap[2][0] == 1488 assert proxies.fspSubarray[1].outputLinkMap[2][1] == 12 assert proxies.fspSubarray[1].outputLinkMap[3][0] == 2232", "DevState.DISABLE, DevState.DISABLE, DevState.DISABLE # ] # check configured attributes of FSP subarrays #", "f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) assert proxies.subarray[1].obsState == ObsState.READY assert proxies.fspSubarray[1].obsState == ObsState.READY", "assert sw_1_proxy.State() == DevState.ON # assert sw_1_proxy.searchWindowTuning == 6000000000 # assert sw_1_proxy.tdcEnable ==", "for i, j in zip(range(3), [1, 3, 4])]) assert proxies.fspSubarray[1].obsState == ObsState.IDLE assert", "assert proxies.sw[1].tdcPeriodAfterEpoch == 25 # assert \"\".join(proxies.sw[1].tdcDestinationAddress.split()) in [ # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\",", "3.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 3.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 3.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 3.3", "# update delay models from tm emulator f = open(file_path + \"/../data/delaymodel_fsp.json\") delay_model", "# assert fsp_1_proxies.subarray[1].fspChannelOffset == 14880 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[0][0] == 0 # #", "assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE proxies.clean_proxies() except AssertionError as ae:", "DevState.DISABLE, DevState.DISABLE, DevState.ON] # # check the rest of the configured attributes of", "vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].State() == DevState.ON # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].searchWindowTuning == 6000000000 #", "== 1.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 1.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 1.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] ==", "model[\"epoch\"] = epoch if model[\"destinationType\"] == \"fsp\": epoch = str(int(epoch) + 10) #", "assert proxies.subarray[1].configID == \"band:5a, fsp1, 744 channels average factor 8\" assert proxies.subarray[1].frequencyBand ==", "\"\"\" Test abort reset \"\"\" try: # turn on Subarray if proxies.subarray[1].State() !=", "ObsState.SCANNING assert proxies.vcc[vcc_ids[num_receptors-1]].obsState == ObsState.SCANNING for fsp in input_config_dict[\"cbf\"][\"fsp\"]: if fsp[\"function_mode\"] == \"CORR\":", "2.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 2.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 2.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 3.0", "assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[3].obsState == ObsState.READY # send the Scan command", "# assert proxies.subarray[1].receptors == (1, 3) # assert all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership == 1", "4])]) # configure scan config_file_name = \"/../data/ConfigureScan_basic.json\" f = open(file_path + config_file_name) proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\",", "ae: proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e @pytest.mark.skip(reason=\"Since there's", "== 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[18][0] == 13392 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[18][1] ==", "# assert proxies.subarray[1].receptors[1] == 3 # assert proxies.subarray[1].receptors[2] == 4 # # configure", "sub_id == int(configuration[\"common\"][\"subarray_id\"]) assert proxies.subarray[sub_id].configID == configuration[\"common\"][\"config_id\"] assert proxies.subarray[sub_id].frequencyBand == band_index assert proxies.subarray[sub_id].obsState", "== test_receptor_ids[0] assert proxies.fspSubarray[fsp_id].frequencyBand == band_index assert proxies.fspSubarray[fsp_id].frequencySliceID == fsp[\"frequency_slice_id\"] assert proxies.fspSubarray[fsp_id].integrationTime ==", "DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ] # TODO - # assert [proxy.State() for proxy in", "takes pretty long for CBF controller to initialize # receptor_to_vcc = dict([*map(int, pair.split(\":\"))]", "proxies.subarray[1].obsState == ObsState.EMPTY # Input test data: input_receptors = input_test_data[0] config_file_name = input_test_data[1]", "# check configured attributes of CBF subarray # def test_ConfigureScan_basic( # self, #", "value of attributes of CBF subarray assert len(proxies.subarray[1].receptors) == 0 assert proxies.subarray[1].configID ==", "# update timing beam weights from tm emulator f = open(file_path + \"/../data/timingbeamweights.json\")", "ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED # ObsReset proxies.subarray[1].ObsReset() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1,", "str(int(epoch) + 10) # update delay model proxies.tm.delayModel = json.dumps(delay_model) time.sleep(1) for model", "initialization assert len(proxies.subarray[1].receptors) == 0 assert all([proxies.vcc[i + 1].subarrayMembership == 0 for i", "( # \"fizz\", \"buzz\", \"80\" # ) # then for search window 2", "# print(\"proxies.sw[2].State() = {}\".format(proxies.sw[2].State())) # assert proxies.sw[1].State() == DevState.ON # assert proxies.sw[1].searchWindowTuning ==", "3.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 3.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 3.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 3.4", "False # # check configured attributes of VCC search windows # # first", "verify delay model values against input json @pytest.mark.skip(reason=\"test needs to be refactored\") def", "FSP 1... (this is a CORR fsp device) assert proxies.fspSubarray[1].obsState == ObsState.READY assert", "assert proxies.fspSubarray[1].channelAveragingMap[2][0] == 1488 assert proxies.fspSubarray[1].channelAveragingMap[2][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[3][0] == 2232 assert", "fsp_1_proxies.subarray[1].channelAveragingMap[4][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[5][0] == 3720 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[5][1]", "emulator f = open(file_path + \"/../data/timingbeamweights.json\") timing_beam_weights = json.loads(f.read().replace(\"\\n\", \"\")) epoch = str(int(time.time()))", "raise ae except Exception as e: proxies.clean_proxies() raise e def test_ConfigureScan_minimal(self, proxies): try:", "ae: proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e #TODO: fix;", "fsp_2_proxies.subarray[1].channelAveragingMap[7][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[8][0] == 5953 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[8][1]", "1, 1) assert proxies.subarray[1].obsState == ObsState.READY # Clean Up proxies.clean_proxies() except AssertionError as", "assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch == 5 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch == 25 #", "== 3.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 3.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 3.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] ==", "-*- # # This file is part of the csp-lmc-prototype project # #", "for CBF Master to initialize tm_telstate_proxy.Init() time.sleep(1) receptor_to_vcc = dict([*map(int, pair.split(\":\"))] for pair", "configured attributes of VCCs # first for VCC belonging to receptor 2... assert", "proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 15, 1) # check configured attributes of CBF", "tm emulator f = open(file_path + \"/../data/jonesmatrix_fsp.json\") jones_matrix = json.loads(f.read().replace(\"\\n\", \"\")) epoch =", "assert proxies.subarray[1].ObsState == ObsState.EMPTY # # assert tm_telstate_proxy.visDestinationAddress == \"{}\" # assert tm_telstate_proxy.receivedOutputLinks", "configured attributes of CBF subarray assert proxies.subarray[1].configID == \"band:5a, fsp1, 744 channels average", "DevState.DISABLE assert sw_2_proxy.searchWindowTuning == 7000000000 assert sw_2_proxy.tdcEnable == False # check configured attributes", "assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].tdcEnable == False # # check configured attributes of FSPs,", "try: sub_id = 1 #TODO currently only support for 1 receptor per fsp", "# cbf_master_proxy.On() # time.sleep(60) # # turn on Subarray # assert proxies.subarray[1].state()==DevState.OFF #", "proxies.sw[2].tdcEnable == False time.sleep(1) # check configured attributes of VCC search windows #", "open(file_path + config_file_name) json_string = f.read().replace(\"\\n\", \"\") input_config_dict = json.loads(json_string) proxies.subarray[subarr_index].ConfigureScan(json_string) f.close() proxies.wait_timeout_obs([proxies.subarray[subarr_index]],", "5.85 assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[1] == 7.25 assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream1 == 0", "= json.loads(f.read().replace(\"\\n\", \"\")) epoch = str(int(time.time())) for matrix in jones_matrix[\"jonesMatrix\"]: matrix[\"epoch\"] = epoch", "= proxies.receptor_to_vcc[receptor_id] proxies.subarray[subarr_index].AddReceptors(input_receptors) proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[subarr_index].receptors[i] == j for i,", "- 1][0].searchWindowTuning == 6000000000 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcEnable == True # assert", "# assert tm_telstate_proxy.receivedOutputLinks == False # # add receptors # proxies.subarray[1].RemoveAllReceptors() # proxies.subarray[1].AddReceptors([1,", "DevState.DISABLE, DevState.ON] # # check the rest of the configured attributes of VCCs", "assert proxies.subarray[subarr_index].obsState == ObsState.IDLE # Check fsp obsState BEFORE scan configuration: assert proxies.fspCorrSubarray[subarr_index-1].obsState", "# proxies.subarray[1].set_timeout_millis(60000) # since the command takes a while # proxies.subarray[1].Init() # time.sleep(3)", "proxies): \"\"\" Test abort restart \"\"\" try: # turn on Subarray if proxies.subarray[1].State()", "== 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[17][0] == 12649 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[17][1] ==", "assert sw_2_proxy.searchWindowTuning == 7000000000 # assert sw_2_proxy.tdcEnable == False # # check configured", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[11][0] == 8185 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[11][1] == 0 # #", "vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcEnable == True assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcNumBits == 8 assert vcc_tdc_proxies[receptor_to_vcc[4]", "in CbfSubarray, at end of scan, clear all private data #assert proxies.subarray[1].frequencyBand ==", "is a CORR fsp device) assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[1].receptors == 4", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[1].receptors[i] == j for i, j in zip(range(3),", "of function mode capabilities # assert fsp_1_proxy.functionMode == 1 # assert 1 in", "1][index] == value except AssertionError as ae: raise ae except Exception as e:", "in [proxies.vcc[i + 1] for i in range(4)]: if proxy.State() == DevState.OFF: proxy.On()", "LoggingLevel, HealthState from ska_tango_base.control_model import AdminMode, ObsState from ska_tango_base.base_device import _DEBUGGER_PORT @pytest.mark.usefixtures(\"proxies\", \"input_test_data\")", "# check initial states assert proxies.subarray[1].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert", "assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcDestinationAddress == ( \"fizz\", \"buzz\", \"80\" ) # then for", "assert searchBeam0[\"enable_output\"] == True assert searchBeam0[\"averaging_interval\"] == 4 # TODO - this does", "time.sleep(60) # takes pretty long for CBF Master to initialize tm_telstate_proxy.Init() time.sleep(1) receptor_to_vcc", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[17][0] == 12648 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[17][1] == 8 #", "fsp_1_proxies.subarray[1].receptors == 4 # assert fsp_1_proxies.subarray[1].frequencyBand == 4 # assert fsp_1_proxies.subarray[1].band5Tuning[0] == 5.85", "assert vcc_proxies[receptor_to_vcc[4] - 1].rfiFlaggingMask == \"{}\" # # then for VCC belonging to", "proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[1].receptors[i] == j for", "7441 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[10][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[11][0] == 8185", "15, 1) # check configured attributes of CBF subarray assert proxies.subarray[1].configID == \"band:5a,", "proxies.subarray[subarr_index].configID == input_config_dict[\"common\"][\"config_id\"] assert proxies.subarray[subarr_index].frequencyBand == input_band_index assert proxies.subarray[subarr_index].obsState == ObsState.READY # Send", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[0][0] == 0 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[0][1] == 8 # #", "0 for i in [1, 3, 4]]) assert proxies.subarray[1].obsState == ObsState.EMPTY proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]],", "proxies.vcc[vcc_ids[0]].obsState == ObsState.SCANNING assert proxies.vcc[vcc_ids[num_receptors-1]].obsState == ObsState.SCANNING for fsp in input_config_dict[\"cbf\"][\"fsp\"]: if fsp[\"function_mode\"]", "\"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) assert proxies.subarray[1].obsState == ObsState.SCANNING time.sleep(10)", "proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY # Input test data: input_receptors", "proxies.subarray[1].frequencyBand == 4 # means 5a assert proxies.subarray[1].obsState == ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i + 1]", "proxies.vcc[vcc_id].jonesMatrix[fs_id-1]) ) raise ae except Exception as e: raise e time.sleep(10) for receptor", "def test_ConfigureScan_delayModel(self, proxies): \"\"\" Test the reception of delay models \"\"\" # Read", "data: input_receptors = input_test_data[0] config_file_name = input_test_data[1] subarr_index = 1; logging.info( \"input_receptors =", "assert fsp_2_proxies.subarray[1].channelAveragingMap[14][0] == 10417 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[14][1] == 0 # # assert", "ObsState.READY, 1, 1) proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae except Exception", "(this is a PSS fsp device) assert proxies.fspSubarray[3].receptors[0] == 3 assert proxies.fspSubarray[3].receptors[1] ==", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[2][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[3][0] == 2233 #", "== band_index assert proxies.fspSubarray[fsp_id].frequencySliceID == fsp[\"frequency_slice_id\"] assert proxies.fspSubarray[fsp_id].integrationTime == fsp[\"integration_factor\"] assert proxies.fspSubarray[fsp_id].corrBandwidth ==", "0 assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 0 for i in [1, 3, 4]]) assert proxies.subarray[1].obsState", "CBF controller to initialize # receptor_to_vcc = dict([*map(int, pair.split(\":\"))] for pair in #", "searchBeam = fsp_3_proxies.subarray[1].searchBeams searchBeam300 = json.loads(searchBeam[0]) searchBeam400 = json.loads(searchBeam[1]) assert searchBeam300[\"searchBeamID\"] == 300", "proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.READY, 1, 1) # Check obsStates AFTER the EndScan() command assert proxies.subarray[subarr_index].obsState", "open(file_path + \"/../data/delaymodel_fsp.json\") delay_model = json.loads(f.read().replace(\"\\n\", \"\")) epoch = str(int(time.time())) for model in", "attributes of CBF subarray # def test_ConfigureScan_basic( # self, # cbf_master_proxy, # proxies.subarray[1],", "align IDs of fspSubarrays to fsp_id in conftest; currently works for fsps 1", "1].band5Tuning[0] == 5.85 # assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[1] == 7.25 # assert vcc_proxies[receptor_to_vcc[1]", "the configured attributes of VCCs # first for VCC belonging to receptor 10...", "1, 1) assert len(proxies.subarray[1].receptors) == 0 assert proxies.fspSubarray[1].obsState == ObsState.IDLE assert proxies.fspSubarray[3].obsState ==", "== ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY # abort proxies.subarray[1].Abort()", "proxy in [proxies.fsp[i + 1] for i in range(4)]: if proxy.State() == DevState.OFF:", "DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE # ] # check configured attributes of FSP subarrays", "== 0.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 0.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 0.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] ==", "vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcDestinationAddress == ( # \"fizz\", \"buzz\", \"80\" # ) # #", "fsp_1_proxies.subarray[1].obsState == ObsState.EMPTY # assert fsp_1_proxies.subarray[1].receptors == 4 # assert fsp_1_proxies.subarray[1].frequencyBand == 4", "1) assert [proxies.subarray[1].receptors[i] for i in range(3)] == input_receptors assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1", "delay_model[\"delayModel\"]: model[\"epoch\"] = epoch if model[\"destinationType\"] == \"fsp\": epoch = str(int(epoch) + 10)", "proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) # check initial value of attributes of CBF", "300 # assert searchBeam300[\"receptors\"][0] == 3 # assert searchBeam300[\"outputEnable\"] == True # assert", "since the command takes a while proxies.subarray[1].Init() time.sleep(3) cbf_master_proxy.set_timeout_millis(60000) cbf_master_proxy.Init() time.sleep(60) # takes", "@pytest.mark.skip(reason=\"pst not currently supported\") def test_ConfigureScan_onlyPst_basic_FSP_scan_parameters(self, proxies): \"\"\" Test a successful transmission of", "os import time from datetime import datetime import json import logging # Path", "as df: # proxies.subarray[1].AddReceptors([5]) # time.sleep(1) # assert \"Invalid receptor ID\" in str(df.value.args[0].desc)", "assert fsp_1_proxies.subarray[1].channelAveragingMap[3][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[4][0] == 2976 # # assert", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[3][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[4][0] == 2976 #", "1][0].tdcPeriodBeforeEpoch == 5 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch == 25 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcDestinationAddress", "assert fsp_1_proxies.subarray[1].channelAveragingMap[7][0] == 5208 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[7][1] == 8 # # assert", "assert proxies.vcc[vcc_ids[num_receptors-1]].obsState == ObsState.SCANNING for fsp in input_config_dict[\"cbf\"][\"fsp\"]: if fsp[\"function_mode\"] == \"CORR\": assert", "and RemoveReceptors commands \"\"\" timeout_millis = proxies.subarray[1].get_timeout_millis() log_msg = \"timeout_millis = {} \".format(timeout_millis)", "zip(range(3), [1, 3, 4])]) # configure scan f = open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\",", "1] assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBand == 4 assert proxies.vcc[proxies.receptor_to_vcc[1]].frequencyBand == 4 for proxy in proxies.vccBand[proxies.receptor_to_vcc[4]", "assert tm_telstate_proxy.receivedOutputLinks == False # add receptors proxies.subarray[1].AddReceptors([1, 3, 4]) time.sleep(1) assert proxies.subarray[1].receptors[0]", "5.85 assert proxies.fspSubarray[1].band5Tuning[1] == 7.25 assert proxies.fspSubarray[1].frequencyBandOffsetStream1 == 0 assert proxies.fspSubarray[1].frequencyBandOffsetStream2 == 0", "- 1][0].tdcDestinationAddress == ( # \"foo\", \"bar\", \"8080\" # ) # # then", "assert sw_2_proxy.State() == DevState.DISABLE assert sw_2_proxy.searchWindowTuning == 7000000000 assert sw_2_proxy.tdcEnable == False #", "json.loads(searchBeam[1]) # assert searchBeam300[\"searchBeamID\"] == 300 # assert searchBeam300[\"receptors\"][0] == 3 # assert", "1, 1) for proxy in [proxies.fsp[i + 1] for i in range(4)]: if", "- 1].frequencyBand == 4 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand == 4 assert [proxy.State() for", "== 0) or (i == (band_index - 1)): # assert vcc_band_proxies[i].State() == DevState.ON", "assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[1] == 7.25 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream1 == 0 assert", "assert len(proxies.subarray[1].receptors) == 0 assert proxies.fspSubarray[1].obsState == ObsState.IDLE assert proxies.fspSubarray[3].obsState == ObsState.IDLE assert", "Send the Scan command f2 = open(file_path + \"/../data/Scan1_basic.json\") json_string = f2.read().replace(\"\\n\", \"\")", "ObsState.IDLE, 1, 1) assert all([proxies.subarray[1].receptors[i] == j for i, j in zip(range(4), [4,", "check configured attributes of CBF subarray assert sub_id == int(configuration[\"common\"][\"subarray_id\"]) assert proxies.subarray[sub_id].configID ==", "in zip(range(4), [4, 1, 3, 2])]) # configure scan f = open(file_path +", "1][1].searchWindowTuning == 7000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].tdcEnable == False # and lastly for", "vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].State() == DevState.DISABLE assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].searchWindowTuning == 7000000000 assert vcc_tdc_proxies[receptor_to_vcc[1]", "- 1] assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBand == 4 assert proxies.vcc[proxies.receptor_to_vcc[1]].frequencyBand == 4 for proxy in", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 3.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 4.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 4.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3]", "attributes of CBF subarray assert sub_id == int(configuration[\"common\"][\"subarray_id\"]) assert proxies.subarray[sub_id].configID == configuration[\"common\"][\"config_id\"] assert", "value of attributes of CBF subarray # assert proxies.subarray[1].receptors == () # assert", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[6][0] == 4464 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[6][1] == 8 #", "+ config_file_name) proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 15, 1) # check configured attributes", "proxy in proxies.fsp1FunctionMode] == [ DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ] # TODO -", "assert proxies.fspSubarray[1].outputLinkMap[2][0] == 1488 assert proxies.fspSubarray[1].outputLinkMap[2][1] == 12 assert proxies.fspSubarray[1].outputLinkMap[3][0] == 2232 assert", "== ObsState.READY assert fsp_1_proxies.subarray[1].frequencyBand == 0 assert fsp_1_proxies.subarray[1].frequencySliceID == 1 assert fsp_1_proxies.subarray[1].corrBandwidth ==", "== ObsState.READY assert proxies.fspSubarray[1].receptors == 4 assert proxies.fspSubarray[1].frequencyBand == 4 assert proxies.fspSubarray[1].band5Tuning[0] ==", "6000000000 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcEnable == True assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcNumBits == 8", "# # assert fsp_2_proxies.subarray[1].frequencyBand == 4 # # assert fsp_2_proxies.subarray[1].band5Tuning[0] == 5.85 #", "\"\")) f.close() jones_matrix[\"jonesMatrix\"][0][\"epoch\"] = str(int(time.time()) + 20) jones_matrix[\"jonesMatrix\"][1][\"epoch\"] = \"0\" jones_matrix[\"jonesMatrix\"][2][\"epoch\"] = str(int(time.time())", "assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].tdcEnable == False # and lastly for search window 2", "of VCC belonging to receptor 10... assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].State() == DevState.ON assert", "# assert sw_1_proxy.State() == DevState.ON # assert sw_1_proxy.searchWindowTuning == 6000000000 # assert sw_1_proxy.tdcEnable", "for j in range(len(fsp[\"channel_averaging_map\"][i])): assert proxies.fspSubarray[fsp_id].channelAveragingMap[i][j] == fsp[\"channel_averaging_map\"][i][j] for i in range(len(fsp[\"output_link_map\"])): for", "assert \"Invalid receptor ID\" in str(df.value.args[0].desc) # try removing a receptor not assigned", "assert proxies.fsp[2].State() == DevState.ON assert proxies.fsp[2].functionMode == 3 assert 1 in proxies.fsp[2].subarrayMembership assert", "in jones_matrix[\"jonesMatrix\"]: if matrix[\"destinationType\"] == \"fsp\": for receptor in matrix[\"matrixDetails\"]: rec_id = int(receptor[\"receptor\"])", "configured attributes of FSP subarrays # # first for FSP 1... # assert", "and debug! # assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcDestinationAddress == ( # \"foo\", \"bar\", \"8080\"", "== 0 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand == 0 # check the rest of", "# Test a minimal successful configuration # \"\"\" # for proxy in vcc_proxies:", "proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies()", "emulator f = open(file_path + \"/../data/jonesmatrix_fsp.json\") jones_matrix = json.loads(f.read().replace(\"\\n\", \"\")) epoch = str(int(time.time()))", "1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED # Restart: receptors should be empty proxies.subarray[1].Restart()", "reset \"\"\" try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On() proxies.wait_timeout_dev([proxies.subarray[1]],", "frequency band of VCCs, including states of frequency band capabilities assert vcc_proxies[receptor_to_vcc[4] -", "open(file_path + \"/../data/jonesmatrix.json\") jones_matrix = json.loads(f.read().replace(\"\\n\", \"\")) f.close() jones_matrix[\"jonesMatrix\"][0][\"epoch\"] = str(int(time.time()) + 20)", "frequency_slice[\"fsid\"] try: assert proxies.vcc[vcc_id].jonesMatrix[fs_id-1][index] == value except AssertionError as ae: logging.error(\"AssertionError; incorrect Jones", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 1.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 1.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 1.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1]", "to receptor 10... assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].State() == DevState.DISABLE assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].searchWindowTuning", "fsp_2_proxies.subarray[1].band5Tuning[1] == 7.25 # # assert fsp_2_proxies.subarray[1].frequencyBandOffsetStream1 == 0 # # assert fsp_2_proxies.subarray[1].frequencyBandOffsetStream2", "# add some receptors to subarray 1 # proxies.subarray[1].AddReceptors([1, 3]) # time.sleep(1) #", "ObsState = {}\". format(proxies.vcc[proxies.receptor_to_vcc[1]].ObsState)) ) #proxies.vcc[0].receptorID assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 1.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] ==", "raise e ''' def test_ConfigureScan_onlyPss_basic( self, cbf_master_proxy, proxies.subarray[1], sw_1_proxy, sw_2_proxy, vcc_proxies, vcc_band_proxies, vcc_tdc_proxies,", "ObsReset proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert len(proxies.subarray[1].receptors) == 0 assert proxies.fspSubarray[1].obsState ==", "== 2 assert proxies.fspSubarray[3].searchBeamID[0] == 300 assert proxies.fspSubarray[3].searchBeamID[1] == 400 # TODO: currently", "json.loads(searchBeam[0]) searchBeam1 = json.loads(searchBeam[1]) assert searchBeam0[\"search_beam_id\"] == 300 assert searchBeam0[\"receptor_ids\"][0] == 3 assert", "value in enumerate(frequency_slice[\"matrix\"]): vcc_id = proxies.receptor_to_vcc[receptor[\"receptor\"]] fs_id = frequency_slice[\"fsid\"] try: assert proxies.vcc[vcc_id].jonesMatrix[fs_id-1][index] ==", "25 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcDestinationAddress == ( # \"fizz\", \"buzz\", \"80\" #", "# assert subarray_2_proxy.State() == DevState.OFF # # add some receptors to subarray 1", "== ( # \"foo\", \"bar\", \"8080\" # ) # then for search window", "initial value of attributes of CBF subarray assert len(proxies.subarray[1].receptors) == 0 assert proxies.subarray[1].configID", "fsp_1_proxies.subarray[1].channelAveragingMap[16][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[17][0] == 12648 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[17][1]", "= {}, jonesMatrix[{}] = {}\".format( jones_matrix[\"jonesMatrix\"][1][\"epoch\"], vcc_id, index, fs_id-1, proxies.vcc[vcc_id].jonesMatrix[fs_id-1]) ) raise ae", "- 1)): # assert vcc_band_proxies[i].State() == DevState.ON # else: # assert vcc_band_proxies[i].State() ==", "assert fsp_2_proxies.subarray[1].channelAveragingMap[16][0] == 11905 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[16][1] == 0 # # assert", "scan_index is an index into an array, therefore 0-based scan_index = int(input_scan_dict[\"scan_id\"]) -", "CBF subarray # def test_ConfigureScan_basic( # self, # cbf_master_proxy, # proxies.subarray[1], # sw_1_proxy,", "weights[\"epoch\"] = epoch epoch = str(int(epoch) + 10) # update delay model proxies.tm.beamWeights", "proxies.receptor_to_vcc[receptor[\"receptor\"]] fs_id = frequency_slice[\"fsid\"] try: assert proxies.vcc[vcc_id].jonesMatrix[fs_id-1][index] == value except AssertionError as ae:", "# fsp_2_proxies.subarray[1], # fsp_3_proxies.subarray[1], # tm_telstate_proxy # ): # \"\"\" # Test a", "ObsState.IDLE # abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED #", "raise e #TODO refactor to verify delay model values against input json @pytest.mark.skip(reason=\"test", "subarrays # first for FSP 1... (this is a CORR fsp device) assert", "scan configuration: assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.IDLE assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.IDLE assert proxies.fspPstSubarray[subarr_index-1].obsState ==", "model # Insert the epoch delay_model[\"delayModel\"][0][\"epoch\"] = str(int(time.time()) + 20) delay_model[\"delayModel\"][1][\"epoch\"] = \"0\"", "= {}\".format(proxy.State())) assert [proxy.State() for proxy in proxies.vccBand[proxies.receptor_to_vcc[4] - 1]] == [ DevState.DISABLE,", "0 assert vcc_proxies[receptor_to_vcc[4] - 1].rfiFlaggingMask == \"{}\" # then for VCC belonging to", "0 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream2 == 0 assert vcc_proxies[receptor_to_vcc[1] - 1].rfiFlaggingMask == \"{}\"", "= str(int(time.time())) for weights in timing_beam_weights[\"beamWeights\"]: weights[\"epoch\"] = epoch epoch = str(int(epoch) +", "proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY # Input test data:", "tm_telstate_proxy.visDestinationAddress == \"{}\" assert tm_telstate_proxy.receivedOutputLinks == False # add receptors proxies.subarray[1].AddReceptors([1, 3, 4])", "j in zip(range(num_receptors), input_receptors)]) assert proxies.subarray[subarr_index].obsState == ObsState.IDLE # Check fsp obsState BEFORE", "1) assert proxies.subarray[1].obsState == ObsState.READY # Clean Up proxies.clean_proxies() except AssertionError as ae:", "== \"CORR\": function_mode = 1 elif fsp[\"function_mode\"] == \"PSS-BF\": function_mode = 2 elif", "channels average factor 8\" assert proxies.subarray[1].frequencyBand == 4 # means 5a assert proxies.subarray[1].obsState", "3 # assert proxies.subarray[1].receptors[2] == 4 # # configure scan # f =", "+ \"/../data/Scan1_basic.json\") json_string = f2.read().replace(\"\\n\", \"\") input_scan_dict = json.loads(json_string) proxies.subarray[subarr_index].Scan(json_string) f2.close() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.SCANNING,", "Scan command f2 = open(file_path + \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1,", "== 4 assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[4] - 1]] == [ DevState.DISABLE,", "in [ # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", # ] #", "fsp_2_proxies.subarray[1].frequencyBand == 4 # # assert fsp_2_proxies.subarray[1].band5Tuning[0] == 5.85 # # assert fsp_2_proxies.subarray[1].band5Tuning[1]", "Vcc device # for proxy in vcc_band_proxies: # logging.info(\"VCC proxy.State() = {}\".format(proxy.State())) #", "for pair in cbf_master_proxy.receptorToVcc) cbf_master_proxy.On() time.sleep(3) # check initial value of attributes of", "attributes of VCCs # first for VCC belonging to receptor 10... assert proxies.vcc[proxies.receptor_to_vcc[4]].subarrayMembership", "test_ConfigureScan_minimal(self, proxies): try: sub_id = 1 #TODO currently only support for 1 receptor", "pretty long for CBF Master to initialize tm_telstate_proxy.Init() time.sleep(1) receptor_to_vcc = dict([*map(int, pair.split(\":\"))]", "check frequency band of VCCs, including states of frequency band capabilities assert vcc_proxies[receptor_to_vcc[4]", "proxies.fspSubarray[1].frequencyBandOffsetStream1 == 0 assert proxies.fspSubarray[1].frequencyBandOffsetStream2 == 0 assert proxies.fspSubarray[1].frequencySliceID == 1 assert proxies.fspSubarray[1].corrBandwidth", "frequency_slice in receptor[\"receptorMatrix\"]: for index, value in enumerate(frequency_slice[\"matrix\"]): vcc_id = proxies.receptor_to_vcc[receptor[\"receptor\"]] fs_id =", "proxies.subarray[1].obsState == ObsState.ABORTED # ObsReset proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert proxies.subarray[1].obsState ==", "# # check the rest of the configured attributes of VCCs # #", "range(4)]: proxy.loggingLevel = \"DEBUG\" if proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1)", "== 1 # assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[0] == 5.85 # assert vcc_proxies[receptor_to_vcc[1] -", "\"fizz\", \"buzz\", \"80\" # ) # then for search window 2 of VCC", "# assert proxies.subarray[1].obsState.value == ObsState.READY.value # # check frequency band of VCCs, including", "= {}\".format( jones_matrix[\"jonesMatrix\"][1][\"epoch\"], vcc_id, index, fs_id-1, proxies.vcc[vcc_id].jonesMatrix[fs_id-1]) ) raise ae except Exception as", "300 assert fsp_3_proxies.subarray[1].searchBeamID[1] == 400 searchBeam = fsp_3_proxies.subarray[1].searchBeams searchBeam300 = json.loads(searchBeam[0]) searchBeam400 =", "proxies.subarray[1].receptors[1] == 3 assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for i in [1, 3]]) assert", "- 1].frequencyBand == 4 # assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand == 4 # assert", "Distributed under the terms of the BSD-3-Clause license. # See LICENSE.txt for more", "Clean Up proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae except Exception as", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) # scan f2 = open(file_path + \"/../data/Scan2_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\"))", "timing_beam_weights[\"beamWeights\"]: weights[\"epoch\"] = epoch epoch = str(int(epoch) + 10) # update delay model", "# assert fsp_1_proxies.subarray[1].outputLinkMap[0][0] == 0 # assert fsp_1_proxies.subarray[1].outputLinkMap[0][1] == 4 # assert fsp_1_proxies.subarray[1].outputLinkMap[1][0]", "# \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", # ] # # then", "!= DevState.ON: proxies.subarray[sub_id].On() proxies.wait_timeout_dev([proxies.subarray[sub_id]], DevState.ON, 3, 1) for proxy in [proxies.vcc[i + 1]", "FSPs, including states of function mode capabilities fsp_function_mode_proxies = [proxies.fsp1FunctionMode, proxies.fsp2FunctionMode, proxies.fsp3FunctionMode, proxies.fsp4FunctionMode]", "1) assert len(proxies.subarray[1].receptors) == 0 assert proxies.vcc[proxies.receptor_to_vcc[3]].subarrayMembership == 0 assert proxies.subarray[1].obsState == ObsState.EMPTY", "Path file_path = os.path.dirname(os.path.abspath(__file__)) # Tango imports import tango from tango import DevState", "1]]}).replace('\"',\"'\") # Clean Up proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae except", "command \"\"\" try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On() proxies.wait_timeout_dev([proxies.subarray[1]],", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 2.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 2.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 2.4 assert", "4 assert proxies.fspSubarray[1].frequencyBand == 4 assert proxies.fspSubarray[1].band5Tuning[0] == 5.85 assert proxies.fspSubarray[1].band5Tuning[1] == 7.25", "assert proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1] == 3 assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for", "model data from file f = open(file_path + \"/../data/delaymodel.json\") delay_model = json.loads(f.read().replace(\"\\n\", \"\"))", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED # ObsReset proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY,", "proxies.subarray[1].RemoveAllReceptors() time.sleep(3) assert proxies.subarray[1].state() == tango.DevState.OFF def test_band1( self, cbf_master_proxy, proxies.subarray[1], sw_1_proxy, sw_2_proxy,", "proxies.subarray[1].get_timeout_millis() log_msg = \"timeout_millis = {} \".format(timeout_millis) #logging.info(log_msg) #logging.info(\"start_time = {}\".format(time.time())) logging.info(\"start datetime", "2.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 3.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 3.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 3.2", "# \"\"\" # for proxy in vcc_proxies: # proxy.Init() # fsp_1_proxies.subarray[1].Init() # fsp_2_proxies.subarray[1].Init()", "fsp_2_proxies.subarray[1].channelAveragingMap[18][0] == 13393 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[18][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[19][0]", "assert vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership == 1 assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[0] == 5.85 assert", "receptors proxies.subarray[sub_id].AddReceptors(test_receptor_ids) proxies.wait_timeout_obs([proxies.subarray[sub_id]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[sub_id].receptors[i] == j for i, j", "break if multiple scan configurations are tested def test_ConfigureScan_basic(self, proxies): \"\"\" Test a", "assert proxies.subarray[1].obsState == ObsState.IDLE # abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState", "ObsState.EMPTY ############################# abort from READY ########################### # add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2])", "assert fsp_2_proxies.subarray[1].frequencyBand == 4 # # assert fsp_2_proxies.subarray[1].band5Tuning[0] == 5.85 # # assert", "3 assert proxies.fspSubarray[3].receptors[1] == 1 assert proxies.fspSubarray[3].searchWindowID == 2 assert proxies.fspSubarray[3].searchBeamID[0] == 300", "search window 2 of VCC belonging to receptor 1... assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].State()", "0 # # then for FSP 3... # assert fsp_3_proxies.subarray[1].receptors[0] == 3 #", "receptor not assigned to subarray 1 # doing this doesn't actually throw an", "2, 4]) # time.sleep(1) # assert \"already in use\" in str(df.value.args[0].desc) # assert", "1 receptor per fsp test_receptor_ids = [4, 1] #test_receptor_ids = [1] vcc_index =", "receptors proxies.subarray[1].AddReceptors([1, 3, 4]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[1].receptors[i] == j for", "support for 1 receptor per fsp test_receptor_ids = [4, 1] #test_receptor_ids = [1]", "sw_2_proxy, vcc_proxies, vcc_band_proxies, vcc_tdc_proxies, fsp_1_proxy, fsp_2_proxy, fsp_1_function_mode_proxy, fsp_2_function_mode_proxy, fsp_1_proxies.subarray[1], fsp_2_proxies.subarray[1], fsp_3_proxies.subarray[1], tm_telstate_proxy ):", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[4][0] == 2976 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[4][1] == 8 #", "1) # scan f2 = open(file_path + \"/../data/Scan2_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING,", "device; # to be decide which one to keep. # print(\"proxies.sw[1].State() = {}\".format(proxies.sw[1].State()))", "2])]) # configure scan f = open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]],", "of function mode capabilities fsp_function_mode_proxies = [proxies.fsp1FunctionMode, proxies.fsp2FunctionMode, proxies.fsp3FunctionMode, proxies.fsp4FunctionMode] for fsp in", "3, 4])]) # configure scan f = open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close()", "assert fsp_2_proxies.subarray[1].channelAveragingMap[7][0] == 5209 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[7][1] == 0 # # assert", "1].subarrayMembership == 0 for i in range(4)]) input_receptors = [1, 3, 4] #", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 1.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 1.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 2.0 assert", "assert proxies.subarray[1].frequencyBand == 0 # means 1 assert proxies.subarray[1].obsState.value == ObsState.READY.value # check", "assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcDestinationAddress == ( \"foo\", \"bar\", \"8080\" ) # then for", "3]) # time.sleep(1) # assert proxies.subarray[1].receptors == (1, 3) # assert all([vcc_proxies[receptor_to_vcc[i] -", "# update delay model proxies.tm.delayModel = json.dumps(delay_model) time.sleep(1) for jj in range(4): logging.info((\"", "proxies.subarray[1].frequencyBand == 0 # assert proxies.subarray[1].State() == DevState.ON # assert proxies.subarray[1].ObsState == ObsState.EMPTY", "the rest of the configured attributes of VCCs # first for VCC belonging", "= open(file_path + config_file_name) proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 15, 1) # check", "'searchBeams'); # this has to be updated in FspPssSubarray # to read/write individual", "3.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 3.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 4.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 4.1", "proxies.wait_timeout_obs([proxies.subarray[sub_id]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[sub_id].receptors[i] == j for i, j in zip(range(len(test_receptor_ids)),", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[2][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[3][0] == 2232 # #", "fsp_2_proxies.subarray[1].channelAveragingMap[3][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[4][0] == 2977 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[4][1]", "fsp_1_proxies.subarray[1].band5Tuning[0] == 5.85 # assert fsp_1_proxies.subarray[1].band5Tuning[1] == 7.25 # assert fsp_1_proxies.subarray[1].frequencyBandOffsetStream1 == 0", "= json.loads(f.read().replace(\"\\n\", \"\")) epoch = str(int(time.time())) for weights in timing_beam_weights[\"beamWeights\"]: weights[\"epoch\"] = epoch", "currently searchBeams is stored by the device # as a json string (", "if proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) # check initial value", "delay_model[\"delayModel\"][0][\"delayDetails\"][0][\"receptorDelayDetails\"] num_fsp_IDs = len(aa) for jj in range(num_fsp_IDs): logging.info( \"delayCoeff = {}\".format( aa[jj][\"delayCoeff\"])", "[proxies.vcc[i + 1] for i in range(4)]: if proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy],", "30, 1) assert proxies.subarray[1].obsState == ObsState.READY #create a Jones matrix f = open(file_path", "proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e ''' def test_ConfigureScan_onlyPss_basic(", "== 4 # configure scan f = open(file_path + \"/test_json/test_ConfigureScan_onlyPss_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close()", "subarray, this test is currently broken.\") def test_AddRemoveReceptors_invalid_multiple(self, proxies): \"\"\" Test invalid AddReceptors", "if model[\"destinationType\"] == \"fsp\": epoch = str(int(epoch) + 10) # update delay model", "== 6000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcEnable == True assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcNumBits ==", "\"DEBUG\" if proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) # check initial", "of FSP subarrays # first for FSP 1... assert fsp_1_proxies.subarray[1].obsState == ObsState.READY assert", "############################# abort from IDLE ########################### # add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]],", "of CBF subarray frequency_band = input_config_dict[\"common\"][\"frequency_band\"] input_band_index = freq_band_dict()[frequency_band] assert proxies.subarray[subarr_index].configID == input_config_dict[\"common\"][\"config_id\"]", "attributes of VCCs # first for VCC belonging to receptor 10... assert vcc_proxies[receptor_to_vcc[4]", "window 1 of VCC belonging to receptor 10... assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].State() ==", "part of the csp-lmc-prototype project # # # # Distributed under the terms", "2.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 2.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 2.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 2.7", "# assert all([proxy.subarrayMembership == 0 for proxy in vcc_proxies]) # assert proxies.subarray[1].State() ==", "ae except Exception as e: proxies.clean_proxies() raise e @pytest.mark.skip(reason=\"pst not currently supported\") def", "proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.SCANNING # TODO: this check does not pass, to fix #elif", "assert [proxy.State() for proxy in proxies.vccBand[proxies.receptor_to_vcc[1] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE,", "vcc_proxies[receptor_to_vcc[1] - 1].rfiFlaggingMask == \"{}\" # check configured attributes of search windows #", "ObsState.SCANNING assert proxies.subarray[1].scanID == 2 assert proxies.fspSubarray[1].obsState == ObsState.SCANNING assert proxies.fspSubarray[3].obsState == ObsState.SCANNING", "fsp_2_proxy.subarrayMembership assert [proxy.State() for proxy in fsp_1_function_mode_proxy] == [ DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE", "AssertionError as ae: logging.error(\"AssertionError; incorrect Jones matrix entry: epoch {}, VCC {}, i", "ae except Exception as e: raise e time.sleep(10) # update delay models from", "assert fsp_2_proxies.subarray[1].channelAveragingMap[16][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[17][0] == 12649 # # assert", "ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE proxies.clean_proxies() except AssertionError as", "assert fsp_2_proxies.subarray[1].corrBandwidth == 0 # # assert fsp_2_proxies.subarray[1].integrationTime == 1400 # # assert", "proxy in vcc_proxies: proxy.Init() fsp_1_proxies.subarray[1].Init() fsp_2_proxies.subarray[1].Init() fsp_3_proxies.subarray[1].Init() fsp_1_proxy.Init() fsp_2_proxy.Init() time.sleep(3) cbf_master_proxy.set_timeout_millis(60000) cbf_master_proxy.Init() time.sleep(60)", "= open(file_path + \"/../data/jonesmatrix.json\") jones_matrix = json.loads(f.read().replace(\"\\n\", \"\")) f.close() jones_matrix[\"jonesMatrix\"][0][\"epoch\"] = str(int(time.time()) +", "receptor 2... assert proxies.vcc[proxies.receptor_to_vcc[2]].subarrayMembership == 1 assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBandOffsetStream1 == 0 assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBandOffsetStream2 ==", "1, 1) # check initial value of attributes of CBF subarray vcc_index =", "range(3)] == input_receptors assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for i in input_receptors]) assert proxies.subarray[1].obsState", "proxies.subarray[1].AddReceptors([2]) time.sleep(1) assert [proxies.subarray[1].receptors[i] for i in range(4)] == [1, 3, 4, 2]", "== 8 # assert proxies.sw[1].tdcPeriodBeforeEpoch == 5 # assert proxies.sw[1].tdcPeriodAfterEpoch == 25 #", "ObsState.SCANNING, 1, 1) # check scanID on VCC and FSP assert proxies.fspSubarray[1].scanID ==", "from SCANNING ########################### # add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1,", "assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBandOffsetStream1 == 0 assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBandOffsetStream2 == 0 assert proxies.vcc[proxies.receptor_to_vcc[2]].rfiFlaggingMask == \"{}\" #", "2... assert proxies.vcc[proxies.receptor_to_vcc[2]].subarrayMembership == 1 assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBandOffsetStream1 == 0 assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBandOffsetStream2 == 0", "# assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].searchWindowTuning == 6000000000 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcEnable ==", "assert searchBeam300[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" assert searchBeam400[\"searchBeamID\"] == 400 assert searchBeam400[\"receptors\"][0] == 1 assert", "# \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", # ] # # then for search", "for search window 2 of VCC belonging to receptor 10... # assert vcc_tdc_proxies[receptor_to_vcc[4]", "assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].searchWindowTuning == 6000000000 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcEnable == True assert", "== \"{}\" # check configured attributes of FSPs, including states of function mode", "attributes of CBF subarray assert proxies.subarray[1].configID == \"sbi-mvp01-20200325-00001-science_A\" assert proxies.subarray[1].frequencyBand == 0 #", "== fsp[\"integration_factor\"] assert proxies.fspSubarray[fsp_id].corrBandwidth == fsp[\"zoom_factor\"] if fsp[\"zoom_factor\"] > 0: assert proxies.fspSubarray[fsp_id].zoomWindowTuning ==", "False assert fsp_3_proxies.subarray[1].receptors[0] == 3 assert fsp_3_proxies.subarray[1].receptors[1] == 1 assert fsp_3_proxies.subarray[1].searchWindowID == 2", "assigned to subarray 1 # doing this doesn't actually throw an error proxies.subarray[1].RemoveReceptors([2])", "Exception as e: raise e # transition to obsState == SCANNING f2 =", "1][0].tdcEnable == True assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcNumBits == 8 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch", "== 1 for i in [1, 3]]) assert proxies.subarray[1].obsState == ObsState.IDLE # TODO:", "#assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState == ObsState.EMPTY # add receptors proxies.subarray[1].AddReceptors([1, 3,", "== 1 for i in [1, 3]]) # assert proxies.subarray[1].State() == DevState.ON #", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[7][0] == 5208 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[7][1] == 8 #", "- 1].frequencyBand == 4 # assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[4] - 1]]", "# then for VCC belonging to receptor 1... # assert vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership", "( # \"foo\", \"bar\", \"8080\" # ) # # then for search window", "# assert fsp_2_proxies.subarray[1].integrationTime == 1400 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[0][0] == 1 # #", "LoggingLevel.DEBUG try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.ON,", "in FSP if fsp[\"function_mode\"] == \"CORR\": function_mode = 1 elif fsp[\"function_mode\"] == \"PSS-BF\":", "e: proxies.clean_proxies() raise e def test_Abort_Reset(self, proxies): \"\"\" Test abort reset \"\"\" try:", "VCC belonging to receptor 1... # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].State() == DevState.ON #", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 1.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 1.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 1.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2]", "[1, 3]]) # assert proxies.subarray[1].State() == DevState.ON # # try adding some receptors", "time.sleep(60) # takes pretty long for CBF controller to initialize # receptor_to_vcc =", "assert proxies.subarray[1].configID == \"sbi-mvp01-20200325-00001-science_A\" assert proxies.subarray[1].frequencyBand == 0 # means 1 assert proxies.subarray[1].obsState.value", "zip(range(3), [1, 3, 4])]) assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for i in [1, 3,", "== \"PST-BF\": function_mode = 3 elif fsp[\"function_mode\"] == \"VLBI\": function_mode = 4 assert", "j for i, j in zip(range(num_receptors), input_receptors)]) assert proxies.subarray[subarr_index].obsState == ObsState.IDLE # Check", "time.sleep(15) # check configured attributes of CBF subarray # def test_ConfigureScan_basic( # self,", "assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch == 25 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcDestinationAddress == (", "1 assert fsp_3_proxies.subarray[1].searchWindowID == 2 assert fsp_3_proxies.subarray[1].searchBeamID[0] == 300 assert fsp_3_proxies.subarray[1].searchBeamID[1] == 400", "of frequency band capabilities # assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand == 4 # assert", "Test valid AddReceptors and RemoveReceptors commands \"\"\" timeout_millis = proxies.subarray[1].get_timeout_millis() log_msg = \"timeout_millis", "assert all([proxy.subarrayMembership == 0 for proxy in vcc_proxies]) # assert proxies.subarray[1].State() == DevState.OFF", "obsStates AFTER the EndScan() command assert proxies.subarray[subarr_index].obsState == ObsState.READY assert proxies.vcc[vcc_ids[0]].obsState == ObsState.READY", "proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) assert proxies.subarray[1].State() == DevState.ON assert proxies.subarray[1].obsState == ObsState.EMPTY", "== 8 assert proxies.fspSubarray[1].channelAveragingMap[2][0] == 1488 assert proxies.fspSubarray[1].channelAveragingMap[2][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[3][0] ==", "# receptor list should be empty right after initialization assert len(proxies.subarray[1].receptors) == 0", "proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1, 1) proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae", "8 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch == 5 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch", "vcc_ids[ii] = proxies.receptor_to_vcc[receptor_id] proxies.subarray[subarr_index].AddReceptors(input_receptors) proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[subarr_index].receptors[i] == j for", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 3.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 3.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 3.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4]", "= fsp_3_proxies.subarray[1].searchBeams searchBeam300 = json.loads(searchBeam[0]) searchBeam400 = json.loads(searchBeam[1]) assert searchBeam300[\"searchBeamID\"] == 300 assert", "#elif fsp[\"function_mode\"] == \"PST-BF\": # assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.SCANNING proxies.subarray[subarr_index].EndScan() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.READY, 1,", "ObsState.READY, 1, 1) assert proxies.subarray[1].obsState == ObsState.READY # Clean Up proxies.clean_proxies() except AssertionError", "check configured attributes of FSPs, including states of function mode capabilities # assert", "fsp_2_proxies.subarray[1].channelAveragingMap[7][0] == 5209 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[7][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[8][0]", "subarray 2 # with pytest.raises(tango.DevFailed) as df: # subarray_2_proxy.AddReceptors([1, 2, 4]) # time.sleep(1)", "1].subarrayMembership == 1 # then for VCC belonging to receptor 1... assert vcc_proxies[receptor_to_vcc[1]", "time.sleep(1) # assert proxies.subarray[1].receptors == (1, 3) # assert all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership ==", "= {}\".format(proxies.sw[2].State())) # assert proxies.sw[1].State() == DevState.ON # assert proxies.sw[1].searchWindowTuning == 6000000000 #", "0 assert proxies.subarray[1].obsState == ObsState.EMPTY proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.OFF, 3, 1) except AssertionError as", "attributes of CBF subarray assert len(proxies.subarray[1].receptors) == 0 assert proxies.subarray[1].configID == '' assert", "8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[6][0] == 4464 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[6][1] == 8", "== 0 assert all([proxies.vcc[i + 1].subarrayMembership == 0 for i in range(4)]) input_receptors", "== 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[12][0] == 8928 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[12][1] ==", "proxies.fspSubarray[1].outputLinkMap[3][1] == 16 assert str(proxies.fspSubarray[1].visDestinationAddress).replace('\"',\"'\") == \\ str({\"outputHost\": [[0, \"192.168.0.1\"], [8184, \"192.168.0.2\"]], \"outputMac\":", "fsp_3_proxies.subarray[1].Init() fsp_1_proxy.Init() fsp_2_proxy.Init() proxies.subarray[1].set_timeout_millis(60000) # since the command takes a while proxies.subarray[1].Init() time.sleep(3)", "ObsState.IDLE, 1, 1) assert all([proxies.subarray[sub_id].receptors[i] == j for i, j in zip(range(len(test_receptor_ids)), test_receptor_ids)])", "assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for i in [1, 3, 4]]) assert proxies.subarray[1].obsState ==", "3 proxies.subarray[1].RemoveAllReceptors() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.OFF, 3, 1) except AssertionError", "for i, j in zip(range(3), [1, 3, 4])]) # configure scan f1 =", "refactor to verify delay model values against input json @pytest.mark.skip(reason=\"test needs to be", "4 for proxy in proxies.vccBand[proxies.receptor_to_vcc[4] - 1]: logging.info(\"VCC proxy.State() = {}\".format(proxy.State())) assert [proxy.State()", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) assert proxies.subarray[1].obsState == ObsState.SCANNING time.sleep(10) for receptor in jones_matrix[\"jonesMatrix\"][2][\"matrixDetails\"]:", "- 1].band5Tuning[0] == 5.85 # assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[1] == 7.25 # assert", "== True assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcNumBits == 8 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch ==", "search window 2... assert sw_2_proxy.State() == DevState.DISABLE assert sw_2_proxy.searchWindowTuning == 7000000000 assert sw_2_proxy.tdcEnable", "CBF Master to initialize tm_telstate_proxy.Init() time.sleep(1) receptor_to_vcc = dict([*map(int, pair.split(\":\"))] for pair in", "assert proxies.subarray[subarr_index].obsState == ObsState.SCANNING assert proxies.vcc[vcc_ids[0]].obsState == ObsState.SCANNING assert proxies.vcc[vcc_ids[num_receptors-1]].obsState == ObsState.SCANNING for", "assert all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership == 1 for i in [1, 3]]) # assert", "e #TODO refactor to verify delay model values against input json @pytest.mark.skip(reason=\"test needs", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 4.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 4.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 4.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4]", "== 7000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].tdcEnable == False # check configured attributes of", "a delay model # Insert the epoch delay_model[\"delayModel\"][0][\"epoch\"] = str(int(time.time()) + 20) delay_model[\"delayModel\"][1][\"epoch\"]", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 1.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 1.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 1.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3]", "# Distributed under the terms of the BSD-3-Clause license. # See LICENSE.txt for", "- 1][0].tdcEnable == True # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcNumBits == 8 # assert", "== 0 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream2 == 0 assert vcc_proxies[receptor_to_vcc[1] - 1].rfiFlaggingMask ==", "assert proxies.subarray[1].receptors[2] == 4 # configure scan f = open(file_path + \"/test_json/test_ConfigureScan_onlyPss_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\",", "20) delay_model[\"delayModel\"][1][\"epoch\"] = \"0\" delay_model[\"delayModel\"][2][\"epoch\"] = str(int(time.time()) + 10) # update delay model", "8 assert proxies.fspSubarray[1].channelAveragingMap[2][0] == 1488 assert proxies.fspSubarray[1].channelAveragingMap[2][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[3][0] == 2232", "# check configured attributes of FSP subarrays # first for FSP 1... assert", "- 1].frequencyBandOffsetStream1 == 0 # assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream2 == 0 # assert", "VCC belonging to receptor 1... # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].State() == DevState.DISABLE #", "== band_index assert proxies.subarray[sub_id].obsState == ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i + 1] for i in range(4)],", "sub_id #TODO fix these tests; issue with VccBand devices either not reconfiguring in", "# assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcNumBits == 8 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch ==", "# assert fsp_1_proxies.subarray[1].outputLinkMap[2][0] == 1488 # assert fsp_1_proxies.subarray[1].outputLinkMap[2][1] == 12 # assert fsp_1_proxies.subarray[1].outputLinkMap[3][0]", "belonging to receptor 1... assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].State() == DevState.ON assert vcc_tdc_proxies[receptor_to_vcc[1] -", "sw_1_proxy.tdcEnable == True assert sw_1_proxy.tdcNumBits == 8 assert sw_1_proxy.tdcPeriodBeforeEpoch == 5 assert sw_1_proxy.tdcPeriodAfterEpoch", "== ObsState.ABORTED # ObsReset proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY", "in vcc_band_proxies[receptor_to_vcc[1] - 1]] == [ # DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # #", "# proxies.subarray[1].AddReceptors([1, 3]) # time.sleep(1) # assert proxies.subarray[1].receptors == (1, 3) # assert", "1].rfiFlaggingMask == \"{}\" # then for VCC belonging to receptor 1... assert vcc_proxies[receptor_to_vcc[1]", "commands \"\"\" timeout_millis = proxies.subarray[1].get_timeout_millis() log_msg = \"timeout_millis = {} \".format(timeout_millis) #logging.info(log_msg) #logging.info(\"start_time", "e: proxies.clean_proxies() raise e @pytest.mark.skip(reason=\"pst not currently supported\") def test_ConfigureScan_onlyPst_basic(self, proxies): \"\"\" Test", "delay model proxies.tm.beamWeights = json.dumps(timing_beam_weights) time.sleep(1) for weights in timing_beam_weights[\"beamWeights\"]: for receptor in", "5 assert sw_1_proxy.tdcPeriodAfterEpoch == 25 assert \"\".join(sw_1_proxy.tdcDestinationAddress.split()) in [ \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\",", "FSPs, including states of function mode capabilities assert fsp_1_proxy.functionMode == 1 assert 1", "for fsp in configuration[\"cbf\"][\"fsp\"]: fsp_id = fsp[\"fsp_id\"] logging.info(\"{}\".format(fsp_id)) #TODO add function mode to", "the VccSearchWindow device; # to be decide which one to keep. # print(\"proxies.sw[1].State()", "# assert sw_2_proxy.State() == DevState.DISABLE # assert sw_2_proxy.searchWindowTuning == 7000000000 # assert sw_2_proxy.tdcEnable", "for search window 1 of VCC belonging to receptor 1... assert vcc_tdc_proxies[receptor_to_vcc[1] -", "Test the Scan command \"\"\" try: # turn on Subarray if proxies.subarray[1].State() !=", "{}\".format(vcc_index)) vcc_band_proxies = proxies.vccBand[vcc_index - 1] # turn on Subarray if proxies.subarray[sub_id].State() !=", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 2.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 2.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 2.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0]", "1 # assert fsp_3_proxies.subarray[1].searchWindowID == 2 # assert fsp_3_proxies.subarray[1].searchBeamID[0] == 300 # assert", "test_ConfigureScan_basic(self, proxies): \"\"\" Test a successful scan configuration \"\"\" proxies.subarray[1].loggingLevel = LoggingLevel.DEBUG try:", "in [1, 2, 4]]) assert proxies.vcc[proxies.receptor_to_vcc[3]].subarrayMembership == 1 # remove remaining receptors proxies.subarray[1].RemoveReceptors([3])", "== 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[3][0] == 2232 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[3][1] ==", "== ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE ############################# abort from", "configured attributes of FSP subarrays # first for FSP 3 ... (this is", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 1.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 1.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 1.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5]", "proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e def test_Scan(self, proxies):", "of function mode capabilities assert fsp_1_proxy.functionMode == 1 assert 1 in fsp_1_proxy.subarrayMembership #", "# assert proxies.sw[1].searchWindowTuning == 6000000000 # assert proxies.sw[1].tdcEnable == True # assert proxies.sw[1].tdcNumBits", "in proxies.vccBand[proxies.receptor_to_vcc[4] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] assert [proxy.State() for", "True # assert proxies.sw[1].tdcNumBits == 8 # assert proxies.sw[1].tdcPeriodBeforeEpoch == 5 # assert", "a receptor ID is invalid (e.g. out of range) - when a receptor", "# first for search window 1 of VCC belonging to receptor 10... assert", "assert proxies.subarray[1].State() == DevState.OFF # assert subarray_2_proxy.State() == DevState.OFF # # add some", "\"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) assert proxies.subarray[1].obsState == ObsState.READY #create", "ID is invalid (e.g. out of range) - when a receptor to be", "== 4 # assert searchBeam300[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" # assert searchBeam400[\"searchBeamID\"] == 400 #", "are tested def test_ConfigureScan_basic(self, proxies): \"\"\" Test a successful scan configuration \"\"\" proxies.subarray[1].loggingLevel", "for i, j in zip(range(1), [2])]) assert all([proxies.fspSubarray[6].timingBeamID[i] == j for i, j", "- 1][0].tdcPeriodAfterEpoch == 25 # TODO - re-enable and debug! # assert proxies.vccTdc[proxies.receptor_to_vcc[1]", "== 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[8][0] == 5953 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[8][1] ==", "== 3.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 3.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 3.4 # transition to", "True assert searchBeam400[\"averagingInterval\"] == 2 assert searchBeam400[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" proxies.subarray[1].GoToIdle() time.sleep(3) assert proxies.subarray[1].obsState", "1][0].tdcEnable == True # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcNumBits == 8 # assert vcc_tdc_proxies[receptor_to_vcc[4]", "vcc_band_proxies[receptor_to_vcc[4] - 1]] == [ # DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # assert [proxy.State()", "import AdminMode, ObsState from ska_tango_base.base_device import _DEBUGGER_PORT @pytest.mark.usefixtures(\"proxies\", \"input_test_data\") class TestCbfSubarray: def test_AddRemoveReceptors_valid(self,", "invalid one) to subarray 2 # with pytest.raises(tango.DevFailed) as df: # subarray_2_proxy.AddReceptors([1, 2,", "1][0].tdcPeriodBeforeEpoch == 5 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch == 25 # TODO - re-enable", "search window 2... # assert sw_2_proxy.State() == DevState.DISABLE # assert sw_2_proxy.searchWindowTuning == 7000000000", "except Exception as e: proxies.clean_proxies() raise e def test_Abort_Restart(self, proxies): \"\"\" Test abort", "and FSP assert proxies.fspSubarray[1].scanID == 1 assert proxies.vcc[proxies.receptor_to_vcc[4]].scanID ==1 # check states assert", "to subarray 2 # with pytest.raises(tango.DevFailed) as df: # subarray_2_proxy.AddReceptors([1, 2, 4]) #", "of VCCs # first for VCC belonging to receptor 10... assert proxies.vcc[proxies.receptor_to_vcc[4]].subarrayMembership ==", "\"/../data/timingbeamweights.json\") timing_beam_weights = json.loads(f.read().replace(\"\\n\", \"\")) epoch = str(int(time.time())) for weights in timing_beam_weights[\"beamWeights\"]: weights[\"epoch\"]", "add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[1].receptors[i] ==", "i in range(4): # if (i == 0 and band_index == 0) or", "ObsState.READY # send the Scan command f2 = open(file_path + \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\"))", "assert proxies.fspSubarray[6].obsState == ObsState.READY assert all([proxies.fspSubarray[6].receptors[i] == j for i, j in zip(range(1),", "vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream2 == 0 assert vcc_proxies[receptor_to_vcc[4] - 1].rfiFlaggingMask == \"{}\" # then", "4 assert [proxy.State() for proxy in proxies.vccBand[proxies.receptor_to_vcc[2] - 1]] == [ DevState.DISABLE, DevState.DISABLE,", "1][1].searchWindowTuning == 7000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].tdcEnable == False # check configured attributes", "assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.SCANNING assert proxies.fspSubarray[1].obsState == ObsState.SCANNING assert", "1, ObsState = {}\". format(proxies.vcc[proxies.receptor_to_vcc[1]].ObsState)) ) #proxies.vcc[0].receptorID assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 1.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1]", "# assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].State() == DevState.ON # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].searchWindowTuning ==", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[10][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[11][0] == 8184 #", "when a receptor ID is invalid (e.g. out of range) - when a", "fsp_1_proxies.subarray[1].channelAveragingMap[10][0] == 7440 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[10][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[11][0]", "assert proxies.vcc[proxies.receptor_to_vcc[4]].subarrayMembership == 1 assert proxies.vcc[proxies.receptor_to_vcc[4]].band5Tuning[0] == 5.85 assert proxies.vcc[proxies.receptor_to_vcc[4]].band5Tuning[1] == 7.25 assert", "== 13393 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[18][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[19][0] ==", "j for i, j in zip(range(3), [1, 3, 4])]) assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1", "0 # check the rest of the configured attributes of VCCs # first", "ObsState.READY, 1, 1) # Check obsStates AFTER the EndScan() command assert proxies.subarray[subarr_index].obsState ==", "for search window 2 of VCC belonging to receptor 10... assert proxies.vccTdc[proxies.receptor_to_vcc[4] -", "assert fsp_2_proxies.subarray[1].channelAveragingMap[8][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[9][0] == 6697 # # assert", "searchBeam1[\"search_beam_id\"] == 400 assert searchBeam1[\"receptor_ids\"][0] == 1 assert searchBeam1[\"enable_output\"] == True assert searchBeam1[\"averaging_interval\"]", "1, 1) assert all([proxies.subarray[1].receptors[i] == j for i, j in zip(range(3), [1, 3,", "\"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) assert proxies.subarray[1].obsState == ObsState.READY #create a Jones", "1][0].State() == DevState.ON # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].searchWindowTuning == 6000000000 # assert vcc_tdc_proxies[receptor_to_vcc[1]", "proxies.vccBand[proxies.receptor_to_vcc[2] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # check the rest", "1, 1) assert proxies.subarray[1].obsState == ObsState.IDLE assert proxies.subarray[1].scanID == 0 assert proxies.fspSubarray[1].obsState ==", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 4.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 4.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 4.3 assert", "proxies.vcc[proxies.receptor_to_vcc[2]].subarrayMembership == 1 assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBandOffsetStream1 == 0 assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBandOffsetStream2 == 0 assert proxies.vcc[proxies.receptor_to_vcc[2]].rfiFlaggingMask", "\"{}\" # check configured attributes of FSPs, including states of function mode capabilities", "sw_2_proxy, # vcc_proxies, # vcc_band_proxies, # vcc_tdc_proxies, # fsp_1_proxy, # fsp_2_proxy, # fsp_1_function_mode_proxy,", "VCC belonging to receptor 1... assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].State() == DevState.DISABLE assert vcc_tdc_proxies[receptor_to_vcc[1]", "fsp_1_proxies.subarray[1].channelAveragingMap[4][0] == 2976 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[4][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[5][0]", "1 assert proxies.fspSubarray[1].zoomWindowTuning == 4700000 assert proxies.fspSubarray[1].integrationTime == 1 assert proxies.fspSubarray[1].fspChannelOffset == 14880", "- 1].band5Tuning[1] == 7.25 assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream1 == 0 assert vcc_proxies[receptor_to_vcc[4] -", "proxies.vcc[proxies.receptor_to_vcc[1]].frequencyBand == 4 for proxy in proxies.vccBand[proxies.receptor_to_vcc[4] - 1]: logging.info(\"VCC proxy.State() = {}\".format(proxy.State()))", "as ae: proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e @pytest.mark.skip(reason=\"pst", "- 1].subarrayMembership == 1 # then for VCC belonging to receptor 1... assert", "assert proxies.subarray[1].scanID == 0 assert proxies.fspSubarray[1].obsState == ObsState.IDLE assert proxies.fspSubarray[3].obsState == ObsState.IDLE assert", "\"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 15, 1) # update jones matrices from tm emulator", "2.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 2.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 2.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 2.4", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 2.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 2.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 2.5 assert", "function mode capabilities assert proxies.fsp[2].State() == DevState.ON assert proxies.fsp[2].functionMode == 3 assert 1", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 1.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 1.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 1.5 assert", "weights[\"beamWeightsDetails\"]: rec_id = int(receptor[\"receptor\"]) fs_id = receptor[\"receptorWeightsDetails\"][0][\"fsid\"] for index, value in enumerate(receptor[\"receptorWeightsDetails\"][0][\"weights\"]): try:", "1][0].tdcPeriodBeforeEpoch == 5 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch == 25 # TODO - re-enable", "proxies.subarray[1].configID == 0 # assert proxies.subarray[1].frequencyBand == 0 # assert proxies.subarray[1].State() == DevState.ON", "abort restart \"\"\" try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On()", "== ObsState.IDLE assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.IDLE logging.info( \"First vcc obsState BEFORE ConfigureScan =", "6000000000 # assert sw_1_proxy.tdcEnable == True # assert sw_1_proxy.tdcNumBits == 8 # assert", "is a PSS fsp device) assert proxies.fspSubarray[3].receptors[0] == 3 assert proxies.fspSubarray[3].receptors[1] == 1", "searchBeam300[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" # assert searchBeam400[\"searchBeamID\"] == 400 # assert searchBeam400[\"receptors\"][0] == 1", "# TODO - this does not pass - to debug & fix #assert", "- 1][1].State() == DevState.DISABLE assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].searchWindowTuning == 7000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[4] -", "proxies.fspSubarray[3].obsState == ObsState.READY # send the Scan command f2 = open(file_path + \"/../data/Scan1_basic.json\")", "744 channels average factor 8\" assert proxies.subarray[1].frequencyBand == 4 # means 5a assert", "- 1][0].tdcEnable == True assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcNumBits == 8 assert proxies.vccTdc[proxies.receptor_to_vcc[4] -", "0 # # assert fsp_2_proxies.subarray[1].frequencyBandOffsetStream2 == 0 # # assert fsp_2_proxies.subarray[1].frequencySliceID == 20", "1) # check frequency band of VCCs, including states of # frequency band", "# try adding an invalid receptor ID # with pytest.raises(tango.DevFailed) as df: #", "4]]) assert proxies.subarray[1].obsState == ObsState.IDLE # remove all receptors proxies.subarray[1].RemoveAllReceptors() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1,", "4.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 4.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 4.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 4.3", "DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) for proxy in [proxies.fsp[i + 1] for", "# receptor list should be empty right after initialization # assert proxies.subarray[1].receptors ==", "# configure scan config_file_name = \"/../data/ConfigureScan_basic.json\" f = open(file_path + config_file_name) proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\"))", "assert fsp_1_proxies.subarray[1].channelAveragingMap[10][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[11][0] == 8184 # # assert", "assert proxies.fspSubarray[1].outputLinkMap[3][1] == 16 assert str(proxies.fspSubarray[1].visDestinationAddress).replace('\"',\"'\") == \\ str({\"outputHost\": [[0, \"192.168.0.1\"], [8184, \"192.168.0.2\"]],", ") #proxies.vcc[0].receptorID assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 1.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 1.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] ==", "vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership == 1 assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[0] == 5.85 assert vcc_proxies[receptor_to_vcc[4]", "assert fsp_1_proxies.subarray[1].channelAveragingMap[12][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[13][0] == 9672 # # assert", "assert proxies.vcc[vcc_id].jonesMatrix[fs_id-1][index] == value except AssertionError as ae: logging.error(\"AssertionError; incorrect Jones matrix entry:", "== 0.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 1.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 1.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] ==", "5 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch == 25 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcDestinationAddress == (", "3.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 3.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 3.4 # transition to obsState=SCANNING", "configuration[\"common\"][\"config_id\"] assert proxies.subarray[sub_id].frequencyBand == band_index assert proxies.subarray[sub_id].obsState == ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i + 1] for", "to receptor 10... assert proxies.vcc[proxies.receptor_to_vcc[4]].subarrayMembership == 1 assert proxies.vcc[proxies.receptor_to_vcc[4]].band5Tuning[0] == 5.85 assert proxies.vcc[proxies.receptor_to_vcc[4]].band5Tuning[1]", "search window 1 of VCC belonging to receptor 1... assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].State()", "4]) time.sleep(1) assert proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1] == 3 assert proxies.subarray[1].receptors[2] ==", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 2.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 2.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 2.2 assert", "4 # # configure scan # f = open(file_path + \"/test_json/test_ConfigureScan_basic.json\") # proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\",", "from tango import DevState import pytest # SKA specific imports from ska_mid_cbf_mcs.commons.global_enum import", "- 1].frequencyBandOffsetStream2 == 0 assert vcc_proxies[receptor_to_vcc[1] - 1].rfiFlaggingMask == \"{}\" # check configured", "# add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) # configure", "- 1].rfiFlaggingMask == \"{}\" # # check configured attributes of search windows #", "type # scan_index is an index into an array, therefore 0-based scan_index =", "1].frequencyBand == 0 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand == 0 # check the rest", "f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) # scan f2 = open(file_path + \"/../data/Scan2_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\",", "# assert fsp_1_proxies.subarray[1].frequencyBand == 4 # assert fsp_1_proxies.subarray[1].band5Tuning[0] == 5.85 # assert fsp_1_proxies.subarray[1].band5Tuning[1]", "assert proxies.fspSubarray[1].band5Tuning[1] == 7.25 assert proxies.fspSubarray[1].frequencyBandOffsetStream1 == 0 assert proxies.fspSubarray[1].frequencyBandOffsetStream2 == 0 assert", "as ae: logging.error(\"AssertionError; incorrect Jones matrix entry: epoch {}, VCC {}, i =", "minimal successful configuration # \"\"\" # for proxy in vcc_proxies: # proxy.Init() #", "1, 1) assert all([proxies.subarray[1].receptors[i] == j for i, j in zip(range(4), [4, 1,", "assert fsp_1_proxies.subarray[1].frequencySliceID == 1 # assert fsp_1_proxies.subarray[1].corrBandwidth == 1 # assert fsp_1_proxies.subarray[1].zoomWindowTuning ==", "attributes of CBF subarray assert len(proxies.subarray[sub_id].receptors) == 0 assert proxies.subarray[sub_id].configID == '' #", "ae except Exception as e: proxies.clean_proxies() raise e def test_AddRemoveReceptors_invalid_single(self, proxies): \"\"\" Test", "(including an invalid one) to subarray 2 # with pytest.raises(tango.DevFailed) as df: #", "== 745 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[1][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[2][0] ==", "assert proxies.subarray[sub_id].configID == configuration[\"common\"][\"config_id\"] assert proxies.subarray[sub_id].frequencyBand == band_index assert proxies.subarray[sub_id].obsState == ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i", "# fsp_1_proxies.subarray[1].Init() # fsp_2_proxies.subarray[1].Init() # fsp_3_proxies.subarray[1].Init() # fsp_1_proxy.Init() # fsp_2_proxy.Init() # proxies.subarray[1].set_timeout_millis(60000) #", "CBF subarray vcc_index = proxies.receptor_to_vcc[4] logging.info(\"vcc_index = {}\".format( vcc_index )) assert len(proxies.subarray[1].receptors) ==", "command takes a while # proxies.subarray[1].Init() # time.sleep(3) # cbf_master_proxy.set_timeout_millis(60000) # cbf_master_proxy.Init() #", "except Exception as e: raise e time.sleep(10) # update delay models from tm", "= json.dumps(jones_matrix) time.sleep(5) for receptor in jones_matrix[\"jonesMatrix\"][1][\"matrixDetails\"]: for frequency_slice in receptor[\"receptorMatrix\"]: for index,", "fsp_2_proxies.subarray[1].channelAveragingMap[11][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[12][0] == 8929 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[12][1]", "for i in range(3)] == input_receptors assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for i in", "ae except Exception as e: raise e # transition to obsState == SCANNING", "== fsp[\"zoom_window_tuning\"] assert proxies.fspSubarray[fsp_id].fspChannelOffset == fsp[\"channel_offset\"] for i in range(len(fsp[\"channel_averaging_map\"])): for j in", "<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- # # This file is", "> 0: assert proxies.fspSubarray[fsp_id].zoomWindowTuning == fsp[\"zoom_window_tuning\"] assert proxies.fspSubarray[fsp_id].fspChannelOffset == fsp[\"channel_offset\"] for i in", "# tm_telstate_proxy # ): # \"\"\" # Test a minimal successful configuration #", "4 assert proxies.fspSubarray[1].band5Tuning[0] == 5.85 assert proxies.fspSubarray[1].band5Tuning[1] == 7.25 assert proxies.fspSubarray[1].frequencyBandOffsetStream1 == 0", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 1.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 2.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 2.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5]", "successful scan configuration \"\"\" proxies.subarray[1].loggingLevel = LoggingLevel.DEBUG try: # turn on Subarray if", "assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY # ObsReset proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert len(proxies.subarray[1].receptors)", "assert fsp_2_proxies.subarray[1].channelAveragingMap[0][0] == 1 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[0][1] == 0 # # assert", "fsp_1_proxies.subarray[1].integrationTime == 140 # assert fsp_1_proxies.subarray[1].fspChannelOffset == 14880 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[0][0] ==", "j for i, j in zip(range(3), [1, 3, 4])]) assert proxies.fspSubarray[1].obsState == ObsState.IDLE", "assert proxies.fspSubarray[3].searchBeamID[1] == 400 # TODO: currently searchBeams is stored by the device", "# proxies.subarray[1].AddReceptors([1, 3, 4]) # time.sleep(1) # assert proxies.subarray[1].receptors[0] == 1 # assert", "assert proxies.subarray[1].obsState == ObsState.EMPTY # add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE,", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 3.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 3.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 3.9 assert", "\"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) assert proxies.subarray[1].obsState == ObsState.READY # create a", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 3.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 3.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 3.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3]", "assert searchBeam400[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" proxies.subarray[1].GoToIdle() time.sleep(3) assert proxies.subarray[1].obsState == ObsState.IDLE proxies.subarray[1].RemoveAllReceptors() time.sleep(3) assert", "{}\".format(input_receptors) ) logging.info( \"config_file_name = {}\".format(config_file_name) ) num_receptors = len(input_receptors) vcc_ids = [None", "# add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[1].receptors[i]", "of frequency band capabilities assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBand == 4 assert [proxy.State() for proxy in", "window 1... assert sw_1_proxy.State() == DevState.ON assert sw_1_proxy.searchWindowTuning == 6000000000 assert sw_1_proxy.tdcEnable ==", "proxies.subarray[1].obsState == ObsState.READY assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[3].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState", "fsp_2_proxies.subarray[1].channelAveragingMap[17][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[18][0] == 13393 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[18][1]", "configured attributes of FSPs, including states of function mode capabilities fsp_function_mode_proxies = [proxies.fsp1FunctionMode,", "search windows # first for search window 1... # TODO - SearchWidow device", "8 # assert fsp_1_proxies.subarray[1].outputLinkMap[0][0] == 0 # assert fsp_1_proxies.subarray[1].outputLinkMap[0][1] == 4 # assert", "file is part of the csp-lmc-prototype project # # # # Distributed under", "in [1, 3]]) # assert proxies.subarray[1].State() == DevState.ON # # try adding some", "1].band5Tuning[1] == 7.25 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream1 == 0 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream2", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[5][0] == 3721 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[5][1] == 0 # #", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[3][0] == 2233 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[3][1] == 0 # #", "sw_1_proxy.searchWindowTuning == 6000000000 # assert sw_1_proxy.tdcEnable == True # assert sw_1_proxy.tdcNumBits == 8", "for VCC belonging to receptor 10... assert proxies.vcc[proxies.receptor_to_vcc[4]].subarrayMembership == 1 assert proxies.vcc[proxies.receptor_to_vcc[4]].band5Tuning[0] ==", "== 7.25 # assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream1 == 0 # assert vcc_proxies[receptor_to_vcc[1] -", "either not reconfiguring in between # configurations or causing a fault within the", "= 2 elif fsp[\"function_mode\"] == \"PST-BF\": function_mode = 3 elif fsp[\"function_mode\"] == \"VLBI\":", "1] for i in range(4)], ObsState.READY, 1, 1) # check frequency band of", "== False time.sleep(1) # check configured attributes of VCC search windows # first", "= json.loads(searchBeam[0]) searchBeam1 = json.loads(searchBeam[1]) assert searchBeam0[\"search_beam_id\"] == 300 assert searchBeam0[\"receptor_ids\"][0] == 3", "Test the EndScan command \"\"\" try: # turn on Subarray if proxies.subarray[1].State() !=", "# assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].tdcEnable == False # # and lastly for search", "for i in [1, 3]]) assert proxies.subarray[1].obsState == ObsState.IDLE # TODO: fix this", "# assert sw_2_proxy.searchWindowTuning == 7000000000 # assert sw_2_proxy.tdcEnable == False # # check", "assert fsp_2_proxies.subarray[1].frequencySliceID == 20 # # assert fsp_2_proxies.subarray[1].corrBandwidth == 0 # # assert", "- 1][0].tdcEnable == True assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcNumBits == 8 assert vcc_tdc_proxies[receptor_to_vcc[4] -", "7000000000 # assert proxies.sw[2].tdcEnable == False time.sleep(1) # check configured attributes of VCC", "fsp_1_proxies.subarray[1].outputLinkMap[0][0] == 0 # assert fsp_1_proxies.subarray[1].outputLinkMap[0][1] == 4 # assert fsp_1_proxies.subarray[1].outputLinkMap[1][0] == 744", "DevState.ON # # try adding some receptors (including an invalid one) to subarray", "1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY assert len(proxies.subarray[1].receptors) == 0 assert proxies.fspSubarray[1].obsState ==", "= fsp_3_proxies.subarray[1].searchBeams # searchBeam300 = json.loads(searchBeam[0]) # searchBeam400 = json.loads(searchBeam[1]) # assert searchBeam300[\"searchBeamID\"]", "2 of VCC belonging to receptor 10... assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].State() == DevState.DISABLE", "proxies.vcc[proxies.receptor_to_vcc[4]].rfiFlaggingMask == \"{}\" # then for VCC belonging to receptor 1... assert proxies.vcc[proxies.receptor_to_vcc[1]].subarrayMembership", "logging.info( (\"proxies.vcc[vcc_index].frequencyBand = {}\". format( proxies.vcc[vcc_index].frequencyBand)) ) vcc_band_proxies = proxies.vccBand[vcc_index - 1] assert", "same # functionality is implemented by the VccSearchWindow device; # to be decide", "proxies.fspSubarray[1].frequencySliceID == 1 assert proxies.fspSubarray[1].corrBandwidth == 1 assert proxies.fspSubarray[1].zoomWindowTuning == 4700000 assert proxies.fspSubarray[1].integrationTime", "\"fizz\", \"buzz\", \"80\" # ) # # then for search window 2 of", "fsp_2_proxies.subarray[1].channelAveragingMap[2][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[3][0] == 2233 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[3][1]", "proxies.clean_proxies() raise e def test_ConfigureScan_jonesMatrix(self, proxies): \"\"\" Test the reception of Jones matrices", "# assert fsp_2_proxies.subarray[1].frequencyBandOffsetStream1 == 0 # # assert fsp_2_proxies.subarray[1].frequencyBandOffsetStream2 == 0 # #", "# time.sleep(1) # assert proxies.subarray[1].receptors[0] == 1 # assert proxies.subarray[1].receptors[1] == 3 #", "receptors proxies.subarray[1].AddReceptors(input_receptors) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert [proxies.subarray[1].receptors[i] for i in range(3)] ==", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[9][0] == 6697 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[9][1] == 0 # #", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 2.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 3.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 3.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5]", "VCCs # # first for VCC belonging to receptor 10... # assert vcc_proxies[receptor_to_vcc[4]", "epoch = str(int(epoch) + 10) # update delay model proxies.tm.beamWeights = json.dumps(timing_beam_weights) time.sleep(1)", "assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[1] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE,", "logging.info(\"VCC proxy.State() = {}\".format(proxy.State())) # for i in range(4): # if (i ==", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[15][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[16][0] == 11904 #", "proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY ############################# abort from IDLE ###########################", "\"bar\", \"8080\" # ) # # then for search window 1 of VCC", "for search window 1 of VCC belonging to receptor 10... assert vcc_tdc_proxies[receptor_to_vcc[4] -", "7000000000 assert sw_2_proxy.tdcEnable == False # check configured attributes of VCC search windows", "\"10.05.2.1\" # check configured attributes of FSP subarrays # first for FSP 1...", "not currently supported\") def test_ConfigureScan_onlyPst_basic(self, proxies): \"\"\" Test a successful PST-BF scan configuration", "DevState.ON assert proxies.subarray[1].obsState == ObsState.EMPTY # receptor list should be empty right after", "\"\")) epoch = str(int(time.time())) for matrix in jones_matrix[\"jonesMatrix\"]: matrix[\"epoch\"] = epoch if matrix[\"destinationType\"]", "involving a single subarray: - when a receptor ID is invalid (e.g. out", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 0.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 0.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 0.5 assert", "receptor_to_vcc = dict([*map(int, pair.split(\":\"))] for pair in # cbf_controller_proxy.receptorToVcc) # cbf_controller_proxy.On() # time.sleep(3)", "1].frequencyBandOffsetStream2 == 0 assert vcc_proxies[receptor_to_vcc[4] - 1].rfiFlaggingMask == \"{}\" # then for VCC", "[proxy.State() for proxy in fsp_1_function_mode_proxy] == [ # DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE #", "assert proxies.vcc[vcc_index].configID == configuration[\"common\"][\"config_id\"] assert proxies.vcc[vcc_index].frequencyBand == band_index assert proxies.vcc[vcc_index].subarrayMembership == sub_id #TODO", "fsp_1_proxies.subarray[1].frequencyBandOffsetStream1 == 0 # assert fsp_1_proxies.subarray[1].frequencyBandOffsetStream2 == 0 # assert fsp_1_proxies.subarray[1].frequencySliceID == 1", "from IDLE ########################### # add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1,", "configured attributes of FSP subarray #TODO align IDs of fspSubarrays to fsp_id in", "== ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.SCANNING assert proxies.fspSubarray[1].obsState == ObsState.SCANNING assert proxies.fspSubarray[3].obsState ==", "receptor 10... assert vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership == 1 assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[0] ==", "proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae except Exception", "# # assert fsp_2_proxies.subarray[1].band5Tuning[0] == 5.85 # # assert fsp_2_proxies.subarray[1].band5Tuning[1] == 7.25 #", "== 3720 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[5][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[6][0] ==", "proxy in vcc_band_proxies[receptor_to_vcc[1] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # check", "vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcNumBits == 8 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch == 5 #", "fsp_2_proxies.subarray[1].frequencyBandOffsetStream1 == 0 # # assert fsp_2_proxies.subarray[1].frequencyBandOffsetStream2 == 0 # # assert fsp_2_proxies.subarray[1].frequencySliceID", "# update jones matrices from tm emulator f = open(file_path + \"/../data/jonesmatrix_fsp.json\") jones_matrix", "assert fsp_2_proxies.subarray[1].channelAveragingMap[4][0] == 2977 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[4][1] == 0 # # assert", "\"buzz\", \"80\" ) # then for search window 2 of VCC belonging to", "proxies.subarray[1].receptors[2] == 4 # configure scan f = open(file_path + \"/test_json/test_ConfigureScan_onlyPss_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\"))", "def test_EndScan(self, proxies, input_test_data): \"\"\" Test the EndScan command \"\"\" try: # turn", "for i, j in zip(range(len(test_receptor_ids)), test_receptor_ids)]) # configure scan f = open(file_path +", "open(file_path + \"/../data/Configure_TM-CSP_v2.json\") configuration = f.read().replace(\"\\n\", \"\") f.close() proxies.subarray[sub_id].ConfigureScan(configuration) proxies.wait_timeout_obs([proxies.subarray[sub_id]], ObsState.READY, 15, 1)", "configured attributes of search windows # first for search window 1... # TODO", "fsp_2_proxies.subarray[1].channelAveragingMap[5][0] == 3721 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[5][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[6][0]", "proxies): \"\"\" Test abort reset \"\"\" try: # turn on Subarray if proxies.subarray[1].State()", "1) assert proxies.subarray[1].obsState == ObsState.EMPTY # Input test data: input_receptors = input_test_data[0] config_file_name", "ii in zip(input_receptors, range(num_receptors)): vcc_ids[ii] = proxies.receptor_to_vcc[receptor_id] proxies.subarray[subarr_index].AddReceptors(input_receptors) proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.IDLE, 1, 1) assert", "== ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY # ObsReset proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1)", "proxy in [proxies.fsp[i + 1] for i in range(4)]: proxy.loggingLevel = \"DEBUG\" if", "as e: proxies.clean_proxies() raise e def test_EndScan(self, proxies, input_test_data): \"\"\" Test the EndScan", "receptor ID # with pytest.raises(tango.DevFailed) as df: # proxies.subarray[1].AddReceptors([5]) # time.sleep(1) # assert", "assert proxies.fspSubarray[3].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE #############################", "+ 10) # update delay model proxies.tm.delayModel = json.dumps(delay_model) time.sleep(1) for model in", "# assert searchBeam400[\"searchBeamID\"] == 400 # assert searchBeam400[\"receptors\"][0] == 1 # assert searchBeam400[\"outputEnable\"]", "assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch == 5 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch == 25 #", "# TODO: this check does not pass, to fix #elif fsp[\"function_mode\"] == \"PST-BF\":", "assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBandOffsetStream2 == 0 assert proxies.vcc[proxies.receptor_to_vcc[4]].rfiFlaggingMask == \"{}\" # then for VCC belonging", "\"{}\" # then for VCC belonging to receptor 1... assert vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership", "== 1 assert searchBeam1[\"enable_output\"] == True assert searchBeam1[\"averaging_interval\"] == 2 # TODO -", "assert proxies.subarray[subarr_index].frequencyBand == input_band_index assert proxies.subarray[subarr_index].obsState == ObsState.READY # Send the Scan command", "1.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 1.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 1.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 1.5", "sw_2_proxy, vcc_proxies, vcc_band_proxies, vcc_tdc_proxies, fsp_1_proxy, fsp_2_proxy, fsp_1_function_mode_proxy, fsp_2_function_mode_proxy, fsp_3_proxies.subarray[1], tm_telstate_proxy ): \"\"\" Test", "assert fsp_1_proxies.subarray[1].channelAveragingMap[2][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[3][0] == 2232 # # assert", "proxies): \"\"\" Test a successful scan configuration \"\"\" proxies.subarray[1].loggingLevel = LoggingLevel.DEBUG try: #", "vcc_band_proxies = proxies.vccBand[vcc_index - 1] assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBand == 4 assert proxies.vcc[proxies.receptor_to_vcc[1]].frequencyBand == 4", "1, 1) proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae except Exception as", "1, 1) # check scanID on VCC and FSP assert proxies.fspSubarray[1].scanID == 1", "25 # assert \"\".join(sw_1_proxy.tdcDestinationAddress.split()) in [ # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", #", "\"PSS-BF\": assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.READY # TODO: this check does not pass, to", "capabilities fsp_function_mode_proxies = [proxies.fsp1FunctionMode, proxies.fsp2FunctionMode, proxies.fsp3FunctionMode, proxies.fsp4FunctionMode] for fsp in configuration[\"cbf\"][\"fsp\"]: fsp_id =", "remaining receptors proxies.subarray[1].RemoveReceptors([3]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert len(proxies.subarray[1].receptors) == 0 assert proxies.vcc[proxies.receptor_to_vcc[3]].subarrayMembership", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 2.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 2.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 2.2 assert", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[2][0] == 1489 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[2][1] == 0 #", "proxies.fspSubarray[1].outputLinkMap[0][1] == 4 assert proxies.fspSubarray[1].outputLinkMap[1][0] == 744 assert proxies.fspSubarray[1].outputLinkMap[1][1] == 8 assert proxies.fspSubarray[1].outputLinkMap[2][0]", "time.sleep(3) # cbf_controller_proxy.set_timeout_millis(60000) # cbf_controller_proxy.Init() # time.sleep(60) # takes pretty long for CBF", "for i in range(len(fsp[\"output_link_map\"])): for j in range(len(fsp[\"output_link_map\"][i])): assert proxies.fspSubarray[fsp_id].outputLinkMap[i][j] == fsp[\"output_link_map\"][i][j] proxies.clean_proxies()", "= len(input_receptors) vcc_ids = [None for _ in range(num_receptors)] for receptor_id, ii in", "fsp_1_proxies.subarray[1].channelAveragingMap[18][0] == 13392 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[18][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[19][0]", "VCC search windows # # first for search window 1 of VCC belonging", "== ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise", "\"bar\", \"8080\" # ) # then for search window 1 of VCC belonging", "1.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 1.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 1.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 1.6", "factor 8\" assert proxies.subarray[1].frequencyBand == 4 # means 5a assert proxies.subarray[1].obsState == ObsState.READY", "= {}\". format( proxies.vcc[vcc_index].frequencyBand)) ) assert proxies.vcc[vcc_index].configID == configuration[\"common\"][\"config_id\"] assert proxies.vcc[vcc_index].frequencyBand == band_index", "# assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream2 == 0 # assert vcc_proxies[receptor_to_vcc[1] - 1].rfiFlaggingMask ==", "proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e @pytest.mark.skip(reason=\"Since there's only", "proxies.vccBand[proxies.receptor_to_vcc[4] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] assert [proxy.State() for proxy", "== DevState.ON assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].searchWindowTuning == 6000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcEnable ==", "8184 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[11][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[12][0] == 8928", "== DevState.DISABLE assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].searchWindowTuning == 7000000000 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].tdcEnable ==", "len(proxies.subarray[1].receptors) == 0 assert proxies.subarray[1].configID == '' assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState", "== DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY ############################# abort", "timing_beam_weights[\"beamWeights\"]: for receptor in weights[\"beamWeightsDetails\"]: rec_id = int(receptor[\"receptor\"]) fs_id = receptor[\"receptorWeightsDetails\"][0][\"fsid\"] for index,", "assert tm_telstate_proxy.receivedOutputLinks == False # # add receptors # proxies.subarray[1].RemoveAllReceptors() # proxies.subarray[1].AddReceptors([1, 3,", "fsp_2_proxies.subarray[1].channelAveragingMap[13][0] == 9673 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[13][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[14][0]", "of FSPs, including states of function mode capabilities assert proxies.fsp[2].State() == DevState.ON assert", "DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ] # assert [proxy.State() for proxy in fsp_2_function_mode_proxy] ==", "of CBF subarray assert len(proxies.subarray[sub_id].receptors) == 0 assert proxies.subarray[sub_id].configID == '' # TODO", "# assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch == 25 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcDestinationAddress ==", "# assert [proxy.State() for proxy in fsp_1_function_mode_proxy] == [ # DevState.ON, DevState.DISABLE, DevState.DISABLE,", "assert vcc_proxies[receptor_to_vcc[1] - 1].rfiFlaggingMask == \"{}\" # check configured attributes of search windows", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 1.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 1.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 1.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0]", "== 14136 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[19][1] == 8 # assert fsp_1_proxies.subarray[1].outputLinkMap[0][0] == 0", "proxies.clean_proxies() raise e ''' def test_ConfigureScan_onlyPss_basic( self, cbf_master_proxy, proxies.subarray[1], sw_1_proxy, sw_2_proxy, vcc_proxies, vcc_band_proxies,", "# time.sleep(3) # cbf_controller_proxy.set_timeout_millis(60000) # cbf_controller_proxy.Init() # time.sleep(60) # takes pretty long for", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[5][0] == 3720 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[5][1] == 8 #", "fsp_1_proxies.subarray[1].Init() # fsp_2_proxies.subarray[1].Init() # fsp_3_proxies.subarray[1].Init() # fsp_1_proxy.Init() # fsp_2_proxy.Init() # proxies.subarray[1].set_timeout_millis(60000) # since", "proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE # Clean Up proxies.clean_proxies() except AssertionError", "for proxy in proxies.vccBand[proxies.receptor_to_vcc[2] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] #", "Master to initialize tm_telstate_proxy.Init() time.sleep(1) receptor_to_vcc = dict([*map(int, pair.split(\":\"))] for pair in cbf_master_proxy.receptorToVcc)", "== 8 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch == 5 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch ==", "not pass, to fix #elif fsp[\"function_mode\"] == \"PST-BF\": # assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.READY", "in range(len(fsp[\"channel_averaging_map\"][i])): assert proxies.fspSubarray[fsp_id].channelAveragingMap[i][j] == fsp[\"channel_averaging_map\"][i][j] for i in range(len(fsp[\"output_link_map\"])): for j in", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[17][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[18][0] == 13392 # #", "subarray_2_proxy.set_timeout_millis(60000) # proxies.subarray[1].Init() # subarray_2_proxy.Init() # time.sleep(3) # cbf_controller_proxy.set_timeout_millis(60000) # cbf_controller_proxy.Init() # time.sleep(60)", "in # cbf_master_proxy.receptorToVcc) # cbf_master_proxy.On() # time.sleep(60) # # turn on Subarray #", "proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.OFF, 3, 1) except AssertionError as ae: proxies.clean_proxies() raise ae except", "assert fsp_1_proxies.subarray[1].channelAveragingMap[0][0] == 0 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[0][1] == 8 # # assert", "6000000000 assert sw_1_proxy.tdcEnable == True assert sw_1_proxy.tdcNumBits == 8 assert sw_1_proxy.tdcPeriodBeforeEpoch == 5", "proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() time.sleep(15) # check configured attributes of CBF subarray # def", "to fsp_id in conftest; currently works for fsps 1 and 2 assert proxies.fspSubarray[fsp_id].obsState", "\"{}\" # # then for VCC belonging to receptor 1... # assert vcc_proxies[receptor_to_vcc[1]", "vcc_proxies, # vcc_band_proxies, # vcc_tdc_proxies, # fsp_1_proxy, # fsp_2_proxy, # fsp_1_function_mode_proxy, # fsp_2_function_mode_proxy,", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 4.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 4.4 time.sleep(10) assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 0.1", "vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].searchWindowTuning == 6000000000 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcEnable == True assert vcc_tdc_proxies[receptor_to_vcc[1]", "2... assert sw_2_proxy.State() == DevState.DISABLE assert sw_2_proxy.searchWindowTuning == 7000000000 assert sw_2_proxy.tdcEnable == False", "add some receptors to subarray 1 proxies.subarray[1].AddReceptors([1, 3]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert", "proxies.subarray[1].loggingLevel = LoggingLevel.DEBUG try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On()", "assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].searchWindowTuning == 6000000000 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcEnable == True assert", "# assert tm_telstate_proxy.visDestinationAddress == \"{}\" assert tm_telstate_proxy.receivedOutputLinks == False # add receptors proxies.subarray[1].AddReceptors([1,", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 1.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 2.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 2.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3]", "assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE # Clean Up proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies()", ") logging.info( \"proxies.fspPstSubarray[subarr_index-1].obsState = {}\". format(proxies.fspPstSubarray[subarr_index-1].obsState) ) # Check obsStates BEFORE the EndScan()", "for i, j in zip(range(num_receptors), input_receptors)]) assert proxies.subarray[subarr_index].obsState == ObsState.IDLE # Check fsp", "[ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[1] - 1]]", "DevState.ON] # check the rest of the configured attributes of VCCs # first", "DevState.ON assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].searchWindowTuning == 6000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcEnable == True", "== [ DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ] # TODO - # assert [proxy.State()", "takes a while proxies.subarray[1].Init() time.sleep(3) cbf_master_proxy.set_timeout_millis(60000) cbf_master_proxy.Init() time.sleep(60) # takes pretty long for", "== \"{}\" # check configured attributes of search windows # first for search", "= json.dumps(jones_matrix) time.sleep(1) for matrix in jones_matrix[\"jonesMatrix\"]: if matrix[\"destinationType\"] == \"fsp\": for receptor", "assert vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership == 1 # assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[0] == 5.85", "if fsp[\"zoom_factor\"] > 0: assert proxies.fspSubarray[fsp_id].zoomWindowTuning == fsp[\"zoom_window_tuning\"] assert proxies.fspSubarray[fsp_id].fspChannelOffset == fsp[\"channel_offset\"] for", "test_AddRemoveReceptors_invalid_multiple(self, proxies): \"\"\" Test invalid AddReceptors commands involving multiple subarrays: - when a", "debug! # assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcDestinationAddress == ( # \"fizz\", \"buzz\", \"80\" #", "there's only a single subarray, this test is currently broken.\") def test_AddRemoveReceptors_invalid_multiple(self, proxies):", "1... # assert vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership == 1 # assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[0]", "assert proxies.fspSubarray[3].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE proxies.clean_proxies()", "proxies.subarray[1].GoToIdle() # time.sleep(3) # assert proxies.subarray[1].obsState == ObsState.IDLE # proxies.subarray[1].RemoveAllReceptors() # time.sleep(3) #", "if proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY", "aa[jj][\"delayCoeff\"]) ) try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On() proxies.wait_timeout_dev([proxies.subarray[1]],", "ObsState.ABORTED # ObsReset proxies.subarray[1].ObsReset() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].obsState == ObsState.IDLE assert", "abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED # Restart: receptors", "= dict([*map(int, pair.split(\":\"))] for pair in cbf_master_proxy.receptorToVcc) cbf_master_proxy.On() time.sleep(3) # check initial value", "band_index = freq_band_dict()[configuration[\"common\"][\"frequency_band\"]] # check configured attributes of CBF subarray assert sub_id ==", "== 1 # assert proxies.subarray[1].receptors[1] == 3 # assert proxies.subarray[1].receptors[2] == 4 #", "0 assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBandOffsetStream2 == 0 assert proxies.vcc[proxies.receptor_to_vcc[2]].rfiFlaggingMask == \"{}\" # check configured attributes", "proxies.subarray[1].obsState == ObsState.EMPTY assert len(proxies.subarray[1].receptors) == 0 assert proxies.fspSubarray[1].obsState == ObsState.IDLE assert proxies.fspSubarray[3].obsState", "j for i, j in zip(range(3), [1, 3, 4])]) # configure scan f1", "tm_telstate_proxy # ): # \"\"\" # Test a minimal successful configuration # \"\"\"", "FSP 1... # assert fsp_1_proxies.subarray[1].obsState == ObsState.EMPTY # assert fsp_1_proxies.subarray[1].receptors == 4 #", "== 8 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch == 5 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch ==", "8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[13][0] == 9672 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[13][1] == 8", "== 0 assert proxies.vcc[proxies.receptor_to_vcc[4]].rfiFlaggingMask == \"{}\" # then for VCC belonging to receptor", "- 1][0].tdcNumBits == 8 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch == 5 assert proxies.vccTdc[proxies.receptor_to_vcc[4] -", "if proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) for proxy in [proxies.fsp[i", "== 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[5][0] == 3721 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[5][1] ==", "== DevState.DISABLE assert sw_2_proxy.searchWindowTuning == 7000000000 assert sw_2_proxy.tdcEnable == False # check configured", "proxies.receptor_to_vcc[4] logging.info(\"vcc_index = {}\".format( vcc_index )) assert len(proxies.subarray[1].receptors) == 0 assert proxies.subarray[1].configID ==", "proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY # ObsReset proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1,", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 2.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 2.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 2.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1]", "DevState.DISABLE assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].searchWindowTuning == 7000000000 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].tdcEnable == False", "DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[1] - 1]] ==", "[proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[1] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON]", "== 1 assert proxies.subarray[1].receptors[1] == 3 proxies.subarray[1].RemoveAllReceptors() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]],", "VCC belonging to receptor 10... assert vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership == 1 # then", "proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].State() == DevState.ON assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].searchWindowTuning == 6000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[1]", "- 1][1].tdcEnable == False assert fsp_3_proxies.subarray[1].receptors[0] == 3 assert fsp_3_proxies.subarray[1].receptors[1] == 1 assert", "factor 8\" assert proxies.subarray[1].frequencyBand == 4 assert proxies.subarray[1].obsState == ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i + 1]", "IDLE ########################### # add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1)", "4]]) assert proxies.subarray[1].obsState == ObsState.EMPTY proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.OFF, 3, 1) except AssertionError as", "# subarray_2_proxy.Init() # time.sleep(3) # cbf_controller_proxy.set_timeout_millis(60000) # cbf_controller_proxy.Init() # time.sleep(60) # takes pretty", "== \"{}\" assert tm_telstate_proxy.receivedOutputLinks == False # add receptors proxies.subarray[1].AddReceptors([1, 3, 4]) time.sleep(1)", "# means 1 assert proxies.subarray[1].obsState.value == ObsState.READY.value # check frequency band of VCCs,", "if fsp[\"function_mode\"] == \"CORR\": assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.SCANNING elif fsp[\"function_mode\"] == \"PSS-BF\": assert", "# since the command takes a while proxies.subarray[1].Init() time.sleep(3) cbf_master_proxy.set_timeout_millis(60000) cbf_master_proxy.Init() time.sleep(60) #", "- 1][0].tdcDestinationAddress == ( \"fizz\", \"buzz\", \"80\" ) # then for search window", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED # ObsReset proxies.subarray[1].ObsReset() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE,", "for i, j in zip(range(3), [1, 3, 4])]) assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for", "dict([*map(int, pair.split(\":\"))] for pair in cbf_master_proxy.receptorToVcc) cbf_master_proxy.On() time.sleep(3) # check initial value of", "assert fsp_2_proxies.subarray[1].channelAveragingMap[17][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[18][0] == 13393 # # assert", "25 # assert \"\".join(proxies.sw[1].tdcDestinationAddress.split()) in [ # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", #", "proxy.State() = {}\".format(proxy.State())) # for i in range(4): # if (i == 0", "check configured attributes of search windows # # first for search window 1...", "fsp_2_proxies.subarray[1].Init() fsp_3_proxies.subarray[1].Init() fsp_1_proxy.Init() fsp_2_proxy.Init() time.sleep(3) cbf_master_proxy.set_timeout_millis(60000) cbf_master_proxy.Init() time.sleep(60) # takes pretty long for", "from tm emulator f = open(file_path + \"/../data/delaymodel_fsp.json\") delay_model = json.loads(f.read().replace(\"\\n\", \"\")) epoch", "private data #assert proxies.subarray[sub_id].frequencyBand == 0 assert proxies.subarray[sub_id].obsState == ObsState.EMPTY # add receptors", "- when a receptor ID is invalid (e.g. out of range) - when", "proxies.fspSubarray[1].receptors == 4 assert proxies.fspSubarray[1].frequencyBand == 4 assert proxies.fspSubarray[1].band5Tuning[0] == 5.85 assert proxies.fspSubarray[1].band5Tuning[1]", "function_mode = 3 elif fsp[\"function_mode\"] == \"VLBI\": function_mode = 4 assert proxies.fsp[fsp_id].functionMode ==", "range(len(fsp[\"channel_averaging_map\"][i])): assert proxies.fspSubarray[fsp_id].channelAveragingMap[i][j] == fsp[\"channel_averaging_map\"][i][j] for i in range(len(fsp[\"output_link_map\"])): for j in range(len(fsp[\"output_link_map\"][i])):", "== ObsState.SCANNING # abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED", "VCC belonging to receptor 10... assert vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership == 1 assert vcc_proxies[receptor_to_vcc[4]", "vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[1] == 7.25 # assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream1 == 0 #", "1].frequencyBandOffsetStream1 == 0 assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream2 == 0 assert vcc_proxies[receptor_to_vcc[4] - 1].rfiFlaggingMask", "of function mode capabilities assert proxies.fsp[2].State() == DevState.ON assert proxies.fsp[2].functionMode == 3 assert", "lastly for search window 2 of VCC belonging to receptor 1... assert proxies.vccTdc[proxies.receptor_to_vcc[1]", "at end of scan, clear all private data #assert proxies.subarray[sub_id].frequencyBand == 0 assert", ") # Check obsStates BEFORE the EndScan() command assert proxies.subarray[subarr_index].obsState == ObsState.SCANNING assert", "== SCANNING f2 = open(file_path + \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1,", "== 1 # assert searchBeam400[\"outputEnable\"] == True # assert searchBeam400[\"averagingInterval\"] == 2 #", "1) assert proxies.subarray[1].obsState == ObsState.ABORTED assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[3].obsState == ObsState.READY", "== 4700000 assert proxies.fspSubarray[1].integrationTime == 1 assert proxies.fspSubarray[1].fspChannelOffset == 14880 assert proxies.fspSubarray[1].channelAveragingMap[0][0] ==", "== 4 # assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[4] - 1]] == [", "from datetime import datetime import json import logging # Path file_path = os.path.dirname(os.path.abspath(__file__))", "TODO - re-enable and debug! # assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcDestinationAddress == ( #", "proxies.fsp[fs_id].jonesMatrix[rec_id - 1][index] == value except AssertionError as ae: raise ae except Exception", "configure scan f = open(file_path + \"/test_json/data_model_confluence.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() time.sleep(15) # check", "= {}\". format(proxies.fspPstSubarray[subarr_index-1].obsState) ) # Check obsStates BEFORE the EndScan() command assert proxies.subarray[subarr_index].obsState", "1][0].tdcPeriodAfterEpoch == 25 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcDestinationAddress == ( \"foo\", \"bar\", \"8080\" )", "i in [1, 3]]) assert proxies.subarray[1].obsState == ObsState.IDLE # TODO: fix this #", "receptor per fsp test_receptor_ids = [4, 1] #test_receptor_ids = [1] vcc_index = proxies.receptor_to_vcc[test_receptor_ids[0]]", "format( proxies.vcc[vcc_index].frequencyBand)) ) vcc_band_proxies = proxies.vccBand[vcc_index - 1] assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBand == 4 assert", "capabilities assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBand == 4 assert [proxy.State() for proxy in proxies.vccBand[proxies.receptor_to_vcc[2] - 1]]", "this # try adding an invalid receptor ID # with pytest.raises(tango.DevFailed) as df:", "1].band5Tuning[1] == 7.25 # assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream1 == 0 # assert vcc_proxies[receptor_to_vcc[4]", "check configured attributes of FSP subarrays # first for FSP 3 ... (this", "0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[15][0] == 11161 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[15][1] == 0", "belonging to receptor 10... # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].State() == DevState.DISABLE # assert", "configure scan # f = open(file_path + \"/test_json/test_ConfigureScan_basic.json\") # proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) # f.close()", "== [ DevState.DISABLE, DevState.DISABLE, DevState.ON, DevState.DISABLE ] # check configured attributes of FSP", "assert proxies.subarray[1].obsState.value == ObsState.READY.value # # check frequency band of VCCs, including states", "f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 15, 1) # check configured attributes of CBF subarray assert", "including states of function mode capabilities assert proxies.fsp[1].functionMode == 1 assert 1 in", "== 201 assert fsp_1_proxies.subarray[1].outputLinkMap[1][1] == 1 proxies.subarray[1].GoToIdle() time.sleep(3) assert proxies.subarray[1].obsState == ObsState.IDLE proxies.subarray[1].RemoveAllReceptors()", "proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch == 25 # TODO - re-enable and debug! # assert", "ObsState.IDLE, 1, 1) assert proxies.subarray[1].obsState == ObsState.IDLE assert proxies.subarray[1].scanID == 0 assert proxies.fspSubarray[1].obsState", "2 assert proxies.fspSubarray[1].obsState == ObsState.SCANNING assert proxies.fspSubarray[3].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.SCANNING", "input_scan_dict = json.loads(json_string) proxies.subarray[subarr_index].Scan(json_string) f2.close() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.SCANNING, 1, 1) # Note: scan_id is", "== False # # and lastly for search window 2 of VCC belonging", "proxies.clean_proxies() raise e def test_Scan(self, proxies): \"\"\" Test the Scan command \"\"\" try:", "# check configured attributes of CBF subarray assert proxies.subarray[1].configID == \"band:5a, fsp1, 744", "assert proxies.subarray[sub_id].frequencyBand == band_index assert proxies.subarray[sub_id].obsState == ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i + 1] for i", "attributes of FSP subarrays # first for FSP 3 ... (this is a", "# assert proxies.subarray[1].State() == DevState.ON # assert proxies.subarray[1].ObsState == ObsState.EMPTY # # assert", "ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY # ObsReset proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]],", "1.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 1.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 1.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 2.0", "since the same # functionality is implemented by the VccSearchWindow device; # to", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 1.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 1.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 1.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4]", "f1 = open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f1.read().replace(\"\\n\", \"\")) f1.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) #", "in jones_matrix[\"jonesMatrix\"][1][\"matrixDetails\"]: for frequency_slice in receptor[\"receptorMatrix\"]: for index, value in enumerate(frequency_slice[\"matrix\"]): vcc_id =", "def test_Abort_Restart(self, proxies): \"\"\" Test abort restart \"\"\" try: # turn on Subarray", "TODO: fix this # try adding an invalid receptor ID # with pytest.raises(tango.DevFailed)", "4 # TODO - this does not pass - to debug & fix", "import DevState import pytest # SKA specific imports from ska_mid_cbf_mcs.commons.global_enum import freq_band_dict from", "fsp_1_proxies.subarray[1].channelAveragingMap[19][0] == 14136 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[19][1] == 8 # assert fsp_1_proxies.subarray[1].outputLinkMap[0][0] ==", "of the csp-lmc-prototype project # # # # Distributed under the terms of", "the CbfSubarray.\"\"\" # Standard imports import sys import os import time from datetime", "# f.close() # time.sleep(15) # # check configured attributes of CBF subarray #", "True # assert sw_1_proxy.tdcNumBits == 8 # assert sw_1_proxy.tdcPeriodBeforeEpoch == 5 # assert", "assert [proxy.State() for proxy in fsp_1_function_mode_proxy] == [ # DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE", "DevState.DISABLE, DevState.DISABLE, DevState.ON] # check the rest of the configured attributes of VCCs", "# fsp_1_proxy.Init() # fsp_2_proxy.Init() # proxies.subarray[1].set_timeout_millis(60000) # since the command takes a while", "# assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcEnable == True # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcNumBits ==", "searchBeam0[\"averaging_interval\"] == 4 # TODO - this does not pass - to debug", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 1.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 2.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 2.1 assert", "fsp_3_proxies.subarray[1].searchBeams searchBeam300 = json.loads(searchBeam[0]) searchBeam400 = json.loads(searchBeam[1]) assert searchBeam300[\"searchBeamID\"] == 300 assert searchBeam300[\"receptors\"][0]", "DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # # check the rest of the configured attributes", "# # then for FSP 3... # assert fsp_3_proxies.subarray[1].receptors[0] == 3 # assert", "the tests for the CbfSubarray.\"\"\" # Standard imports import sys import os import", "1][0].tdcPeriodAfterEpoch == 25 # TODO - re-enable and debug! # assert proxies.vccTdc[proxies.receptor_to_vcc[4] -", "assert fsp_2_proxies.subarray[1].channelAveragingMap[10][0] == 7441 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[10][1] == 0 # # assert", "assert proxies.subarray[1].configID == '' assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState == ObsState.EMPTY #", "proxies.vcc[vcc_id].jonesMatrix[fs_id-1][index] == value except AssertionError as ae: logging.error(\"AssertionError; incorrect Jones matrix entry: epoch", "all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for i in [1, 3, 4]]) assert proxies.subarray[1].obsState == ObsState.IDLE", "e time.sleep(10) # update timing beam weights from tm emulator f = open(file_path", "test_receptor_ids[0] assert proxies.fspSubarray[fsp_id].frequencyBand == band_index assert proxies.fspSubarray[fsp_id].frequencySliceID == fsp[\"frequency_slice_id\"] assert proxies.fspSubarray[fsp_id].integrationTime == fsp[\"integration_factor\"]", "the command takes a while # proxies.subarray[1].Init() # time.sleep(3) # cbf_master_proxy.set_timeout_millis(60000) # cbf_master_proxy.Init()", "assert sw_1_proxy.tdcPeriodBeforeEpoch == 5 # assert sw_1_proxy.tdcPeriodAfterEpoch == 25 # assert \"\".join(sw_1_proxy.tdcDestinationAddress.split()) in", "== 1 assert 1 in proxies.fsp[1].subarrayMembership assert [proxy.State() for proxy in proxies.fsp1FunctionMode] ==", "8 assert proxies.fspSubarray[1].channelAveragingMap[1][0] == 744 assert proxies.fspSubarray[1].channelAveragingMap[1][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[2][0] == 1488", "assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream1 == 0 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream2 == 0 assert", "check initial value of attributes of CBF subarray assert len(proxies.subarray[sub_id].receptors) == 0 assert", "1488 assert proxies.fspSubarray[1].outputLinkMap[2][1] == 12 assert proxies.fspSubarray[1].outputLinkMap[3][0] == 2232 assert proxies.fspSubarray[1].outputLinkMap[3][1] == 16", "proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED # Restart: receptors should", "cbf_master_proxy.receptorToVcc) cbf_master_proxy.On() time.sleep(3) # check initial value of attributes of CBF subarray assert", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[0][0] == 1 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[0][1] == 0 # #", "== 0 # assert fsp_1_proxies.subarray[1].frequencyBandOffsetStream2 == 0 # assert fsp_1_proxies.subarray[1].frequencySliceID == 1 #", "receptor 10... assert vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership == 1 # then for VCC belonging", "attributes of VCC search windows # # first for search window 1 of", "== (1, 3) # assert all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership == 1 for i in", "- 1][1].tdcEnable == False # # and lastly for search window 2 of", "cbf_controller_proxy.receptorToVcc) # cbf_controller_proxy.On() # time.sleep(3) # # receptor list should be empty right", "# # then for search window 2... # assert proxies.sw[2].State() == DevState.DISABLE #", "# assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcNumBits == 8 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch ==", "proxies.vccBand[vcc_index - 1] # turn on Subarray if proxies.subarray[sub_id].State() != DevState.ON: proxies.subarray[sub_id].On() proxies.wait_timeout_dev([proxies.subarray[sub_id]],", "2 assert proxies.fspSubarray[fsp_id].obsState == ObsState.READY assert proxies.fspSubarray[fsp_id].receptors == test_receptor_ids[0] assert proxies.fspSubarray[fsp_id].frequencyBand == band_index", "fsp_3_proxies.subarray[1].receptors[0] == 3 # assert fsp_3_proxies.subarray[1].receptors[1] == 1 # assert fsp_3_proxies.subarray[1].searchWindowID == 2", "DevState.DISABLE # assert sw_2_proxy.searchWindowTuning == 7000000000 # assert sw_2_proxy.tdcEnable == False # #", "assert proxies.subarray[1].frequencyBand == 4 # means 5a assert proxies.subarray[1].obsState == ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i +", "1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY ############################# abort from IDLE ########################### # add", "744 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[1][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[2][0] == 1488", "to subarray 1 proxies.subarray[1].AddReceptors([1, 3]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].receptors[0] == 1", "logging.info( \"delayCoeff = {}\".format( aa[jj][\"delayCoeff\"]) ) try: # turn on Subarray if proxies.subarray[1].State()", "== 11161 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[15][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[16][0] ==", "in proxies.fsp1FunctionMode] == [ DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ] # TODO - #", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1, 1) proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae except", "create a delay model # Insert the epoch delay_model[\"delayModel\"][0][\"epoch\"] = str(int(time.time()) + 20)", "assert searchBeam0[\"averaging_interval\"] == 4 # TODO - this does not pass - to", "raise ae except Exception as e: proxies.clean_proxies() raise e def test_ConfigureScan_jonesMatrix(self, proxies): \"\"\"", "fsp_1_proxies.subarray[1].channelAveragingMap[17][0] == 12648 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[17][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[18][0]", "== ObsState.IDLE # abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED", "delay_model = json.loads(f.read().replace(\"\\n\", \"\")) epoch = str(int(time.time())) for model in delay_model[\"delayModel\"]: model[\"epoch\"] =", "FSP subarrays # # first for FSP 1... # assert fsp_1_proxies.subarray[1].obsState == ObsState.EMPTY", "f = open(file_path + \"/../data/timingbeamweights.json\") timing_beam_weights = json.loads(f.read().replace(\"\\n\", \"\")) epoch = str(int(time.time())) for", "vcc_band_proxies: # logging.info(\"VCC proxy.State() = {}\".format(proxy.State())) # for i in range(4): # if", "fsp_1_proxies.subarray[1].channelAveragingMap[11][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[12][0] == 8928 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[12][1]", "# add some receptors to subarray 1 proxies.subarray[1].AddReceptors([1, 3]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1)", "Test a minimal successful configuration # \"\"\" # for proxy in vcc_proxies: #", "to initialize # tm_telstate_proxy.Init() # time.sleep(1) # receptor_to_vcc = dict([*map(int, pair.split(\":\"))] for pair", "proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[3].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState", "assert fsp_1_proxies.subarray[1].outputLinkMap[2][0] == 1488 # assert fsp_1_proxies.subarray[1].outputLinkMap[2][1] == 12 # assert fsp_1_proxies.subarray[1].outputLinkMap[3][0] ==", "1) assert proxies.subarray[1].obsState == ObsState.READY assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[3].obsState == ObsState.READY", "be empty right after initialization assert len(proxies.subarray[1].receptors) == 0 assert all([proxies.vcc[i + 1].subarrayMembership", "25 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcDestinationAddress == ( # \"foo\", \"bar\", \"8080\" #", "2232 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[3][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[4][0] == 2976", "proxies.subarray[subarr_index].ConfigureScan(json_string) f.close() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.READY, 15, 1) logging.info( \"First vcc obsState AFTER ConfigureScan =", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 2.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 2.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 2.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4]", "- 1][0].State() == DevState.ON assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].searchWindowTuning == 6000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[4] -", "test data: input_receptors = input_test_data[0] config_file_name = input_test_data[1] subarr_index = 1; logging.info( \"input_receptors", "subarray #TODO align IDs of fspSubarrays to fsp_id in conftest; currently works for", "# fsp_2_proxy.Init() # proxies.subarray[1].set_timeout_millis(60000) # since the command takes a while # proxies.subarray[1].Init()", "# assert \"already in use\" in str(df.value.args[0].desc) # assert subarray_2_proxy.receptors == (2, 4)", "assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcDestinationAddress == ( # \"foo\", \"bar\", \"8080\" # ) #", "range(len(fsp[\"output_link_map\"])): for j in range(len(fsp[\"output_link_map\"][i])): assert proxies.fspSubarray[fsp_id].outputLinkMap[i][j] == fsp[\"output_link_map\"][i][j] proxies.clean_proxies() except AssertionError as", "@pytest.mark.skip(reason=\"pst not currently supported\") def test_ConfigureScan_onlyPst_basic(self, proxies): \"\"\" Test a successful PST-BF scan", "for search window 1... # assert sw_1_proxy.State() == DevState.ON # assert sw_1_proxy.searchWindowTuning ==", "1].subarrayMembership == 1 # assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[0] == 5.85 # assert vcc_proxies[receptor_to_vcc[4]", "proxies.subarray[1].configID == '' assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState == ObsState.EMPTY # add", "proxies.subarray[1].AddReceptors([1, 3]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1] ==", "of scan, clear all private data #assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState ==", "== 6000000000 # assert proxies.sw[1].tdcEnable == True # assert proxies.sw[1].tdcNumBits == 8 #", "to receptor 1... # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].State() == DevState.ON # assert vcc_tdc_proxies[receptor_to_vcc[1]", "0 assert proxies.subarray[sub_id].configID == '' # TODO in CbfSubarray, at end of scan,", "== 0 assert proxies.subarray[1].obsState == ObsState.EMPTY # add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2])", "zip(range(1), [2])]) assert all([proxies.fspSubarray[6].timingBeamID[i] == j for i, j in zip(range(1), [10])]) #", "sw_2_proxy.State() == DevState.DISABLE # assert sw_2_proxy.searchWindowTuning == 7000000000 # assert sw_2_proxy.tdcEnable == False", "i in range(4)]) # add some receptors to subarray 1 proxies.subarray[1].AddReceptors([1, 3]) proxies.wait_timeout_obs([proxies.subarray[1]],", "for fsp in input_config_dict[\"cbf\"][\"fsp\"]: if fsp[\"function_mode\"] == \"CORR\": assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.READY elif", "scan f = open(file_path + \"/../data/Configure_TM-CSP_v2.json\") configuration = f.read().replace(\"\\n\", \"\") f.close() proxies.subarray[sub_id].ConfigureScan(configuration) proxies.wait_timeout_obs([proxies.subarray[sub_id]],", "Standard imports import sys import os import time from datetime import datetime import", "raise ae except Exception as e: proxies.clean_proxies() raise e #TODO: fix; currently tests", "8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[9][0] == 6696 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[9][1] == 8", "ObsState.READY assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[3].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY", "ObsState.SCANNING time.sleep(10) for receptor in jones_matrix[\"jonesMatrix\"][2][\"matrixDetails\"]: for frequency_slice in receptor[\"receptorMatrix\"]: for index, value", "8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[7][0] == 5208 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[7][1] == 8", "1].rfiFlaggingMask == \"{}\" # check configured attributes of search windows # first for", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[4][0] == 2977 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[4][1] == 0 #", "to FSP \"\"\" try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On()", "fsp[\"frequency_slice_id\"] assert proxies.fspSubarray[fsp_id].integrationTime == fsp[\"integration_factor\"] assert proxies.fspSubarray[fsp_id].corrBandwidth == fsp[\"zoom_factor\"] if fsp[\"zoom_factor\"] > 0:", "# assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[1] == 7.25 # assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream1 ==", "\"\"\" Test a successful transmission of PST-BF parameters to FSP \"\"\" try: #", "assert proxies.subarray[1].obsState == ObsState.READY #create a Jones matrix f = open(file_path + \"/../data/jonesmatrix.json\")", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[8][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[9][0] == 6696 #", "\"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) assert proxies.subarray[1].obsState == ObsState.SCANNING assert proxies.subarray[1].scanID ==", "update Jones Matrix proxies.tm.jonesMatrix = json.dumps(jones_matrix) time.sleep(1) for matrix in jones_matrix[\"jonesMatrix\"]: if matrix[\"destinationType\"]", "= \"0\" jones_matrix[\"jonesMatrix\"][2][\"epoch\"] = str(int(time.time()) + 10) # update Jones Matrix proxies.tm.jonesMatrix =", "as ae: raise ae except Exception as e: raise e time.sleep(10) # Clean", "= json.loads(configuration) band_index = freq_band_dict()[configuration[\"common\"][\"frequency_band\"]] # check configured attributes of CBF subarray assert", "-1]].obsState == ObsState.READY assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.READY for fsp in input_config_dict[\"cbf\"][\"fsp\"]: if fsp[\"function_mode\"]", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 3.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 3.4 # transition to obsState=SCANNING f2", "obsState == SCANNING f2 = open(file_path + \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING,", "assert len(proxies.subarray[1].receptors) == 0 assert proxies.subarray[1].configID == '' assert proxies.subarray[1].frequencyBand == 0 assert", "for proxy in fsp_function_mode_proxies[fsp_id-1]] == [ DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ] # check", "range(4)]: if proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) assert proxies.subarray[1].State() ==", "VCC belonging to receptor 1... assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].State() == DevState.DISABLE assert proxies.vccTdc[proxies.receptor_to_vcc[1]", "== fsp[\"channel_offset\"] for i in range(len(fsp[\"channel_averaging_map\"])): for j in range(len(fsp[\"channel_averaging_map\"][i])): assert proxies.fspSubarray[fsp_id].channelAveragingMap[i][j] ==", "ObsState.IDLE # Clean Up proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae except", "fs_id-1, proxies.vcc[vcc_id].jonesMatrix[fs_id-1]) ) raise ae except Exception as e: raise e # transition", "assert searchBeam1[\"search_beam_id\"] == 400 assert searchBeam1[\"receptor_ids\"][0] == 1 assert searchBeam1[\"enable_output\"] == True assert", "fsp_3_proxies.subarray[1].receptors[1] == 1 # assert fsp_3_proxies.subarray[1].searchWindowID == 2 # assert fsp_3_proxies.subarray[1].searchBeamID[0] == 300", "0 # # assert fsp_2_proxies.subarray[1].frequencySliceID == 20 # # assert fsp_2_proxies.subarray[1].corrBandwidth == 0", "self, # cbf_master_proxy, # proxies.subarray[1], # sw_1_proxy, # sw_2_proxy, # vcc_proxies, # vcc_band_proxies,", "3 assert fsp_3_proxies.subarray[1].receptors[1] == 1 assert fsp_3_proxies.subarray[1].searchWindowID == 2 assert fsp_3_proxies.subarray[1].searchBeamID[0] == 300", "end of scan, clear all private data #assert proxies.subarray[sub_id].frequencyBand == 0 assert proxies.subarray[sub_id].obsState", "debug & fix #assert searchBeam0[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" assert searchBeam1[\"search_beam_id\"] == 400 assert searchBeam1[\"receptor_ids\"][0]", "in enumerate(receptor[\"receptorMatrix\"][0][\"matrix\"]): try: assert proxies.fsp[fs_id].jonesMatrix[rec_id - 1][index] == value except AssertionError as ae:", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[12][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[13][0] == 9673 #", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[4][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[5][0] == 3720 # #", "0 for i in range(4)]) # add some receptors proxies.subarray[1].AddReceptors([1, 3, 4]) proxies.wait_timeout_obs([proxies.subarray[1]],", "def test_ConfigureScan_onlyPss_basic( self, cbf_master_proxy, proxies.subarray[1], sw_1_proxy, sw_2_proxy, vcc_proxies, vcc_band_proxies, vcc_tdc_proxies, fsp_1_proxy, fsp_2_proxy, fsp_1_function_mode_proxy,", "capabilities logging.info( (\"proxies.vcc[vcc_index].frequencyBand = {}\". format( proxies.vcc[vcc_index].frequencyBand)) ) vcc_band_proxies = proxies.vccBand[vcc_index - 1]", "for proxy in vcc_proxies: proxy.Init() fsp_3_proxies.subarray[1].Init() fsp_1_proxy.Init() fsp_2_proxy.Init() proxies.subarray[1].set_timeout_millis(60000) # since the command", "TODO: this check does not pass, to fix #elif fsp[\"function_mode\"] == \"PST-BF\": #", "# assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcDestinationAddress == ( # \"fizz\", \"buzz\", \"80\" # )", "ObsState.SCANNING # TODO: this check does not pass, to fix #elif fsp[\"function_mode\"] ==", "+ \"/../data/delaymodel.json\") delay_model = json.loads(f.read().replace(\"\\n\", \"\")) f.close() aa = delay_model[\"delayModel\"][0][\"delayDetails\"][0][\"receptorDelayDetails\"] num_fsp_IDs = len(aa)", "for search window 1 of VCC belonging to receptor 10... # assert vcc_tdc_proxies[receptor_to_vcc[4]", "Insert the epoch delay_model[\"delayModel\"][0][\"epoch\"] = str(int(time.time()) + 20) delay_model[\"delayModel\"][1][\"epoch\"] = \"0\" delay_model[\"delayModel\"][2][\"epoch\"] =", "== 4 # assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand == 4 # assert [proxy.State() for", "vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].State() == DevState.ON # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].searchWindowTuning == 6000000000 #", "jones_matrix = json.loads(f.read().replace(\"\\n\", \"\")) f.close() jones_matrix[\"jonesMatrix\"][0][\"epoch\"] = str(int(time.time()) + 20) jones_matrix[\"jonesMatrix\"][1][\"epoch\"] = \"0\"", "config_file_name) json_string = f.read().replace(\"\\n\", \"\") input_config_dict = json.loads(json_string) proxies.subarray[subarr_index].ConfigureScan(json_string) f.close() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.READY, 15,", "assert proxies.subarray[sub_id].obsState == ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i + 1] for i in range(4)], ObsState.READY, 1,", "one) to subarray 2 # with pytest.raises(tango.DevFailed) as df: # subarray_2_proxy.AddReceptors([1, 2, 4])", "# means 5a assert proxies.subarray[1].obsState == ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i + 1] for i in", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[7][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[8][0] == 5953 #", "j in zip(range(len(test_receptor_ids)), test_receptor_ids)]) # configure scan f = open(file_path + \"/../data/Configure_TM-CSP_v2.json\") configuration", "False # and lastly for search window 2 of VCC belonging to receptor", "1... assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].State() == DevState.DISABLE assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].searchWindowTuning == 7000000000", "25 # TODO - re-enable and debug! # assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcDestinationAddress ==", "== False # add receptors proxies.subarray[1].RemoveAllReceptors() proxies.subarray[1].AddReceptors([1, 3, 4]) time.sleep(1) assert proxies.subarray[1].receptors[0] ==", "# assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcDestinationAddress == ( # \"foo\", \"bar\", \"8080\" # )", "DevState.ON, 1, 1) # check initial value of attributes of CBF subarray assert", "to receptor 10... # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].State() == DevState.DISABLE # assert vcc_tdc_proxies[receptor_to_vcc[4]", "proxies.fsp[fs_id].delayModel[rec_id - 1][index] == value except AssertionError as ae: raise ae except Exception", "assert subarray_2_proxy.State() == DevState.OFF # # add some receptors to subarray 1 #", "assert fsp_1_proxies.subarray[1].channelAveragingMap[16][0] == 11904 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[16][1] == 8 # # assert", "band of VCCs, including states of frequency band capabilities assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBand == 4", "assert proxies.subarray[1].obsState == ObsState.ABORTED # ObsReset proxies.subarray[1].ObsReset() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].obsState", "sw_1_proxy.tdcPeriodAfterEpoch == 25 # assert \"\".join(sw_1_proxy.tdcDestinationAddress.split()) in [ # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", #", "# assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[1] == 7.25 # assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream1 ==", "these tests; issue with VccBand devices either not reconfiguring in between # configurations", "== 7440 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[10][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[11][0] ==", "configuration \"\"\" proxies.subarray[1].loggingLevel = LoggingLevel.DEBUG try: # turn on Subarray if proxies.subarray[1].State() !=", "\"\"\" for proxy in vcc_proxies: proxy.Init() fsp_1_proxies.subarray[1].Init() fsp_2_proxies.subarray[1].Init() fsp_3_proxies.subarray[1].Init() fsp_1_proxy.Init() fsp_2_proxy.Init() time.sleep(3) cbf_master_proxy.set_timeout_millis(60000)", "assert proxies.fspSubarray[1].channelAveragingMap[0][0] == 0 assert proxies.fspSubarray[1].channelAveragingMap[0][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[1][0] == 744 assert", "timeout_millis = proxies.subarray[1].get_timeout_millis() log_msg = \"timeout_millis = {} \".format(timeout_millis) #logging.info(log_msg) #logging.info(\"start_time = {}\".format(time.time()))", "3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].obsState == ObsState.IDLE # abort", "# fsp_1_function_mode_proxy, # fsp_2_function_mode_proxy, # fsp_1_proxies.subarray[1], # fsp_2_proxies.subarray[1], # fsp_3_proxies.subarray[1], # tm_telstate_proxy #", "== 400 searchBeam = fsp_3_proxies.subarray[1].searchBeams searchBeam300 = json.loads(searchBeam[0]) searchBeam400 = json.loads(searchBeam[1]) assert searchBeam300[\"searchBeamID\"]", "== DevState.ON assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].searchWindowTuning == 6000000000 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcEnable ==", "DevState.DISABLE # check configured attributes of FSPs, including states of function mode capabilities", "assert proxies.vcc[proxies.receptor_to_vcc[1]].subarrayMembership == 1 assert proxies.vcc[proxies.receptor_to_vcc[1]].band5Tuning[0] == 5.85 assert proxies.vcc[proxies.receptor_to_vcc[1]].band5Tuning[1] == 7.25 #", "== 3.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 3.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 3.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] ==", "10) # update delay model proxies.tm.delayModel = json.dumps(delay_model) time.sleep(1) for jj in range(4):", "############################# abort from SCANNING ########################### # add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]],", "# \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", # ] # # then for search window 2... # assert", "== \"PST-BF\": # assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.READY proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies()", "- 1][0].State() == DevState.ON assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].searchWindowTuning == 6000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[1] -", "# DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE # ] # check configured attributes of FSP", "capabilities # assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand == 4 # assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand", "assert fsp_1_proxies.subarray[1].channelAveragingMap[15][0] == 11160 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[15][1] == 8 # # assert", "# \"\"\" # Test a minimal successful configuration # \"\"\" # for proxy", "scan_id is 1-based and of 'string' type # scan_index is an index into", "VCC belonging to receptor 1... assert proxies.vcc[proxies.receptor_to_vcc[1]].subarrayMembership == 1 assert proxies.vcc[proxies.receptor_to_vcc[1]].band5Tuning[0] == 5.85", "== 4 # means 5a assert proxies.subarray[1].obsState == ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i + 1] for", "== 2.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 2.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 2.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] ==", "proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].searchWindowTuning == 6000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcEnable == True assert proxies.vccTdc[proxies.receptor_to_vcc[1]", "capabilities assert proxies.fsp[2].State() == DevState.ON assert proxies.fsp[2].functionMode == 3 assert 1 in proxies.fsp[2].subarrayMembership", "to receptor 1... assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].State() == DevState.DISABLE assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].searchWindowTuning", "to receptor 10... assert vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership == 1 # then for VCC", "# receptor_to_vcc = dict([*map(int, pair.split(\":\"))] for pair in # cbf_controller_proxy.receptorToVcc) # cbf_controller_proxy.On() #", "enumerate(frequency_slice[\"matrix\"]): vcc_id = proxies.receptor_to_vcc[receptor[\"receptor\"]] fs_id = frequency_slice[\"fsid\"] try: assert proxies.vcc[vcc_id].jonesMatrix[fs_id-1][index] == value except", "== 0 for i in range(4)]) input_receptors = [1, 3, 4] # add", "10) # update Jones Matrix proxies.tm.jonesMatrix = json.dumps(jones_matrix) time.sleep(1) for matrix in jones_matrix[\"jonesMatrix\"]:", "# time.sleep(1) # assert proxies.subarray[1].receptors == (1, 3) # assert all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 3.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 3.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 3.4 # transition", "1 in proxies.fsp[2].subarrayMembership assert [proxy.State() for proxy in proxies.fsp2FunctionMode] == [ DevState.DISABLE, DevState.DISABLE,", "subarray assert len(proxies.subarray[sub_id].receptors) == 0 assert proxies.subarray[sub_id].configID == '' # TODO in CbfSubarray,", "DevState.DISABLE assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].searchWindowTuning == 7000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].tdcEnable == False", "assert fsp_1_proxies.subarray[1].channelAveragingMap[11][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[12][0] == 8928 # # assert", "fsp_2_proxies.subarray[1].channelAveragingMap[17][0] == 12649 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[17][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[18][0]", "0.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 0.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 1.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 1.1", "DevState.DISABLE # ] # # assert [proxy.State() for proxy in fsp_2_function_mode_proxy] == [", "belonging to receptor 10... assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].State() == DevState.ON assert proxies.vccTdc[proxies.receptor_to_vcc[4] -", "# cbf_master_proxy.receptorToVcc) # cbf_master_proxy.On() # time.sleep(60) # # turn on Subarray # assert", "for receptor in model[\"delayDetails\"]: rec_id = int(receptor[\"receptor\"]) fs_id = receptor[\"receptorDelayDetails\"][0][\"fsid\"] for index, value", "- 1][1].tdcEnable == False # # check configured attributes of FSPs, including states", "freq_band_dict from ska_tango_base.control_model import LoggingLevel, HealthState from ska_tango_base.control_model import AdminMode, ObsState from ska_tango_base.base_device", "assert proxies.subarray[1].state() == tango.DevState.OFF def test_band1( self, cbf_master_proxy, proxies.subarray[1], sw_1_proxy, sw_2_proxy, vcc_proxies, vcc_band_proxies,", "attributes of CBF subarray vcc_index = proxies.receptor_to_vcc[4] logging.info(\"vcc_index = {}\".format( vcc_index )) assert", "assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch == 5 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch == 25", "\"\"\" Test valid AddReceptors and RemoveReceptors commands \"\"\" timeout_millis = proxies.subarray[1].get_timeout_millis() log_msg =", "FSP subarray #TODO align IDs of fspSubarrays to fsp_id in conftest; currently works", "proxies.subarray[1].obsState == ObsState.ABORTED # Restart: receptors should be empty proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1,", "sw_1_proxy.tdcEnable == True # assert sw_1_proxy.tdcNumBits == 8 # assert sw_1_proxy.tdcPeriodBeforeEpoch == 5", "e ''' def test_ConfigureScan_onlyPss_basic( self, cbf_master_proxy, proxies.subarray[1], sw_1_proxy, sw_2_proxy, vcc_proxies, vcc_band_proxies, vcc_tdc_proxies, fsp_1_proxy,", "sw_1_proxy.tdcNumBits == 8 assert sw_1_proxy.tdcPeriodBeforeEpoch == 5 assert sw_1_proxy.tdcPeriodAfterEpoch == 25 assert \"\".join(sw_1_proxy.tdcDestinationAddress.split())", "== ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY # abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1)", "python # -*- coding: utf-8 -*- # # This file is part of", "vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].tdcEnable == False # and lastly for search window 2 of", "assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].searchWindowTuning == 7000000000 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].tdcEnable == False assert", "== 0 # assert vcc_proxies[receptor_to_vcc[1] - 1].rfiFlaggingMask == \"{}\" # # check configured", "assert fsp_2_proxies.subarray[1].frequencyBandOffsetStream2 == 0 # # assert fsp_2_proxies.subarray[1].frequencySliceID == 20 # # assert", "proxies.subarray[subarr_index].obsState == ObsState.READY assert proxies.vcc[vcc_ids[0]].obsState == ObsState.READY assert proxies.vcc[vcc_ids[num_receptors -1]].obsState == ObsState.READY assert", "sw_2_proxy.State() == DevState.DISABLE assert sw_2_proxy.searchWindowTuning == 7000000000 assert sw_2_proxy.tdcEnable == False # check", "proxies.subarray[1].obsState == ObsState.IDLE # add more receptors... proxies.subarray[1].AddReceptors([2]) time.sleep(1) assert [proxies.subarray[1].receptors[i] for i", "json string ( via attribute 'searchBeams'); # this has to be updated in", "ObsState.IDLE assert proxies.subarray[1].scanID == 0 assert proxies.fspSubarray[1].obsState == ObsState.IDLE assert proxies.fspSubarray[3].obsState == ObsState.IDLE", "ae except Exception as e: proxies.clean_proxies() raise e #TODO: fix; currently tests break", "abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED # ObsReset proxies.subarray[1].Restart()", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 0.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 0.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 0.6 assert", "== ObsState.READY # send the Scan command f2 = open(file_path + \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\",", "IDs of fspSubarrays to fsp_id in conftest; currently works for fsps 1 and", "in fsp_2_function_mode_proxy] == [ # DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE # ] # check", "f = open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) #", "FSP subarrays # first for FSP 1... assert fsp_1_proxies.subarray[1].obsState == ObsState.READY assert fsp_1_proxies.subarray[1].frequencyBand", "proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e def test_EndScan(self, proxies,", "- 1][0].tdcEnable == True assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcNumBits == 8 assert proxies.vccTdc[proxies.receptor_to_vcc[1] -", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 1.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 1.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 1.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1]", "# transition to obsState == SCANNING f2 = open(file_path + \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\"))", "ObsState.SCANNING for fsp in input_config_dict[\"cbf\"][\"fsp\"]: if fsp[\"function_mode\"] == \"CORR\": assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.SCANNING", "imports from ska_mid_cbf_mcs.commons.global_enum import freq_band_dict from ska_tango_base.control_model import LoggingLevel, HealthState from ska_tango_base.control_model import", "json.dumps(delay_model) time.sleep(1) for jj in range(4): logging.info((\" proxies.vcc[{}].receptorID = {}\". format(jj+1, proxies.vcc[jj+1].receptorID))) logging.info(", "2.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 2.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 2.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 2.5", "time.sleep(3) # cbf_master_proxy.set_timeout_millis(60000) # cbf_master_proxy.Init() # time.sleep(60) # takes pretty long for CBF", "assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].State() == DevState.DISABLE # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].searchWindowTuning == 7000000000", "proxy.loggingLevel = \"DEBUG\" if proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) #", "of FSPs, including states of function mode capabilities # assert fsp_1_proxy.functionMode == 1", "Exception as e: proxies.clean_proxies() raise e #TODO: fix; currently tests break if multiple", "1488 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[2][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[3][0] == 2232", "= len(aa) for jj in range(num_fsp_IDs): logging.info( \"delayCoeff = {}\".format( aa[jj][\"delayCoeff\"]) ) try:", "proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE ############################# abort from READY ########################### # add receptors proxies.subarray[1].AddReceptors([1, 3,", "\"buzz\", \"80\" # ) # then for search window 2 of VCC belonging", "time.sleep(10) # Clean Up proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae except", "then for VCC belonging to receptor 1... assert proxies.vcc[proxies.receptor_to_vcc[1]].subarrayMembership == 1 assert proxies.vcc[proxies.receptor_to_vcc[1]].band5Tuning[0]", "== 1 assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[0] == 5.85 assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[1] ==", "proxies): \"\"\" Test the Scan command \"\"\" try: # turn on Subarray if", "is implemented by the VccSearchWindow device; # to be decide which one to", "proxies.tm.delayModel = json.dumps(delay_model) time.sleep(1) for jj in range(4): logging.info((\" proxies.vcc[{}].receptorID = {}\". format(jj+1,", "open(file_path + \"/../data/Scan1_basic.json\") json_string = f2.read().replace(\"\\n\", \"\") input_scan_dict = json.loads(json_string) proxies.subarray[subarr_index].Scan(json_string) f2.close() proxies.wait_timeout_obs([proxies.subarray[subarr_index]],", "matrix[\"destinationType\"] == \"fsp\": for receptor in matrix[\"matrixDetails\"]: rec_id = int(receptor[\"receptor\"]) fs_id = receptor[\"receptorMatrix\"][0][\"fsid\"]", "str(int(time.time()) + 20) jones_matrix[\"jonesMatrix\"][1][\"epoch\"] = \"0\" jones_matrix[\"jonesMatrix\"][2][\"epoch\"] = str(int(time.time()) + 10) # update", "tm_telstate_proxy ): \"\"\" Test a minimal successful configuration \"\"\" for proxy in vcc_proxies:", "CBF subarray # assert proxies.subarray[1].configID == \"band:5a, fsp1, 744 channels average factor 8\"", "1) # Note: scan_id is 1-based and of 'string' type # scan_index is", "a single subarray, this test is currently broken.\") def test_AddRemoveReceptors_invalid_multiple(self, proxies): \"\"\" Test", "fsp[\"zoom_factor\"] if fsp[\"zoom_factor\"] > 0: assert proxies.fspSubarray[fsp_id].zoomWindowTuning == fsp[\"zoom_window_tuning\"] assert proxies.fspSubarray[fsp_id].fspChannelOffset == fsp[\"channel_offset\"]", "\"\"\"Contain the tests for the CbfSubarray.\"\"\" # Standard imports import sys import os", "# assert fsp_1_proxies.subarray[1].outputLinkMap[1][0] == 744 # assert fsp_1_proxies.subarray[1].outputLinkMap[1][1] == 8 # assert fsp_1_proxies.subarray[1].outputLinkMap[2][0]", "8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[19][0] == 14136 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[19][1] == 8", "0.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 0.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 0.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 0.5", "attributes of CBF subarray # assert proxies.subarray[1].receptors == () # assert proxies.subarray[1].configID ==", "proxies.fspSubarray[1].band5Tuning[0] == 5.85 assert proxies.fspSubarray[1].band5Tuning[1] == 7.25 assert proxies.fspSubarray[1].frequencyBandOffsetStream1 == 0 assert proxies.fspSubarray[1].frequencyBandOffsetStream2", "vcc obsState AFTER ConfigureScan = {}\". format(proxies.vcc[vcc_ids[0]].obsState) ) # check some configured attributes", "assert searchBeam300[\"outputEnable\"] == True # assert searchBeam300[\"averagingInterval\"] == 4 # assert searchBeam300[\"searchBeamDestinationAddress\"] ==", "= {}\". format(proxies.vcc[vcc_ids[0]].obsState) ) f = open(file_path + config_file_name) json_string = f.read().replace(\"\\n\", \"\")", "capabilities assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand == 4 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand == 4", "check configured attributes of FSPs, including states of function mode capabilities assert proxies.fsp[1].functionMode", "in range(4)]: proxy.loggingLevel = \"DEBUG\" if proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1,", "\"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", # ] # # then for", "raise ae except Exception as e: raise e time.sleep(10) # update delay models", "\"\"\" Test a successful PST-BF scan configuration \"\"\" try: # turn on Subarray", "csp-lmc-prototype project # # # # Distributed under the terms of the BSD-3-Clause", "== ObsState.READY # abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED", "def test_ConfigureScan_jonesMatrix(self, proxies): \"\"\" Test the reception of Jones matrices \"\"\" try: #", "8 assert sw_1_proxy.tdcPeriodBeforeEpoch == 5 assert sw_1_proxy.tdcPeriodAfterEpoch == 25 assert \"\".join(sw_1_proxy.tdcDestinationAddress.split()) in [", "(band_index - 1)): # assert vcc_band_proxies[i].State() == DevState.ON # else: # assert vcc_band_proxies[i].State()", "vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[0] == 5.85 # assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[1] == 7.25 #", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 3.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 3.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 3.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5]", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 3.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 3.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 3.7 assert", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[14][0] == 10416 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[14][1] == 8 #", "proxy in vcc_proxies: # proxy.Init() # proxies.subarray[1].set_timeout_millis(60000) # subarray_2_proxy.set_timeout_millis(60000) # proxies.subarray[1].Init() # subarray_2_proxy.Init()", "1][0].searchWindowTuning == 6000000000 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcEnable == True # assert vcc_tdc_proxies[receptor_to_vcc[1]", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 2.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 2.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 2.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5]", "assert proxies.subarray[1].configID == \"band:5a, fsp1, 744 channels average factor 8\" # assert proxies.subarray[1].frequencyBand", "pair.split(\":\"))] for pair in # cbf_controller_proxy.receptorToVcc) # cbf_controller_proxy.On() # time.sleep(3) # # receptor", "DevState.ON, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY # Input test data: input_receptors =", "\"bar\", \"8080\" ) # then for search window 1 of VCC belonging to", "receptor 1... # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].State() == DevState.DISABLE # assert vcc_tdc_proxies[receptor_to_vcc[1] -", "CBF subarray assert len(proxies.subarray[sub_id].receptors) == 0 assert proxies.subarray[sub_id].configID == '' # TODO in", "= LoggingLevel.DEBUG try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On() proxies.wait_timeout_dev([proxies.subarray[1]],", "proxies.subarray[1].Init() # subarray_2_proxy.Init() # time.sleep(3) # cbf_controller_proxy.set_timeout_millis(60000) # cbf_controller_proxy.Init() # time.sleep(60) # takes", "= open(file_path + \"/test_json/test_ConfigureScan_basic.json\") # proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) # f.close() # time.sleep(15) # #", "tm_telstate_proxy.receivedOutputLinks == False # # add receptors # proxies.subarray[1].RemoveAllReceptors() # proxies.subarray[1].AddReceptors([1, 3, 4])", "\"\"\" Test the reception of Jones matrices \"\"\" try: # turn on Subarray", "the EndScan() command assert proxies.subarray[subarr_index].obsState == ObsState.READY assert proxies.vcc[vcc_ids[0]].obsState == ObsState.READY assert proxies.vcc[vcc_ids[num_receptors", "# assert \"\".join(proxies.sw[1].tdcDestinationAddress.split()) in [ # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\",", "try adding some receptors (including an invalid one) to subarray 2 # with", "\"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) # scan f2 = open(file_path + \"/../data/Scan2_basic.json\")", "window 1 of VCC belonging to receptor 1... assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].State() ==", "1 # assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[0] == 5.85 # assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[1]", "1, 1) # configure scan f = open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close()", "proxies.fspSubarray[1].outputLinkMap[1][0] == 744 assert proxies.fspSubarray[1].outputLinkMap[1][1] == 8 assert proxies.fspSubarray[1].outputLinkMap[2][0] == 1488 assert proxies.fspSubarray[1].outputLinkMap[2][1]", "1].frequencyBand == 4 assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[4] - 1]] == [", "5.85 # assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[1] == 7.25 # assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream1", "# assert proxies.sw[2].searchWindowTuning == 7000000000 # assert proxies.sw[2].tdcEnable == False time.sleep(1) # check", "assert fsp_3_proxies.subarray[1].searchBeamID[1] == 400 # searchBeam = fsp_3_proxies.subarray[1].searchBeams # searchBeam300 = json.loads(searchBeam[0]) #", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[18][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[19][0] == 14137 #", "15, 1) configuration = json.loads(configuration) band_index = freq_band_dict()[configuration[\"common\"][\"frequency_band\"]] # check configured attributes of", "== 2.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 2.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 3.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] ==", "1] # turn on Subarray if proxies.subarray[sub_id].State() != DevState.ON: proxies.subarray[sub_id].On() proxies.wait_timeout_dev([proxies.subarray[sub_id]], DevState.ON, 3,", "# vcc_band_proxies, # vcc_tdc_proxies, # fsp_1_proxy, # fsp_2_proxy, # fsp_1_function_mode_proxy, # fsp_2_function_mode_proxy, #", "proxies.sw[1].tdcPeriodBeforeEpoch == 5 # assert proxies.sw[1].tdcPeriodAfterEpoch == 25 # assert \"\".join(proxies.sw[1].tdcDestinationAddress.split()) in [", "4] # add some receptors proxies.subarray[1].AddReceptors(input_receptors) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert [proxies.subarray[1].receptors[i] for", "sw_1_proxy.tdcPeriodBeforeEpoch == 5 # assert sw_1_proxy.tdcPeriodAfterEpoch == 25 # assert \"\".join(sw_1_proxy.tdcDestinationAddress.split()) in [", "# then for search window 2 of VCC belonging to receptor 10... assert", "1) proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.OFF, 3, 1) except AssertionError as ae: proxies.clean_proxies() raise ae", "fsp_1_proxies.subarray[1].outputLinkMap[1][1] == 1 proxies.subarray[1].GoToIdle() time.sleep(3) assert proxies.subarray[1].obsState == ObsState.IDLE proxies.subarray[1].RemoveAllReceptors() time.sleep(1) proxies.subarray[1].Off() assert", "- 1][0].tdcNumBits == 8 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch == 5 # assert", "PST-BF scan configuration \"\"\" try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON:", "fs_id = receptor[\"receptorDelayDetails\"][0][\"fsid\"] for index, value in enumerate(receptor[\"receptorDelayDetails\"][0][\"delayCoeff\"]): try: assert proxies.fsp[fs_id].delayModel[rec_id - 1][index]", "1 assert proxies.vcc[proxies.receptor_to_vcc[1]].band5Tuning[0] == 5.85 assert proxies.vcc[proxies.receptor_to_vcc[1]].band5Tuning[1] == 7.25 # check configured attributes", "1.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 1.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 1.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 1.7", "assert proxies.subarray[1].state() == tango.DevState.OFFequency band capabilities assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand == 4 assert", "proxy in fsp_2_function_mode_proxy] == [ # # DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE # #", "assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 0 for i in [1, 2, 4]]) assert proxies.vcc[proxies.receptor_to_vcc[3]].subarrayMembership ==", "tm_telstate_proxy.visDestinationAddress == \"{}\" # assert tm_telstate_proxy.receivedOutputLinks == False # # add receptors #", "== 0 assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 0 for i in [1, 3, 4]]) assert", "proxies.fspSubarray[3].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY # abort", "== 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[9][0] == 6696 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[9][1] ==", "proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY #", "commands involving multiple subarrays: - when a receptor to be added is already", "DevState.ON: proxies.subarray[sub_id].On() proxies.wait_timeout_dev([proxies.subarray[sub_id]], DevState.ON, 3, 1) for proxy in [proxies.vcc[i + 1] for", "FSP subarrays # first for FSP 1... (this is a CORR fsp device)", "e: proxies.clean_proxies() raise e def test_EndScan(self, proxies, input_test_data): \"\"\" Test the EndScan command", "== 1 assert proxies.vcc[proxies.receptor_to_vcc[4]].scanID ==1 # check states assert proxies.subarray[1].obsState == ObsState.SCANNING assert", "1][1].tdcEnable == False # # check configured attributes of FSPs, including states of", "# Restart: receptors should be empty proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert proxies.subarray[1].obsState", "== ObsState.EMPTY # add receptors proxies.subarray[1].AddReceptors([4, 1, 3, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1)", "receptor in model[\"delayDetails\"]: rec_id = int(receptor[\"receptor\"]) fs_id = receptor[\"receptorDelayDetails\"][0][\"fsid\"] for index, value in", "all([proxies.fspSubarray[6].timingBeamID[i] == j for i, j in zip(range(1), [10])]) # Clean Up proxies.clean_proxies()", "() # assert all([proxy.subarrayMembership == 0 for proxy in vcc_proxies]) # assert proxies.subarray[1].State()", "assert searchBeam1[\"receptor_ids\"][0] == 1 assert searchBeam1[\"enable_output\"] == True assert searchBeam1[\"averaging_interval\"] == 2 #", "= dict([*map(int, pair.split(\":\"))] for pair in # cbf_master_proxy.receptorToVcc) # cbf_master_proxy.On() # time.sleep(60) #", "as e: proxies.clean_proxies() raise e def test_ConfigureScan_minimal(self, proxies): try: sub_id = 1 #TODO", "the Scan command f2 = open(file_path + \"/../data/Scan1_basic.json\") json_string = f2.read().replace(\"\\n\", \"\") input_scan_dict", "zip(input_receptors, range(num_receptors)): vcc_ids[ii] = proxies.receptor_to_vcc[receptor_id] proxies.subarray[subarr_index].AddReceptors(input_receptors) proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[subarr_index].receptors[i] ==", "as e: proxies.clean_proxies() raise e def test_ConfigureScan_jonesMatrix(self, proxies): \"\"\" Test the reception of", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[11][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[12][0] == 8928 #", "j for i, j in zip(range(3), [1, 3, 4])]) # configure scan config_file_name", "= open(file_path + \"/../data/Configure_TM-CSP_v2.json\") configuration = f.read().replace(\"\\n\", \"\") f.close() proxies.subarray[sub_id].ConfigureScan(configuration) proxies.wait_timeout_obs([proxies.subarray[sub_id]], ObsState.READY, 15,", "# ObsReset proxies.subarray[1].ObsReset() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].obsState == ObsState.IDLE assert all([proxies.subarray[1].receptors[i]", "device test is disabled since the same # functionality is implemented by the", "to the subarray \"\"\" try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON:", "VCC belonging to receptor 10... assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].State() == DevState.ON assert proxies.vccTdc[proxies.receptor_to_vcc[4]", "[ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] assert [proxy.State() for proxy in proxies.vccBand[proxies.receptor_to_vcc[1] - 1]]", "attributes of VCCs # # first for VCC belonging to receptor 10... #", "proxies.fsp3FunctionMode, proxies.fsp4FunctionMode] for fsp in configuration[\"cbf\"][\"fsp\"]: fsp_id = fsp[\"fsp_id\"] logging.info(\"{}\".format(fsp_id)) #TODO add function", "''' def test_ConfigureScan_onlyPss_basic( self, cbf_master_proxy, proxies.subarray[1], sw_1_proxy, sw_2_proxy, vcc_proxies, vcc_band_proxies, vcc_tdc_proxies, fsp_1_proxy, fsp_2_proxy,", "- 1].frequencyBand == 0 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand == 0 # check the", "DevState.DISABLE, DevState.DISABLE, DevState.ON] assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[1] - 1]] == [", "j for i, j in zip(range(1), [10])]) # Clean Up proxies.clean_proxies() except AssertionError", "is already in use by a different subarray \"\"\" # for proxy in", "ObsState.SCANNING proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1, 1) assert proxies.subarray[1].obsState == ObsState.READY # Clean Up", "\"CORR\": assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.READY elif fsp[\"function_mode\"] == \"PSS-BF\": assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.READY", "proxies.subarray[1].obsState == ObsState.EMPTY # add receptors proxies.subarray[1].AddReceptors([4, 1, 3, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1,", "assert fsp_2_proxies.subarray[1].channelAveragingMap[13][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[14][0] == 10417 # # assert", "proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED # ObsReset proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]],", "assert proxies.fspSubarray[1].channelAveragingMap[0][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[1][0] == 744 assert proxies.fspSubarray[1].channelAveragingMap[1][1] == 8 assert", "fsp_1_proxies.subarray[1].obsState == ObsState.READY assert fsp_1_proxies.subarray[1].frequencyBand == 0 assert fsp_1_proxies.subarray[1].frequencySliceID == 1 assert fsp_1_proxies.subarray[1].corrBandwidth", "# configure scan f = open(file_path + \"/../data/Configure_TM-CSP_v2.json\") configuration = f.read().replace(\"\\n\", \"\") f.close()", "0 # assert fsp_1_proxies.subarray[1].outputLinkMap[0][1] == 4 # assert fsp_1_proxies.subarray[1].outputLinkMap[1][0] == 744 # assert", "== 300 assert searchBeam0[\"receptor_ids\"][0] == 3 assert searchBeam0[\"enable_output\"] == True assert searchBeam0[\"averaging_interval\"] ==", "Exception as e: proxies.clean_proxies() raise e ''' def test_ConfigureScan_onlyPss_basic( self, cbf_master_proxy, proxies.subarray[1], sw_1_proxy,", "# remove remaining receptors proxies.subarray[1].RemoveReceptors([3]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert len(proxies.subarray[1].receptors) == 0", "proxies.subarray[1].RemoveAllReceptors() # time.sleep(3) # assert proxies.subarray[1].state() == tango.DevState.OFFequency band capabilities assert vcc_proxies[receptor_to_vcc[4] -", "== DevState.OFF # # add some receptors to subarray 1 # proxies.subarray[1].AddReceptors([1, 3])", "proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) for proxy in [proxies.fsp[i + 1] for i", "proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.SCANNING proxies.subarray[subarr_index].EndScan() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.READY, 1, 1) # Check obsStates AFTER the", "== DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) # check initial value of attributes", "assert fsp_3_proxies.subarray[1].searchBeamID[0] == 300 assert fsp_3_proxies.subarray[1].searchBeamID[1] == 400 searchBeam = fsp_3_proxies.subarray[1].searchBeams searchBeam300 =", "assert proxies.fspSubarray[1].frequencyBand == 4 assert proxies.fspSubarray[1].band5Tuning[0] == 5.85 assert proxies.fspSubarray[1].band5Tuning[1] == 7.25 assert", "3 assert 1 in proxies.fsp[2].subarrayMembership assert [proxy.State() for proxy in proxies.fsp2FunctionMode] == [", "\"10.05.1.1\" assert searchBeam400[\"searchBeamID\"] == 400 assert searchBeam400[\"receptors\"][0] == 1 assert searchBeam400[\"outputEnable\"] == True", "ObsState.SCANNING time.sleep(10) assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 2.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 2.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] ==", "== DevState.DISABLE assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].searchWindowTuning == 7000000000 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].tdcEnable ==", "for VCC belonging to receptor 1... assert vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership == 1 #", "assert sw_1_proxy.tdcNumBits == 8 assert sw_1_proxy.tdcPeriodBeforeEpoch == 5 assert sw_1_proxy.tdcPeriodAfterEpoch == 25 assert", "f = open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 15, 1) #", "fsp_1_proxies.subarray[1].integrationTime == 1400 assert fsp_1_proxies.subarray[1].outputLinkMap[0][0] == 1 assert fsp_1_proxies.subarray[1].outputLinkMap[0][1] == 0 assert fsp_1_proxies.subarray[1].outputLinkMap[1][0]", "fsp_2_proxies.subarray[1].band5Tuning[0] == 5.85 # # assert fsp_2_proxies.subarray[1].band5Tuning[1] == 7.25 # # assert fsp_2_proxies.subarray[1].frequencyBandOffsetStream1", "2.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 2.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 2.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 3.0", "== 0 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[0][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[1][0] ==", "vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[1] == 7.25 assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream1 == 0 assert vcc_proxies[receptor_to_vcc[4]", "sw_1_proxy.State() == DevState.ON assert sw_1_proxy.searchWindowTuning == 6000000000 assert sw_1_proxy.tdcEnable == True assert sw_1_proxy.tdcNumBits", "elif fsp[\"function_mode\"] == \"PSS-BF\": assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.READY # TODO: this check does", "1 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[0][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[1][0] == 745", "import sys import os import time from datetime import datetime import json import", "== 0 assert all([proxies.vcc[i + 1].subarrayMembership == 0 for i in range(4)]) #", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 2.4 proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1, 1) proxies.clean_proxies() except AssertionError as", "fsp_2_proxies.subarray[1].frequencySliceID == 20 # # assert fsp_2_proxies.subarray[1].corrBandwidth == 0 # # assert fsp_2_proxies.subarray[1].integrationTime", "fsp_2_proxies.subarray[1].channelAveragingMap[2][0] == 1489 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[2][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[3][0]", "[proxy.State() for proxy in fsp_1_function_mode_proxy] == [ DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ] #", "of VCCs, including states of # frequency band capabilities logging.info( (\"proxies.vcc[vcc_index].frequencyBand = {}\".", "does not pass - to debug & fix #assert searchBeam0[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" assert", "ObsState.IDLE assert proxies.fspSubarray[3].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE", "[proxies.fsp1FunctionMode, proxies.fsp2FunctionMode, proxies.fsp3FunctionMode, proxies.fsp4FunctionMode] for fsp in configuration[\"cbf\"][\"fsp\"]: fsp_id = fsp[\"fsp_id\"] logging.info(\"{}\".format(fsp_id)) #TODO", "accept string in FSP if fsp[\"function_mode\"] == \"CORR\": function_mode = 1 elif fsp[\"function_mode\"]", "list should be empty right after initialization # assert proxies.subarray[1].receptors == () #", "array, therefore 0-based scan_index = int(input_scan_dict[\"scan_id\"]) - 1 logging.info( \"proxies.fspCorrSubarray[subarr_index-1].obsState = {}\". format(proxies.fspCorrSubarray[subarr_index-1].obsState)", "== 5 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch == 25 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcDestinationAddress ==", "1] for i in range(4)]: if proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1,", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[12][0] == 8928 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[12][1] == 8 # #", "1) assert proxies.subarray[1].obsState == ObsState.EMPTY # add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]],", "configured attributes of CBF subarray assert sub_id == int(configuration[\"common\"][\"subarray_id\"]) assert proxies.subarray[sub_id].configID == configuration[\"common\"][\"config_id\"]", "Exception as e: raise e time.sleep(10) # update delay models from tm emulator", "== 4464 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[6][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[7][0] ==", "& fix #assert searchBeam1[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" # check configured attributes of FSP subarrays", "DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY # Input test", "window 1... # assert sw_1_proxy.State() == DevState.ON # assert sw_1_proxy.searchWindowTuning == 6000000000 #", "f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) assert proxies.subarray[1].obsState == ObsState.SCANNING assert proxies.subarray[1].scanID == 2", "import freq_band_dict from ska_tango_base.control_model import LoggingLevel, HealthState from ska_tango_base.control_model import AdminMode, ObsState from", "assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.READY for fsp in input_config_dict[\"cbf\"][\"fsp\"]: if fsp[\"function_mode\"] == \"CORR\": assert", "j for i, j in zip(range(3), [1, 3, 4])]) # configure scan f", "# to read/write individual members searchBeam = proxies.fspSubarray[3].searchBeams searchBeam0 = json.loads(searchBeam[0]) searchBeam1 =", "to subarray 1 # doing this doesn't actually throw an error proxies.subarray[1].RemoveReceptors([2]) assert", "1 # proxies.subarray[1].AddReceptors([1, 3]) # time.sleep(1) # assert proxies.subarray[1].receptors == (1, 3) #", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 0.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 0.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 0.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0]", "== 0.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 0.2 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][2] == 0.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] ==", "assert proxies.fspSubarray[1].obsState == ObsState.SCANNING assert proxies.fspSubarray[3].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.SCANNING assert", "0 assert proxies.fspSubarray[1].frequencySliceID == 1 assert proxies.fspSubarray[1].corrBandwidth == 1 assert proxies.fspSubarray[1].zoomWindowTuning == 4700000", "to receptor 1... assert vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership == 1 assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[0]", "receptor 1... assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].State() == DevState.ON assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].searchWindowTuning ==", "check the rest of the configured attributes of VCCs # first for VCC", "SearchWidow device test is disabled since the same # functionality is implemented by", "proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY # abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState ==", "0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[13][0] == 9673 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[13][1] == 0", "functionality is implemented by the VccSearchWindow device; # to be decide which one", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 1.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 1.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 1.7 assert", "of VCCs # first for VCC belonging to receptor 2... assert proxies.vcc[proxies.receptor_to_vcc[2]].subarrayMembership ==", "140 # assert fsp_1_proxies.subarray[1].fspChannelOffset == 14880 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[0][0] == 0 #", "proxies.wait_timeout_dev([proxies.subarray[sub_id]], DevState.ON, 3, 1) for proxy in [proxies.vcc[i + 1] for i in", "fsp_2_proxies.subarray[1].channelAveragingMap[0][0] == 1 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[0][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[1][0]", "== 25 # assert \"\".join(proxies.sw[1].tdcDestinationAddress.split()) in [ # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\",", "3 assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for i in [1, 3]]) assert proxies.subarray[1].obsState ==", "= 1 #TODO currently only support for 1 receptor per fsp test_receptor_ids =", "DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY # add receptors", "assert fsp_1_proxies.subarray[1].frequencySliceID == 1 assert fsp_1_proxies.subarray[1].corrBandwidth == 0 assert fsp_1_proxies.subarray[1].integrationTime == 1400 assert", "ae: logging.error(\"AssertionError; incorrect Jones matrix entry: epoch {}, VCC {}, i = {},", "of VCC belonging to receptor 10... assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].State() == DevState.DISABLE assert", "3 assert searchBeam0[\"enable_output\"] == True assert searchBeam0[\"averaging_interval\"] == 4 # TODO - this", "assert proxies.vcc[proxies.receptor_to_vcc[3]].subarrayMembership == 0 assert proxies.subarray[1].obsState == ObsState.EMPTY proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.OFF, 3, 1)", "transmission of PST-BF parameters to FSP \"\"\" try: # turn on Subarray if", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 1.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 1.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 1.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3]", "1 for i in [1, 3]]) # assert all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership == 2", "# assert \"Invalid receptor ID\" in str(df.value.args[0].desc) # try removing a receptor not", "# abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED # ObsReset", "== 1 assert searchBeam400[\"outputEnable\"] == True assert searchBeam400[\"averagingInterval\"] == 2 assert searchBeam400[\"searchBeamDestinationAddress\"] ==", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 0.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 0.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 0.8 assert", "# # first for VCC belonging to receptor 10... # assert vcc_proxies[receptor_to_vcc[4] -", "== 3 proxies.subarray[1].RemoveAllReceptors() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.OFF, 3, 1) except", "== 3.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 3.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 3.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] ==", "assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY assert proxies.fspSubarray[1].obsState == ObsState.READY assert", "jj in range(4): logging.info((\" proxies.vcc[{}].receptorID = {}\". format(jj+1, proxies.vcc[jj+1].receptorID))) logging.info( (\"Vcc, receptor 1,", "project # # # # Distributed under the terms of the BSD-3-Clause license.", "attributes of FSP subarrays # FSP 2 assert proxies.fspSubarray[6].obsState == ObsState.READY assert all([proxies.fspSubarray[6].receptors[i]", "DevState.ON, 3, 1) proxies.clean_proxies() # turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On()", "assert proxies.subarray[1].obsState == ObsState.EMPTY ############################# abort from IDLE ########################### # add receptors proxies.subarray[1].AddReceptors([1,", "proxies.fspSubarray[1].obsState == ObsState.SCANNING assert proxies.fspSubarray[3].obsState == ObsState.SCANNING proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1, 1) assert", "subarrays # first for FSP 1... assert fsp_1_proxies.subarray[1].obsState == ObsState.READY assert fsp_1_proxies.subarray[1].frequencyBand ==", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[10][0] == 7441 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[10][1] == 0 #", "1 assert proxies.fspSubarray[1].fspChannelOffset == 14880 assert proxies.fspSubarray[1].channelAveragingMap[0][0] == 0 assert proxies.fspSubarray[1].channelAveragingMap[0][1] == 8", "# Send the Scan command f2 = open(file_path + \"/../data/Scan1_basic.json\") json_string = f2.read().replace(\"\\n\",", "== [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] assert [proxy.State() for proxy in proxies.vccBand[proxies.receptor_to_vcc[1] -", "in [proxies.fsp[i + 1] for i in range(4)]: if proxy.State() == DevState.OFF: proxy.On()", "in fsp_2_proxy.subarrayMembership assert [proxy.State() for proxy in fsp_1_function_mode_proxy] == [ DevState.ON, DevState.DISABLE, DevState.DISABLE,", "DevState.DISABLE, DevState.ON] # check the rest of the configured attributes of VCCs #", "jones_matrix[\"jonesMatrix\"]: matrix[\"epoch\"] = epoch if matrix[\"destinationType\"] == \"fsp\": epoch = str(int(epoch) + 10)", "def test_AddRemoveReceptors_invalid_single(self, proxies): \"\"\" Test invalid AddReceptors commands involving a single subarray: -", "zip(range(3), [1, 3, 4])]) # configure scan config_file_name = \"/../data/ConfigureScan_basic.json\" f = open(file_path", "ObsState.SCANNING elif fsp[\"function_mode\"] == \"PSS-BF\": assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.SCANNING # TODO: this check", "vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership == 1 assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[0] == 5.85 assert vcc_proxies[receptor_to_vcc[1]", "proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) assert proxies.subarray[1].obsState == ObsState.SCANNING time.sleep(10) for", "CBF subarray frequency_band = input_config_dict[\"common\"][\"frequency_band\"] input_band_index = freq_band_dict()[frequency_band] assert proxies.subarray[subarr_index].configID == input_config_dict[\"common\"][\"config_id\"] assert", "refactored\") def test_ConfigureScan_delayModel(self, proxies): \"\"\" Test the reception of delay models \"\"\" #", "ae except Exception as e: proxies.clean_proxies() raise e def test_Abort_Restart(self, proxies): \"\"\" Test", "check configured attributes of CBF subarray # assert proxies.subarray[1].configID == \"band:5a, fsp1, 744", "9000, 1]]}).replace('\"',\"'\") # Clean Up proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae", "searchBeam300[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" assert searchBeam400[\"searchBeamID\"] == 400 assert searchBeam400[\"receptors\"][0] == 1 assert searchBeam400[\"outputEnable\"]", "- 1].band5Tuning[1] == 7.25 # assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream1 == 0 # assert", "average factor 8\" assert proxies.subarray[1].frequencyBand == 4 # means 5a assert proxies.subarray[1].obsState ==", "subarray_2_proxy.Init() # time.sleep(3) # cbf_controller_proxy.set_timeout_millis(60000) # cbf_controller_proxy.Init() # time.sleep(60) # takes pretty long", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[15][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[16][0] == 11905 #", "proxies.subarray[1].state() == tango.DevState.OFF def test_band1( self, cbf_master_proxy, proxies.subarray[1], sw_1_proxy, sw_2_proxy, vcc_proxies, vcc_band_proxies, vcc_tdc_proxies,", "{}\". format(proxies.vcc[proxies.receptor_to_vcc[1]].ObsState)) ) #proxies.vcc[0].receptorID assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 1.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 1.2 assert", "for search window 2... # assert sw_2_proxy.State() == DevState.DISABLE # assert sw_2_proxy.searchWindowTuning ==", "first for VCC belonging to receptor 10... assert vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership == 1", "== 1 for i in input_receptors]) assert proxies.subarray[1].obsState == ObsState.IDLE # add more", "then for FSP 3... # assert fsp_3_proxies.subarray[1].receptors[0] == 3 # assert fsp_3_proxies.subarray[1].receptors[1] ==", "= f.read().replace(\"\\n\", \"\") f.close() proxies.subarray[sub_id].ConfigureScan(configuration) proxies.wait_timeout_obs([proxies.subarray[sub_id]], ObsState.READY, 15, 1) configuration = json.loads(configuration) band_index", "range(num_receptors)): vcc_ids[ii] = proxies.receptor_to_vcc[receptor_id] proxies.subarray[subarr_index].AddReceptors(input_receptors) proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[subarr_index].receptors[i] == j", "for VCC belonging to receptor 10... assert vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership == 1 #", "is disabled since the same # functionality is implemented by the VccSearchWindow device;", "assert proxies.vcc[proxies.receptor_to_vcc[1]].band5Tuning[1] == 7.25 # check configured attributes of search windows # first", "FSPs, including states of function mode capabilities assert proxies.fsp[2].State() == DevState.ON assert proxies.fsp[2].functionMode", "5.85 assert proxies.vcc[proxies.receptor_to_vcc[1]].band5Tuning[1] == 7.25 # check configured attributes of search windows #", "assert proxies.fspSubarray[1].receptors == 4 assert proxies.fspSubarray[1].frequencyBand == 4 assert proxies.fspSubarray[1].band5Tuning[0] == 5.85 assert", "fix; currently tests break if multiple scan configurations are tested def test_ConfigureScan_basic(self, proxies):", "== True # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcNumBits == 8 # assert vcc_tdc_proxies[receptor_to_vcc[4] -", "of FSPs, including states of function mode capabilities assert fsp_1_proxy.functionMode == 1 assert", "\"\"\" try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.ON,", "\"\".join(sw_1_proxy.tdcDestinationAddress.split()) in [ \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", ] # then for search window", "# assert all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership == 1 for i in [1, 3]]) #", "print(\"proxies.sw[1].State() = {}\".format(proxies.sw[1].State())) # print(\"proxies.sw[2].State() = {}\".format(proxies.sw[2].State())) # assert proxies.sw[1].State() == DevState.ON #", "1].band5Tuning[0] == 5.85 assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[1] == 7.25 assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream1", "this test is currently broken.\") def test_AddRemoveReceptors_invalid_multiple(self, proxies): \"\"\" Test invalid AddReceptors commands", "frequency band capabilities assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBand == 4 assert [proxy.State() for proxy in proxies.vccBand[proxies.receptor_to_vcc[2]", "ObsState.IDLE assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.IDLE logging.info( \"First vcc obsState BEFORE ConfigureScan = {}\".", "not assigned to the subarray \"\"\" try: # turn on Subarray if proxies.subarray[1].State()", "datetime import datetime import json import logging # Path file_path = os.path.dirname(os.path.abspath(__file__)) #", "== 11160 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[15][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[16][0] ==", "search window 1 of VCC belonging to receptor 10... assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].State()", "ObsState.READY, 15, 1) # update jones matrices from tm emulator f = open(file_path", "assert fsp_1_proxies.subarray[1].channelAveragingMap[0][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[1][0] == 744 # # assert", "f.close() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.READY, 15, 1) logging.info( \"First vcc obsState AFTER ConfigureScan = {}\".", "== ObsState.EMPTY assert len(proxies.subarray[1].receptors) == 0 assert proxies.fspSubarray[1].obsState == ObsState.IDLE assert proxies.fspSubarray[3].obsState ==", "proxies.vcc[proxies.receptor_to_vcc[3]].subarrayMembership == 0 assert proxies.subarray[1].obsState == ObsState.EMPTY proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.OFF, 3, 1) except", "== 300 assert searchBeam300[\"receptors\"][0] == 3 assert searchBeam300[\"outputEnable\"] == True assert searchBeam300[\"averagingInterval\"] ==", "= int(input_scan_dict[\"scan_id\"]) - 1 logging.info( \"proxies.fspCorrSubarray[subarr_index-1].obsState = {}\". format(proxies.fspCorrSubarray[subarr_index-1].obsState) ) logging.info( \"proxies.fspPssSubarray[subarr_index-1].obsState =", "not pass - to debug & fix #assert searchBeam1[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" # check", "= frequency_slice[\"fsid\"] try: assert proxies.vcc[vcc_id].jonesMatrix[fs_id-1][index] == value except AssertionError as ae: logging.error(\"AssertionError; incorrect", "] # # assert [proxy.State() for proxy in fsp_2_function_mode_proxy] == [ # #", "= json.loads(searchBeam[0]) # searchBeam400 = json.loads(searchBeam[1]) # assert searchBeam300[\"searchBeamID\"] == 300 # assert", "test_ConfigureScan_basic( # self, # cbf_master_proxy, # proxies.subarray[1], # sw_1_proxy, # sw_2_proxy, # vcc_proxies,", "as e: proxies.clean_proxies() raise e @pytest.mark.skip(reason=\"Since there's only a single subarray, this test", "model proxies.tm.delayModel = json.dumps(delay_model) time.sleep(1) for model in delay_model[\"delayModel\"]: if model[\"destinationType\"] == \"fsp\":", "e def test_Scan(self, proxies): \"\"\" Test the Scan command \"\"\" try: # turn", "initial value of attributes of CBF subarray vcc_index = proxies.receptor_to_vcc[4] logging.info(\"vcc_index = {}\".format(", "str(int(time.time())) for weights in timing_beam_weights[\"beamWeights\"]: weights[\"epoch\"] = epoch epoch = str(int(epoch) + 10)", "ae except Exception as e: raise e time.sleep(10) for receptor in jones_matrix[\"jonesMatrix\"][0][\"matrixDetails\"]: for", ") # then for search window 2 of VCC belonging to receptor 10...", "VccBand devices either not reconfiguring in between # configurations or causing a fault", "assert 1 in fsp_2_proxy.subarrayMembership assert [proxy.State() for proxy in fsp_1_function_mode_proxy] == [ DevState.ON,", "assert len(proxies.subarray[1].receptors) == 0 assert proxies.vcc[proxies.receptor_to_vcc[3]].subarrayMembership == 0 assert proxies.subarray[1].obsState == ObsState.EMPTY proxies.subarray[1].Off()", "fsp_1_proxy.Init() fsp_2_proxy.Init() time.sleep(3) cbf_master_proxy.set_timeout_millis(60000) cbf_master_proxy.Init() time.sleep(60) # takes pretty long for CBF Master", "- 1]] == [ # DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # # check the", "== 1.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 1.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 2.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] ==", "[proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[1] - 1]] == [ # DevState.DISABLE, DevState.DISABLE, DevState.DISABLE,", "in model[\"delayDetails\"]: rec_id = int(receptor[\"receptor\"]) fs_id = receptor[\"receptorDelayDetails\"][0][\"fsid\"] for index, value in enumerate(receptor[\"receptorDelayDetails\"][0][\"delayCoeff\"]):", "# vcc_proxies, # vcc_band_proxies, # vcc_tdc_proxies, # fsp_1_proxy, # fsp_2_proxy, # fsp_1_function_mode_proxy, #", "json.dumps(jones_matrix) time.sleep(1) for matrix in jones_matrix[\"jonesMatrix\"]: if matrix[\"destinationType\"] == \"fsp\": for receptor in", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 2.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 2.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 2.3 assert", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[11][0] == 8184 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[11][1] == 8 #", "window 1 of VCC belonging to receptor 10... # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].State()", "\"fsp\": epoch = str(int(epoch) + 10) # update delay model proxies.tm.delayModel = json.dumps(delay_model)", "== ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE # Clean Up proxies.clean_proxies() except AssertionError as", "including states of function mode capabilities assert fsp_1_proxy.functionMode == 1 assert 1 in", "assert proxies.fsp[fs_id].jonesMatrix[rec_id - 1][index] == value except AssertionError as ae: raise ae except", "the Scan command \"\"\" try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON:", "open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 15, 1) # check configured", "proxies.subarray[subarr_index].obsState == ObsState.READY # Send the Scan command f2 = open(file_path + \"/../data/Scan1_basic.json\")", "an array, therefore 0-based scan_index = int(input_scan_dict[\"scan_id\"]) - 1 logging.info( \"proxies.fspCorrSubarray[subarr_index-1].obsState = {}\".", "ObsState.IDLE # add more receptors... proxies.subarray[1].AddReceptors([2]) time.sleep(1) assert [proxies.subarray[1].receptors[i] for i in range(4)]", "open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) assert proxies.subarray[1].obsState ==", "mode capabilities fsp_function_mode_proxies = [proxies.fsp1FunctionMode, proxies.fsp2FunctionMode, proxies.fsp3FunctionMode, proxies.fsp4FunctionMode] for fsp in configuration[\"cbf\"][\"fsp\"]: fsp_id", "fsp_2_proxies.subarray[1], fsp_3_proxies.subarray[1], tm_telstate_proxy ): \"\"\" Test a minimal successful configuration \"\"\" for proxy", "as e: raise e time.sleep(10) for receptor in jones_matrix[\"jonesMatrix\"][0][\"matrixDetails\"]: for frequency_slice in receptor[\"receptorMatrix\"]:", "744 channels average factor 8\" # assert proxies.subarray[1].frequencyBand == 4 # means 5a?", "ObsState.READY # TODO: this check does not pass, to fix #elif fsp[\"function_mode\"] ==", "== ObsState.READY #create a Jones matrix f = open(file_path + \"/../data/jonesmatrix.json\") jones_matrix =", "elif fsp[\"function_mode\"] == \"VLBI\": function_mode = 4 assert proxies.fsp[fsp_id].functionMode == function_mode assert sub_id", "assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcEnable == True assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcNumBits == 8 assert", "this does not pass - to debug & fix #assert searchBeam0[\"searchBeamDestinationAddress\"] == \"10.05.1.1\"", "configuration[\"common\"][\"config_id\"] assert proxies.vcc[vcc_index].frequencyBand == band_index assert proxies.vcc[vcc_index].subarrayMembership == sub_id #TODO fix these tests;", "== 7.25 # check configured attributes of search windows # first for search", "+ \"/../data/delaymodel_fsp.json\") delay_model = json.loads(f.read().replace(\"\\n\", \"\")) epoch = str(int(time.time())) for model in delay_model[\"delayModel\"]:", "assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.IDLE assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.IDLE logging.info( \"First vcc obsState BEFORE", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 3.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 3.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 3.5 assert", "[1, 3, 4])]) assert proxies.fspSubarray[1].obsState == ObsState.IDLE assert proxies.fspSubarray[3].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState", "assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBand == 4 assert [proxy.State() for proxy in proxies.vccBand[proxies.receptor_to_vcc[2] - 1]] ==", "assert fsp_2_proxies.subarray[1].channelAveragingMap[13][0] == 9673 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[13][1] == 0 # # assert", "input_receptors)]) assert proxies.subarray[subarr_index].obsState == ObsState.IDLE # Check fsp obsState BEFORE scan configuration: assert", "proxy in vcc_band_proxies[receptor_to_vcc[4] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] assert [proxy.State()", "4 # configure scan f = open(file_path + \"/test_json/data_model_confluence.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() time.sleep(15)", "# proxies.subarray[1], # sw_1_proxy, # sw_2_proxy, # vcc_proxies, # vcc_band_proxies, # vcc_tdc_proxies, #", "attributes of FSPs, including states of function mode capabilities # assert fsp_1_proxy.functionMode ==", "== 16 assert str(proxies.fspSubarray[1].visDestinationAddress).replace('\"',\"'\") == \\ str({\"outputHost\": [[0, \"192.168.0.1\"], [8184, \"192.168.0.2\"]], \"outputMac\": [[0,", "\"/test_json/test_ConfigureScan_basic.json\") # proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) # f.close() # time.sleep(15) # # check configured attributes", "10417 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[14][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[15][0] == 11161", "tango.DevState.OFFequency band capabilities assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand == 4 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand", "then for search window 2... # assert proxies.sw[2].State() == DevState.DISABLE # assert proxies.sw[2].searchWindowTuning", "= \"DEBUG\" if proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) # check", "# check the rest of the configured attributes of VCCs # # first", "== 5 # assert proxies.sw[1].tdcPeriodAfterEpoch == 25 # assert \"\".join(proxies.sw[1].tdcDestinationAddress.split()) in [ #", "currently broken.\") def test_AddRemoveReceptors_invalid_multiple(self, proxies): \"\"\" Test invalid AddReceptors commands involving multiple subarrays:", "time.sleep(15) # check configured attributes of CBF subarray assert proxies.subarray[1].configID == \"sbi-mvp01-20200325-00001-science_A\" assert", "proxies.vcc[vcc_index].frequencyBand)) ) assert proxies.vcc[vcc_index].configID == configuration[\"common\"][\"config_id\"] assert proxies.vcc[vcc_index].frequencyBand == band_index assert proxies.vcc[vcc_index].subarrayMembership ==", "from tm emulator f = open(file_path + \"/../data/timingbeamweights.json\") timing_beam_weights = json.loads(f.read().replace(\"\\n\", \"\")) epoch", "1 of VCC belonging to receptor 10... assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].State() == DevState.ON", "VCCs # first for VCC belonging to receptor 2... assert proxies.vcc[proxies.receptor_to_vcc[2]].subarrayMembership == 1", "f2 = open(file_path + \"/../data/Scan1_basic.json\") json_string = f2.read().replace(\"\\n\", \"\") input_scan_dict = json.loads(json_string) proxies.subarray[subarr_index].Scan(json_string)", "logging.info(\"VCC proxy.State() = {}\".format(proxy.State())) assert [proxy.State() for proxy in proxies.vccBand[proxies.receptor_to_vcc[4] - 1]] ==", "raise ae except Exception as e: proxies.clean_proxies() raise e @pytest.mark.skip(reason=\"Since there's only a", "try adding an invalid receptor ID # with pytest.raises(tango.DevFailed) as df: # proxies.subarray[1].AddReceptors([5])", "# FSP 2 assert proxies.fspSubarray[6].obsState == ObsState.READY assert all([proxies.fspSubarray[6].receptors[i] == j for i,", "#logging.info(log_msg) #logging.info(\"start_time = {}\".format(time.time())) logging.info(\"start datetime = {}\".format(datetime.now())) if proxies.debug_device_is_on: port = proxies.subarray[1].DebugDevice()", "cbf_master_proxy.Init() # time.sleep(60) # takes pretty long for CBF Master to initialize #", "fsp_3_proxies.subarray[1].searchBeamID[1] == 400 # searchBeam = fsp_3_proxies.subarray[1].searchBeams # searchBeam300 = json.loads(searchBeam[0]) # searchBeam400", "check configured attributes of CBF subarray # def test_ConfigureScan_basic( # self, # cbf_master_proxy,", "\"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) assert proxies.subarray[1].obsState == ObsState.SCANNING time.sleep(10) for receptor", "\"PSS-BF\": assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.SCANNING # TODO: this check does not pass, to", "fsp[\"channel_averaging_map\"][i][j] for i in range(len(fsp[\"output_link_map\"])): for j in range(len(fsp[\"output_link_map\"][i])): assert proxies.fspSubarray[fsp_id].outputLinkMap[i][j] == fsp[\"output_link_map\"][i][j]", "sw_2_proxy.tdcEnable == False # check configured attributes of VCC search windows # first", "of VCC belonging to receptor 1... # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].State() == DevState.ON", "assert sw_2_proxy.State() == DevState.DISABLE # assert sw_2_proxy.searchWindowTuning == 7000000000 # assert sw_2_proxy.tdcEnable ==", "tm_telstate_proxy.visDestinationAddress == \"{}\" assert tm_telstate_proxy.receivedOutputLinks == False # add receptors proxies.subarray[1].RemoveAllReceptors() proxies.subarray[1].AddReceptors([1, 3,", "fsp_3_proxies.subarray[1].receptors[1] == 1 assert fsp_3_proxies.subarray[1].searchWindowID == 2 assert fsp_3_proxies.subarray[1].searchBeamID[0] == 300 assert fsp_3_proxies.subarray[1].searchBeamID[1]", "assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[1] - 1]] == [ # DevState.DISABLE, DevState.DISABLE,", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 0.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 0.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 0.9 assert", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[18][0] == 13392 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[18][1] == 8 # #", "for VCC belonging to receptor 1... assert proxies.vcc[proxies.receptor_to_vcc[1]].subarrayMembership == 1 assert proxies.vcc[proxies.receptor_to_vcc[1]].band5Tuning[0] ==", "open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) # scan f2", "searchBeam = proxies.fspSubarray[3].searchBeams searchBeam0 = json.loads(searchBeam[0]) searchBeam1 = json.loads(searchBeam[1]) assert searchBeam0[\"search_beam_id\"] == 300", "is 1-based and of 'string' type # scan_index is an index into an", "# takes pretty long for CBF controller to initialize # receptor_to_vcc = dict([*map(int,", "for i, j in zip(range(3), [1, 3, 4])]) # configure scan config_file_name =", "ae: proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e #TODO refactor", "for i in range(4)]) input_receptors = [1, 3, 4] # add some receptors", "3.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 3.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 3.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 3.5", "fsp obsState BEFORE scan configuration: assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.IDLE assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.IDLE", "# assert 1 in fsp_2_proxy.subarrayMembership assert [proxy.State() for proxy in fsp_1_function_mode_proxy] == [", "ObsState.ABORTED # ObsReset proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY assert", "== input_config_dict[\"common\"][\"config_id\"] assert proxies.subarray[subarr_index].frequencyBand == input_band_index assert proxies.subarray[subarr_index].obsState == ObsState.READY # Send the", "add some receptors proxies.subarray[1].AddReceptors([1, 3, 4]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[1].receptors[i] ==", "# check configured attributes of FSPs, including states of function mode capabilities #", "5 # assert sw_1_proxy.tdcPeriodAfterEpoch == 25 # assert \"\".join(sw_1_proxy.tdcDestinationAddress.split()) in [ # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\",", "len(proxies.subarray[1].receptors) == 0 assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 0 for i in [1, 3, 4]])", "1) assert proxies.subarray[1].obsState == ObsState.IDLE # abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert", "\"{}\" # then for VCC belonging to receptor 1... assert proxies.vcc[proxies.receptor_to_vcc[1]].subarrayMembership == 1", "assert sw_1_proxy.tdcPeriodBeforeEpoch == 5 assert sw_1_proxy.tdcPeriodAfterEpoch == 25 assert \"\".join(sw_1_proxy.tdcDestinationAddress.split()) in [ \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\",", "assert \"\".join(sw_1_proxy.tdcDestinationAddress.split()) in [ \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", ] # then for search", "pass - to debug & fix #assert searchBeam1[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" # check configured", "subarray # assert proxies.subarray[1].receptors == () # assert proxies.subarray[1].configID == 0 assert proxies.subarray[1].frequencyBand", "\"{}\" assert tm_telstate_proxy.receivedOutputLinks == False # add receptors proxies.subarray[1].RemoveAllReceptors() proxies.subarray[1].AddReceptors([1, 3, 4]) time.sleep(1)", "class TestCbfSubarray: def test_AddRemoveReceptors_valid(self, proxies): \"\"\" Test valid AddReceptors and RemoveReceptors commands \"\"\"", "ae: raise ae except Exception as e: raise e time.sleep(10) # update timing", "# # check configured attributes of FSP subarrays # # first for FSP", "# ) # # then for search window 2 of VCC belonging to", "more info. \"\"\"Contain the tests for the CbfSubarray.\"\"\" # Standard imports import sys", "1, 3, 2])]) # configure scan f = open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\"))", "ObsState.EMPTY, 1, 1) proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.OFF, 3, 1) except AssertionError as ae: proxies.clean_proxies()", "into an array, therefore 0-based scan_index = int(input_scan_dict[\"scan_id\"]) - 1 logging.info( \"proxies.fspCorrSubarray[subarr_index-1].obsState =", "# assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch == 25 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcDestinationAddress ==", "assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].searchWindowTuning == 6000000000 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcEnable == True", "# # and lastly for search window 2 of VCC belonging to receptor", "ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED # ObsReset proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1,", "fsp_2_proxies.subarray[1].channelAveragingMap[13][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[14][0] == 10417 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[14][1]", "2 for i in [2, 4]]) # assert subarray_2_proxy.State() == DevState.ON def test_RemoveAllReceptors(self,", "under the terms of the BSD-3-Clause license. # See LICENSE.txt for more info.", "proxies.vcc[proxies.receptor_to_vcc[4]].subarrayMembership == 1 assert proxies.vcc[proxies.receptor_to_vcc[4]].band5Tuning[0] == 5.85 assert proxies.vcc[proxies.receptor_to_vcc[4]].band5Tuning[1] == 7.25 assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBandOffsetStream1", "3 elif fsp[\"function_mode\"] == \"VLBI\": function_mode = 4 assert proxies.fsp[fsp_id].functionMode == function_mode assert", "assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[3].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert", "== ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE ############################# abort from READY ########################### # add", "6000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcEnable == True assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcNumBits == 8", "\"\"\" Test a minimal successful configuration \"\"\" for proxy in vcc_proxies: proxy.Init() fsp_1_proxies.subarray[1].Init()", "in cbf_master_proxy.receptorToVcc) cbf_master_proxy.On() time.sleep(3) # check initial value of attributes of CBF subarray", "proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) assert proxies.subarray[1].obsState == ObsState.READY #create a", "in vcc_proxies]) # assert proxies.subarray[1].State() == DevState.OFF # assert subarray_2_proxy.State() == DevState.OFF #", "3 assert searchBeam300[\"outputEnable\"] == True assert searchBeam300[\"averagingInterval\"] == 4 assert searchBeam300[\"searchBeamDestinationAddress\"] == \"10.05.1.1\"", "ObsState.IDLE # proxies.subarray[1].RemoveAllReceptors() # time.sleep(3) # assert proxies.subarray[1].state() == tango.DevState.OFFequency band capabilities assert", "for proxy in vcc_proxies: # proxy.Init() # proxies.subarray[1].set_timeout_millis(60000) # subarray_2_proxy.set_timeout_millis(60000) # proxies.subarray[1].Init() #", "2, 4]]) assert proxies.vcc[proxies.receptor_to_vcc[3]].subarrayMembership == 1 # remove remaining receptors proxies.subarray[1].RemoveReceptors([3]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY,", "# assert fsp_3_proxies.subarray[1].searchBeamID[0] == 300 # assert fsp_3_proxies.subarray[1].searchBeamID[1] == 400 # searchBeam =", "5.85 # # assert fsp_2_proxies.subarray[1].band5Tuning[1] == 7.25 # # assert fsp_2_proxies.subarray[1].frequencyBandOffsetStream1 == 0", "ObsState.IDLE.value # assert tm_telstate_proxy.visDestinationAddress == \"{}\" assert tm_telstate_proxy.receivedOutputLinks == False # add receptors", "frequency band capabilities assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand == 0 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand", "subarrays # first for FSP 3 ... (this is a PSS fsp device)", "== DevState.DISABLE # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].searchWindowTuning == 7000000000 # assert vcc_tdc_proxies[receptor_to_vcc[1] -", "assert proxies.fspSubarray[3].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY #", "== 400 # TODO: currently searchBeams is stored by the device # as", "== sub_id #TODO fix these tests; issue with VccBand devices either not reconfiguring", "1) # update jones matrices from tm emulator f = open(file_path + \"/../data/jonesmatrix_fsp.json\")", "sw_1_proxy, sw_2_proxy, vcc_proxies, vcc_band_proxies, vcc_tdc_proxies, fsp_1_proxy, fsp_2_proxy, fsp_1_function_mode_proxy, fsp_2_function_mode_proxy, fsp_1_proxies.subarray[1], fsp_2_proxies.subarray[1], fsp_3_proxies.subarray[1], tm_telstate_proxy", "VCC belonging to receptor 10... assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].State() == DevState.ON assert vcc_tdc_proxies[receptor_to_vcc[4]", "band_index assert proxies.fspSubarray[fsp_id].frequencySliceID == fsp[\"frequency_slice_id\"] assert proxies.fspSubarray[fsp_id].integrationTime == fsp[\"integration_factor\"] assert proxies.fspSubarray[fsp_id].corrBandwidth == fsp[\"zoom_factor\"]", ") # # then for search window 1 of VCC belonging to receptor", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 2.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 2.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 2.4 assert", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[4][0] == 2976 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[4][1] == 8 # #", "fsp_1_proxies.subarray[1].frequencyBandOffsetStream2 == 0 # assert fsp_1_proxies.subarray[1].frequencySliceID == 1 # assert fsp_1_proxies.subarray[1].corrBandwidth == 1", "proxies.subarray[1].obsState.value == ObsState.READY.value # # check frequency band of VCCs, including states of", "1.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 1.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 1.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 1.8", "VCC belonging to receptor 10... assert proxies.vcc[proxies.receptor_to_vcc[4]].subarrayMembership == 1 assert proxies.vcc[proxies.receptor_to_vcc[4]].band5Tuning[0] == 5.85", "== 0 and band_index == 0) or (i == (band_index - 1)): #", "== 1.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 1.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 1.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] ==", "json import logging # Path file_path = os.path.dirname(os.path.abspath(__file__)) # Tango imports import tango", "== 25 assert \"\".join(sw_1_proxy.tdcDestinationAddress.split()) in [ \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", ] # then", "2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].obsState == ObsState.IDLE # abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]],", "as e: raise e proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1, 1) proxies.clean_proxies() except AssertionError as", "1... # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].State() == DevState.DISABLE # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].searchWindowTuning", "as e: proxies.clean_proxies() raise e def test_AddRemoveReceptors_invalid_single(self, proxies): \"\"\" Test invalid AddReceptors commands", "# assert proxies.subarray[1].state()==DevState.OFF # proxies.subarray[1].On() # time.sleep(10) # # check initial value of", "DevState.ON, 1, 1) # check initial value of attributes of CBF subarray vcc_index", "info. \"\"\"Contain the tests for the CbfSubarray.\"\"\" # Standard imports import sys import", "Note: scan_id is 1-based and of 'string' type # scan_index is an index", "0 # assert fsp_1_proxies.subarray[1].frequencySliceID == 1 # assert fsp_1_proxies.subarray[1].corrBandwidth == 1 # assert", "# remove all receptors proxies.subarray[1].RemoveAllReceptors() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert len(proxies.subarray[1].receptors) == 0", "4 # assert fsp_1_proxies.subarray[1].outputLinkMap[1][0] == 744 # assert fsp_1_proxies.subarray[1].outputLinkMap[1][1] == 8 # assert", "fsp_1_proxies.subarray[1].channelAveragingMap[8][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[9][0] == 6696 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[9][1]", "matrix[\"epoch\"] = epoch if matrix[\"destinationType\"] == \"fsp\": epoch = str(int(epoch) + 10) #", "# assert proxies.subarray[1].obsState == ObsState.IDLE # proxies.subarray[1].RemoveAllReceptors() # time.sleep(3) # assert proxies.subarray[1].state() ==", "= {} \".format(timeout_millis) #logging.info(log_msg) #logging.info(\"start_time = {}\".format(time.time())) logging.info(\"start datetime = {}\".format(datetime.now())) if proxies.debug_device_is_on:", "2 assert proxies.fspSubarray[3].searchBeamID[0] == 300 assert proxies.fspSubarray[3].searchBeamID[1] == 400 # TODO: currently searchBeams", "proxies.subarray[1].scanID == 0 assert proxies.fspSubarray[1].obsState == ObsState.IDLE assert proxies.fspSubarray[3].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState", "== 7000000000 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].tdcEnable == False # # and lastly", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 3.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 3.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 3.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2]", "= 3 elif fsp[\"function_mode\"] == \"VLBI\": function_mode = 4 assert proxies.fsp[fsp_id].functionMode == function_mode", "assert fsp_1_proxies.subarray[1].outputLinkMap[0][1] == 0 assert fsp_1_proxies.subarray[1].outputLinkMap[1][0] == 201 assert fsp_1_proxies.subarray[1].outputLinkMap[1][1] == 1 proxies.subarray[1].GoToIdle()", "sw_1_proxy.State() == DevState.ON # assert sw_1_proxy.searchWindowTuning == 6000000000 # assert sw_1_proxy.tdcEnable == True", "fsp_2_function_mode_proxy, fsp_1_proxies.subarray[1], fsp_2_proxies.subarray[1], fsp_3_proxies.subarray[1], tm_telstate_proxy ): \"\"\" Test a minimal successful configuration \"\"\"", "vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand == 4 # assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[4] -", "ObsState.READY #create a Jones matrix f = open(file_path + \"/../data/jonesmatrix.json\") jones_matrix = json.loads(f.read().replace(\"\\n\",", "1][0].tdcPeriodBeforeEpoch == 5 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch == 25 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcDestinationAddress", "adding an invalid receptor ID # with pytest.raises(tango.DevFailed) as df: # proxies.subarray[1].AddReceptors([5]) #", "( # \"fizz\", \"buzz\", \"80\" # ) # # then for search window", "10... assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].State() == DevState.DISABLE assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].searchWindowTuning == 7000000000", "== 4 # means 5a? # assert proxies.subarray[1].obsState.value == ObsState.READY.value # # check", "- 1].rfiFlaggingMask == \"{}\" # then for VCC belonging to receptor 1... assert", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 4.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 4.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 4.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5]", "for i in range(4)], ObsState.READY, 1, 1) # check frequency band of VCCs,", "assert fsp_2_proxies.subarray[1].channelAveragingMap[18][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[19][0] == 14137 # # assert", "fsp_2_proxies.subarray[1].channelAveragingMap[19][1] == 0 # # then for FSP 3... # assert fsp_3_proxies.subarray[1].receptors[0] ==", "to keep. # print(\"proxies.sw[1].State() = {}\".format(proxies.sw[1].State())) # print(\"proxies.sw[2].State() = {}\".format(proxies.sw[2].State())) # assert proxies.sw[1].State()", "i in range(4)] == [1, 3, 4, 2] assert proxies.vcc[proxies.receptor_to_vcc[2]].subarrayMembership == 1 #", "1-based and of 'string' type # scan_index is an index into an array,", "band capabilities assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand == 4 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand ==", "1) for proxy in [proxies.fsp[i + 1] for i in range(4)]: proxy.loggingLevel =", "1][0].tdcNumBits == 8 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch == 5 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch", "this check does not pass, to fix #elif fsp[\"function_mode\"] == \"PST-BF\": # assert", "# configure scan f = open(file_path + \"/test_json/data_model_confluence.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() time.sleep(15) #", "epoch = str(int(time.time())) for matrix in jones_matrix[\"jonesMatrix\"]: matrix[\"epoch\"] = epoch if matrix[\"destinationType\"] ==", "assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.IDLE ############################# abort from SCANNING ###########################", "== 7000000000 # assert sw_2_proxy.tdcEnable == False # # check configured attributes of", "DevState.DISABLE, DevState.DISABLE, DevState.DISABLE # ] # # assert [proxy.State() for proxy in fsp_2_function_mode_proxy]", "transition to obsState=SCANNING f2 = open(file_path + \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING,", "0 # assert vcc_proxies[receptor_to_vcc[4] - 1].rfiFlaggingMask == \"{}\" # # then for VCC", "check initial value of attributes of CBF subarray # assert proxies.subarray[1].receptors == ()", "== 1 # then for VCC belonging to receptor 1... assert vcc_proxies[receptor_to_vcc[1] -", "# assert subarray_2_proxy.receptors == () # assert all([proxy.subarrayMembership == 0 for proxy in", "== () # assert subarray_2_proxy.receptors == () # assert all([proxy.subarrayMembership == 0 for", "30, 1) assert proxies.subarray[1].obsState == ObsState.READY assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[3].obsState ==", "vcc_band_proxies, # vcc_tdc_proxies, # fsp_1_proxy, # fsp_2_proxy, # fsp_1_function_mode_proxy, # fsp_2_function_mode_proxy, # fsp_1_proxies.subarray[1],", "assert proxies.vcc[vcc_index].subarrayMembership == sub_id #TODO fix these tests; issue with VccBand devices either", "== 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[15][0] == 11161 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[15][1] ==", "== DevState.OFF: proxies.controller.Init() proxies.wait_timeout_dev([proxies.controller], DevState.STANDBY, 3, 1) proxies.controller.On() proxies.wait_timeout_dev([proxies.controller], DevState.ON, 3, 1) proxies.clean_proxies()", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 2.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 2.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 2.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3]", "# check configured attributes of FSPs, including states of function mode capabilities assert", "len(proxies.subarray[1].receptors) == 0 assert proxies.subarray[1].configID == '' assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState.value", "dict([*map(int, pair.split(\":\"))] for pair in # cbf_master_proxy.receptorToVcc) # cbf_master_proxy.On() # time.sleep(60) # #", "] # check configured attributes of FSP subarrays # first for FSP 3", "== 3 assert searchBeam0[\"enable_output\"] == True assert searchBeam0[\"averaging_interval\"] == 4 # TODO -", "proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY ############################# abort from READY ###########################", "# ] # # check configured attributes of FSP subarrays # # first", "# ) # # then for search window 1 of VCC belonging to", "{}\".format(proxies.sw[2].State())) # assert proxies.sw[1].State() == DevState.ON # assert proxies.sw[1].searchWindowTuning == 6000000000 # assert", "# assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].searchWindowTuning == 6000000000 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcEnable ==", "[ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # check the rest of the configured attributes", "fsp_1_proxies.subarray[1].channelAveragingMap[16][0] == 11904 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[16][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[17][0]", "0 # assert proxies.subarray[1].State() == DevState.ON # assert proxies.subarray[1].ObsState == ObsState.EMPTY # #", "average factor 8\" assert proxies.subarray[1].frequencyBand == 4 assert proxies.subarray[1].obsState == ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i +", "matrix entry: epoch {}, VCC {}, i = {}, jonesMatrix[{}] = {}\".format( jones_matrix[\"jonesMatrix\"][1][\"epoch\"],", "+ \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) assert proxies.subarray[1].obsState == ObsState.SCANNING", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 3.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 3.4 # transition to obsState=SCANNING f2 =", "of Jones matrices \"\"\" try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON:", "configuration = json.loads(configuration) band_index = freq_band_dict()[configuration[\"common\"][\"frequency_band\"]] # check configured attributes of CBF subarray", "== 0 assert proxies.subarray[1].configID == '' assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState.value ==", "ae: proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e def test_AddRemoveReceptors_invalid_single(self,", "fsp_1_proxies.subarray[1].zoomWindowTuning == 4700000 # assert fsp_1_proxies.subarray[1].integrationTime == 140 # assert fsp_1_proxies.subarray[1].fspChannelOffset == 14880", "average factor 8\" # assert proxies.subarray[1].frequencyBand == 4 # means 5a? # assert", "proxies.subarray[1].obsState.value == ObsState.READY.value # check frequency band of VCCs, including states of frequency", "function_mode assert sub_id in proxies.fsp[fsp_id].subarrayMembership assert [proxy.State() for proxy in fsp_function_mode_proxies[fsp_id-1]] == [", "belonging to receptor 1... assert proxies.vcc[proxies.receptor_to_vcc[1]].subarrayMembership == 1 assert proxies.vcc[proxies.receptor_to_vcc[1]].band5Tuning[0] == 5.85 assert", "assert fsp_2_proxies.subarray[1].integrationTime == 1400 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[0][0] == 1 # # assert", "assert proxies.subarray[sub_id].obsState == ObsState.EMPTY # add receptors proxies.subarray[sub_id].AddReceptors(test_receptor_ids) proxies.wait_timeout_obs([proxies.subarray[sub_id]], ObsState.IDLE, 1, 1) assert", "# assert proxies.subarray[1].State() == DevState.ON # # try adding some receptors (including an", "- 1].subarrayMembership == 1 assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[0] == 5.85 assert vcc_proxies[receptor_to_vcc[1] -", "i = {}, jonesMatrix[{}] = {}\".format( jones_matrix[\"jonesMatrix\"][1][\"epoch\"], vcc_id, index, fs_id-1, proxies.vcc[vcc_id].jonesMatrix[fs_id-1]) ) raise", "3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[1].receptors[i] == j for i,", "vcc_band_proxies = proxies.vccBand[vcc_index - 1] # turn on Subarray if proxies.subarray[sub_id].State() != DevState.ON:", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[16][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[17][0] == 12649 # #", "assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for i in input_receptors]) assert proxies.subarray[1].obsState == ObsState.IDLE #", "assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[1] == 7.25 # assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream1 == 0", "models \"\"\" # Read delay model data from file f = open(file_path +", "receptor list should be empty right after initialization # assert proxies.subarray[1].receptors == ()", "value of attributes of CBF subarray assert len(proxies.subarray[sub_id].receptors) == 0 assert proxies.subarray[sub_id].configID ==", "proxies.vcc[proxies.receptor_to_vcc[3]].subarrayMembership == 1 # remove remaining receptors proxies.subarray[1].RemoveReceptors([3]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert", "proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY # ObsReset proxies.subarray[1].ObsReset() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1,", "DevState.DISABLE assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].searchWindowTuning == 7000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].tdcEnable == False", "fsp_1_proxies.subarray[1].channelAveragingMap[2][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[3][0] == 2232 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[3][1]", "empty right after initialization # assert proxies.subarray[1].receptors == () # assert subarray_2_proxy.receptors ==", "keep. # print(\"proxies.sw[1].State() = {}\".format(proxies.sw[1].State())) # print(\"proxies.sw[2].State() = {}\".format(proxies.sw[2].State())) # assert proxies.sw[1].State() ==", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[11][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[12][0] == 8929 # #", "True assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcNumBits == 8 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch == 5", "== True # assert proxies.sw[1].tdcNumBits == 8 # assert proxies.sw[1].tdcPeriodBeforeEpoch == 5 #", "1 of VCC belonging to receptor 10... assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].State() == DevState.ON", "assert 1 in proxies.fsp[1].subarrayMembership assert [proxy.State() for proxy in proxies.fsp1FunctionMode] == [ DevState.ON,", "== 140 # assert fsp_1_proxies.subarray[1].fspChannelOffset == 14880 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[0][0] == 0", "of attributes of CBF subarray assert len(proxies.subarray[1].receptors) == 0 assert proxies.subarray[1].configID == ''", "AssertionError as ae: proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e", "# assert fsp_1_proxies.subarray[1].frequencyBandOffsetStream1 == 0 # assert fsp_1_proxies.subarray[1].frequencyBandOffsetStream2 == 0 # assert fsp_1_proxies.subarray[1].frequencySliceID", "assert proxies.fspSubarray[3].receptors[0] == 3 assert proxies.fspSubarray[3].receptors[1] == 1 assert proxies.fspSubarray[3].searchWindowID == 2 assert", "assert fsp_1_proxies.subarray[1].channelAveragingMap[15][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[16][0] == 11904 # # assert", "proxies.clean_proxies() if proxies.controller.State() == DevState.OFF: proxies.controller.Init() proxies.wait_timeout_dev([proxies.controller], DevState.STANDBY, 3, 1) proxies.controller.On() proxies.wait_timeout_dev([proxies.controller], DevState.ON,", "1].frequencyBand == 4 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand == 4 assert [proxy.State() for proxy", "== \"10.05.1.1\" assert searchBeam400[\"searchBeamID\"] == 400 assert searchBeam400[\"receptors\"][0] == 1 assert searchBeam400[\"outputEnable\"] ==", "ObsState.SCANNING, 1, 1) assert proxies.subarray[1].obsState == ObsState.SCANNING assert proxies.subarray[1].scanID == 2 assert proxies.fspSubarray[1].obsState", "\"0\" jones_matrix[\"jonesMatrix\"][2][\"epoch\"] = str(int(time.time()) + 10) # update Jones Matrix proxies.tm.jonesMatrix = json.dumps(jones_matrix)", "proxies.vcc[vcc_ids[num_receptors-1]].obsState == ObsState.SCANNING for fsp in input_config_dict[\"cbf\"][\"fsp\"]: if fsp[\"function_mode\"] == \"CORR\": assert proxies.fspCorrSubarray[subarr_index-1].obsState", "== 6000000000 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcEnable == True # assert vcc_tdc_proxies[receptor_to_vcc[4] -", "assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.READY # TODO: this check does not pass, to fix", "timing_beam_weights = json.loads(f.read().replace(\"\\n\", \"\")) epoch = str(int(time.time())) for weights in timing_beam_weights[\"beamWeights\"]: weights[\"epoch\"] =", "#assert searchBeam1[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" # check configured attributes of FSP subarrays # first", "proxies.subarray[1].obsState == ObsState.SCANNING assert proxies.subarray[1].scanID == 2 assert proxies.fspSubarray[1].obsState == ObsState.SCANNING assert proxies.fspSubarray[3].obsState", "assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcEnable == True assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcNumBits == 8 assert", "5a? # assert proxies.subarray[1].obsState.value == ObsState.READY.value # # check frequency band of VCCs,", "fsp_1_proxies.subarray[1].frequencySliceID == 1 # assert fsp_1_proxies.subarray[1].corrBandwidth == 1 # assert fsp_1_proxies.subarray[1].zoomWindowTuning == 4700000", "TODO: currently searchBeams is stored by the device # as a json string", "of VCCs, including states of frequency band capabilities assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBand == 4 assert", "0 assert proxies.vcc[proxies.receptor_to_vcc[4]].rfiFlaggingMask == \"{}\" # then for VCC belonging to receptor 1...", "\"/../data/delaymodel.json\") delay_model = json.loads(f.read().replace(\"\\n\", \"\")) f.close() aa = delay_model[\"delayModel\"][0][\"delayDetails\"][0][\"receptorDelayDetails\"] num_fsp_IDs = len(aa) for", "model[\"delayDetails\"]: rec_id = int(receptor[\"receptor\"]) fs_id = receptor[\"receptorDelayDetails\"][0][\"fsid\"] for index, value in enumerate(receptor[\"receptorDelayDetails\"][0][\"delayCoeff\"]): try:", "conftest; currently works for fsps 1 and 2 assert proxies.fspSubarray[fsp_id].obsState == ObsState.READY assert", "initial value of attributes of CBF subarray # assert proxies.subarray[1].receptors == () #", "proxy.Init() fsp_1_proxies.subarray[1].Init() fsp_2_proxies.subarray[1].Init() fsp_3_proxies.subarray[1].Init() fsp_1_proxy.Init() fsp_2_proxy.Init() time.sleep(3) cbf_master_proxy.set_timeout_millis(60000) cbf_master_proxy.Init() time.sleep(60) # takes pretty", "1].frequencyBand == 4 # assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[4] - 1]] ==", "# then for search window 2 of VCC belonging to receptor 10... #", "[ # DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE # ] # # assert [proxy.State() for", "invalid receptor ID # with pytest.raises(tango.DevFailed) as df: # proxies.subarray[1].AddReceptors([5]) # time.sleep(1) #", "== 3.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 3.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 3.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] ==", "{}\". format( proxies.vcc[vcc_index].frequencyBand)) ) vcc_band_proxies = proxies.vccBand[vcc_index - 1] assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBand == 4", "proxy.State() = {}\".format(proxy.State())) assert [proxy.State() for proxy in proxies.vccBand[proxies.receptor_to_vcc[4] - 1]] == [", "- 1].rfiFlaggingMask == \"{}\" # # then for VCC belonging to receptor 1...", "assert proxies.vcc[proxies.receptor_to_vcc[1]].band5Tuning[0] == 5.85 assert proxies.vcc[proxies.receptor_to_vcc[1]].band5Tuning[1] == 7.25 # check configured attributes of", "proxies.fspSubarray[3].receptors[1] == 1 assert proxies.fspSubarray[3].searchWindowID == 2 assert proxies.fspSubarray[3].searchBeamID[0] == 300 assert proxies.fspSubarray[3].searchBeamID[1]", "proxies.subarray[sub_id].frequencyBand == band_index assert proxies.subarray[sub_id].obsState == ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i + 1] for i in", "AddReceptors commands involving multiple subarrays: - when a receptor to be added is", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 2.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 2.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 2.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0]", "vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch == 25 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcDestinationAddress == ( #", "0 # means 1 assert proxies.subarray[1].obsState.value == ObsState.READY.value # check frequency band of", "== (band_index - 1)): # assert vcc_band_proxies[i].State() == DevState.ON # else: # assert", "ObsState.READY # Send the Scan command f2 = open(file_path + \"/../data/Scan1_basic.json\") json_string =", "0.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 0.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 0.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 0.6", "== 1 assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[0] == 5.85 assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[1] ==", "proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY # add receptors proxies.subarray[1].AddReceptors([1, 3,", "assert fsp_2_proxies.subarray[1].band5Tuning[0] == 5.85 # # assert fsp_2_proxies.subarray[1].band5Tuning[1] == 7.25 # # assert", "proxies.subarray[1].RemoveAllReceptors() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.OFF, 3, 1) except AssertionError as", "proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState.value == ObsState.IDLE.value # assert tm_telstate_proxy.visDestinationAddress == \"{}\" assert", "as e: raise e time.sleep(10) # Clean Up proxies.clean_proxies() except AssertionError as ae:", "assert fsp_1_proxies.subarray[1].channelAveragingMap[1][0] == 744 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[1][1] == 8 # # assert", "== ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.SCANNING # abort proxies.subarray[1].Abort()", "some receptors to subarray 1 proxies.subarray[1].AddReceptors([1, 3]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].receptors[0]", "# first for search window 1... # TODO - SearchWidow device test is", "long for CBF Master to initialize tm_telstate_proxy.Init() time.sleep(1) receptor_to_vcc = dict([*map(int, pair.split(\":\"))] for", "= str(int(epoch) + 10) # update delay model proxies.tm.beamWeights = json.dumps(timing_beam_weights) time.sleep(1) for", "proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) assert proxies.subarray[1].State() == DevState.ON assert", "scan config_file_name = \"/../data/ConfigureScan_basic.json\" f = open(file_path + config_file_name) proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]],", "fsp_1_proxies.subarray[1].channelAveragingMap[13][0] == 9672 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[13][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[14][0]", "# assert proxies.sw[2].tdcEnable == False time.sleep(1) # check configured attributes of VCC search", "proxies.tm.delayModel = json.dumps(delay_model) time.sleep(1) for model in delay_model[\"delayModel\"]: if model[\"destinationType\"] == \"fsp\": for", "0 for proxy in vcc_proxies]) # assert proxies.subarray[1].State() == DevState.OFF # assert subarray_2_proxy.State()", "== 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[4][0] == 2977 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[4][1] ==", "5208 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[7][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[8][0] == 5952", "including states of frequency band capabilities assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand == 0 assert", "\"\"\" Test invalid AddReceptors commands involving multiple subarrays: - when a receptor to", "== 2.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 2.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 2.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] ==", "# assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].tdcEnable == False # # check configured attributes of", "i in range(4)]: proxy.loggingLevel = \"DEBUG\" if proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON,", "# configure scan # f = open(file_path + \"/test_json/test_ConfigureScan_basic.json\") # proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) #", "2.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 2.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 2.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 2.4", "= open(file_path + \"/../data/Scan1_basic.json\") json_string = f2.read().replace(\"\\n\", \"\") input_scan_dict = json.loads(json_string) proxies.subarray[subarr_index].Scan(json_string) f2.close()", "for index, value in enumerate(frequency_slice[\"matrix\"]): vcc_id = proxies.receptor_to_vcc[receptor[\"receptor\"]] fs_id = frequency_slice[\"fsid\"] try: assert", "ID\" in str(df.value.args[0].desc) # try removing a receptor not assigned to subarray 1", "- 1][0].tdcDestinationAddress == ( # \"foo\", \"bar\", \"8080\" # ) # then for", "ObsState.EMPTY proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.OFF, 3, 1) except AssertionError as ae: proxies.clean_proxies() raise ae", "zip(range(1), [10])]) # Clean Up proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae", "assert sw_2_proxy.tdcEnable == False # check configured attributes of VCC search windows #", "# Check obsStates AFTER the EndScan() command assert proxies.subarray[subarr_index].obsState == ObsState.READY assert proxies.vcc[vcc_ids[0]].obsState", "time.sleep(5) for receptor in jones_matrix[\"jonesMatrix\"][1][\"matrixDetails\"]: for frequency_slice in receptor[\"receptorMatrix\"]: for index, value in", "time.sleep(3) # # receptor list should be empty right after initialization # assert", "# assert proxies.subarray[1].configID == 0 # assert proxies.subarray[1].frequencyBand == 0 # assert proxies.subarray[1].State()", "DevState.DISABLE # # ] # # check configured attributes of FSP subarrays #", "# check initial value of attributes of CBF subarray vcc_index = proxies.receptor_to_vcc[4] logging.info(\"vcc_index", "multiple subarrays: - when a receptor to be added is already in use", "a receptor to be removed is not assigned to the subarray \"\"\" try:", "== 0 # assert proxies.subarray[1].State() == DevState.ON # assert proxies.subarray[1].ObsState == ObsState.EMPTY #", "- 1].subarrayMembership == 1 # assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[0] == 5.85 # assert", "assert tm_telstate_proxy.visDestinationAddress == \"{}\" # assert tm_telstate_proxy.receivedOutputLinks == False # # add receptors", "== 3 assert proxies.fspSubarray[3].receptors[1] == 1 assert proxies.fspSubarray[3].searchWindowID == 2 assert proxies.fspSubarray[3].searchBeamID[0] ==", "\"\") input_scan_dict = json.loads(json_string) proxies.subarray[subarr_index].Scan(json_string) f2.close() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.SCANNING, 1, 1) # Note: scan_id", "assert fsp_2_proxies.subarray[1].channelAveragingMap[9][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[10][0] == 7441 # # assert", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[19][1] == 0 # # then for FSP 3... # assert", "== 7.25 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream1 == 0 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream2 ==", "== ObsState.ABORTED assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[3].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState ==", "assert proxies.subarray[1].configID == 0 # assert proxies.subarray[1].frequencyBand == 0 # assert proxies.subarray[1].State() ==", "fsp_1_proxies.subarray[1].channelAveragingMap[8][0] == 5952 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[8][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[9][0]", "configured attributes of VCC search windows # # first for search window 1", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 2.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 2.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 2.4 proxies.subarray[1].EndScan()", "assert proxies.subarray[1].obsState == ObsState.EMPTY # add receptors proxies.subarray[1].AddReceptors([4, 1, 3, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE,", "assert proxies.fspSubarray[fsp_id].frequencyBand == band_index assert proxies.fspSubarray[fsp_id].frequencySliceID == fsp[\"frequency_slice_id\"] assert proxies.fspSubarray[fsp_id].integrationTime == fsp[\"integration_factor\"] assert", "should be empty right after initialization assert len(proxies.subarray[1].receptors) == 0 assert all([proxies.vcc[i +", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[14][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[15][0] == 11160 #", "1].subarrayMembership == 1 # check configured attributes of FSPs, including states of function", "assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[0] == 5.85 assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[1] == 7.25 assert", "- 1].band5Tuning[0] == 5.85 assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[1] == 7.25 assert vcc_proxies[receptor_to_vcc[4] -", "assert proxies.sw[1].State() == DevState.ON # assert proxies.sw[1].searchWindowTuning == 6000000000 # assert proxies.sw[1].tdcEnable ==", "searchBeam400[\"averagingInterval\"] == 2 assert searchBeam400[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" proxies.subarray[1].GoToIdle() time.sleep(3) assert proxies.subarray[1].obsState == ObsState.IDLE", "== 0 # assert fsp_1_proxies.subarray[1].frequencySliceID == 1 # assert fsp_1_proxies.subarray[1].corrBandwidth == 1 #", "time.sleep(1) assert proxies.subarray[1].receptors == ([3]) assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 0 for i in [1,", "== 0 assert proxies.fspSubarray[1].frequencyBandOffsetStream2 == 0 assert proxies.fspSubarray[1].frequencySliceID == 1 assert proxies.fspSubarray[1].corrBandwidth ==", "proxies.subarray[1].set_timeout_millis(60000) # since the command takes a while # proxies.subarray[1].Init() # time.sleep(3) #", "of FSPs, including states of function mode capabilities fsp_function_mode_proxies = [proxies.fsp1FunctionMode, proxies.fsp2FunctionMode, proxies.fsp3FunctionMode,", "proxies.fspSubarray[3].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.SCANNING # abort", "if fsp[\"function_mode\"] == \"CORR\": function_mode = 1 elif fsp[\"function_mode\"] == \"PSS-BF\": function_mode =", "assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcNumBits == 8 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch == 5 assert", "of CBF subarray assert sub_id == int(configuration[\"common\"][\"subarray_id\"]) assert proxies.subarray[sub_id].configID == configuration[\"common\"][\"config_id\"] assert proxies.subarray[sub_id].frequencyBand", "assert proxies.subarray[1].configID == '' # TODO in CbfSubarray, at end of scan, clear", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 3.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 3.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 3.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5]", "assert proxies.subarray[1].obsState == ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i + 1] for i in range(4)], ObsState.READY, 1,", "== 0.3 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 0.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 0.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] ==", "vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand == 0 # check the rest of the configured attributes", "window 2... # assert sw_2_proxy.State() == DevState.DISABLE # assert sw_2_proxy.searchWindowTuning == 7000000000 #", "True # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcNumBits == 8 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch", "VCCs # first for VCC belonging to receptor 10... assert vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 2.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 2.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 3.0 assert", "in range(4)] == [1, 3, 4, 2] assert proxies.vcc[proxies.receptor_to_vcc[2]].subarrayMembership == 1 # remove", "logging.info( (\"proxies.vcc[vcc_index].frequencyBand = {}\". format( proxies.vcc[vcc_index].frequencyBand)) ) assert proxies.vcc[vcc_index].configID == configuration[\"common\"][\"config_id\"] assert proxies.vcc[vcc_index].frequencyBand", "json.dumps(timing_beam_weights) time.sleep(1) for weights in timing_beam_weights[\"beamWeights\"]: for receptor in weights[\"beamWeightsDetails\"]: rec_id = int(receptor[\"receptor\"])", "DevState.DISABLE, DevState.DISABLE # ] # # assert [proxy.State() for proxy in fsp_2_function_mode_proxy] ==", "assert proxies.subarray[sub_id].configID == '' # TODO in CbfSubarray, at end of scan, clear", "in range(4)]) # add some receptors proxies.subarray[1].AddReceptors([1, 3, 4]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1)", "10... # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].State() == DevState.ON # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].searchWindowTuning", "0 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand == 0 # check the rest of the", "== 3.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 3.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 3.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] ==", "'' assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState.value == ObsState.IDLE.value # assert tm_telstate_proxy.visDestinationAddress ==", "== ( # \"fizz\", \"buzz\", \"80\" # ) # # then for search", "ObsState.READY, 1, 1) # check frequency band of VCCs, including states of frequency", "disabled since the same # functionality is implemented by the VccSearchWindow device; #", "== ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.SCANNING assert proxies.fspSubarray[1].obsState ==", "2.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 2.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 2.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 2.8", "assert proxies.subarray[1].obsState == ObsState.IDLE assert all([proxies.subarray[1].receptors[i] == j for i, j in zip(range(3),", "- 1][0].searchWindowTuning == 6000000000 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcEnable == True # assert", "== 3 # assert proxies.subarray[1].receptors[2] == 4 # # configure scan # f", "6000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcEnable == True assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcNumBits == 8", "1][0].tdcDestinationAddress == ( # \"foo\", \"bar\", \"8080\" # ) # then for search", "FSP 3... # assert fsp_3_proxies.subarray[1].receptors[0] == 3 # assert fsp_3_proxies.subarray[1].receptors[1] == 1 #", "all([proxy.subarrayMembership == 0 for proxy in vcc_proxies]) # assert proxies.subarray[1].State() == DevState.OFF #", "datetime import json import logging # Path file_path = os.path.dirname(os.path.abspath(__file__)) # Tango imports", "1][1].State() == DevState.DISABLE assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].searchWindowTuning == 7000000000 assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].tdcEnable", "False time.sleep(1) # check configured attributes of VCC search windows # first for", "Test the reception of Jones matrices \"\"\" try: # turn on Subarray if", "assert fsp_2_proxies.subarray[1].channelAveragingMap[2][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[3][0] == 2233 # # assert", "ObsState.READY assert proxies.vcc[vcc_ids[num_receptors -1]].obsState == ObsState.READY assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.READY for fsp in", "cbf_master_proxy, proxies.subarray[1], sw_1_proxy, sw_2_proxy, vcc_proxies, vcc_band_proxies, vcc_tdc_proxies, fsp_1_proxy, fsp_2_proxy, fsp_1_function_mode_proxy, fsp_2_function_mode_proxy, fsp_3_proxies.subarray[1], tm_telstate_proxy", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 4.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] == 4.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 4.4 time.sleep(10) assert", "1].subarrayMembership == 1 for i in [1, 3]]) # assert all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership", "assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 0 for i in [1, 3, 4]]) assert proxies.subarray[1].obsState ==", "== 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[11][0] == 8184 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[11][1] ==", "subarray: - when a receptor ID is invalid (e.g. out of range) -", "() # assert proxies.subarray[1].configID == 0 assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState.value ==", "weights in timing_beam_weights[\"beamWeights\"]: weights[\"epoch\"] = epoch epoch = str(int(epoch) + 10) # update", "add some receptors to subarray 1 # proxies.subarray[1].AddReceptors([1, 3]) # time.sleep(1) # assert", "zip(range(num_receptors), input_receptors)]) assert proxies.subarray[subarr_index].obsState == ObsState.IDLE # Check fsp obsState BEFORE scan configuration:", "to be refactored\") def test_ConfigureScan_delayModel(self, proxies): \"\"\" Test the reception of delay models", "proxies): try: sub_id = 1 #TODO currently only support for 1 receptor per", "# then for search window 1 of VCC belonging to receptor 1... assert", "with pytest.raises(tango.DevFailed) as df: # subarray_2_proxy.AddReceptors([1, 2, 4]) # time.sleep(1) # assert \"already", "== 1.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 1.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 1.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] ==", "+ config_file_name) json_string = f.read().replace(\"\\n\", \"\") input_config_dict = json.loads(json_string) proxies.subarray[subarr_index].ConfigureScan(json_string) f.close() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.READY,", "input_test_data[0] config_file_name = input_test_data[1] subarr_index = 1; logging.info( \"input_receptors = {}\".format(input_receptors) ) logging.info(", "fsp_1_proxies.subarray[1].channelAveragingMap[15][0] == 11160 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[15][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[16][0]", "vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch == 5 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch == 25 #", "search window 2 of VCC belonging to receptor 1... assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].State()", "ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.SCANNING assert proxies.fspSubarray[1].obsState == ObsState.SCANNING", "1488 # assert fsp_1_proxies.subarray[1].outputLinkMap[2][1] == 12 # assert fsp_1_proxies.subarray[1].outputLinkMap[3][0] == 2232 # assert", "proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1] == 3 proxies.subarray[1].RemoveAllReceptors() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) proxies.subarray[1].Off()", "of CBF subarray assert proxies.subarray[1].configID == \"sbi-mvp01-20200325-00001-science_A\" assert proxies.subarray[1].frequencyBand == 0 # means", "logging.info(\"start datetime = {}\".format(datetime.now())) if proxies.debug_device_is_on: port = proxies.subarray[1].DebugDevice() try: proxies.clean_proxies() if proxies.controller.State()", "in zip(range(1), [2])]) assert all([proxies.fspSubarray[6].timingBeamID[i] == j for i, j in zip(range(1), [10])])", "fsp_1_proxies.subarray[1].channelAveragingMap[7][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[8][0] == 5952 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[8][1]", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 1.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 1.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 1.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0]", "assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY # ObsReset proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE,", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[8][0] == 5953 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[8][1] == 0 # #", ") assert proxies.vcc[vcc_index].configID == configuration[\"common\"][\"config_id\"] assert proxies.vcc[vcc_index].frequencyBand == band_index assert proxies.vcc[vcc_index].subarrayMembership == sub_id", "assert proxies.fspSubarray[3].receptors[1] == 1 assert proxies.fspSubarray[3].searchWindowID == 2 assert proxies.fspSubarray[3].searchBeamID[0] == 300 assert", "\"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) assert proxies.subarray[1].obsState == ObsState.READY assert", "== 5 # assert sw_1_proxy.tdcPeriodAfterEpoch == 25 # assert \"\".join(sw_1_proxy.tdcDestinationAddress.split()) in [ #", "# SKA specific imports from ska_mid_cbf_mcs.commons.global_enum import freq_band_dict from ska_tango_base.control_model import LoggingLevel, HealthState", "# assert proxies.subarray[1].state() == tango.DevState.OFFequency band capabilities assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand == 4", "== 0.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 0.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 0.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] ==", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[1][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[2][0] == 1489 # #", "proxies): \"\"\" Test a successful transmission of PST-BF parameters to FSP \"\"\" try:", "vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].State() == DevState.DISABLE # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].searchWindowTuning == 7000000000 #", "ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i + 1] for i in range(4)], ObsState.READY, 1, 1) # check", "assert fsp_2_proxies.subarray[1].channelAveragingMap[12][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[13][0] == 9673 # # assert", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 2.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 2.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 2.3 assert", "frequency band of VCCs, including states of frequency band capabilities assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBand ==", "= freq_band_dict()[configuration[\"common\"][\"frequency_band\"]] # check configured attributes of CBF subarray assert sub_id == int(configuration[\"common\"][\"subarray_id\"])", "== ObsState.EMPTY # receptor list should be empty right after initialization assert len(proxies.subarray[1].receptors)", "re-enable and debug! # assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].tdcDestinationAddress == ( # \"foo\", \"bar\",", "- 1][0].State() == DevState.ON assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].searchWindowTuning == 6000000000 assert vcc_tdc_proxies[receptor_to_vcc[1] -", "proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e def test_AddRemoveReceptors_invalid_single(self, proxies):", "raise e @pytest.mark.skip(reason=\"pst not currently supported\") def test_ConfigureScan_onlyPst_basic_FSP_scan_parameters(self, proxies): \"\"\" Test a successful", "0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[4][0] == 2977 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[4][1] == 0", "2.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 2.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0] == 2.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 2.4", "assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[3].obsState == ObsState.READY #", "3.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 3.4 # transition to obsState=SCANNING f2 = open(file_path +", "1].band5Tuning[1] == 7.25 # assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream1 == 0 # assert vcc_proxies[receptor_to_vcc[1]", ") f = open(file_path + config_file_name) json_string = f.read().replace(\"\\n\", \"\") input_config_dict = json.loads(json_string)", "individual members searchBeam = proxies.fspSubarray[3].searchBeams searchBeam0 = json.loads(searchBeam[0]) searchBeam1 = json.loads(searchBeam[1]) assert searchBeam0[\"search_beam_id\"]", "1 # remove some receptors proxies.subarray[1].RemoveReceptors([2, 1, 4]) time.sleep(1) assert proxies.subarray[1].receptors == ([3])", "== 0 assert fsp_1_proxies.subarray[1].outputLinkMap[1][0] == 201 assert fsp_1_proxies.subarray[1].outputLinkMap[1][1] == 1 proxies.subarray[1].GoToIdle() time.sleep(3) assert", "at end of scan, clear all private data #assert proxies.subarray[1].frequencyBand == 0 assert", "# fsp_2_function_mode_proxy, # fsp_1_proxies.subarray[1], # fsp_2_proxies.subarray[1], # fsp_3_proxies.subarray[1], # tm_telstate_proxy # ): #", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 1.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 1.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 2.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4]", "configuration[\"cbf\"][\"fsp\"]: fsp_id = fsp[\"fsp_id\"] logging.info(\"{}\".format(fsp_id)) #TODO add function mode to enum or edit", "cbf_master_proxy.receptorToVcc) # cbf_master_proxy.On() # time.sleep(60) # # turn on Subarray # assert proxies.subarray[1].state()==DevState.OFF", "== 8 # assert sw_1_proxy.tdcPeriodBeforeEpoch == 5 # assert sw_1_proxy.tdcPeriodAfterEpoch == 25 #", "Check obsStates AFTER the EndScan() command assert proxies.subarray[subarr_index].obsState == ObsState.READY assert proxies.vcc[vcc_ids[0]].obsState ==", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][1] == 2.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 2.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 2.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4]", "configured attributes of CBF subarray # assert proxies.subarray[1].configID == \"band:5a, fsp1, 744 channels", "# for proxy in vcc_band_proxies: # logging.info(\"VCC proxy.State() = {}\".format(proxy.State())) # for i", "i, j in zip(range(3), [1, 3, 4])]) # configure scan f = open(file_path", "in matrix[\"matrixDetails\"]: rec_id = int(receptor[\"receptor\"]) fs_id = receptor[\"receptorMatrix\"][0][\"fsid\"] for index, value in enumerate(receptor[\"receptorMatrix\"][0][\"matrix\"]):", "== 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[6][0] == 4465 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[6][1] ==", "== 8 assert proxies.fspSubarray[1].channelAveragingMap[4][0] == 2976 assert proxies.fspSubarray[1].outputLinkMap[0][0] == 0 assert proxies.fspSubarray[1].outputLinkMap[0][1] ==", "== 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[5][0] == 3720 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[5][1] ==", "for i in range(len(fsp[\"channel_averaging_map\"])): for j in range(len(fsp[\"channel_averaging_map\"][i])): assert proxies.fspSubarray[fsp_id].channelAveragingMap[i][j] == fsp[\"channel_averaging_map\"][i][j] for", "[2, 4]]) # assert subarray_2_proxy.State() == DevState.ON def test_RemoveAllReceptors(self, proxies): \"\"\" Test RemoveAllReceptors", "states of function mode capabilities # assert fsp_1_proxy.functionMode == 1 # assert 1", "input json @pytest.mark.skip(reason=\"test needs to be refactored\") def test_ConfigureScan_delayModel(self, proxies): \"\"\" Test the", "open(file_path + \"/test_json/test_ConfigureScan_onlyPss_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() time.sleep(15) # check configured attributes of CBF", "tango.DevState.OFF def test_band1( self, cbf_master_proxy, proxies.subarray[1], sw_1_proxy, sw_2_proxy, vcc_proxies, vcc_band_proxies, vcc_tdc_proxies, fsp_1_proxy, fsp_2_proxy,", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 1.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 1.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 1.9 assert", "1... assert vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership == 1 # check configured attributes of FSPs,", "tm_telstate_proxy.Init() time.sleep(1) receptor_to_vcc = dict([*map(int, pair.split(\":\"))] for pair in cbf_master_proxy.receptorToVcc) cbf_master_proxy.On() time.sleep(3) #", "== 5.85 # assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[1] == 7.25 # assert vcc_proxies[receptor_to_vcc[4] -", "assert proxies.fsp[2].functionMode == 3 assert 1 in proxies.fsp[2].subarrayMembership assert [proxy.State() for proxy in", "assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcNumBits == 8 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch == 5", "1].frequencyBand == 4 # assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand == 4 # assert [proxy.State()", "1) except AssertionError as ae: proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies()", "proxies.subarray[1].Init() time.sleep(3) cbf_master_proxy.set_timeout_millis(60000) cbf_master_proxy.Init() time.sleep(60) # takes pretty long for CBF Master to", "== 1 # assert fsp_1_proxies.subarray[1].zoomWindowTuning == 4700000 # assert fsp_1_proxies.subarray[1].integrationTime == 140 #", "- 1][1].State() == DevState.DISABLE assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].searchWindowTuning == 7000000000 assert vcc_tdc_proxies[receptor_to_vcc[4] -", "of FSP subarrays # first for FSP 1... (this is a CORR fsp", "= f.read().replace(\"\\n\", \"\") input_config_dict = json.loads(json_string) proxies.subarray[subarr_index].ConfigureScan(json_string) f.close() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.READY, 15, 1) logging.info(", "raise e def test_Scan(self, proxies): \"\"\" Test the Scan command \"\"\" try: #", "belonging to receptor 10... assert vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership == 1 assert vcc_proxies[receptor_to_vcc[4] -", "1; logging.info( \"input_receptors = {}\".format(input_receptors) ) logging.info( \"config_file_name = {}\".format(config_file_name) ) num_receptors =", "implemented by the VccSearchWindow device; # to be decide which one to keep.", "assert proxies.subarray[1].configID == 0 assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState.value == ObsState.IDLE.value #", "DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[1] - 1]]", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 0.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 0.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 0.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3]", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 2.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 2.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 2.9 assert", "assert proxies.fspSubarray[1].obsState == ObsState.IDLE assert proxies.fspSubarray[3].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.IDLE assert", "channels average factor 8\" assert proxies.subarray[1].frequencyBand == 4 assert proxies.subarray[1].obsState == ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i", "vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream2 == 0 # assert vcc_proxies[receptor_to_vcc[4] - 1].rfiFlaggingMask == \"{}\" #", "json_string = f.read().replace(\"\\n\", \"\") input_config_dict = json.loads(json_string) proxies.subarray[subarr_index].ConfigureScan(json_string) f.close() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.READY, 15, 1)", "assert proxies.fspSubarray[1].channelAveragingMap[2][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[3][0] == 2232 assert proxies.fspSubarray[1].channelAveragingMap[3][1] == 8 assert", "\"band:5a, fsp1, 744 channels average factor 8\" # assert proxies.subarray[1].frequencyBand == 4 #", "assert fsp_2_proxies.subarray[1].band5Tuning[1] == 7.25 # # assert fsp_2_proxies.subarray[1].frequencyBandOffsetStream1 == 0 # # assert", "assert fsp_1_proxies.subarray[1].channelAveragingMap[18][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[19][0] == 14136 # # assert", "try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.ON, 3,", "(i == 0 and band_index == 0) or (i == (band_index - 1)):", "including states of function mode capabilities # assert fsp_1_proxy.functionMode == 1 # assert", "# try removing a receptor not assigned to subarray 1 # doing this", "- 1]: logging.info(\"VCC proxy.State() = {}\".format(proxy.State())) assert [proxy.State() for proxy in proxies.vccBand[proxies.receptor_to_vcc[4] -", "= open(file_path + \"/test_json/test_ConfigureScan_onlyPss_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() time.sleep(15) # check configured attributes of", "fs_id = frequency_slice[\"fsid\"] try: assert proxies.vcc[vcc_id].jonesMatrix[fs_id-1][index] == value except AssertionError as ae: logging.error(\"AssertionError;", "assert fsp_1_proxies.subarray[1].fspChannelOffset == 14880 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[0][0] == 0 # # assert", "== 0 assert proxies.subarray[1].configID == '' # TODO in CbfSubarray, at end of", "1][0].tdcPeriodAfterEpoch == 25 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcDestinationAddress == ( \"fizz\", \"buzz\", \"80\" )", "proxies.fspSubarray[1].frequencyBand == 4 assert proxies.fspSubarray[1].band5Tuning[0] == 5.85 assert proxies.fspSubarray[1].band5Tuning[1] == 7.25 assert proxies.fspSubarray[1].frequencyBandOffsetStream1", "ObsState from ska_tango_base.base_device import _DEBUGGER_PORT @pytest.mark.usefixtures(\"proxies\", \"input_test_data\") class TestCbfSubarray: def test_AddRemoveReceptors_valid(self, proxies): \"\"\"", "format(proxies.vcc[vcc_ids[0]].obsState) ) f = open(file_path + config_file_name) json_string = f.read().replace(\"\\n\", \"\") input_config_dict =", "belonging to receptor 10... assert proxies.vcc[proxies.receptor_to_vcc[4]].subarrayMembership == 1 assert proxies.vcc[proxies.receptor_to_vcc[4]].band5Tuning[0] == 5.85 assert", "== True assert searchBeam0[\"averaging_interval\"] == 4 # TODO - this does not pass", "abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED # ObsReset proxies.subarray[1].ObsReset()", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[6][0] == 4465 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[6][1] == 0 # #", "proxies.wait_timeout_dev([proxies.subarray[1]], DevState.ON, 3, 1) for proxy in [proxies.vcc[i + 1] for i in", "f.close() proxies.subarray[sub_id].ConfigureScan(configuration) proxies.wait_timeout_obs([proxies.subarray[sub_id]], ObsState.READY, 15, 1) configuration = json.loads(configuration) band_index = freq_band_dict()[configuration[\"common\"][\"frequency_band\"]] #", "= {}\".format(input_receptors) ) logging.info( \"config_file_name = {}\".format(config_file_name) ) num_receptors = len(input_receptors) vcc_ids =", "# send the Scan command f2 = open(file_path + \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close()", "proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e #TODO refactor to", "time.sleep(10) # # check initial value of attributes of CBF subarray # assert", "assert proxies.sw[2].tdcEnable == False time.sleep(1) # check configured attributes of VCC search windows", "assert vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership == 1 assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[0] == 5.85 assert", "function_mode = 2 elif fsp[\"function_mode\"] == \"PST-BF\": function_mode = 3 elif fsp[\"function_mode\"] ==", "use\" in str(df.value.args[0].desc) # assert subarray_2_proxy.receptors == (2, 4) # assert all([vcc_proxies[receptor_to_vcc[i] -", "DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ] # assert [proxy.State() for proxy in fsp_2_function_mode_proxy] == [", "# assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].searchWindowTuning == 7000000000 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].tdcEnable ==", "except Exception as e: proxies.clean_proxies() raise e def test_Abort_Reset(self, proxies): \"\"\" Test abort", "assert vcc_band_proxies[i].State() == DevState.DISABLE # check configured attributes of FSPs, including states of", "- 1 logging.info( \"proxies.fspCorrSubarray[subarr_index-1].obsState = {}\". format(proxies.fspCorrSubarray[subarr_index-1].obsState) ) logging.info( \"proxies.fspPssSubarray[subarr_index-1].obsState = {}\". format(proxies.fspPssSubarray[subarr_index-1].obsState)", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 1.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 1.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 1.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1]", "clear all private data #assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState == ObsState.EMPTY #", "search window 1 of VCC belonging to receptor 10... assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][0].State()", "proxies.subarray[1].configID == '' assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState.value == ObsState.IDLE.value # assert", "CORR fsp device) assert proxies.fspSubarray[1].obsState == ObsState.READY assert proxies.fspSubarray[1].receptors == 4 assert proxies.fspSubarray[1].frequencyBand", "# check configured attributes of FSP subarrays # first for FSP 3 ...", "1, 1) assert proxies.subarray[1].obsState == ObsState.SCANNING time.sleep(10) assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 2.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1]", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[0][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[1][0] == 744 #", "of frequency band capabilities assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand == 0 assert vcc_proxies[receptor_to_vcc[1] -", "ae: raise ae except Exception as e: raise e time.sleep(10) # update delay", "400 assert searchBeam400[\"receptors\"][0] == 1 assert searchBeam400[\"outputEnable\"] == True assert searchBeam400[\"averagingInterval\"] == 2", "epoch delay_model[\"delayModel\"][0][\"epoch\"] = str(int(time.time()) + 20) delay_model[\"delayModel\"][1][\"epoch\"] = \"0\" delay_model[\"delayModel\"][2][\"epoch\"] = str(int(time.time()) +", "delay_model[\"delayModel\"][0][\"epoch\"] = str(int(time.time()) + 20) delay_model[\"delayModel\"][1][\"epoch\"] = \"0\" delay_model[\"delayModel\"][2][\"epoch\"] = str(int(time.time()) + 10)", "sub_id in proxies.fsp[fsp_id].subarrayMembership assert [proxy.State() for proxy in fsp_function_mode_proxies[fsp_id-1]] == [ DevState.ON, DevState.DISABLE,", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 3.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 4.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 4.1 assert", "1][0].searchWindowTuning == 6000000000 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcEnable == True # assert vcc_tdc_proxies[receptor_to_vcc[4]", "\"timeout_millis = {} \".format(timeout_millis) #logging.info(log_msg) #logging.info(\"start_time = {}\".format(time.time())) logging.info(\"start datetime = {}\".format(datetime.now())) if", "scan configurations are tested def test_ConfigureScan_basic(self, proxies): \"\"\" Test a successful scan configuration", "to be decide which one to keep. # print(\"proxies.sw[1].State() = {}\".format(proxies.sw[1].State())) # print(\"proxies.sw[2].State()", "1 proxies.subarray[1].GoToIdle() time.sleep(3) assert proxies.subarray[1].obsState == ObsState.IDLE proxies.subarray[1].RemoveAllReceptors() time.sleep(1) proxies.subarray[1].Off() assert proxies.subarray[1].state() ==", "e def test_EndScan(self, proxies, input_test_data): \"\"\" Test the EndScan command \"\"\" try: #", "in [1, 3]]) assert proxies.subarray[1].obsState == ObsState.IDLE # TODO: fix this # try", "assert tm_telstate_proxy.visDestinationAddress == \"{}\" assert tm_telstate_proxy.receivedOutputLinks == False # add receptors proxies.subarray[1].RemoveAllReceptors() proxies.subarray[1].AddReceptors([1,", "assert fsp_1_proxies.subarray[1].channelAveragingMap[16][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[17][0] == 12648 # # assert", "for receptor_id, ii in zip(input_receptors, range(num_receptors)): vcc_ids[ii] = proxies.receptor_to_vcc[receptor_id] proxies.subarray[subarr_index].AddReceptors(input_receptors) proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.IDLE, 1,", "except Exception as e: raise e time.sleep(10) # Clean Up proxies.clean_proxies() except AssertionError", "assert proxies.fspSubarray[fsp_id].corrBandwidth == fsp[\"zoom_factor\"] if fsp[\"zoom_factor\"] > 0: assert proxies.fspSubarray[fsp_id].zoomWindowTuning == fsp[\"zoom_window_tuning\"] assert", "ObsState.IDLE, 1, 1) assert all([proxies.subarray[1].receptors[i] == j for i, j in zip(range(3), [1,", "time.sleep(3) assert proxies.subarray[1].state() == tango.DevState.OFF def test_band1( self, cbf_master_proxy, proxies.subarray[1], sw_1_proxy, sw_2_proxy, vcc_proxies,", "== 2.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 2.1 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][3] == 2.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][4] ==", "== 7.25 # assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream1 == 0 # assert vcc_proxies[receptor_to_vcc[4] -", "== 0 assert fsp_1_proxies.subarray[1].frequencySliceID == 1 assert fsp_1_proxies.subarray[1].corrBandwidth == 0 assert fsp_1_proxies.subarray[1].integrationTime ==", "receptor 10... # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].State() == DevState.DISABLE # assert vcc_tdc_proxies[receptor_to_vcc[4] -", "{}\".format(time.time())) logging.info(\"start datetime = {}\".format(datetime.now())) if proxies.debug_device_is_on: port = proxies.subarray[1].DebugDevice() try: proxies.clean_proxies() if", "assert fsp_1_proxies.subarray[1].frequencyBand == 4 # assert fsp_1_proxies.subarray[1].band5Tuning[0] == 5.85 # assert fsp_1_proxies.subarray[1].band5Tuning[1] ==", "True # assert searchBeam300[\"averagingInterval\"] == 4 # assert searchBeam300[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" # assert", "== ObsState.IDLE # remove all receptors proxies.subarray[1].RemoveAllReceptors() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert len(proxies.subarray[1].receptors)", "proxies.fsp4FunctionMode] for fsp in configuration[\"cbf\"][\"fsp\"]: fsp_id = fsp[\"fsp_id\"] logging.info(\"{}\".format(fsp_id)) #TODO add function mode", "== 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[13][0] == 9672 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[13][1] ==", "in range(num_receptors)] for receptor_id, ii in zip(input_receptors, range(num_receptors)): vcc_ids[ii] = proxies.receptor_to_vcc[receptor_id] proxies.subarray[subarr_index].AddReceptors(input_receptors) proxies.wait_timeout_obs([proxies.subarray[subarr_index]],", "2.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 2.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 3.0 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][2] == 3.1", "== 1.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 1.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 1.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] ==", "== 1 assert fsp_3_proxies.subarray[1].searchWindowID == 2 assert fsp_3_proxies.subarray[1].searchBeamID[0] == 300 assert fsp_3_proxies.subarray[1].searchBeamID[1] ==", "proxies.subarray[1].ObsReset() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert proxies.subarray[1].obsState == ObsState.IDLE assert proxies.subarray[1].scanID == 0", "proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1] == 3 assert proxies.subarray[1].receptors[2] == 4 # configure", "configuration = f.read().replace(\"\\n\", \"\") f.close() proxies.subarray[sub_id].ConfigureScan(configuration) proxies.wait_timeout_obs([proxies.subarray[sub_id]], ObsState.READY, 15, 1) configuration = json.loads(configuration)", "time.sleep(60) # # turn on Subarray # assert proxies.subarray[1].state()==DevState.OFF # proxies.subarray[1].On() # time.sleep(10)", "proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.IDLE logging.info( \"First vcc obsState BEFORE ConfigureScan = {}\". format(proxies.vcc[vcc_ids[0]].obsState) )", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][3] == 2.4 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][4] == 2.5 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 2.6 assert", "Exception as e: raise e time.sleep(10) # update timing beam weights from tm", "searchBeam400[\"outputEnable\"] == True # assert searchBeam400[\"averagingInterval\"] == 2 # assert searchBeam400[\"searchBeamDestinationAddress\"] == \"10.05.2.1\"", "time.sleep(3) cbf_master_proxy.set_timeout_millis(60000) cbf_master_proxy.Init() time.sleep(60) # takes pretty long for CBF Master to initialize", "== ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY # ObsReset proxies.subarray[1].ObsReset()", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 1.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 2.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 2.1 assert", "== 0 # assert fsp_1_proxies.subarray[1].outputLinkMap[0][1] == 4 # assert fsp_1_proxies.subarray[1].outputLinkMap[1][0] == 744 #", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[9][0] == 6697 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[9][1] == 0 #", "1) assert proxies.subarray[1].obsState == ObsState.EMPTY ############################# abort from READY ########################### # add receptors", "range(4)], ObsState.READY, 1, 1) # check frequency band of VCCs, including states of", "9673 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[13][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[14][0] == 10417", "searchBeam0[\"enable_output\"] == True assert searchBeam0[\"averaging_interval\"] == 4 # TODO - this does not", "fsp1, 744 channels average factor 8\" assert proxies.subarray[1].frequencyBand == 4 assert proxies.subarray[1].obsState ==", "f2 = open(file_path + \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) #", "for search window 1 of VCC belonging to receptor 10... assert proxies.vccTdc[proxies.receptor_to_vcc[4] -", "{}\".format( jones_matrix[\"jonesMatrix\"][1][\"epoch\"], vcc_id, index, fs_id-1, proxies.vcc[vcc_id].jonesMatrix[fs_id-1]) ) raise ae except Exception as e:", "len(input_receptors) vcc_ids = [None for _ in range(num_receptors)] for receptor_id, ii in zip(input_receptors,", "== [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] # check the rest of the configured", "== \"band:5a, fsp1, 744 channels average factor 8\" assert proxies.subarray[1].frequencyBand == 4 assert", "different subarray \"\"\" # for proxy in vcc_proxies: # proxy.Init() # proxies.subarray[1].set_timeout_millis(60000) #", "raise ae except Exception as e: proxies.clean_proxies() raise e #TODO refactor to verify", "# check configured attributes of VCC search windows # first for search window", "obsState BEFORE ConfigureScan = {}\". format(proxies.vcc[vcc_ids[0]].obsState) ) f = open(file_path + config_file_name) json_string", "of VCC belonging to receptor 10... assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].State() == DevState.ON assert", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 4.4 time.sleep(10) assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 0.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] == 0.2 assert", "value in enumerate(receptor[\"receptorMatrix\"][0][\"matrix\"]): try: assert proxies.fsp[fs_id].jonesMatrix[rec_id - 1][index] == value except AssertionError as", "assert proxies.fspSubarray[1].outputLinkMap[1][1] == 8 assert proxies.fspSubarray[1].outputLinkMap[2][0] == 1488 assert proxies.fspSubarray[1].outputLinkMap[2][1] == 12 assert", "# first for FSP 1... # assert fsp_1_proxies.subarray[1].obsState == ObsState.EMPTY # assert fsp_1_proxies.subarray[1].receptors", ") raise ae except Exception as e: raise e proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1,", "assert fsp_2_proxies.subarray[1].channelAveragingMap[4][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[5][0] == 3721 # # assert", "10... assert vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership == 1 # then for VCC belonging to", "] # check configured attributes of FSP subarray #TODO align IDs of fspSubarrays", "\"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", ] # then for search window 2... assert sw_2_proxy.State() == DevState.DISABLE assert", "DevState.OFF: proxies.controller.Init() proxies.wait_timeout_dev([proxies.controller], DevState.STANDBY, 3, 1) proxies.controller.On() proxies.wait_timeout_dev([proxies.controller], DevState.ON, 3, 1) proxies.clean_proxies() #", "== 1 assert proxies.fspSubarray[3].searchWindowID == 2 assert proxies.fspSubarray[3].searchBeamID[0] == 300 assert proxies.fspSubarray[3].searchBeamID[1] ==", "vcc_proxies[receptor_to_vcc[1] - 1].rfiFlaggingMask == \"{}\" # # check configured attributes of search windows", "# self, # cbf_master_proxy, # proxies.subarray[1], # sw_1_proxy, # sw_2_proxy, # vcc_proxies, #", "7000000000 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].tdcEnable == False assert fsp_3_proxies.subarray[1].receptors[0] == 3 assert fsp_3_proxies.subarray[1].receptors[1]", "when a receptor to be added is already in use by a different", "== ObsState.IDLE # Clean Up proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae", "# # then for VCC belonging to receptor 1... # assert vcc_proxies[receptor_to_vcc[1] -", "raise e time.sleep(10) for receptor in jones_matrix[\"jonesMatrix\"][0][\"matrixDetails\"]: for frequency_slice in receptor[\"receptorMatrix\"]: for index,", "\"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) assert proxies.subarray[1].obsState == ObsState.SCANNING time.sleep(10) assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0]", "assert fsp_2_proxies.subarray[1].channelAveragingMap[11][0] == 8185 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[11][1] == 0 # # assert", "searchBeam300 = json.loads(searchBeam[0]) # searchBeam400 = json.loads(searchBeam[1]) # assert searchBeam300[\"searchBeamID\"] == 300 #", "ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.READY assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.READY # abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]],", "\"input_receptors = {}\".format(input_receptors) ) logging.info( \"config_file_name = {}\".format(config_file_name) ) num_receptors = len(input_receptors) vcc_ids", "proxies): \"\"\" Test invalid AddReceptors commands involving a single subarray: - when a", "== 5208 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[7][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[8][0] ==", "30, 1) # scan f2 = open(file_path + \"/../data/Scan2_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]],", "df: # subarray_2_proxy.AddReceptors([1, 2, 4]) # time.sleep(1) # assert \"already in use\" in", "== 2232 assert proxies.fspSubarray[1].channelAveragingMap[3][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[4][0] == 2976 assert proxies.fspSubarray[1].outputLinkMap[0][0] ==", "be refactored\") def test_ConfigureScan_delayModel(self, proxies): \"\"\" Test the reception of delay models \"\"\"", "= str(int(time.time())) for matrix in jones_matrix[\"jonesMatrix\"]: matrix[\"epoch\"] = epoch if matrix[\"destinationType\"] == \"fsp\":", "{}\".format( aa[jj][\"delayCoeff\"]) ) try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On()", "\"{}\" assert tm_telstate_proxy.receivedOutputLinks == False # add receptors proxies.subarray[1].AddReceptors([1, 3, 4]) time.sleep(1) assert", "CBF Master to initialize # tm_telstate_proxy.Init() # time.sleep(1) # receptor_to_vcc = dict([*map(int, pair.split(\":\"))]", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[1][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[2][0] == 1488 # #", "= json.loads(f.read().replace(\"\\n\", \"\")) f.close() aa = delay_model[\"delayModel\"][0][\"delayDetails\"][0][\"receptorDelayDetails\"] num_fsp_IDs = len(aa) for jj in", "== False # add receptors proxies.subarray[1].AddReceptors([1, 3, 4]) time.sleep(1) assert proxies.subarray[1].receptors[0] == 1", "vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].State() == DevState.ON assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].searchWindowTuning == 6000000000 assert vcc_tdc_proxies[receptor_to_vcc[4]", "enumerate(receptor[\"receptorWeightsDetails\"][0][\"weights\"]): try: assert proxies.fsp[fs_id].timingBeamWeights[rec_id - 1][index] == value except AssertionError as ae: raise", "f.read().replace(\"\\n\", \"\") input_config_dict = json.loads(json_string) proxies.subarray[subarr_index].ConfigureScan(json_string) f.close() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.READY, 15, 1) logging.info( \"First", "== 4465 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[6][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[7][0] ==", "to debug & fix #assert searchBeam0[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" assert searchBeam1[\"search_beam_id\"] == 400 assert", "== \"fsp\": epoch = str(int(epoch) + 10) # update Jones Matrix proxies.tm.jonesMatrix =", "= f2.read().replace(\"\\n\", \"\") input_scan_dict = json.loads(json_string) proxies.subarray[subarr_index].Scan(json_string) f2.close() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.SCANNING, 1, 1) #", "range(num_fsp_IDs): logging.info( \"delayCoeff = {}\".format( aa[jj][\"delayCoeff\"]) ) try: # turn on Subarray if", "proxies.fspSubarray[1].outputLinkMap[3][0] == 2232 assert proxies.fspSubarray[1].outputLinkMap[3][1] == 16 assert str(proxies.fspSubarray[1].visDestinationAddress).replace('\"',\"'\") == \\ str({\"outputHost\": [[0,", "0 # assert proxies.subarray[1].configID == 0 # assert proxies.subarray[1].frequencyBand == 0 # assert", "in range(num_fsp_IDs): logging.info( \"delayCoeff = {}\".format( aa[jj][\"delayCoeff\"]) ) try: # turn on Subarray", "== 0 # assert proxies.subarray[1].frequencyBand == 0 # assert proxies.subarray[1].State() == DevState.ON #", "4700000 assert proxies.fspSubarray[1].integrationTime == 1 assert proxies.fspSubarray[1].fspChannelOffset == 14880 assert proxies.fspSubarray[1].channelAveragingMap[0][0] == 0", "i in input_receptors]) assert proxies.subarray[1].obsState == ObsState.IDLE # add more receptors... proxies.subarray[1].AddReceptors([2]) time.sleep(1)", "fsp device) assert proxies.fspSubarray[3].receptors[0] == 3 assert proxies.fspSubarray[3].receptors[1] == 1 assert proxies.fspSubarray[3].searchWindowID ==", "proxies.subarray[subarr_index].Scan(json_string) f2.close() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.SCANNING, 1, 1) # Note: scan_id is 1-based and of", "assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.IDLE logging.info( \"First vcc obsState BEFORE ConfigureScan = {}\". format(proxies.vcc[vcc_ids[0]].obsState)", "fs_id-1, proxies.vcc[vcc_id].jonesMatrix[fs_id-1]) ) raise ae except Exception as e: raise e time.sleep(10) for", "check states assert proxies.subarray[1].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState ==", "assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for i in [1, 3]]) assert proxies.subarray[1].obsState == ObsState.IDLE", "fault within the Vcc device # for proxy in vcc_band_proxies: # logging.info(\"VCC proxy.State()", "edit attribute to accept string in FSP if fsp[\"function_mode\"] == \"CORR\": function_mode =", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[11][0] == 8184 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[11][1] == 8 # #", "throw an error proxies.subarray[1].RemoveReceptors([2]) assert proxies.subarray[1].receptors[0] == 1 assert proxies.subarray[1].receptors[1] == 3 proxies.subarray[1].RemoveAllReceptors()", "- 1][0].tdcPeriodBeforeEpoch == 5 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch == 25 # assert", "0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[8][0] == 5953 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[8][1] == 0", "Exception as e: raise e time.sleep(10) # Clean Up proxies.clean_proxies() except AssertionError as", "1) # check scanID on VCC and FSP assert proxies.fspSubarray[1].scanID == 1 assert", "1.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 1.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 1.9 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][1] == 2.0", "tm_telstate_proxy.receivedOutputLinks == False # add receptors proxies.subarray[1].AddReceptors([1, 3, 4]) time.sleep(1) assert proxies.subarray[1].receptors[0] ==", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 3.4 # transition to obsState=SCANNING f2 = open(file_path + \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\",", "== \"{}\" # then for VCC belonging to receptor 1... assert proxies.vcc[proxies.receptor_to_vcc[1]].subarrayMembership ==", "proxies.fspSubarray[1].outputLinkMap[0][0] == 0 assert proxies.fspSubarray[1].outputLinkMap[0][1] == 4 assert proxies.fspSubarray[1].outputLinkMap[1][0] == 744 assert proxies.fspSubarray[1].outputLinkMap[1][1]", "search window 2 of VCC belonging to receptor 10... assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].State()", "proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBand == 4 assert [proxy.State() for proxy in proxies.vccBand[proxies.receptor_to_vcc[2] - 1]] == [", "scan f = open(file_path + \"/test_json/test_ConfigureScan_onlyPss_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() time.sleep(15) # check configured", "sub_id = 1 #TODO currently only support for 1 receptor per fsp test_receptor_ids", "DevState.ON] # # check the rest of the configured attributes of VCCs #", "jonesMatrix[{}] = {}\".format( jones_matrix[\"jonesMatrix\"][1][\"epoch\"], vcc_id, index, fs_id-1, proxies.vcc[vcc_id].jonesMatrix[fs_id-1]) ) raise ae except Exception", "assert proxies.fspSubarray[1].frequencyBandOffsetStream1 == 0 assert proxies.fspSubarray[1].frequencyBandOffsetStream2 == 0 assert proxies.fspSubarray[1].frequencySliceID == 1 assert", "1][0].tdcNumBits == 8 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodBeforeEpoch == 5 # assert vcc_tdc_proxies[receptor_to_vcc[1]", "\"band:5a, fsp1, 744 channels average factor 8\" assert proxies.subarray[1].frequencyBand == 4 # means", "assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][5] == 2.6 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][0] == 2.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 2.8 assert", "open(file_path + \"/test_json/test_ConfigureScan_basic.json\") # proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) # f.close() # time.sleep(15) # # check", "time.sleep(1) # assert \"already in use\" in str(df.value.args[0].desc) # assert subarray_2_proxy.receptors == (2,", "== 3.4 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][2] == 3.5 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 3.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] ==", "0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[18][0] == 13393 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[18][1] == 0", "# proxies.subarray[1].RemoveAllReceptors() # proxies.subarray[1].AddReceptors([1, 3, 4]) # time.sleep(1) # assert proxies.subarray[1].receptors[0] == 1", "# fsp_3_proxies.subarray[1], # tm_telstate_proxy # ): # \"\"\" # Test a minimal successful", "vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].searchWindowTuning == 6000000000 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcEnable == True #", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[15][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[16][0] == 11905 # #", "300 # assert fsp_3_proxies.subarray[1].searchBeamID[1] == 400 # searchBeam = fsp_3_proxies.subarray[1].searchBeams # searchBeam300 =", "TODO - # assert [proxy.State() for proxy in fsp_2_function_mode_proxy] == [ # DevState.ON,", "[4, 1, 3, 2])]) # configure scan f = open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\",", "assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[1] == 7.25 assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream1 == 0 assert", "initial value of attributes of CBF subarray # assert len(proxies.subarray[1].receptors) == 0 #", "proxies.fspSubarray[1].channelAveragingMap[0][0] == 0 assert proxies.fspSubarray[1].channelAveragingMap[0][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[1][0] == 744 assert proxies.fspSubarray[1].channelAveragingMap[1][1]", "jones_matrix = json.loads(f.read().replace(\"\\n\", \"\")) epoch = str(int(time.time())) for matrix in jones_matrix[\"jonesMatrix\"]: matrix[\"epoch\"] =", "744 # assert fsp_1_proxies.subarray[1].outputLinkMap[1][1] == 8 # assert fsp_1_proxies.subarray[1].outputLinkMap[2][0] == 1488 # assert", "and band_index == 0) or (i == (band_index - 1)): # assert vcc_band_proxies[i].State()", "\"80\" # ) # then for search window 2 of VCC belonging to", "subarray assert sub_id == int(configuration[\"common\"][\"subarray_id\"]) assert proxies.subarray[sub_id].configID == configuration[\"common\"][\"config_id\"] assert proxies.subarray[sub_id].frequencyBand == band_index", "0: assert proxies.fspSubarray[fsp_id].zoomWindowTuning == fsp[\"zoom_window_tuning\"] assert proxies.fspSubarray[fsp_id].fspChannelOffset == fsp[\"channel_offset\"] for i in range(len(fsp[\"channel_averaging_map\"])):", "== ObsState.SCANNING proxies.subarray[1].EndScan() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 1, 1) assert proxies.subarray[1].obsState == ObsState.READY # Clean", "raise e def test_Abort_Reset(self, proxies): \"\"\" Test abort reset \"\"\" try: # turn", "DevState.DISABLE, DevState.DISABLE ] # check configured attributes of FSP subarray #TODO align IDs", "\"\")) # f.close() # time.sleep(15) # # check configured attributes of CBF subarray", "[1, 3, 4]]) assert proxies.subarray[1].obsState == ObsState.EMPTY proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.OFF, 3, 1) except", "ObsState.EMPTY # add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert", "receptor 1... assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].State() == DevState.DISABLE assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].searchWindowTuning ==", "1, 1) assert all([proxies.subarray[subarr_index].receptors[i] == j for i, j in zip(range(num_receptors), input_receptors)]) assert", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[5][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[6][0] == 4464 #", "assert proxies.subarray[1].state()==DevState.OFF # proxies.subarray[1].On() # time.sleep(10) # # check initial value of attributes", "a minimal successful configuration \"\"\" for proxy in vcc_proxies: proxy.Init() fsp_3_proxies.subarray[1].Init() fsp_1_proxy.Init() fsp_2_proxy.Init()", "# # assert fsp_2_proxies.subarray[1].channelAveragingMap[18][0] == 13393 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[18][1] == 0 #", "e def test_Abort_Restart(self, proxies): \"\"\" Test abort restart \"\"\" try: # turn on", "7000000000 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].tdcEnable == False # # and lastly for", "TODO in CbfSubarray, at end of scan, clear all private data #assert proxies.subarray[sub_id].frequencyBand", "in vcc_band_proxies[receptor_to_vcc[4] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] assert [proxy.State() for", "scanID on VCC and FSP assert proxies.fspSubarray[1].scanID == 1 assert proxies.vcc[proxies.receptor_to_vcc[4]].scanID ==1 #", "- 1][0].tdcPeriodAfterEpoch == 25 assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcDestinationAddress == ( \"foo\", \"bar\", \"8080\"", "# proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) # f.close() # time.sleep(15) # # check configured attributes of", "i in range(3)] == input_receptors assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for i in input_receptors])", "0 assert proxies.subarray[sub_id].obsState == ObsState.EMPTY # add receptors proxies.subarray[sub_id].AddReceptors(test_receptor_ids) proxies.wait_timeout_obs([proxies.subarray[sub_id]], ObsState.IDLE, 1, 1)", "assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[0] == 5.85 # assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[1] == 7.25", "VCC belonging to receptor 2... assert proxies.vcc[proxies.receptor_to_vcc[2]].subarrayMembership == 1 assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBandOffsetStream1 == 0", "first for VCC belonging to receptor 10... assert proxies.vcc[proxies.receptor_to_vcc[4]].subarrayMembership == 1 assert proxies.vcc[proxies.receptor_to_vcc[4]].band5Tuning[0]", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[13][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[14][0] == 10417 # #", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[15][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[16][0] == 11904 # #", "function_mode = 1 elif fsp[\"function_mode\"] == \"PSS-BF\": function_mode = 2 elif fsp[\"function_mode\"] ==", "\"CORR\": function_mode = 1 elif fsp[\"function_mode\"] == \"PSS-BF\": function_mode = 2 elif fsp[\"function_mode\"]", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[14][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[15][0] == 11161 # #", "= json.loads(f.read().replace(\"\\n\", \"\")) f.close() jones_matrix[\"jonesMatrix\"][0][\"epoch\"] = str(int(time.time()) + 20) jones_matrix[\"jonesMatrix\"][1][\"epoch\"] = \"0\" jones_matrix[\"jonesMatrix\"][2][\"epoch\"]", "fsp_1_function_mode_proxy, fsp_2_function_mode_proxy, fsp_3_proxies.subarray[1], tm_telstate_proxy ): \"\"\" Test a minimal successful configuration \"\"\" for", "proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) assert proxies.subarray[1].State() == DevState.ON assert proxies.subarray[1].obsState == ObsState.EMPTY #", "proxies): \"\"\" Test the reception of Jones matrices \"\"\" try: # turn on", "( \"fizz\", \"buzz\", \"80\" ) # then for search window 2 of VCC", "assert proxies.subarray[subarr_index].obsState == ObsState.READY # Send the Scan command f2 = open(file_path +", "TestCbfSubarray: def test_AddRemoveReceptors_valid(self, proxies): \"\"\" Test valid AddReceptors and RemoveReceptors commands \"\"\" timeout_millis", "# assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[0] == 5.85 # assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[1] ==", "DevState.DISABLE ] # check configured attributes of FSP subarray #TODO align IDs of", "== j for i, j in zip(range(num_receptors), input_receptors)]) assert proxies.subarray[subarr_index].obsState == ObsState.IDLE #", "= json.dumps(delay_model) time.sleep(1) for model in delay_model[\"delayModel\"]: if model[\"destinationType\"] == \"fsp\": for receptor", "0 assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState.value == ObsState.IDLE.value # assert tm_telstate_proxy.visDestinationAddress ==", "open(file_path + \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) # check scanID", "1, 1) # Check obsStates AFTER the EndScan() command assert proxies.subarray[subarr_index].obsState == ObsState.READY", "ObsState.READY assert proxies.fspSubarray[3].obsState == ObsState.READY # send the Scan command f2 = open(file_path", "assert vcc_proxies[receptor_to_vcc[4] - 1].rfiFlaggingMask == \"{}\" # then for VCC belonging to receptor", "\"\".join(proxies.sw[1].tdcDestinationAddress.split()) in [ # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", # \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", # \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\", # ]", "== 3.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 3.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 3.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] ==", "assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch == 25 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcDestinationAddress == (", "fsp_1_proxies.subarray[1].channelAveragingMap[3][0] == 2232 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[3][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[4][0]", "assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream2 == 0 assert vcc_proxies[receptor_to_vcc[1] - 1].rfiFlaggingMask == \"{}\" #", "input_receptors]) assert proxies.subarray[1].obsState == ObsState.IDLE # add more receptors... proxies.subarray[1].AddReceptors([2]) time.sleep(1) assert [proxies.subarray[1].receptors[i]", "# # assert 1 in fsp_2_proxy.subarrayMembership # assert [proxy.State() for proxy in fsp_1_function_mode_proxy]", "pytest.raises(tango.DevFailed) as df: # subarray_2_proxy.AddReceptors([1, 2, 4]) # time.sleep(1) # assert \"already in", "[8184, \"192.168.0.2\"]], \"outputMac\": [[0, \"06-00-00-00-00-01\"]], \"outputPort\": [[0, 9000, 1], [8184, 9000, 1]]}).replace('\"',\"'\") #", "and debug! # assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcDestinationAddress == ( # \"fizz\", \"buzz\", \"80\"", "proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1, 1) assert proxies.subarray[1].obsState == ObsState.ABORTED # ObsReset proxies.subarray[1].ObsReset() proxies.wait_timeout_obs([proxies.subarray[1]],", "aa = delay_model[\"delayModel\"][0][\"delayDetails\"][0][\"receptorDelayDetails\"] num_fsp_IDs = len(aa) for jj in range(num_fsp_IDs): logging.info( \"delayCoeff =", "ae: proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e def test_ConfigureScan_minimal(self,", "DevState.DISABLE, DevState.DISABLE, DevState.DISABLE # # ] # # check configured attributes of FSP", "1) assert proxies.subarray[1].obsState == ObsState.SCANNING assert proxies.subarray[1].scanID == 2 assert proxies.fspSubarray[1].obsState == ObsState.SCANNING", "e def test_AddRemoveReceptors_invalid_single(self, proxies): \"\"\" Test invalid AddReceptors commands involving a single subarray:", "jj in range(num_fsp_IDs): logging.info( \"delayCoeff = {}\".format( aa[jj][\"delayCoeff\"]) ) try: # turn on", "4464 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[6][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[7][0] == 5208", "# fsp_2_proxy, # fsp_1_function_mode_proxy, # fsp_2_function_mode_proxy, # fsp_1_proxies.subarray[1], # fsp_2_proxies.subarray[1], # fsp_3_proxies.subarray[1], #", "assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcNumBits == 8 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch == 5", "TODO - re-enable and debug! # assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcDestinationAddress == ( #", "test_band1( self, cbf_master_proxy, proxies.subarray[1], sw_1_proxy, sw_2_proxy, vcc_proxies, vcc_band_proxies, vcc_tdc_proxies, fsp_1_proxy, fsp_2_proxy, fsp_1_function_mode_proxy, fsp_2_function_mode_proxy,", "== 1 # remove some receptors proxies.subarray[1].RemoveReceptors([2, 1, 4]) time.sleep(1) assert proxies.subarray[1].receptors ==", "first for search window 1 of VCC belonging to receptor 10... # assert", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 3.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 3.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 3.8 assert", "assert proxies.subarray[1].obsState == ObsState.IDLE # TODO: fix this # try adding an invalid", "matrix f = open(file_path + \"/../data/jonesmatrix.json\") jones_matrix = json.loads(f.read().replace(\"\\n\", \"\")) f.close() jones_matrix[\"jonesMatrix\"][0][\"epoch\"] =", "# time.sleep(15) # # check configured attributes of CBF subarray # assert proxies.subarray[1].configID", "= delay_model[\"delayModel\"][0][\"delayDetails\"][0][\"receptorDelayDetails\"] num_fsp_IDs = len(aa) for jj in range(num_fsp_IDs): logging.info( \"delayCoeff = {}\".format(", "== \"{}\" # # then for VCC belonging to receptor 1... # assert", "proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 3.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 3.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 3.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0]", "add function mode to enum or edit attribute to accept string in FSP", "{}, VCC {}, i = {}, jonesMatrix[{}] = {}\".format( jones_matrix[\"jonesMatrix\"][1][\"epoch\"], vcc_id, index, fs_id-1,", "in [2, 4]]) # assert subarray_2_proxy.State() == DevState.ON def test_RemoveAllReceptors(self, proxies): \"\"\" Test", "== ObsState.SCANNING assert proxies.fspSubarray[3].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState ==", "check configured attributes of CBF subarray assert proxies.subarray[1].configID == \"sbi-mvp01-20200325-00001-science_A\" assert proxies.subarray[1].frequencyBand ==", "reception of Jones matrices \"\"\" try: # turn on Subarray if proxies.subarray[1].State() !=", "[proxy.State() for proxy in proxies.vccBand[proxies.receptor_to_vcc[2] - 1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON]", "4700000 # assert fsp_1_proxies.subarray[1].integrationTime == 140 # assert fsp_1_proxies.subarray[1].fspChannelOffset == 14880 # #", "receptor list should be empty right after initialization assert len(proxies.subarray[1].receptors) == 0 assert", "e: raise e time.sleep(10) # update delay models from tm emulator f =", "all([vcc_proxies[receptor_to_vcc[i] - 1].subarrayMembership == 1 for i in [1, 3]]) # assert proxies.subarray[1].State()", "# assert [proxy.State() for proxy in fsp_2_function_mode_proxy] == [ # # DevState.ON, DevState.DISABLE,", "fsp_1_proxies.subarray[1].channelAveragingMap[2][0] == 1488 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[2][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[3][0]", "index, value in enumerate(receptor[\"receptorMatrix\"][0][\"matrix\"]): try: assert proxies.fsp[fs_id].jonesMatrix[rec_id - 1][index] == value except AssertionError", "all private data #assert proxies.subarray[1].frequencyBand == 0 assert proxies.subarray[1].obsState == ObsState.EMPTY # add", "10) # update delay model proxies.tm.beamWeights = json.dumps(timing_beam_weights) time.sleep(1) for weights in timing_beam_weights[\"beamWeights\"]:", "proxies.subarray[subarr_index].AddReceptors(input_receptors) proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[subarr_index].receptors[i] == j for i, j in", "f = open(file_path + \"/../data/delaymodel.json\") delay_model = json.loads(f.read().replace(\"\\n\", \"\")) f.close() aa = delay_model[\"delayModel\"][0][\"delayDetails\"][0][\"receptorDelayDetails\"]", "e: proxies.clean_proxies() raise e @pytest.mark.skip(reason=\"Since there's only a single subarray, this test is", "assert searchBeam400[\"averagingInterval\"] == 2 # assert searchBeam400[\"searchBeamDestinationAddress\"] == \"10.05.2.1\" # proxies.subarray[1].GoToIdle() # time.sleep(3)", "str(int(time.time())) for model in delay_model[\"delayModel\"]: model[\"epoch\"] = epoch if model[\"destinationType\"] == \"fsp\": epoch", "+ \"/../data/timingbeamweights.json\") timing_beam_weights = json.loads(f.read().replace(\"\\n\", \"\")) epoch = str(int(time.time())) for weights in timing_beam_weights[\"beamWeights\"]:", "config_file_name = input_test_data[1] subarr_index = 1; logging.info( \"input_receptors = {}\".format(input_receptors) ) logging.info( \"config_file_name", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 0.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 1.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 1.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5]", "assert fsp_1_proxies.subarray[1].outputLinkMap[3][0] == 2232 # assert fsp_1_subarray_1_proroxy.receptors[2] == 4 # # assert fsp_2_proxies.subarray[1].frequencyBand", "assert proxies.subarray[1].obsState == ObsState.EMPTY assert len(proxies.subarray[1].receptors) == 0 assert proxies.fspSubarray[1].obsState == ObsState.IDLE assert", "fsp_1_proxies.subarray[1].channelAveragingMap[13][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[14][0] == 10416 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[14][1]", "proxies.fspSubarray[3].receptors[0] == 3 assert proxies.fspSubarray[3].receptors[1] == 1 assert proxies.fspSubarray[3].searchWindowID == 2 assert proxies.fspSubarray[3].searchBeamID[0]", "assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[1] == 7.25 # assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream1 == 0", "= input_test_data[1] subarr_index = 1; logging.info( \"input_receptors = {}\".format(input_receptors) ) logging.info( \"config_file_name =", "# means 5a? # assert proxies.subarray[1].obsState.value == ObsState.READY.value # # check frequency band", "TODO in CbfSubarray, at end of scan, clear all private data #assert proxies.subarray[1].frequencyBand", "2 # with pytest.raises(tango.DevFailed) as df: # subarray_2_proxy.AddReceptors([1, 2, 4]) # time.sleep(1) #", "belonging to receptor 10... assert proxies.vccTdc[proxies.receptor_to_vcc[4] - 1][1].State() == DevState.DISABLE assert proxies.vccTdc[proxies.receptor_to_vcc[4] -", "Test invalid AddReceptors commands involving multiple subarrays: - when a receptor to be", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[7][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[8][0] == 5952 # #", ") # then for search window 1 of VCC belonging to receptor 1...", "proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY assert len(proxies.subarray[1].receptors) == 0", "in vcc_proxies: proxy.Init() fsp_3_proxies.subarray[1].Init() fsp_1_proxy.Init() fsp_2_proxy.Init() proxies.subarray[1].set_timeout_millis(60000) # since the command takes a", "from ska_mid_cbf_mcs.commons.global_enum import freq_band_dict from ska_tango_base.control_model import LoggingLevel, HealthState from ska_tango_base.control_model import AdminMode,", "1) configuration = json.loads(configuration) band_index = freq_band_dict()[configuration[\"common\"][\"frequency_band\"]] # check configured attributes of CBF", "assert fsp_2_proxies.subarray[1].channelAveragingMap[19][0] == 14137 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[19][1] == 0 # # then", "== 0 for i in [1, 3, 4]]) assert proxies.subarray[1].obsState == ObsState.EMPTY proxies.subarray[1].Off()", "fsp_1_function_mode_proxy, # fsp_2_function_mode_proxy, # fsp_1_proxies.subarray[1], # fsp_2_proxies.subarray[1], # fsp_3_proxies.subarray[1], # tm_telstate_proxy # ):", "assert fsp_3_proxies.subarray[1].searchBeamID[1] == 400 searchBeam = fsp_3_proxies.subarray[1].searchBeams searchBeam300 = json.loads(searchBeam[0]) searchBeam400 = json.loads(searchBeam[1])", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 2.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 2.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 2.8 assert", "assert proxies.vcc[vcc_index].frequencyBand == band_index assert proxies.vcc[vcc_index].subarrayMembership == sub_id #TODO fix these tests; issue", "# check configured attributes of search windows # first for search window 1...", "of CBF subarray vcc_index = proxies.receptor_to_vcc[4] logging.info(\"vcc_index = {}\".format( vcc_index )) assert len(proxies.subarray[1].receptors)", "fsp_2_proxy, fsp_1_function_mode_proxy, fsp_2_function_mode_proxy, fsp_3_proxies.subarray[1], tm_telstate_proxy ): \"\"\" Test a minimal successful configuration \"\"\"", "# proxy.Init() # fsp_1_proxies.subarray[1].Init() # fsp_2_proxies.subarray[1].Init() # fsp_3_proxies.subarray[1].Init() # fsp_1_proxy.Init() # fsp_2_proxy.Init() #", "configure scan f = open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30,", "ska_mid_cbf_mcs.commons.global_enum import freq_band_dict from ska_tango_base.control_model import LoggingLevel, HealthState from ska_tango_base.control_model import AdminMode, ObsState", "assert proxies.subarray[1].receptors[1] == 3 proxies.subarray[1].RemoveAllReceptors() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.OFF, 3,", "[proxy.State() for proxy in proxies.fsp2FunctionMode] == [ DevState.DISABLE, DevState.DISABLE, DevState.ON, DevState.DISABLE ] #", "turn on Subarray # assert proxies.subarray[1].state()==DevState.OFF # proxies.subarray[1].On() # time.sleep(10) # # check", "except Exception as e: proxies.clean_proxies() raise e def test_AddRemoveReceptors_invalid_single(self, proxies): \"\"\" Test invalid", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[13][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[14][0] == 10416 #", "{}\".format(datetime.now())) if proxies.debug_device_is_on: port = proxies.subarray[1].DebugDevice() try: proxies.clean_proxies() if proxies.controller.State() == DevState.OFF: proxies.controller.Init()", "Exception as e: proxies.clean_proxies() raise e @pytest.mark.skip(reason=\"Since there's only a single subarray, this", "DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ] # check configured attributes of FSP subarray #TODO", "assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState == ObsState.SCANNING assert proxies.fspSubarray[1].obsState == ObsState.SCANNING assert proxies.fspSubarray[3].obsState == ObsState.SCANNING proxies.subarray[1].EndScan()", "proxies.clean_proxies() raise ae except Exception as e: proxies.clean_proxies() raise e @pytest.mark.skip(reason=\"pst not currently", "for i in range(4)]: if proxy.State() == DevState.OFF: proxy.On() proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1)", "fsp_2_proxies.subarray[1].channelAveragingMap[19][0] == 14137 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[19][1] == 0 # # then for", "json.loads(configuration) band_index = freq_band_dict()[configuration[\"common\"][\"frequency_band\"]] # check configured attributes of CBF subarray assert sub_id", "ObsState.READY for fsp in input_config_dict[\"cbf\"][\"fsp\"]: if fsp[\"function_mode\"] == \"CORR\": assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.READY", "{}\".format(proxy.State())) # for i in range(4): # if (i == 0 and band_index", "i in range(4)], ObsState.READY, 1, 1) # check frequency band of VCCs, including", "# # configure scan # f = open(file_path + \"/test_json/test_ConfigureScan_basic.json\") # proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\"))", "proxies.wait_timeout_dev([proxy], DevState.ON, 1, 1) for proxy in [proxies.fsp[i + 1] for i in", "2.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 2.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 2.8 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][0] == 2.9", "TODO - this does not pass - to debug & fix #assert searchBeam1[\"searchBeamDestinationAddress\"]", "takes pretty long for CBF Master to initialize tm_telstate_proxy.Init() time.sleep(1) receptor_to_vcc = dict([*map(int,", "- # assert [proxy.State() for proxy in fsp_2_function_mode_proxy] == [ # DevState.ON, DevState.DISABLE,", "== 12648 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[17][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[18][0] ==", "== 3 assert all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 1 for i in [1, 3]]) assert proxies.subarray[1].obsState", "() # assert subarray_2_proxy.receptors == () # assert all([proxy.subarrayMembership == 0 for proxy", "fix #elif fsp[\"function_mode\"] == \"PST-BF\": # assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.SCANNING proxies.subarray[subarr_index].EndScan() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.READY,", "1].frequencyBandOffsetStream1 == 0 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream2 == 0 assert vcc_proxies[receptor_to_vcc[1] - 1].rfiFlaggingMask", "belonging to receptor 10... assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].State() == DevState.DISABLE assert vcc_tdc_proxies[receptor_to_vcc[4] -", "0 assert proxies.vcc[proxies.receptor_to_vcc[3]].subarrayMembership == 0 assert proxies.subarray[1].obsState == ObsState.EMPTY proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.OFF, 3,", "== 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[8][0] == 5952 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[8][1] ==", "== 0 # means 1 assert proxies.subarray[1].obsState.value == ObsState.READY.value # check frequency band", "proxies.fspSubarray[fsp_id].frequencyBand == band_index assert proxies.fspSubarray[fsp_id].frequencySliceID == fsp[\"frequency_slice_id\"] assert proxies.fspSubarray[fsp_id].integrationTime == fsp[\"integration_factor\"] assert proxies.fspSubarray[fsp_id].corrBandwidth", "of attributes of CBF subarray # assert proxies.subarray[1].receptors == () # assert proxies.subarray[1].configID", "== 3.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 3.4 # transition to obsState=SCANNING f2 = open(file_path", "# and lastly for search window 2 of VCC belonging to receptor 1...", "# assert proxies.sw[1].tdcNumBits == 8 # assert proxies.sw[1].tdcPeriodBeforeEpoch == 5 # assert proxies.sw[1].tdcPeriodAfterEpoch", "1 for i in [1, 3, 4]]) assert proxies.subarray[1].obsState == ObsState.IDLE # remove", "# first for VCC belonging to receptor 10... assert vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership ==", "to obsState=SCANNING f2 = open(file_path + \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1,", "# # assert fsp_2_proxies.subarray[1].frequencySliceID == 20 # # assert fsp_2_proxies.subarray[1].corrBandwidth == 0 #", "# to be decide which one to keep. # print(\"proxies.sw[1].State() = {}\".format(proxies.sw[1].State())) #", "6000000000 assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcEnable == True assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcNumBits == 8", "#TODO: fix; currently tests break if multiple scan configurations are tested def test_ConfigureScan_basic(self,", "{}\".format(config_file_name) ) num_receptors = len(input_receptors) vcc_ids = [None for _ in range(num_receptors)] for", "ObsState.IDLE, 1, 1) # configure scan f = open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\"))", "ObsState.SCANNING, 1, 1) assert proxies.subarray[1].obsState == ObsState.SCANNING time.sleep(10) assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 2.1 assert", "configure scan f = open(file_path + \"/test_json/test_ConfigureScan_onlyPss_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close() time.sleep(15) # check", "fs_id = receptor[\"receptorMatrix\"][0][\"fsid\"] for index, value in enumerate(receptor[\"receptorMatrix\"][0][\"matrix\"]): try: assert proxies.fsp[fs_id].jonesMatrix[rec_id - 1][index]", "3, 2])]) # configure scan f = open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\", \"\")) f.close()", "for FSP 3 ... (this is a PSS fsp device) assert proxies.fspSubarray[3].receptors[0] ==", "# assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcDestinationAddress == ( # \"foo\", \"bar\", \"8080\" # )", "# cbf_master_proxy.set_timeout_millis(60000) # cbf_master_proxy.Init() # time.sleep(60) # takes pretty long for CBF Master", "of VCC belonging to receptor 1... assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].State() == DevState.ON assert", "assert proxies.subarray[1].receptors[1] == 3 assert proxies.subarray[1].receptors[2] == 4 # configure scan f =", "assert fsp_1_proxies.subarray[1].outputLinkMap[1][0] == 744 # assert fsp_1_proxies.subarray[1].outputLinkMap[1][1] == 8 # assert fsp_1_proxies.subarray[1].outputLinkMap[2][0] ==", "1, 1) # check initial value of attributes of CBF subarray assert len(proxies.subarray[sub_id].receptors)", "# time.sleep(1) # receptor_to_vcc = dict([*map(int, pair.split(\":\"))] for pair in # cbf_master_proxy.receptorToVcc) #", "assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][3] == 1.6 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][4] == 1.7 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][5] == 1.8 assert", "== 8 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch == 5 # assert vcc_tdc_proxies[receptor_to_vcc[4] -", "== 1488 # assert fsp_1_proxies.subarray[1].outputLinkMap[2][1] == 12 # assert fsp_1_proxies.subarray[1].outputLinkMap[3][0] == 2232 #", "for proxy in proxies.fsp2FunctionMode] == [ DevState.DISABLE, DevState.DISABLE, DevState.ON, DevState.DISABLE ] # check", "assert proxies.subarray[1].obsState == ObsState.IDLE proxies.subarray[1].RemoveAllReceptors() time.sleep(3) assert proxies.subarray[1].state() == tango.DevState.OFF def test_band1( self,", "f.close() time.sleep(15) # check configured attributes of CBF subarray assert proxies.subarray[1].configID == \"sbi-mvp01-20200325-00001-science_A\"", "== 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[16][0] == 11904 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[16][1] ==", "e @pytest.mark.skip(reason=\"pst not currently supported\") def test_ConfigureScan_onlyPst_basic(self, proxies): \"\"\" Test a successful PST-BF", "vcc_tdc_proxies, fsp_1_proxy, fsp_2_proxy, fsp_1_function_mode_proxy, fsp_2_function_mode_proxy, fsp_1_proxies.subarray[1], fsp_2_proxies.subarray[1], fsp_3_proxies.subarray[1], tm_telstate_proxy ): \"\"\" Test a", "proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][1].tdcEnable == False # check configured attributes of FSPs, including states", "# # assert fsp_1_proxies.subarray[1].channelAveragingMap[8][0] == 5952 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[8][1] == 8 #", "len(proxies.subarray[1].receptors) == 0 assert proxies.vcc[proxies.receptor_to_vcc[3]].subarrayMembership == 0 assert proxies.subarray[1].obsState == ObsState.EMPTY proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]],", "range(num_receptors)] for receptor_id, ii in zip(input_receptors, range(num_receptors)): vcc_ids[ii] = proxies.receptor_to_vcc[receptor_id] proxies.subarray[subarr_index].AddReceptors(input_receptors) proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.IDLE,", "ObsState.EMPTY # receptor list should be empty right after initialization assert len(proxies.subarray[1].receptors) ==", "5 assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch == 25 # TODO - re-enable and debug!", "1 assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[0] == 5.85 assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[1] == 7.25", "# assert fsp_1_proxies.subarray[1].channelAveragingMap[13][0] == 9672 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[13][1] == 8 # #", "assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[4] - 1]] == [ # DevState.DISABLE, DevState.DISABLE,", "Jones matrices \"\"\" try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On()", "1].frequencyBandOffsetStream1 == 0 # assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream2 == 0 # assert vcc_proxies[receptor_to_vcc[1]", "proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 3.0 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][4] == 3.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][5] == 3.2 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[0][0]", "vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream1 == 0 assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBandOffsetStream2 == 0 assert vcc_proxies[receptor_to_vcc[4]", "assert fsp_1_proxies.subarray[1].channelAveragingMap[9][1] == 8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[10][0] == 7440 # # assert", "== \"10.05.2.1\" # check configured attributes of FSP subarrays # first for FSP", "fsp_function_mode_proxies[fsp_id-1]] == [ DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE ] # check configured attributes of", "fsp_2_proxies.subarray[1].channelAveragingMap[3][0] == 2233 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[3][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[4][0]", "proxies.fspSubarray[fsp_id].channelAveragingMap[i][j] == fsp[\"channel_averaging_map\"][i][j] for i in range(len(fsp[\"output_link_map\"])): for j in range(len(fsp[\"output_link_map\"][i])): assert proxies.fspSubarray[fsp_id].outputLinkMap[i][j]", "vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].State() == DevState.ON assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].searchWindowTuning == 6000000000 assert vcc_tdc_proxies[receptor_to_vcc[1]", "assert searchBeam400[\"receptors\"][0] == 1 assert searchBeam400[\"outputEnable\"] == True assert searchBeam400[\"averagingInterval\"] == 2 assert", "3, 4])]) assert proxies.fspSubarray[1].obsState == ObsState.IDLE assert proxies.fspSubarray[3].obsState == ObsState.IDLE assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState ==", "2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[1].receptors[i] == j for i, j in", "assert proxies.fspSubarray[fsp_id].zoomWindowTuning == fsp[\"zoom_window_tuning\"] assert proxies.fspSubarray[fsp_id].fspChannelOffset == fsp[\"channel_offset\"] for i in range(len(fsp[\"channel_averaging_map\"])): for", "proxies.subarray[1].obsState == ObsState.EMPTY proxies.subarray[1].Off() proxies.wait_timeout_dev([proxies.subarray[1]], DevState.OFF, 3, 1) except AssertionError as ae: proxies.clean_proxies()", "\"foo\", \"bar\", \"8080\" ) # then for search window 1 of VCC belonging", "e: proxies.clean_proxies() raise e def test_Abort_Restart(self, proxies): \"\"\" Test abort restart \"\"\" try:", "configuration: assert proxies.fspCorrSubarray[subarr_index-1].obsState == ObsState.IDLE assert proxies.fspPssSubarray[subarr_index-1].obsState == ObsState.IDLE assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.IDLE", "== DevState.ON # assert sw_1_proxy.searchWindowTuning == 6000000000 # assert sw_1_proxy.tdcEnable == True #", "# fsp_3_proxies.subarray[1].Init() # fsp_1_proxy.Init() # fsp_2_proxy.Init() # proxies.subarray[1].set_timeout_millis(60000) # since the command takes", "== 12 # assert fsp_1_proxies.subarray[1].outputLinkMap[3][0] == 2232 # assert fsp_1_subarray_1_proroxy.receptors[2] == 4 #", "# assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand == 4 # assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBand ==", "configuration \"\"\" try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On() proxies.wait_timeout_dev([proxies.subarray[1]],", "all([proxies.vcc[proxies.receptor_to_vcc[i]].subarrayMembership == 0 for i in [1, 2, 4]]) assert proxies.vcc[proxies.receptor_to_vcc[3]].subarrayMembership == 1", "1]] == [ DevState.DISABLE, DevState.DISABLE, DevState.DISABLE, DevState.ON] assert [proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[1]", "True assert searchBeam1[\"averaging_interval\"] == 2 # TODO - this does not pass -", "== ObsState.READY assert all([proxies.fspSubarray[6].receptors[i] == j for i, j in zip(range(1), [2])]) assert", "3, 1) for proxy in [proxies.vcc[i + 1] for i in range(4)]: if", "fsp_3_proxies.subarray[1].searchBeamID[0] == 300 # assert fsp_3_proxies.subarray[1].searchBeamID[1] == 400 # searchBeam = fsp_3_proxies.subarray[1].searchBeams #", "assert all([proxies.fspSubarray[6].timingBeamID[i] == j for i, j in zip(range(1), [10])]) # Clean Up", "json.loads(json_string) proxies.subarray[subarr_index].Scan(json_string) f2.close() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.SCANNING, 1, 1) # Note: scan_id is 1-based and", "proxies, input_test_data): \"\"\" Test the EndScan command \"\"\" try: # turn on Subarray", "\"band:5a, fsp1, 744 channels average factor 8\" assert proxies.subarray[1].frequencyBand == 4 assert proxies.subarray[1].obsState", "assert all([proxies.fspSubarray[6].receptors[i] == j for i, j in zip(range(1), [2])]) assert all([proxies.fspSubarray[6].timingBeamID[i] ==", "attributes of CBF subarray # assert len(proxies.subarray[1].receptors) == 0 # assert proxies.subarray[1].configID ==", "# configurations or causing a fault within the Vcc device # for proxy", "band_index assert proxies.subarray[sub_id].obsState == ObsState.READY proxies.wait_timeout_obs([proxies.vcc[i + 1] for i in range(4)], ObsState.READY,", "== ObsState.EMPTY # add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1)", "abort reset \"\"\" try: # turn on Subarray if proxies.subarray[1].State() != DevState.ON: proxies.subarray[1].On()", "of CBF subarray # assert proxies.subarray[1].configID == \"band:5a, fsp1, 744 channels average factor", "port = proxies.subarray[1].DebugDevice() try: proxies.clean_proxies() if proxies.controller.State() == DevState.OFF: proxies.controller.Init() proxies.wait_timeout_dev([proxies.controller], DevState.STANDBY, 3,", "ObsState.IDLE, 1, 1) assert proxies.subarray[1].obsState == ObsState.IDLE # abort proxies.subarray[1].Abort() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.ABORTED, 1,", "tm emulator f = open(file_path + \"/../data/delaymodel_fsp.json\") delay_model = json.loads(f.read().replace(\"\\n\", \"\")) epoch =", "[proxy.State() for proxy in vcc_band_proxies[receptor_to_vcc[4] - 1]] == [ # DevState.DISABLE, DevState.DISABLE, DevState.DISABLE,", "for i in [1, 2, 4]]) assert proxies.vcc[proxies.receptor_to_vcc[3]].subarrayMembership == 1 # remove remaining", "4]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) assert all([proxies.subarray[1].receptors[i] == j for i, j in", "proxies.fspSubarray[1].obsState == ObsState.SCANNING assert proxies.fspSubarray[3].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[1]].obsState == ObsState.SCANNING assert proxies.vcc[proxies.receptor_to_vcc[4]].obsState", "range(len(fsp[\"output_link_map\"][i])): assert proxies.fspSubarray[fsp_id].outputLinkMap[i][j] == fsp[\"output_link_map\"][i][j] proxies.clean_proxies() except AssertionError as ae: proxies.clean_proxies() raise ae", "10... # assert vcc_proxies[receptor_to_vcc[4] - 1].subarrayMembership == 1 # assert vcc_proxies[receptor_to_vcc[4] - 1].band5Tuning[0]", "in [1, 3, 4]]) assert proxies.subarray[1].obsState == ObsState.IDLE # remove all receptors proxies.subarray[1].RemoveAllReceptors()", "== 5.85 # assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[1] == 7.25 # assert vcc_proxies[receptor_to_vcc[1] -", "# TODO: fix this # try adding an invalid receptor ID # with", "== 1489 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[2][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[3][0] ==", "8 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[11][0] == 8184 # # assert fsp_1_proxies.subarray[1].channelAveragingMap[11][1] == 8", "1].frequencyBand == 0 # check the rest of the configured attributes of VCCs", "1].band5Tuning[0] == 5.85 assert vcc_proxies[receptor_to_vcc[1] - 1].band5Tuning[1] == 7.25 assert vcc_proxies[receptor_to_vcc[1] - 1].frequencyBandOffsetStream1", "of VCCs, including states of frequency band capabilities assert vcc_proxies[receptor_to_vcc[4] - 1].frequencyBand ==", "proxies.vcc[jj+1].receptorID))) logging.info( (\"Vcc, receptor 1, ObsState = {}\". format(proxies.vcc[proxies.receptor_to_vcc[1]].ObsState)) ) #proxies.vcc[0].receptorID assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0]", "of # frequency band capabilities logging.info( (\"proxies.vcc[vcc_index].frequencyBand = {}\". format( proxies.vcc[vcc_index].frequencyBand)) ) vcc_band_proxies", "1][0].tdcPeriodBeforeEpoch == 5 # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcPeriodAfterEpoch == 25 # assert vcc_tdc_proxies[receptor_to_vcc[1]", "assert vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership == 1 # check configured attributes of FSPs, including", "and lastly for search window 2 of VCC belonging to receptor 1... assert", "window 2 of VCC belonging to receptor 1... # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][1].State()", "== 3.4 # transition to obsState=SCANNING f2 = open(file_path + \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\"))", "band of VCCs, including states of frequency band capabilities # assert vcc_proxies[receptor_to_vcc[4] -", "proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.IDLE, 1, 1) # configure scan f = open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f.read().replace(\"\\n\",", "first for search window 1... # assert sw_1_proxy.State() == DevState.ON # assert sw_1_proxy.searchWindowTuning", "to receptor 1... assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].State() == DevState.ON assert proxies.vccTdc[proxies.receptor_to_vcc[1] - 1][0].searchWindowTuning", "in proxies.fsp2FunctionMode] == [ DevState.DISABLE, DevState.DISABLE, DevState.ON, DevState.DISABLE ] # check configured attributes", "1) assert proxies.subarray[1].obsState == ObsState.IDLE assert all([proxies.subarray[1].receptors[i] == j for i, j in", "8 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodBeforeEpoch == 5 # assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][0].tdcPeriodAfterEpoch", "ObsState.EMPTY, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY assert len(proxies.subarray[1].receptors) == 0 assert proxies.fspSubarray[1].obsState", "j for i, j in zip(range(len(test_receptor_ids)), test_receptor_ids)]) # configure scan f = open(file_path", "== 0 assert proxies.fspSubarray[1].channelAveragingMap[0][1] == 8 assert proxies.fspSubarray[1].channelAveragingMap[1][0] == 744 assert proxies.fspSubarray[1].channelAveragingMap[1][1] ==", "fsp_2_proxies.subarray[1].channelAveragingMap[16][0] == 11905 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[16][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[17][0]", "# assert searchBeam300[\"searchBeamDestinationAddress\"] == \"10.05.1.1\" # assert searchBeam400[\"searchBeamID\"] == 400 # assert searchBeam400[\"receptors\"][0]", "1 # remove remaining receptors proxies.subarray[1].RemoveReceptors([3]) proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert len(proxies.subarray[1].receptors) ==", "then for search window 2 of VCC belonging to receptor 10... assert proxies.vccTdc[proxies.receptor_to_vcc[4]", "1 and 2 assert proxies.fspSubarray[fsp_id].obsState == ObsState.READY assert proxies.fspSubarray[fsp_id].receptors == test_receptor_ids[0] assert proxies.fspSubarray[fsp_id].frequencyBand", "# assert fsp_2_proxies.subarray[1].channelAveragingMap[0][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[1][0] == 745 # #", "DevState.ON, DevState.DISABLE, DevState.DISABLE, DevState.DISABLE # # ] # # check configured attributes of", "#create a Jones matrix f = open(file_path + \"/../data/jonesmatrix.json\") jones_matrix = json.loads(f.read().replace(\"\\n\", \"\"))", "proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBandOffsetStream1 == 0 assert proxies.vcc[proxies.receptor_to_vcc[2]].frequencyBandOffsetStream2 == 0 assert proxies.vcc[proxies.receptor_to_vcc[2]].rfiFlaggingMask == \"{}\" # check", "proxies.subarray[sub_id].frequencyBand == 0 assert proxies.subarray[sub_id].obsState == ObsState.EMPTY # add receptors proxies.subarray[sub_id].AddReceptors(test_receptor_ids) proxies.wait_timeout_obs([proxies.subarray[sub_id]], ObsState.IDLE,", "== 1 assert proxies.vcc[proxies.receptor_to_vcc[4]].band5Tuning[0] == 5.85 assert proxies.vcc[proxies.receptor_to_vcc[4]].band5Tuning[1] == 7.25 assert proxies.vcc[proxies.receptor_to_vcc[4]].frequencyBandOffsetStream1 ==", "{} \".format(timeout_millis) #logging.info(log_msg) #logging.info(\"start_time = {}\".format(time.time())) logging.info(\"start datetime = {}\".format(datetime.now())) if proxies.debug_device_is_on: port", "then for VCC belonging to receptor 1... # assert vcc_proxies[receptor_to_vcc[1] - 1].subarrayMembership ==", "f2 = open(file_path + \"/../data/Scan1_basic.json\") proxies.subarray[1].Scan(f2.read().replace(\"\\n\", \"\")) f2.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.SCANNING, 1, 1) assert", "\"\") f.close() proxies.subarray[sub_id].ConfigureScan(configuration) proxies.wait_timeout_obs([proxies.subarray[sub_id]], ObsState.READY, 15, 1) configuration = json.loads(configuration) band_index = freq_band_dict()[configuration[\"common\"][\"frequency_band\"]]", "in timing_beam_weights[\"beamWeights\"]: for receptor in weights[\"beamWeightsDetails\"]: rec_id = int(receptor[\"receptor\"]) fs_id = receptor[\"receptorWeightsDetails\"][0][\"fsid\"] for", "search window 1... # assert sw_1_proxy.State() == DevState.ON # assert sw_1_proxy.searchWindowTuning == 6000000000", "1 # doing this doesn't actually throw an error proxies.subarray[1].RemoveReceptors([2]) assert proxies.subarray[1].receptors[0] ==", "== 5 assert sw_1_proxy.tdcPeriodAfterEpoch == 25 assert \"\".join(sw_1_proxy.tdcDestinationAddress.split()) in [ \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", \"[{\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"],\\\"receptorID\\\":4},{\\\"receptorID\\\":1,\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"]}]\", \"[{\\\"receptorID\\\":4,\\\"tdcDestinationAddress\\\":[\\\"foo\\\",\\\"bar\\\",\\\"8080\\\"]},{\\\"tdcDestinationAddress\\\":[\\\"fizz\\\",\\\"buzz\\\",\\\"80\\\"],\\\"receptorID\\\":1}]\",", "states of function mode capabilities assert fsp_1_proxy.functionMode == 1 assert 1 in fsp_1_proxy.subarrayMembership", "( \"foo\", \"bar\", \"8080\" ) # then for search window 1 of VCC", "Test the reception of delay models \"\"\" # Read delay model data from", "# turn on Subarray # assert proxies.subarray[1].state()==DevState.OFF # proxies.subarray[1].On() # time.sleep(10) # #", "== 1 assert fsp_1_proxies.subarray[1].outputLinkMap[0][1] == 0 assert fsp_1_proxies.subarray[1].outputLinkMap[1][0] == 201 assert fsp_1_proxies.subarray[1].outputLinkMap[1][1] ==", "1... # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].State() == DevState.ON # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].searchWindowTuning", "# assert fsp_2_proxies.subarray[1].frequencySliceID == 20 # # assert fsp_2_proxies.subarray[1].corrBandwidth == 0 # #", "should be empty proxies.subarray[1].Restart() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.EMPTY, 1, 1) assert proxies.subarray[1].obsState == ObsState.EMPTY assert", "proxies.sw[2].searchWindowTuning == 7000000000 # assert proxies.sw[2].tdcEnable == False time.sleep(1) # check configured attributes", "assert vcc_tdc_proxies[receptor_to_vcc[4] - 1][1].tdcEnable == False # # and lastly for search window", "== 9673 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[13][1] == 0 # # assert fsp_2_proxies.subarray[1].channelAveragingMap[14][0] ==", "fsp[\"zoom_window_tuning\"] assert proxies.fspSubarray[fsp_id].fspChannelOffset == fsp[\"channel_offset\"] for i in range(len(fsp[\"channel_averaging_map\"])): for j in range(len(fsp[\"channel_averaging_map\"][i])):", "open(file_path + \"/../data/ConfigureScan_basic.json\") proxies.subarray[1].ConfigureScan(f1.read().replace(\"\\n\", \"\")) f1.close() proxies.wait_timeout_obs([proxies.subarray[1]], ObsState.READY, 30, 1) # check initial", "0 assert proxies.subarray[1].obsState == ObsState.EMPTY # add receptors proxies.subarray[1].AddReceptors([1, 3, 4, 2]) proxies.wait_timeout_obs([proxies.subarray[1]],", "4.3 assert proxies.vcc[proxies.receptor_to_vcc[4]].delayModel[1][5] == 4.4 time.sleep(10) assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][0] == 0.1 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[0][1] ==", "== 1 assert proxies.fspSubarray[1].fspChannelOffset == 14880 assert proxies.fspSubarray[1].channelAveragingMap[0][0] == 0 assert proxies.fspSubarray[1].channelAveragingMap[0][1] ==", "\"/../data/Scan1_basic.json\") json_string = f2.read().replace(\"\\n\", \"\") input_scan_dict = json.loads(json_string) proxies.subarray[subarr_index].Scan(json_string) f2.close() proxies.wait_timeout_obs([proxies.subarray[subarr_index]], ObsState.SCANNING, 1,", "# assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcEnable == True # assert vcc_tdc_proxies[receptor_to_vcc[1] - 1][0].tdcNumBits ==", "fsp_1_proxies.subarray[1], fsp_2_proxies.subarray[1], fsp_3_proxies.subarray[1], tm_telstate_proxy ): \"\"\" Test a minimal successful configuration \"\"\" for", "file_path = os.path.dirname(os.path.abspath(__file__)) # Tango imports import tango from tango import DevState import", "0.7 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][1] == 0.8 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][2] == 0.9 assert proxies.vcc[proxies.receptor_to_vcc[1]].delayModel[1][3] == 1.0", "pass, to fix #elif fsp[\"function_mode\"] == \"PST-BF\": # assert proxies.fspPstSubarray[subarr_index-1].obsState == ObsState.READY proxies.clean_proxies()" ]
[ "from mmgroup.mm_space import MMSpace, MMV, MMVector from mmgroup.mm_space import characteristics from mmgroup.structures.mm0_group import", "self.space(*args) def MMTestSpace(p): global spaces_dict try: return spaces_dict[p] except KeyError: spaces_dict[p] = TestSpace(p)", "spaces_dict = {} g = MM0Group() ref_g = MGroupN() class TestSpace: def __init__(self,", "mmgroup.structures.mm0_group import MM0Group from mmgroup.tests.spaces.sparse_mm_space import SparseMmSpace from mmgroup.tests.spaces.sparse_mm_space import SparseMmV from mmgroup.tests.groups.mgroup_n", "mmgroup.tests.spaces.sparse_mm_space import SparseMmV from mmgroup.tests.groups.mgroup_n import MGroupN #print(\"module mmgroup.tests.spaces.spaces is deprecated!!\") spaces_dict =", "MGroupN() class TestSpace: def __init__(self, p): self.p = p self.space = MMV(p) self.ref_space", "MM0Group() ref_g = MGroupN() class TestSpace: def __init__(self, p): self.p = p self.space", "self.ref_group = ref_g def __call__(self, *args): return self.space(*args) def MMTestSpace(p): global spaces_dict try:", "import MGroupN #print(\"module mmgroup.tests.spaces.spaces is deprecated!!\") spaces_dict = {} g = MM0Group() ref_g", "p self.space = MMV(p) self.ref_space = SparseMmV(p) self.group = g self.ref_group = ref_g", "ref_g def __call__(self, *args): return self.space(*args) def MMTestSpace(p): global spaces_dict try: return spaces_dict[p]", "__call__(self, *args): return self.space(*args) def MMTestSpace(p): global spaces_dict try: return spaces_dict[p] except KeyError:", "import characteristics from mmgroup.structures.mm0_group import MM0Group from mmgroup.tests.spaces.sparse_mm_space import SparseMmSpace from mmgroup.tests.spaces.sparse_mm_space import", "from mmgroup.mm_space import characteristics from mmgroup.structures.mm0_group import MM0Group from mmgroup.tests.spaces.sparse_mm_space import SparseMmSpace from", "def __init__(self, p): self.p = p self.space = MMV(p) self.ref_space = SparseMmV(p) self.group", "self.p = p self.space = MMV(p) self.ref_space = SparseMmV(p) self.group = g self.ref_group", "#print(\"module mmgroup.tests.spaces.spaces is deprecated!!\") spaces_dict = {} g = MM0Group() ref_g = MGroupN()", "mmgroup.mm_space import MMSpace, MMV, MMVector from mmgroup.mm_space import characteristics from mmgroup.structures.mm0_group import MM0Group", "class TestSpace: def __init__(self, p): self.p = p self.space = MMV(p) self.ref_space =", "MMVector from mmgroup.mm_space import characteristics from mmgroup.structures.mm0_group import MM0Group from mmgroup.tests.spaces.sparse_mm_space import SparseMmSpace", "__init__(self, p): self.p = p self.space = MMV(p) self.ref_space = SparseMmV(p) self.group =", "SparseMmV(p) self.group = g self.ref_group = ref_g def __call__(self, *args): return self.space(*args) def", "*args): return self.space(*args) def MMTestSpace(p): global spaces_dict try: return spaces_dict[p] except KeyError: spaces_dict[p]", "deprecated!!\") spaces_dict = {} g = MM0Group() ref_g = MGroupN() class TestSpace: def", "from mmgroup.tests.spaces.sparse_mm_space import SparseMmSpace from mmgroup.tests.spaces.sparse_mm_space import SparseMmV from mmgroup.tests.groups.mgroup_n import MGroupN #print(\"module", "mmgroup.tests.groups.mgroup_n import MGroupN #print(\"module mmgroup.tests.spaces.spaces is deprecated!!\") spaces_dict = {} g = MM0Group()", "mmgroup.mm_space import characteristics from mmgroup.structures.mm0_group import MM0Group from mmgroup.tests.spaces.sparse_mm_space import SparseMmSpace from mmgroup.tests.spaces.sparse_mm_space", "= SparseMmV(p) self.group = g self.ref_group = ref_g def __call__(self, *args): return self.space(*args)", "mmgroup.tests.spaces.spaces is deprecated!!\") spaces_dict = {} g = MM0Group() ref_g = MGroupN() class", "= ref_g def __call__(self, *args): return self.space(*args) def MMTestSpace(p): global spaces_dict try: return", "g = MM0Group() ref_g = MGroupN() class TestSpace: def __init__(self, p): self.p =", "MMV, MMVector from mmgroup.mm_space import characteristics from mmgroup.structures.mm0_group import MM0Group from mmgroup.tests.spaces.sparse_mm_space import", "import MM0Group from mmgroup.tests.spaces.sparse_mm_space import SparseMmSpace from mmgroup.tests.spaces.sparse_mm_space import SparseMmV from mmgroup.tests.groups.mgroup_n import", "= MMV(p) self.ref_space = SparseMmV(p) self.group = g self.ref_group = ref_g def __call__(self,", "import MMSpace, MMV, MMVector from mmgroup.mm_space import characteristics from mmgroup.structures.mm0_group import MM0Group from", "def __call__(self, *args): return self.space(*args) def MMTestSpace(p): global spaces_dict try: return spaces_dict[p] except", "MMV(p) self.ref_space = SparseMmV(p) self.group = g self.ref_group = ref_g def __call__(self, *args):", "MMTestSpace(p): global spaces_dict try: return spaces_dict[p] except KeyError: spaces_dict[p] = TestSpace(p) return spaces_dict[p]", "self.ref_space = SparseMmV(p) self.group = g self.ref_group = ref_g def __call__(self, *args): return", "import SparseMmSpace from mmgroup.tests.spaces.sparse_mm_space import SparseMmV from mmgroup.tests.groups.mgroup_n import MGroupN #print(\"module mmgroup.tests.spaces.spaces is", "= g self.ref_group = ref_g def __call__(self, *args): return self.space(*args) def MMTestSpace(p): global", "from mmgroup.tests.spaces.sparse_mm_space import SparseMmV from mmgroup.tests.groups.mgroup_n import MGroupN #print(\"module mmgroup.tests.spaces.spaces is deprecated!!\") spaces_dict", "def MMTestSpace(p): global spaces_dict try: return spaces_dict[p] except KeyError: spaces_dict[p] = TestSpace(p) return", "MMSpace, MMV, MMVector from mmgroup.mm_space import characteristics from mmgroup.structures.mm0_group import MM0Group from mmgroup.tests.spaces.sparse_mm_space", "import SparseMmV from mmgroup.tests.groups.mgroup_n import MGroupN #print(\"module mmgroup.tests.spaces.spaces is deprecated!!\") spaces_dict = {}", "= {} g = MM0Group() ref_g = MGroupN() class TestSpace: def __init__(self, p):", "self.group = g self.ref_group = ref_g def __call__(self, *args): return self.space(*args) def MMTestSpace(p):", "is deprecated!!\") spaces_dict = {} g = MM0Group() ref_g = MGroupN() class TestSpace:", "{} g = MM0Group() ref_g = MGroupN() class TestSpace: def __init__(self, p): self.p", "ref_g = MGroupN() class TestSpace: def __init__(self, p): self.p = p self.space =", "p): self.p = p self.space = MMV(p) self.ref_space = SparseMmV(p) self.group = g", "return self.space(*args) def MMTestSpace(p): global spaces_dict try: return spaces_dict[p] except KeyError: spaces_dict[p] =", "self.space = MMV(p) self.ref_space = SparseMmV(p) self.group = g self.ref_group = ref_g def", "= p self.space = MMV(p) self.ref_space = SparseMmV(p) self.group = g self.ref_group =", "SparseMmSpace from mmgroup.tests.spaces.sparse_mm_space import SparseMmV from mmgroup.tests.groups.mgroup_n import MGroupN #print(\"module mmgroup.tests.spaces.spaces is deprecated!!\")", "SparseMmV from mmgroup.tests.groups.mgroup_n import MGroupN #print(\"module mmgroup.tests.spaces.spaces is deprecated!!\") spaces_dict = {} g", "TestSpace: def __init__(self, p): self.p = p self.space = MMV(p) self.ref_space = SparseMmV(p)", "MGroupN #print(\"module mmgroup.tests.spaces.spaces is deprecated!!\") spaces_dict = {} g = MM0Group() ref_g =", "from mmgroup.structures.mm0_group import MM0Group from mmgroup.tests.spaces.sparse_mm_space import SparseMmSpace from mmgroup.tests.spaces.sparse_mm_space import SparseMmV from", "= MM0Group() ref_g = MGroupN() class TestSpace: def __init__(self, p): self.p = p", "g self.ref_group = ref_g def __call__(self, *args): return self.space(*args) def MMTestSpace(p): global spaces_dict", "characteristics from mmgroup.structures.mm0_group import MM0Group from mmgroup.tests.spaces.sparse_mm_space import SparseMmSpace from mmgroup.tests.spaces.sparse_mm_space import SparseMmV", "MM0Group from mmgroup.tests.spaces.sparse_mm_space import SparseMmSpace from mmgroup.tests.spaces.sparse_mm_space import SparseMmV from mmgroup.tests.groups.mgroup_n import MGroupN", "from mmgroup.tests.groups.mgroup_n import MGroupN #print(\"module mmgroup.tests.spaces.spaces is deprecated!!\") spaces_dict = {} g =", "= MGroupN() class TestSpace: def __init__(self, p): self.p = p self.space = MMV(p)", "mmgroup.tests.spaces.sparse_mm_space import SparseMmSpace from mmgroup.tests.spaces.sparse_mm_space import SparseMmV from mmgroup.tests.groups.mgroup_n import MGroupN #print(\"module mmgroup.tests.spaces.spaces" ]
[ "print_function import feedparser import subprocess import time import re def parse_archive(archive, updates=True, link_to=\"pdf\"):", "unescape it result = re.sub(r\"\\\\([\\\\$^_*<>])\", r\"\\1\", result) if error: result = result +", "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER", "ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN", "(C) 2014 <NAME> # Permission is hereby granted, free of charge, to any", "files (the \"Software\"), # to deal in the Software without restriction, including without", "import re def parse_archive(archive, updates=True, link_to=\"pdf\"): out = u\"\" d = feedparser.parse(\"http://export.arxiv.org/rss/{}\".format(archive)) day", "deal in the Software without restriction, including without limitation # the rights to", "and entry.title.endswith(\"UPDATED)\"): break out = out + u\"<h2>{}</h2>\\n\".format(entry.title) out = out + u\"<p>Authors:", "# in all copies or substantial portions of the Software. # THE SOFTWARE", "{} {}</h1>\\n\".format(a, day, update_string) for entry in d.entries: if (not updates) and entry.title.endswith(\"UPDATED)\"):", "= time.strftime(\"%F\", d.feed.updated_parsed) if updates: update_string=u\"with replacements\" else: update_string=u\"\" out=out + u\"<h1>{} arXiv", "+ u\"<h2>{}</h2>\\n\".format(entry.title) out = out + u\"<p>Authors: {}</p>\\n\".format(entry.author) out = out + u\"<a", "to the abstracts rather than the PDFs\", action=\"store_true\", default=False) args = parser.parse_args() if", "fetch the latest arXiv listings and transform them to markdown # Copyright (C)", "update_string=u\"\" out=out + u\"<h1>{} arXiv of {} {}</h1>\\n\".format(a, day, update_string) for entry in", "to the following conditions: # The above copyright notice and this permission notice", "-f html -t markdown --atx-headers\".split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE) (result,error) = pandoc.communicate(input=out) pandoc.stdout.close() # Pandoc", "to do so, subject to the following conditions: # The above copyright notice", "argparse parser = argparse.ArgumentParser(description=\"fetch the latest arXiv listings and transform them to markdown\")", "pandoc = subprocess.Popen(\"pandoc -R -f html -t markdown --atx-headers\".split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE) (result,error) =", "OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE # OR", "the abstracts rather than the PDFs\", action=\"store_true\", default=False) args = parser.parse_args() if args.link_to_abstract:", "Software is furnished to do so, subject to the following conditions: # The", "obtaining # a copy of this software and associated documentation files (the \"Software\"),", "and this permission notice shall be included # in all copies or substantial", "entry.summary+u\"\\n\" pandoc = subprocess.Popen(\"pandoc -R -f html -t markdown --atx-headers\".split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE) (result,error)", "for entry in d.entries: if (not updates) and entry.title.endswith(\"UPDATED)\"): break out = out", "link_to=\"pdf\"): out = u\"\" d = feedparser.parse(\"http://export.arxiv.org/rss/{}\".format(archive)) day = time.strftime(\"%F\", d.feed.updated_parsed) if updates:", "latest arXiv listings and transform them to markdown # Copyright (C) 2014 <NAME>", "WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN", "d.feed.updated_parsed) if updates: update_string=u\"with replacements\" else: update_string=u\"\" out=out + u\"<h1>{} arXiv of {}", "subject to the following conditions: # The above copyright notice and this permission", "NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE", "= result + u\"*ERROR: Pandoc conversion failed with error {}*\\n\".format(error) return result if", "any person obtaining # a copy of this software and associated documentation files", "listings and transform them to markdown\") parser.add_argument(\"archive\", help=\"an archive to fetch\", nargs=\"+\") parser.add_argument(\"-r\",", "failed with error {}*\\n\".format(error) return result if __name__ == \"__main__\": import argparse parser", "#!/usr/bin/python # arxiv2md.py: fetch the latest arXiv listings and transform them to markdown", "href='{}'>Link</a>\\n\".format(entry.link.replace(\"abs\",link_to,1)) out = out + entry.summary+u\"\\n\" pandoc = subprocess.Popen(\"pandoc -R -f html -t", "Permission is hereby granted, free of charge, to any person obtaining # a", "pandoc.stdout.close() # Pandoc conversion to markdown escapes LaTeX, we need to unescape it", "TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE", "parse_archive(archive, updates=True, link_to=\"pdf\"): out = u\"\" d = feedparser.parse(\"http://export.arxiv.org/rss/{}\".format(archive)) day = time.strftime(\"%F\", d.feed.updated_parsed)", "= argparse.ArgumentParser(description=\"fetch the latest arXiv listings and transform them to markdown\") parser.add_argument(\"archive\", help=\"an", "ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE # OR THE", "out + u\"<p>Authors: {}</p>\\n\".format(entry.author) out = out + u\"<a href='{}'>Link</a>\\n\".format(entry.link.replace(\"abs\",link_to,1)) out = out", "= out + entry.summary+u\"\\n\" pandoc = subprocess.Popen(\"pandoc -R -f html -t markdown --atx-headers\".split(),", "FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE # OR THE USE", "OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY,", "distribute, sublicense, # and/or sell copies of the Software, and to permit persons", "out = out + u\"<h2>{}</h2>\\n\".format(entry.title) out = out + u\"<p>Authors: {}</p>\\n\".format(entry.author) out =", "if updates: update_string=u\"with replacements\" else: update_string=u\"\" out=out + u\"<h1>{} arXiv of {} {}</h1>\\n\".format(a,", "THE SOFTWARE. from __future__ import print_function import feedparser import subprocess import time import", "this software and associated documentation files (the \"Software\"), # to deal in the", "day = time.strftime(\"%F\", d.feed.updated_parsed) if updates: update_string=u\"with replacements\" else: update_string=u\"\" out=out + u\"<h1>{}", "u\"<p>Authors: {}</p>\\n\".format(entry.author) out = out + u\"<a href='{}'>Link</a>\\n\".format(entry.link.replace(\"abs\",link_to,1)) out = out + entry.summary+u\"\\n\"", "parser.add_argument(\"-r\", \"--replacements\", help=\"also fetch the replacements\", action=\"store_true\", default=False) parser.add_argument(\"-a\", \"--link-to-abstract\", help=\"make the links", "= subprocess.Popen(\"pandoc -R -f html -t markdown --atx-headers\".split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE) (result,error) = pandoc.communicate(input=out)", "Software without restriction, including without limitation # the rights to use, copy, modify,", "result if __name__ == \"__main__\": import argparse parser = argparse.ArgumentParser(description=\"fetch the latest arXiv", "# and/or sell copies of the Software, and to permit persons to whom", "KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES #", "IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY", "copies of the Software, and to permit persons to whom the # Software", "result + u\"*ERROR: Pandoc conversion failed with error {}*\\n\".format(error) return result if __name__", "archive to fetch\", nargs=\"+\") parser.add_argument(\"-r\", \"--replacements\", help=\"also fetch the replacements\", action=\"store_true\", default=False) parser.add_argument(\"-a\",", "PDFs\", action=\"store_true\", default=False) args = parser.parse_args() if args.link_to_abstract: link_to = \"abs\" else: link_to", "CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, #", "# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE", "conversion to markdown escapes LaTeX, we need to unescape it result = re.sub(r\"\\\\([\\\\$^_*<>])\",", "# Software is furnished to do so, subject to the following conditions: #", "updates=True, link_to=\"pdf\"): out = u\"\" d = feedparser.parse(\"http://export.arxiv.org/rss/{}\".format(archive)) day = time.strftime(\"%F\", d.feed.updated_parsed) if", "== \"__main__\": import argparse parser = argparse.ArgumentParser(description=\"fetch the latest arXiv listings and transform", "SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR", "WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED", "action=\"store_true\", default=False) args = parser.parse_args() if args.link_to_abstract: link_to = \"abs\" else: link_to =", "help=\"also fetch the replacements\", action=\"store_true\", default=False) parser.add_argument(\"-a\", \"--link-to-abstract\", help=\"make the links point to", "SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES", "PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING", "pandoc.communicate(input=out) pandoc.stdout.close() # Pandoc conversion to markdown escapes LaTeX, we need to unescape", "IS\", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT", "CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH", "# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT", "PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS", "PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT", "OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION", "+ u\"<h1>{} arXiv of {} {}</h1>\\n\".format(a, day, update_string) for entry in d.entries: if", "out + u\"<a href='{}'>Link</a>\\n\".format(entry.link.replace(\"abs\",link_to,1)) out = out + entry.summary+u\"\\n\" pandoc = subprocess.Popen(\"pandoc -R", "software and associated documentation files (the \"Software\"), # to deal in the Software", "persons to whom the # Software is furnished to do so, subject to", "update_string) for entry in d.entries: if (not updates) and entry.title.endswith(\"UPDATED)\"): break out =", "(result,error) = pandoc.communicate(input=out) pandoc.stdout.close() # Pandoc conversion to markdown escapes LaTeX, we need", "Pandoc conversion failed with error {}*\\n\".format(error) return result if __name__ == \"__main__\": import", "conversion failed with error {}*\\n\".format(error) return result if __name__ == \"__main__\": import argparse", "person obtaining # a copy of this software and associated documentation files (the", "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM,", "default=False) parser.add_argument(\"-a\", \"--link-to-abstract\", help=\"make the links point to the abstracts rather than the", "time.strftime(\"%F\", d.feed.updated_parsed) if updates: update_string=u\"with replacements\" else: update_string=u\"\" out=out + u\"<h1>{} arXiv of", "use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the", "HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN", "to markdown # Copyright (C) 2014 <NAME> # Permission is hereby granted, free", "from __future__ import print_function import feedparser import subprocess import time import re def", "EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY,", "parser.parse_args() if args.link_to_abstract: link_to = \"abs\" else: link_to = \"pdf\" for a in", "conditions: # The above copyright notice and this permission notice shall be included", "IN CONNECTION WITH THE SOFTWARE # OR THE USE OR OTHER DEALINGS IN", "OR IN CONNECTION WITH THE SOFTWARE # OR THE USE OR OTHER DEALINGS", "rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies", "OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. from __future__ import print_function", "merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to", "to unescape it result = re.sub(r\"\\\\([\\\\$^_*<>])\", r\"\\1\", result) if error: result = result", "to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of", "LaTeX, we need to unescape it result = re.sub(r\"\\\\([\\\\$^_*<>])\", r\"\\1\", result) if error:", "def parse_archive(archive, updates=True, link_to=\"pdf\"): out = u\"\" d = feedparser.parse(\"http://export.arxiv.org/rss/{}\".format(archive)) day = time.strftime(\"%F\",", "action=\"store_true\", default=False) parser.add_argument(\"-a\", \"--link-to-abstract\", help=\"make the links point to the abstracts rather than", "FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF", "publish, distribute, sublicense, # and/or sell copies of the Software, and to permit", "# Copyright (C) 2014 <NAME> # Permission is hereby granted, free of charge,", "updates: update_string=u\"with replacements\" else: update_string=u\"\" out=out + u\"<h1>{} arXiv of {} {}</h1>\\n\".format(a, day,", "sell copies of the Software, and to permit persons to whom the #", "out = out + u\"<p>Authors: {}</p>\\n\".format(entry.author) out = out + u\"<a href='{}'>Link</a>\\n\".format(entry.link.replace(\"abs\",link_to,1)) out", "feedparser.parse(\"http://export.arxiv.org/rss/{}\".format(archive)) day = time.strftime(\"%F\", d.feed.updated_parsed) if updates: update_string=u\"with replacements\" else: update_string=u\"\" out=out +", "EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, #", "out = out + u\"<a href='{}'>Link</a>\\n\".format(entry.link.replace(\"abs\",link_to,1)) out = out + entry.summary+u\"\\n\" pandoc =", "if error: result = result + u\"*ERROR: Pandoc conversion failed with error {}*\\n\".format(error)", "hereby granted, free of charge, to any person obtaining # a copy of", "= feedparser.parse(\"http://export.arxiv.org/rss/{}\".format(archive)) day = time.strftime(\"%F\", d.feed.updated_parsed) if updates: update_string=u\"with replacements\" else: update_string=u\"\" out=out", "limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, #", "<gh_stars>1-10 #!/usr/bin/python # arxiv2md.py: fetch the latest arXiv listings and transform them to", "granted, free of charge, to any person obtaining # a copy of this", "\"AS IS\", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT", "updates) and entry.title.endswith(\"UPDATED)\"): break out = out + u\"<h2>{}</h2>\\n\".format(entry.title) out = out +", "Software. # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,", "the # Software is furnished to do so, subject to the following conditions:", "to markdown escapes LaTeX, we need to unescape it result = re.sub(r\"\\\\([\\\\$^_*<>])\", r\"\\1\",", "documentation files (the \"Software\"), # to deal in the Software without restriction, including", "else: update_string=u\"\" out=out + u\"<h1>{} arXiv of {} {}</h1>\\n\".format(a, day, update_string) for entry", "BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN", "parser.add_argument(\"archive\", help=\"an archive to fetch\", nargs=\"+\") parser.add_argument(\"-r\", \"--replacements\", help=\"also fetch the replacements\", action=\"store_true\",", "# arxiv2md.py: fetch the latest arXiv listings and transform them to markdown #", "OTHER DEALINGS IN THE SOFTWARE. from __future__ import print_function import feedparser import subprocess", "arXiv listings and transform them to markdown\") parser.add_argument(\"archive\", help=\"an archive to fetch\", nargs=\"+\")", "to fetch\", nargs=\"+\") parser.add_argument(\"-r\", \"--replacements\", help=\"also fetch the replacements\", action=\"store_true\", default=False) parser.add_argument(\"-a\", \"--link-to-abstract\",", "arXiv listings and transform them to markdown # Copyright (C) 2014 <NAME> #", "if args.link_to_abstract: link_to = \"abs\" else: link_to = \"pdf\" for a in args.archive:", "argparse.ArgumentParser(description=\"fetch the latest arXiv listings and transform them to markdown\") parser.add_argument(\"archive\", help=\"an archive", "them to markdown\") parser.add_argument(\"archive\", help=\"an archive to fetch\", nargs=\"+\") parser.add_argument(\"-r\", \"--replacements\", help=\"also fetch", "markdown # Copyright (C) 2014 <NAME> # Permission is hereby granted, free of", "parser.add_argument(\"-a\", \"--link-to-abstract\", help=\"make the links point to the abstracts rather than the PDFs\",", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR", "= out + u\"<p>Authors: {}</p>\\n\".format(entry.author) out = out + u\"<a href='{}'>Link</a>\\n\".format(entry.link.replace(\"abs\",link_to,1)) out =", "listings and transform them to markdown # Copyright (C) 2014 <NAME> # Permission", "ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,", "is furnished to do so, subject to the following conditions: # The above", "arxiv2md.py: fetch the latest arXiv listings and transform them to markdown # Copyright", "in d.entries: if (not updates) and entry.title.endswith(\"UPDATED)\"): break out = out + u\"<h2>{}</h2>\\n\".format(entry.title)", "restriction, including without limitation # the rights to use, copy, modify, merge, publish,", "-t markdown --atx-headers\".split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE) (result,error) = pandoc.communicate(input=out) pandoc.stdout.close() # Pandoc conversion to", "import argparse parser = argparse.ArgumentParser(description=\"fetch the latest arXiv listings and transform them to", "OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING", "+ entry.summary+u\"\\n\" pandoc = subprocess.Popen(\"pandoc -R -f html -t markdown --atx-headers\".split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE)", "sublicense, # and/or sell copies of the Software, and to permit persons to", "the replacements\", action=\"store_true\", default=False) parser.add_argument(\"-a\", \"--link-to-abstract\", help=\"make the links point to the abstracts", "Pandoc conversion to markdown escapes LaTeX, we need to unescape it result =", "the Software, and to permit persons to whom the # Software is furnished", "return result if __name__ == \"__main__\": import argparse parser = argparse.ArgumentParser(description=\"fetch the latest", "the Software. # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY", "be included # in all copies or substantial portions of the Software. #", "AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE", "result = re.sub(r\"\\\\([\\\\$^_*<>])\", r\"\\1\", result) if error: result = result + u\"*ERROR: Pandoc", "to whom the # Software is furnished to do so, subject to the", "arXiv of {} {}</h1>\\n\".format(a, day, update_string) for entry in d.entries: if (not updates)", "need to unescape it result = re.sub(r\"\\\\([\\\\$^_*<>])\", r\"\\1\", result) if error: result =", "+ u\"<a href='{}'>Link</a>\\n\".format(entry.link.replace(\"abs\",link_to,1)) out = out + entry.summary+u\"\\n\" pandoc = subprocess.Popen(\"pandoc -R -f", "FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS", "# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF", "OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE", "out + u\"<h2>{}</h2>\\n\".format(entry.title) out = out + u\"<p>Authors: {}</p>\\n\".format(entry.author) out = out +", "re.sub(r\"\\\\([\\\\$^_*<>])\", r\"\\1\", result) if error: result = result + u\"*ERROR: Pandoc conversion failed", "error {}*\\n\".format(error) return result if __name__ == \"__main__\": import argparse parser = argparse.ArgumentParser(description=\"fetch", "# the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or", "permission notice shall be included # in all copies or substantial portions of", "2014 <NAME> # Permission is hereby granted, free of charge, to any person", "it result = re.sub(r\"\\\\([\\\\$^_*<>])\", r\"\\1\", result) if error: result = result + u\"*ERROR:", "MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL", "replacements\" else: update_string=u\"\" out=out + u\"<h1>{} arXiv of {} {}</h1>\\n\".format(a, day, update_string) for", "modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and", "this permission notice shall be included # in all copies or substantial portions", "the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell", "help=\"make the links point to the abstracts rather than the PDFs\", action=\"store_true\", default=False)", "we need to unescape it result = re.sub(r\"\\\\([\\\\$^_*<>])\", r\"\\1\", result) if error: result", "ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES", "OF OR IN CONNECTION WITH THE SOFTWARE # OR THE USE OR OTHER", "THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. #", "notice and this permission notice shall be included # in all copies or", "NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE", "escapes LaTeX, we need to unescape it result = re.sub(r\"\\\\([\\\\$^_*<>])\", r\"\\1\", result) if", "= out + u\"<a href='{}'>Link</a>\\n\".format(entry.link.replace(\"abs\",link_to,1)) out = out + entry.summary+u\"\\n\" pandoc = subprocess.Popen(\"pandoc", "replacements\", action=\"store_true\", default=False) parser.add_argument(\"-a\", \"--link-to-abstract\", help=\"make the links point to the abstracts rather", "following conditions: # The above copyright notice and this permission notice shall be", "CONNECTION WITH THE SOFTWARE # OR THE USE OR OTHER DEALINGS IN THE", "u\"<h1>{} arXiv of {} {}</h1>\\n\".format(a, day, update_string) for entry in d.entries: if (not", "the links point to the abstracts rather than the PDFs\", action=\"store_true\", default=False) args", "SOFTWARE. from __future__ import print_function import feedparser import subprocess import time import re", "__name__ == \"__main__\": import argparse parser = argparse.ArgumentParser(description=\"fetch the latest arXiv listings and", "including without limitation # the rights to use, copy, modify, merge, publish, distribute,", "\"Software\"), # to deal in the Software without restriction, including without limitation #", "u\"\" d = feedparser.parse(\"http://export.arxiv.org/rss/{}\".format(archive)) day = time.strftime(\"%F\", d.feed.updated_parsed) if updates: update_string=u\"with replacements\" else:", "# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. from __future__ import", "without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense,", "the following conditions: # The above copyright notice and this permission notice shall", "= out + u\"<h2>{}</h2>\\n\".format(entry.title) out = out + u\"<p>Authors: {}</p>\\n\".format(entry.author) out = out", "the latest arXiv listings and transform them to markdown\") parser.add_argument(\"archive\", help=\"an archive to", "out=out + u\"<h1>{} arXiv of {} {}</h1>\\n\".format(a, day, update_string) for entry in d.entries:", "# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, #", "WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO", "in the Software without restriction, including without limitation # the rights to use,", "u\"<h2>{}</h2>\\n\".format(entry.title) out = out + u\"<p>Authors: {}</p>\\n\".format(entry.author) out = out + u\"<a href='{}'>Link</a>\\n\".format(entry.link.replace(\"abs\",link_to,1))", "result = result + u\"*ERROR: Pandoc conversion failed with error {}*\\n\".format(error) return result", "included # in all copies or substantial portions of the Software. # THE", "IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF", "html -t markdown --atx-headers\".split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE) (result,error) = pandoc.communicate(input=out) pandoc.stdout.close() # Pandoc conversion", "entry in d.entries: if (not updates) and entry.title.endswith(\"UPDATED)\"): break out = out +", "transform them to markdown\") parser.add_argument(\"archive\", help=\"an archive to fetch\", nargs=\"+\") parser.add_argument(\"-r\", \"--replacements\", help=\"also", "than the PDFs\", action=\"store_true\", default=False) args = parser.parse_args() if args.link_to_abstract: link_to = \"abs\"", "copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software,", "the PDFs\", action=\"store_true\", default=False) args = parser.parse_args() if args.link_to_abstract: link_to = \"abs\" else:", "in all copies or substantial portions of the Software. # THE SOFTWARE IS", "fetch\", nargs=\"+\") parser.add_argument(\"-r\", \"--replacements\", help=\"also fetch the replacements\", action=\"store_true\", default=False) parser.add_argument(\"-a\", \"--link-to-abstract\", help=\"make", "charge, to any person obtaining # a copy of this software and associated", "{}</p>\\n\".format(entry.author) out = out + u\"<a href='{}'>Link</a>\\n\".format(entry.link.replace(\"abs\",link_to,1)) out = out + entry.summary+u\"\\n\" pandoc", "The above copyright notice and this permission notice shall be included # in", "copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED \"AS", "day, update_string) for entry in d.entries: if (not updates) and entry.title.endswith(\"UPDATED)\"): break out", "shall be included # in all copies or substantial portions of the Software.", "# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR", "d.entries: if (not updates) and entry.title.endswith(\"UPDATED)\"): break out = out + u\"<h2>{}</h2>\\n\".format(entry.title) out", "COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER", "a copy of this software and associated documentation files (the \"Software\"), # to", "(not updates) and entry.title.endswith(\"UPDATED)\"): break out = out + u\"<h2>{}</h2>\\n\".format(entry.title) out = out", "fetch the replacements\", action=\"store_true\", default=False) parser.add_argument(\"-a\", \"--link-to-abstract\", help=\"make the links point to the", "subprocess.Popen(\"pandoc -R -f html -t markdown --atx-headers\".split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE) (result,error) = pandoc.communicate(input=out) pandoc.stdout.close()", "-R -f html -t markdown --atx-headers\".split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE) (result,error) = pandoc.communicate(input=out) pandoc.stdout.close() #", "import print_function import feedparser import subprocess import time import re def parse_archive(archive, updates=True,", "break out = out + u\"<h2>{}</h2>\\n\".format(entry.title) out = out + u\"<p>Authors: {}</p>\\n\".format(entry.author) out", "links point to the abstracts rather than the PDFs\", action=\"store_true\", default=False) args =", "permit persons to whom the # Software is furnished to do so, subject", "out = u\"\" d = feedparser.parse(\"http://export.arxiv.org/rss/{}\".format(archive)) day = time.strftime(\"%F\", d.feed.updated_parsed) if updates: update_string=u\"with", "of charge, to any person obtaining # a copy of this software and", "import feedparser import subprocess import time import re def parse_archive(archive, updates=True, link_to=\"pdf\"): out", "the Software without restriction, including without limitation # the rights to use, copy,", "entry.title.endswith(\"UPDATED)\"): break out = out + u\"<h2>{}</h2>\\n\".format(entry.title) out = out + u\"<p>Authors: {}</p>\\n\".format(entry.author)", "whom the # Software is furnished to do so, subject to the following", "markdown --atx-headers\".split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE) (result,error) = pandoc.communicate(input=out) pandoc.stdout.close() # Pandoc conversion to markdown", "Copyright (C) 2014 <NAME> # Permission is hereby granted, free of charge, to", "and transform them to markdown\") parser.add_argument(\"archive\", help=\"an archive to fetch\", nargs=\"+\") parser.add_argument(\"-r\", \"--replacements\",", "# Permission is hereby granted, free of charge, to any person obtaining #", "OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS", "--atx-headers\".split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE) (result,error) = pandoc.communicate(input=out) pandoc.stdout.close() # Pandoc conversion to markdown escapes", "OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE,", "THE SOFTWARE # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. from", "stdin=subprocess.PIPE, stdout=subprocess.PIPE) (result,error) = pandoc.communicate(input=out) pandoc.stdout.close() # Pandoc conversion to markdown escapes LaTeX,", "u\"*ERROR: Pandoc conversion failed with error {}*\\n\".format(error) return result if __name__ == \"__main__\":", "and/or sell copies of the Software, and to permit persons to whom the", "default=False) args = parser.parse_args() if args.link_to_abstract: link_to = \"abs\" else: link_to = \"pdf\"", "INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A", "+ u\"<p>Authors: {}</p>\\n\".format(entry.author) out = out + u\"<a href='{}'>Link</a>\\n\".format(entry.link.replace(\"abs\",link_to,1)) out = out +", "THE USE OR OTHER DEALINGS IN THE SOFTWARE. from __future__ import print_function import", "of this software and associated documentation files (the \"Software\"), # to deal in", "WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT", "rather than the PDFs\", action=\"store_true\", default=False) args = parser.parse_args() if args.link_to_abstract: link_to =", "of the Software. # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF", "LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION", "# Pandoc conversion to markdown escapes LaTeX, we need to unescape it result", "import subprocess import time import re def parse_archive(archive, updates=True, link_to=\"pdf\"): out = u\"\"", "re def parse_archive(archive, updates=True, link_to=\"pdf\"): out = u\"\" d = feedparser.parse(\"http://export.arxiv.org/rss/{}\".format(archive)) day =", "if (not updates) and entry.title.endswith(\"UPDATED)\"): break out = out + u\"<h2>{}</h2>\\n\".format(entry.title) out =", "copy of this software and associated documentation files (the \"Software\"), # to deal", "{}</h1>\\n\".format(a, day, update_string) for entry in d.entries: if (not updates) and entry.title.endswith(\"UPDATED)\"): break", "A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR", "THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR", "out + entry.summary+u\"\\n\" pandoc = subprocess.Popen(\"pandoc -R -f html -t markdown --atx-headers\".split(), stdin=subprocess.PIPE,", "markdown\") parser.add_argument(\"archive\", help=\"an archive to fetch\", nargs=\"+\") parser.add_argument(\"-r\", \"--replacements\", help=\"also fetch the replacements\",", "+ u\"*ERROR: Pandoc conversion failed with error {}*\\n\".format(error) return result if __name__ ==", "notice shall be included # in all copies or substantial portions of the", "furnished to do so, subject to the following conditions: # The above copyright", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, # EXPRESS", "OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT", "= parser.parse_args() if args.link_to_abstract: link_to = \"abs\" else: link_to = \"pdf\" for a", "substantial portions of the Software. # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT", "portions of the Software. # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY", "out = out + entry.summary+u\"\\n\" pandoc = subprocess.Popen(\"pandoc -R -f html -t markdown", "the latest arXiv listings and transform them to markdown # Copyright (C) 2014", "and to permit persons to whom the # Software is furnished to do", "or substantial portions of the Software. # THE SOFTWARE IS PROVIDED \"AS IS\",", "TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.", "nargs=\"+\") parser.add_argument(\"-r\", \"--replacements\", help=\"also fetch the replacements\", action=\"store_true\", default=False) parser.add_argument(\"-a\", \"--link-to-abstract\", help=\"make the", "stdout=subprocess.PIPE) (result,error) = pandoc.communicate(input=out) pandoc.stdout.close() # Pandoc conversion to markdown escapes LaTeX, we", "parser = argparse.ArgumentParser(description=\"fetch the latest arXiv listings and transform them to markdown\") parser.add_argument(\"archive\",", "OUT OF OR IN CONNECTION WITH THE SOFTWARE # OR THE USE OR", "error: result = result + u\"*ERROR: Pandoc conversion failed with error {}*\\n\".format(error) return", "and transform them to markdown # Copyright (C) 2014 <NAME> # Permission is", "args = parser.parse_args() if args.link_to_abstract: link_to = \"abs\" else: link_to = \"pdf\" for", "Software, and to permit persons to whom the # Software is furnished to", "__future__ import print_function import feedparser import subprocess import time import re def parse_archive(archive,", "associated documentation files (the \"Software\"), # to deal in the Software without restriction,", "transform them to markdown # Copyright (C) 2014 <NAME> # Permission is hereby", "and associated documentation files (the \"Software\"), # to deal in the Software without", "of the Software, and to permit persons to whom the # Software is", "args.link_to_abstract: link_to = \"abs\" else: link_to = \"pdf\" for a in args.archive: print(parse_archive(a,args.replacements,link_to))", "USE OR OTHER DEALINGS IN THE SOFTWARE. from __future__ import print_function import feedparser", "SOFTWARE # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. from __future__", "<NAME> # Permission is hereby granted, free of charge, to any person obtaining", "= pandoc.communicate(input=out) pandoc.stdout.close() # Pandoc conversion to markdown escapes LaTeX, we need to", "\"--replacements\", help=\"also fetch the replacements\", action=\"store_true\", default=False) parser.add_argument(\"-a\", \"--link-to-abstract\", help=\"make the links point", "feedparser import subprocess import time import re def parse_archive(archive, updates=True, link_to=\"pdf\"): out =", "# The above copyright notice and this permission notice shall be included #", "# a copy of this software and associated documentation files (the \"Software\"), #", "subprocess import time import re def parse_archive(archive, updates=True, link_to=\"pdf\"): out = u\"\" d", "to any person obtaining # a copy of this software and associated documentation", "import time import re def parse_archive(archive, updates=True, link_to=\"pdf\"): out = u\"\" d =", "is hereby granted, free of charge, to any person obtaining # a copy", "NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,", "to markdown\") parser.add_argument(\"archive\", help=\"an archive to fetch\", nargs=\"+\") parser.add_argument(\"-r\", \"--replacements\", help=\"also fetch the", "{}*\\n\".format(error) return result if __name__ == \"__main__\": import argparse parser = argparse.ArgumentParser(description=\"fetch the", "# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO", "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE", "without restriction, including without limitation # the rights to use, copy, modify, merge,", "OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE #", "\"--link-to-abstract\", help=\"make the links point to the abstracts rather than the PDFs\", action=\"store_true\",", "free of charge, to any person obtaining # a copy of this software", "them to markdown # Copyright (C) 2014 <NAME> # Permission is hereby granted,", "so, subject to the following conditions: # The above copyright notice and this", "# to deal in the Software without restriction, including without limitation # the", "IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED,", "\"__main__\": import argparse parser = argparse.ArgumentParser(description=\"fetch the latest arXiv listings and transform them", "(the \"Software\"), # to deal in the Software without restriction, including without limitation", "IN THE SOFTWARE. from __future__ import print_function import feedparser import subprocess import time", "if __name__ == \"__main__\": import argparse parser = argparse.ArgumentParser(description=\"fetch the latest arXiv listings", "DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR", "to permit persons to whom the # Software is furnished to do so,", "= u\"\" d = feedparser.parse(\"http://export.arxiv.org/rss/{}\".format(archive)) day = time.strftime(\"%F\", d.feed.updated_parsed) if updates: update_string=u\"with replacements\"", "BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR", "to deal in the Software without restriction, including without limitation # the rights", "DEALINGS IN THE SOFTWARE. from __future__ import print_function import feedparser import subprocess import", "copyright notice and this permission notice shall be included # in all copies", "OR OTHER DEALINGS IN THE SOFTWARE. from __future__ import print_function import feedparser import", "help=\"an archive to fetch\", nargs=\"+\") parser.add_argument(\"-r\", \"--replacements\", help=\"also fetch the replacements\", action=\"store_true\", default=False)", "u\"<a href='{}'>Link</a>\\n\".format(entry.link.replace(\"abs\",link_to,1)) out = out + entry.summary+u\"\\n\" pandoc = subprocess.Popen(\"pandoc -R -f html", "markdown escapes LaTeX, we need to unescape it result = re.sub(r\"\\\\([\\\\$^_*<>])\", r\"\\1\", result)", "update_string=u\"with replacements\" else: update_string=u\"\" out=out + u\"<h1>{} arXiv of {} {}</h1>\\n\".format(a, day, update_string)", "= re.sub(r\"\\\\([\\\\$^_*<>])\", r\"\\1\", result) if error: result = result + u\"*ERROR: Pandoc conversion", "LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND", "latest arXiv listings and transform them to markdown\") parser.add_argument(\"archive\", help=\"an archive to fetch\",", "time import re def parse_archive(archive, updates=True, link_to=\"pdf\"): out = u\"\" d = feedparser.parse(\"http://export.arxiv.org/rss/{}\".format(archive))", "abstracts rather than the PDFs\", action=\"store_true\", default=False) args = parser.parse_args() if args.link_to_abstract: link_to", "of {} {}</h1>\\n\".format(a, day, update_string) for entry in d.entries: if (not updates) and", "r\"\\1\", result) if error: result = result + u\"*ERROR: Pandoc conversion failed with", "d = feedparser.parse(\"http://export.arxiv.org/rss/{}\".format(archive)) day = time.strftime(\"%F\", d.feed.updated_parsed) if updates: update_string=u\"with replacements\" else: update_string=u\"\"", "with error {}*\\n\".format(error) return result if __name__ == \"__main__\": import argparse parser =", "WITH THE SOFTWARE # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", "point to the abstracts rather than the PDFs\", action=\"store_true\", default=False) args = parser.parse_args()", "all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED", "result) if error: result = result + u\"*ERROR: Pandoc conversion failed with error", "AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR", "above copyright notice and this permission notice shall be included # in all", "do so, subject to the following conditions: # The above copyright notice and" ]
[ "of height 10\"\"\" __author__ = '<NAME>' import Autodesk.Revit.DB as DB doc = __revit__.ActiveUIDocument.Document", "Autodesk.Revit.DB as DB doc = __revit__.ActiveUIDocument.Document uidoc = __revit__.ActiveUIDocument height_param_id = DB.ElementId(DB.BuiltInParameter.WALL_USER_HEIGHT_PARAM) height_param_prov", "DB.ElementId(DB.BuiltInParameter.WALL_USER_HEIGHT_PARAM) height_param_prov = DB.ParameterValueProvider(height_param_id) param_equality = DB.FilterNumericEquals() heigh_value_rule = DB.FilterDoubleRule(height_param_prov, param_equality, 10.0, 1E-6)", "param_equality, 10.0, 1E-6) param_filter = DB.ElementParameterFilter(heigh_value_rule) walls = DB.FilteredElementCollector(doc) \\ .WherePasses(param_filter) \\ .ToElementIds()", "Collection of Data: Collects all the walls of height 10\"\"\" __author__ = '<NAME>'", "__revit__.ActiveUIDocument height_param_id = DB.ElementId(DB.BuiltInParameter.WALL_USER_HEIGHT_PARAM) height_param_prov = DB.ParameterValueProvider(height_param_id) param_equality = DB.FilterNumericEquals() heigh_value_rule = DB.FilterDoubleRule(height_param_prov,", "param_equality = DB.FilterNumericEquals() heigh_value_rule = DB.FilterDoubleRule(height_param_prov, param_equality, 10.0, 1E-6) param_filter = DB.ElementParameterFilter(heigh_value_rule) walls", "as DB doc = __revit__.ActiveUIDocument.Document uidoc = __revit__.ActiveUIDocument height_param_id = DB.ElementId(DB.BuiltInParameter.WALL_USER_HEIGHT_PARAM) height_param_prov =", "uidoc = __revit__.ActiveUIDocument height_param_id = DB.ElementId(DB.BuiltInParameter.WALL_USER_HEIGHT_PARAM) height_param_prov = DB.ParameterValueProvider(height_param_id) param_equality = DB.FilterNumericEquals() heigh_value_rule", "all the walls of height 10\"\"\" __author__ = '<NAME>' import Autodesk.Revit.DB as DB", "walls of height 10\"\"\" __author__ = '<NAME>' import Autodesk.Revit.DB as DB doc =", "= DB.ElementId(DB.BuiltInParameter.WALL_USER_HEIGHT_PARAM) height_param_prov = DB.ParameterValueProvider(height_param_id) param_equality = DB.FilterNumericEquals() heigh_value_rule = DB.FilterDoubleRule(height_param_prov, param_equality, 10.0,", "= __revit__.ActiveUIDocument.Document uidoc = __revit__.ActiveUIDocument height_param_id = DB.ElementId(DB.BuiltInParameter.WALL_USER_HEIGHT_PARAM) height_param_prov = DB.ParameterValueProvider(height_param_id) param_equality =", "height_param_prov = DB.ParameterValueProvider(height_param_id) param_equality = DB.FilterNumericEquals() heigh_value_rule = DB.FilterDoubleRule(height_param_prov, param_equality, 10.0, 1E-6) param_filter", "doc = __revit__.ActiveUIDocument.Document uidoc = __revit__.ActiveUIDocument height_param_id = DB.ElementId(DB.BuiltInParameter.WALL_USER_HEIGHT_PARAM) height_param_prov = DB.ParameterValueProvider(height_param_id) param_equality", "= __revit__.ActiveUIDocument height_param_id = DB.ElementId(DB.BuiltInParameter.WALL_USER_HEIGHT_PARAM) height_param_prov = DB.ParameterValueProvider(height_param_id) param_equality = DB.FilterNumericEquals() heigh_value_rule =", "= DB.ParameterValueProvider(height_param_id) param_equality = DB.FilterNumericEquals() heigh_value_rule = DB.FilterDoubleRule(height_param_prov, param_equality, 10.0, 1E-6) param_filter =", "heigh_value_rule = DB.FilterDoubleRule(height_param_prov, param_equality, 10.0, 1E-6) param_filter = DB.ElementParameterFilter(heigh_value_rule) walls = DB.FilteredElementCollector(doc) \\", "\"\"\"Advanced Collection of Data: Collects all the walls of height 10\"\"\" __author__ =", "10\"\"\" __author__ = '<NAME>' import Autodesk.Revit.DB as DB doc = __revit__.ActiveUIDocument.Document uidoc =", "= DB.FilterNumericEquals() heigh_value_rule = DB.FilterDoubleRule(height_param_prov, param_equality, 10.0, 1E-6) param_filter = DB.ElementParameterFilter(heigh_value_rule) walls =", "DB.FilterDoubleRule(height_param_prov, param_equality, 10.0, 1E-6) param_filter = DB.ElementParameterFilter(heigh_value_rule) walls = DB.FilteredElementCollector(doc) \\ .WherePasses(param_filter) \\", "DB.FilterNumericEquals() heigh_value_rule = DB.FilterDoubleRule(height_param_prov, param_equality, 10.0, 1E-6) param_filter = DB.ElementParameterFilter(heigh_value_rule) walls = DB.FilteredElementCollector(doc)", "Collects all the walls of height 10\"\"\" __author__ = '<NAME>' import Autodesk.Revit.DB as", "DB doc = __revit__.ActiveUIDocument.Document uidoc = __revit__.ActiveUIDocument height_param_id = DB.ElementId(DB.BuiltInParameter.WALL_USER_HEIGHT_PARAM) height_param_prov = DB.ParameterValueProvider(height_param_id)", "height_param_id = DB.ElementId(DB.BuiltInParameter.WALL_USER_HEIGHT_PARAM) height_param_prov = DB.ParameterValueProvider(height_param_id) param_equality = DB.FilterNumericEquals() heigh_value_rule = DB.FilterDoubleRule(height_param_prov, param_equality,", "= DB.FilterDoubleRule(height_param_prov, param_equality, 10.0, 1E-6) param_filter = DB.ElementParameterFilter(heigh_value_rule) walls = DB.FilteredElementCollector(doc) \\ .WherePasses(param_filter)", "import Autodesk.Revit.DB as DB doc = __revit__.ActiveUIDocument.Document uidoc = __revit__.ActiveUIDocument height_param_id = DB.ElementId(DB.BuiltInParameter.WALL_USER_HEIGHT_PARAM)", "'<NAME>' import Autodesk.Revit.DB as DB doc = __revit__.ActiveUIDocument.Document uidoc = __revit__.ActiveUIDocument height_param_id =", "= '<NAME>' import Autodesk.Revit.DB as DB doc = __revit__.ActiveUIDocument.Document uidoc = __revit__.ActiveUIDocument height_param_id", "height 10\"\"\" __author__ = '<NAME>' import Autodesk.Revit.DB as DB doc = __revit__.ActiveUIDocument.Document uidoc", "__revit__.ActiveUIDocument.Document uidoc = __revit__.ActiveUIDocument height_param_id = DB.ElementId(DB.BuiltInParameter.WALL_USER_HEIGHT_PARAM) height_param_prov = DB.ParameterValueProvider(height_param_id) param_equality = DB.FilterNumericEquals()", "DB.ParameterValueProvider(height_param_id) param_equality = DB.FilterNumericEquals() heigh_value_rule = DB.FilterDoubleRule(height_param_prov, param_equality, 10.0, 1E-6) param_filter = DB.ElementParameterFilter(heigh_value_rule)", "Data: Collects all the walls of height 10\"\"\" __author__ = '<NAME>' import Autodesk.Revit.DB", "of Data: Collects all the walls of height 10\"\"\" __author__ = '<NAME>' import", "__author__ = '<NAME>' import Autodesk.Revit.DB as DB doc = __revit__.ActiveUIDocument.Document uidoc = __revit__.ActiveUIDocument", "10.0, 1E-6) param_filter = DB.ElementParameterFilter(heigh_value_rule) walls = DB.FilteredElementCollector(doc) \\ .WherePasses(param_filter) \\ .ToElementIds() uidoc.Selection.SetElementIds(walls)", "the walls of height 10\"\"\" __author__ = '<NAME>' import Autodesk.Revit.DB as DB doc" ]
[ "while(count<limit): flag = 0 for i in range(3,count,2): if (count%i==0): flag = 1", "1 while(count<limit): flag = 0 for i in range(3,count,2): if (count%i==0): flag =", "count = 1 while(count<limit): flag = 0 for i in range(3,count,2): if (count%i==0):", "= 1 while(count<limit): flag = 0 for i in range(3,count,2): if (count%i==0): flag", "0 for i in range(3,count,2): if (count%i==0): flag = 1 if (flag==0): print(count)", "flag = 0 for i in range(3,count,2): if (count%i==0): flag = 1 if", "= 0 for i in range(3,count,2): if (count%i==0): flag = 1 if (flag==0):", "i in range(3,count,2): if (count%i==0): flag = 1 if (flag==0): print(count) count+=2 prime(100)", "for i in range(3,count,2): if (count%i==0): flag = 1 if (flag==0): print(count) count+=2", "prime(limit): count = 1 while(count<limit): flag = 0 for i in range(3,count,2): if", "def prime(limit): count = 1 while(count<limit): flag = 0 for i in range(3,count,2):" ]
[ "Database(self.configuration['db']) self.storage = raw_storage(self.configuration['storage']) self.process_synchronizer = ProcessSynchronizer( self.configuration['synchronization']) def execute_with(self, message): video_chunk =", "big_fiubrother_core.synchronization import ProcessSynchronizer from os import path import logging class StoreVideoChunk(QueueTask): def __init__(self,", "def init(self): self.db = Database(self.configuration['db']) self.storage = raw_storage(self.configuration['storage']) self.process_synchronizer = ProcessSynchronizer( self.configuration['synchronization']) def", "input_queue, output_queue): super().__init__(input_queue) self.output_queue = output_queue self.configuration = configuration def init(self): self.db =", "output_queue): super().__init__(input_queue) self.output_queue = output_queue self.configuration = configuration def init(self): self.db = Database(self.configuration['db'])", "output_queue self.configuration = configuration def init(self): self.db = Database(self.configuration['db']) self.storage = raw_storage(self.configuration['storage']) self.process_synchronizer", "VideoChunk(camera_id=message.camera_id, timestamp=message.timestamp) self.db.add(video_chunk) logging.info(f\"{video_chunk.id} created in DB. Sampling starting!\") self.process_synchronizer.register_video_task(str(video_chunk.id)) filepath = path.join('tmp',", "= configuration def init(self): self.db = Database(self.configuration['db']) self.storage = raw_storage(self.configuration['storage']) self.process_synchronizer = ProcessSynchronizer(", "in DB. Sampling starting!\") self.process_synchronizer.register_video_task(str(video_chunk.id)) filepath = path.join('tmp', '{}.h264'.format(video_chunk.id)) with open(filepath, 'wb') as", "Sampling starting!\") self.process_synchronizer.register_video_task(str(video_chunk.id)) filepath = path.join('tmp', '{}.h264'.format(video_chunk.id)) with open(filepath, 'wb') as file: file.write(message.payload)", "file.write(message.payload) self.storage.store_file(str(video_chunk.id), filepath) self.output_queue.put({ 'video_chunk_id': video_chunk.id, 'path': filepath }) def close(self): self.db.close() self.process_synchronizer.close()", "raw_storage(self.configuration['storage']) self.process_synchronizer = ProcessSynchronizer( self.configuration['synchronization']) def execute_with(self, message): video_chunk = VideoChunk(camera_id=message.camera_id, timestamp=message.timestamp) self.db.add(video_chunk)", "= VideoChunk(camera_id=message.camera_id, timestamp=message.timestamp) self.db.add(video_chunk) logging.info(f\"{video_chunk.id} created in DB. Sampling starting!\") self.process_synchronizer.register_video_task(str(video_chunk.id)) filepath =", "VideoChunk from big_fiubrother_core.storage import raw_storage from big_fiubrother_core.synchronization import ProcessSynchronizer from os import path", "= ProcessSynchronizer( self.configuration['synchronization']) def execute_with(self, message): video_chunk = VideoChunk(camera_id=message.camera_id, timestamp=message.timestamp) self.db.add(video_chunk) logging.info(f\"{video_chunk.id} created", "from big_fiubrother_core.synchronization import ProcessSynchronizer from os import path import logging class StoreVideoChunk(QueueTask): def", "def execute_with(self, message): video_chunk = VideoChunk(camera_id=message.camera_id, timestamp=message.timestamp) self.db.add(video_chunk) logging.info(f\"{video_chunk.id} created in DB. Sampling", "= Database(self.configuration['db']) self.storage = raw_storage(self.configuration['storage']) self.process_synchronizer = ProcessSynchronizer( self.configuration['synchronization']) def execute_with(self, message): video_chunk", "import logging class StoreVideoChunk(QueueTask): def __init__(self, configuration, input_queue, output_queue): super().__init__(input_queue) self.output_queue = output_queue", "StoreVideoChunk(QueueTask): def __init__(self, configuration, input_queue, output_queue): super().__init__(input_queue) self.output_queue = output_queue self.configuration = configuration", "= raw_storage(self.configuration['storage']) self.process_synchronizer = ProcessSynchronizer( self.configuration['synchronization']) def execute_with(self, message): video_chunk = VideoChunk(camera_id=message.camera_id, timestamp=message.timestamp)", "filepath = path.join('tmp', '{}.h264'.format(video_chunk.id)) with open(filepath, 'wb') as file: file.write(message.payload) self.storage.store_file(str(video_chunk.id), filepath) self.output_queue.put({", "import path import logging class StoreVideoChunk(QueueTask): def __init__(self, configuration, input_queue, output_queue): super().__init__(input_queue) self.output_queue", "import QueueTask from big_fiubrother_core.db import Database, VideoChunk from big_fiubrother_core.storage import raw_storage from big_fiubrother_core.synchronization", "self.db = Database(self.configuration['db']) self.storage = raw_storage(self.configuration['storage']) self.process_synchronizer = ProcessSynchronizer( self.configuration['synchronization']) def execute_with(self, message):", "from big_fiubrother_core.db import Database, VideoChunk from big_fiubrother_core.storage import raw_storage from big_fiubrother_core.synchronization import ProcessSynchronizer", "video_chunk = VideoChunk(camera_id=message.camera_id, timestamp=message.timestamp) self.db.add(video_chunk) logging.info(f\"{video_chunk.id} created in DB. Sampling starting!\") self.process_synchronizer.register_video_task(str(video_chunk.id)) filepath", "with open(filepath, 'wb') as file: file.write(message.payload) self.storage.store_file(str(video_chunk.id), filepath) self.output_queue.put({ 'video_chunk_id': video_chunk.id, 'path': filepath", "path import logging class StoreVideoChunk(QueueTask): def __init__(self, configuration, input_queue, output_queue): super().__init__(input_queue) self.output_queue =", "def __init__(self, configuration, input_queue, output_queue): super().__init__(input_queue) self.output_queue = output_queue self.configuration = configuration def", "import raw_storage from big_fiubrother_core.synchronization import ProcessSynchronizer from os import path import logging class", "= path.join('tmp', '{}.h264'.format(video_chunk.id)) with open(filepath, 'wb') as file: file.write(message.payload) self.storage.store_file(str(video_chunk.id), filepath) self.output_queue.put({ 'video_chunk_id':", "execute_with(self, message): video_chunk = VideoChunk(camera_id=message.camera_id, timestamp=message.timestamp) self.db.add(video_chunk) logging.info(f\"{video_chunk.id} created in DB. Sampling starting!\")", "path.join('tmp', '{}.h264'.format(video_chunk.id)) with open(filepath, 'wb') as file: file.write(message.payload) self.storage.store_file(str(video_chunk.id), filepath) self.output_queue.put({ 'video_chunk_id': video_chunk.id,", "= output_queue self.configuration = configuration def init(self): self.db = Database(self.configuration['db']) self.storage = raw_storage(self.configuration['storage'])", "timestamp=message.timestamp) self.db.add(video_chunk) logging.info(f\"{video_chunk.id} created in DB. Sampling starting!\") self.process_synchronizer.register_video_task(str(video_chunk.id)) filepath = path.join('tmp', '{}.h264'.format(video_chunk.id))", "as file: file.write(message.payload) self.storage.store_file(str(video_chunk.id), filepath) self.output_queue.put({ 'video_chunk_id': video_chunk.id, 'path': filepath }) def close(self):", "big_fiubrother_core import QueueTask from big_fiubrother_core.db import Database, VideoChunk from big_fiubrother_core.storage import raw_storage from", "class StoreVideoChunk(QueueTask): def __init__(self, configuration, input_queue, output_queue): super().__init__(input_queue) self.output_queue = output_queue self.configuration =", "init(self): self.db = Database(self.configuration['db']) self.storage = raw_storage(self.configuration['storage']) self.process_synchronizer = ProcessSynchronizer( self.configuration['synchronization']) def execute_with(self,", "self.output_queue = output_queue self.configuration = configuration def init(self): self.db = Database(self.configuration['db']) self.storage =", "Database, VideoChunk from big_fiubrother_core.storage import raw_storage from big_fiubrother_core.synchronization import ProcessSynchronizer from os import", "from big_fiubrother_core.storage import raw_storage from big_fiubrother_core.synchronization import ProcessSynchronizer from os import path import", "logging.info(f\"{video_chunk.id} created in DB. Sampling starting!\") self.process_synchronizer.register_video_task(str(video_chunk.id)) filepath = path.join('tmp', '{}.h264'.format(video_chunk.id)) with open(filepath,", "import Database, VideoChunk from big_fiubrother_core.storage import raw_storage from big_fiubrother_core.synchronization import ProcessSynchronizer from os", "configuration def init(self): self.db = Database(self.configuration['db']) self.storage = raw_storage(self.configuration['storage']) self.process_synchronizer = ProcessSynchronizer( self.configuration['synchronization'])", "starting!\") self.process_synchronizer.register_video_task(str(video_chunk.id)) filepath = path.join('tmp', '{}.h264'.format(video_chunk.id)) with open(filepath, 'wb') as file: file.write(message.payload) self.storage.store_file(str(video_chunk.id),", "self.configuration['synchronization']) def execute_with(self, message): video_chunk = VideoChunk(camera_id=message.camera_id, timestamp=message.timestamp) self.db.add(video_chunk) logging.info(f\"{video_chunk.id} created in DB.", "os import path import logging class StoreVideoChunk(QueueTask): def __init__(self, configuration, input_queue, output_queue): super().__init__(input_queue)", "from os import path import logging class StoreVideoChunk(QueueTask): def __init__(self, configuration, input_queue, output_queue):", "ProcessSynchronizer( self.configuration['synchronization']) def execute_with(self, message): video_chunk = VideoChunk(camera_id=message.camera_id, timestamp=message.timestamp) self.db.add(video_chunk) logging.info(f\"{video_chunk.id} created in", "self.process_synchronizer = ProcessSynchronizer( self.configuration['synchronization']) def execute_with(self, message): video_chunk = VideoChunk(camera_id=message.camera_id, timestamp=message.timestamp) self.db.add(video_chunk) logging.info(f\"{video_chunk.id}", "message): video_chunk = VideoChunk(camera_id=message.camera_id, timestamp=message.timestamp) self.db.add(video_chunk) logging.info(f\"{video_chunk.id} created in DB. Sampling starting!\") self.process_synchronizer.register_video_task(str(video_chunk.id))", "DB. Sampling starting!\") self.process_synchronizer.register_video_task(str(video_chunk.id)) filepath = path.join('tmp', '{}.h264'.format(video_chunk.id)) with open(filepath, 'wb') as file:", "raw_storage from big_fiubrother_core.synchronization import ProcessSynchronizer from os import path import logging class StoreVideoChunk(QueueTask):", "self.db.add(video_chunk) logging.info(f\"{video_chunk.id} created in DB. Sampling starting!\") self.process_synchronizer.register_video_task(str(video_chunk.id)) filepath = path.join('tmp', '{}.h264'.format(video_chunk.id)) with", "open(filepath, 'wb') as file: file.write(message.payload) self.storage.store_file(str(video_chunk.id), filepath) self.output_queue.put({ 'video_chunk_id': video_chunk.id, 'path': filepath })", "ProcessSynchronizer from os import path import logging class StoreVideoChunk(QueueTask): def __init__(self, configuration, input_queue,", "from big_fiubrother_core import QueueTask from big_fiubrother_core.db import Database, VideoChunk from big_fiubrother_core.storage import raw_storage", "'{}.h264'.format(video_chunk.id)) with open(filepath, 'wb') as file: file.write(message.payload) self.storage.store_file(str(video_chunk.id), filepath) self.output_queue.put({ 'video_chunk_id': video_chunk.id, 'path':", "big_fiubrother_core.storage import raw_storage from big_fiubrother_core.synchronization import ProcessSynchronizer from os import path import logging", "logging class StoreVideoChunk(QueueTask): def __init__(self, configuration, input_queue, output_queue): super().__init__(input_queue) self.output_queue = output_queue self.configuration", "super().__init__(input_queue) self.output_queue = output_queue self.configuration = configuration def init(self): self.db = Database(self.configuration['db']) self.storage", "__init__(self, configuration, input_queue, output_queue): super().__init__(input_queue) self.output_queue = output_queue self.configuration = configuration def init(self):", "self.storage = raw_storage(self.configuration['storage']) self.process_synchronizer = ProcessSynchronizer( self.configuration['synchronization']) def execute_with(self, message): video_chunk = VideoChunk(camera_id=message.camera_id,", "configuration, input_queue, output_queue): super().__init__(input_queue) self.output_queue = output_queue self.configuration = configuration def init(self): self.db", "file: file.write(message.payload) self.storage.store_file(str(video_chunk.id), filepath) self.output_queue.put({ 'video_chunk_id': video_chunk.id, 'path': filepath }) def close(self): self.db.close()", "self.process_synchronizer.register_video_task(str(video_chunk.id)) filepath = path.join('tmp', '{}.h264'.format(video_chunk.id)) with open(filepath, 'wb') as file: file.write(message.payload) self.storage.store_file(str(video_chunk.id), filepath)", "created in DB. Sampling starting!\") self.process_synchronizer.register_video_task(str(video_chunk.id)) filepath = path.join('tmp', '{}.h264'.format(video_chunk.id)) with open(filepath, 'wb')", "'wb') as file: file.write(message.payload) self.storage.store_file(str(video_chunk.id), filepath) self.output_queue.put({ 'video_chunk_id': video_chunk.id, 'path': filepath }) def", "big_fiubrother_core.db import Database, VideoChunk from big_fiubrother_core.storage import raw_storage from big_fiubrother_core.synchronization import ProcessSynchronizer from", "import ProcessSynchronizer from os import path import logging class StoreVideoChunk(QueueTask): def __init__(self, configuration,", "self.configuration = configuration def init(self): self.db = Database(self.configuration['db']) self.storage = raw_storage(self.configuration['storage']) self.process_synchronizer =", "QueueTask from big_fiubrother_core.db import Database, VideoChunk from big_fiubrother_core.storage import raw_storage from big_fiubrother_core.synchronization import" ]
[ "output in _core_generator(solid_def, context, input_dict): if not isinstance(output, AssetMaterialization): if output.output_name in output_values:", "resource \"{resource_key}\", but no resource ' \"with that key was found on the", "Any] ) -> tuple: output_values = {} output_names = {output_def.name for output_def in", "_core_generator(solid_def, context, input_dict): if not isinstance(output, AssetMaterialization): if output.output_name in output_values: raise DagsterInvariantViolationError(", "output.value else: context.record_materialization(output) # Check to make sure all non-optional outputs were yielded.", "parameter was defined \" \"for the solid.\" ) input_dict = { input_def.name: input_val", "= mapped_config_evr.value.get(\"config\", {}) return ( context if context else DirectSolidExecutionContext(solid_config=config, resources_dict=None, instance=None) )", "in solid_def.output_defs]) def _core_generator( solid_def: \"SolidDefinition\", context: \"DirectSolidExecutionContext\", input_dict: Dict[str, Any] ) ->", "resource_key not in resources_dict: raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" requires resource \"{resource_key}\", but no", "else None, \"solid_config\" ) config_evr = validate_config(solid_def.config_field.config_type, solid_config) if not config_evr.success: raise DagsterInvalidConfigError(", "parameter, but no context parameter was defined \" \"for the solid.\" ) input_dict", "solid_def.config_field: solid_config = check.opt_dict_param( context.solid_config if context else None, \"solid_config\" ) config_evr =", "mapped_config_evr.errors, solid_config ) config = mapped_config_evr.value.get(\"config\", {}) return ( context if context else", "for solid '{solid_def.name}'. This may be because \" \"an argument was provided for", "output defs return tuple([output_values[output_def.name] for output_def in solid_def.output_defs]) def _core_generator( solid_def: \"SolidDefinition\", context:", "returned an output \"{output.output_name}\" that does ' f\"not exist. The available outputs are", "\"Error in config for solid \", config_evr.errors, solid_config ) mapped_config_evr = solid_def.apply_config_mapping({\"config\": solid_config})", "context, input_dict) if len(outputs) == 1: return outputs[0] return outputs def _check_invocation_requirements( solid_def:", "): compute_iterator = solid_def.compute_fn(context, input_dict) if inspect.isasyncgen(compute_iterator): compute_iterator = gen_from_async_gen(compute_iterator) yield from compute_iterator", "solid_def.config_schema.as_field().is_required: raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" has required config schema, but no context was", "\" \"for the solid.\" ) input_dict = { input_def.name: input_val for input_val, input_def", "1: return outputs[0] return outputs def _check_invocation_requirements( solid_def: \"SolidDefinition\", context: Optional[\"DirectSolidExecutionContext\"] ) ->", "else DirectSolidExecutionContext(solid_config=config, resources_dict=None, instance=None) ) def _resolve_inputs(solid_def, args, kwargs): input_defs = solid_def.input_defs #", "None and solid_def.required_resource_keys: resources_dict = cast( # type: ignore[attr-defined] \"DirectSolidExecutionContext\", context, ).resources._asdict() for", "DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" returned an output \"{output.output_name}\" that does ' f\"not exist. The", "raise DagsterInvalidInvocationError( f\"Too many input arguments were provided for solid '{solid_def.name}'. This may", "occurred while invoking solid \"{solid_def.name}\":', ): compute_iterator = solid_def.compute_fn(context, input_dict) if inspect.isasyncgen(compute_iterator): compute_iterator", "enpty DirectSolidExecutionContext \"\"\" from dagster.core.execution.context.invocation import DirectSolidExecutionContext from dagster.config.validate import validate_config # Check", "required config schema, but no context was provided. ' \"Use the `build_solid_context` function", "\"{solid_def.name}\" requires resource \"{resource_key}\", but no resource ' \"with that key was found", "input_defs[len(args) :]: if not input_def.has_default_value and input_def.name not in kwargs: raise DagsterInvalidInvocationError( f'No", "Dict[str, Any] ) -> tuple: output_values = {} output_names = {output_def.name for output_def", "\"{solid_def.name}\":', ): compute_iterator = solid_def.compute_fn(context, input_dict) if inspect.isasyncgen(compute_iterator): compute_iterator = gen_from_async_gen(compute_iterator) yield from", "no resource ' \"with that key was found on the context.\" ) #", "Check config requirements if not context and solid_def.config_schema.as_field().is_required: raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" has", "_resolve_inputs(solid_def, args, kwargs) outputs = _execute_and_retrieve_outputs(solid_def, context, input_dict) if len(outputs) == 1: return", "else: context.record_materialization(output) # Check to make sure all non-optional outputs were yielded. for", "\", config_evr.errors, solid_config ) mapped_config_evr = solid_def.apply_config_mapping({\"config\": solid_config}) if not mapped_config_evr.success: raise DagsterInvalidConfigError(", "< len(args) + len(kwargs): raise DagsterInvalidInvocationError( f\"Too many input arguments were provided for", "solid_def.required_resource_keys: resources_dict = cast( # type: ignore[attr-defined] \"DirectSolidExecutionContext\", context, ).resources._asdict() for resource_key in", "solid_def: \"SolidDefinition\", context: \"DirectSolidExecutionContext\", input_dict: Dict[str, Any] ) -> tuple: output_values = {}", "solid_invocation_result( solid_def: \"SolidDefinition\", context: Optional[\"DirectSolidExecutionContext\"], *args, **kwargs ) -> Any: context = _check_invocation_requirements(solid_def,", "DirectSolidExecutionContext \"\"\" from dagster.core.execution.context.invocation import DirectSolidExecutionContext from dagster.config.validate import validate_config # Check resource", "construct a context with the required \" \"resources.\" ) if context is not", "a context with config.\" ) config = None if solid_def.config_field: solid_config = check.opt_dict_param(", "raise DagsterInvalidConfigError( \"Error in config for solid \", config_evr.errors, solid_config ) mapped_config_evr =", "{}) return ( context if context else DirectSolidExecutionContext(solid_config=config, resources_dict=None, instance=None) ) def _resolve_inputs(solid_def,", "if not isinstance(output, AssetMaterialization): if output.output_name in output_values: raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" returned", "required \" \"resources.\" ) if context is not None and solid_def.required_resource_keys: resources_dict =", "`build_solid_context` function to create a context with config.\" ) config = None if", "invoking solid \"{solid_def.name}\":', ): compute_iterator = solid_def.compute_fn(context, input_dict) if inspect.isasyncgen(compute_iterator): compute_iterator = gen_from_async_gen(compute_iterator)", "config = mapped_config_evr.value.get(\"config\", {}) return ( context if context else DirectSolidExecutionContext(solid_config=config, resources_dict=None, instance=None)", "\" \"resources.\" ) if context is not None and solid_def.required_resource_keys: resources_dict = cast(", "solid_def.input_defs # Fail early if too many inputs were provided. if len(input_defs) <", "solid \"{solid_def.name}\":', ): compute_iterator = solid_def.compute_fn(context, input_dict) if inspect.isasyncgen(compute_iterator): compute_iterator = gen_from_async_gen(compute_iterator) yield", "_check_invocation_requirements(solid_def, context) input_dict = _resolve_inputs(solid_def, args, kwargs) outputs = _execute_and_retrieve_outputs(solid_def, context, input_dict) if", "is None: raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" has required resources, but no context was", "not in output_values and output_def.is_required: raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" did not return an", "from dagster.core.execution.context.invocation import DirectSolidExecutionContext from dagster.config.validate import validate_config # Check resource requirements if", "\"Use the `build_solid_context` function to create a context with config.\" ) config =", "*args, **kwargs ) -> Any: context = _check_invocation_requirements(solid_def, context) input_dict = _resolve_inputs(solid_def, args,", "\"\"\" from dagster.core.execution.context.invocation import DirectSolidExecutionContext from dagster.config.validate import validate_config # Check resource requirements", "config schema, but no context was provided. ' \"Use the `build_solid_context` function to", ") else: output_values[output.output_name] = output.value else: context.record_materialization(output) # Check to make sure all", "import DirectSolidExecutionContext from dagster.config.validate import validate_config # Check resource requirements if solid_def.required_resource_keys and", "many input arguments were provided for solid '{solid_def.name}'. This may be because \"", "all non-optional outputs were yielded. for output_def in solid_def.output_defs: if output_def.name not in", "The available outputs are {list(output_names)}\" ) else: output_values[output.output_name] = output.value else: context.record_materialization(output) #", "Optional, cast from dagster import check from dagster.core.definitions.events import AssetMaterialization, RetryRequested from dagster.core.errors", "tuple: output_values = {} output_names = {output_def.name for output_def in solid_def.output_defs} for output", "from dagster.core.definitions.events import AssetMaterialization, RetryRequested from dagster.core.errors import ( DagsterInvalidConfigError, DagsterInvalidInvocationError, DagsterInvariantViolationError, DagsterSolidInvocationError,", "f'Solid \"{solid_def.name}\" has required config schema, but no context was provided. ' \"Use", "Check to make sure all non-optional outputs were yielded. for output_def in solid_def.output_defs:", "did not return an output for non-optional ' f'output \"{output_def.name}\"' ) # Explicitly", "raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" requires resource \"{resource_key}\", but no resource ' \"with that", ") # Check config requirements if not context and solid_def.config_schema.as_field().is_required: raise DagsterInvalidInvocationError( f'Solid", "context was provided. ' \"Use the `build_solid_context` function to create a context with", "len(outputs) == 1: return outputs[0] return outputs def _check_invocation_requirements( solid_def: \"SolidDefinition\", context: Optional[\"DirectSolidExecutionContext\"]", "-> Generator[Any, None, None]: from dagster.core.execution.plan.compute import gen_from_async_gen with user_code_error_boundary( DagsterSolidInvocationError, control_flow_exceptions=[RetryRequested], msg_fn=lambda:", "mapped_config_evr.success: raise DagsterInvalidConfigError( \"Error in config for solid \", mapped_config_evr.errors, solid_config ) config", "kwargs): input_defs = solid_def.input_defs # Fail early if too many inputs were provided.", "preserve the ordering of output defs return tuple([output_values[output_def.name] for output_def in solid_def.output_defs]) def", "# Check resource requirements if solid_def.required_resource_keys and context is None: raise DagsterInvalidInvocationError( f'Solid", "if not mapped_config_evr.success: raise DagsterInvalidConfigError( \"Error in config for solid \", mapped_config_evr.errors, solid_config", "' f'output \"{output_def.name}\"' ) # Explicitly preserve the ordering of output defs return", "= {} output_names = {output_def.name for output_def in solid_def.output_defs} for output in _core_generator(solid_def,", "f'Solid \"{solid_def.name}\" did not return an output for non-optional ' f'output \"{output_def.name}\"' )", "has required config schema, but no context was provided. ' \"Use the `build_solid_context`", "from dagster import check from dagster.core.definitions.events import AssetMaterialization, RetryRequested from dagster.core.errors import (", "= check.opt_dict_param( context.solid_config if context else None, \"solid_config\" ) config_evr = validate_config(solid_def.config_field.config_type, solid_config)", "-> tuple: output_values = {} output_names = {output_def.name for output_def in solid_def.output_defs} for", "len(args) + len(kwargs): raise DagsterInvalidInvocationError( f\"Too many input arguments were provided for solid", "schema, but no context was provided. ' \"Use the `build_solid_context` function to create", "yielded. for output_def in solid_def.output_defs: if output_def.name not in output_values and output_def.is_required: raise", "raise DagsterInvalidConfigError( \"Error in config for solid \", mapped_config_evr.errors, solid_config ) config =", "for non-optional ' f'output \"{output_def.name}\"' ) # Explicitly preserve the ordering of output", ").resources._asdict() for resource_key in solid_def.required_resource_keys: if resource_key not in resources_dict: raise DagsterInvalidInvocationError( f'Solid", "TYPE_CHECKING, Any, Dict, Generator, Optional, cast from dagster import check from dagster.core.definitions.events import", "config = None if solid_def.config_field: solid_config = check.opt_dict_param( context.solid_config if context else None,", "def _core_generator( solid_def: \"SolidDefinition\", context: \"DirectSolidExecutionContext\", input_dict: Dict[str, Any] ) -> Generator[Any, None,", ") mapped_config_evr = solid_def.apply_config_mapping({\"config\": solid_config}) if not mapped_config_evr.success: raise DagsterInvalidConfigError( \"Error in config", "if context is not None and solid_def.required_resource_keys: resources_dict = cast( # type: ignore[attr-defined]", "resources, but no context was provided. Use the' \"`build_solid_context` function to construct a", "solid_def.required_resource_keys: if resource_key not in resources_dict: raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" requires resource \"{resource_key}\",", "with user_code_error_boundary( DagsterSolidInvocationError, control_flow_exceptions=[RetryRequested], msg_fn=lambda: f'Error occurred while invoking solid \"{solid_def.name}\":', ): compute_iterator", "This may be because \" \"an argument was provided for the context parameter,", "DagsterInvalidInvocationError( f'No value provided for required input \"{input_def.name}\".' ) input_dict[input_def.name] = ( kwargs[input_def.name]", "input_def.name not in kwargs: raise DagsterInvalidInvocationError( f'No value provided for required input \"{input_def.name}\".'", "+ len(kwargs): raise DagsterInvalidInvocationError( f\"Too many input arguments were provided for solid '{solid_def.name}'.", "arguments were provided for solid '{solid_def.name}'. This may be because \" \"an argument", "context and solid_def.config_schema.as_field().is_required: raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" has required config schema, but no", "provided for solid '{solid_def.name}'. This may be because \" \"an argument was provided", "solid_def.output_defs} for output in _core_generator(solid_def, context, input_dict): if not isinstance(output, AssetMaterialization): if output.output_name", "solid_def.required_resource_keys and context is None: raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" has required resources, but", "context: \"DirectSolidExecutionContext\", input_dict: Dict[str, Any] ) -> tuple: output_values = {} output_names =", "f'Solid \"{solid_def.name}\" has required resources, but no context was provided. Use the' \"`build_solid_context`", "the context parameter, but no context parameter was defined \" \"for the solid.\"", "not isinstance(output, AssetMaterialization): if output.output_name in output_values: raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" returned an", "input_dict: Dict[str, Any] ) -> Generator[Any, None, None]: from dagster.core.execution.plan.compute import gen_from_async_gen with", "type: ignore[attr-defined] \"DirectSolidExecutionContext\", context, ).resources._asdict() for resource_key in solid_def.required_resource_keys: if resource_key not in", "output_names = {output_def.name for output_def in solid_def.output_defs} for output in _core_generator(solid_def, context, input_dict):", "outputs[0] return outputs def _check_invocation_requirements( solid_def: \"SolidDefinition\", context: Optional[\"DirectSolidExecutionContext\"] ) -> \"DirectSolidExecutionContext\": \"\"\"Ensure", "\"an argument was provided for the context parameter, but no context parameter was", "f'Solid \"{solid_def.name}\" returned an output \"{output.output_name}\" that does ' f\"not exist. The available", "context with the required \" \"resources.\" ) if context is not None and", "the solid.\" ) input_dict = { input_def.name: input_val for input_val, input_def in zip(args,", ") config = None if solid_def.config_field: solid_config = check.opt_dict_param( context.solid_config if context else", "for resource_key in solid_def.required_resource_keys: if resource_key not in resources_dict: raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\"", "in kwargs: raise DagsterInvalidInvocationError( f'No value provided for required input \"{input_def.name}\".' ) input_dict[input_def.name]", "in output_values and output_def.is_required: raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" did not return an output", "outputs def _check_invocation_requirements( solid_def: \"SolidDefinition\", context: Optional[\"DirectSolidExecutionContext\"] ) -> \"DirectSolidExecutionContext\": \"\"\"Ensure that provided", "context with config.\" ) config = None if solid_def.config_field: solid_config = check.opt_dict_param( context.solid_config", "{list(output_names)}\" ) else: output_values[output.output_name] = output.value else: context.record_materialization(output) # Check to make sure", "non-optional outputs were yielded. for output_def in solid_def.output_defs: if output_def.name not in output_values", "the required \" \"resources.\" ) if context is not None and solid_def.required_resource_keys: resources_dict", "if output_def.name not in output_values and output_def.is_required: raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" did not", "function to create a context with config.\" ) config = None if solid_def.config_field:", "not None and solid_def.required_resource_keys: resources_dict = cast( # type: ignore[attr-defined] \"DirectSolidExecutionContext\", context, ).resources._asdict()", "no context was provided. Use the' \"`build_solid_context` function to construct a context with", "def _resolve_inputs(solid_def, args, kwargs): input_defs = solid_def.input_defs # Fail early if too many", "from typing import TYPE_CHECKING, Any, Dict, Generator, Optional, cast from dagster import check", "= _resolve_inputs(solid_def, args, kwargs) outputs = _execute_and_retrieve_outputs(solid_def, context, input_dict) if len(outputs) == 1:", "RetryRequested from dagster.core.errors import ( DagsterInvalidConfigError, DagsterInvalidInvocationError, DagsterInvariantViolationError, DagsterSolidInvocationError, user_code_error_boundary, ) if TYPE_CHECKING:", "f'No value provided for required input \"{input_def.name}\".' ) input_dict[input_def.name] = ( kwargs[input_def.name] if", "return outputs[0] return outputs def _check_invocation_requirements( solid_def: \"SolidDefinition\", context: Optional[\"DirectSolidExecutionContext\"] ) -> \"DirectSolidExecutionContext\":", "If no context was provided, then construct an enpty DirectSolidExecutionContext \"\"\" from dagster.core.execution.context.invocation", ") -> tuple: output_values = {} output_names = {output_def.name for output_def in solid_def.output_defs}", "-> \"DirectSolidExecutionContext\": \"\"\"Ensure that provided context fulfills requirements of solid definition. If no", "# Check config requirements if not context and solid_def.config_schema.as_field().is_required: raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\"", "and input_def.name not in kwargs: raise DagsterInvalidInvocationError( f'No value provided for required input", "DagsterInvalidInvocationError( f\"Too many input arguments were provided for solid '{solid_def.name}'. This may be", "context.\" ) # Check config requirements if not context and solid_def.config_schema.as_field().is_required: raise DagsterInvalidInvocationError(", "DagsterInvalidInvocationError, DagsterInvariantViolationError, DagsterSolidInvocationError, user_code_error_boundary, ) if TYPE_CHECKING: from dagster.core.definitions import SolidDefinition from dagster.core.execution.context.invocation", "inputs were provided. if len(input_defs) < len(args) + len(kwargs): raise DagsterInvalidInvocationError( f\"Too many", "a context with the required \" \"resources.\" ) if context is not None", "cast( # type: ignore[attr-defined] \"DirectSolidExecutionContext\", context, ).resources._asdict() for resource_key in solid_def.required_resource_keys: if resource_key", "\"DirectSolidExecutionContext\", input_dict: Dict[str, Any] ) -> Generator[Any, None, None]: from dagster.core.execution.plan.compute import gen_from_async_gen", "DagsterSolidInvocationError, user_code_error_boundary, ) if TYPE_CHECKING: from dagster.core.definitions import SolidDefinition from dagster.core.execution.context.invocation import DirectSolidExecutionContext", ") input_dict[input_def.name] = ( kwargs[input_def.name] if input_def.name in kwargs else input_def.default_value ) return", "\"solid_config\" ) config_evr = validate_config(solid_def.config_field.config_type, solid_config) if not config_evr.success: raise DagsterInvalidConfigError( \"Error in", "-> Any: context = _check_invocation_requirements(solid_def, context) input_dict = _resolve_inputs(solid_def, args, kwargs) outputs =", "output.output_name not in output_names: raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" returned an output \"{output.output_name}\" that", "Dict[str, Any] ) -> Generator[Any, None, None]: from dagster.core.execution.plan.compute import gen_from_async_gen with user_code_error_boundary(", "to construct a context with the required \" \"resources.\" ) if context is", "has required resources, but no context was provided. Use the' \"`build_solid_context` function to", "return input_dict def _execute_and_retrieve_outputs( solid_def: \"SolidDefinition\", context: \"DirectSolidExecutionContext\", input_dict: Dict[str, Any] ) ->", "raise DagsterInvalidInvocationError( f'No value provided for required input \"{input_def.name}\".' ) input_dict[input_def.name] = (", "were provided. if len(input_defs) < len(args) + len(kwargs): raise DagsterInvalidInvocationError( f\"Too many input", "_execute_and_retrieve_outputs( solid_def: \"SolidDefinition\", context: \"DirectSolidExecutionContext\", input_dict: Dict[str, Any] ) -> tuple: output_values =", "output_def in solid_def.output_defs]) def _core_generator( solid_def: \"SolidDefinition\", context: \"DirectSolidExecutionContext\", input_dict: Dict[str, Any] )", "= output.value else: context.record_materialization(output) # Check to make sure all non-optional outputs were", "solid_def: \"SolidDefinition\", context: \"DirectSolidExecutionContext\", input_dict: Dict[str, Any] ) -> Generator[Any, None, None]: from", "input_dict) if len(outputs) == 1: return outputs[0] return outputs def _check_invocation_requirements( solid_def: \"SolidDefinition\",", "solid \", config_evr.errors, solid_config ) mapped_config_evr = solid_def.apply_config_mapping({\"config\": solid_config}) if not mapped_config_evr.success: raise", "= solid_def.input_defs # Fail early if too many inputs were provided. if len(input_defs)", ") config_evr = validate_config(solid_def.config_field.config_type, solid_config) if not config_evr.success: raise DagsterInvalidConfigError( \"Error in config", "output_def in solid_def.output_defs: if output_def.name not in output_values and output_def.is_required: raise DagsterInvariantViolationError( f'Solid", "None]: from dagster.core.execution.plan.compute import gen_from_async_gen with user_code_error_boundary( DagsterSolidInvocationError, control_flow_exceptions=[RetryRequested], msg_fn=lambda: f'Error occurred while", "config for solid \", mapped_config_evr.errors, solid_config ) config = mapped_config_evr.value.get(\"config\", {}) return (", "raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" did not return an output for non-optional ' f'output", "not return an output for non-optional ' f'output \"{output_def.name}\"' ) # Explicitly preserve", "' f\"not exist. The available outputs are {list(output_names)}\" ) else: output_values[output.output_name] = output.value", "Use the' \"`build_solid_context` function to construct a context with the required \" \"resources.\"", "config requirements if not context and solid_def.config_schema.as_field().is_required: raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" has required", "if too many inputs were provided. if len(input_defs) < len(args) + len(kwargs): raise", "output_def in solid_def.output_defs} for output in _core_generator(solid_def, context, input_dict): if not isinstance(output, AssetMaterialization):", "if len(input_defs) < len(args) + len(kwargs): raise DagsterInvalidInvocationError( f\"Too many input arguments were", "solid_def.apply_config_mapping({\"config\": solid_config}) if not mapped_config_evr.success: raise DagsterInvalidConfigError( \"Error in config for solid \",", "many inputs were provided. if len(input_defs) < len(args) + len(kwargs): raise DagsterInvalidInvocationError( f\"Too", "non-optional ' f'output \"{output_def.name}\"' ) # Explicitly preserve the ordering of output defs", "input_def in zip(args, input_defs[: len(args)]) } for input_def in input_defs[len(args) :]: if not", "import TYPE_CHECKING, Any, Dict, Generator, Optional, cast from dagster import check from dagster.core.definitions.events", "from dagster.core.execution.context.invocation import DirectSolidExecutionContext def solid_invocation_result( solid_def: \"SolidDefinition\", context: Optional[\"DirectSolidExecutionContext\"], *args, **kwargs )", "context fulfills requirements of solid definition. If no context was provided, then construct", "resource_key in solid_def.required_resource_keys: if resource_key not in resources_dict: raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" requires", "was provided for the context parameter, but no context parameter was defined \"", "input \"{input_def.name}\".' ) input_dict[input_def.name] = ( kwargs[input_def.name] if input_def.name in kwargs else input_def.default_value", "was provided. ' \"Use the `build_solid_context` function to create a context with config.\"", "in config for solid \", mapped_config_evr.errors, solid_config ) config = mapped_config_evr.value.get(\"config\", {}) return", "create a context with config.\" ) config = None if solid_def.config_field: solid_config =", "solid_config = check.opt_dict_param( context.solid_config if context else None, \"solid_config\" ) config_evr = validate_config(solid_def.config_field.config_type,", "def _check_invocation_requirements( solid_def: \"SolidDefinition\", context: Optional[\"DirectSolidExecutionContext\"] ) -> \"DirectSolidExecutionContext\": \"\"\"Ensure that provided context", "from dagster.core.errors import ( DagsterInvalidConfigError, DagsterInvalidInvocationError, DagsterInvariantViolationError, DagsterSolidInvocationError, user_code_error_boundary, ) if TYPE_CHECKING: from", "input_defs[: len(args)]) } for input_def in input_defs[len(args) :]: if not input_def.has_default_value and input_def.name", "context else DirectSolidExecutionContext(solid_config=config, resources_dict=None, instance=None) ) def _resolve_inputs(solid_def, args, kwargs): input_defs = solid_def.input_defs", "input arguments were provided for solid '{solid_def.name}'. This may be because \" \"an", "' \"Use the `build_solid_context` function to create a context with config.\" ) config", "{ input_def.name: input_val for input_val, input_def in zip(args, input_defs[: len(args)]) } for input_def", "DagsterInvalidConfigError( \"Error in config for solid \", mapped_config_evr.errors, solid_config ) config = mapped_config_evr.value.get(\"config\",", "( DagsterInvalidConfigError, DagsterInvalidInvocationError, DagsterInvariantViolationError, DagsterSolidInvocationError, user_code_error_boundary, ) if TYPE_CHECKING: from dagster.core.definitions import SolidDefinition", "\", mapped_config_evr.errors, solid_config ) config = mapped_config_evr.value.get(\"config\", {}) return ( context if context", "is not None and solid_def.required_resource_keys: resources_dict = cast( # type: ignore[attr-defined] \"DirectSolidExecutionContext\", context,", "solid_config}) if not mapped_config_evr.success: raise DagsterInvalidConfigError( \"Error in config for solid \", mapped_config_evr.errors,", "resources_dict: raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" requires resource \"{resource_key}\", but no resource ' \"with", "ordering of output defs return tuple([output_values[output_def.name] for output_def in solid_def.output_defs]) def _core_generator( solid_def:", "\"SolidDefinition\", context: \"DirectSolidExecutionContext\", input_dict: Dict[str, Any] ) -> tuple: output_values = {} output_names", "in config for solid \", config_evr.errors, solid_config ) mapped_config_evr = solid_def.apply_config_mapping({\"config\": solid_config}) if", "DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" did not return an output for non-optional ' f'output \"{output_def.name}\"'", "dagster.config.validate import validate_config # Check resource requirements if solid_def.required_resource_keys and context is None:", "_resolve_inputs(solid_def, args, kwargs): input_defs = solid_def.input_defs # Fail early if too many inputs", "input_def.name in kwargs else input_def.default_value ) return input_dict def _execute_and_retrieve_outputs( solid_def: \"SolidDefinition\", context:", "Optional[\"DirectSolidExecutionContext\"], *args, **kwargs ) -> Any: context = _check_invocation_requirements(solid_def, context) input_dict = _resolve_inputs(solid_def,", "no context was provided. ' \"Use the `build_solid_context` function to create a context", "and context is None: raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" has required resources, but no", "in resources_dict: raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" requires resource \"{resource_key}\", but no resource '", "= {output_def.name for output_def in solid_def.output_defs} for output in _core_generator(solid_def, context, input_dict): if", "\"{solid_def.name}\" returned an output \"{output.output_name}\" multiple ' \"times\" ) elif output.output_name not in", "function to construct a context with the required \" \"resources.\" ) if context", "raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" has required config schema, but no context was provided.", "elif output.output_name not in output_names: raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" returned an output \"{output.output_name}\"", "solid definition. If no context was provided, then construct an enpty DirectSolidExecutionContext \"\"\"", "validate_config # Check resource requirements if solid_def.required_resource_keys and context is None: raise DagsterInvalidInvocationError(", "config_evr.success: raise DagsterInvalidConfigError( \"Error in config for solid \", config_evr.errors, solid_config ) mapped_config_evr", "input_def.name: input_val for input_val, input_def in zip(args, input_defs[: len(args)]) } for input_def in", "on the context.\" ) # Check config requirements if not context and solid_def.config_schema.as_field().is_required:", "kwargs[input_def.name] if input_def.name in kwargs else input_def.default_value ) return input_dict def _execute_and_retrieve_outputs( solid_def:", "not in output_names: raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" returned an output \"{output.output_name}\" that does", "from dagster.core.definitions import SolidDefinition from dagster.core.execution.context.invocation import DirectSolidExecutionContext def solid_invocation_result( solid_def: \"SolidDefinition\", context:", "context parameter, but no context parameter was defined \" \"for the solid.\" )", "gen_from_async_gen with user_code_error_boundary( DagsterSolidInvocationError, control_flow_exceptions=[RetryRequested], msg_fn=lambda: f'Error occurred while invoking solid \"{solid_def.name}\":', ):", "= _execute_and_retrieve_outputs(solid_def, context, input_dict) if len(outputs) == 1: return outputs[0] return outputs def", "== 1: return outputs[0] return outputs def _check_invocation_requirements( solid_def: \"SolidDefinition\", context: Optional[\"DirectSolidExecutionContext\"] )", "and output_def.is_required: raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" did not return an output for non-optional", "input_val for input_val, input_def in zip(args, input_defs[: len(args)]) } for input_def in input_defs[len(args)", "DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" returned an output \"{output.output_name}\" multiple ' \"times\" ) elif output.output_name", "DagsterInvalidConfigError( \"Error in config for solid \", config_evr.errors, solid_config ) mapped_config_evr = solid_def.apply_config_mapping({\"config\":", "import DirectSolidExecutionContext def solid_invocation_result( solid_def: \"SolidDefinition\", context: Optional[\"DirectSolidExecutionContext\"], *args, **kwargs ) -> Any:", "import inspect from typing import TYPE_CHECKING, Any, Dict, Generator, Optional, cast from dagster", "dagster.core.definitions import SolidDefinition from dagster.core.execution.context.invocation import DirectSolidExecutionContext def solid_invocation_result( solid_def: \"SolidDefinition\", context: Optional[\"DirectSolidExecutionContext\"],", "but no context was provided. ' \"Use the `build_solid_context` function to create a", "DagsterInvalidConfigError, DagsterInvalidInvocationError, DagsterInvariantViolationError, DagsterSolidInvocationError, user_code_error_boundary, ) if TYPE_CHECKING: from dagster.core.definitions import SolidDefinition from", "if not context and solid_def.config_schema.as_field().is_required: raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" has required config schema,", "input_val, input_def in zip(args, input_defs[: len(args)]) } for input_def in input_defs[len(args) :]: if", "else: output_values[output.output_name] = output.value else: context.record_materialization(output) # Check to make sure all non-optional", "kwargs) outputs = _execute_and_retrieve_outputs(solid_def, context, input_dict) if len(outputs) == 1: return outputs[0] return", "DirectSolidExecutionContext def solid_invocation_result( solid_def: \"SolidDefinition\", context: Optional[\"DirectSolidExecutionContext\"], *args, **kwargs ) -> Any: context", "DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" requires resource \"{resource_key}\", but no resource ' \"with that key", "in kwargs else input_def.default_value ) return input_dict def _execute_and_retrieve_outputs( solid_def: \"SolidDefinition\", context: \"DirectSolidExecutionContext\",", "no context parameter was defined \" \"for the solid.\" ) input_dict = {", "for solid \", config_evr.errors, solid_config ) mapped_config_evr = solid_def.apply_config_mapping({\"config\": solid_config}) if not mapped_config_evr.success:", "return ( context if context else DirectSolidExecutionContext(solid_config=config, resources_dict=None, instance=None) ) def _resolve_inputs(solid_def, args,", "config_evr.errors, solid_config ) mapped_config_evr = solid_def.apply_config_mapping({\"config\": solid_config}) if not mapped_config_evr.success: raise DagsterInvalidConfigError( \"Error", "and solid_def.config_schema.as_field().is_required: raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" has required config schema, but no context", "user_code_error_boundary( DagsterSolidInvocationError, control_flow_exceptions=[RetryRequested], msg_fn=lambda: f'Error occurred while invoking solid \"{solid_def.name}\":', ): compute_iterator =", "context = _check_invocation_requirements(solid_def, context) input_dict = _resolve_inputs(solid_def, args, kwargs) outputs = _execute_and_retrieve_outputs(solid_def, context,", "an enpty DirectSolidExecutionContext \"\"\" from dagster.core.execution.context.invocation import DirectSolidExecutionContext from dagster.config.validate import validate_config #", "context: \"DirectSolidExecutionContext\", input_dict: Dict[str, Any] ) -> Generator[Any, None, None]: from dagster.core.execution.plan.compute import", "if not config_evr.success: raise DagsterInvalidConfigError( \"Error in config for solid \", config_evr.errors, solid_config", "provided for required input \"{input_def.name}\".' ) input_dict[input_def.name] = ( kwargs[input_def.name] if input_def.name in", "input_dict): if not isinstance(output, AssetMaterialization): if output.output_name in output_values: raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\"", "AssetMaterialization, RetryRequested from dagster.core.errors import ( DagsterInvalidConfigError, DagsterInvalidInvocationError, DagsterInvariantViolationError, DagsterSolidInvocationError, user_code_error_boundary, ) if", "value provided for required input \"{input_def.name}\".' ) input_dict[input_def.name] = ( kwargs[input_def.name] if input_def.name", "not mapped_config_evr.success: raise DagsterInvalidConfigError( \"Error in config for solid \", mapped_config_evr.errors, solid_config )", "_check_invocation_requirements( solid_def: \"SolidDefinition\", context: Optional[\"DirectSolidExecutionContext\"] ) -> \"DirectSolidExecutionContext\": \"\"\"Ensure that provided context fulfills", "cast from dagster import check from dagster.core.definitions.events import AssetMaterialization, RetryRequested from dagster.core.errors import", "config_evr = validate_config(solid_def.config_field.config_type, solid_config) if not config_evr.success: raise DagsterInvalidConfigError( \"Error in config for", "return an output for non-optional ' f'output \"{output_def.name}\"' ) # Explicitly preserve the", "check.opt_dict_param( context.solid_config if context else None, \"solid_config\" ) config_evr = validate_config(solid_def.config_field.config_type, solid_config) if", "} for input_def in input_defs[len(args) :]: if not input_def.has_default_value and input_def.name not in", "in output_names: raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" returned an output \"{output.output_name}\" that does '", "context, ).resources._asdict() for resource_key in solid_def.required_resource_keys: if resource_key not in resources_dict: raise DagsterInvalidInvocationError(", "input_defs = solid_def.input_defs # Fail early if too many inputs were provided. if", "to create a context with config.\" ) config = None if solid_def.config_field: solid_config", "was defined \" \"for the solid.\" ) input_dict = { input_def.name: input_val for", "kwargs: raise DagsterInvalidInvocationError( f'No value provided for required input \"{input_def.name}\".' ) input_dict[input_def.name] =", "for output_def in solid_def.output_defs]) def _core_generator( solid_def: \"SolidDefinition\", context: \"DirectSolidExecutionContext\", input_dict: Dict[str, Any]", "\"{input_def.name}\".' ) input_dict[input_def.name] = ( kwargs[input_def.name] if input_def.name in kwargs else input_def.default_value )", "\"{output.output_name}\" multiple ' \"times\" ) elif output.output_name not in output_names: raise DagsterInvariantViolationError( f'Solid", "AssetMaterialization): if output.output_name in output_values: raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" returned an output \"{output.output_name}\"", "_execute_and_retrieve_outputs(solid_def, context, input_dict) if len(outputs) == 1: return outputs[0] return outputs def _check_invocation_requirements(", "args, kwargs) outputs = _execute_and_retrieve_outputs(solid_def, context, input_dict) if len(outputs) == 1: return outputs[0]", "in output_values: raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" returned an output \"{output.output_name}\" multiple ' \"times\"", "make sure all non-optional outputs were yielded. for output_def in solid_def.output_defs: if output_def.name", "requirements of solid definition. If no context was provided, then construct an enpty", "raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" returned an output \"{output.output_name}\" multiple ' \"times\" ) elif", "# Check to make sure all non-optional outputs were yielded. for output_def in", "inspect from typing import TYPE_CHECKING, Any, Dict, Generator, Optional, cast from dagster import", "# Fail early if too many inputs were provided. if len(input_defs) < len(args)", "'{solid_def.name}'. This may be because \" \"an argument was provided for the context", "for required input \"{input_def.name}\".' ) input_dict[input_def.name] = ( kwargs[input_def.name] if input_def.name in kwargs", ") -> Any: context = _check_invocation_requirements(solid_def, context) input_dict = _resolve_inputs(solid_def, args, kwargs) outputs", "solid_config ) config = mapped_config_evr.value.get(\"config\", {}) return ( context if context else DirectSolidExecutionContext(solid_config=config,", "for input_val, input_def in zip(args, input_defs[: len(args)]) } for input_def in input_defs[len(args) :]:", "required input \"{input_def.name}\".' ) input_dict[input_def.name] = ( kwargs[input_def.name] if input_def.name in kwargs else", "not context and solid_def.config_schema.as_field().is_required: raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" has required config schema, but", "provided. ' \"Use the `build_solid_context` function to create a context with config.\" )", "input_dict[input_def.name] = ( kwargs[input_def.name] if input_def.name in kwargs else input_def.default_value ) return input_dict", "\"DirectSolidExecutionContext\": \"\"\"Ensure that provided context fulfills requirements of solid definition. If no context", "in solid_def.output_defs} for output in _core_generator(solid_def, context, input_dict): if not isinstance(output, AssetMaterialization): if", "= validate_config(solid_def.config_field.config_type, solid_config) if not config_evr.success: raise DagsterInvalidConfigError( \"Error in config for solid", "the ordering of output defs return tuple([output_values[output_def.name] for output_def in solid_def.output_defs]) def _core_generator(", "kwargs else input_def.default_value ) return input_dict def _execute_and_retrieve_outputs( solid_def: \"SolidDefinition\", context: \"DirectSolidExecutionContext\", input_dict:", "_core_generator( solid_def: \"SolidDefinition\", context: \"DirectSolidExecutionContext\", input_dict: Dict[str, Any] ) -> Generator[Any, None, None]:", "**kwargs ) -> Any: context = _check_invocation_requirements(solid_def, context) input_dict = _resolve_inputs(solid_def, args, kwargs)", "= solid_def.apply_config_mapping({\"config\": solid_config}) if not mapped_config_evr.success: raise DagsterInvalidConfigError( \"Error in config for solid", "but no resource ' \"with that key was found on the context.\" )", "output \"{output.output_name}\" multiple ' \"times\" ) elif output.output_name not in output_names: raise DagsterInvariantViolationError(", "solid_def: \"SolidDefinition\", context: Optional[\"DirectSolidExecutionContext\"] ) -> \"DirectSolidExecutionContext\": \"\"\"Ensure that provided context fulfills requirements", "dagster import check from dagster.core.definitions.events import AssetMaterialization, RetryRequested from dagster.core.errors import ( DagsterInvalidConfigError,", ") elif output.output_name not in output_names: raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" returned an output", "output for non-optional ' f'output \"{output_def.name}\"' ) # Explicitly preserve the ordering of", "output_def.name not in output_values and output_def.is_required: raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" did not return", "args, kwargs): input_defs = solid_def.input_defs # Fail early if too many inputs were", "# Explicitly preserve the ordering of output defs return tuple([output_values[output_def.name] for output_def in", "DirectSolidExecutionContext(solid_config=config, resources_dict=None, instance=None) ) def _resolve_inputs(solid_def, args, kwargs): input_defs = solid_def.input_defs # Fail", "\"{resource_key}\", but no resource ' \"with that key was found on the context.\"", "an output \"{output.output_name}\" that does ' f\"not exist. The available outputs are {list(output_names)}\"", ") input_dict = { input_def.name: input_val for input_val, input_def in zip(args, input_defs[: len(args)])", "\"`build_solid_context` function to construct a context with the required \" \"resources.\" ) if", "if context else None, \"solid_config\" ) config_evr = validate_config(solid_def.config_field.config_type, solid_config) if not config_evr.success:", "if solid_def.config_field: solid_config = check.opt_dict_param( context.solid_config if context else None, \"solid_config\" ) config_evr", "outputs are {list(output_names)}\" ) else: output_values[output.output_name] = output.value else: context.record_materialization(output) # Check to", "f\"not exist. The available outputs are {list(output_names)}\" ) else: output_values[output.output_name] = output.value else:", "were provided for solid '{solid_def.name}'. This may be because \" \"an argument was", "import ( DagsterInvalidConfigError, DagsterInvalidInvocationError, DagsterInvariantViolationError, DagsterSolidInvocationError, user_code_error_boundary, ) if TYPE_CHECKING: from dagster.core.definitions import", "of output defs return tuple([output_values[output_def.name] for output_def in solid_def.output_defs]) def _core_generator( solid_def: \"SolidDefinition\",", "provided. if len(input_defs) < len(args) + len(kwargs): raise DagsterInvalidInvocationError( f\"Too many input arguments", "check from dagster.core.definitions.events import AssetMaterialization, RetryRequested from dagster.core.errors import ( DagsterInvalidConfigError, DagsterInvalidInvocationError, DagsterInvariantViolationError,", "= cast( # type: ignore[attr-defined] \"DirectSolidExecutionContext\", context, ).resources._asdict() for resource_key in solid_def.required_resource_keys: if", "context.solid_config if context else None, \"solid_config\" ) config_evr = validate_config(solid_def.config_field.config_type, solid_config) if not", "requirements if solid_def.required_resource_keys and context is None: raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" has required", "= None if solid_def.config_field: solid_config = check.opt_dict_param( context.solid_config if context else None, \"solid_config\"", "resource requirements if solid_def.required_resource_keys and context is None: raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" has", "available outputs are {list(output_names)}\" ) else: output_values[output.output_name] = output.value else: context.record_materialization(output) # Check", ") -> Generator[Any, None, None]: from dagster.core.execution.plan.compute import gen_from_async_gen with user_code_error_boundary( DagsterSolidInvocationError, control_flow_exceptions=[RetryRequested],", "instance=None) ) def _resolve_inputs(solid_def, args, kwargs): input_defs = solid_def.input_defs # Fail early if", "because \" \"an argument was provided for the context parameter, but no context", "control_flow_exceptions=[RetryRequested], msg_fn=lambda: f'Error occurred while invoking solid \"{solid_def.name}\":', ): compute_iterator = solid_def.compute_fn(context, input_dict)", "dagster.core.execution.plan.compute import gen_from_async_gen with user_code_error_boundary( DagsterSolidInvocationError, control_flow_exceptions=[RetryRequested], msg_fn=lambda: f'Error occurred while invoking solid", "provided context fulfills requirements of solid definition. If no context was provided, then", "output_values[output.output_name] = output.value else: context.record_materialization(output) # Check to make sure all non-optional outputs", "Fail early if too many inputs were provided. if len(input_defs) < len(args) +", "does ' f\"not exist. The available outputs are {list(output_names)}\" ) else: output_values[output.output_name] =", "\"SolidDefinition\", context: Optional[\"DirectSolidExecutionContext\"], *args, **kwargs ) -> Any: context = _check_invocation_requirements(solid_def, context) input_dict", "for output_def in solid_def.output_defs} for output in _core_generator(solid_def, context, input_dict): if not isinstance(output,", "msg_fn=lambda: f'Error occurred while invoking solid \"{solid_def.name}\":', ): compute_iterator = solid_def.compute_fn(context, input_dict) if", "were yielded. for output_def in solid_def.output_defs: if output_def.name not in output_values and output_def.is_required:", "while invoking solid \"{solid_def.name}\":', ): compute_iterator = solid_def.compute_fn(context, input_dict) if inspect.isasyncgen(compute_iterator): compute_iterator =", "input_def.default_value ) return input_dict def _execute_and_retrieve_outputs( solid_def: \"SolidDefinition\", context: \"DirectSolidExecutionContext\", input_dict: Dict[str, Any]", "that provided context fulfills requirements of solid definition. If no context was provided,", "key was found on the context.\" ) # Check config requirements if not", "context else None, \"solid_config\" ) config_evr = validate_config(solid_def.config_field.config_type, solid_config) if not config_evr.success: raise", "SolidDefinition from dagster.core.execution.context.invocation import DirectSolidExecutionContext def solid_invocation_result( solid_def: \"SolidDefinition\", context: Optional[\"DirectSolidExecutionContext\"], *args, **kwargs", "return tuple([output_values[output_def.name] for output_def in solid_def.output_defs]) def _core_generator( solid_def: \"SolidDefinition\", context: \"DirectSolidExecutionContext\", input_dict:", "zip(args, input_defs[: len(args)]) } for input_def in input_defs[len(args) :]: if not input_def.has_default_value and", "input_dict = { input_def.name: input_val for input_val, input_def in zip(args, input_defs[: len(args)]) }", "if output.output_name in output_values: raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" returned an output \"{output.output_name}\" multiple", "solid_config ) mapped_config_evr = solid_def.apply_config_mapping({\"config\": solid_config}) if not mapped_config_evr.success: raise DagsterInvalidConfigError( \"Error in", "but no context was provided. Use the' \"`build_solid_context` function to construct a context", "context) input_dict = _resolve_inputs(solid_def, args, kwargs) outputs = _execute_and_retrieve_outputs(solid_def, context, input_dict) if len(outputs)", "if input_def.name in kwargs else input_def.default_value ) return input_dict def _execute_and_retrieve_outputs( solid_def: \"SolidDefinition\",", "context: Optional[\"DirectSolidExecutionContext\"] ) -> \"DirectSolidExecutionContext\": \"\"\"Ensure that provided context fulfills requirements of solid", "import AssetMaterialization, RetryRequested from dagster.core.errors import ( DagsterInvalidConfigError, DagsterInvalidInvocationError, DagsterInvariantViolationError, DagsterSolidInvocationError, user_code_error_boundary, )", "for input_def in input_defs[len(args) :]: if not input_def.has_default_value and input_def.name not in kwargs:", "output_names: raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" returned an output \"{output.output_name}\" that does ' f\"not", "None: raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" has required resources, but no context was provided.", "None if solid_def.config_field: solid_config = check.opt_dict_param( context.solid_config if context else None, \"solid_config\" )", "if not input_def.has_default_value and input_def.name not in kwargs: raise DagsterInvalidInvocationError( f'No value provided", "was provided, then construct an enpty DirectSolidExecutionContext \"\"\" from dagster.core.execution.context.invocation import DirectSolidExecutionContext from", "requirements if not context and solid_def.config_schema.as_field().is_required: raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" has required config", "Generator, Optional, cast from dagster import check from dagster.core.definitions.events import AssetMaterialization, RetryRequested from", "Dict, Generator, Optional, cast from dagster import check from dagster.core.definitions.events import AssetMaterialization, RetryRequested", "\"Error in config for solid \", mapped_config_evr.errors, solid_config ) config = mapped_config_evr.value.get(\"config\", {})", "def solid_invocation_result( solid_def: \"SolidDefinition\", context: Optional[\"DirectSolidExecutionContext\"], *args, **kwargs ) -> Any: context =", "not in resources_dict: raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" requires resource \"{resource_key}\", but no resource", "in input_defs[len(args) :]: if not input_def.has_default_value and input_def.name not in kwargs: raise DagsterInvalidInvocationError(", "and solid_def.required_resource_keys: resources_dict = cast( # type: ignore[attr-defined] \"DirectSolidExecutionContext\", context, ).resources._asdict() for resource_key", "\"SolidDefinition\", context: Optional[\"DirectSolidExecutionContext\"] ) -> \"DirectSolidExecutionContext\": \"\"\"Ensure that provided context fulfills requirements of", "may be because \" \"an argument was provided for the context parameter, but", "\"DirectSolidExecutionContext\", input_dict: Dict[str, Any] ) -> tuple: output_values = {} output_names = {output_def.name", "solid_def.output_defs: if output_def.name not in output_values and output_def.is_required: raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" did", "f'Error occurred while invoking solid \"{solid_def.name}\":', ): compute_iterator = solid_def.compute_fn(context, input_dict) if inspect.isasyncgen(compute_iterator):", "defined \" \"for the solid.\" ) input_dict = { input_def.name: input_val for input_val,", "else input_def.default_value ) return input_dict def _execute_and_retrieve_outputs( solid_def: \"SolidDefinition\", context: \"DirectSolidExecutionContext\", input_dict: Dict[str,", "was found on the context.\" ) # Check config requirements if not context", "from dagster.core.execution.plan.compute import gen_from_async_gen with user_code_error_boundary( DagsterSolidInvocationError, control_flow_exceptions=[RetryRequested], msg_fn=lambda: f'Error occurred while invoking", "DagsterSolidInvocationError, control_flow_exceptions=[RetryRequested], msg_fn=lambda: f'Error occurred while invoking solid \"{solid_def.name}\":', ): compute_iterator = solid_def.compute_fn(context,", "\"{output_def.name}\"' ) # Explicitly preserve the ordering of output defs return tuple([output_values[output_def.name] for", "\"{solid_def.name}\" has required config schema, but no context was provided. ' \"Use the", "solid.\" ) input_dict = { input_def.name: input_val for input_val, input_def in zip(args, input_defs[:", "mapped_config_evr = solid_def.apply_config_mapping({\"config\": solid_config}) if not mapped_config_evr.success: raise DagsterInvalidConfigError( \"Error in config for", "multiple ' \"times\" ) elif output.output_name not in output_names: raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\"", "validate_config(solid_def.config_field.config_type, solid_config) if not config_evr.success: raise DagsterInvalidConfigError( \"Error in config for solid \",", "context: Optional[\"DirectSolidExecutionContext\"], *args, **kwargs ) -> Any: context = _check_invocation_requirements(solid_def, context) input_dict =", "argument was provided for the context parameter, but no context parameter was defined", "to make sure all non-optional outputs were yielded. for output_def in solid_def.output_defs: if", "\" \"an argument was provided for the context parameter, but no context parameter", "dagster.core.execution.context.invocation import DirectSolidExecutionContext from dagster.config.validate import validate_config # Check resource requirements if solid_def.required_resource_keys", ") return input_dict def _execute_and_retrieve_outputs( solid_def: \"SolidDefinition\", context: \"DirectSolidExecutionContext\", input_dict: Dict[str, Any] )", "import SolidDefinition from dagster.core.execution.context.invocation import DirectSolidExecutionContext def solid_invocation_result( solid_def: \"SolidDefinition\", context: Optional[\"DirectSolidExecutionContext\"], *args,", "context parameter was defined \" \"for the solid.\" ) input_dict = { input_def.name:", "None, None]: from dagster.core.execution.plan.compute import gen_from_async_gen with user_code_error_boundary( DagsterSolidInvocationError, control_flow_exceptions=[RetryRequested], msg_fn=lambda: f'Error occurred", "f'Solid \"{solid_def.name}\" returned an output \"{output.output_name}\" multiple ' \"times\" ) elif output.output_name not", "f'output \"{output_def.name}\"' ) # Explicitly preserve the ordering of output defs return tuple([output_values[output_def.name]", "context, input_dict): if not isinstance(output, AssetMaterialization): if output.output_name in output_values: raise DagsterInvariantViolationError( f'Solid", "if TYPE_CHECKING: from dagster.core.definitions import SolidDefinition from dagster.core.execution.context.invocation import DirectSolidExecutionContext def solid_invocation_result( solid_def:", "context is not None and solid_def.required_resource_keys: resources_dict = cast( # type: ignore[attr-defined] \"DirectSolidExecutionContext\",", "f'Solid \"{solid_def.name}\" requires resource \"{resource_key}\", but no resource ' \"with that key was", "the context.\" ) # Check config requirements if not context and solid_def.config_schema.as_field().is_required: raise", "' \"times\" ) elif output.output_name not in output_names: raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" returned", "raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" has required resources, but no context was provided. Use", "typing import TYPE_CHECKING, Any, Dict, Generator, Optional, cast from dagster import check from", ") # Explicitly preserve the ordering of output defs return tuple([output_values[output_def.name] for output_def", "solid_def.output_defs]) def _core_generator( solid_def: \"SolidDefinition\", context: \"DirectSolidExecutionContext\", input_dict: Dict[str, Any] ) -> Generator[Any,", "in solid_def.required_resource_keys: if resource_key not in resources_dict: raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" requires resource", "found on the context.\" ) # Check config requirements if not context and", "resources_dict = cast( # type: ignore[attr-defined] \"DirectSolidExecutionContext\", context, ).resources._asdict() for resource_key in solid_def.required_resource_keys:", "\"times\" ) elif output.output_name not in output_names: raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" returned an", "\"{solid_def.name}\" has required resources, but no context was provided. Use the' \"`build_solid_context` function", "too many inputs were provided. if len(input_defs) < len(args) + len(kwargs): raise DagsterInvalidInvocationError(", "solid '{solid_def.name}'. This may be because \" \"an argument was provided for the", "provided for the context parameter, but no context parameter was defined \" \"for", "input_def.has_default_value and input_def.name not in kwargs: raise DagsterInvalidInvocationError( f'No value provided for required", "but no context parameter was defined \" \"for the solid.\" ) input_dict =", "Explicitly preserve the ordering of output defs return tuple([output_values[output_def.name] for output_def in solid_def.output_defs])", "the' \"`build_solid_context` function to construct a context with the required \" \"resources.\" )", "config.\" ) config = None if solid_def.config_field: solid_config = check.opt_dict_param( context.solid_config if context", ") def _resolve_inputs(solid_def, args, kwargs): input_defs = solid_def.input_defs # Fail early if too", "context if context else DirectSolidExecutionContext(solid_config=config, resources_dict=None, instance=None) ) def _resolve_inputs(solid_def, args, kwargs): input_defs", "with config.\" ) config = None if solid_def.config_field: solid_config = check.opt_dict_param( context.solid_config if", "in solid_def.output_defs: if output_def.name not in output_values and output_def.is_required: raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\"", "len(args)]) } for input_def in input_defs[len(args) :]: if not input_def.has_default_value and input_def.name not", "return outputs def _check_invocation_requirements( solid_def: \"SolidDefinition\", context: Optional[\"DirectSolidExecutionContext\"] ) -> \"DirectSolidExecutionContext\": \"\"\"Ensure that", "was provided. Use the' \"`build_solid_context` function to construct a context with the required", "\"for the solid.\" ) input_dict = { input_def.name: input_val for input_val, input_def in", "from dagster.config.validate import validate_config # Check resource requirements if solid_def.required_resource_keys and context is", "resource ' \"with that key was found on the context.\" ) # Check", "output_values = {} output_names = {output_def.name for output_def in solid_def.output_defs} for output in", "\"SolidDefinition\", context: \"DirectSolidExecutionContext\", input_dict: Dict[str, Any] ) -> Generator[Any, None, None]: from dagster.core.execution.plan.compute", "import check from dagster.core.definitions.events import AssetMaterialization, RetryRequested from dagster.core.errors import ( DagsterInvalidConfigError, DagsterInvalidInvocationError,", "Generator[Any, None, None]: from dagster.core.execution.plan.compute import gen_from_async_gen with user_code_error_boundary( DagsterSolidInvocationError, control_flow_exceptions=[RetryRequested], msg_fn=lambda: f'Error", "construct an enpty DirectSolidExecutionContext \"\"\" from dagster.core.execution.context.invocation import DirectSolidExecutionContext from dagster.config.validate import validate_config", "mapped_config_evr.value.get(\"config\", {}) return ( context if context else DirectSolidExecutionContext(solid_config=config, resources_dict=None, instance=None) ) def", "output \"{output.output_name}\" that does ' f\"not exist. The available outputs are {list(output_names)}\" )", "not config_evr.success: raise DagsterInvalidConfigError( \"Error in config for solid \", config_evr.errors, solid_config )", "TYPE_CHECKING: from dagster.core.definitions import SolidDefinition from dagster.core.execution.context.invocation import DirectSolidExecutionContext def solid_invocation_result( solid_def: \"SolidDefinition\",", "output_values and output_def.is_required: raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" did not return an output for", "ignore[attr-defined] \"DirectSolidExecutionContext\", context, ).resources._asdict() for resource_key in solid_def.required_resource_keys: if resource_key not in resources_dict:", "outputs were yielded. for output_def in solid_def.output_defs: if output_def.name not in output_values and", ") config = mapped_config_evr.value.get(\"config\", {}) return ( context if context else DirectSolidExecutionContext(solid_config=config, resources_dict=None,", "= ( kwargs[input_def.name] if input_def.name in kwargs else input_def.default_value ) return input_dict def", "\"DirectSolidExecutionContext\", context, ).resources._asdict() for resource_key in solid_def.required_resource_keys: if resource_key not in resources_dict: raise", "input_dict def _execute_and_retrieve_outputs( solid_def: \"SolidDefinition\", context: \"DirectSolidExecutionContext\", input_dict: Dict[str, Any] ) -> tuple:", "dagster.core.execution.context.invocation import DirectSolidExecutionContext def solid_invocation_result( solid_def: \"SolidDefinition\", context: Optional[\"DirectSolidExecutionContext\"], *args, **kwargs ) ->", "an output \"{output.output_name}\" multiple ' \"times\" ) elif output.output_name not in output_names: raise", "context is None: raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" has required resources, but no context", "<reponame>drewsonne/dagster<filename>python_modules/dagster/dagster/core/definitions/solid_invocation.py import inspect from typing import TYPE_CHECKING, Any, Dict, Generator, Optional, cast from", "DirectSolidExecutionContext from dagster.config.validate import validate_config # Check resource requirements if solid_def.required_resource_keys and context", "config for solid \", config_evr.errors, solid_config ) mapped_config_evr = solid_def.apply_config_mapping({\"config\": solid_config}) if not", "dagster.core.errors import ( DagsterInvalidConfigError, DagsterInvalidInvocationError, DagsterInvariantViolationError, DagsterSolidInvocationError, user_code_error_boundary, ) if TYPE_CHECKING: from dagster.core.definitions", "for output in _core_generator(solid_def, context, input_dict): if not isinstance(output, AssetMaterialization): if output.output_name in", "Optional[\"DirectSolidExecutionContext\"] ) -> \"DirectSolidExecutionContext\": \"\"\"Ensure that provided context fulfills requirements of solid definition.", "' \"with that key was found on the context.\" ) # Check config", "output_def.is_required: raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" did not return an output for non-optional '", "isinstance(output, AssetMaterialization): if output.output_name in output_values: raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" returned an output", "requires resource \"{resource_key}\", but no resource ' \"with that key was found on", "\"\"\"Ensure that provided context fulfills requirements of solid definition. If no context was", "# type: ignore[attr-defined] \"DirectSolidExecutionContext\", context, ).resources._asdict() for resource_key in solid_def.required_resource_keys: if resource_key not", "output.output_name in output_values: raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" returned an output \"{output.output_name}\" multiple '", "in _core_generator(solid_def, context, input_dict): if not isinstance(output, AssetMaterialization): if output.output_name in output_values: raise", "raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" returned an output \"{output.output_name}\" that does ' f\"not exist.", "provided. Use the' \"`build_solid_context` function to construct a context with the required \"", "exist. The available outputs are {list(output_names)}\" ) else: output_values[output.output_name] = output.value else: context.record_materialization(output)", "context.record_materialization(output) # Check to make sure all non-optional outputs were yielded. for output_def", ") if context is not None and solid_def.required_resource_keys: resources_dict = cast( # type:", "def _execute_and_retrieve_outputs( solid_def: \"SolidDefinition\", context: \"DirectSolidExecutionContext\", input_dict: Dict[str, Any] ) -> tuple: output_values", "outputs = _execute_and_retrieve_outputs(solid_def, context, input_dict) if len(outputs) == 1: return outputs[0] return outputs", "the `build_solid_context` function to create a context with config.\" ) config = None", "solid_def: \"SolidDefinition\", context: Optional[\"DirectSolidExecutionContext\"], *args, **kwargs ) -> Any: context = _check_invocation_requirements(solid_def, context)", "fulfills requirements of solid definition. If no context was provided, then construct an", "output_values: raise DagsterInvariantViolationError( f'Solid \"{solid_def.name}\" returned an output \"{output.output_name}\" multiple ' \"times\" )", "import gen_from_async_gen with user_code_error_boundary( DagsterSolidInvocationError, control_flow_exceptions=[RetryRequested], msg_fn=lambda: f'Error occurred while invoking solid \"{solid_def.name}\":',", "early if too many inputs were provided. if len(input_defs) < len(args) + len(kwargs):", "Any] ) -> Generator[Any, None, None]: from dagster.core.execution.plan.compute import gen_from_async_gen with user_code_error_boundary( DagsterSolidInvocationError,", "no context was provided, then construct an enpty DirectSolidExecutionContext \"\"\" from dagster.core.execution.context.invocation import", "len(kwargs): raise DagsterInvalidInvocationError( f\"Too many input arguments were provided for solid '{solid_def.name}'. This", "solid_config) if not config_evr.success: raise DagsterInvalidConfigError( \"Error in config for solid \", config_evr.errors,", "resources_dict=None, instance=None) ) def _resolve_inputs(solid_def, args, kwargs): input_defs = solid_def.input_defs # Fail early", "in zip(args, input_defs[: len(args)]) } for input_def in input_defs[len(args) :]: if not input_def.has_default_value", "Any, Dict, Generator, Optional, cast from dagster import check from dagster.core.definitions.events import AssetMaterialization,", "if resource_key not in resources_dict: raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" requires resource \"{resource_key}\", but", "( kwargs[input_def.name] if input_def.name in kwargs else input_def.default_value ) return input_dict def _execute_and_retrieve_outputs(", "{} output_names = {output_def.name for output_def in solid_def.output_defs} for output in _core_generator(solid_def, context,", "not in kwargs: raise DagsterInvalidInvocationError( f'No value provided for required input \"{input_def.name}\".' )", "DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" has required config schema, but no context was provided. '", ") if TYPE_CHECKING: from dagster.core.definitions import SolidDefinition from dagster.core.execution.context.invocation import DirectSolidExecutionContext def solid_invocation_result(", "input_dict: Dict[str, Any] ) -> tuple: output_values = {} output_names = {output_def.name for", "provided, then construct an enpty DirectSolidExecutionContext \"\"\" from dagster.core.execution.context.invocation import DirectSolidExecutionContext from dagster.config.validate", ":]: if not input_def.has_default_value and input_def.name not in kwargs: raise DagsterInvalidInvocationError( f'No value", "DagsterInvariantViolationError, DagsterSolidInvocationError, user_code_error_boundary, ) if TYPE_CHECKING: from dagster.core.definitions import SolidDefinition from dagster.core.execution.context.invocation import", "{output_def.name for output_def in solid_def.output_defs} for output in _core_generator(solid_def, context, input_dict): if not", "\"resources.\" ) if context is not None and solid_def.required_resource_keys: resources_dict = cast( #", "\"{output.output_name}\" that does ' f\"not exist. The available outputs are {list(output_names)}\" ) else:", "returned an output \"{output.output_name}\" multiple ' \"times\" ) elif output.output_name not in output_names:", "DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" has required resources, but no context was provided. Use the'", "if context else DirectSolidExecutionContext(solid_config=config, resources_dict=None, instance=None) ) def _resolve_inputs(solid_def, args, kwargs): input_defs =", "input_dict = _resolve_inputs(solid_def, args, kwargs) outputs = _execute_and_retrieve_outputs(solid_def, context, input_dict) if len(outputs) ==", "None, \"solid_config\" ) config_evr = validate_config(solid_def.config_field.config_type, solid_config) if not config_evr.success: raise DagsterInvalidConfigError( \"Error", "be because \" \"an argument was provided for the context parameter, but no", "context was provided. Use the' \"`build_solid_context` function to construct a context with the", "if len(outputs) == 1: return outputs[0] return outputs def _check_invocation_requirements( solid_def: \"SolidDefinition\", context:", "for solid \", mapped_config_evr.errors, solid_config ) config = mapped_config_evr.value.get(\"config\", {}) return ( context", "Check resource requirements if solid_def.required_resource_keys and context is None: raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\"", "\"with that key was found on the context.\" ) # Check config requirements", "definition. If no context was provided, then construct an enpty DirectSolidExecutionContext \"\"\" from", "that does ' f\"not exist. The available outputs are {list(output_names)}\" ) else: output_values[output.output_name]", "Any: context = _check_invocation_requirements(solid_def, context) input_dict = _resolve_inputs(solid_def, args, kwargs) outputs = _execute_and_retrieve_outputs(solid_def,", "\"{solid_def.name}\" returned an output \"{output.output_name}\" that does ' f\"not exist. The available outputs", "required resources, but no context was provided. Use the' \"`build_solid_context` function to construct", "f\"Too many input arguments were provided for solid '{solid_def.name}'. This may be because", "not input_def.has_default_value and input_def.name not in kwargs: raise DagsterInvalidInvocationError( f'No value provided for", "len(input_defs) < len(args) + len(kwargs): raise DagsterInvalidInvocationError( f\"Too many input arguments were provided", "are {list(output_names)}\" ) else: output_values[output.output_name] = output.value else: context.record_materialization(output) # Check to make", "tuple([output_values[output_def.name] for output_def in solid_def.output_defs]) def _core_generator( solid_def: \"SolidDefinition\", context: \"DirectSolidExecutionContext\", input_dict: Dict[str,", "\"{solid_def.name}\" did not return an output for non-optional ' f'output \"{output_def.name}\"' ) #", ") -> \"DirectSolidExecutionContext\": \"\"\"Ensure that provided context fulfills requirements of solid definition. If", "( context if context else DirectSolidExecutionContext(solid_config=config, resources_dict=None, instance=None) ) def _resolve_inputs(solid_def, args, kwargs):", "if solid_def.required_resource_keys and context is None: raise DagsterInvalidInvocationError( f'Solid \"{solid_def.name}\" has required resources,", "an output for non-optional ' f'output \"{output_def.name}\"' ) # Explicitly preserve the ordering", "= { input_def.name: input_val for input_val, input_def in zip(args, input_defs[: len(args)]) } for", "with the required \" \"resources.\" ) if context is not None and solid_def.required_resource_keys:", "then construct an enpty DirectSolidExecutionContext \"\"\" from dagster.core.execution.context.invocation import DirectSolidExecutionContext from dagster.config.validate import", "user_code_error_boundary, ) if TYPE_CHECKING: from dagster.core.definitions import SolidDefinition from dagster.core.execution.context.invocation import DirectSolidExecutionContext def", "import validate_config # Check resource requirements if solid_def.required_resource_keys and context is None: raise", "for the context parameter, but no context parameter was defined \" \"for the", "that key was found on the context.\" ) # Check config requirements if", "for output_def in solid_def.output_defs: if output_def.name not in output_values and output_def.is_required: raise DagsterInvariantViolationError(", "= _check_invocation_requirements(solid_def, context) input_dict = _resolve_inputs(solid_def, args, kwargs) outputs = _execute_and_retrieve_outputs(solid_def, context, input_dict)", "defs return tuple([output_values[output_def.name] for output_def in solid_def.output_defs]) def _core_generator( solid_def: \"SolidDefinition\", context: \"DirectSolidExecutionContext\",", "of solid definition. If no context was provided, then construct an enpty DirectSolidExecutionContext", "input_def in input_defs[len(args) :]: if not input_def.has_default_value and input_def.name not in kwargs: raise", "sure all non-optional outputs were yielded. for output_def in solid_def.output_defs: if output_def.name not", "context was provided, then construct an enpty DirectSolidExecutionContext \"\"\" from dagster.core.execution.context.invocation import DirectSolidExecutionContext", "dagster.core.definitions.events import AssetMaterialization, RetryRequested from dagster.core.errors import ( DagsterInvalidConfigError, DagsterInvalidInvocationError, DagsterInvariantViolationError, DagsterSolidInvocationError, user_code_error_boundary,", "solid \", mapped_config_evr.errors, solid_config ) config = mapped_config_evr.value.get(\"config\", {}) return ( context if" ]
[ "Maze from .mountain_car import MountainCar from .random_walk import RandomWalk from .short_corridor import ShortCorridor", "WindyGridWorld from .maze import Maze from .mountain_car import MountainCar from .random_walk import RandomWalk", "from .windy_grid_world import WindyGridWorld from .maze import Maze from .mountain_car import MountainCar from", ".maze import Maze from .mountain_car import MountainCar from .random_walk import RandomWalk from .short_corridor", ".k_armed_bandit import KArmedBandit from .grid_world import GridWorld from .race_track import RaceTrack from .windy_grid_world", "RaceTrack from .windy_grid_world import WindyGridWorld from .maze import Maze from .mountain_car import MountainCar", ".grid_world import GridWorld from .race_track import RaceTrack from .windy_grid_world import WindyGridWorld from .maze", "import Maze from .mountain_car import MountainCar from .random_walk import RandomWalk from .short_corridor import", "from .race_track import RaceTrack from .windy_grid_world import WindyGridWorld from .maze import Maze from", "import KArmedBandit from .grid_world import GridWorld from .race_track import RaceTrack from .windy_grid_world import", ".windy_grid_world import WindyGridWorld from .maze import Maze from .mountain_car import MountainCar from .random_walk", "import WindyGridWorld from .maze import Maze from .mountain_car import MountainCar from .random_walk import", "import RaceTrack from .windy_grid_world import WindyGridWorld from .maze import Maze from .mountain_car import", "from .maze import Maze from .mountain_car import MountainCar from .random_walk import RandomWalk from", "KArmedBandit from .grid_world import GridWorld from .race_track import RaceTrack from .windy_grid_world import WindyGridWorld", "GridWorld from .race_track import RaceTrack from .windy_grid_world import WindyGridWorld from .maze import Maze", ".race_track import RaceTrack from .windy_grid_world import WindyGridWorld from .maze import Maze from .mountain_car", "import GridWorld from .race_track import RaceTrack from .windy_grid_world import WindyGridWorld from .maze import", "from .k_armed_bandit import KArmedBandit from .grid_world import GridWorld from .race_track import RaceTrack from", "from .grid_world import GridWorld from .race_track import RaceTrack from .windy_grid_world import WindyGridWorld from" ]
[ "from random import randint for i in range(5): n = (randint(0,10)) if(i ==", "= n elif (n < m): m = n print(n, end=' ') print(f'\\nO", "= n print(n, end=' ') print(f'\\nO maior número foi {M}\\nE o Menor foi", "m = n print(n, end=' ') print(f'\\nO maior número foi {M}\\nE o Menor", "n if (n > M): M = n elif (n < m): m", "random import randint for i in range(5): n = (randint(0,10)) if(i == 0):", "if (n > M): M = n elif (n < m): m =", "import randint for i in range(5): n = (randint(0,10)) if(i == 0): m", "for i in range(5): n = (randint(0,10)) if(i == 0): m = n", "m): m = n print(n, end=' ') print(f'\\nO maior número foi {M}\\nE o", "in range(5): n = (randint(0,10)) if(i == 0): m = n M =", "elif (n < m): m = n print(n, end=' ') print(f'\\nO maior número", "== 0): m = n M = n if (n > M): M", "0): m = n M = n if (n > M): M =", "randint for i in range(5): n = (randint(0,10)) if(i == 0): m =", "range(5): n = (randint(0,10)) if(i == 0): m = n M = n", "n elif (n < m): m = n print(n, end=' ') print(f'\\nO maior", "M): M = n elif (n < m): m = n print(n, end='", "M = n if (n > M): M = n elif (n <", "= (randint(0,10)) if(i == 0): m = n M = n if (n", "n = (randint(0,10)) if(i == 0): m = n M = n if", "= n M = n if (n > M): M = n elif", "> M): M = n elif (n < m): m = n print(n,", "n M = n if (n > M): M = n elif (n", "< m): m = n print(n, end=' ') print(f'\\nO maior número foi {M}\\nE", "(randint(0,10)) if(i == 0): m = n M = n if (n >", "if(i == 0): m = n M = n if (n > M):", "(n < m): m = n print(n, end=' ') print(f'\\nO maior número foi", "M = n elif (n < m): m = n print(n, end=' ')", "= n if (n > M): M = n elif (n < m):", "(n > M): M = n elif (n < m): m = n", "m = n M = n if (n > M): M = n", "i in range(5): n = (randint(0,10)) if(i == 0): m = n M", "n print(n, end=' ') print(f'\\nO maior número foi {M}\\nE o Menor foi {m}')" ]
[ "Frame(self.elements['editors_frame'], bg='gray') editor_frame.pack(side=TOP, expand=False, fill=X, pady=10) editor_label = Label(editor_frame, font=('Arial', 18), bg='gray', text='%s", "if not editor_username: self.parent.display_error('You have to enter an editor username.') return response =", "self.elements['editors_frame'] = Frame(self) self.elements['editors_frame'].pack(side=TOP, padx=120, pady=30, expand=False, fill=BOTH) self.elements['new_editor_frame'] = Frame(self) self.elements['new_editor_frame'].pack(side=TOP, padx=120,", "= Label(title_frame, text='Editors', fg='#003399', font=('Arial', 28)) self.elements['title'].pack(side=TOP) self.elements['editors_frame'] = Frame(self) self.elements['editors_frame'].pack(side=TOP, padx=120, pady=30,", "for this file.', font=('Arial', 22), anchor='w') no_editors_label.pack(side=LEFT, expand=True, fill=X) self.elements['editor_frames'].append(no_editors_label) for editor in", "fill=X) self.elements['editor_frames'].append(no_editors_label) for editor in self.editors: editor_frame = Frame(self.elements['editors_frame'], bg='gray') editor_frame.pack(side=TOP, expand=False, fill=X,", "self.elements['new_editor_frame'].pack(side=TOP, padx=120, pady=(10, 30), expand=False, fill=BOTH) if not self.editors: no_editors_label = Label(self.elements['editors_frame'], bg='gray',", "if 'add_editor_button' in self.elements: self.elements['add_editor_button'].pack_forget() self.elements['add_editor_button'] = Button(self.elements['new_editor_frame'], text='Add Editor', font=('Arial', 18), bg='#003399',", "16), bg='#990000', fg='#ffffff', activebackground='#b30000', activeforeground='#ffffff', command=self.generate_remove_editor(editor['id'])) remove_editor_button.pack(side=RIGHT, padx=20, pady=10) self.elements['editor_frames'].append(editor_frame) if 'editor_entry' in", "if response.code == Codes.SUCCESS: self.parent.display_info('Editor added successfully!') self.initialize() else: self.parent.display_error(response.payload['message']) def generate_remove_editor(self, editor_id):", "else: self.parent.display_error(response.payload['message']) def generate_remove_editor(self, editor_id): return lambda: self.remove_editor(editor_id) def remove_editor(self, editor_id): response =", "no_editors_label.pack(side=LEFT, expand=True, fill=X) self.elements['editor_frames'].append(no_editors_label) for editor in self.editors: editor_frame = Frame(self.elements['editors_frame'], bg='gray') editor_frame.pack(side=TOP,", "in self.elements: self.elements['editor_entry'].pack_forget() self.elements['editor_entry'] = Entry(self.elements['new_editor_frame'], font=('Arial', 18)) self.elements['editor_entry'].pack(side=LEFT, padx=(0, 10), expand=True, fill=BOTH)", "20)) self.elements['title'] = Label(title_frame, text='Editors', fg='#003399', font=('Arial', 28)) self.elements['title'].pack(side=TOP) self.elements['editors_frame'] = Frame(self) self.elements['editors_frame'].pack(side=TOP,", "expand=False, fill=BOTH) if not self.editors: no_editors_label = Label(self.elements['editors_frame'], bg='gray', text='There are no editors", "font=('Arial', 18)) self.elements['editor_entry'].pack(side=LEFT, padx=(0, 10), expand=True, fill=BOTH) if 'add_editor_button' in self.elements: self.elements['add_editor_button'].pack_forget() self.elements['add_editor_button']", "import Data class Editors(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.elements", "30), expand=False, fill=BOTH) if not self.editors: no_editors_label = Label(self.elements['editors_frame'], bg='gray', text='There are no", "lambda: self.remove_editor(editor_id) def remove_editor(self, editor_id): response = FileController.remove_file_editor(editor_id, Data().get_token()) if response.code == Codes.SUCCESS:", "response = FileController.remove_file_editor(editor_id, Data().get_token()) if response.code == Codes.SUCCESS: self.parent.display_info('Editor removed successfully!') self.initialize() else:", "self.current_file = Data().get_current_file() self.editors = FileController.get_file_editors(self.current_file, Data().get_token()) for editor_frame in self.elements['editor_frames']: editor_frame.pack_forget() self.elements['editor_frames']", "activeforeground='#ffffff', command=self.generate_remove_editor(editor['id'])) remove_editor_button.pack(side=RIGHT, padx=20, pady=10) self.elements['editor_frames'].append(editor_frame) if 'editor_entry' in self.elements: self.elements['editor_entry'].pack_forget() self.elements['editor_entry'] =", "padx=20, pady=10) self.elements['editor_frames'].append(editor_frame) if 'editor_entry' in self.elements: self.elements['editor_entry'].pack_forget() self.elements['editor_entry'] = Entry(self.elements['new_editor_frame'], font=('Arial', 18))", "= None def initialize(self): self.current_file = Data().get_current_file() self.editors = FileController.get_file_editors(self.current_file, Data().get_token()) for editor_frame", "FileController.add_file_editor(self.current_file, editor_username, Data().get_token()) if response.code == Codes.SUCCESS: self.parent.display_info('Editor added successfully!') self.initialize() else: self.parent.display_error(response.payload['message'])", "self.elements['editors_frame'].pack(side=TOP, padx=120, pady=30, expand=False, fill=BOTH) self.elements['new_editor_frame'].pack_forget() self.elements['new_editor_frame'].pack(side=TOP, padx=120, pady=(10, 30), expand=False, fill=BOTH) if", "editor_frame in self.elements['editor_frames']: editor_frame.pack_forget() self.elements['editor_frames'] = [] self.elements['editors_frame'].pack_forget() self.elements['editors_frame'].pack(side=TOP, padx=120, pady=30, expand=False, fill=BOTH)", "title_frame = Frame(self) title_frame.pack(expand=True, fill=BOTH, padx=70, pady=(30, 20)) self.elements['title'] = Label(title_frame, text='Editors', fg='#003399',", "= Frame(self) title_frame.pack(expand=True, fill=BOTH, padx=70, pady=(30, 20)) self.elements['title'] = Label(title_frame, text='Editors', fg='#003399', font=('Arial',", "import * from common import Codes from ..controllers import FileController # EditorController (?)", "self.elements['title'] = Label(title_frame, text='Editors', fg='#003399', font=('Arial', 28)) self.elements['title'].pack(side=TOP) self.elements['editors_frame'] = Frame(self) self.elements['editors_frame'].pack(side=TOP, padx=120,", "bg='gray') editor_frame.pack(side=TOP, expand=False, fill=X, pady=10) editor_label = Label(editor_frame, font=('Arial', 18), bg='gray', text='%s (%s)'", "font=('Arial', 18), bg='gray', text='%s (%s)' % (editor['user']['username'], editor['user']['full_name'])) editor_label.pack(side=LEFT, padx=20, pady=10) remove_editor_button =", "font=('Arial', 28)) self.elements['title'].pack(side=TOP) self.elements['editors_frame'] = Frame(self) self.elements['editors_frame'].pack(side=TOP, padx=120, pady=30, expand=False, fill=BOTH) self.elements['new_editor_frame'] =", "padx=120, pady=30, expand=False, fill=BOTH) self.elements['editor_frames'] = [] self.current_file = None def initialize(self): self.current_file", "= Frame(self) self.elements['new_editor_frame'].pack(side=TOP, padx=120, pady=30, expand=False, fill=BOTH) self.elements['editor_frames'] = [] self.current_file = None", "self.editors: no_editors_label = Label(self.elements['editors_frame'], bg='gray', text='There are no editors for this file.', font=('Arial',", "fill=BOTH) if 'add_editor_button' in self.elements: self.elements['add_editor_button'].pack_forget() self.elements['add_editor_button'] = Button(self.elements['new_editor_frame'], text='Add Editor', font=('Arial', 18),", "self.parent.display_error('You have to enter an editor username.') return response = FileController.add_file_editor(self.current_file, editor_username, Data().get_token())", "(%s)' % (editor['user']['username'], editor['user']['full_name'])) editor_label.pack(side=LEFT, padx=20, pady=10) remove_editor_button = Button(editor_frame, text='Remove', font=('Arial', 16),", "def add_editor(self): editor_username = self.elements['editor_entry'].get() self.elements['editor_entry'].delete(0, END) if not editor_username: self.parent.display_error('You have to", "Editor', font=('Arial', 18), bg='#003399', activebackground='#002266', fg='#ffffff', activeforeground='#ffffff', command=self.add_editor) self.elements['add_editor_button'].pack(side=LEFT, expand=False, fill=X) def add_editor(self):", "for editor_frame in self.elements['editor_frames']: editor_frame.pack_forget() self.elements['editor_frames'] = [] self.elements['editors_frame'].pack_forget() self.elements['editors_frame'].pack(side=TOP, padx=120, pady=30, expand=False,", "text='Editors', fg='#003399', font=('Arial', 28)) self.elements['title'].pack(side=TOP) self.elements['editors_frame'] = Frame(self) self.elements['editors_frame'].pack(side=TOP, padx=120, pady=30, expand=False, fill=BOTH)", "Frame(self) self.elements['new_editor_frame'].pack(side=TOP, padx=120, pady=30, expand=False, fill=BOTH) self.elements['editor_frames'] = [] self.current_file = None def", "bg='gray', text='%s (%s)' % (editor['user']['username'], editor['user']['full_name'])) editor_label.pack(side=LEFT, padx=20, pady=10) remove_editor_button = Button(editor_frame, text='Remove',", "title_frame.pack(expand=True, fill=BOTH, padx=70, pady=(30, 20)) self.elements['title'] = Label(title_frame, text='Editors', fg='#003399', font=('Arial', 28)) self.elements['title'].pack(side=TOP)", "editor_username = self.elements['editor_entry'].get() self.elements['editor_entry'].delete(0, END) if not editor_username: self.parent.display_error('You have to enter an", "= [] self.current_file = None def initialize(self): self.current_file = Data().get_current_file() self.editors = FileController.get_file_editors(self.current_file,", "enter an editor username.') return response = FileController.add_file_editor(self.current_file, editor_username, Data().get_token()) if response.code ==", "are no editors for this file.', font=('Arial', 22), anchor='w') no_editors_label.pack(side=LEFT, expand=True, fill=X) self.elements['editor_frames'].append(no_editors_label)", "<reponame>omerk2511/dropbox from Tkinter import * from common import Codes from ..controllers import FileController", "self.remove_editor(editor_id) def remove_editor(self, editor_id): response = FileController.remove_file_editor(editor_id, Data().get_token()) if response.code == Codes.SUCCESS: self.parent.display_info('Editor", "response.code == Codes.SUCCESS: self.parent.display_info('Editor added successfully!') self.initialize() else: self.parent.display_error(response.payload['message']) def generate_remove_editor(self, editor_id): return", "expand=False, fill=BOTH) self.elements['new_editor_frame'] = Frame(self) self.elements['new_editor_frame'].pack(side=TOP, padx=120, pady=30, expand=False, fill=BOTH) self.elements['editor_frames'] = []", "parent): Frame.__init__(self, parent) self.parent = parent self.elements = {} title_frame = Frame(self) title_frame.pack(expand=True,", "self.elements['editor_entry'].get() self.elements['editor_entry'].delete(0, END) if not editor_username: self.parent.display_error('You have to enter an editor username.')", "pady=30, expand=False, fill=BOTH) self.elements['new_editor_frame'].pack_forget() self.elements['new_editor_frame'].pack(side=TOP, padx=120, pady=(10, 30), expand=False, fill=BOTH) if not self.editors:", "editor username.') return response = FileController.add_file_editor(self.current_file, editor_username, Data().get_token()) if response.code == Codes.SUCCESS: self.parent.display_info('Editor", "parent self.elements = {} title_frame = Frame(self) title_frame.pack(expand=True, fill=BOTH, padx=70, pady=(30, 20)) self.elements['title']", "* from common import Codes from ..controllers import FileController # EditorController (?) from", "self.elements['editor_frames'] = [] self.current_file = None def initialize(self): self.current_file = Data().get_current_file() self.editors =", "self.elements['editors_frame'].pack(side=TOP, padx=120, pady=30, expand=False, fill=BOTH) self.elements['new_editor_frame'] = Frame(self) self.elements['new_editor_frame'].pack(side=TOP, padx=120, pady=30, expand=False, fill=BOTH)", "this file.', font=('Arial', 22), anchor='w') no_editors_label.pack(side=LEFT, expand=True, fill=X) self.elements['editor_frames'].append(no_editors_label) for editor in self.editors:", "Label(editor_frame, font=('Arial', 18), bg='gray', text='%s (%s)' % (editor['user']['username'], editor['user']['full_name'])) editor_label.pack(side=LEFT, padx=20, pady=10) remove_editor_button", "= Button(editor_frame, text='Remove', font=('Arial', 16), bg='#990000', fg='#ffffff', activebackground='#b30000', activeforeground='#ffffff', command=self.generate_remove_editor(editor['id'])) remove_editor_button.pack(side=RIGHT, padx=20, pady=10)", "self.editors = FileController.get_file_editors(self.current_file, Data().get_token()) for editor_frame in self.elements['editor_frames']: editor_frame.pack_forget() self.elements['editor_frames'] = [] self.elements['editors_frame'].pack_forget()", "Button(editor_frame, text='Remove', font=('Arial', 16), bg='#990000', fg='#ffffff', activebackground='#b30000', activeforeground='#ffffff', command=self.generate_remove_editor(editor['id'])) remove_editor_button.pack(side=RIGHT, padx=20, pady=10) self.elements['editor_frames'].append(editor_frame)", "pady=10) editor_label = Label(editor_frame, font=('Arial', 18), bg='gray', text='%s (%s)' % (editor['user']['username'], editor['user']['full_name'])) editor_label.pack(side=LEFT,", "fill=BOTH, padx=70, pady=(30, 20)) self.elements['title'] = Label(title_frame, text='Editors', fg='#003399', font=('Arial', 28)) self.elements['title'].pack(side=TOP) self.elements['editors_frame']", "no_editors_label = Label(self.elements['editors_frame'], bg='gray', text='There are no editors for this file.', font=('Arial', 22),", "for editor in self.editors: editor_frame = Frame(self.elements['editors_frame'], bg='gray') editor_frame.pack(side=TOP, expand=False, fill=X, pady=10) editor_label", "self.elements['editor_entry'].pack_forget() self.elements['editor_entry'] = Entry(self.elements['new_editor_frame'], font=('Arial', 18)) self.elements['editor_entry'].pack(side=LEFT, padx=(0, 10), expand=True, fill=BOTH) if 'add_editor_button'", "22), anchor='w') no_editors_label.pack(side=LEFT, expand=True, fill=X) self.elements['editor_frames'].append(no_editors_label) for editor in self.editors: editor_frame = Frame(self.elements['editors_frame'],", "END) if not editor_username: self.parent.display_error('You have to enter an editor username.') return response", "expand=True, fill=BOTH) if 'add_editor_button' in self.elements: self.elements['add_editor_button'].pack_forget() self.elements['add_editor_button'] = Button(self.elements['new_editor_frame'], text='Add Editor', font=('Arial',", "padx=120, pady=30, expand=False, fill=BOTH) self.elements['new_editor_frame'] = Frame(self) self.elements['new_editor_frame'].pack(side=TOP, padx=120, pady=30, expand=False, fill=BOTH) self.elements['editor_frames']", "'editor_entry' in self.elements: self.elements['editor_entry'].pack_forget() self.elements['editor_entry'] = Entry(self.elements['new_editor_frame'], font=('Arial', 18)) self.elements['editor_entry'].pack(side=LEFT, padx=(0, 10), expand=True,", "import Codes from ..controllers import FileController # EditorController (?) from ..handlers.data import Data", "self.elements['add_editor_button'] = Button(self.elements['new_editor_frame'], text='Add Editor', font=('Arial', 18), bg='#003399', activebackground='#002266', fg='#ffffff', activeforeground='#ffffff', command=self.add_editor) self.elements['add_editor_button'].pack(side=LEFT,", "self.elements['title'].pack(side=TOP) self.elements['editors_frame'] = Frame(self) self.elements['editors_frame'].pack(side=TOP, padx=120, pady=30, expand=False, fill=BOTH) self.elements['new_editor_frame'] = Frame(self) self.elements['new_editor_frame'].pack(side=TOP,", "bg='#003399', activebackground='#002266', fg='#ffffff', activeforeground='#ffffff', command=self.add_editor) self.elements['add_editor_button'].pack(side=LEFT, expand=False, fill=X) def add_editor(self): editor_username = self.elements['editor_entry'].get()", "padx=120, pady=(10, 30), expand=False, fill=BOTH) if not self.editors: no_editors_label = Label(self.elements['editors_frame'], bg='gray', text='There", "FileController.get_file_editors(self.current_file, Data().get_token()) for editor_frame in self.elements['editor_frames']: editor_frame.pack_forget() self.elements['editor_frames'] = [] self.elements['editors_frame'].pack_forget() self.elements['editors_frame'].pack(side=TOP, padx=120,", "% (editor['user']['username'], editor['user']['full_name'])) editor_label.pack(side=LEFT, padx=20, pady=10) remove_editor_button = Button(editor_frame, text='Remove', font=('Arial', 16), bg='#990000',", "text='Add Editor', font=('Arial', 18), bg='#003399', activebackground='#002266', fg='#ffffff', activeforeground='#ffffff', command=self.add_editor) self.elements['add_editor_button'].pack(side=LEFT, expand=False, fill=X) def", "FileController # EditorController (?) from ..handlers.data import Data class Editors(Frame): def __init__(self, parent):", "fill=X, pady=10) editor_label = Label(editor_frame, font=('Arial', 18), bg='gray', text='%s (%s)' % (editor['user']['username'], editor['user']['full_name']))", "self.elements['editor_entry'] = Entry(self.elements['new_editor_frame'], font=('Arial', 18)) self.elements['editor_entry'].pack(side=LEFT, padx=(0, 10), expand=True, fill=BOTH) if 'add_editor_button' in", "expand=False, fill=X) def add_editor(self): editor_username = self.elements['editor_entry'].get() self.elements['editor_entry'].delete(0, END) if not editor_username: self.parent.display_error('You", "class Editors(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.elements = {}", "self.elements['add_editor_button'].pack(side=LEFT, expand=False, fill=X) def add_editor(self): editor_username = self.elements['editor_entry'].get() self.elements['editor_entry'].delete(0, END) if not editor_username:", "fill=X) def add_editor(self): editor_username = self.elements['editor_entry'].get() self.elements['editor_entry'].delete(0, END) if not editor_username: self.parent.display_error('You have", "= self.elements['editor_entry'].get() self.elements['editor_entry'].delete(0, END) if not editor_username: self.parent.display_error('You have to enter an editor", "editor_username, Data().get_token()) if response.code == Codes.SUCCESS: self.parent.display_info('Editor added successfully!') self.initialize() else: self.parent.display_error(response.payload['message']) def", "None def initialize(self): self.current_file = Data().get_current_file() self.editors = FileController.get_file_editors(self.current_file, Data().get_token()) for editor_frame in", "in self.editors: editor_frame = Frame(self.elements['editors_frame'], bg='gray') editor_frame.pack(side=TOP, expand=False, fill=X, pady=10) editor_label = Label(editor_frame,", "= Frame(self.elements['editors_frame'], bg='gray') editor_frame.pack(side=TOP, expand=False, fill=X, pady=10) editor_label = Label(editor_frame, font=('Arial', 18), bg='gray',", "pady=10) remove_editor_button = Button(editor_frame, text='Remove', font=('Arial', 16), bg='#990000', fg='#ffffff', activebackground='#b30000', activeforeground='#ffffff', command=self.generate_remove_editor(editor['id'])) remove_editor_button.pack(side=RIGHT,", "self.elements['editor_frames'] = [] self.elements['editors_frame'].pack_forget() self.elements['editors_frame'].pack(side=TOP, padx=120, pady=30, expand=False, fill=BOTH) self.elements['new_editor_frame'].pack_forget() self.elements['new_editor_frame'].pack(side=TOP, padx=120, pady=(10,", "pady=10) self.elements['editor_frames'].append(editor_frame) if 'editor_entry' in self.elements: self.elements['editor_entry'].pack_forget() self.elements['editor_entry'] = Entry(self.elements['new_editor_frame'], font=('Arial', 18)) self.elements['editor_entry'].pack(side=LEFT,", "not self.editors: no_editors_label = Label(self.elements['editors_frame'], bg='gray', text='There are no editors for this file.',", "parent) self.parent = parent self.elements = {} title_frame = Frame(self) title_frame.pack(expand=True, fill=BOTH, padx=70,", "18)) self.elements['editor_entry'].pack(side=LEFT, padx=(0, 10), expand=True, fill=BOTH) if 'add_editor_button' in self.elements: self.elements['add_editor_button'].pack_forget() self.elements['add_editor_button'] =", "self.elements['editor_frames']: editor_frame.pack_forget() self.elements['editor_frames'] = [] self.elements['editors_frame'].pack_forget() self.elements['editors_frame'].pack(side=TOP, padx=120, pady=30, expand=False, fill=BOTH) self.elements['new_editor_frame'].pack_forget() self.elements['new_editor_frame'].pack(side=TOP,", "Data().get_token()) for editor_frame in self.elements['editor_frames']: editor_frame.pack_forget() self.elements['editor_frames'] = [] self.elements['editors_frame'].pack_forget() self.elements['editors_frame'].pack(side=TOP, padx=120, pady=30,", "in self.elements['editor_frames']: editor_frame.pack_forget() self.elements['editor_frames'] = [] self.elements['editors_frame'].pack_forget() self.elements['editors_frame'].pack(side=TOP, padx=120, pady=30, expand=False, fill=BOTH) self.elements['new_editor_frame'].pack_forget()", "editor_label = Label(editor_frame, font=('Arial', 18), bg='gray', text='%s (%s)' % (editor['user']['username'], editor['user']['full_name'])) editor_label.pack(side=LEFT, padx=20,", "self.initialize() else: self.parent.display_error(response.payload['message']) def generate_remove_editor(self, editor_id): return lambda: self.remove_editor(editor_id) def remove_editor(self, editor_id): response", "generate_remove_editor(self, editor_id): return lambda: self.remove_editor(editor_id) def remove_editor(self, editor_id): response = FileController.remove_file_editor(editor_id, Data().get_token()) if", "def remove_editor(self, editor_id): response = FileController.remove_file_editor(editor_id, Data().get_token()) if response.code == Codes.SUCCESS: self.parent.display_info('Editor removed", "editor in self.editors: editor_frame = Frame(self.elements['editors_frame'], bg='gray') editor_frame.pack(side=TOP, expand=False, fill=X, pady=10) editor_label =", "from Tkinter import * from common import Codes from ..controllers import FileController #", "self.parent.display_error(response.payload['message']) def generate_remove_editor(self, editor_id): return lambda: self.remove_editor(editor_id) def remove_editor(self, editor_id): response = FileController.remove_file_editor(editor_id,", "Codes from ..controllers import FileController # EditorController (?) from ..handlers.data import Data class", "editor_frame.pack(side=TOP, expand=False, fill=X, pady=10) editor_label = Label(editor_frame, font=('Arial', 18), bg='gray', text='%s (%s)' %", "fill=BOTH) self.elements['editor_frames'] = [] self.current_file = None def initialize(self): self.current_file = Data().get_current_file() self.editors", "editor_frame.pack_forget() self.elements['editor_frames'] = [] self.elements['editors_frame'].pack_forget() self.elements['editors_frame'].pack(side=TOP, padx=120, pady=30, expand=False, fill=BOTH) self.elements['new_editor_frame'].pack_forget() self.elements['new_editor_frame'].pack(side=TOP, padx=120,", "pady=30, expand=False, fill=BOTH) self.elements['new_editor_frame'] = Frame(self) self.elements['new_editor_frame'].pack(side=TOP, padx=120, pady=30, expand=False, fill=BOTH) self.elements['editor_frames'] =", "(?) from ..handlers.data import Data class Editors(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent", "fill=BOTH) if not self.editors: no_editors_label = Label(self.elements['editors_frame'], bg='gray', text='There are no editors for", "common import Codes from ..controllers import FileController # EditorController (?) from ..handlers.data import", "def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.elements = {} title_frame =", "response = FileController.add_file_editor(self.current_file, editor_username, Data().get_token()) if response.code == Codes.SUCCESS: self.parent.display_info('Editor added successfully!') self.initialize()", "== Codes.SUCCESS: self.parent.display_info('Editor added successfully!') self.initialize() else: self.parent.display_error(response.payload['message']) def generate_remove_editor(self, editor_id): return lambda:", "padx=120, pady=30, expand=False, fill=BOTH) self.elements['new_editor_frame'].pack_forget() self.elements['new_editor_frame'].pack(side=TOP, padx=120, pady=(10, 30), expand=False, fill=BOTH) if not", "activebackground='#b30000', activeforeground='#ffffff', command=self.generate_remove_editor(editor['id'])) remove_editor_button.pack(side=RIGHT, padx=20, pady=10) self.elements['editor_frames'].append(editor_frame) if 'editor_entry' in self.elements: self.elements['editor_entry'].pack_forget() self.elements['editor_entry']", "..handlers.data import Data class Editors(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent", "editor['user']['full_name'])) editor_label.pack(side=LEFT, padx=20, pady=10) remove_editor_button = Button(editor_frame, text='Remove', font=('Arial', 16), bg='#990000', fg='#ffffff', activebackground='#b30000',", "command=self.add_editor) self.elements['add_editor_button'].pack(side=LEFT, expand=False, fill=X) def add_editor(self): editor_username = self.elements['editor_entry'].get() self.elements['editor_entry'].delete(0, END) if not", "28)) self.elements['title'].pack(side=TOP) self.elements['editors_frame'] = Frame(self) self.elements['editors_frame'].pack(side=TOP, padx=120, pady=30, expand=False, fill=BOTH) self.elements['new_editor_frame'] = Frame(self)", "editor_frame = Frame(self.elements['editors_frame'], bg='gray') editor_frame.pack(side=TOP, expand=False, fill=X, pady=10) editor_label = Label(editor_frame, font=('Arial', 18),", "padx=20, pady=10) remove_editor_button = Button(editor_frame, text='Remove', font=('Arial', 16), bg='#990000', fg='#ffffff', activebackground='#b30000', activeforeground='#ffffff', command=self.generate_remove_editor(editor['id']))", "text='Remove', font=('Arial', 16), bg='#990000', fg='#ffffff', activebackground='#b30000', activeforeground='#ffffff', command=self.generate_remove_editor(editor['id'])) remove_editor_button.pack(side=RIGHT, padx=20, pady=10) self.elements['editor_frames'].append(editor_frame) if", "= Frame(self) self.elements['editors_frame'].pack(side=TOP, padx=120, pady=30, expand=False, fill=BOTH) self.elements['new_editor_frame'] = Frame(self) self.elements['new_editor_frame'].pack(side=TOP, padx=120, pady=30,", "editors for this file.', font=('Arial', 22), anchor='w') no_editors_label.pack(side=LEFT, expand=True, fill=X) self.elements['editor_frames'].append(no_editors_label) for editor", "= FileController.remove_file_editor(editor_id, Data().get_token()) if response.code == Codes.SUCCESS: self.parent.display_info('Editor removed successfully!') self.initialize() else: self.parent.display_error(response.payload['message'])", "Data().get_token()) if response.code == Codes.SUCCESS: self.parent.display_info('Editor added successfully!') self.initialize() else: self.parent.display_error(response.payload['message']) def generate_remove_editor(self,", "font=('Arial', 18), bg='#003399', activebackground='#002266', fg='#ffffff', activeforeground='#ffffff', command=self.add_editor) self.elements['add_editor_button'].pack(side=LEFT, expand=False, fill=X) def add_editor(self): editor_username", "text='%s (%s)' % (editor['user']['username'], editor['user']['full_name'])) editor_label.pack(side=LEFT, padx=20, pady=10) remove_editor_button = Button(editor_frame, text='Remove', font=('Arial',", "bg='#990000', fg='#ffffff', activebackground='#b30000', activeforeground='#ffffff', command=self.generate_remove_editor(editor['id'])) remove_editor_button.pack(side=RIGHT, padx=20, pady=10) self.elements['editor_frames'].append(editor_frame) if 'editor_entry' in self.elements:", "fg='#003399', font=('Arial', 28)) self.elements['title'].pack(side=TOP) self.elements['editors_frame'] = Frame(self) self.elements['editors_frame'].pack(side=TOP, padx=120, pady=30, expand=False, fill=BOTH) self.elements['new_editor_frame']", "file.', font=('Arial', 22), anchor='w') no_editors_label.pack(side=LEFT, expand=True, fill=X) self.elements['editor_frames'].append(no_editors_label) for editor in self.editors: editor_frame", "..controllers import FileController # EditorController (?) from ..handlers.data import Data class Editors(Frame): def", "= parent self.elements = {} title_frame = Frame(self) title_frame.pack(expand=True, fill=BOTH, padx=70, pady=(30, 20))", "= Entry(self.elements['new_editor_frame'], font=('Arial', 18)) self.elements['editor_entry'].pack(side=LEFT, padx=(0, 10), expand=True, fill=BOTH) if 'add_editor_button' in self.elements:", "pady=(30, 20)) self.elements['title'] = Label(title_frame, text='Editors', fg='#003399', font=('Arial', 28)) self.elements['title'].pack(side=TOP) self.elements['editors_frame'] = Frame(self)", "fg='#ffffff', activeforeground='#ffffff', command=self.add_editor) self.elements['add_editor_button'].pack(side=LEFT, expand=False, fill=X) def add_editor(self): editor_username = self.elements['editor_entry'].get() self.elements['editor_entry'].delete(0, END)", "command=self.generate_remove_editor(editor['id'])) remove_editor_button.pack(side=RIGHT, padx=20, pady=10) self.elements['editor_frames'].append(editor_frame) if 'editor_entry' in self.elements: self.elements['editor_entry'].pack_forget() self.elements['editor_entry'] = Entry(self.elements['new_editor_frame'],", "expand=False, fill=X, pady=10) editor_label = Label(editor_frame, font=('Arial', 18), bg='gray', text='%s (%s)' % (editor['user']['username'],", "bg='gray', text='There are no editors for this file.', font=('Arial', 22), anchor='w') no_editors_label.pack(side=LEFT, expand=True,", "Label(title_frame, text='Editors', fg='#003399', font=('Arial', 28)) self.elements['title'].pack(side=TOP) self.elements['editors_frame'] = Frame(self) self.elements['editors_frame'].pack(side=TOP, padx=120, pady=30, expand=False,", "not editor_username: self.parent.display_error('You have to enter an editor username.') return response = FileController.add_file_editor(self.current_file,", "# EditorController (?) from ..handlers.data import Data class Editors(Frame): def __init__(self, parent): Frame.__init__(self,", "10), expand=True, fill=BOTH) if 'add_editor_button' in self.elements: self.elements['add_editor_button'].pack_forget() self.elements['add_editor_button'] = Button(self.elements['new_editor_frame'], text='Add Editor',", "self.current_file = None def initialize(self): self.current_file = Data().get_current_file() self.editors = FileController.get_file_editors(self.current_file, Data().get_token()) for", "anchor='w') no_editors_label.pack(side=LEFT, expand=True, fill=X) self.elements['editor_frames'].append(no_editors_label) for editor in self.editors: editor_frame = Frame(self.elements['editors_frame'], bg='gray')", "[] self.elements['editors_frame'].pack_forget() self.elements['editors_frame'].pack(side=TOP, padx=120, pady=30, expand=False, fill=BOTH) self.elements['new_editor_frame'].pack_forget() self.elements['new_editor_frame'].pack(side=TOP, padx=120, pady=(10, 30), expand=False,", "font=('Arial', 16), bg='#990000', fg='#ffffff', activebackground='#b30000', activeforeground='#ffffff', command=self.generate_remove_editor(editor['id'])) remove_editor_button.pack(side=RIGHT, padx=20, pady=10) self.elements['editor_frames'].append(editor_frame) if 'editor_entry'", "remove_editor_button.pack(side=RIGHT, padx=20, pady=10) self.elements['editor_frames'].append(editor_frame) if 'editor_entry' in self.elements: self.elements['editor_entry'].pack_forget() self.elements['editor_entry'] = Entry(self.elements['new_editor_frame'], font=('Arial',", "initialize(self): self.current_file = Data().get_current_file() self.editors = FileController.get_file_editors(self.current_file, Data().get_token()) for editor_frame in self.elements['editor_frames']: editor_frame.pack_forget()", "(editor['user']['username'], editor['user']['full_name'])) editor_label.pack(side=LEFT, padx=20, pady=10) remove_editor_button = Button(editor_frame, text='Remove', font=('Arial', 16), bg='#990000', fg='#ffffff',", "self.parent = parent self.elements = {} title_frame = Frame(self) title_frame.pack(expand=True, fill=BOTH, padx=70, pady=(30,", "expand=True, fill=X) self.elements['editor_frames'].append(no_editors_label) for editor in self.editors: editor_frame = Frame(self.elements['editors_frame'], bg='gray') editor_frame.pack(side=TOP, expand=False,", "import FileController # EditorController (?) from ..handlers.data import Data class Editors(Frame): def __init__(self,", "an editor username.') return response = FileController.add_file_editor(self.current_file, editor_username, Data().get_token()) if response.code == Codes.SUCCESS:", "self.parent.display_info('Editor added successfully!') self.initialize() else: self.parent.display_error(response.payload['message']) def generate_remove_editor(self, editor_id): return lambda: self.remove_editor(editor_id) def", "self.elements['add_editor_button'].pack_forget() self.elements['add_editor_button'] = Button(self.elements['new_editor_frame'], text='Add Editor', font=('Arial', 18), bg='#003399', activebackground='#002266', fg='#ffffff', activeforeground='#ffffff', command=self.add_editor)", "from ..handlers.data import Data class Editors(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent =", "editor_label.pack(side=LEFT, padx=20, pady=10) remove_editor_button = Button(editor_frame, text='Remove', font=('Arial', 16), bg='#990000', fg='#ffffff', activebackground='#b30000', activeforeground='#ffffff',", "18), bg='#003399', activebackground='#002266', fg='#ffffff', activeforeground='#ffffff', command=self.add_editor) self.elements['add_editor_button'].pack(side=LEFT, expand=False, fill=X) def add_editor(self): editor_username =", "Frame(self) self.elements['editors_frame'].pack(side=TOP, padx=120, pady=30, expand=False, fill=BOTH) self.elements['new_editor_frame'] = Frame(self) self.elements['new_editor_frame'].pack(side=TOP, padx=120, pady=30, expand=False,", "expand=False, fill=BOTH) self.elements['new_editor_frame'].pack_forget() self.elements['new_editor_frame'].pack(side=TOP, padx=120, pady=(10, 30), expand=False, fill=BOTH) if not self.editors: no_editors_label", "activebackground='#002266', fg='#ffffff', activeforeground='#ffffff', command=self.add_editor) self.elements['add_editor_button'].pack(side=LEFT, expand=False, fill=X) def add_editor(self): editor_username = self.elements['editor_entry'].get() self.elements['editor_entry'].delete(0,", "self.elements['editor_entry'].delete(0, END) if not editor_username: self.parent.display_error('You have to enter an editor username.') return", "editor_id): response = FileController.remove_file_editor(editor_id, Data().get_token()) if response.code == Codes.SUCCESS: self.parent.display_info('Editor removed successfully!') self.initialize()", "= {} title_frame = Frame(self) title_frame.pack(expand=True, fill=BOTH, padx=70, pady=(30, 20)) self.elements['title'] = Label(title_frame,", "return lambda: self.remove_editor(editor_id) def remove_editor(self, editor_id): response = FileController.remove_file_editor(editor_id, Data().get_token()) if response.code ==", "self.elements['editors_frame'].pack_forget() self.elements['editors_frame'].pack(side=TOP, padx=120, pady=30, expand=False, fill=BOTH) self.elements['new_editor_frame'].pack_forget() self.elements['new_editor_frame'].pack(side=TOP, padx=120, pady=(10, 30), expand=False, fill=BOTH)", "'add_editor_button' in self.elements: self.elements['add_editor_button'].pack_forget() self.elements['add_editor_button'] = Button(self.elements['new_editor_frame'], text='Add Editor', font=('Arial', 18), bg='#003399', activebackground='#002266',", "fill=BOTH) self.elements['new_editor_frame'].pack_forget() self.elements['new_editor_frame'].pack(side=TOP, padx=120, pady=(10, 30), expand=False, fill=BOTH) if not self.editors: no_editors_label =", "padx=70, pady=(30, 20)) self.elements['title'] = Label(title_frame, text='Editors', fg='#003399', font=('Arial', 28)) self.elements['title'].pack(side=TOP) self.elements['editors_frame'] =", "from common import Codes from ..controllers import FileController # EditorController (?) from ..handlers.data", "added successfully!') self.initialize() else: self.parent.display_error(response.payload['message']) def generate_remove_editor(self, editor_id): return lambda: self.remove_editor(editor_id) def remove_editor(self,", "= Button(self.elements['new_editor_frame'], text='Add Editor', font=('Arial', 18), bg='#003399', activebackground='#002266', fg='#ffffff', activeforeground='#ffffff', command=self.add_editor) self.elements['add_editor_button'].pack(side=LEFT, expand=False,", "self.elements['new_editor_frame'] = Frame(self) self.elements['new_editor_frame'].pack(side=TOP, padx=120, pady=30, expand=False, fill=BOTH) self.elements['editor_frames'] = [] self.current_file =", "= FileController.add_file_editor(self.current_file, editor_username, Data().get_token()) if response.code == Codes.SUCCESS: self.parent.display_info('Editor added successfully!') self.initialize() else:", "18), bg='gray', text='%s (%s)' % (editor['user']['username'], editor['user']['full_name'])) editor_label.pack(side=LEFT, padx=20, pady=10) remove_editor_button = Button(editor_frame,", "= Label(self.elements['editors_frame'], bg='gray', text='There are no editors for this file.', font=('Arial', 22), anchor='w')", "self.elements: self.elements['add_editor_button'].pack_forget() self.elements['add_editor_button'] = Button(self.elements['new_editor_frame'], text='Add Editor', font=('Arial', 18), bg='#003399', activebackground='#002266', fg='#ffffff', activeforeground='#ffffff',", "= Data().get_current_file() self.editors = FileController.get_file_editors(self.current_file, Data().get_token()) for editor_frame in self.elements['editor_frames']: editor_frame.pack_forget() self.elements['editor_frames'] =", "username.') return response = FileController.add_file_editor(self.current_file, editor_username, Data().get_token()) if response.code == Codes.SUCCESS: self.parent.display_info('Editor added", "{} title_frame = Frame(self) title_frame.pack(expand=True, fill=BOTH, padx=70, pady=(30, 20)) self.elements['title'] = Label(title_frame, text='Editors',", "pady=(10, 30), expand=False, fill=BOTH) if not self.editors: no_editors_label = Label(self.elements['editors_frame'], bg='gray', text='There are", "add_editor(self): editor_username = self.elements['editor_entry'].get() self.elements['editor_entry'].delete(0, END) if not editor_username: self.parent.display_error('You have to enter", "remove_editor(self, editor_id): response = FileController.remove_file_editor(editor_id, Data().get_token()) if response.code == Codes.SUCCESS: self.parent.display_info('Editor removed successfully!')", "to enter an editor username.') return response = FileController.add_file_editor(self.current_file, editor_username, Data().get_token()) if response.code", "self.elements = {} title_frame = Frame(self) title_frame.pack(expand=True, fill=BOTH, padx=70, pady=(30, 20)) self.elements['title'] =", "text='There are no editors for this file.', font=('Arial', 22), anchor='w') no_editors_label.pack(side=LEFT, expand=True, fill=X)", "no editors for this file.', font=('Arial', 22), anchor='w') no_editors_label.pack(side=LEFT, expand=True, fill=X) self.elements['editor_frames'].append(no_editors_label) for", "self.elements: self.elements['editor_entry'].pack_forget() self.elements['editor_entry'] = Entry(self.elements['new_editor_frame'], font=('Arial', 18)) self.elements['editor_entry'].pack(side=LEFT, padx=(0, 10), expand=True, fill=BOTH) if", "padx=(0, 10), expand=True, fill=BOTH) if 'add_editor_button' in self.elements: self.elements['add_editor_button'].pack_forget() self.elements['add_editor_button'] = Button(self.elements['new_editor_frame'], text='Add", "Button(self.elements['new_editor_frame'], text='Add Editor', font=('Arial', 18), bg='#003399', activebackground='#002266', fg='#ffffff', activeforeground='#ffffff', command=self.add_editor) self.elements['add_editor_button'].pack(side=LEFT, expand=False, fill=X)", "fg='#ffffff', activebackground='#b30000', activeforeground='#ffffff', command=self.generate_remove_editor(editor['id'])) remove_editor_button.pack(side=RIGHT, padx=20, pady=10) self.elements['editor_frames'].append(editor_frame) if 'editor_entry' in self.elements: self.elements['editor_entry'].pack_forget()", "self.elements['new_editor_frame'].pack_forget() self.elements['new_editor_frame'].pack(side=TOP, padx=120, pady=(10, 30), expand=False, fill=BOTH) if not self.editors: no_editors_label = Label(self.elements['editors_frame'],", "Data().get_current_file() self.editors = FileController.get_file_editors(self.current_file, Data().get_token()) for editor_frame in self.elements['editor_frames']: editor_frame.pack_forget() self.elements['editor_frames'] = []", "self.editors: editor_frame = Frame(self.elements['editors_frame'], bg='gray') editor_frame.pack(side=TOP, expand=False, fill=X, pady=10) editor_label = Label(editor_frame, font=('Arial',", "= [] self.elements['editors_frame'].pack_forget() self.elements['editors_frame'].pack(side=TOP, padx=120, pady=30, expand=False, fill=BOTH) self.elements['new_editor_frame'].pack_forget() self.elements['new_editor_frame'].pack(side=TOP, padx=120, pady=(10, 30),", "pady=30, expand=False, fill=BOTH) self.elements['editor_frames'] = [] self.current_file = None def initialize(self): self.current_file =", "remove_editor_button = Button(editor_frame, text='Remove', font=('Arial', 16), bg='#990000', fg='#ffffff', activebackground='#b30000', activeforeground='#ffffff', command=self.generate_remove_editor(editor['id'])) remove_editor_button.pack(side=RIGHT, padx=20,", "editor_username: self.parent.display_error('You have to enter an editor username.') return response = FileController.add_file_editor(self.current_file, editor_username,", "have to enter an editor username.') return response = FileController.add_file_editor(self.current_file, editor_username, Data().get_token()) if", "Tkinter import * from common import Codes from ..controllers import FileController # EditorController", "successfully!') self.initialize() else: self.parent.display_error(response.payload['message']) def generate_remove_editor(self, editor_id): return lambda: self.remove_editor(editor_id) def remove_editor(self, editor_id):", "self.elements['new_editor_frame'].pack(side=TOP, padx=120, pady=30, expand=False, fill=BOTH) self.elements['editor_frames'] = [] self.current_file = None def initialize(self):", "Label(self.elements['editors_frame'], bg='gray', text='There are no editors for this file.', font=('Arial', 22), anchor='w') no_editors_label.pack(side=LEFT,", "= FileController.get_file_editors(self.current_file, Data().get_token()) for editor_frame in self.elements['editor_frames']: editor_frame.pack_forget() self.elements['editor_frames'] = [] self.elements['editors_frame'].pack_forget() self.elements['editors_frame'].pack(side=TOP,", "= Label(editor_frame, font=('Arial', 18), bg='gray', text='%s (%s)' % (editor['user']['username'], editor['user']['full_name'])) editor_label.pack(side=LEFT, padx=20, pady=10)", "Frame.__init__(self, parent) self.parent = parent self.elements = {} title_frame = Frame(self) title_frame.pack(expand=True, fill=BOTH,", "font=('Arial', 22), anchor='w') no_editors_label.pack(side=LEFT, expand=True, fill=X) self.elements['editor_frames'].append(no_editors_label) for editor in self.editors: editor_frame =", "EditorController (?) from ..handlers.data import Data class Editors(Frame): def __init__(self, parent): Frame.__init__(self, parent)", "Editors(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.elements = {} title_frame", "expand=False, fill=BOTH) self.elements['editor_frames'] = [] self.current_file = None def initialize(self): self.current_file = Data().get_current_file()", "def initialize(self): self.current_file = Data().get_current_file() self.editors = FileController.get_file_editors(self.current_file, Data().get_token()) for editor_frame in self.elements['editor_frames']:", "if not self.editors: no_editors_label = Label(self.elements['editors_frame'], bg='gray', text='There are no editors for this", "Entry(self.elements['new_editor_frame'], font=('Arial', 18)) self.elements['editor_entry'].pack(side=LEFT, padx=(0, 10), expand=True, fill=BOTH) if 'add_editor_button' in self.elements: self.elements['add_editor_button'].pack_forget()", "activeforeground='#ffffff', command=self.add_editor) self.elements['add_editor_button'].pack(side=LEFT, expand=False, fill=X) def add_editor(self): editor_username = self.elements['editor_entry'].get() self.elements['editor_entry'].delete(0, END) if", "editor_id): return lambda: self.remove_editor(editor_id) def remove_editor(self, editor_id): response = FileController.remove_file_editor(editor_id, Data().get_token()) if response.code", "if 'editor_entry' in self.elements: self.elements['editor_entry'].pack_forget() self.elements['editor_entry'] = Entry(self.elements['new_editor_frame'], font=('Arial', 18)) self.elements['editor_entry'].pack(side=LEFT, padx=(0, 10),", "def generate_remove_editor(self, editor_id): return lambda: self.remove_editor(editor_id) def remove_editor(self, editor_id): response = FileController.remove_file_editor(editor_id, Data().get_token())", "from ..controllers import FileController # EditorController (?) from ..handlers.data import Data class Editors(Frame):", "return response = FileController.add_file_editor(self.current_file, editor_username, Data().get_token()) if response.code == Codes.SUCCESS: self.parent.display_info('Editor added successfully!')", "Frame(self) title_frame.pack(expand=True, fill=BOTH, padx=70, pady=(30, 20)) self.elements['title'] = Label(title_frame, text='Editors', fg='#003399', font=('Arial', 28))", "self.elements['editor_frames'].append(editor_frame) if 'editor_entry' in self.elements: self.elements['editor_entry'].pack_forget() self.elements['editor_entry'] = Entry(self.elements['new_editor_frame'], font=('Arial', 18)) self.elements['editor_entry'].pack(side=LEFT, padx=(0,", "Data class Editors(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.elements =", "Codes.SUCCESS: self.parent.display_info('Editor added successfully!') self.initialize() else: self.parent.display_error(response.payload['message']) def generate_remove_editor(self, editor_id): return lambda: self.remove_editor(editor_id)", "self.elements['editor_frames'].append(no_editors_label) for editor in self.editors: editor_frame = Frame(self.elements['editors_frame'], bg='gray') editor_frame.pack(side=TOP, expand=False, fill=X, pady=10)", "fill=BOTH) self.elements['new_editor_frame'] = Frame(self) self.elements['new_editor_frame'].pack(side=TOP, padx=120, pady=30, expand=False, fill=BOTH) self.elements['editor_frames'] = [] self.current_file", "self.elements['editor_entry'].pack(side=LEFT, padx=(0, 10), expand=True, fill=BOTH) if 'add_editor_button' in self.elements: self.elements['add_editor_button'].pack_forget() self.elements['add_editor_button'] = Button(self.elements['new_editor_frame'],", "in self.elements: self.elements['add_editor_button'].pack_forget() self.elements['add_editor_button'] = Button(self.elements['new_editor_frame'], text='Add Editor', font=('Arial', 18), bg='#003399', activebackground='#002266', fg='#ffffff',", "[] self.current_file = None def initialize(self): self.current_file = Data().get_current_file() self.editors = FileController.get_file_editors(self.current_file, Data().get_token())", "__init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.elements = {} title_frame = Frame(self)" ]
[ "(C) 2018 <NAME> # This program is free software: you can redistribute it", "name in parent._declared_fields.keys(): del child_def['properties'][name] try: child_def['required'].remove(name) except ValueError: pass if not child_def['required']:", "distributed in the hope that it will be useful, # but WITHOUT ANY", "before the \" \"child schema\") child_def = definition.copy() for parent in parents: for", "using `allOf`. Uses the `schema` parameter. \"\"\" parents = [b for b in", "std_bases.append(OneOfSchema) except ImportError: pass def swaggerinherit_definition_helper(spec, name, schema, definition, **kwargs): \"\"\"Definition helper that", "either version 3 of the License, or # (at your option) any later", "except ValueError: pass if not child_def['required']: del child_def['required'] definition.clear() return { 'allOf': [{'$ref':", "by # the Free Software Foundation, either version 3 of the License, or", "License # along with this program. If not, see <http://www.gnu.org/licenses/>. from apispec.ext.marshmallow import", "version 3 of the License, or # (at your option) any later version.", "FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for", "OneOfSchema std_bases.append(OneOfSchema) except ImportError: pass def swaggerinherit_definition_helper(spec, name, schema, definition, **kwargs): \"\"\"Definition helper", "spec before the \" \"child schema\") child_def = definition.copy() for parent in parents:", "published by # the Free Software Foundation, either version 3 of the License,", "or # (at your option) any later version. # This program is distributed", "for Swagger-style # inheritance using `allOf` # Copyright (C) 2018 <NAME> # This", "swagger.get_ref_path(spec.openapi_version.version[0]) try: refs = ['#/{}/{}'.format(ref_path, spec.plugins['apispec.ext.marshmallow']['refs'][schema_cls]) for schema_cls in parents] except KeyError: raise", "child_def['required'] definition.clear() return { 'allOf': [{'$ref': ref} for ref in refs] + [child_def]", "modifies the schema definition to make use of swagger-style inheritance using `allOf`. Uses", "it under the terms of the GNU Lesser General Public License as published", "for b in schema.__bases__ if b not in std_bases] if not parents: return", "added to the spec before the \" \"child schema\") child_def = definition.copy() for", "You should have received a copy of the GNU Lesser General Public License", "redistribute it and/or modify # it under the terms of the GNU Lesser", "`allOf` # Copyright (C) 2018 <NAME> # This program is free software: you", "# (at your option) any later version. # This program is distributed in", "from apispec.ext.marshmallow import swagger from marshmallow import Schema std_bases = [Schema] try: from", "or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public", "parents: for name in parent._declared_fields.keys(): del child_def['properties'][name] try: child_def['required'].remove(name) except ValueError: pass if", "child_def['required']: del child_def['required'] definition.clear() return { 'allOf': [{'$ref': ref} for ref in refs]", "# it under the terms of the GNU Lesser General Public License as", "If not, see <http://www.gnu.org/licenses/>. from apispec.ext.marshmallow import swagger from marshmallow import Schema std_bases", "free software: you can redistribute it and/or modify # it under the terms", "with this program. If not, see <http://www.gnu.org/licenses/>. from apispec.ext.marshmallow import swagger from marshmallow", "import Schema std_bases = [Schema] try: from marshmallow_oneofschema import OneOfSchema std_bases.append(OneOfSchema) except ImportError:", "schemas must be added to the spec before the \" \"child schema\") child_def", "you can redistribute it and/or modify # it under the terms of the", "must be added to the spec before the \" \"child schema\") child_def =", "License for more details. # You should have received a copy of the", "ref_path = swagger.get_ref_path(spec.openapi_version.version[0]) try: refs = ['#/{}/{}'.format(ref_path, spec.plugins['apispec.ext.marshmallow']['refs'][schema_cls]) for schema_cls in parents] except", "details. # You should have received a copy of the GNU Lesser General", "Public License as published by # the Free Software Foundation, either version 3", "parents = [b for b in schema.__bases__ if b not in std_bases] if", "definition.copy() for parent in parents: for name in parent._declared_fields.keys(): del child_def['properties'][name] try: child_def['required'].remove(name)", "import swagger from marshmallow import Schema std_bases = [Schema] try: from marshmallow_oneofschema import", "std_bases = [Schema] try: from marshmallow_oneofschema import OneOfSchema std_bases.append(OneOfSchema) except ImportError: pass def", "\"\"\"Definition helper that modifies the schema definition to make use of swagger-style inheritance", "= [b for b in schema.__bases__ if b not in std_bases] if not", "'allOf': [{'$ref': ref} for ref in refs] + [child_def] } def setup(spec): spec.register_definition_helper(swaggerinherit_definition_helper)", "the Free Software Foundation, either version 3 of the License, or # (at", "try: refs = ['#/{}/{}'.format(ref_path, spec.plugins['apispec.ext.marshmallow']['refs'][schema_cls]) for schema_cls in parents] except KeyError: raise ValueError(\"Parent", "in parents: for name in parent._declared_fields.keys(): del child_def['properties'][name] try: child_def['required'].remove(name) except ValueError: pass", "{ 'allOf': [{'$ref': ref} for ref in refs] + [child_def] } def setup(spec):", "# GNU Lesser General Public License for more details. # You should have", "the `schema` parameter. \"\"\" parents = [b for b in schema.__bases__ if b", "if not child_def['required']: del child_def['required'] definition.clear() return { 'allOf': [{'$ref': ref} for ref", "- Plugin for apispec adding support for Swagger-style # inheritance using `allOf` #", "inheritance using `allOf` # Copyright (C) 2018 <NAME> # This program is free", "is free software: you can redistribute it and/or modify # it under the", "support for Swagger-style # inheritance using `allOf` # Copyright (C) 2018 <NAME> #", "without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR", "except KeyError: raise ValueError(\"Parent schemas must be added to the spec before the", "General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from", "[Schema] try: from marshmallow_oneofschema import OneOfSchema std_bases.append(OneOfSchema) except ImportError: pass def swaggerinherit_definition_helper(spec, name,", "schema_cls in parents] except KeyError: raise ValueError(\"Parent schemas must be added to the", "return { 'allOf': [{'$ref': ref} for ref in refs] + [child_def] } def", "hope that it will be useful, # but WITHOUT ANY WARRANTY; without even", "(at your option) any later version. # This program is distributed in the", "copy of the GNU Lesser General Public License # along with this program.", "the # GNU Lesser General Public License for more details. # You should", "for parent in parents: for name in parent._declared_fields.keys(): del child_def['properties'][name] try: child_def['required'].remove(name) except", "child_def['properties'][name] try: child_def['required'].remove(name) except ValueError: pass if not child_def['required']: del child_def['required'] definition.clear() return", "= ['#/{}/{}'.format(ref_path, spec.plugins['apispec.ext.marshmallow']['refs'][schema_cls]) for schema_cls in parents] except KeyError: raise ValueError(\"Parent schemas must", "name, schema, definition, **kwargs): \"\"\"Definition helper that modifies the schema definition to make", "GNU Lesser General Public License # along with this program. If not, see", "ValueError(\"Parent schemas must be added to the spec before the \" \"child schema\")", "under the terms of the GNU Lesser General Public License as published by", "version. # This program is distributed in the hope that it will be", "from marshmallow import Schema std_bases = [Schema] try: from marshmallow_oneofschema import OneOfSchema std_bases.append(OneOfSchema)", "in std_bases] if not parents: return ref_path = swagger.get_ref_path(spec.openapi_version.version[0]) try: refs = ['#/{}/{}'.format(ref_path,", "see <http://www.gnu.org/licenses/>. from apispec.ext.marshmallow import swagger from marshmallow import Schema std_bases = [Schema]", "of swagger-style inheritance using `allOf`. Uses the `schema` parameter. \"\"\" parents = [b", "[b for b in schema.__bases__ if b not in std_bases] if not parents:", "of the License, or # (at your option) any later version. # This", "program. If not, see <http://www.gnu.org/licenses/>. from apispec.ext.marshmallow import swagger from marshmallow import Schema", "parameter. \"\"\" parents = [b for b in schema.__bases__ if b not in", "= definition.copy() for parent in parents: for name in parent._declared_fields.keys(): del child_def['properties'][name] try:", "marshmallow_oneofschema import OneOfSchema std_bases.append(OneOfSchema) except ImportError: pass def swaggerinherit_definition_helper(spec, name, schema, definition, **kwargs):", "warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #", "in parent._declared_fields.keys(): del child_def['properties'][name] try: child_def['required'].remove(name) except ValueError: pass if not child_def['required']: del", "# along with this program. If not, see <http://www.gnu.org/licenses/>. from apispec.ext.marshmallow import swagger", "# the Free Software Foundation, either version 3 of the License, or #", "# inheritance using `allOf` # Copyright (C) 2018 <NAME> # This program is", "Lesser General Public License for more details. # You should have received a", "a copy of the GNU Lesser General Public License # along with this", "in schema.__bases__ if b not in std_bases] if not parents: return ref_path =", "to the spec before the \" \"child schema\") child_def = definition.copy() for parent", "of the GNU Lesser General Public License # along with this program. If", "the \" \"child schema\") child_def = definition.copy() for parent in parents: for name", "for name in parent._declared_fields.keys(): del child_def['properties'][name] try: child_def['required'].remove(name) except ValueError: pass if not", "<NAME> # This program is free software: you can redistribute it and/or modify", "to make use of swagger-style inheritance using `allOf`. Uses the `schema` parameter. \"\"\"", "Foundation, either version 3 of the License, or # (at your option) any", "the GNU Lesser General Public License as published by # the Free Software", "`schema` parameter. \"\"\" parents = [b for b in schema.__bases__ if b not", "not child_def['required']: del child_def['required'] definition.clear() return { 'allOf': [{'$ref': ref} for ref in", "This program is distributed in the hope that it will be useful, #", "# apispec-swaggerinherit - Plugin for apispec adding support for Swagger-style # inheritance using", "program is free software: you can redistribute it and/or modify # it under", "WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A", "definition to make use of swagger-style inheritance using `allOf`. Uses the `schema` parameter.", "useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of #", "for schema_cls in parents] except KeyError: raise ValueError(\"Parent schemas must be added to", "use of swagger-style inheritance using `allOf`. Uses the `schema` parameter. \"\"\" parents =", "not parents: return ref_path = swagger.get_ref_path(spec.openapi_version.version[0]) try: refs = ['#/{}/{}'.format(ref_path, spec.plugins['apispec.ext.marshmallow']['refs'][schema_cls]) for schema_cls", "apispec-swaggerinherit - Plugin for apispec adding support for Swagger-style # inheritance using `allOf`", "that it will be useful, # but WITHOUT ANY WARRANTY; without even the", "pass if not child_def['required']: del child_def['required'] definition.clear() return { 'allOf': [{'$ref': ref} for", "# This program is free software: you can redistribute it and/or modify #", "refs = ['#/{}/{}'.format(ref_path, spec.plugins['apispec.ext.marshmallow']['refs'][schema_cls]) for schema_cls in parents] except KeyError: raise ValueError(\"Parent schemas", "GNU Lesser General Public License as published by # the Free Software Foundation,", "it and/or modify # it under the terms of the GNU Lesser General", "License as published by # the Free Software Foundation, either version 3 of", "except ImportError: pass def swaggerinherit_definition_helper(spec, name, schema, definition, **kwargs): \"\"\"Definition helper that modifies", "later version. # This program is distributed in the hope that it will", "parent in parents: for name in parent._declared_fields.keys(): del child_def['properties'][name] try: child_def['required'].remove(name) except ValueError:", "PURPOSE. See the # GNU Lesser General Public License for more details. #", "terms of the GNU Lesser General Public License as published by # the", "License, or # (at your option) any later version. # This program is", "as published by # the Free Software Foundation, either version 3 of the", "FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License", "ImportError: pass def swaggerinherit_definition_helper(spec, name, schema, definition, **kwargs): \"\"\"Definition helper that modifies the", "\"\"\" parents = [b for b in schema.__bases__ if b not in std_bases]", "schema.__bases__ if b not in std_bases] if not parents: return ref_path = swagger.get_ref_path(spec.openapi_version.version[0])", "the terms of the GNU Lesser General Public License as published by #", "not in std_bases] if not parents: return ref_path = swagger.get_ref_path(spec.openapi_version.version[0]) try: refs =", "in parents] except KeyError: raise ValueError(\"Parent schemas must be added to the spec", "even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", "your option) any later version. # This program is distributed in the hope", "**kwargs): \"\"\"Definition helper that modifies the schema definition to make use of swagger-style", "# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser", "\" \"child schema\") child_def = definition.copy() for parent in parents: for name in", "swagger from marshmallow import Schema std_bases = [Schema] try: from marshmallow_oneofschema import OneOfSchema", "Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>.", "implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the", "ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR", "and/or modify # it under the terms of the GNU Lesser General Public", "Public License for more details. # You should have received a copy of", "parent._declared_fields.keys(): del child_def['properties'][name] try: child_def['required'].remove(name) except ValueError: pass if not child_def['required']: del child_def['required']", "definition, **kwargs): \"\"\"Definition helper that modifies the schema definition to make use of", "it will be useful, # but WITHOUT ANY WARRANTY; without even the implied", "received a copy of the GNU Lesser General Public License # along with", "Schema std_bases = [Schema] try: from marshmallow_oneofschema import OneOfSchema std_bases.append(OneOfSchema) except ImportError: pass", "WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS", "the hope that it will be useful, # but WITHOUT ANY WARRANTY; without", "swagger-style inheritance using `allOf`. Uses the `schema` parameter. \"\"\" parents = [b for", "b not in std_bases] if not parents: return ref_path = swagger.get_ref_path(spec.openapi_version.version[0]) try: refs", "['#/{}/{}'.format(ref_path, spec.plugins['apispec.ext.marshmallow']['refs'][schema_cls]) for schema_cls in parents] except KeyError: raise ValueError(\"Parent schemas must be", "del child_def['required'] definition.clear() return { 'allOf': [{'$ref': ref} for ref in refs] +", "that modifies the schema definition to make use of swagger-style inheritance using `allOf`.", "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General", "the GNU Lesser General Public License # along with this program. If not,", "std_bases] if not parents: return ref_path = swagger.get_ref_path(spec.openapi_version.version[0]) try: refs = ['#/{}/{}'.format(ref_path, spec.plugins['apispec.ext.marshmallow']['refs'][schema_cls])", "<http://www.gnu.org/licenses/>. from apispec.ext.marshmallow import swagger from marshmallow import Schema std_bases = [Schema] try:", "parents: return ref_path = swagger.get_ref_path(spec.openapi_version.version[0]) try: refs = ['#/{}/{}'.format(ref_path, spec.plugins['apispec.ext.marshmallow']['refs'][schema_cls]) for schema_cls in", "should have received a copy of the GNU Lesser General Public License #", "# You should have received a copy of the GNU Lesser General Public", "schema definition to make use of swagger-style inheritance using `allOf`. Uses the `schema`", "any later version. # This program is distributed in the hope that it", "See the # GNU Lesser General Public License for more details. # You", "GNU Lesser General Public License for more details. # You should have received", "for more details. # You should have received a copy of the GNU", "be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of", "spec.plugins['apispec.ext.marshmallow']['refs'][schema_cls]) for schema_cls in parents] except KeyError: raise ValueError(\"Parent schemas must be added", "the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See", "PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details.", "\"child schema\") child_def = definition.copy() for parent in parents: for name in parent._declared_fields.keys():", "try: child_def['required'].remove(name) except ValueError: pass if not child_def['required']: del child_def['required'] definition.clear() return {", "the License, or # (at your option) any later version. # This program", "Uses the `schema` parameter. \"\"\" parents = [b for b in schema.__bases__ if", "2018 <NAME> # This program is free software: you can redistribute it and/or", "for apispec adding support for Swagger-style # inheritance using `allOf` # Copyright (C)", "child_def['required'].remove(name) except ValueError: pass if not child_def['required']: del child_def['required'] definition.clear() return { 'allOf':", "if not parents: return ref_path = swagger.get_ref_path(spec.openapi_version.version[0]) try: refs = ['#/{}/{}'.format(ref_path, spec.plugins['apispec.ext.marshmallow']['refs'][schema_cls]) for", "have received a copy of the GNU Lesser General Public License # along", "the spec before the \" \"child schema\") child_def = definition.copy() for parent in", "modify # it under the terms of the GNU Lesser General Public License", "schema, definition, **kwargs): \"\"\"Definition helper that modifies the schema definition to make use", "is distributed in the hope that it will be useful, # but WITHOUT", "adding support for Swagger-style # inheritance using `allOf` # Copyright (C) 2018 <NAME>", "def swaggerinherit_definition_helper(spec, name, schema, definition, **kwargs): \"\"\"Definition helper that modifies the schema definition", "swaggerinherit_definition_helper(spec, name, schema, definition, **kwargs): \"\"\"Definition helper that modifies the schema definition to", "parents] except KeyError: raise ValueError(\"Parent schemas must be added to the spec before", "using `allOf` # Copyright (C) 2018 <NAME> # This program is free software:", "import OneOfSchema std_bases.append(OneOfSchema) except ImportError: pass def swaggerinherit_definition_helper(spec, name, schema, definition, **kwargs): \"\"\"Definition", "inheritance using `allOf`. Uses the `schema` parameter. \"\"\" parents = [b for b", "in the hope that it will be useful, # but WITHOUT ANY WARRANTY;", "General Public License for more details. # You should have received a copy", "the schema definition to make use of swagger-style inheritance using `allOf`. Uses the", "if b not in std_bases] if not parents: return ref_path = swagger.get_ref_path(spec.openapi_version.version[0]) try:", "# Copyright (C) 2018 <NAME> # This program is free software: you can", "along with this program. If not, see <http://www.gnu.org/licenses/>. from apispec.ext.marshmallow import swagger from", "This program is free software: you can redistribute it and/or modify # it", "raise ValueError(\"Parent schemas must be added to the spec before the \" \"child", "b in schema.__bases__ if b not in std_bases] if not parents: return ref_path", "ValueError: pass if not child_def['required']: del child_def['required'] definition.clear() return { 'allOf': [{'$ref': ref}", "3 of the License, or # (at your option) any later version. #", "of the GNU Lesser General Public License as published by # the Free", "this program. If not, see <http://www.gnu.org/licenses/>. from apispec.ext.marshmallow import swagger from marshmallow import", "apispec.ext.marshmallow import swagger from marshmallow import Schema std_bases = [Schema] try: from marshmallow_oneofschema", "marshmallow import Schema std_bases = [Schema] try: from marshmallow_oneofschema import OneOfSchema std_bases.append(OneOfSchema) except", "definition.clear() return { 'allOf': [{'$ref': ref} for ref in refs] + [child_def] }", "schema\") child_def = definition.copy() for parent in parents: for name in parent._declared_fields.keys(): del", "Copyright (C) 2018 <NAME> # This program is free software: you can redistribute", "`allOf`. Uses the `schema` parameter. \"\"\" parents = [b for b in schema.__bases__", "pass def swaggerinherit_definition_helper(spec, name, schema, definition, **kwargs): \"\"\"Definition helper that modifies the schema", "del child_def['properties'][name] try: child_def['required'].remove(name) except ValueError: pass if not child_def['required']: del child_def['required'] definition.clear()", "from marshmallow_oneofschema import OneOfSchema std_bases.append(OneOfSchema) except ImportError: pass def swaggerinherit_definition_helper(spec, name, schema, definition,", "option) any later version. # This program is distributed in the hope that", "more details. # You should have received a copy of the GNU Lesser", "helper that modifies the schema definition to make use of swagger-style inheritance using", "will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty", "= swagger.get_ref_path(spec.openapi_version.version[0]) try: refs = ['#/{}/{}'.format(ref_path, spec.plugins['apispec.ext.marshmallow']['refs'][schema_cls]) for schema_cls in parents] except KeyError:", "A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more", "General Public License as published by # the Free Software Foundation, either version", "apispec adding support for Swagger-style # inheritance using `allOf` # Copyright (C) 2018", "software: you can redistribute it and/or modify # it under the terms of", "return ref_path = swagger.get_ref_path(spec.openapi_version.version[0]) try: refs = ['#/{}/{}'.format(ref_path, spec.plugins['apispec.ext.marshmallow']['refs'][schema_cls]) for schema_cls in parents]", "try: from marshmallow_oneofschema import OneOfSchema std_bases.append(OneOfSchema) except ImportError: pass def swaggerinherit_definition_helper(spec, name, schema,", "child_def = definition.copy() for parent in parents: for name in parent._declared_fields.keys(): del child_def['properties'][name]", "= [Schema] try: from marshmallow_oneofschema import OneOfSchema std_bases.append(OneOfSchema) except ImportError: pass def swaggerinherit_definition_helper(spec,", "make use of swagger-style inheritance using `allOf`. Uses the `schema` parameter. \"\"\" parents", "of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU", "not, see <http://www.gnu.org/licenses/>. from apispec.ext.marshmallow import swagger from marshmallow import Schema std_bases =", "Lesser General Public License as published by # the Free Software Foundation, either", "be added to the spec before the \" \"child schema\") child_def = definition.copy()", "# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY", "Swagger-style # inheritance using `allOf` # Copyright (C) 2018 <NAME> # This program", "can redistribute it and/or modify # it under the terms of the GNU", "Free Software Foundation, either version 3 of the License, or # (at your", "Software Foundation, either version 3 of the License, or # (at your option)", "Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from apispec.ext.marshmallow", "Plugin for apispec adding support for Swagger-style # inheritance using `allOf` # Copyright", "program is distributed in the hope that it will be useful, # but", "# This program is distributed in the hope that it will be useful,", "KeyError: raise ValueError(\"Parent schemas must be added to the spec before the \"", "but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or" ]
[ "meta.bind = migrate_engine t = Table(\"demographics_request_column_definition\", meta, autoload=True) uhl_system_number_column_id = Column(\"uhl_system_number_column_id\", Integer) uhl_system_number_column_id.create(t)", "upgrade(migrate_engine): meta.bind = migrate_engine t = Table(\"demographics_request_column_definition\", meta, autoload=True) uhl_system_number_column_id = Column(\"uhl_system_number_column_id\", Integer)", "( MetaData, Table, Column, Integer, ) meta = MetaData() def upgrade(migrate_engine): meta.bind =", "= migrate_engine t = Table(\"demographics_request_column_definition\", meta, autoload=True) uhl_system_number_column_id = Column(\"uhl_system_number_column_id\", Integer) uhl_system_number_column_id.create(t) def", "MetaData, Table, Column, Integer, ) meta = MetaData() def upgrade(migrate_engine): meta.bind = migrate_engine", "= Table(\"demographics_request_column_definition\", meta, autoload=True) uhl_system_number_column_id = Column(\"uhl_system_number_column_id\", Integer) uhl_system_number_column_id.create(t) def downgrade(migrate_engine): meta.bind =", "Column(\"uhl_system_number_column_id\", Integer) uhl_system_number_column_id.create(t) def downgrade(migrate_engine): meta.bind = migrate_engine t = Table(\"demographics_request_column_definition\", meta, autoload=True)", "= MetaData() def upgrade(migrate_engine): meta.bind = migrate_engine t = Table(\"demographics_request_column_definition\", meta, autoload=True) uhl_system_number_column_id", "autoload=True) uhl_system_number_column_id = Column(\"uhl_system_number_column_id\", Integer) uhl_system_number_column_id.create(t) def downgrade(migrate_engine): meta.bind = migrate_engine t =", "from sqlalchemy import ( MetaData, Table, Column, Integer, ) meta = MetaData() def", "Column, Integer, ) meta = MetaData() def upgrade(migrate_engine): meta.bind = migrate_engine t =", "MetaData() def upgrade(migrate_engine): meta.bind = migrate_engine t = Table(\"demographics_request_column_definition\", meta, autoload=True) uhl_system_number_column_id =", "def upgrade(migrate_engine): meta.bind = migrate_engine t = Table(\"demographics_request_column_definition\", meta, autoload=True) uhl_system_number_column_id = Column(\"uhl_system_number_column_id\",", "Table(\"demographics_request_column_definition\", meta, autoload=True) uhl_system_number_column_id = Column(\"uhl_system_number_column_id\", Integer) uhl_system_number_column_id.create(t) def downgrade(migrate_engine): meta.bind = migrate_engine", "uhl_system_number_column_id = Column(\"uhl_system_number_column_id\", Integer) uhl_system_number_column_id.create(t) def downgrade(migrate_engine): meta.bind = migrate_engine t = Table(\"demographics_request_column_definition\",", "import ( MetaData, Table, Column, Integer, ) meta = MetaData() def upgrade(migrate_engine): meta.bind", "Table, Column, Integer, ) meta = MetaData() def upgrade(migrate_engine): meta.bind = migrate_engine t", "Integer) uhl_system_number_column_id.create(t) def downgrade(migrate_engine): meta.bind = migrate_engine t = Table(\"demographics_request_column_definition\", meta, autoload=True) t.c.uhl_system_number_column_id.drop()", "t = Table(\"demographics_request_column_definition\", meta, autoload=True) uhl_system_number_column_id = Column(\"uhl_system_number_column_id\", Integer) uhl_system_number_column_id.create(t) def downgrade(migrate_engine): meta.bind", "= Column(\"uhl_system_number_column_id\", Integer) uhl_system_number_column_id.create(t) def downgrade(migrate_engine): meta.bind = migrate_engine t = Table(\"demographics_request_column_definition\", meta,", "Integer, ) meta = MetaData() def upgrade(migrate_engine): meta.bind = migrate_engine t = Table(\"demographics_request_column_definition\",", "sqlalchemy import ( MetaData, Table, Column, Integer, ) meta = MetaData() def upgrade(migrate_engine):", "meta = MetaData() def upgrade(migrate_engine): meta.bind = migrate_engine t = Table(\"demographics_request_column_definition\", meta, autoload=True)", "<gh_stars>0 from sqlalchemy import ( MetaData, Table, Column, Integer, ) meta = MetaData()", ") meta = MetaData() def upgrade(migrate_engine): meta.bind = migrate_engine t = Table(\"demographics_request_column_definition\", meta,", "migrate_engine t = Table(\"demographics_request_column_definition\", meta, autoload=True) uhl_system_number_column_id = Column(\"uhl_system_number_column_id\", Integer) uhl_system_number_column_id.create(t) def downgrade(migrate_engine):", "meta, autoload=True) uhl_system_number_column_id = Column(\"uhl_system_number_column_id\", Integer) uhl_system_number_column_id.create(t) def downgrade(migrate_engine): meta.bind = migrate_engine t" ]
[ "supported *'): spider.soccer.teams(country, league) @pytest.mark.parametrize('country,league', competitions.items()) def test_setattr_competiton(self, spider, country, league): spider.soccer._setattr_competiton(country, league)", "'england': 'premier_league', 'italy': 'serie_a', 'spain': 'la_liga', } def test_countries(self, spider): countries = spider.soccer.countries()", "def test_teams(self, spider, country, league): teams = spider.soccer.teams(country, league) assert isinstance(teams, list) @pytest.mark.parametrize('country,league',", "assert self.competitions[country] in leagues.keys() assert isinstance(leagues, dict) def test_league_not_supported(self, spider): country = 'foo_country'", "@pytest.mark.parametrize('country,league', competitions.items()) def test_setattr_competiton(self, spider, country, league): spider.soccer._setattr_competiton(country, league) assert spider.soccer._country assert spider.soccer.country", "@pytest.mark.parametrize( 'country,league', [next(iter(competitions.items()))]) def test_events(self, spider, country, league): events = spider.soccer.events(country, league) assert", "= spider.soccer.teams(country, league) assert isinstance(teams, list) @pytest.mark.parametrize('country,league', competitions.items()) def test_teams_full(self, spider, country, league):", "= spider.soccer.odds(country, league) assert isinstance(events, list) assert events assert isinstance(odds, list) assert odds", "competitions.keys()) def test_leagues(self, spider, country): leagues = spider.soccer.leagues(country) assert self.competitions[country] in leagues assert", "country, league): events, odds = spider.soccer.odds(country, league) assert isinstance(events, list) assert events assert", "def test_teams_full(self, spider, country, league): teams = spider.soccer.teams(country, league, full=True) assert isinstance(teams, dict)", "country, league = 'serie_a', 'foo_league' with pytest.raises(KeyError, match=f'{league} is not supported *'): spider.soccer.teams(country,", "test_league_not_supported(self, spider): country = 'foo_country' with pytest.raises(KeyError, match=f'{country} is not supported *'): spider.soccer.leagues(country)", "test_countries_full(self, spider): countries = spider.soccer.countries(full=True) assert set(self.competitions.keys()) <= set(countries.keys()) assert isinstance(countries, dict) @pytest.mark.parametrize('country',", "spider): countries = spider.soccer.countries(full=True) assert set(self.competitions.keys()) <= set(countries.keys()) assert isinstance(countries, dict) @pytest.mark.parametrize('country', competitions.keys())", "from aao.spiders import spiders pytestmark = pytest.mark.sports class TestSport(): \"\"\"Nothing to test. \"\"\"", "\"\"\"Nothing to test. \"\"\" pass class TestSoccer(): \"\"\"Test the Soccer ABC across all", "list) @pytest.mark.parametrize('country', competitions.keys()) def test_leagues_full(self, spider, country): leagues = spider.soccer.leagues(country, full=True) assert self.competitions[country]", "spider.soccer.countries(full=True) assert set(self.competitions.keys()) <= set(countries.keys()) assert isinstance(countries, dict) @pytest.mark.parametrize('country', competitions.keys()) def test_leagues(self, spider,", "def test_leagues(self, spider, country): leagues = spider.soccer.leagues(country) assert self.competitions[country] in leagues assert isinstance(leagues,", "spider, country): leagues = spider.soccer.leagues(country) assert self.competitions[country] in leagues assert isinstance(leagues, list) @pytest.mark.parametrize('country',", "request.param() yield s s.quit() competitions = { 'england': 'premier_league', 'italy': 'serie_a', 'spain': 'la_liga',", "spider.soccer.teams(country, league) assert isinstance(teams, list) @pytest.mark.parametrize('country,league', competitions.items()) def test_teams_full(self, spider, country, league): teams", "competitions.items()) def test_setattr_competiton(self, spider, country, league): spider.soccer._setattr_competiton(country, league) assert spider.soccer._country assert spider.soccer.country assert", "= pytest.mark.sports class TestSport(): \"\"\"Nothing to test. \"\"\" pass class TestSoccer(): \"\"\"Test the", "match=f'{country} is not supported *'): spider.soccer.leagues(country) @pytest.mark.parametrize('country,league', competitions.items()) def test_teams(self, spider, country, league):", "= spider.soccer.countries() assert set(self.competitions.keys()) <= set(countries) assert isinstance(countries, list) def test_countries_full(self, spider): countries", "assert spider.soccer._league assert spider.soccer.league @pytest.mark.parametrize( 'country,league', [next(iter(competitions.items()))]) def test_events(self, spider, country, league): events", "events @pytest.mark.parametrize( 'country,league', [next(iter(competitions.items()))]) def test_odds(self, spider, country, league): events, odds = spider.soccer.odds(country,", "'premier_league', 'italy': 'serie_a', 'spain': 'la_liga', } def test_countries(self, spider): countries = spider.soccer.countries() assert", "league) assert isinstance(teams, list) @pytest.mark.parametrize('country,league', competitions.items()) def test_teams_full(self, spider, country, league): teams =", "spider): country, league = 'serie_a', 'foo_league' with pytest.raises(KeyError, match=f'{league} is not supported *'):", "= request.param() yield s s.quit() competitions = { 'england': 'premier_league', 'italy': 'serie_a', 'spain':", "assert isinstance(leagues, list) @pytest.mark.parametrize('country', competitions.keys()) def test_leagues_full(self, spider, country): leagues = spider.soccer.leagues(country, full=True)", "spider, country, league): events = spider.soccer.events(country, league) assert isinstance(events, list) assert events @pytest.mark.parametrize(", "to test. \"\"\" pass class TestSoccer(): \"\"\"Test the Soccer ABC across all bookmakers.", "spider, country, league): teams = spider.soccer.teams(country, league) assert isinstance(teams, list) @pytest.mark.parametrize('country,league', competitions.items()) def", "spider.soccer._league assert spider.soccer.league @pytest.mark.parametrize( 'country,league', [next(iter(competitions.items()))]) def test_events(self, spider, country, league): events =", "dict) def test_teams_not_supported(self, spider): country, league = 'serie_a', 'foo_league' with pytest.raises(KeyError, match=f'{league} is", "full=True) assert self.competitions[country] in leagues.keys() assert isinstance(leagues, dict) def test_league_not_supported(self, spider): country =", "supported *'): spider.soccer.leagues(country) @pytest.mark.parametrize('country,league', competitions.items()) def test_teams(self, spider, country, league): teams = spider.soccer.teams(country,", "spider, country, league): teams = spider.soccer.teams(country, league, full=True) assert isinstance(teams, dict) def test_teams_not_supported(self,", "test_events(self, spider, country, league): events = spider.soccer.events(country, league) assert isinstance(events, list) assert events", "spider.soccer.countries() assert set(self.competitions.keys()) <= set(countries) assert isinstance(countries, list) def test_countries_full(self, spider): countries =", "leagues = spider.soccer.leagues(country) assert self.competitions[country] in leagues assert isinstance(leagues, list) @pytest.mark.parametrize('country', competitions.keys()) def", "} def test_countries(self, spider): countries = spider.soccer.countries() assert set(self.competitions.keys()) <= set(countries) assert isinstance(countries,", "competitions.keys()) def test_leagues_full(self, spider, country): leagues = spider.soccer.leagues(country, full=True) assert self.competitions[country] in leagues.keys()", "test_setattr_competiton(self, spider, country, league): spider.soccer._setattr_competiton(country, league) assert spider.soccer._country assert spider.soccer.country assert spider.soccer._league assert", "set(self.competitions.keys()) <= set(countries) assert isinstance(countries, list) def test_countries_full(self, spider): countries = spider.soccer.countries(full=True) assert", "def spider(self, request): s = request.param() yield s s.quit() competitions = { 'england':", "not supported *'): spider.soccer.teams(country, league) @pytest.mark.parametrize('country,league', competitions.items()) def test_setattr_competiton(self, spider, country, league): spider.soccer._setattr_competiton(country,", "bookmakers. \"\"\" @pytest.fixture(scope='class', params=spiders.values()) def spider(self, request): s = request.param() yield s s.quit()", "assert isinstance(countries, dict) @pytest.mark.parametrize('country', competitions.keys()) def test_leagues(self, spider, country): leagues = spider.soccer.leagues(country) assert", "isinstance(events, list) assert events @pytest.mark.parametrize( 'country,league', [next(iter(competitions.items()))]) def test_odds(self, spider, country, league): events,", "set(countries) assert isinstance(countries, list) def test_countries_full(self, spider): countries = spider.soccer.countries(full=True) assert set(self.competitions.keys()) <=", "pytest.raises(KeyError, match=f'{country} is not supported *'): spider.soccer.leagues(country) @pytest.mark.parametrize('country,league', competitions.items()) def test_teams(self, spider, country,", "class TestSport(): \"\"\"Nothing to test. \"\"\" pass class TestSoccer(): \"\"\"Test the Soccer ABC", "league) assert spider.soccer._country assert spider.soccer.country assert spider.soccer._league assert spider.soccer.league @pytest.mark.parametrize( 'country,league', [next(iter(competitions.items()))]) def", "@pytest.mark.parametrize('country', competitions.keys()) def test_leagues_full(self, spider, country): leagues = spider.soccer.leagues(country, full=True) assert self.competitions[country] in", "assert set(self.competitions.keys()) <= set(countries) assert isinstance(countries, list) def test_countries_full(self, spider): countries = spider.soccer.countries(full=True)", "isinstance(countries, dict) @pytest.mark.parametrize('country', competitions.keys()) def test_leagues(self, spider, country): leagues = spider.soccer.leagues(country) assert self.competitions[country]", "spiders pytestmark = pytest.mark.sports class TestSport(): \"\"\"Nothing to test. \"\"\" pass class TestSoccer():", "def test_countries(self, spider): countries = spider.soccer.countries() assert set(self.competitions.keys()) <= set(countries) assert isinstance(countries, list)", "<= set(countries.keys()) assert isinstance(countries, dict) @pytest.mark.parametrize('country', competitions.keys()) def test_leagues(self, spider, country): leagues =", "spider): country = 'foo_country' with pytest.raises(KeyError, match=f'{country} is not supported *'): spider.soccer.leagues(country) @pytest.mark.parametrize('country,league',", "TestSoccer(): \"\"\"Test the Soccer ABC across all bookmakers. \"\"\" @pytest.fixture(scope='class', params=spiders.values()) def spider(self,", "test. \"\"\" pass class TestSoccer(): \"\"\"Test the Soccer ABC across all bookmakers. \"\"\"", "set(self.competitions.keys()) <= set(countries.keys()) assert isinstance(countries, dict) @pytest.mark.parametrize('country', competitions.keys()) def test_leagues(self, spider, country): leagues", "= 'serie_a', 'foo_league' with pytest.raises(KeyError, match=f'{league} is not supported *'): spider.soccer.teams(country, league) @pytest.mark.parametrize('country,league',", "<= set(countries) assert isinstance(countries, list) def test_countries_full(self, spider): countries = spider.soccer.countries(full=True) assert set(self.competitions.keys())", "= spider.soccer.teams(country, league, full=True) assert isinstance(teams, dict) def test_teams_not_supported(self, spider): country, league =", "spider.soccer.events(country, league) assert isinstance(events, list) assert events @pytest.mark.parametrize( 'country,league', [next(iter(competitions.items()))]) def test_odds(self, spider,", "country = 'foo_country' with pytest.raises(KeyError, match=f'{country} is not supported *'): spider.soccer.leagues(country) @pytest.mark.parametrize('country,league', competitions.items())", "def test_events(self, spider, country, league): events = spider.soccer.events(country, league) assert isinstance(events, list) assert", "import spiders pytestmark = pytest.mark.sports class TestSport(): \"\"\"Nothing to test. \"\"\" pass class", "s s.quit() competitions = { 'england': 'premier_league', 'italy': 'serie_a', 'spain': 'la_liga', } def", "@pytest.mark.parametrize('country', competitions.keys()) def test_leagues(self, spider, country): leagues = spider.soccer.leagues(country) assert self.competitions[country] in leagues", "isinstance(teams, dict) def test_teams_not_supported(self, spider): country, league = 'serie_a', 'foo_league' with pytest.raises(KeyError, match=f'{league}", "country): leagues = spider.soccer.leagues(country, full=True) assert self.competitions[country] in leagues.keys() assert isinstance(leagues, dict) def", "assert isinstance(teams, list) @pytest.mark.parametrize('country,league', competitions.items()) def test_teams_full(self, spider, country, league): teams = spider.soccer.teams(country,", "'italy': 'serie_a', 'spain': 'la_liga', } def test_countries(self, spider): countries = spider.soccer.countries() assert set(self.competitions.keys())", "league): teams = spider.soccer.teams(country, league, full=True) assert isinstance(teams, dict) def test_teams_not_supported(self, spider): country,", "leagues assert isinstance(leagues, list) @pytest.mark.parametrize('country', competitions.keys()) def test_leagues_full(self, spider, country): leagues = spider.soccer.leagues(country,", "assert isinstance(teams, dict) def test_teams_not_supported(self, spider): country, league = 'serie_a', 'foo_league' with pytest.raises(KeyError,", "pytest.mark.sports class TestSport(): \"\"\"Nothing to test. \"\"\" pass class TestSoccer(): \"\"\"Test the Soccer", "request): s = request.param() yield s s.quit() competitions = { 'england': 'premier_league', 'italy':", "pytest.raises(KeyError, match=f'{league} is not supported *'): spider.soccer.teams(country, league) @pytest.mark.parametrize('country,league', competitions.items()) def test_setattr_competiton(self, spider,", "spider.soccer.leagues(country, full=True) assert self.competitions[country] in leagues.keys() assert isinstance(leagues, dict) def test_league_not_supported(self, spider): country", "*'): spider.soccer.leagues(country) @pytest.mark.parametrize('country,league', competitions.items()) def test_teams(self, spider, country, league): teams = spider.soccer.teams(country, league)", "assert spider.soccer.league @pytest.mark.parametrize( 'country,league', [next(iter(competitions.items()))]) def test_events(self, spider, country, league): events = spider.soccer.events(country,", "'spain': 'la_liga', } def test_countries(self, spider): countries = spider.soccer.countries() assert set(self.competitions.keys()) <= set(countries)", "assert isinstance(countries, list) def test_countries_full(self, spider): countries = spider.soccer.countries(full=True) assert set(self.competitions.keys()) <= set(countries.keys())", "teams = spider.soccer.teams(country, league, full=True) assert isinstance(teams, dict) def test_teams_not_supported(self, spider): country, league", "params=spiders.values()) def spider(self, request): s = request.param() yield s s.quit() competitions = {", "spider.soccer._setattr_competiton(country, league) assert spider.soccer._country assert spider.soccer.country assert spider.soccer._league assert spider.soccer.league @pytest.mark.parametrize( 'country,league', [next(iter(competitions.items()))])", "spider.soccer.country assert spider.soccer._league assert spider.soccer.league @pytest.mark.parametrize( 'country,league', [next(iter(competitions.items()))]) def test_events(self, spider, country, league):", "spider, country, league): events, odds = spider.soccer.odds(country, league) assert isinstance(events, list) assert events", "spider.soccer.teams(country, league) @pytest.mark.parametrize('country,league', competitions.items()) def test_setattr_competiton(self, spider, country, league): spider.soccer._setattr_competiton(country, league) assert spider.soccer._country", "\"\"\" @pytest.fixture(scope='class', params=spiders.values()) def spider(self, request): s = request.param() yield s s.quit() competitions", "country, league): events = spider.soccer.events(country, league) assert isinstance(events, list) assert events @pytest.mark.parametrize( 'country,league',", "test_leagues(self, spider, country): leagues = spider.soccer.leagues(country) assert self.competitions[country] in leagues assert isinstance(leagues, list)", "full=True) assert isinstance(teams, dict) def test_teams_not_supported(self, spider): country, league = 'serie_a', 'foo_league' with", "Soccer ABC across all bookmakers. \"\"\" @pytest.fixture(scope='class', params=spiders.values()) def spider(self, request): s =", "country): leagues = spider.soccer.leagues(country) assert self.competitions[country] in leagues assert isinstance(leagues, list) @pytest.mark.parametrize('country', competitions.keys())", "all bookmakers. \"\"\" @pytest.fixture(scope='class', params=spiders.values()) def spider(self, request): s = request.param() yield s", "yield s s.quit() competitions = { 'england': 'premier_league', 'italy': 'serie_a', 'spain': 'la_liga', }", "teams = spider.soccer.teams(country, league) assert isinstance(teams, list) @pytest.mark.parametrize('country,league', competitions.items()) def test_teams_full(self, spider, country,", "league) assert isinstance(events, list) assert events @pytest.mark.parametrize( 'country,league', [next(iter(competitions.items()))]) def test_odds(self, spider, country,", "events, odds = spider.soccer.odds(country, league) assert isinstance(events, list) assert events assert isinstance(odds, list)", "test_teams_full(self, spider, country, league): teams = spider.soccer.teams(country, league, full=True) assert isinstance(teams, dict) def", "= spider.soccer.countries(full=True) assert set(self.competitions.keys()) <= set(countries.keys()) assert isinstance(countries, dict) @pytest.mark.parametrize('country', competitions.keys()) def test_leagues(self,", "competitions.items()) def test_teams(self, spider, country, league): teams = spider.soccer.teams(country, league) assert isinstance(teams, list)", "with pytest.raises(KeyError, match=f'{league} is not supported *'): spider.soccer.teams(country, league) @pytest.mark.parametrize('country,league', competitions.items()) def test_setattr_competiton(self,", "import pytest from aao.spiders import spiders pytestmark = pytest.mark.sports class TestSport(): \"\"\"Nothing to", "aao.spiders import spiders pytestmark = pytest.mark.sports class TestSport(): \"\"\"Nothing to test. \"\"\" pass", "league): events, odds = spider.soccer.odds(country, league) assert isinstance(events, list) assert events assert isinstance(odds,", "list) def test_countries_full(self, spider): countries = spider.soccer.countries(full=True) assert set(self.competitions.keys()) <= set(countries.keys()) assert isinstance(countries,", "\"\"\"Test the Soccer ABC across all bookmakers. \"\"\" @pytest.fixture(scope='class', params=spiders.values()) def spider(self, request):", "spider.soccer.league @pytest.mark.parametrize( 'country,league', [next(iter(competitions.items()))]) def test_events(self, spider, country, league): events = spider.soccer.events(country, league)", "countries = spider.soccer.countries() assert set(self.competitions.keys()) <= set(countries) assert isinstance(countries, list) def test_countries_full(self, spider):", "countries = spider.soccer.countries(full=True) assert set(self.competitions.keys()) <= set(countries.keys()) assert isinstance(countries, dict) @pytest.mark.parametrize('country', competitions.keys()) def", "league): events = spider.soccer.events(country, league) assert isinstance(events, list) assert events @pytest.mark.parametrize( 'country,league', [next(iter(competitions.items()))])", "the Soccer ABC across all bookmakers. \"\"\" @pytest.fixture(scope='class', params=spiders.values()) def spider(self, request): s", "spider.soccer.teams(country, league, full=True) assert isinstance(teams, dict) def test_teams_not_supported(self, spider): country, league = 'serie_a',", "'la_liga', } def test_countries(self, spider): countries = spider.soccer.countries() assert set(self.competitions.keys()) <= set(countries) assert", "isinstance(leagues, dict) def test_league_not_supported(self, spider): country = 'foo_country' with pytest.raises(KeyError, match=f'{country} is not", "self.competitions[country] in leagues assert isinstance(leagues, list) @pytest.mark.parametrize('country', competitions.keys()) def test_leagues_full(self, spider, country): leagues", "def test_league_not_supported(self, spider): country = 'foo_country' with pytest.raises(KeyError, match=f'{country} is not supported *'):", "= 'foo_country' with pytest.raises(KeyError, match=f'{country} is not supported *'): spider.soccer.leagues(country) @pytest.mark.parametrize('country,league', competitions.items()) def", "spider.soccer._country assert spider.soccer.country assert spider.soccer._league assert spider.soccer.league @pytest.mark.parametrize( 'country,league', [next(iter(competitions.items()))]) def test_events(self, spider,", "competitions = { 'england': 'premier_league', 'italy': 'serie_a', 'spain': 'la_liga', } def test_countries(self, spider):", "@pytest.mark.parametrize('country,league', competitions.items()) def test_teams_full(self, spider, country, league): teams = spider.soccer.teams(country, league, full=True) assert", "pytestmark = pytest.mark.sports class TestSport(): \"\"\"Nothing to test. \"\"\" pass class TestSoccer(): \"\"\"Test", "= { 'england': 'premier_league', 'italy': 'serie_a', 'spain': 'la_liga', } def test_countries(self, spider): countries", "dict) @pytest.mark.parametrize('country', competitions.keys()) def test_leagues(self, spider, country): leagues = spider.soccer.leagues(country) assert self.competitions[country] in", "spider(self, request): s = request.param() yield s s.quit() competitions = { 'england': 'premier_league',", "'serie_a', 'spain': 'la_liga', } def test_countries(self, spider): countries = spider.soccer.countries() assert set(self.competitions.keys()) <=", "isinstance(countries, list) def test_countries_full(self, spider): countries = spider.soccer.countries(full=True) assert set(self.competitions.keys()) <= set(countries.keys()) assert", "'country,league', [next(iter(competitions.items()))]) def test_events(self, spider, country, league): events = spider.soccer.events(country, league) assert isinstance(events,", "league = 'serie_a', 'foo_league' with pytest.raises(KeyError, match=f'{league} is not supported *'): spider.soccer.teams(country, league)", "assert self.competitions[country] in leagues assert isinstance(leagues, list) @pytest.mark.parametrize('country', competitions.keys()) def test_leagues_full(self, spider, country):", "isinstance(teams, list) @pytest.mark.parametrize('country,league', competitions.items()) def test_teams_full(self, spider, country, league): teams = spider.soccer.teams(country, league,", "not supported *'): spider.soccer.leagues(country) @pytest.mark.parametrize('country,league', competitions.items()) def test_teams(self, spider, country, league): teams =", "pytest from aao.spiders import spiders pytestmark = pytest.mark.sports class TestSport(): \"\"\"Nothing to test.", "with pytest.raises(KeyError, match=f'{country} is not supported *'): spider.soccer.leagues(country) @pytest.mark.parametrize('country,league', competitions.items()) def test_teams(self, spider,", "across all bookmakers. \"\"\" @pytest.fixture(scope='class', params=spiders.values()) def spider(self, request): s = request.param() yield", "leagues.keys() assert isinstance(leagues, dict) def test_league_not_supported(self, spider): country = 'foo_country' with pytest.raises(KeyError, match=f'{country}", "spider, country, league): spider.soccer._setattr_competiton(country, league) assert spider.soccer._country assert spider.soccer.country assert spider.soccer._league assert spider.soccer.league", "\"\"\" pass class TestSoccer(): \"\"\"Test the Soccer ABC across all bookmakers. \"\"\" @pytest.fixture(scope='class',", "pass class TestSoccer(): \"\"\"Test the Soccer ABC across all bookmakers. \"\"\" @pytest.fixture(scope='class', params=spiders.values())", "set(countries.keys()) assert isinstance(countries, dict) @pytest.mark.parametrize('country', competitions.keys()) def test_leagues(self, spider, country): leagues = spider.soccer.leagues(country)", "assert isinstance(leagues, dict) def test_league_not_supported(self, spider): country = 'foo_country' with pytest.raises(KeyError, match=f'{country} is", "is not supported *'): spider.soccer.leagues(country) @pytest.mark.parametrize('country,league', competitions.items()) def test_teams(self, spider, country, league): teams", "ABC across all bookmakers. \"\"\" @pytest.fixture(scope='class', params=spiders.values()) def spider(self, request): s = request.param()", "spider.soccer.leagues(country) assert self.competitions[country] in leagues assert isinstance(leagues, list) @pytest.mark.parametrize('country', competitions.keys()) def test_leagues_full(self, spider,", "isinstance(leagues, list) @pytest.mark.parametrize('country', competitions.keys()) def test_leagues_full(self, spider, country): leagues = spider.soccer.leagues(country, full=True) assert", "league): spider.soccer._setattr_competiton(country, league) assert spider.soccer._country assert spider.soccer.country assert spider.soccer._league assert spider.soccer.league @pytest.mark.parametrize( 'country,league',", "def test_odds(self, spider, country, league): events, odds = spider.soccer.odds(country, league) assert isinstance(events, list)", "{ 'england': 'premier_league', 'italy': 'serie_a', 'spain': 'la_liga', } def test_countries(self, spider): countries =", "'foo_country' with pytest.raises(KeyError, match=f'{country} is not supported *'): spider.soccer.leagues(country) @pytest.mark.parametrize('country,league', competitions.items()) def test_teams(self,", "[next(iter(competitions.items()))]) def test_odds(self, spider, country, league): events, odds = spider.soccer.odds(country, league) assert isinstance(events,", "assert set(self.competitions.keys()) <= set(countries.keys()) assert isinstance(countries, dict) @pytest.mark.parametrize('country', competitions.keys()) def test_leagues(self, spider, country):", "TestSport(): \"\"\"Nothing to test. \"\"\" pass class TestSoccer(): \"\"\"Test the Soccer ABC across", "spider.soccer.leagues(country) @pytest.mark.parametrize('country,league', competitions.items()) def test_teams(self, spider, country, league): teams = spider.soccer.teams(country, league) assert", "def test_setattr_competiton(self, spider, country, league): spider.soccer._setattr_competiton(country, league) assert spider.soccer._country assert spider.soccer.country assert spider.soccer._league", "country, league): spider.soccer._setattr_competiton(country, league) assert spider.soccer._country assert spider.soccer.country assert spider.soccer._league assert spider.soccer.league @pytest.mark.parametrize(", "= spider.soccer.leagues(country, full=True) assert self.competitions[country] in leagues.keys() assert isinstance(leagues, dict) def test_league_not_supported(self, spider):", "'foo_league' with pytest.raises(KeyError, match=f'{league} is not supported *'): spider.soccer.teams(country, league) @pytest.mark.parametrize('country,league', competitions.items()) def", "spider): countries = spider.soccer.countries() assert set(self.competitions.keys()) <= set(countries) assert isinstance(countries, list) def test_countries_full(self,", "in leagues assert isinstance(leagues, list) @pytest.mark.parametrize('country', competitions.keys()) def test_leagues_full(self, spider, country): leagues =", "s = request.param() yield s s.quit() competitions = { 'england': 'premier_league', 'italy': 'serie_a',", "league, full=True) assert isinstance(teams, dict) def test_teams_not_supported(self, spider): country, league = 'serie_a', 'foo_league'", "assert spider.soccer.country assert spider.soccer._league assert spider.soccer.league @pytest.mark.parametrize( 'country,league', [next(iter(competitions.items()))]) def test_events(self, spider, country,", "def test_countries_full(self, spider): countries = spider.soccer.countries(full=True) assert set(self.competitions.keys()) <= set(countries.keys()) assert isinstance(countries, dict)", "= spider.soccer.leagues(country) assert self.competitions[country] in leagues assert isinstance(leagues, list) @pytest.mark.parametrize('country', competitions.keys()) def test_leagues_full(self,", "test_teams_not_supported(self, spider): country, league = 'serie_a', 'foo_league' with pytest.raises(KeyError, match=f'{league} is not supported", "'serie_a', 'foo_league' with pytest.raises(KeyError, match=f'{league} is not supported *'): spider.soccer.teams(country, league) @pytest.mark.parametrize('country,league', competitions.items())", "@pytest.mark.parametrize( 'country,league', [next(iter(competitions.items()))]) def test_odds(self, spider, country, league): events, odds = spider.soccer.odds(country, league)", "country, league): teams = spider.soccer.teams(country, league) assert isinstance(teams, list) @pytest.mark.parametrize('country,league', competitions.items()) def test_teams_full(self,", "@pytest.mark.parametrize('country,league', competitions.items()) def test_teams(self, spider, country, league): teams = spider.soccer.teams(country, league) assert isinstance(teams,", "def test_teams_not_supported(self, spider): country, league = 'serie_a', 'foo_league' with pytest.raises(KeyError, match=f'{league} is not", "leagues = spider.soccer.leagues(country, full=True) assert self.competitions[country] in leagues.keys() assert isinstance(leagues, dict) def test_league_not_supported(self,", "assert spider.soccer._country assert spider.soccer.country assert spider.soccer._league assert spider.soccer.league @pytest.mark.parametrize( 'country,league', [next(iter(competitions.items()))]) def test_events(self,", "[next(iter(competitions.items()))]) def test_events(self, spider, country, league): events = spider.soccer.events(country, league) assert isinstance(events, list)", "*'): spider.soccer.teams(country, league) @pytest.mark.parametrize('country,league', competitions.items()) def test_setattr_competiton(self, spider, country, league): spider.soccer._setattr_competiton(country, league) assert", "list) @pytest.mark.parametrize('country,league', competitions.items()) def test_teams_full(self, spider, country, league): teams = spider.soccer.teams(country, league, full=True)", "is not supported *'): spider.soccer.teams(country, league) @pytest.mark.parametrize('country,league', competitions.items()) def test_setattr_competiton(self, spider, country, league):", "'country,league', [next(iter(competitions.items()))]) def test_odds(self, spider, country, league): events, odds = spider.soccer.odds(country, league) assert", "test_odds(self, spider, country, league): events, odds = spider.soccer.odds(country, league) assert isinstance(events, list) assert", "test_countries(self, spider): countries = spider.soccer.countries() assert set(self.competitions.keys()) <= set(countries) assert isinstance(countries, list) def", "assert isinstance(events, list) assert events @pytest.mark.parametrize( 'country,league', [next(iter(competitions.items()))]) def test_odds(self, spider, country, league):", "assert events @pytest.mark.parametrize( 'country,league', [next(iter(competitions.items()))]) def test_odds(self, spider, country, league): events, odds =", "events = spider.soccer.events(country, league) assert isinstance(events, list) assert events @pytest.mark.parametrize( 'country,league', [next(iter(competitions.items()))]) def", "= spider.soccer.events(country, league) assert isinstance(events, list) assert events @pytest.mark.parametrize( 'country,league', [next(iter(competitions.items()))]) def test_odds(self,", "odds = spider.soccer.odds(country, league) assert isinstance(events, list) assert events assert isinstance(odds, list) assert", "league): teams = spider.soccer.teams(country, league) assert isinstance(teams, list) @pytest.mark.parametrize('country,league', competitions.items()) def test_teams_full(self, spider,", "s.quit() competitions = { 'england': 'premier_league', 'italy': 'serie_a', 'spain': 'la_liga', } def test_countries(self,", "match=f'{league} is not supported *'): spider.soccer.teams(country, league) @pytest.mark.parametrize('country,league', competitions.items()) def test_setattr_competiton(self, spider, country,", "list) assert events @pytest.mark.parametrize( 'country,league', [next(iter(competitions.items()))]) def test_odds(self, spider, country, league): events, odds", "def test_leagues_full(self, spider, country): leagues = spider.soccer.leagues(country, full=True) assert self.competitions[country] in leagues.keys() assert", "league) @pytest.mark.parametrize('country,league', competitions.items()) def test_setattr_competiton(self, spider, country, league): spider.soccer._setattr_competiton(country, league) assert spider.soccer._country assert", "@pytest.fixture(scope='class', params=spiders.values()) def spider(self, request): s = request.param() yield s s.quit() competitions =", "self.competitions[country] in leagues.keys() assert isinstance(leagues, dict) def test_league_not_supported(self, spider): country = 'foo_country' with", "spider, country): leagues = spider.soccer.leagues(country, full=True) assert self.competitions[country] in leagues.keys() assert isinstance(leagues, dict)", "in leagues.keys() assert isinstance(leagues, dict) def test_league_not_supported(self, spider): country = 'foo_country' with pytest.raises(KeyError,", "class TestSoccer(): \"\"\"Test the Soccer ABC across all bookmakers. \"\"\" @pytest.fixture(scope='class', params=spiders.values()) def", "test_leagues_full(self, spider, country): leagues = spider.soccer.leagues(country, full=True) assert self.competitions[country] in leagues.keys() assert isinstance(leagues,", "test_teams(self, spider, country, league): teams = spider.soccer.teams(country, league) assert isinstance(teams, list) @pytest.mark.parametrize('country,league', competitions.items())", "competitions.items()) def test_teams_full(self, spider, country, league): teams = spider.soccer.teams(country, league, full=True) assert isinstance(teams,", "country, league): teams = spider.soccer.teams(country, league, full=True) assert isinstance(teams, dict) def test_teams_not_supported(self, spider):", "dict) def test_league_not_supported(self, spider): country = 'foo_country' with pytest.raises(KeyError, match=f'{country} is not supported" ]
[ "28), date(2028, 4, 16), date(2029, 4, 1), date(2030, 4, 21), date(2031, 4, 13),", "date(2041, 4, 21), date(2042, 4, 6), date(2043, 3, 29), date(2044, 4, 17), date(2045,", "date(1333, 4, 4), date(1351, 4, 17), date(1371, 4, 6), date(1391, 3, 26), date(1402,", "5, 1), date(1995, 4, 23), date(1996, 4, 14), date(1997, 4, 27), date(1998, 4,", "26), date(1058, 4, 19), date(1113, 4, 6), date(1119, 3, 30), date(1242, 4, 20),", "date(2021, 4, 4), date(2022, 4, 17), date(2023, 4, 9), date(2024, 3, 31), date(2025,", "4, 14), date(867, 3, 30), date(890, 4, 12), date(922, 4, 21), date(934, 4,", "12), date(2016, 5, 1), date(2017, 4, 16), date(2018, 4, 8), date(2019, 4, 28),", "19), date(1999, 4, 11), date(2000, 4, 30), date(2001, 4, 15), date(2002, 5, 5),", "date(1351, 4, 17), date(1371, 4, 6), date(1391, 3, 26), date(1402, 3, 26), date(1412,", "27), date(2009, 4, 19), date(2010, 4, 4), date(2011, 4, 24), date(2012, 4, 15),", "4, 25), date(2039, 4, 17), date(2040, 5, 6), date(2041, 4, 21), date(2042, 4,", "date(2035, 3, 25), date(2036, 4, 13), date(2037, 4, 5), date(2038, 4, 25), date(2039,", "date(2026, 4, 12), date(2027, 5, 2), date(2028, 4, 16), date(2029, 4, 8), date(2030,", "4, 19), date(2010, 4, 4), date(2011, 4, 24), date(2012, 4, 15), date(2013, 5,", "17), date(2045, 4, 9), date(2046, 3, 25), date(2047, 4, 14), date(2048, 4, 5),", "4, 6), date(2043, 3, 29), date(2044, 4, 17), date(2045, 4, 9), date(2046, 3,", "date(1999, 4, 11), date(2000, 4, 30), date(2001, 4, 15), date(2002, 5, 5), date(2003,", "date(2031, 4, 13), date(2032, 3, 28), date(2033, 4, 17), date(2034, 4, 9), date(2035,", "date(2000, 4, 23), date(2001, 4, 15), date(2002, 3, 31), date(2003, 4, 20), date(2004,", "4, 6), date(1049, 3, 26), date(1058, 4, 19), date(1113, 4, 6), date(1119, 3,", "date(1119, 3, 30), date(1242, 4, 20), date(1255, 3, 28), date(1257, 4, 8), date(1258,", "4, 7), date(1997, 3, 30), date(1998, 4, 12), date(1999, 4, 4), date(2000, 4,", "3, 26), date(1412, 4, 3), date(1439, 4, 5), date(1445, 3, 28), date(1531, 4,", "3, 30), date(890, 4, 12), date(922, 4, 21), date(934, 4, 6), date(1049, 3,", "] @pytest.mark.parametrize(\"easter_date\", western_easter_dates) def test_easter_western(easter_date): assert easter_date == easter(easter_date.year, EASTER_WESTERN) @pytest.mark.parametrize(\"easter_date\", orthodox_easter_dates) def", "random smattering of Julian dates. # Pulled values from http://www.kevinlaughery.com/east4099.html julian_easter_dates = [", "4, 15), date(2002, 5, 5), date(2003, 4, 27), date(2004, 4, 11), date(2005, 5,", "date(922, 4, 21), date(934, 4, 6), date(1049, 3, 26), date(1058, 4, 19), date(1113,", "date(1995, 4, 23), date(1996, 4, 14), date(1997, 4, 27), date(1998, 4, 19), date(1999,", "from datetime import date import pytest # List of easters between 1990 and", "1), date(2030, 4, 21), date(2031, 4, 13), date(2032, 3, 28), date(2033, 4, 17),", "12), date(2021, 4, 4), date(2022, 4, 17), date(2023, 4, 9), date(2024, 3, 31),", "date(782, 4, 7), date(835, 4, 18), date(849, 4, 14), date(867, 3, 30), date(890,", "easter(easter_date.year, EASTER_WESTERN) @pytest.mark.parametrize(\"easter_date\", orthodox_easter_dates) def test_easter_orthodox(easter_date): assert easter_date == easter(easter_date.year, EASTER_ORTHODOX) @pytest.mark.parametrize(\"easter_date\", julian_easter_dates)", "4, 16), date(2018, 4, 8), date(2019, 4, 28), date(2020, 4, 19), date(2021, 5,", "date(2043, 3, 29), date(2044, 4, 17), date(2045, 4, 9), date(2046, 3, 25), date(2047,", "date(700, 4, 11), date(725, 4, 8), date(750, 3, 29), date(782, 4, 7), date(835,", "5, 3), date(2044, 4, 24), date(2045, 4, 9), date(2046, 4, 29), date(2047, 4,", "4, 17), ] # A random smattering of Julian dates. # Pulled values", "5, 5), date(2025, 4, 20), date(2026, 4, 12), date(2027, 5, 2), date(2028, 4,", "date(2039, 4, 10), date(2040, 4, 1), date(2041, 4, 21), date(2042, 4, 6), date(2043,", "= [ date(1990, 4, 15), date(1991, 3, 31), date(1992, 4, 19), date(1993, 4,", "pytest # List of easters between 1990 and 2050 western_easter_dates = [ date(1990,", "date(2019, 4, 28), date(2020, 4, 19), date(2021, 5, 2), date(2022, 4, 24), date(2023,", "date(1998, 4, 19), date(1999, 4, 11), date(2000, 4, 30), date(2001, 4, 15), date(2002,", "4, 1), date(2019, 4, 21), date(2020, 4, 12), date(2021, 4, 4), date(2022, 4,", "8), date(2030, 4, 28), date(2031, 4, 13), date(2032, 5, 2), date(2033, 4, 24),", "3), date(2044, 4, 24), date(2045, 4, 9), date(2046, 4, 29), date(2047, 4, 21),", "date(1113, 4, 6), date(1119, 3, 30), date(1242, 4, 20), date(1255, 3, 28), date(1257,", "4, 11), date(1994, 4, 3), date(1995, 4, 16), date(1996, 4, 7), date(1997, 3,", "date(2029, 4, 8), date(2030, 4, 28), date(2031, 4, 13), date(2032, 5, 2), date(2033,", "@pytest.mark.parametrize(\"easter_date\", julian_easter_dates) def test_easter_julian(easter_date): assert easter_date == easter(easter_date.year, EASTER_JULIAN) def test_easter_bad_method(): with pytest.raises(ValueError):", "date(597, 4, 14), date(621, 4, 19), date(636, 3, 31), date(655, 3, 29), date(700,", "17), date(1333, 4, 4), date(1351, 4, 17), date(1371, 4, 6), date(1391, 3, 26),", "= [ date(326, 4, 3), date(375, 4, 5), date(492, 4, 5), date(552, 3,", "date(1049, 3, 26), date(1058, 4, 19), date(1113, 4, 6), date(1119, 3, 30), date(1242,", "3, 28), date(2028, 4, 16), date(2029, 4, 1), date(2030, 4, 21), date(2031, 4,", "4, 12), date(2021, 4, 4), date(2022, 4, 17), date(2023, 4, 9), date(2024, 3,", "date(2016, 5, 1), date(2017, 4, 16), date(2018, 4, 8), date(2019, 4, 28), date(2020,", "date(2012, 4, 8), date(2013, 3, 31), date(2014, 4, 20), date(2015, 4, 5), date(2016,", "date(2013, 3, 31), date(2014, 4, 20), date(2015, 4, 5), date(2016, 3, 27), date(2017,", "4, 15), date(2013, 5, 5), date(2014, 4, 20), date(2015, 4, 12), date(2016, 5,", "date(2036, 4, 20), date(2037, 4, 5), date(2038, 4, 25), date(2039, 4, 17), date(2040,", "4, 4), date(1351, 4, 17), date(1371, 4, 6), date(1391, 3, 26), date(1402, 3,", "15), date(2002, 3, 31), date(2003, 4, 20), date(2004, 4, 11), date(2005, 3, 27),", "date(2028, 4, 16), date(2029, 4, 8), date(2030, 4, 28), date(2031, 4, 13), date(2032,", "date(1990, 4, 15), date(1991, 3, 31), date(1992, 4, 19), date(1993, 4, 11), date(1994,", "date(2024, 3, 31), date(2025, 4, 20), date(2026, 4, 5), date(2027, 3, 28), date(2028,", "date(2037, 4, 5), date(2038, 4, 25), date(2039, 4, 17), date(2040, 5, 6), date(2041,", "4, 18), date(2050, 4, 10), ] orthodox_easter_dates = [ date(1990, 4, 15), date(1991,", "9), date(2024, 3, 31), date(2025, 4, 20), date(2026, 4, 5), date(2027, 3, 28),", "date(2011, 4, 24), date(2012, 4, 8), date(2013, 3, 31), date(2014, 4, 20), date(2015,", "4, 13), date(2043, 5, 3), date(2044, 4, 24), date(2045, 4, 9), date(2046, 4,", "A random smattering of Julian dates. # Pulled values from http://www.kevinlaughery.com/east4099.html julian_easter_dates =", "3, 28), date(1257, 4, 8), date(1258, 3, 24), date(1261, 4, 24), date(1278, 4,", "24), date(1278, 4, 17), date(1333, 4, 4), date(1351, 4, 17), date(1371, 4, 6),", "date(1531, 4, 9), date(1555, 4, 14), ] @pytest.mark.parametrize(\"easter_date\", western_easter_dates) def test_easter_western(easter_date): assert easter_date", "date(2025, 4, 20), date(2026, 4, 5), date(2027, 3, 28), date(2028, 4, 16), date(2029,", "date(1991, 4, 7), date(1992, 4, 26), date(1993, 4, 18), date(1994, 5, 1), date(1995,", "4, 5), date(2049, 4, 18), date(2050, 4, 10), ] orthodox_easter_dates = [ date(1990,", "3, 31), date(562, 4, 9), date(569, 4, 21), date(597, 4, 14), date(621, 4,", "29), date(700, 4, 11), date(725, 4, 8), date(750, 3, 29), date(782, 4, 7),", "4, 10), date(2040, 4, 1), date(2041, 4, 21), date(2042, 4, 6), date(2043, 3,", "date(2029, 4, 1), date(2030, 4, 21), date(2031, 4, 13), date(2032, 3, 28), date(2033,", "date(2015, 4, 12), date(2016, 5, 1), date(2017, 4, 16), date(2018, 4, 8), date(2019,", "date(2004, 4, 11), date(2005, 5, 1), date(2006, 4, 23), date(2007, 4, 8), date(2008,", "4, 12), date(2027, 5, 2), date(2028, 4, 16), date(2029, 4, 8), date(2030, 4,", "date(1998, 4, 12), date(1999, 4, 4), date(2000, 4, 23), date(2001, 4, 15), date(2002,", "3, 26), date(1058, 4, 19), date(1113, 4, 6), date(1119, 3, 30), date(1242, 4,", "5), date(2014, 4, 20), date(2015, 4, 12), date(2016, 5, 1), date(2017, 4, 16),", "21), date(934, 4, 6), date(1049, 3, 26), date(1058, 4, 19), date(1113, 4, 6),", "4, 9), date(1555, 4, 14), ] @pytest.mark.parametrize(\"easter_date\", western_easter_dates) def test_easter_western(easter_date): assert easter_date ==", "9), date(2035, 3, 25), date(2036, 4, 13), date(2037, 4, 5), date(2038, 4, 25),", "date(1391, 3, 26), date(1402, 3, 26), date(1412, 4, 3), date(1439, 4, 5), date(1445,", "EASTER_ORTHODOX, EASTER_JULIAN from datetime import date import pytest # List of easters between", "date(1371, 4, 6), date(1391, 3, 26), date(1402, 3, 26), date(1412, 4, 3), date(1439,", "21), date(597, 4, 14), date(621, 4, 19), date(636, 3, 31), date(655, 3, 29),", "date(2012, 4, 15), date(2013, 5, 5), date(2014, 4, 20), date(2015, 4, 12), date(2016,", "4, 23), date(2007, 4, 8), date(2008, 4, 27), date(2009, 4, 19), date(2010, 4,", "date(2027, 5, 2), date(2028, 4, 16), date(2029, 4, 8), date(2030, 4, 28), date(2031,", "20), date(2026, 4, 12), date(2027, 5, 2), date(2028, 4, 16), date(2029, 4, 8),", "11), date(725, 4, 8), date(750, 3, 29), date(782, 4, 7), date(835, 4, 18),", "4, 8), date(2008, 3, 23), date(2009, 4, 12), date(2010, 4, 4), date(2011, 4,", "21), date(2042, 4, 6), date(2043, 3, 29), date(2044, 4, 17), date(2045, 4, 9),", "4, 20), date(2015, 4, 5), date(2016, 3, 27), date(2017, 4, 16), date(2018, 4,", "4, 30), date(2001, 4, 15), date(2002, 5, 5), date(2003, 4, 27), date(2004, 4,", "date(2032, 5, 2), date(2033, 4, 24), date(2034, 4, 9), date(2035, 4, 29), date(2036,", "4, 9), date(569, 4, 21), date(597, 4, 14), date(621, 4, 19), date(636, 3,", "3, 31), date(2025, 4, 20), date(2026, 4, 5), date(2027, 3, 28), date(2028, 4,", "4), date(1351, 4, 17), date(1371, 4, 6), date(1391, 3, 26), date(1402, 3, 26),", "4, 5), date(2049, 4, 25), date(2050, 4, 17), ] # A random smattering", "date(2018, 4, 8), date(2019, 4, 28), date(2020, 4, 19), date(2021, 5, 2), date(2022,", "http://www.kevinlaughery.com/east4099.html julian_easter_dates = [ date(326, 4, 3), date(375, 4, 5), date(492, 4, 5),", "Julian dates. # Pulled values from http://www.kevinlaughery.com/east4099.html julian_easter_dates = [ date(326, 4, 3),", "4, 19), date(1993, 4, 11), date(1994, 4, 3), date(1995, 4, 16), date(1996, 4,", "16), date(2018, 4, 8), date(2019, 4, 28), date(2020, 4, 19), date(2021, 5, 2),", "EASTER_JULIAN from datetime import date import pytest # List of easters between 1990", "4), date(2022, 4, 17), date(2023, 4, 9), date(2024, 3, 31), date(2025, 4, 20),", "17), date(2023, 4, 9), date(2024, 3, 31), date(2025, 4, 20), date(2026, 4, 5),", "28), date(2033, 4, 17), date(2034, 4, 9), date(2035, 3, 25), date(2036, 4, 13),", "date(2000, 4, 30), date(2001, 4, 15), date(2002, 5, 5), date(2003, 4, 27), date(2004,", "21), date(2031, 4, 13), date(2032, 3, 28), date(2033, 4, 17), date(2034, 4, 9),", "16), date(2029, 4, 8), date(2030, 4, 28), date(2031, 4, 13), date(2032, 5, 2),", "31), date(562, 4, 9), date(569, 4, 21), date(597, 4, 14), date(621, 4, 19),", "14), ] @pytest.mark.parametrize(\"easter_date\", western_easter_dates) def test_easter_western(easter_date): assert easter_date == easter(easter_date.year, EASTER_WESTERN) @pytest.mark.parametrize(\"easter_date\", orthodox_easter_dates)", "4, 9), date(2046, 3, 25), date(2047, 4, 14), date(2048, 4, 5), date(2049, 4,", "27), date(2017, 4, 16), date(2018, 4, 1), date(2019, 4, 21), date(2020, 4, 12),", "5), date(2038, 4, 25), date(2039, 4, 17), date(2040, 5, 6), date(2041, 4, 21),", "4, 20), date(2026, 4, 5), date(2027, 3, 28), date(2028, 4, 16), date(2029, 4,", "2), date(2028, 4, 16), date(2029, 4, 8), date(2030, 4, 28), date(2031, 4, 13),", "date(2010, 4, 4), date(2011, 4, 24), date(2012, 4, 8), date(2013, 3, 31), date(2014,", "5), date(2027, 3, 28), date(2028, 4, 16), date(2029, 4, 1), date(2030, 4, 21),", "4, 25), date(2039, 4, 10), date(2040, 4, 1), date(2041, 4, 21), date(2042, 4,", "4, 19), date(2021, 5, 2), date(2022, 4, 24), date(2023, 4, 16), date(2024, 5,", "4, 16), date(2018, 4, 1), date(2019, 4, 21), date(2020, 4, 12), date(2021, 4,", "= [ date(1990, 4, 15), date(1991, 4, 7), date(1992, 4, 26), date(1993, 4,", "date(2021, 5, 2), date(2022, 4, 24), date(2023, 4, 16), date(2024, 5, 5), date(2025,", "easter_date == easter(easter_date.year, EASTER_WESTERN) @pytest.mark.parametrize(\"easter_date\", orthodox_easter_dates) def test_easter_orthodox(easter_date): assert easter_date == easter(easter_date.year, EASTER_ORTHODOX)", "date(890, 4, 12), date(922, 4, 21), date(934, 4, 6), date(1049, 3, 26), date(1058,", "4, 20), date(2015, 4, 12), date(2016, 5, 1), date(2017, 4, 16), date(2018, 4,", "6), date(1119, 3, 30), date(1242, 4, 20), date(1255, 3, 28), date(1257, 4, 8),", "List of easters between 1990 and 2050 western_easter_dates = [ date(1990, 4, 15),", "date(2015, 4, 5), date(2016, 3, 27), date(2017, 4, 16), date(2018, 4, 1), date(2019,", "24), date(1261, 4, 24), date(1278, 4, 17), date(1333, 4, 4), date(1351, 4, 17),", "16), date(2018, 4, 1), date(2019, 4, 21), date(2020, 4, 12), date(2021, 4, 4),", "14), date(2048, 4, 5), date(2049, 4, 18), date(2050, 4, 10), ] orthodox_easter_dates =", "30), date(1998, 4, 12), date(1999, 4, 4), date(2000, 4, 23), date(2001, 4, 15),", "import pytest # List of easters between 1990 and 2050 western_easter_dates = [", "10), date(2040, 4, 1), date(2041, 4, 21), date(2042, 4, 6), date(2043, 3, 29),", "4, 1), date(2030, 4, 21), date(2031, 4, 13), date(2032, 3, 28), date(2033, 4,", "4, 21), date(2031, 4, 13), date(2032, 3, 28), date(2033, 4, 17), date(2034, 4,", "4, 3), date(1439, 4, 5), date(1445, 3, 28), date(1531, 4, 9), date(1555, 4,", "date(655, 3, 29), date(700, 4, 11), date(725, 4, 8), date(750, 3, 29), date(782,", "6), date(2043, 3, 29), date(2044, 4, 17), date(2045, 4, 9), date(2046, 3, 25),", "31), date(1992, 4, 19), date(1993, 4, 11), date(1994, 4, 3), date(1995, 4, 16),", "date(2031, 4, 13), date(2032, 5, 2), date(2033, 4, 24), date(2034, 4, 9), date(2035,", "4, 7), date(1992, 4, 26), date(1993, 4, 18), date(1994, 5, 1), date(1995, 4,", "4, 6), date(1391, 3, 26), date(1402, 3, 26), date(1412, 4, 3), date(1439, 4,", "EASTER_ORTHODOX) @pytest.mark.parametrize(\"easter_date\", julian_easter_dates) def test_easter_julian(easter_date): assert easter_date == easter(easter_date.year, EASTER_JULIAN) def test_easter_bad_method(): with", "19), date(2010, 4, 4), date(2011, 4, 24), date(2012, 4, 15), date(2013, 5, 5),", "[ date(1990, 4, 15), date(1991, 4, 7), date(1992, 4, 26), date(1993, 4, 18),", "date(2022, 4, 17), date(2023, 4, 9), date(2024, 3, 31), date(2025, 4, 20), date(2026,", "20), date(2015, 4, 5), date(2016, 3, 27), date(2017, 4, 16), date(2018, 4, 1),", "@pytest.mark.parametrize(\"easter_date\", western_easter_dates) def test_easter_western(easter_date): assert easter_date == easter(easter_date.year, EASTER_WESTERN) @pytest.mark.parametrize(\"easter_date\", orthodox_easter_dates) def test_easter_orthodox(easter_date):", "23), date(2007, 4, 8), date(2008, 4, 27), date(2009, 4, 19), date(2010, 4, 4),", "7), date(1992, 4, 26), date(1993, 4, 18), date(1994, 5, 1), date(1995, 4, 23),", "date(2019, 4, 21), date(2020, 4, 12), date(2021, 4, 4), date(2022, 4, 17), date(2023,", "orthodox_easter_dates) def test_easter_orthodox(easter_date): assert easter_date == easter(easter_date.year, EASTER_ORTHODOX) @pytest.mark.parametrize(\"easter_date\", julian_easter_dates) def test_easter_julian(easter_date): assert", "4, 5), date(1445, 3, 28), date(1531, 4, 9), date(1555, 4, 14), ] @pytest.mark.parametrize(\"easter_date\",", "date(2044, 4, 17), date(2045, 4, 9), date(2046, 3, 25), date(2047, 4, 14), date(2048,", "4, 6), date(1119, 3, 30), date(1242, 4, 20), date(1255, 3, 28), date(1257, 4,", "smattering of Julian dates. # Pulled values from http://www.kevinlaughery.com/east4099.html julian_easter_dates = [ date(326,", "28), date(1257, 4, 8), date(1258, 3, 24), date(1261, 4, 24), date(1278, 4, 17),", "14), date(1997, 4, 27), date(1998, 4, 19), date(1999, 4, 11), date(2000, 4, 30),", "9), date(1555, 4, 14), ] @pytest.mark.parametrize(\"easter_date\", western_easter_dates) def test_easter_western(easter_date): assert easter_date == easter(easter_date.year,", "date(2006, 4, 16), date(2007, 4, 8), date(2008, 3, 23), date(2009, 4, 12), date(2010,", "4, 20), date(2004, 4, 11), date(2005, 3, 27), date(2006, 4, 16), date(2007, 4,", "values from http://www.kevinlaughery.com/east4099.html julian_easter_dates = [ date(326, 4, 3), date(375, 4, 5), date(492,", "date(2024, 5, 5), date(2025, 4, 20), date(2026, 4, 12), date(2027, 5, 2), date(2028,", "3), date(375, 4, 5), date(492, 4, 5), date(552, 3, 31), date(562, 4, 9),", "19), date(1113, 4, 6), date(1119, 3, 30), date(1242, 4, 20), date(1255, 3, 28),", "16), date(1996, 4, 7), date(1997, 3, 30), date(1998, 4, 12), date(1999, 4, 4),", "4, 23), date(2001, 4, 15), date(2002, 3, 31), date(2003, 4, 20), date(2004, 4,", "27), date(2006, 4, 16), date(2007, 4, 8), date(2008, 3, 23), date(2009, 4, 12),", "date(2039, 4, 17), date(2040, 5, 6), date(2041, 4, 21), date(2042, 4, 13), date(2043,", "date(1997, 4, 27), date(1998, 4, 19), date(1999, 4, 11), date(2000, 4, 30), date(2001,", "24), date(2012, 4, 15), date(2013, 5, 5), date(2014, 4, 20), date(2015, 4, 12),", "3, 31), date(1992, 4, 19), date(1993, 4, 11), date(1994, 4, 3), date(1995, 4,", "date(1994, 5, 1), date(1995, 4, 23), date(1996, 4, 14), date(1997, 4, 27), date(1998,", "24), date(2012, 4, 8), date(2013, 3, 31), date(2014, 4, 20), date(2015, 4, 5),", "3, 30), date(1242, 4, 20), date(1255, 3, 28), date(1257, 4, 8), date(1258, 3,", "5), date(2003, 4, 27), date(2004, 4, 11), date(2005, 5, 1), date(2006, 4, 23),", "EASTER_WESTERN) @pytest.mark.parametrize(\"easter_date\", orthodox_easter_dates) def test_easter_orthodox(easter_date): assert easter_date == easter(easter_date.year, EASTER_ORTHODOX) @pytest.mark.parametrize(\"easter_date\", julian_easter_dates) def", "date(2017, 4, 16), date(2018, 4, 1), date(2019, 4, 21), date(2020, 4, 12), date(2021,", "date(1242, 4, 20), date(1255, 3, 28), date(1257, 4, 8), date(1258, 3, 24), date(1261,", "of Julian dates. # Pulled values from http://www.kevinlaughery.com/east4099.html julian_easter_dates = [ date(326, 4,", "1), date(1995, 4, 23), date(1996, 4, 14), date(1997, 4, 27), date(1998, 4, 19),", "4, 9), date(2035, 3, 25), date(2036, 4, 13), date(2037, 4, 5), date(2038, 4,", "5), date(492, 4, 5), date(552, 3, 31), date(562, 4, 9), date(569, 4, 21),", "4, 21), date(2042, 4, 13), date(2043, 5, 3), date(2044, 4, 24), date(2045, 4,", "13), date(2032, 3, 28), date(2033, 4, 17), date(2034, 4, 9), date(2035, 3, 25),", "test_easter_orthodox(easter_date): assert easter_date == easter(easter_date.year, EASTER_ORTHODOX) @pytest.mark.parametrize(\"easter_date\", julian_easter_dates) def test_easter_julian(easter_date): assert easter_date ==", "15), date(1991, 4, 7), date(1992, 4, 26), date(1993, 4, 18), date(1994, 5, 1),", "5), date(2025, 4, 20), date(2026, 4, 12), date(2027, 5, 2), date(2028, 4, 16),", "4, 8), date(2008, 4, 27), date(2009, 4, 19), date(2010, 4, 4), date(2011, 4,", "5), date(2038, 4, 25), date(2039, 4, 10), date(2040, 4, 1), date(2041, 4, 21),", "3, 29), date(700, 4, 11), date(725, 4, 8), date(750, 3, 29), date(782, 4,", "31), date(655, 3, 29), date(700, 4, 11), date(725, 4, 8), date(750, 3, 29),", "date(1261, 4, 24), date(1278, 4, 17), date(1333, 4, 4), date(1351, 4, 17), date(1371,", "date(2010, 4, 4), date(2011, 4, 24), date(2012, 4, 15), date(2013, 5, 5), date(2014,", "date(2048, 4, 5), date(2049, 4, 25), date(2050, 4, 17), ] # A random", "date(2002, 5, 5), date(2003, 4, 27), date(2004, 4, 11), date(2005, 5, 1), date(2006,", "date(2026, 4, 5), date(2027, 3, 28), date(2028, 4, 16), date(2029, 4, 1), date(2030,", "31), date(2003, 4, 20), date(2004, 4, 11), date(2005, 3, 27), date(2006, 4, 16),", "26), date(1402, 3, 26), date(1412, 4, 3), date(1439, 4, 5), date(1445, 3, 28),", "orthodox_easter_dates = [ date(1990, 4, 15), date(1991, 4, 7), date(1992, 4, 26), date(1993,", "4, 24), date(2045, 4, 9), date(2046, 4, 29), date(2047, 4, 21), date(2048, 4,", "19), date(1993, 4, 11), date(1994, 4, 3), date(1995, 4, 16), date(1996, 4, 7),", "date(2023, 4, 16), date(2024, 5, 5), date(2025, 4, 20), date(2026, 4, 12), date(2027,", "julian_easter_dates) def test_easter_julian(easter_date): assert easter_date == easter(easter_date.year, EASTER_JULIAN) def test_easter_bad_method(): with pytest.raises(ValueError): easter(1975,", "date(1445, 3, 28), date(1531, 4, 9), date(1555, 4, 14), ] @pytest.mark.parametrize(\"easter_date\", western_easter_dates) def", "date(2002, 3, 31), date(2003, 4, 20), date(2004, 4, 11), date(2005, 3, 27), date(2006,", "date(2023, 4, 9), date(2024, 3, 31), date(2025, 4, 20), date(2026, 4, 5), date(2027,", "4, 5), date(492, 4, 5), date(552, 3, 31), date(562, 4, 9), date(569, 4,", "date(2001, 4, 15), date(2002, 5, 5), date(2003, 4, 27), date(2004, 4, 11), date(2005,", "assert easter_date == easter(easter_date.year, EASTER_WESTERN) @pytest.mark.parametrize(\"easter_date\", orthodox_easter_dates) def test_easter_orthodox(easter_date): assert easter_date == easter(easter_date.year,", "3, 23), date(2009, 4, 12), date(2010, 4, 4), date(2011, 4, 24), date(2012, 4,", "between 1990 and 2050 western_easter_dates = [ date(1990, 4, 15), date(1991, 3, 31),", "4, 21), date(597, 4, 14), date(621, 4, 19), date(636, 3, 31), date(655, 3,", "bs_dateutil.easter import EASTER_WESTERN, EASTER_ORTHODOX, EASTER_JULIAN from datetime import date import pytest # List", "1990 and 2050 western_easter_dates = [ date(1990, 4, 15), date(1991, 3, 31), date(1992,", "date(2008, 4, 27), date(2009, 4, 19), date(2010, 4, 4), date(2011, 4, 24), date(2012,", "4, 15), date(1991, 3, 31), date(1992, 4, 19), date(1993, 4, 11), date(1994, 4,", "date(1999, 4, 4), date(2000, 4, 23), date(2001, 4, 15), date(2002, 3, 31), date(2003,", "4, 27), date(1998, 4, 19), date(1999, 4, 11), date(2000, 4, 30), date(2001, 4,", "19), date(636, 3, 31), date(655, 3, 29), date(700, 4, 11), date(725, 4, 8),", "date(1995, 4, 16), date(1996, 4, 7), date(1997, 3, 30), date(1998, 4, 12), date(1999,", "4, 26), date(1993, 4, 18), date(1994, 5, 1), date(1995, 4, 23), date(1996, 4,", "date(2038, 4, 25), date(2039, 4, 17), date(2040, 5, 6), date(2041, 4, 21), date(2042,", "6), date(1049, 3, 26), date(1058, 4, 19), date(1113, 4, 6), date(1119, 3, 30),", "date(326, 4, 3), date(375, 4, 5), date(492, 4, 5), date(552, 3, 31), date(562,", "3, 25), date(2047, 4, 14), date(2048, 4, 5), date(2049, 4, 18), date(2050, 4,", "4, 27), date(2009, 4, 19), date(2010, 4, 4), date(2011, 4, 24), date(2012, 4,", "date(2044, 4, 24), date(2045, 4, 9), date(2046, 4, 29), date(2047, 4, 21), date(2048,", "4, 20), date(2037, 4, 5), date(2038, 4, 25), date(2039, 4, 17), date(2040, 5,", "date(2040, 5, 6), date(2041, 4, 21), date(2042, 4, 13), date(2043, 5, 3), date(2044,", "date(1412, 4, 3), date(1439, 4, 5), date(1445, 3, 28), date(1531, 4, 9), date(1555,", "date(1996, 4, 14), date(1997, 4, 27), date(1998, 4, 19), date(1999, 4, 11), date(2000,", "date(1991, 3, 31), date(1992, 4, 19), date(1993, 4, 11), date(1994, 4, 3), date(1995,", "date(2032, 3, 28), date(2033, 4, 17), date(2034, 4, 9), date(2035, 3, 25), date(2036,", "4, 4), date(2011, 4, 24), date(2012, 4, 8), date(2013, 3, 31), date(2014, 4,", "16), date(2024, 5, 5), date(2025, 4, 20), date(2026, 4, 12), date(2027, 5, 2),", "15), date(2013, 5, 5), date(2014, 4, 20), date(2015, 4, 12), date(2016, 5, 1),", "date(2009, 4, 12), date(2010, 4, 4), date(2011, 4, 24), date(2012, 4, 8), date(2013,", "9), date(2035, 4, 29), date(2036, 4, 20), date(2037, 4, 5), date(2038, 4, 25),", "16), date(2029, 4, 1), date(2030, 4, 21), date(2031, 4, 13), date(2032, 3, 28),", "23), date(2009, 4, 12), date(2010, 4, 4), date(2011, 4, 24), date(2012, 4, 8),", "4, 24), date(2012, 4, 8), date(2013, 3, 31), date(2014, 4, 20), date(2015, 4,", "17), date(2034, 4, 9), date(2035, 3, 25), date(2036, 4, 13), date(2037, 4, 5),", "from bs_dateutil.easter import easter from bs_dateutil.easter import EASTER_WESTERN, EASTER_ORTHODOX, EASTER_JULIAN from datetime import", "1), date(2019, 4, 21), date(2020, 4, 12), date(2021, 4, 4), date(2022, 4, 17),", "date(2050, 4, 10), ] orthodox_easter_dates = [ date(1990, 4, 15), date(1991, 4, 7),", "4, 12), date(2010, 4, 4), date(2011, 4, 24), date(2012, 4, 8), date(2013, 3,", "1), date(2041, 4, 21), date(2042, 4, 6), date(2043, 3, 29), date(2044, 4, 17),", "5, 5), date(2014, 4, 20), date(2015, 4, 12), date(2016, 5, 1), date(2017, 4,", "date(1997, 3, 30), date(1998, 4, 12), date(1999, 4, 4), date(2000, 4, 23), date(2001,", "4, 16), date(2029, 4, 8), date(2030, 4, 28), date(2031, 4, 13), date(2032, 5,", "4, 28), date(2031, 4, 13), date(2032, 5, 2), date(2033, 4, 24), date(2034, 4,", "4, 11), date(2000, 4, 30), date(2001, 4, 15), date(2002, 5, 5), date(2003, 4,", "date(2014, 4, 20), date(2015, 4, 12), date(2016, 5, 1), date(2017, 4, 16), date(2018,", "14), date(867, 3, 30), date(890, 4, 12), date(922, 4, 21), date(934, 4, 6),", "Pulled values from http://www.kevinlaughery.com/east4099.html julian_easter_dates = [ date(326, 4, 3), date(375, 4, 5),", "29), date(2047, 4, 21), date(2048, 4, 5), date(2049, 4, 25), date(2050, 4, 17),", "date(2005, 5, 1), date(2006, 4, 23), date(2007, 4, 8), date(2008, 4, 27), date(2009,", "23), date(2001, 4, 15), date(2002, 3, 31), date(2003, 4, 20), date(2004, 4, 11),", "date(2020, 4, 12), date(2021, 4, 4), date(2022, 4, 17), date(2023, 4, 9), date(2024,", "3, 29), date(782, 4, 7), date(835, 4, 18), date(849, 4, 14), date(867, 3,", "9), date(2046, 3, 25), date(2047, 4, 14), date(2048, 4, 5), date(2049, 4, 18),", "date(849, 4, 14), date(867, 3, 30), date(890, 4, 12), date(922, 4, 21), date(934,", "4, 19), date(1999, 4, 11), date(2000, 4, 30), date(2001, 4, 15), date(2002, 5,", "3), date(1995, 4, 16), date(1996, 4, 7), date(1997, 3, 30), date(1998, 4, 12),", "4, 8), date(1258, 3, 24), date(1261, 4, 24), date(1278, 4, 17), date(1333, 4,", "20), date(2037, 4, 5), date(2038, 4, 25), date(2039, 4, 17), date(2040, 5, 6),", "11), date(2005, 5, 1), date(2006, 4, 23), date(2007, 4, 8), date(2008, 4, 27),", "and 2050 western_easter_dates = [ date(1990, 4, 15), date(1991, 3, 31), date(1992, 4,", "25), date(2050, 4, 17), ] # A random smattering of Julian dates. #", "date(2030, 4, 28), date(2031, 4, 13), date(2032, 5, 2), date(2033, 4, 24), date(2034,", "31), date(2025, 4, 20), date(2026, 4, 5), date(2027, 3, 28), date(2028, 4, 16),", "== easter(easter_date.year, EASTER_ORTHODOX) @pytest.mark.parametrize(\"easter_date\", julian_easter_dates) def test_easter_julian(easter_date): assert easter_date == easter(easter_date.year, EASTER_JULIAN) def", "4, 19), date(636, 3, 31), date(655, 3, 29), date(700, 4, 11), date(725, 4,", "3, 29), date(2044, 4, 17), date(2045, 4, 9), date(2046, 3, 25), date(2047, 4,", "4, 23), date(1996, 4, 14), date(1997, 4, 27), date(1998, 4, 19), date(1999, 4,", "date import pytest # List of easters between 1990 and 2050 western_easter_dates =", "western_easter_dates = [ date(1990, 4, 15), date(1991, 3, 31), date(1992, 4, 19), date(1993,", "easter(easter_date.year, EASTER_ORTHODOX) @pytest.mark.parametrize(\"easter_date\", julian_easter_dates) def test_easter_julian(easter_date): assert easter_date == easter(easter_date.year, EASTER_JULIAN) def test_easter_bad_method():", "date(2040, 4, 1), date(2041, 4, 21), date(2042, 4, 6), date(2043, 3, 29), date(2044,", "4, 15), date(1991, 4, 7), date(1992, 4, 26), date(1993, 4, 18), date(1994, 5,", "from http://www.kevinlaughery.com/east4099.html julian_easter_dates = [ date(326, 4, 3), date(375, 4, 5), date(492, 4,", "4), date(2011, 4, 24), date(2012, 4, 8), date(2013, 3, 31), date(2014, 4, 20),", "4, 25), date(2050, 4, 17), ] # A random smattering of Julian dates.", "date(1278, 4, 17), date(1333, 4, 4), date(1351, 4, 17), date(1371, 4, 6), date(1391,", "date(2046, 4, 29), date(2047, 4, 21), date(2048, 4, 5), date(2049, 4, 25), date(2050,", "30), date(890, 4, 12), date(922, 4, 21), date(934, 4, 6), date(1049, 3, 26),", "2), date(2033, 4, 24), date(2034, 4, 9), date(2035, 4, 29), date(2036, 4, 20),", "24), date(2045, 4, 9), date(2046, 4, 29), date(2047, 4, 21), date(2048, 4, 5),", "12), date(1999, 4, 4), date(2000, 4, 23), date(2001, 4, 15), date(2002, 3, 31),", "date(2017, 4, 16), date(2018, 4, 8), date(2019, 4, 28), date(2020, 4, 19), date(2021,", "julian_easter_dates = [ date(326, 4, 3), date(375, 4, 5), date(492, 4, 5), date(552,", "4, 17), date(2023, 4, 9), date(2024, 3, 31), date(2025, 4, 20), date(2026, 4,", "8), date(2013, 3, 31), date(2014, 4, 20), date(2015, 4, 5), date(2016, 3, 27),", "1), date(2017, 4, 16), date(2018, 4, 8), date(2019, 4, 28), date(2020, 4, 19),", "4, 3), date(375, 4, 5), date(492, 4, 5), date(552, 3, 31), date(562, 4,", "date(1555, 4, 14), ] @pytest.mark.parametrize(\"easter_date\", western_easter_dates) def test_easter_western(easter_date): assert easter_date == easter(easter_date.year, EASTER_WESTERN)", "date(2047, 4, 14), date(2048, 4, 5), date(2049, 4, 18), date(2050, 4, 10), ]", "28), date(2020, 4, 19), date(2021, 5, 2), date(2022, 4, 24), date(2023, 4, 16),", "date(2049, 4, 18), date(2050, 4, 10), ] orthodox_easter_dates = [ date(1990, 4, 15),", "4, 18), date(1994, 5, 1), date(1995, 4, 23), date(1996, 4, 14), date(1997, 4,", "date(2020, 4, 19), date(2021, 5, 2), date(2022, 4, 24), date(2023, 4, 16), date(2024,", "4, 12), date(1999, 4, 4), date(2000, 4, 23), date(2001, 4, 15), date(2002, 3,", "21), date(2020, 4, 12), date(2021, 4, 4), date(2022, 4, 17), date(2023, 4, 9),", "5, 2), date(2022, 4, 24), date(2023, 4, 16), date(2024, 5, 5), date(2025, 4,", "date(569, 4, 21), date(597, 4, 14), date(621, 4, 19), date(636, 3, 31), date(655,", "4, 24), date(1278, 4, 17), date(1333, 4, 4), date(1351, 4, 17), date(1371, 4,", "4, 1), date(2041, 4, 21), date(2042, 4, 6), date(2043, 3, 29), date(2044, 4,", "date(2038, 4, 25), date(2039, 4, 10), date(2040, 4, 1), date(2041, 4, 21), date(2042,", "4, 16), date(2007, 4, 8), date(2008, 3, 23), date(2009, 4, 12), date(2010, 4,", "date(2037, 4, 5), date(2038, 4, 25), date(2039, 4, 10), date(2040, 4, 1), date(2041,", "date(750, 3, 29), date(782, 4, 7), date(835, 4, 18), date(849, 4, 14), date(867,", "4, 21), date(2020, 4, 12), date(2021, 4, 4), date(2022, 4, 17), date(2023, 4,", "date(1993, 4, 18), date(1994, 5, 1), date(1995, 4, 23), date(1996, 4, 14), date(1997,", "2), date(2022, 4, 24), date(2023, 4, 16), date(2024, 5, 5), date(2025, 4, 20),", "date(2011, 4, 24), date(2012, 4, 15), date(2013, 5, 5), date(2014, 4, 20), date(2015,", "4, 13), date(2032, 5, 2), date(2033, 4, 24), date(2034, 4, 9), date(2035, 4,", "18), date(1994, 5, 1), date(1995, 4, 23), date(1996, 4, 14), date(1997, 4, 27),", "25), date(2039, 4, 17), date(2040, 5, 6), date(2041, 4, 21), date(2042, 4, 13),", "20), date(2026, 4, 5), date(2027, 3, 28), date(2028, 4, 16), date(2029, 4, 1),", "5), date(2049, 4, 25), date(2050, 4, 17), ] # A random smattering of", "dates. # Pulled values from http://www.kevinlaughery.com/east4099.html julian_easter_dates = [ date(326, 4, 3), date(375,", "3, 31), date(2003, 4, 20), date(2004, 4, 11), date(2005, 3, 27), date(2006, 4,", "15), date(1991, 3, 31), date(1992, 4, 19), date(1993, 4, 11), date(1994, 4, 3),", "easters between 1990 and 2050 western_easter_dates = [ date(1990, 4, 15), date(1991, 3,", "4, 24), date(2023, 4, 16), date(2024, 5, 5), date(2025, 4, 20), date(2026, 4,", "date(2007, 4, 8), date(2008, 3, 23), date(2009, 4, 12), date(2010, 4, 4), date(2011,", "date(1258, 3, 24), date(1261, 4, 24), date(1278, 4, 17), date(1333, 4, 4), date(1351,", "5), date(552, 3, 31), date(562, 4, 9), date(569, 4, 21), date(597, 4, 14),", "5, 2), date(2028, 4, 16), date(2029, 4, 8), date(2030, 4, 28), date(2031, 4,", "5, 1), date(2017, 4, 16), date(2018, 4, 8), date(2019, 4, 28), date(2020, 4,", "# List of easters between 1990 and 2050 western_easter_dates = [ date(1990, 4,", "21), date(2042, 4, 13), date(2043, 5, 3), date(2044, 4, 24), date(2045, 4, 9),", "date(2041, 4, 21), date(2042, 4, 13), date(2043, 5, 3), date(2044, 4, 24), date(2045,", "4, 13), date(2037, 4, 5), date(2038, 4, 25), date(2039, 4, 10), date(2040, 4,", "4, 3), date(1995, 4, 16), date(1996, 4, 7), date(1997, 3, 30), date(1998, 4,", "6), date(1391, 3, 26), date(1402, 3, 26), date(1412, 4, 3), date(1439, 4, 5),", "date(2034, 4, 9), date(2035, 4, 29), date(2036, 4, 20), date(2037, 4, 5), date(2038,", "5, 6), date(2041, 4, 21), date(2042, 4, 13), date(2043, 5, 3), date(2044, 4,", "12), date(922, 4, 21), date(934, 4, 6), date(1049, 3, 26), date(1058, 4, 19),", "24), date(2023, 4, 16), date(2024, 5, 5), date(2025, 4, 20), date(2026, 4, 12),", "date(2006, 4, 23), date(2007, 4, 8), date(2008, 4, 27), date(2009, 4, 19), date(2010,", "4, 16), date(2029, 4, 1), date(2030, 4, 21), date(2031, 4, 13), date(2032, 3,", "date(2048, 4, 5), date(2049, 4, 18), date(2050, 4, 10), ] orthodox_easter_dates = [", "9), date(569, 4, 21), date(597, 4, 14), date(621, 4, 19), date(636, 3, 31),", "date(375, 4, 5), date(492, 4, 5), date(552, 3, 31), date(562, 4, 9), date(569,", "4, 4), date(2011, 4, 24), date(2012, 4, 15), date(2013, 5, 5), date(2014, 4,", "17), date(1371, 4, 6), date(1391, 3, 26), date(1402, 3, 26), date(1412, 4, 3),", "date(1994, 4, 3), date(1995, 4, 16), date(1996, 4, 7), date(1997, 3, 30), date(1998,", "4, 5), date(552, 3, 31), date(562, 4, 9), date(569, 4, 21), date(597, 4,", "date(725, 4, 8), date(750, 3, 29), date(782, 4, 7), date(835, 4, 18), date(849,", "1), date(2006, 4, 23), date(2007, 4, 8), date(2008, 4, 27), date(2009, 4, 19),", "date(1993, 4, 11), date(1994, 4, 3), date(1995, 4, 16), date(1996, 4, 7), date(1997,", "date(2046, 3, 25), date(2047, 4, 14), date(2048, 4, 5), date(2049, 4, 18), date(2050,", "date(2027, 3, 28), date(2028, 4, 16), date(2029, 4, 1), date(2030, 4, 21), date(2031,", "date(2045, 4, 9), date(2046, 3, 25), date(2047, 4, 14), date(2048, 4, 5), date(2049,", "date(2033, 4, 24), date(2034, 4, 9), date(2035, 4, 29), date(2036, 4, 20), date(2037,", "date(2028, 4, 16), date(2029, 4, 1), date(2030, 4, 21), date(2031, 4, 13), date(2032,", "bs_dateutil.easter import easter from bs_dateutil.easter import EASTER_WESTERN, EASTER_ORTHODOX, EASTER_JULIAN from datetime import date", "25), date(2039, 4, 10), date(2040, 4, 1), date(2041, 4, 21), date(2042, 4, 6),", "4, 11), date(725, 4, 8), date(750, 3, 29), date(782, 4, 7), date(835, 4,", "date(1990, 4, 15), date(1991, 4, 7), date(1992, 4, 26), date(1993, 4, 18), date(1994,", "date(2009, 4, 19), date(2010, 4, 4), date(2011, 4, 24), date(2012, 4, 15), date(2013,", "date(2005, 3, 27), date(2006, 4, 16), date(2007, 4, 8), date(2008, 3, 23), date(2009,", "4, 17), date(2045, 4, 9), date(2046, 3, 25), date(2047, 4, 14), date(2048, 4,", "date(1058, 4, 19), date(1113, 4, 6), date(1119, 3, 30), date(1242, 4, 20), date(1255,", "3, 31), date(2014, 4, 20), date(2015, 4, 5), date(2016, 3, 27), date(2017, 4,", "date(1992, 4, 19), date(1993, 4, 11), date(1994, 4, 3), date(1995, 4, 16), date(1996,", "17), date(2040, 5, 6), date(2041, 4, 21), date(2042, 4, 13), date(2043, 5, 3),", "4, 8), date(2013, 3, 31), date(2014, 4, 20), date(2015, 4, 5), date(2016, 3,", "date(552, 3, 31), date(562, 4, 9), date(569, 4, 21), date(597, 4, 14), date(621,", "18), date(849, 4, 14), date(867, 3, 30), date(890, 4, 12), date(922, 4, 21),", "24), date(2034, 4, 9), date(2035, 4, 29), date(2036, 4, 20), date(2037, 4, 5),", "date(2047, 4, 21), date(2048, 4, 5), date(2049, 4, 25), date(2050, 4, 17), ]", "4, 19), date(1113, 4, 6), date(1119, 3, 30), date(1242, 4, 20), date(1255, 3,", "def test_easter_western(easter_date): assert easter_date == easter(easter_date.year, EASTER_WESTERN) @pytest.mark.parametrize(\"easter_date\", orthodox_easter_dates) def test_easter_orthodox(easter_date): assert easter_date", "20), date(1255, 3, 28), date(1257, 4, 8), date(1258, 3, 24), date(1261, 4, 24),", "4, 14), ] @pytest.mark.parametrize(\"easter_date\", western_easter_dates) def test_easter_western(easter_date): assert easter_date == easter(easter_date.year, EASTER_WESTERN) @pytest.mark.parametrize(\"easter_date\",", "4, 20), date(1255, 3, 28), date(1257, 4, 8), date(1258, 3, 24), date(1261, 4,", "EASTER_WESTERN, EASTER_ORTHODOX, EASTER_JULIAN from datetime import date import pytest # List of easters", "date(867, 3, 30), date(890, 4, 12), date(922, 4, 21), date(934, 4, 6), date(1049,", "31), date(2014, 4, 20), date(2015, 4, 5), date(2016, 3, 27), date(2017, 4, 16),", "date(2035, 4, 29), date(2036, 4, 20), date(2037, 4, 5), date(2038, 4, 25), date(2039,", "14), date(621, 4, 19), date(636, 3, 31), date(655, 3, 29), date(700, 4, 11),", "easter_date == easter(easter_date.year, EASTER_ORTHODOX) @pytest.mark.parametrize(\"easter_date\", julian_easter_dates) def test_easter_julian(easter_date): assert easter_date == easter(easter_date.year, EASTER_JULIAN)", "8), date(1258, 3, 24), date(1261, 4, 24), date(1278, 4, 17), date(1333, 4, 4),", "date(1257, 4, 8), date(1258, 3, 24), date(1261, 4, 24), date(1278, 4, 17), date(1333,", "4, 10), ] orthodox_easter_dates = [ date(1990, 4, 15), date(1991, 4, 7), date(1992,", "# Pulled values from http://www.kevinlaughery.com/east4099.html julian_easter_dates = [ date(326, 4, 3), date(375, 4,", "20), date(2004, 4, 11), date(2005, 3, 27), date(2006, 4, 16), date(2007, 4, 8),", "5, 1), date(2006, 4, 23), date(2007, 4, 8), date(2008, 4, 27), date(2009, 4,", "3, 30), date(1998, 4, 12), date(1999, 4, 4), date(2000, 4, 23), date(2001, 4,", "4, 5), date(2038, 4, 25), date(2039, 4, 17), date(2040, 5, 6), date(2041, 4,", "date(2030, 4, 21), date(2031, 4, 13), date(2032, 3, 28), date(2033, 4, 17), date(2034,", "4, 11), date(2005, 3, 27), date(2006, 4, 16), date(2007, 4, 8), date(2008, 3,", "8), date(2008, 4, 27), date(2009, 4, 19), date(2010, 4, 4), date(2011, 4, 24),", "16), date(2007, 4, 8), date(2008, 3, 23), date(2009, 4, 12), date(2010, 4, 4),", "import date import pytest # List of easters between 1990 and 2050 western_easter_dates", "4, 15), date(2002, 3, 31), date(2003, 4, 20), date(2004, 4, 11), date(2005, 3,", "4, 17), date(2034, 4, 9), date(2035, 3, 25), date(2036, 4, 13), date(2037, 4,", "8), date(2019, 4, 28), date(2020, 4, 19), date(2021, 5, 2), date(2022, 4, 24),", "4, 21), date(2048, 4, 5), date(2049, 4, 25), date(2050, 4, 17), ] #", "4, 5), date(2038, 4, 25), date(2039, 4, 10), date(2040, 4, 1), date(2041, 4,", "4, 27), date(2004, 4, 11), date(2005, 5, 1), date(2006, 4, 23), date(2007, 4,", "western_easter_dates) def test_easter_western(easter_date): assert easter_date == easter(easter_date.year, EASTER_WESTERN) @pytest.mark.parametrize(\"easter_date\", orthodox_easter_dates) def test_easter_orthodox(easter_date): assert", "17), ] # A random smattering of Julian dates. # Pulled values from", "datetime import date import pytest # List of easters between 1990 and 2050", "4, 8), date(2019, 4, 28), date(2020, 4, 19), date(2021, 5, 2), date(2022, 4,", "date(2049, 4, 25), date(2050, 4, 17), ] # A random smattering of Julian", "from bs_dateutil.easter import EASTER_WESTERN, EASTER_ORTHODOX, EASTER_JULIAN from datetime import date import pytest #", "21), date(2048, 4, 5), date(2049, 4, 25), date(2050, 4, 17), ] # A", "of easters between 1990 and 2050 western_easter_dates = [ date(1990, 4, 15), date(1991,", "4, 17), date(1333, 4, 4), date(1351, 4, 17), date(1371, 4, 6), date(1391, 3,", "3, 28), date(1531, 4, 9), date(1555, 4, 14), ] @pytest.mark.parametrize(\"easter_date\", western_easter_dates) def test_easter_western(easter_date):", "4, 8), date(2030, 4, 28), date(2031, 4, 13), date(2032, 5, 2), date(2033, 4,", "@pytest.mark.parametrize(\"easter_date\", orthodox_easter_dates) def test_easter_orthodox(easter_date): assert easter_date == easter(easter_date.year, EASTER_ORTHODOX) @pytest.mark.parametrize(\"easter_date\", julian_easter_dates) def test_easter_julian(easter_date):", "4, 29), date(2047, 4, 21), date(2048, 4, 5), date(2049, 4, 25), date(2050, 4,", "27), date(2004, 4, 11), date(2005, 5, 1), date(2006, 4, 23), date(2007, 4, 8),", "13), date(2037, 4, 5), date(2038, 4, 25), date(2039, 4, 10), date(2040, 4, 1),", "date(1255, 3, 28), date(1257, 4, 8), date(1258, 3, 24), date(1261, 4, 24), date(1278,", "29), date(2036, 4, 20), date(2037, 4, 5), date(2038, 4, 25), date(2039, 4, 17),", "29), date(2044, 4, 17), date(2045, 4, 9), date(2046, 3, 25), date(2047, 4, 14),", "28), date(1531, 4, 9), date(1555, 4, 14), ] @pytest.mark.parametrize(\"easter_date\", western_easter_dates) def test_easter_western(easter_date): assert", "5, 2), date(2033, 4, 24), date(2034, 4, 9), date(2035, 4, 29), date(2036, 4,", "== easter(easter_date.year, EASTER_WESTERN) @pytest.mark.parametrize(\"easter_date\", orthodox_easter_dates) def test_easter_orthodox(easter_date): assert easter_date == easter(easter_date.year, EASTER_ORTHODOX) @pytest.mark.parametrize(\"easter_date\",", "date(2008, 3, 23), date(2009, 4, 12), date(2010, 4, 4), date(2011, 4, 24), date(2012,", "3), date(1439, 4, 5), date(1445, 3, 28), date(1531, 4, 9), date(1555, 4, 14),", "3, 24), date(1261, 4, 24), date(1278, 4, 17), date(1333, 4, 4), date(1351, 4,", "date(2018, 4, 1), date(2019, 4, 21), date(2020, 4, 12), date(2021, 4, 4), date(2022,", "8), date(750, 3, 29), date(782, 4, 7), date(835, 4, 18), date(849, 4, 14),", "5), date(1445, 3, 28), date(1531, 4, 9), date(1555, 4, 14), ] @pytest.mark.parametrize(\"easter_date\", western_easter_dates)", "28), date(2031, 4, 13), date(2032, 5, 2), date(2033, 4, 24), date(2034, 4, 9),", "assert easter_date == easter(easter_date.year, EASTER_ORTHODOX) @pytest.mark.parametrize(\"easter_date\", julian_easter_dates) def test_easter_julian(easter_date): assert easter_date == easter(easter_date.year,", "13), date(2032, 5, 2), date(2033, 4, 24), date(2034, 4, 9), date(2035, 4, 29),", "12), date(2010, 4, 4), date(2011, 4, 24), date(2012, 4, 8), date(2013, 3, 31),", "11), date(2005, 3, 27), date(2006, 4, 16), date(2007, 4, 8), date(2008, 3, 23),", "5, 5), date(2003, 4, 27), date(2004, 4, 11), date(2005, 5, 1), date(2006, 4,", "13), date(2043, 5, 3), date(2044, 4, 24), date(2045, 4, 9), date(2046, 4, 29),", "date(2016, 3, 27), date(2017, 4, 16), date(2018, 4, 1), date(2019, 4, 21), date(2020,", "date(2013, 5, 5), date(2014, 4, 20), date(2015, 4, 12), date(2016, 5, 1), date(2017,", "date(2003, 4, 20), date(2004, 4, 11), date(2005, 3, 27), date(2006, 4, 16), date(2007,", "9), date(2046, 4, 29), date(2047, 4, 21), date(2048, 4, 5), date(2049, 4, 25),", "date(2042, 4, 13), date(2043, 5, 3), date(2044, 4, 24), date(2045, 4, 9), date(2046,", "import EASTER_WESTERN, EASTER_ORTHODOX, EASTER_JULIAN from datetime import date import pytest # List of", "date(636, 3, 31), date(655, 3, 29), date(700, 4, 11), date(725, 4, 8), date(750,", "4, 21), date(934, 4, 6), date(1049, 3, 26), date(1058, 4, 19), date(1113, 4,", "4, 13), date(2032, 3, 28), date(2033, 4, 17), date(2034, 4, 9), date(2035, 3,", "date(2014, 4, 20), date(2015, 4, 5), date(2016, 3, 27), date(2017, 4, 16), date(2018,", "5), date(2049, 4, 18), date(2050, 4, 10), ] orthodox_easter_dates = [ date(1990, 4,", "date(492, 4, 5), date(552, 3, 31), date(562, 4, 9), date(569, 4, 21), date(597,", "date(2007, 4, 8), date(2008, 4, 27), date(2009, 4, 19), date(2010, 4, 4), date(2011,", "def test_easter_julian(easter_date): assert easter_date == easter(easter_date.year, EASTER_JULIAN) def test_easter_bad_method(): with pytest.raises(ValueError): easter(1975, 4)", "4, 9), date(2046, 4, 29), date(2047, 4, 21), date(2048, 4, 5), date(2049, 4,", "4, 12), date(922, 4, 21), date(934, 4, 6), date(1049, 3, 26), date(1058, 4,", "4, 5), date(2027, 3, 28), date(2028, 4, 16), date(2029, 4, 1), date(2030, 4,", "date(2045, 4, 9), date(2046, 4, 29), date(2047, 4, 21), date(2048, 4, 5), date(2049,", "date(621, 4, 19), date(636, 3, 31), date(655, 3, 29), date(700, 4, 11), date(725,", "4, 14), date(621, 4, 19), date(636, 3, 31), date(655, 3, 29), date(700, 4,", "3, 27), date(2017, 4, 16), date(2018, 4, 1), date(2019, 4, 21), date(2020, 4,", "25), date(2036, 4, 13), date(2037, 4, 5), date(2038, 4, 25), date(2039, 4, 10),", "4, 29), date(2036, 4, 20), date(2037, 4, 5), date(2038, 4, 25), date(2039, 4,", "30), date(1242, 4, 20), date(1255, 3, 28), date(1257, 4, 8), date(1258, 3, 24),", "3, 25), date(2036, 4, 13), date(2037, 4, 5), date(2038, 4, 25), date(2039, 4,", "# A random smattering of Julian dates. # Pulled values from http://www.kevinlaughery.com/east4099.html julian_easter_dates", "import easter from bs_dateutil.easter import EASTER_WESTERN, EASTER_ORTHODOX, EASTER_JULIAN from datetime import date import", "date(2036, 4, 13), date(2037, 4, 5), date(2038, 4, 25), date(2039, 4, 10), date(2040,", "[ date(1990, 4, 15), date(1991, 3, 31), date(1992, 4, 19), date(1993, 4, 11),", "25), date(2047, 4, 14), date(2048, 4, 5), date(2049, 4, 18), date(2050, 4, 10),", "[ date(326, 4, 3), date(375, 4, 5), date(492, 4, 5), date(552, 3, 31),", "26), date(1993, 4, 18), date(1994, 5, 1), date(1995, 4, 23), date(1996, 4, 14),", "4, 16), date(2024, 5, 5), date(2025, 4, 20), date(2026, 4, 12), date(2027, 5,", "] orthodox_easter_dates = [ date(1990, 4, 15), date(1991, 4, 7), date(1992, 4, 26),", "3, 26), date(1402, 3, 26), date(1412, 4, 3), date(1439, 4, 5), date(1445, 3,", "4), date(2000, 4, 23), date(2001, 4, 15), date(2002, 3, 31), date(2003, 4, 20),", "4, 28), date(2020, 4, 19), date(2021, 5, 2), date(2022, 4, 24), date(2023, 4,", "15), date(2002, 5, 5), date(2003, 4, 27), date(2004, 4, 11), date(2005, 5, 1),", "29), date(782, 4, 7), date(835, 4, 18), date(849, 4, 14), date(867, 3, 30),", "4, 16), date(1996, 4, 7), date(1997, 3, 30), date(1998, 4, 12), date(1999, 4,", "4, 11), date(2005, 5, 1), date(2006, 4, 23), date(2007, 4, 8), date(2008, 4,", "4, 7), date(835, 4, 18), date(849, 4, 14), date(867, 3, 30), date(890, 4,", "7), date(1997, 3, 30), date(1998, 4, 12), date(1999, 4, 4), date(2000, 4, 23),", "7), date(835, 4, 18), date(849, 4, 14), date(867, 3, 30), date(890, 4, 12),", "date(2033, 4, 17), date(2034, 4, 9), date(2035, 3, 25), date(2036, 4, 13), date(2037,", "test_easter_western(easter_date): assert easter_date == easter(easter_date.year, EASTER_WESTERN) @pytest.mark.parametrize(\"easter_date\", orthodox_easter_dates) def test_easter_orthodox(easter_date): assert easter_date ==", "3, 27), date(2006, 4, 16), date(2007, 4, 8), date(2008, 3, 23), date(2009, 4,", "date(2001, 4, 15), date(2002, 3, 31), date(2003, 4, 20), date(2004, 4, 11), date(2005,", "30), date(2001, 4, 15), date(2002, 5, 5), date(2003, 4, 27), date(2004, 4, 11),", "4, 12), date(2016, 5, 1), date(2017, 4, 16), date(2018, 4, 8), date(2019, 4,", "6), date(2041, 4, 21), date(2042, 4, 13), date(2043, 5, 3), date(2044, 4, 24),", "date(2004, 4, 11), date(2005, 3, 27), date(2006, 4, 16), date(2007, 4, 8), date(2008,", "23), date(1996, 4, 14), date(1997, 4, 27), date(1998, 4, 19), date(1999, 4, 11),", "4, 4), date(2022, 4, 17), date(2023, 4, 9), date(2024, 3, 31), date(2025, 4,", "date(1992, 4, 26), date(1993, 4, 18), date(1994, 5, 1), date(1995, 4, 23), date(1996,", "date(2042, 4, 6), date(2043, 3, 29), date(2044, 4, 17), date(2045, 4, 9), date(2046,", "4, 14), date(2048, 4, 5), date(2049, 4, 18), date(2050, 4, 10), ] orthodox_easter_dates", "5), date(2016, 3, 27), date(2017, 4, 16), date(2018, 4, 1), date(2019, 4, 21),", "19), date(2021, 5, 2), date(2022, 4, 24), date(2023, 4, 16), date(2024, 5, 5),", "3, 31), date(655, 3, 29), date(700, 4, 11), date(725, 4, 8), date(750, 3,", "4, 21), date(2042, 4, 6), date(2043, 3, 29), date(2044, 4, 17), date(2045, 4,", "date(2003, 4, 27), date(2004, 4, 11), date(2005, 5, 1), date(2006, 4, 23), date(2007,", "date(562, 4, 9), date(569, 4, 21), date(597, 4, 14), date(621, 4, 19), date(636,", "4, 4), date(2000, 4, 23), date(2001, 4, 15), date(2002, 3, 31), date(2003, 4,", "date(2025, 4, 20), date(2026, 4, 12), date(2027, 5, 2), date(2028, 4, 16), date(2029,", "date(2022, 4, 24), date(2023, 4, 16), date(2024, 5, 5), date(2025, 4, 20), date(2026,", "4, 9), date(2035, 4, 29), date(2036, 4, 20), date(2037, 4, 5), date(2038, 4,", "26), date(1412, 4, 3), date(1439, 4, 5), date(1445, 3, 28), date(1531, 4, 9),", "10), ] orthodox_easter_dates = [ date(1990, 4, 15), date(1991, 4, 7), date(1992, 4,", "11), date(2000, 4, 30), date(2001, 4, 15), date(2002, 5, 5), date(2003, 4, 27),", "4, 17), date(2040, 5, 6), date(2041, 4, 21), date(2042, 4, 13), date(2043, 5,", "4, 24), date(2012, 4, 15), date(2013, 5, 5), date(2014, 4, 20), date(2015, 4,", "4, 17), date(1371, 4, 6), date(1391, 3, 26), date(1402, 3, 26), date(1412, 4,", "date(1996, 4, 7), date(1997, 3, 30), date(1998, 4, 12), date(1999, 4, 4), date(2000,", "4, 5), date(2016, 3, 27), date(2017, 4, 16), date(2018, 4, 1), date(2019, 4,", "4, 9), date(2024, 3, 31), date(2025, 4, 20), date(2026, 4, 5), date(2027, 3,", "2050 western_easter_dates = [ date(1990, 4, 15), date(1991, 3, 31), date(1992, 4, 19),", "easter from bs_dateutil.easter import EASTER_WESTERN, EASTER_ORTHODOX, EASTER_JULIAN from datetime import date import pytest", "4, 24), date(2034, 4, 9), date(2035, 4, 29), date(2036, 4, 20), date(2037, 4,", "date(835, 4, 18), date(849, 4, 14), date(867, 3, 30), date(890, 4, 12), date(922,", "18), date(2050, 4, 10), ] orthodox_easter_dates = [ date(1990, 4, 15), date(1991, 4,", "date(1402, 3, 26), date(1412, 4, 3), date(1439, 4, 5), date(1445, 3, 28), date(1531,", "4, 8), date(750, 3, 29), date(782, 4, 7), date(835, 4, 18), date(849, 4,", "11), date(1994, 4, 3), date(1995, 4, 16), date(1996, 4, 7), date(1997, 3, 30),", "date(2050, 4, 17), ] # A random smattering of Julian dates. # Pulled", "12), date(2027, 5, 2), date(2028, 4, 16), date(2029, 4, 8), date(2030, 4, 28),", "def test_easter_orthodox(easter_date): assert easter_date == easter(easter_date.year, EASTER_ORTHODOX) @pytest.mark.parametrize(\"easter_date\", julian_easter_dates) def test_easter_julian(easter_date): assert easter_date", "27), date(1998, 4, 19), date(1999, 4, 11), date(2000, 4, 30), date(2001, 4, 15),", "20), date(2015, 4, 12), date(2016, 5, 1), date(2017, 4, 16), date(2018, 4, 8),", "4), date(2011, 4, 24), date(2012, 4, 15), date(2013, 5, 5), date(2014, 4, 20),", "date(1439, 4, 5), date(1445, 3, 28), date(1531, 4, 9), date(1555, 4, 14), ]", "4, 14), date(1997, 4, 27), date(1998, 4, 19), date(1999, 4, 11), date(2000, 4,", "8), date(2008, 3, 23), date(2009, 4, 12), date(2010, 4, 4), date(2011, 4, 24),", "] # A random smattering of Julian dates. # Pulled values from http://www.kevinlaughery.com/east4099.html", "4, 18), date(849, 4, 14), date(867, 3, 30), date(890, 4, 12), date(922, 4,", "date(2034, 4, 9), date(2035, 3, 25), date(2036, 4, 13), date(2037, 4, 5), date(2038,", "date(2043, 5, 3), date(2044, 4, 24), date(2045, 4, 9), date(2046, 4, 29), date(2047,", "4, 20), date(2026, 4, 12), date(2027, 5, 2), date(2028, 4, 16), date(2029, 4,", "date(934, 4, 6), date(1049, 3, 26), date(1058, 4, 19), date(1113, 4, 6), date(1119,", "3, 28), date(2033, 4, 17), date(2034, 4, 9), date(2035, 3, 25), date(2036, 4," ]
[ "str): try: validator = validateYAML() ok, errs = validator.validate_yaml('configs/schema.yaml', config_file) if ok: print(config_file,", "#Functionality to for reading and using config file # #Author: <NAME> #Date: May", "import yaml import cerberus class validateYAML: def validate_yaml(self, schemaFile: str, yamlFile: str): schema", "\"validated\") with open(config_file, 'r') as stream: self.config = yaml.safe_load(stream) else: print(config_file, \"validation failed\")", "str): schema = eval(open(schemaFile, 'r').read()) v = cerberus.Validator(schema) doc = yaml.safe_load(open(yamlFile, 'r').read()) r", "validate_yaml(self, schemaFile: str, yamlFile: str): schema = eval(open(schemaFile, 'r').read()) v = cerberus.Validator(schema) doc", "__init__(self): self.config = None def load(self, config_file: str): try: validator = validateYAML() ok,", "v.errors class Config: \"\"\" Configuration parsed directly from a YAML file \"\"\" def", "validator.validate_yaml('configs/schema.yaml', config_file) if ok: print(config_file, \"validated\") with open(config_file, 'r') as stream: self.config =", "'r') as stream: self.config = yaml.safe_load(stream) else: print(config_file, \"validation failed\") print(errs) except Exception", "v.validate(doc, schema) return r, v.errors class Config: \"\"\" Configuration parsed directly from a", "import shlex import datetime import yaml import cerberus class validateYAML: def validate_yaml(self, schemaFile:", "datetime import yaml import cerberus class validateYAML: def validate_yaml(self, schemaFile: str, yamlFile: str):", "<NAME> #Date: May 2019 import os import subprocess import pathlib import shlex import", "Couldn\\'t setup config parameters') print(e) def load_str(self, config_str: str): self.config = yaml.load(config_str) def", "if ok: print(config_file, \"validated\") with open(config_file, 'r') as stream: self.config = yaml.safe_load(stream) else:", "Exception as e: print('ERROR: Couldn\\'t setup config parameters') print(e) def load_str(self, config_str: str):", "cerberus.Validator(schema) doc = yaml.safe_load(open(yamlFile, 'r').read()) r = v.validate(doc, schema) return r, v.errors class", "YAML file \"\"\" def __init__(self): self.config = None def load(self, config_file: str): try:", "None def load(self, config_file: str): try: validator = validateYAML() ok, errs = validator.validate_yaml('configs/schema.yaml',", "reading and using config file # #Author: <NAME> #Date: May 2019 import os", "pathlib import shlex import datetime import yaml import cerberus class validateYAML: def validate_yaml(self,", "r = v.validate(doc, schema) return r, v.errors class Config: \"\"\" Configuration parsed directly", "= None def load(self, config_file: str): try: validator = validateYAML() ok, errs =", "print(errs) except Exception as e: print('ERROR: Couldn\\'t setup config parameters') print(e) def load_str(self,", "self.config = yaml.safe_load(stream) else: print(config_file, \"validation failed\") print(errs) except Exception as e: print('ERROR:", "str, yamlFile: str): schema = eval(open(schemaFile, 'r').read()) v = cerberus.Validator(schema) doc = yaml.safe_load(open(yamlFile,", "print(config_file, \"validation failed\") print(errs) except Exception as e: print('ERROR: Couldn\\'t setup config parameters')", "\"validation failed\") print(errs) except Exception as e: print('ERROR: Couldn\\'t setup config parameters') print(e)", "<gh_stars>0 #! /usr/bin/python3 #Functionality to for reading and using config file # #Author:", "import datetime import yaml import cerberus class validateYAML: def validate_yaml(self, schemaFile: str, yamlFile:", "and using config file # #Author: <NAME> #Date: May 2019 import os import", "r, v.errors class Config: \"\"\" Configuration parsed directly from a YAML file \"\"\"", "from a YAML file \"\"\" def __init__(self): self.config = None def load(self, config_file:", "class Config: \"\"\" Configuration parsed directly from a YAML file \"\"\" def __init__(self):", "errs = validator.validate_yaml('configs/schema.yaml', config_file) if ok: print(config_file, \"validated\") with open(config_file, 'r') as stream:", "#Date: May 2019 import os import subprocess import pathlib import shlex import datetime", "import cerberus class validateYAML: def validate_yaml(self, schemaFile: str, yamlFile: str): schema = eval(open(schemaFile,", "May 2019 import os import subprocess import pathlib import shlex import datetime import", "os import subprocess import pathlib import shlex import datetime import yaml import cerberus", "subprocess import pathlib import shlex import datetime import yaml import cerberus class validateYAML:", "= validateYAML() ok, errs = validator.validate_yaml('configs/schema.yaml', config_file) if ok: print(config_file, \"validated\") with open(config_file,", "schema) return r, v.errors class Config: \"\"\" Configuration parsed directly from a YAML", "def validate_yaml(self, schemaFile: str, yamlFile: str): schema = eval(open(schemaFile, 'r').read()) v = cerberus.Validator(schema)", "file \"\"\" def __init__(self): self.config = None def load(self, config_file: str): try: validator", "import subprocess import pathlib import shlex import datetime import yaml import cerberus class", "as stream: self.config = yaml.safe_load(stream) else: print(config_file, \"validation failed\") print(errs) except Exception as", "schema = eval(open(schemaFile, 'r').read()) v = cerberus.Validator(schema) doc = yaml.safe_load(open(yamlFile, 'r').read()) r =", "self.config = None def load(self, config_file: str): try: validator = validateYAML() ok, errs", "try: validator = validateYAML() ok, errs = validator.validate_yaml('configs/schema.yaml', config_file) if ok: print(config_file, \"validated\")", "print('ERROR: Couldn\\'t setup config parameters') print(e) def load_str(self, config_str: str): self.config = yaml.load(config_str)", "Configuration parsed directly from a YAML file \"\"\" def __init__(self): self.config = None", "= yaml.safe_load(open(yamlFile, 'r').read()) r = v.validate(doc, schema) return r, v.errors class Config: \"\"\"", "as e: print('ERROR: Couldn\\'t setup config parameters') print(e) def load_str(self, config_str: str): self.config", "Config: \"\"\" Configuration parsed directly from a YAML file \"\"\" def __init__(self): self.config", "doc = yaml.safe_load(open(yamlFile, 'r').read()) r = v.validate(doc, schema) return r, v.errors class Config:", "schemaFile: str, yamlFile: str): schema = eval(open(schemaFile, 'r').read()) v = cerberus.Validator(schema) doc =", "to for reading and using config file # #Author: <NAME> #Date: May 2019", "= eval(open(schemaFile, 'r').read()) v = cerberus.Validator(schema) doc = yaml.safe_load(open(yamlFile, 'r').read()) r = v.validate(doc,", "yaml import cerberus class validateYAML: def validate_yaml(self, schemaFile: str, yamlFile: str): schema =", "ok: print(config_file, \"validated\") with open(config_file, 'r') as stream: self.config = yaml.safe_load(stream) else: print(config_file,", "'r').read()) v = cerberus.Validator(schema) doc = yaml.safe_load(open(yamlFile, 'r').read()) r = v.validate(doc, schema) return", "setup config parameters') print(e) def load_str(self, config_str: str): self.config = yaml.load(config_str) def get(self,", "import pathlib import shlex import datetime import yaml import cerberus class validateYAML: def", "config file # #Author: <NAME> #Date: May 2019 import os import subprocess import", "yaml.safe_load(stream) else: print(config_file, \"validation failed\") print(errs) except Exception as e: print('ERROR: Couldn\\'t setup", "for reading and using config file # #Author: <NAME> #Date: May 2019 import", "config_file: str): try: validator = validateYAML() ok, errs = validator.validate_yaml('configs/schema.yaml', config_file) if ok:", "e: print('ERROR: Couldn\\'t setup config parameters') print(e) def load_str(self, config_str: str): self.config =", "v = cerberus.Validator(schema) doc = yaml.safe_load(open(yamlFile, 'r').read()) r = v.validate(doc, schema) return r,", "validateYAML() ok, errs = validator.validate_yaml('configs/schema.yaml', config_file) if ok: print(config_file, \"validated\") with open(config_file, 'r')", "#! /usr/bin/python3 #Functionality to for reading and using config file # #Author: <NAME>", "\"\"\" def __init__(self): self.config = None def load(self, config_file: str): try: validator =", "= validator.validate_yaml('configs/schema.yaml', config_file) if ok: print(config_file, \"validated\") with open(config_file, 'r') as stream: self.config", "print(config_file, \"validated\") with open(config_file, 'r') as stream: self.config = yaml.safe_load(stream) else: print(config_file, \"validation", "load(self, config_file: str): try: validator = validateYAML() ok, errs = validator.validate_yaml('configs/schema.yaml', config_file) if", "def __init__(self): self.config = None def load(self, config_file: str): try: validator = validateYAML()", "open(config_file, 'r') as stream: self.config = yaml.safe_load(stream) else: print(config_file, \"validation failed\") print(errs) except", "a YAML file \"\"\" def __init__(self): self.config = None def load(self, config_file: str):", "eval(open(schemaFile, 'r').read()) v = cerberus.Validator(schema) doc = yaml.safe_load(open(yamlFile, 'r').read()) r = v.validate(doc, schema)", "def load(self, config_file: str): try: validator = validateYAML() ok, errs = validator.validate_yaml('configs/schema.yaml', config_file)", "validator = validateYAML() ok, errs = validator.validate_yaml('configs/schema.yaml', config_file) if ok: print(config_file, \"validated\") with", "2019 import os import subprocess import pathlib import shlex import datetime import yaml", "else: print(config_file, \"validation failed\") print(errs) except Exception as e: print('ERROR: Couldn\\'t setup config", "validateYAML: def validate_yaml(self, schemaFile: str, yamlFile: str): schema = eval(open(schemaFile, 'r').read()) v =", "file # #Author: <NAME> #Date: May 2019 import os import subprocess import pathlib", "# #Author: <NAME> #Date: May 2019 import os import subprocess import pathlib import", "#Author: <NAME> #Date: May 2019 import os import subprocess import pathlib import shlex", "print(e) def load_str(self, config_str: str): self.config = yaml.load(config_str) def get(self, field: str): return", "class validateYAML: def validate_yaml(self, schemaFile: str, yamlFile: str): schema = eval(open(schemaFile, 'r').read()) v", "ok, errs = validator.validate_yaml('configs/schema.yaml', config_file) if ok: print(config_file, \"validated\") with open(config_file, 'r') as", "parsed directly from a YAML file \"\"\" def __init__(self): self.config = None def", "using config file # #Author: <NAME> #Date: May 2019 import os import subprocess", "config parameters') print(e) def load_str(self, config_str: str): self.config = yaml.load(config_str) def get(self, field:", "cerberus class validateYAML: def validate_yaml(self, schemaFile: str, yamlFile: str): schema = eval(open(schemaFile, 'r').read())", "yamlFile: str): schema = eval(open(schemaFile, 'r').read()) v = cerberus.Validator(schema) doc = yaml.safe_load(open(yamlFile, 'r').read())", "return r, v.errors class Config: \"\"\" Configuration parsed directly from a YAML file", "parameters') print(e) def load_str(self, config_str: str): self.config = yaml.load(config_str) def get(self, field: str):", "config_file) if ok: print(config_file, \"validated\") with open(config_file, 'r') as stream: self.config = yaml.safe_load(stream)", "shlex import datetime import yaml import cerberus class validateYAML: def validate_yaml(self, schemaFile: str,", "= yaml.safe_load(stream) else: print(config_file, \"validation failed\") print(errs) except Exception as e: print('ERROR: Couldn\\'t", "= v.validate(doc, schema) return r, v.errors class Config: \"\"\" Configuration parsed directly from", "'r').read()) r = v.validate(doc, schema) return r, v.errors class Config: \"\"\" Configuration parsed", "directly from a YAML file \"\"\" def __init__(self): self.config = None def load(self,", "\"\"\" Configuration parsed directly from a YAML file \"\"\" def __init__(self): self.config =", "/usr/bin/python3 #Functionality to for reading and using config file # #Author: <NAME> #Date:", "import os import subprocess import pathlib import shlex import datetime import yaml import", "= cerberus.Validator(schema) doc = yaml.safe_load(open(yamlFile, 'r').read()) r = v.validate(doc, schema) return r, v.errors", "except Exception as e: print('ERROR: Couldn\\'t setup config parameters') print(e) def load_str(self, config_str:", "with open(config_file, 'r') as stream: self.config = yaml.safe_load(stream) else: print(config_file, \"validation failed\") print(errs)", "failed\") print(errs) except Exception as e: print('ERROR: Couldn\\'t setup config parameters') print(e) def", "yaml.safe_load(open(yamlFile, 'r').read()) r = v.validate(doc, schema) return r, v.errors class Config: \"\"\" Configuration", "stream: self.config = yaml.safe_load(stream) else: print(config_file, \"validation failed\") print(errs) except Exception as e:", "def load_str(self, config_str: str): self.config = yaml.load(config_str) def get(self, field: str): return self.config[field]" ]
[ "out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*baz', out)))", "pattern (`*.tc`)\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ = run_vhdeps('ghdl', '-i', DIR+'/simple/multiple-ok')", "out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*baz.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out)))", "-r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_multi_tc_per_file(self):", "\"\"\"Test multiple test cases per file\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _", "test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ = run_vhdeps( 'ghdl',", "code, out, _ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-pfoo_tc', '-pbaz') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl", "with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-p*_tc',", "-a [^\\n]*bar_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*baz.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e", "self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_positive_filename(self): \"\"\"Test positive filename", "test case pattern matching logic (also used by the vsim backend).\"\"\" def test_no_patterns(self):", "out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out)))", "self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*baz.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertFalse(bool(re.search(r'ghdl", "out, _ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-p:*.vhd', '-p:!*baz.vhd') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a", "[^\\n]*baz', out))) def test_multi_tc_per_file(self): \"\"\"Test multiple test cases per file\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' +", "'-i', DIR+'/simple/multiple-ok') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl", "case pattern (`*.tc`)\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ = run_vhdeps('ghdl', '-i',", "-a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*baz.vhd', out))) self.assertFalse(bool(re.search(r'ghdl -e", "out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*baz.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out)))", "0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*baz.vhd', out)))", "def test_negative_name(self): \"\"\"Test negative entity name test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']):", "-e [^\\n]*baz', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r", "run_vhdeps('ghdl', '-i', DIR+'/complex/multi-tc-per-file') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*test_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out)))", "self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_negative_filename(self): \"\"\"Test negative filename", "\"\"\"Tests the GHDL backend.\"\"\" from unittest import TestCase import os import re from", "TestPatterns(TestCase): \"\"\"Tests the test case pattern matching logic (also used by the vsim", "[^\\n]*baz', out))) def test_positive_name(self): \"\"\"Test positive entity name test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:'", "self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl", "out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out)))", "backend).\"\"\" def test_no_patterns(self): \"\"\"Test the default test case pattern (`*.tc`)\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' +", "local.env['PATH']): code, out, _ = run_vhdeps('ghdl', '-i', DIR+'/simple/multiple-ok') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd',", "test_multi_tc_per_file(self): \"\"\"Test multiple test cases per file\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out,", "multiple test cases per file\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ =", "[^\\n]*test_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*baz',", "+ local.env['PATH']): code, out, _ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-p:*.vhd', '-p:!*baz.vhd') self.assertEqual(code,", "run_vhdeps DIR = os.path.realpath(os.path.dirname(__file__)) class TestPatterns(TestCase): \"\"\"Tests the test case pattern matching logic", "self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl", "'ghdl', '-i', DIR+'/simple/multiple-ok', '-p*_tc', '-p!foo*') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a", "-r [^\\n]*foo_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_negative_name(self):", "[^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_positive_filename(self): \"\"\"Test positive filename test case", "[^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*bar_tc',", "self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_positive_filename(self): \"\"\"Test positive filename test case patterns\"\"\" with", "import local from .common import run_vhdeps DIR = os.path.realpath(os.path.dirname(__file__)) class TestPatterns(TestCase): \"\"\"Tests the", "DIR+'/simple/multiple-ok', '-p:*_tc.vhd', '-pbaz') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd', out)))", "-r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_positive_name(self):", "local.env['PATH']): code, out, _ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-pfoo_tc', '-pbaz') self.assertEqual(code, 0)", "os.path.realpath(os.path.dirname(__file__)) class TestPatterns(TestCase): \"\"\"Tests the test case pattern matching logic (also used by", "DIR+'/simple/multiple-ok') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a", "out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*baz.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out)))", "-a [^\\n]*baz.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e", "local from .common import run_vhdeps DIR = os.path.realpath(os.path.dirname(__file__)) class TestPatterns(TestCase): \"\"\"Tests the test", "_ = run_vhdeps('ghdl', '-i', DIR+'/simple/multiple-ok') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a", "self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*baz.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl", "-e [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r", "[^\\n]*baz.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*baz',", "self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*baz.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl", "out))) def test_negative_name(self): \"\"\"Test negative entity name test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' +", "'-p:*_tc.vhd', '-pbaz') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl", "= run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-p:*.vhd', '-p:!*baz.vhd') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out)))", "per file\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ = run_vhdeps('ghdl', '-i', DIR+'/complex/multi-tc-per-file')", "case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ = run_vhdeps( 'ghdl', '-i',", "-a [^\\n]*bar_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*baz.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e", "'-i', DIR+'/simple/multiple-ok', '-p*_tc', '-p!foo*') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd',", "with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-p:*_tc.vhd',", "test case pattern (`*.tc`)\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ = run_vhdeps('ghdl',", "run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-pfoo_tc', '-pbaz') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl", "self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*baz.vhd', out))) self.assertFalse(bool(re.search(r'ghdl", "filename test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ = run_vhdeps(", "out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*baz', out)))", "-a [^\\n]*baz.vhd', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e", "self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def", "-e [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r", "= run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-p*_tc', '-p!foo*') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out)))", "self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def", "+ local.env['PATH']): code, out, _ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-p:*_tc.vhd', '-pbaz') self.assertEqual(code,", "code, out, _ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-p:*.vhd', '-p:!*baz.vhd') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl", "_ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-p:*.vhd', '-p:!*baz.vhd') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd',", "self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl", "[^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc',", "DIR+'/simple/multiple-ok', '-p:*.vhd', '-p:!*baz.vhd') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd', out)))", "self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*test_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl", "DIR = os.path.realpath(os.path.dirname(__file__)) class TestPatterns(TestCase): \"\"\"Tests the test case pattern matching logic (also", "re from plumbum import local from .common import run_vhdeps DIR = os.path.realpath(os.path.dirname(__file__)) class", "= run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-pfoo_tc', '-pbaz') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out)))", "(`*.tc`)\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ = run_vhdeps('ghdl', '-i', DIR+'/simple/multiple-ok') self.assertEqual(code,", "= run_vhdeps('ghdl', '-i', DIR+'/complex/multi-tc-per-file') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*test_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc',", "out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_positive_name(self): \"\"\"Test positive", "\"\"\"Test negative filename test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _", "the default test case pattern (`*.tc`)\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _", "[^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*foo_tc',", "local.env['PATH']): code, out, _ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-p*_tc', '-p!foo*') self.assertEqual(code, 0)", "local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ = run_vhdeps('ghdl', '-i', DIR+'/complex/multi-tc-per-file') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl", "self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_negative_filename(self): \"\"\"Test negative filename test case patterns\"\"\" with", "'-p*_tc', '-p!foo*') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl", "-a [^\\n]*baz.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e", "_ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-p*_tc', '-p!foo*') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd',", "[^\\n]*foo_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc',", "logic (also used by the vsim backend).\"\"\" def test_no_patterns(self): \"\"\"Test the default test", "out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*baz.vhd', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out)))", "\"\"\"Test positive entity name test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out,", "out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out)))", "out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*baz', out)))", "test_positive_filename(self): \"\"\"Test positive filename test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out,", "code, out, _ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-p:*_tc.vhd', '-pbaz') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl", "with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-p:*.vhd',", "run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-p:*.vhd', '-p:!*baz.vhd') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl", "'-pbaz') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a", "out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_negative_filename(self): \"\"\"Test negative", "-e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r", "out, _ = run_vhdeps('ghdl', '-i', DIR+'/complex/multi-tc-per-file') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*test_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl", "by the vsim backend).\"\"\" def test_no_patterns(self): \"\"\"Test the default test case pattern (`*.tc`)\"\"\"", "negative filename test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ =", "unittest import TestCase import os import re from plumbum import local from .common", "matching logic (also used by the vsim backend).\"\"\" def test_no_patterns(self): \"\"\"Test the default", "out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_negative_name(self): \"\"\"Test negative", "self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl", "-a [^\\n]*test_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e", "import TestCase import os import re from plumbum import local from .common import", "def test_no_patterns(self): \"\"\"Test the default test case pattern (`*.tc`)\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']):", "test_negative_filename(self): \"\"\"Test negative filename test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out,", "test_negative_name(self): \"\"\"Test negative entity name test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code,", "os import re from plumbum import local from .common import run_vhdeps DIR =", "run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-p*_tc', '-p!foo*') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl", "self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl", "self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*baz.vhd', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl", "self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*baz.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl", "local.env['PATH']): code, out, _ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-p:*.vhd', '-p:!*baz.vhd') self.assertEqual(code, 0)", "-r [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_positive_name(self): \"\"\"Test positive entity name", "code, out, _ = run_vhdeps('ghdl', '-i', DIR+'/simple/multiple-ok') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out)))", "\"\"\"Tests the test case pattern matching logic (also used by the vsim backend).\"\"\"", "self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl", "pattern matching logic (also used by the vsim backend).\"\"\" def test_no_patterns(self): \"\"\"Test the", "-r [^\\n]*baz', out))) def test_negative_name(self): \"\"\"Test negative entity name test case patterns\"\"\" with", "def test_negative_filename(self): \"\"\"Test negative filename test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code,", "out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_multi_tc_per_file(self): \"\"\"Test multiple", "[^\\n]*foo_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_negative_name(self): \"\"\"Test", ".common import run_vhdeps DIR = os.path.realpath(os.path.dirname(__file__)) class TestPatterns(TestCase): \"\"\"Tests the test case pattern", "-a [^\\n]*bar_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*baz.vhd', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e", "'-p!foo*') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a", "the GHDL backend.\"\"\" from unittest import TestCase import os import re from plumbum", "DIR+'/simple/multiple-ok', '-pfoo_tc', '-pbaz') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd', out)))", "-r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_positive_filename(self):", "self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_positive_name(self): \"\"\"Test positive entity", "+ local.env['PATH']): code, out, _ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-pfoo_tc', '-pbaz') self.assertEqual(code,", "'ghdl', '-i', DIR+'/simple/multiple-ok', '-p:*_tc.vhd', '-pbaz') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a", "[^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*baz.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc',", "[^\\n]*baz', out))) def test_negative_name(self): \"\"\"Test negative entity name test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:'", "GHDL backend.\"\"\" from unittest import TestCase import os import re from plumbum import", "the vsim backend).\"\"\" def test_no_patterns(self): \"\"\"Test the default test case pattern (`*.tc`)\"\"\" with", "-r [^\\n]*baz', out))) def test_positive_filename(self): \"\"\"Test positive filename test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:'", "out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*baz', out)))", "from unittest import TestCase import os import re from plumbum import local from", "+ local.env['PATH']): code, out, _ = run_vhdeps('ghdl', '-i', DIR+'/simple/multiple-ok') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a", "-e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertFalse(bool(re.search(r'ghdl -r", "[^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc',", "TestCase import os import re from plumbum import local from .common import run_vhdeps", "out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*baz.vhd', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out)))", "out, _ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-p:*_tc.vhd', '-pbaz') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a", "_ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-p:*_tc.vhd', '-pbaz') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd',", "case pattern matching logic (also used by the vsim backend).\"\"\" def test_no_patterns(self): \"\"\"Test", "[^\\n]*bar_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*baz.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc',", "import run_vhdeps DIR = os.path.realpath(os.path.dirname(__file__)) class TestPatterns(TestCase): \"\"\"Tests the test case pattern matching", "local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-p*_tc', '-p!foo*')", "+ local.env['PATH']): code, out, _ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-p*_tc', '-p!foo*') self.assertEqual(code,", "self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def", "[^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*baz.vhd', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*foo_tc',", "= os.path.realpath(os.path.dirname(__file__)) class TestPatterns(TestCase): \"\"\"Tests the test case pattern matching logic (also used", "with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-pfoo_tc',", "= run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-p:*_tc.vhd', '-pbaz') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out)))", "the test case pattern matching logic (also used by the vsim backend).\"\"\" def", "[^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc',", "[^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc',", "class TestPatterns(TestCase): \"\"\"Tests the test case pattern matching logic (also used by the", "-a [^\\n]*baz.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e", "self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_negative_name(self): \"\"\"Test negative entity name test case patterns\"\"\"", "test cases per file\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ = run_vhdeps('ghdl',", "test_no_patterns(self): \"\"\"Test the default test case pattern (`*.tc`)\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code,", "'-p:*.vhd', '-p:!*baz.vhd') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl", "DIR+'/complex/multi-tc-per-file') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*test_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e", "[^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*baz',", "(also used by the vsim backend).\"\"\" def test_no_patterns(self): \"\"\"Test the default test case", "'-i', DIR+'/simple/multiple-ok', '-p:*.vhd', '-p:!*baz.vhd') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd',", "= run_vhdeps('ghdl', '-i', DIR+'/simple/multiple-ok') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd',", "positive entity name test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _", "[^\\n]*baz', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz',", "out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_positive_filename(self): \"\"\"Test positive filename test case patterns\"\"\"", "backend.\"\"\" from unittest import TestCase import os import re from plumbum import local", "[^\\n]*baz', out))) def test_positive_filename(self): \"\"\"Test positive filename test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' +", "[^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_negative_filename(self): \"\"\"Test", "vsim backend).\"\"\" def test_no_patterns(self): \"\"\"Test the default test case pattern (`*.tc`)\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:'", "-r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_negative_filename(self):", "out))) def test_negative_filename(self): \"\"\"Test negative filename test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']):", "code, out, _ = run_vhdeps('ghdl', '-i', DIR+'/complex/multi-tc-per-file') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*test_tc.vhd', out)))", "'ghdl', '-i', DIR+'/simple/multiple-ok', '-pfoo_tc', '-pbaz') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a", "out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz', out)))", "out, _ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-pfoo_tc', '-pbaz') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a", "-a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*baz.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e", "[^\\n]*bar_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*baz.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*bar_tc',", "self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*baz.vhd',", "run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-p:*_tc.vhd', '-pbaz') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl", "self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*baz.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl", "-r [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_multi_tc_per_file(self): \"\"\"Test multiple test cases", "[^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_multi_tc_per_file(self): \"\"\"Test multiple test cases per", "self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl", "\"\"\"Test the default test case pattern (`*.tc`)\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out,", "self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_positive_name(self): \"\"\"Test positive entity name test case patterns\"\"\"", "self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl", "out, _ = run_vhdeps('ghdl', '-i', DIR+'/simple/multiple-ok') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl", "self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*baz.vhd', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl", "[^\\n]*baz.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*baz',", "self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertFalse(bool(re.search(r'ghdl", "-e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r", "-r [^\\n]*baz', out))) def test_negative_filename(self): \"\"\"Test negative filename test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:'", "out, _ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-p*_tc', '-p!foo*') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a", "\"\"\"Test positive filename test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _", "+ local.env['PATH']): code, out, _ = run_vhdeps('ghdl', '-i', DIR+'/complex/multi-tc-per-file') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a", "out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out)))", "-r [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_positive_filename(self): \"\"\"Test positive filename test", "out))) def test_positive_filename(self): \"\"\"Test positive filename test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']):", "run_vhdeps('ghdl', '-i', DIR+'/simple/multiple-ok') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd', out)))", "[^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_positive_name(self): \"\"\"Test", "out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out)))", "-e [^\\n]*foo_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r", "'-p:!*baz.vhd') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a", "self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def", "self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl", "'-i', DIR+'/simple/multiple-ok', '-pfoo_tc', '-pbaz') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd',", "'-pfoo_tc', '-pbaz') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl", "self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertFalse(bool(re.search(r'ghdl", "default test case pattern (`*.tc`)\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ =", "name test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ = run_vhdeps(", "out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_positive_filename(self): \"\"\"Test positive", "'-i', DIR+'/complex/multi-tc-per-file') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*test_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl", "from .common import run_vhdeps DIR = os.path.realpath(os.path.dirname(__file__)) class TestPatterns(TestCase): \"\"\"Tests the test case", "[^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_positive_filename(self): \"\"\"Test", "local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-p:*_tc.vhd', '-pbaz')", "[^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz',", "_ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-pfoo_tc', '-pbaz') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd',", "out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_negative_name(self): \"\"\"Test negative entity name test case", "out))) def test_positive_name(self): \"\"\"Test positive entity name test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' +", "DIR+'/simple/multiple-ok', '-p*_tc', '-p!foo*') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd', out)))", "def test_multi_tc_per_file(self): \"\"\"Test multiple test cases per file\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code,", "'ghdl', '-i', DIR+'/simple/multiple-ok', '-p:*.vhd', '-p:!*baz.vhd') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a", "code, out, _ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-p*_tc', '-p!foo*') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl", "self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*test_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc',", "0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*test_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out)))", "[^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_negative_name(self): \"\"\"Test negative entity name test", "out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out)))", "import os import re from plumbum import local from .common import run_vhdeps DIR", "[^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*baz',", "local.env['PATH']): code, out, _ = run_vhdeps('ghdl', '-i', DIR+'/complex/multi-tc-per-file') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*test_tc.vhd',", "test_positive_name(self): \"\"\"Test positive entity name test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code,", "with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ = run_vhdeps('ghdl', '-i', DIR+'/complex/multi-tc-per-file') self.assertEqual(code, 0)", "\"\"\"Test negative entity name test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out,", "out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out)))", "_ = run_vhdeps('ghdl', '-i', DIR+'/complex/multi-tc-per-file') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*test_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e", "out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_positive_name(self): \"\"\"Test positive entity name test case", "[^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_negative_filename(self): \"\"\"Test negative filename test case", "self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*baz.vhd', out))) self.assertTrue(bool(re.search(r'ghdl", "-r [^\\n]*baz', out))) def test_positive_name(self): \"\"\"Test positive entity name test case patterns\"\"\" with", "self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_negative_name(self): \"\"\"Test negative entity", "[^\\n]*baz', out))) def test_negative_filename(self): \"\"\"Test negative filename test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' +", "out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*baz', out)))", "local.env['PATH']): code, out, _ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-p:*_tc.vhd', '-pbaz') self.assertEqual(code, 0)", "-e [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r", "-r [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_negative_name(self): \"\"\"Test negative entity name", "out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz', out)))", "from plumbum import local from .common import run_vhdeps DIR = os.path.realpath(os.path.dirname(__file__)) class TestPatterns(TestCase):", "-e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r", "out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out)))", "out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_negative_filename(self): \"\"\"Test negative filename test case patterns\"\"\"", "self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_multi_tc_per_file(self): \"\"\"Test multiple test", "[^\\n]*baz.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*baz',", "file\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ = run_vhdeps('ghdl', '-i', DIR+'/complex/multi-tc-per-file') self.assertEqual(code,", "local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-p:*.vhd', '-p:!*baz.vhd')", "def test_positive_filename(self): \"\"\"Test positive filename test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code,", "'-i', DIR+'/simple/multiple-ok', '-p:*_tc.vhd', '-pbaz') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*foo_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*bar_tc.vhd',", "used by the vsim backend).\"\"\" def test_no_patterns(self): \"\"\"Test the default test case pattern", "def test_positive_name(self): \"\"\"Test positive entity name test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']):", "local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok', '-pfoo_tc', '-pbaz')", "[^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_positive_name(self): \"\"\"Test positive entity name test", "-e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r", "-r [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_negative_filename(self): \"\"\"Test negative filename test", "out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*baz', out)))", "entity name test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ =", "local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ = run_vhdeps('ghdl', '-i', DIR+'/simple/multiple-ok') self.assertEqual(code, 0) self.assertTrue(bool(re.search(r'ghdl", "import re from plumbum import local from .common import run_vhdeps DIR = os.path.realpath(os.path.dirname(__file__))", "[^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc',", "[^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_multi_tc_per_file(self): \"\"\"Test", "self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_multi_tc_per_file(self): \"\"\"Test multiple test cases per file\"\"\" with", "-r [^\\n]*baz', out))) def test_multi_tc_per_file(self): \"\"\"Test multiple test cases per file\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:'", "plumbum import local from .common import run_vhdeps DIR = os.path.realpath(os.path.dirname(__file__)) class TestPatterns(TestCase): \"\"\"Tests", "[^\\n]*baz.vhd', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*baz',", "patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ = run_vhdeps( 'ghdl', '-i', DIR+'/simple/multiple-ok',", "with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ = run_vhdeps('ghdl', '-i', DIR+'/simple/multiple-ok') self.assertEqual(code, 0)", "positive filename test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ =", "cases per file\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _ = run_vhdeps('ghdl', '-i',", "out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*baz', out))) def test_multi_tc_per_file(self): \"\"\"Test multiple test cases per file\"\"\"", "[^\\n]*bar_tc.vhd', out))) self.assertTrue(bool(re.search(r'ghdl -a [^\\n]*baz.vhd', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*bar_tc',", "-e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r", "out))) def test_multi_tc_per_file(self): \"\"\"Test multiple test cases per file\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']):", "negative entity name test case patterns\"\"\" with local.env(PATH=DIR+'/ghdl/fake-ghdl:' + local.env['PATH']): code, out, _", "self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*foo_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*bar_tc', out))) self.assertTrue(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertTrue(bool(re.search(r'ghdl", "-e [^\\n]*bar_tc', out))) self.assertFalse(bool(re.search(r'ghdl -e [^\\n]*baz', out))) self.assertFalse(bool(re.search(r'ghdl -r [^\\n]*foo_tc', out))) self.assertTrue(bool(re.search(r'ghdl -r" ]
[ "0.5, 'word': 0.5, 'char': 0.5}, ), 'union__word__vect__max_df': (0.7, 0.8, 0.9, 1.0), #0.5, 'union__char__vect__max_df':", "%0.3fs\" % (time() - t0)) print() print(\"Best score: %0.3f\" % grid_search.best_score_) print(\"Best parameters", "('tfidf', TfidfTransformer()), ])), ('char', Pipeline([ ('selector', ItemSelector(key='words')), ('vect', CountVectorizer(ngram_range=(1,5), analyzer='char', max_df=0.8)), ('tfidf', TfidfTransformer()),", "counter counter += 1 origin_to_event = {} for i, oidx in enumerate(orig_idx_array): if", "for sentence in x_dataset: # takes raw text and calculates type token ratio", "'char': 0.5}, # {'meta': 1.0, 'word': 0.5, 'char': 1.0}, # {'meta': 1.0, 'word':", "print('Test result: %.3f' % acc) return acc train_data = load_data(sys.argv[1], sys.argv[3]) test_data =", "add event-to-event info #train_data[0] = add_e2e_scores(train_data[0], train_event[0], train_e2o) #test_data[0] = add_e2e_scores(test_data[0], test_event[0], test_e2o)", "token ratio X_num_token.append(len(sentence)) # takes pos tag text and counts number of noun", "== len(neg) count = 0.0 for p, n in zip(pos, neg): if p[1]", "sys.argv[3]) test_data = load_data(sys.argv[2], sys.argv[3]) #train_event = load_data(sys.argv[4], sys.argv[6]) #test_event = load_data(sys.argv[5], sys.argv[6])", "max_df=0.9)), ('tfidf', TfidfTransformer()), ])), ('char', Pipeline([ ('selector', ItemSelector(key='words')), ('vect', CountVectorizer(ngram_range=(1,5), analyzer='char', max_df=0.8)), ('tfidf',", "0.75, 'word': 0.5, 'char': 1.0}, # {'meta': 0.75, 'word': 0.5, 'char': 0.75}, #", "'''for params in grid_params: print('Current parameters:', params) pipeline.set_params(**params) pipeline.fit(train_data[0], train_data[1]) probs = pipeline.predict_proba(test_data[0])", "'score': float(s), 'normscore': float(ns), 'langpred': bool(lp)} if len(elems) > 5: ecs, es, ens,", "#'tfidf__norm': ('l1', 'l2'), 'clf__alpha': (0.001, 0.0005, 0.0001), #'clf__penalty': ('l2', 'l1'), 'clf__tol': (5e-3, 1e-3,", "labels.append(1) for line in finf: elems = line.strip()#.split('\\t') contents.append(elems) labels.append(0) print(\"data size:\", len(contents))", "a usenet post in a single pass. Takes a sequence of strings and", "in enumerate(original_data_array): if i in origin_to_event: original_data_array[i] = elems + '\\t' + event_data_array[origin_to_event[i]]", "'word': 0.5, 'char': 1.0}, # {'meta': 0.75, 'word': 0.5, 'char': 0.75}, # {'meta':", "1.0, 'char': 0.5}, # {'meta': 1.0, 'word': 0.75, 'char': 1.0}, # {'meta': 1.0,", "import StandardScaler #print(__doc__) import warnings with warnings.catch_warnings(): warnings.filterwarnings(\"ignore\",category=Warning) #DeprecationWarning) # Display progress logs", "0.75, 'char': 1.0}, # {'meta': 0.75, 'word': 0.75, 'char': 0.75}, # {'meta': 0.75,", "n_jobs=-1, verbose=1) print(\"Performing grid search...\") print(\"pipeline:\", [name for name, _ in pipeline.steps]) print(\"parameters:\")", "{'meta': 0.5, 'word': 1.0, 'char': 1.0}, {'meta': 0.4, 'word': 1.0, 'char': 1.0}, {'meta':", "produces a dict of sequences. Keys are `subject` and `body`. \"\"\" def fit(self,", "`subject` and `body`. \"\"\" def fit(self, x, y=None): return self def transform(self, posts):", "score = grid_search.score(test_data[0], test_data[1]) print('Test score: %.3f' % score) probs = grid_search.predict_proba(test_data[0]) pairwise_eval(probs)", "1.0, }, )), ('clf', SGDClassifier(loss='log', alpha=0.0005, tol=0.005, random_state=0)), ]) # uncommenting more parameters", "self def transform(self, x_dataset): X_num_token = list() #X_count_nouns = list() for sentence in", "('l2', 'l1'), 'clf__tol': (5e-3, 1e-3, 5e-4), #'clf__n_iter': (10, 50, 80), } if __name__", "for i, text in enumerate(posts): elems = text.split('\\t') words, cs, s, ns, lp", "sklearn.base import BaseEstimator, TransformerMixin from sklearn.pipeline import FeatureUnion from sklearn.pipeline import Pipeline from", "'elasticnet'), 'tfidf__use_idf': (True, False), 'vect__max_n': (1, 2), 'vect__max_df': (0.5, 0.75, 1.0), 'vect__max_features': (None,", "transform(self, data_dict): return data_dict[self.key] class CustomFeatures(BaseEstimator): def __init__(self): pass def get_feature_names(self): return np.array(['sent_len'])", "pipeline.fit(train_data[0], train_data[1]) # probs = pipeline.predict_proba(test_data[0]) # acc = pairwise_eval(probs) # exit(0) #grid_params", "''' grid_search.fit(train_data[0], train_data[1]) print(\"done in %0.3fs\" % (time() - t0)) print() print(\"Best score:", "+ event_data_array[origin_to_event[i]] if i - half_len in origin_to_event: #print(i, origin_to_event[i-half_len], len(origin_to_event)) original_data_array[i] =", "probs = pipeline.predict_proba(test_data[0]) # acc = pairwise_eval(probs) # exit(0) #grid_params = list(ParameterGrid(parameters)) grid_search", "print(\"pipeline:\", [name for name, _ in pipeline.steps]) print(\"parameters:\") pprint(parameters) t0 = time() #pipeline.fit(train_data[0],", "bool(lp)} if len(elems) > 5: ecs, es, ens, ep = elems[5:] features['meta'][i].update({'event_condscore': float(ecs),", "('meta', Pipeline([ ('selector', ItemSelector(key='meta')), ('vect', DictVectorizer()), ('scale', StandardScaler(with_mean=False)), ])), ('word', Pipeline([ ('selector', ItemSelector(key='words')),", "def fit(self, x, y=None): return self def transform(self, data_dict): return data_dict[self.key] class CustomFeatures(BaseEstimator):", "ens, ep = elems[5:] features['meta'][i].update({'event_condscore': float(ecs), 'event_score': float(es), 'event_normscore': float(ens), 'event_pred': bool(ep)}) return", "1.0}, # {'meta': 0.5, 'word': 0.75, 'char': 0.75}, # {'meta': 0.5, 'word': 0.75,", "object), ('meta', object)]) #('length', object), ('condscore', object), ('score', object), ('normscore', object), ('langpred', bool)])", "0.5, 'char': 0.5}, # {'meta': 0.5, 'word': 1.0, 'char': 1.0}, # {'meta': 0.5,", "i - half_len in origin_to_event: #print(i, origin_to_event[i-half_len], len(origin_to_event)) original_data_array[i] = elems + '\\t'", "print_function from pprint import pprint from time import time import logging import sys", "StandardScaler(with_mean=False)), ])), ('word', Pipeline([ ('selector', ItemSelector(key='words')), ('vect', CountVectorizer(ngram_range=(1,5), max_df=0.9)), ('tfidf', TfidfTransformer()), ])), ('char',", "pipeline.set_params(**params) pipeline.fit(train_data[0], train_data[1]) probs = pipeline.predict_proba(test_data[0]) acc = pairwise_eval(probs) exit(0) ''' grid_search.fit(train_data[0], train_data[1])", "# {'meta': 0.5, 'word': 1.0, 'char': 0.75}, # {'meta': 0.5, 'word': 1.0, 'char':", "'word': 0.75, 'char': 0.5}, # {'meta': 1.0, 'word': 0.5, 'char': 1.0}, # {'meta':", "= 0 for line in einf: elems = line.strip().split() event_idx_dict[elems[0]] = counter counter", "1.0, 'char': 1.0}, # {'meta': 0.75, 'word': 1.0, 'char': 0.75}, # {'meta': 0.75,", "cs, s, ns, lp = elems[:5] #print(elems) features['words'][i] = words features['meta'][i] = {'length':", "0.75, 'char': 0.75}, # {'meta': 0.75, 'word': 0.75, 'char': 0.5}, # {'meta': 0.75,", "[] event_idx_dict = {} with open(orig_idx_file) as oinf, open(event_idx_file) as einf: oinf.readline() einf.readline()", "sklearn.feature_extraction.text import TfidfTransformer from sklearn.linear_model import SGDClassifier from sklearn.model_selection import ParameterGrid, GridSearchCV from", "with open(orig_idx_file) as oinf, open(event_idx_file) as einf: oinf.readline() einf.readline() for line in oinf:", "'vect__max_n': (1, 2), 'vect__max_df': (0.5, 0.75, 1.0), 'vect__max_features': (None, 5000, 10000, 50000)} done", "2) print('middle point: %d' % mid) pos = probs[:mid] neg = probs[mid:] assert", "key): self.key = key def fit(self, x, y=None): return self def transform(self, data_dict):", "CustomFeatures(BaseEstimator): def __init__(self): pass def get_feature_names(self): return np.array(['sent_len']) #, 'lang_prob']) def fit(self, documents,", "'union__transformer_weights': ({'meta': 0.6, 'word': 1.0, 'char': 1.0}, # {'meta': 1.0, 'word': 1.0, 'char':", "print('False') acc = count/mid print('Test result: %.3f' % acc) return acc train_data =", "{} with open(orig_idx_file) as oinf, open(event_idx_file) as einf: oinf.readline() einf.readline() for line in", "data test def load_data(filename, suffix): contents, labels = [], [] #data = StoryData()", "from sklearn.model_selection import ParameterGrid, GridSearchCV from sklearn.base import BaseEstimator, TransformerMixin from sklearn.pipeline import", "key def fit(self, x, y=None): return self def transform(self, data_dict): return data_dict[self.key] class", "line.strip()#.split('\\t') contents.append(elems) labels.append(0) print(\"data size:\", len(contents)) return [contents, labels] def event_orig_mapping(orig_idx_file, event_idx_file): orig_idx_array", "= elems + '\\t' + event_data_array[origin_to_event[i-half_len] + len(origin_to_event)] return original_data_array def pairwise_eval(probs): mid", "'char': 1.0}, # {'meta': 0.75, 'word': 1.0, 'char': 0.75}, # {'meta': 0.75, 'word':", "% (param_name, best_parameters[param_name])) print('predicting on the test data...') score = grid_search.score(test_data[0], test_data[1]) print('Test", "# pipeline.fit(train_data[0], train_data[1]) # probs = pipeline.predict_proba(test_data[0]) # acc = pairwise_eval(probs) # exit(0)", "import DictVectorizer from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.linear_model import", "pos tags (NN, NNS etc.) # X_count_nouns.append(count_nouns(sentence)) X = np.array([X_num_token]).T #, X_count_nouns]).T if", "neg = probs[mid:] assert len(pos) == len(neg) count = 0.0 for p, n", "return self def transform(self, posts): features = np.recarray(shape=(len(posts),), dtype=[('words', object), ('meta', object)]) #('length',", "2), 'vect__max_df': (0.5, 0.75, 1.0), 'vect__max_features': (None, 5000, 10000, 50000)} done in 1737.030s", "# {'meta': 1.0, 'word': 1.0, 'char': 0.75}, # {'meta': 1.0, 'word': 1.0, 'char':", "print(\"data size:\", len(contents)) return [contents, labels] def event_orig_mapping(orig_idx_file, event_idx_file): orig_idx_array = [] event_idx_dict", "'char': 1.0}, # {'meta': 0.5, 'word': 0.5, 'char': 0.75}, # {'meta': 0.5, 'word':", "= StoryData() with open(filename+'.true.'+suffix) as tinf, open(filename+'.false.'+suffix) as finf: for line in tinf:", "'clf__n_iter': (10, 50, 80), 'clf__penalty': ('l2', 'elasticnet'), 'tfidf__use_idf': (True, False), 'vect__max_n': (1, 2),", "(1.0000000000000001e-05, 9.9999999999999995e-07), 'clf__n_iter': (10, 50, 80), 'clf__penalty': ('l2', 'elasticnet'), 'tfidf__use_idf': (True, False), 'vect__max_n':", "1.0}, # {'meta': 0.5, 'word': 0.5, 'char': 0.75}, # {'meta': 0.5, 'word': 0.5,", "0.6, 'word': 1.0, 'char': 1.0}, # {'meta': 1.0, 'word': 1.0, 'char': 0.75}, #", "{'meta': 0.75, 'word': 0.5, 'char': 0.5}, # {'meta': 0.5, 'word': 1.0, 'char': 1.0},", "# trigram or 5-grams #'tfidf__use_idf': (True, False), #'tfidf__norm': ('l1', 'l2'), 'clf__alpha': (0.001, 0.0005,", "(10, 50, 80), } if __name__ == \"__main__\": # multiprocessing requires the fork", "sklearn.preprocessing import StandardScaler #print(__doc__) import warnings with warnings.catch_warnings(): warnings.filterwarnings(\"ignore\",category=Warning) #DeprecationWarning) # Display progress", "'word': 1.0, 'char': 1.0, }, )), ('clf', SGDClassifier(loss='log', alpha=0.0005, tol=0.005, random_state=0)), ]) #", "'word': 0.75, 'char': 0.75}, # {'meta': 0.75, 'word': 0.75, 'char': 0.5}, # {'meta':", "'event_pred': bool(ep)}) return features # ############################################################################# # Load data test def load_data(filename, suffix):", "50, 80), 'clf__penalty': ('l2', 'elasticnet'), 'tfidf__use_idf': (True, False), 'vect__max_n': (1, 2), 'vect__max_df': (0.5,", "(0.7, 0.8, 0.9, 1.0), #0.5, 'union__char__vect__max_df': (0.7, 0.8, 0.9, 1.0), #0.5, #'vect__max_features': (None,", "1.0, 'word': 1.0, 'char': 0.5}, # {'meta': 1.0, 'word': 0.75, 'char': 1.0}, #", "0.0005, 0.0001), #'clf__penalty': ('l2', 'l1'), 'clf__tol': (5e-3, 1e-3, 5e-4), #'clf__n_iter': (10, 50, 80),", "# X_count_nouns.append(count_nouns(sentence)) X = np.array([X_num_token]).T #, X_count_nouns]).T if not hasattr(self, 'scalar'): self.scalar =", "feature extraction and evaluation ========================================================== The dataset used in this example is the", "probs[mid:] assert len(pos) == len(neg) count = 0.0 for p, n in zip(pos,", "i in origin_to_event: original_data_array[i] = elems + '\\t' + event_data_array[origin_to_event[i]] if i -", "add_e2e_scores(train_data[0], train_event[0], train_e2o) #test_data[0] = add_e2e_scores(test_data[0], test_event[0], test_e2o) print('Finished data loading!!') for elem", "0.75, 'char': 0.5}, # {'meta': 0.5, 'word': 0.5, 'char': 1.0}, # {'meta': 0.5,", "n in zip(pos, neg): if p[1] > n[1]: count += 1.0 # print('True')", "TransformerMixin): \"\"\"Extract the subject & body from a usenet post in a single", "(1, 4), #'union__char__vect__ngram_range': ((1, 4), (1, 5)), # trigram or 5-grams #'tfidf__use_idf': (True,", "TfidfTransformer()), ])), ('char', Pipeline([ ('selector', ItemSelector(key='words')), ('vect', CountVectorizer(ngram_range=(1,5), analyzer='char', max_df=0.8)), ('tfidf', TfidfTransformer()), ])),", "# classifier pipeline = Pipeline([ ('featextract', FeatureExtractor()), ('union', FeatureUnion( transformer_list=[ ('meta', Pipeline([ ('selector',", "dtype=[('words', object), ('meta', object)]) #('length', object), ('condscore', object), ('score', object), ('normscore', object), ('langpred',", "(1, 5)), # trigram or 5-grams (1, 4), #'union__char__vect__ngram_range': ((1, 4), (1, 5)),", "5)), # trigram or 5-grams (1, 4), #'union__char__vect__ngram_range': ((1, 4), (1, 5)), #", "max_df=0.8)), ('tfidf', TfidfTransformer()), ])), ], transformer_weights={ 'meta': 0.3, 'word': 1.0, 'char': 1.0, },", "exploring power but will # increase processing time in a combinatorial way parameters", "float(es), 'event_normscore': float(ens), 'event_pred': bool(ep)}) return features # ############################################################################# # Load data test", "0.75, 'word': 0.5, 'char': 0.5}, # {'meta': 0.5, 'word': 1.0, 'char': 1.0}, #", "dictionary size:', len(origin_to_event)) return origin_to_event def add_e2e_scores(original_data_array, event_data_array, origin_to_event): assert len(event_data_array) == 2", "Pipeline([ ('featextract', FeatureExtractor()), ('union', FeatureUnion( transformer_list=[ ('meta', Pipeline([ ('selector', ItemSelector(key='meta')), ('vect', DictVectorizer()), ('scale',", "in train_data[0][:10]: print (elem) # ############################################################################# # Define a pipeline combining a text", "contents, labels = [], [] #data = StoryData() with open(filename+'.true.'+suffix) as tinf, open(filename+'.false.'+suffix)", "a __main__ protected # block # find the best parameters for both the", "find the best parameters for both the feature extraction and the # classifier", "print(\"Performing grid search...\") print(\"pipeline:\", [name for name, _ in pipeline.steps]) print(\"parameters:\") pprint(parameters) t0", "<<EMAIL>> # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # License: BSD 3 clause from", "0.75}, # {'meta': 1.0, 'word': 0.5, 'char': 0.5}, {'meta': 0.7, 'word': 1.0, 'char':", "Keys are `subject` and `body`. \"\"\" def fit(self, x, y=None): return self def", "{'meta': 0.5, 'word': 0.75, 'char': 1.0}, # {'meta': 0.5, 'word': 0.75, 'char': 0.75},", "text in enumerate(posts): elems = text.split('\\t') words, cs, s, ns, lp = elems[:5]", "0.5, 'char': 0.75}, # {'meta': 0.75, 'word': 0.5, 'char': 0.5}, # {'meta': 0.5,", "trigram or 5-grams #'tfidf__use_idf': (True, False), #'tfidf__norm': ('l1', 'l2'), 'clf__alpha': (0.001, 0.0005, 0.0001),", "1.0, 'char': 1.0}, # {'meta': 0.5, 'word': 1.0, 'char': 0.75}, # {'meta': 0.5,", "#pipeline.fit(train_data[0], train_data[1]) #.contents, train_data.labels) '''for params in grid_params: print('Current parameters:', params) pipeline.set_params(**params) pipeline.fit(train_data[0],", "a combinatorial way parameters = { 'union__transformer_weights': ({'meta': 0.6, 'word': 1.0, 'char': 1.0},", "(None, 5000, 10000, 50000)} done in 1737.030s Best score: 0.940 Best parameters set:", "1.0, 'char': 1.0}, {'meta': 0.3, 'word': 1.0, 'char': 1.0}, # {'meta': 0.75, 'word':", "Pipeline([ ('selector', ItemSelector(key='words')), ('vect', CountVectorizer(ngram_range=(1,5), analyzer='char', max_df=0.8)), ('tfidf', TfidfTransformer()), ])), ], transformer_weights={ 'meta':", "{'meta': 0.75, 'word': 0.5, 'char': 1.0}, # {'meta': 0.75, 'word': 0.5, 'char': 0.75},", "or setting them to None to get the 20 of them. Here is", "'word': 0.5, 'char': 0.75}, # {'meta': 0.5, 'word': 0.5, 'char': 0.5}, ), 'union__word__vect__max_df':", "'talk.religion.misc'] 1427 documents 2 categories Performing grid search... pipeline: ['vect', 'tfidf', 'clf'] parameters:", "documents 2 categories Performing grid search... pipeline: ['vect', 'tfidf', 'clf'] parameters: {'clf__alpha': (1.0000000000000001e-05,", "Pipeline from sklearn.preprocessing import StandardScaler #print(__doc__) import warnings with warnings.catch_warnings(): warnings.filterwarnings(\"ignore\",category=Warning) #DeprecationWarning) #", "bool(ep)}) return features # ############################################################################# # Load data test def load_data(filename, suffix): contents,", "GridSearchCV(pipeline, parameters, cv=5, n_jobs=-1, verbose=1) print(\"Performing grid search...\") print(\"pipeline:\", [name for name, _", "5000, 10000, 50000), #'union__word__vect__ngram_range': ((1, 4), (1, 5)), # trigram or 5-grams (1,", "'word': 1.0, 'char': 0.75}, # {'meta': 1.0, 'word': 1.0, 'char': 0.5}, # {'meta':", "used in this example is the 20 newsgroups dataset which will be automatically", "'char': 1.0}, # {'meta': 1.0, 'word': 0.5, 'char': 0.75}, # {'meta': 1.0, 'word':", "# {'meta': 0.5, 'word': 0.75, 'char': 1.0}, # {'meta': 0.5, 'word': 0.75, 'char':", "stdout logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') class ItemSelector(BaseEstimator, TransformerMixin): def __init__(self, key): self.key =", "(1, 2), 'vect__max_df': (0.5, 0.75, 1.0), 'vect__max_features': (None, 5000, 10000, 50000)} done in", "def transform(self, data_dict): return data_dict[self.key] class CustomFeatures(BaseEstimator): def __init__(self): pass def get_feature_names(self): return", "import sys import numpy as np from sklearn.feature_extraction import DictVectorizer from sklearn.feature_extraction.text import", "y=None): return self def transform(self, posts): features = np.recarray(shape=(len(posts),), dtype=[('words', object), ('meta', object)])", "========================================================== Sample pipeline for text feature extraction and evaluation ========================================================== The dataset used", "sentence in x_dataset: # takes raw text and calculates type token ratio X_num_token.append(len(sentence))", "(len(event_data_array), len(origin_to_event)) assert len(original_data_array) >= len(event_data_array) half_len = len(original_data_array) / 2 for i,", "{'meta': 1.0, 'word': 1.0, 'char': 0.5}, # {'meta': 1.0, 'word': 0.75, 'char': 1.0},", "= pipeline.predict_proba(test_data[0]) # acc = pairwise_eval(probs) # exit(0) #grid_params = list(ParameterGrid(parameters)) grid_search =", "'word': 1.0, 'char': 0.5}, # {'meta': 0.75, 'word': 0.75, 'char': 1.0}, # {'meta':", "'elasticnet' tfidf__use_idf: True vect__max_n: 2 vect__max_df: 0.75 vect__max_features: 50000 \"\"\" # Author: <NAME>", "import pprint from time import time import logging import sys import numpy as", "X_count_nouns.append(count_nouns(sentence)) X = np.array([X_num_token]).T #, X_count_nouns]).T if not hasattr(self, 'scalar'): self.scalar = StandardScaler().fit(X)", "post in a single pass. Takes a sequence of strings and produces a", ">= len(event_data_array) half_len = len(original_data_array) / 2 for i, elems in enumerate(original_data_array): if", "if i in origin_to_event: original_data_array[i] = elems + '\\t' + event_data_array[origin_to_event[i]] if i", "pos = probs[:mid] neg = probs[mid:] assert len(pos) == len(neg) count = 0.0", "'word': 0.5, 'char': 0.5}, ), 'union__word__vect__max_df': (0.7, 0.8, 0.9, 1.0), #0.5, 'union__char__vect__max_df': (0.7,", "# print('True') # else: # print('False') acc = count/mid print('Test result: %.3f' %", "'event_score': float(es), 'event_normscore': float(ens), 'event_pred': bool(ep)}) return features # ############################################################################# # Load data", "acc train_data = load_data(sys.argv[1], sys.argv[3]) test_data = load_data(sys.argv[2], sys.argv[3]) #train_event = load_data(sys.argv[4], sys.argv[6])", "print(\"done in %0.3fs\" % (time() - t0)) print() print(\"Best score: %0.3f\" % grid_search.best_score_)", "elems = line.strip().split() orig_idx_array.append(elems[0]) counter = 0 for line in einf: elems =", "be automatically downloaded and then cached and reused for the document classification example.", "Best parameters set: clf__alpha: 9.9999999999999995e-07 clf__n_iter: 50 clf__penalty: 'elasticnet' tfidf__use_idf: True vect__max_n: 2", "original_data_array[i] = elems + '\\t' + event_data_array[origin_to_event[i-half_len] + len(origin_to_event)] return original_data_array def pairwise_eval(probs):", "{'meta': 1.0, 'word': 0.5, 'char': 1.0}, # {'meta': 1.0, 'word': 0.5, 'char': 0.75},", "#print(elems) features['words'][i] = words features['meta'][i] = {'length': len(words.split()), 'condscore': float(cs), 'score': float(s), 'normscore':", "'char': 0.75}, # {'meta': 0.75, 'word': 1.0, 'char': 0.5}, # {'meta': 0.75, 'word':", "is a sample output of a run on a quad-core machine:: Loading 20", "'tfidf', 'clf'] parameters: {'clf__alpha': (1.0000000000000001e-05, 9.9999999999999995e-07), 'clf__n_iter': (10, 50, 80), 'clf__penalty': ('l2', 'elasticnet'),", "{'meta': 0.5, 'word': 0.5, 'char': 0.5}, ), 'union__word__vect__max_df': (0.7, 0.8, 0.9, 1.0), #0.5,", "4), (1, 5)), # trigram or 5-grams #'tfidf__use_idf': (True, False), #'tfidf__norm': ('l1', 'l2'),", "name, _ in pipeline.steps]) print(\"parameters:\") pprint(parameters) t0 = time() #pipeline.fit(train_data[0], train_data[1]) #.contents, train_data.labels)", "features = np.recarray(shape=(len(posts),), dtype=[('words', object), ('meta', object)]) #('length', object), ('condscore', object), ('score', object),", "machine:: Loading 20 newsgroups dataset for categories: ['alt.atheism', 'talk.religion.misc'] 1427 documents 2 categories", "done in 1737.030s Best score: 0.940 Best parameters set: clf__alpha: 9.9999999999999995e-07 clf__n_iter: 50", "'char': 1.0}, {'meta': 0.4, 'word': 1.0, 'char': 1.0}, {'meta': 0.3, 'word': 1.0, 'char':", "0.3, 'word': 1.0, 'char': 1.0}, # {'meta': 0.75, 'word': 1.0, 'char': 0.75}, #", "= list(ParameterGrid(parameters)) grid_search = GridSearchCV(pipeline, parameters, cv=5, n_jobs=-1, verbose=1) print(\"Performing grid search...\") print(\"pipeline:\",", "9.9999999999999995e-07 clf__n_iter: 50 clf__penalty: 'elasticnet' tfidf__use_idf: True vect__max_n: 2 vect__max_df: 0.75 vect__max_features: 50000", "then cached and reused for the document classification example. You can adjust the", "from sklearn.base import BaseEstimator, TransformerMixin from sklearn.pipeline import FeatureUnion from sklearn.pipeline import Pipeline", "#test_e2o = event_orig_mapping(sys.argv[9], sys.argv[10]) # add event-to-event info #train_data[0] = add_e2e_scores(train_data[0], train_event[0], train_e2o)", "with a simple # classifier pipeline = Pipeline([ ('featextract', FeatureExtractor()), ('union', FeatureUnion( transformer_list=[", "]) # uncommenting more parameters will give better exploring power but will #", "trigram or 5-grams (1, 4), #'union__char__vect__ngram_range': ((1, 4), (1, 5)), # trigram or", "0.75, 'char': 1.0}, # {'meta': 1.0, 'word': 0.75, 'char': 0.75}, # {'meta': 1.0,", "reused for the document classification example. You can adjust the number of categories", "- half_len in origin_to_event: #print(i, origin_to_event[i-half_len], len(origin_to_event)) original_data_array[i] = elems + '\\t' +", "'char': 0.75}, # {'meta': 0.75, 'word': 0.75, 'char': 0.5}, # {'meta': 0.75, 'word':", "combinatorial way parameters = { 'union__transformer_weights': ({'meta': 0.6, 'word': 1.0, 'char': 1.0}, #", "get the 20 of them. Here is a sample output of a run", "'word': 1.0, 'char': 1.0}, # {'meta': 1.0, 'word': 1.0, 'char': 0.75}, # {'meta':", "# {'meta': 0.5, 'word': 0.75, 'char': 0.5}, # {'meta': 0.5, 'word': 0.5, 'char':", "class FeatureExtractor(BaseEstimator, TransformerMixin): \"\"\"Extract the subject & body from a usenet post in", "as np from sklearn.feature_extraction import DictVectorizer from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import", "0.5, 'word': 0.75, 'char': 0.75}, # {'meta': 0.5, 'word': 0.75, 'char': 0.5}, #", "giving their names to the dataset loader or setting them to None to", "their names to the dataset loader or setting them to None to get", "line.strip().split() event_idx_dict[elems[0]] = counter counter += 1 origin_to_event = {} for i, oidx", "a quad-core machine:: Loading 20 newsgroups dataset for categories: ['alt.atheism', 'talk.religion.misc'] 1427 documents", "better exploring power but will # increase processing time in a combinatorial way", "ParameterGrid, GridSearchCV from sklearn.base import BaseEstimator, TransformerMixin from sklearn.pipeline import FeatureUnion from sklearn.pipeline", "load_data(sys.argv[1], sys.argv[3]) test_data = load_data(sys.argv[2], sys.argv[3]) #train_event = load_data(sys.argv[4], sys.argv[6]) #test_event = load_data(sys.argv[5],", "'word': 1.0, 'char': 1.0}, # {'meta': 0.75, 'word': 1.0, 'char': 0.75}, # {'meta':", "way parameters = { 'union__transformer_weights': ({'meta': 0.6, 'word': 1.0, 'char': 1.0}, # {'meta':", "= GridSearchCV(pipeline, parameters, cv=5, n_jobs=-1, verbose=1) print(\"Performing grid search...\") print(\"pipeline:\", [name for name,", "1.0, 'char': 0.75}, # {'meta': 0.5, 'word': 1.0, 'char': 0.5}, # {'meta': 0.5,", "1.0}, # {'meta': 0.5, 'word': 1.0, 'char': 0.75}, # {'meta': 0.5, 'word': 1.0,", "the document classification example. You can adjust the number of categories by giving", "sorted(parameters.keys()): print(\"\\t%s: %r\" % (param_name, best_parameters[param_name])) print('predicting on the test data...') score =", "requires the fork to happen in a __main__ protected # block # find", "pipeline: ['vect', 'tfidf', 'clf'] parameters: {'clf__alpha': (1.0000000000000001e-05, 9.9999999999999995e-07), 'clf__n_iter': (10, 50, 80), 'clf__penalty':", "& body from a usenet post in a single pass. Takes a sequence", "example is the 20 newsgroups dataset which will be automatically downloaded and then", "= event_orig_mapping(sys.argv[9], sys.argv[10]) # add event-to-event info #train_data[0] = add_e2e_scores(train_data[0], train_event[0], train_e2o) #test_data[0]", "elem in train_data[0][:10]: print (elem) # ############################################################################# # Define a pipeline combining a", "CountVectorizer(ngram_range=(1,5), max_df=0.9)), ('tfidf', TfidfTransformer()), ])), ('char', Pipeline([ ('selector', ItemSelector(key='words')), ('vect', CountVectorizer(ngram_range=(1,5), analyzer='char', max_df=0.8)),", "pipeline.predict_proba(test_data[0]) # acc = pairwise_eval(probs) # exit(0) #grid_params = list(ParameterGrid(parameters)) grid_search = GridSearchCV(pipeline,", "Display progress logs on stdout logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') class ItemSelector(BaseEstimator, TransformerMixin): def", "a dict of sequences. Keys are `subject` and `body`. \"\"\" def fit(self, x,", "tag text and counts number of noun pos tags (NN, NNS etc.) #", "or 5-grams (1, 4), #'union__char__vect__ngram_range': ((1, 4), (1, 5)), # trigram or 5-grams", "load_data(sys.argv[5], sys.argv[6]) #train_e2o = event_orig_mapping(sys.argv[7], sys.argv[8]) #test_e2o = event_orig_mapping(sys.argv[9], sys.argv[10]) # add event-to-event", "can adjust the number of categories by giving their names to the dataset", "('normscore', object), ('langpred', bool)]) for i, text in enumerate(posts): elems = text.split('\\t') words,", "extractor with a simple # classifier pipeline = Pipeline([ ('featextract', FeatureExtractor()), ('union', FeatureUnion(", "= { 'union__transformer_weights': ({'meta': 0.6, 'word': 1.0, 'char': 1.0}, # {'meta': 1.0, 'word':", "'l1'), 'clf__tol': (5e-3, 1e-3, 5e-4), #'clf__n_iter': (10, 50, 80), } if __name__ ==", "train_e2o) #test_data[0] = add_e2e_scores(test_data[0], test_event[0], test_e2o) print('Finished data loading!!') for elem in train_data[0][:10]:", "of strings and produces a dict of sequences. Keys are `subject` and `body`.", "'vect__max_df': (0.5, 0.75, 1.0), 'vect__max_features': (None, 5000, 10000, 50000)} done in 1737.030s Best", "'clf__alpha': (0.001, 0.0005, 0.0001), #'clf__penalty': ('l2', 'l1'), 'clf__tol': (5e-3, 1e-3, 5e-4), #'clf__n_iter': (10,", "'normscore': float(ns), 'langpred': bool(lp)} if len(elems) > 5: ecs, es, ens, ep =", "elems = line.strip().split() event_idx_dict[elems[0]] = counter counter += 1 origin_to_event = {} for", "1.0), #0.5, #'vect__max_features': (None, 5000, 10000, 50000), #'union__word__vect__ngram_range': ((1, 4), (1, 5)), #", "if __name__ == \"__main__\": # multiprocessing requires the fork to happen in a", "pass def get_feature_names(self): return np.array(['sent_len']) #, 'lang_prob']) def fit(self, documents, y=None): return self", "the test data...') score = grid_search.score(test_data[0], test_data[1]) print('Test score: %.3f' % score) probs", "from a usenet post in a single pass. Takes a sequence of strings", "0.8, 0.9, 1.0), #0.5, #'vect__max_features': (None, 5000, 10000, 50000), #'union__word__vect__ngram_range': ((1, 4), (1,", "'\\t' + event_data_array[origin_to_event[i]] if i - half_len in origin_to_event: #print(i, origin_to_event[i-half_len], len(origin_to_event)) original_data_array[i]", "TransformerMixin from sklearn.pipeline import FeatureUnion from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler", "('langpred', bool)]) for i, text in enumerate(posts): elems = text.split('\\t') words, cs, s,", "class CustomFeatures(BaseEstimator): def __init__(self): pass def get_feature_names(self): return np.array(['sent_len']) #, 'lang_prob']) def fit(self,", "in 1737.030s Best score: 0.940 Best parameters set: clf__alpha: 9.9999999999999995e-07 clf__n_iter: 50 clf__penalty:", "len(original_data_array) >= len(event_data_array) half_len = len(original_data_array) / 2 for i, elems in enumerate(original_data_array):", "<<EMAIL>> # License: BSD 3 clause from __future__ import print_function from pprint import", "1.0}, {'meta': 0.3, 'word': 1.0, 'char': 1.0}, # {'meta': 0.75, 'word': 1.0, 'char':", "print('Current parameters:', params) pipeline.set_params(**params) pipeline.fit(train_data[0], train_data[1]) probs = pipeline.predict_proba(test_data[0]) acc = pairwise_eval(probs) exit(0)", "for line in einf: elems = line.strip().split() event_idx_dict[elems[0]] = counter counter += 1", "in x_dataset: # takes raw text and calculates type token ratio X_num_token.append(len(sentence)) #", "train_data[1]) #.contents, train_data.labels) '''for params in grid_params: print('Current parameters:', params) pipeline.set_params(**params) pipeline.fit(train_data[0], train_data[1])", "counter = 0 for line in einf: elems = line.strip().split() event_idx_dict[elems[0]] = counter", "len(origin_to_event)) return origin_to_event def add_e2e_scores(original_data_array, event_data_array, origin_to_event): assert len(event_data_array) == 2 * len(origin_to_event),", "= load_data(sys.argv[4], sys.argv[6]) #test_event = load_data(sys.argv[5], sys.argv[6]) #train_e2o = event_orig_mapping(sys.argv[7], sys.argv[8]) #test_e2o =", "= load_data(sys.argv[5], sys.argv[6]) #train_e2o = event_orig_mapping(sys.argv[7], sys.argv[8]) #test_e2o = event_orig_mapping(sys.argv[9], sys.argv[10]) # add", "orig_idx_array = [] event_idx_dict = {} with open(orig_idx_file) as oinf, open(event_idx_file) as einf:", "- t0)) print() print(\"Best score: %0.3f\" % grid_search.best_score_) print(\"Best parameters set:\") best_parameters =", "(10, 50, 80), 'clf__penalty': ('l2', 'elasticnet'), 'tfidf__use_idf': (True, False), 'vect__max_n': (1, 2), 'vect__max_df':", "x_dataset: # takes raw text and calculates type token ratio X_num_token.append(len(sentence)) # takes", "def load_data(filename, suffix): contents, labels = [], [] #data = StoryData() with open(filename+'.true.'+suffix)", "0.75}, # {'meta': 0.5, 'word': 1.0, 'char': 0.5}, # {'meta': 0.5, 'word': 0.75,", "len(elems) > 5: ecs, es, ens, ep = elems[5:] features['meta'][i].update({'event_condscore': float(ecs), 'event_score': float(es),", "20 of them. Here is a sample output of a run on a", "list() for sentence in x_dataset: # takes raw text and calculates type token", "('selector', ItemSelector(key='words')), ('vect', CountVectorizer(ngram_range=(1,5), max_df=0.9)), ('tfidf', TfidfTransformer()), ])), ('char', Pipeline([ ('selector', ItemSelector(key='words')), ('vect',", "param_name in sorted(parameters.keys()): print(\"\\t%s: %r\" % (param_name, best_parameters[param_name])) print('predicting on the test data...')", "half_len = len(original_data_array) / 2 for i, elems in enumerate(original_data_array): if i in", "import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.linear_model import SGDClassifier from sklearn.model_selection import", "def fit(self, x, y=None): return self def transform(self, posts): features = np.recarray(shape=(len(posts),), dtype=[('words',", "sys.argv[6]) #test_event = load_data(sys.argv[5], sys.argv[6]) #train_e2o = event_orig_mapping(sys.argv[7], sys.argv[8]) #test_e2o = event_orig_mapping(sys.argv[9], sys.argv[10])", "#test_event = load_data(sys.argv[5], sys.argv[6]) #train_e2o = event_orig_mapping(sys.argv[7], sys.argv[8]) #test_e2o = event_orig_mapping(sys.argv[9], sys.argv[10]) #", "0.75, 'word': 0.75, 'char': 0.75}, # {'meta': 0.75, 'word': 0.75, 'char': 0.5}, #", "count += 1.0 # print('True') # else: # print('False') acc = count/mid print('Test", "0.5, 'word': 0.75, 'char': 1.0}, # {'meta': 0.5, 'word': 0.75, 'char': 0.75}, #", "pipeline combining a text feature extractor with a simple # classifier pipeline =", "features['words'][i] = words features['meta'][i] = {'length': len(words.split()), 'condscore': float(cs), 'score': float(s), 'normscore': float(ns),", "} if __name__ == \"__main__\": # multiprocessing requires the fork to happen in", "origin_to_event def add_e2e_scores(original_data_array, event_data_array, origin_to_event): assert len(event_data_array) == 2 * len(origin_to_event), (len(event_data_array), len(origin_to_event))", "for line in finf: elems = line.strip()#.split('\\t') contents.append(elems) labels.append(0) print(\"data size:\", len(contents)) return", "from __future__ import print_function from pprint import pprint from time import time import", "elems = line.strip()#.split('\\t') contents.append(elems) labels.append(0) print(\"data size:\", len(contents)) return [contents, labels] def event_orig_mapping(orig_idx_file,", "fit(self, x, y=None): return self def transform(self, data_dict): return data_dict[self.key] class CustomFeatures(BaseEstimator): def", "as finf: for line in tinf: elems = line.strip()#.split('\\t') contents.append(elems) labels.append(1) for line", "in einf: elems = line.strip().split() event_idx_dict[elems[0]] = counter counter += 1 origin_to_event =", "False), 'vect__max_n': (1, 2), 'vect__max_df': (0.5, 0.75, 1.0), 'vect__max_features': (None, 5000, 10000, 50000)}", "'char': 0.5}, # {'meta': 0.5, 'word': 0.75, 'char': 1.0}, # {'meta': 0.5, 'word':", "# block # find the best parameters for both the feature extraction and", "('char', Pipeline([ ('selector', ItemSelector(key='words')), ('vect', CountVectorizer(ngram_range=(1,5), analyzer='char', max_df=0.8)), ('tfidf', TfidfTransformer()), ])), ], transformer_weights={", "{'meta': 0.3, 'word': 1.0, 'char': 1.0}, # {'meta': 0.75, 'word': 1.0, 'char': 0.75},", "Load data test def load_data(filename, suffix): contents, labels = [], [] #data =", "import time import logging import sys import numpy as np from sklearn.feature_extraction import", "'char': 0.75}, # {'meta': 1.0, 'word': 0.5, 'char': 0.5}, {'meta': 0.7, 'word': 1.0,", "'word': 0.5, 'char': 0.5}, # {'meta': 0.5, 'word': 1.0, 'char': 1.0}, # {'meta':", "probs = pipeline.predict_proba(test_data[0]) acc = pairwise_eval(probs) exit(0) ''' grid_search.fit(train_data[0], train_data[1]) print(\"done in %0.3fs\"", "+= 1 origin_to_event = {} for i, oidx in enumerate(orig_idx_array): if oidx in", "#X_count_nouns = list() for sentence in x_dataset: # takes raw text and calculates", "import SGDClassifier from sklearn.model_selection import ParameterGrid, GridSearchCV from sklearn.base import BaseEstimator, TransformerMixin from", "strings and produces a dict of sequences. Keys are `subject` and `body`. \"\"\"", "'char': 1.0}, # {'meta': 0.75, 'word': 0.75, 'char': 0.75}, # {'meta': 0.75, 'word':", "'clf'] parameters: {'clf__alpha': (1.0000000000000001e-05, 9.9999999999999995e-07), 'clf__n_iter': (10, 50, 80), 'clf__penalty': ('l2', 'elasticnet'), 'tfidf__use_idf':", "{'meta': 0.4, 'word': 1.0, 'char': 1.0}, {'meta': 0.3, 'word': 1.0, 'char': 1.0}, #", "50000), #'union__word__vect__ngram_range': ((1, 4), (1, 5)), # trigram or 5-grams (1, 4), #'union__char__vect__ngram_range':", "The dataset used in this example is the 20 newsgroups dataset which will", "a sequence of strings and produces a dict of sequences. Keys are `subject`", "data_dict): return data_dict[self.key] class CustomFeatures(BaseEstimator): def __init__(self): pass def get_feature_names(self): return np.array(['sent_len']) #,", "Author: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # License: BSD 3", "loading!!') for elem in train_data[0][:10]: print (elem) # ############################################################################# # Define a pipeline", "'char': 1.0}, {'meta': 0.5, 'word': 1.0, 'char': 1.0}, {'meta': 0.4, 'word': 1.0, 'char':", "best_parameters[param_name])) print('predicting on the test data...') score = grid_search.score(test_data[0], test_data[1]) print('Test score: %.3f'", "data_dict[self.key] class CustomFeatures(BaseEstimator): def __init__(self): pass def get_feature_names(self): return np.array(['sent_len']) #, 'lang_prob']) def", "Takes a sequence of strings and produces a dict of sequences. Keys are", "evaluation ========================================================== The dataset used in this example is the 20 newsgroups dataset", "10000, 50000)} done in 1737.030s Best score: 0.940 Best parameters set: clf__alpha: 9.9999999999999995e-07", "return data_dict[self.key] class CustomFeatures(BaseEstimator): def __init__(self): pass def get_feature_names(self): return np.array(['sent_len']) #, 'lang_prob'])", "vect__max_n: 2 vect__max_df: 0.75 vect__max_features: 50000 \"\"\" # Author: <NAME> <<EMAIL>> # <NAME>", "print() print(\"Best score: %0.3f\" % grid_search.best_score_) print(\"Best parameters set:\") best_parameters = grid_search.best_estimator_.get_params() for", "CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.linear_model import SGDClassifier from sklearn.model_selection import ParameterGrid,", "hasattr(self, 'scalar'): self.scalar = StandardScaler().fit(X) return self.scalar.transform(X) class FeatureExtractor(BaseEstimator, TransformerMixin): \"\"\"Extract the subject", "print('Finished data loading!!') for elem in train_data[0][:10]: print (elem) # ############################################################################# # Define", "sequences. Keys are `subject` and `body`. \"\"\" def fit(self, x, y=None): return self", "etc.) # X_count_nouns.append(count_nouns(sentence)) X = np.array([X_num_token]).T #, X_count_nouns]).T if not hasattr(self, 'scalar'): self.scalar", "return self.scalar.transform(X) class FeatureExtractor(BaseEstimator, TransformerMixin): \"\"\"Extract the subject & body from a usenet", "open(orig_idx_file) as oinf, open(event_idx_file) as einf: oinf.readline() einf.readline() for line in oinf: elems", "parameters set: clf__alpha: 9.9999999999999995e-07 clf__n_iter: 50 clf__penalty: 'elasticnet' tfidf__use_idf: True vect__max_n: 2 vect__max_df:", "'char': 1.0}, {'meta': 0.3, 'word': 1.0, 'char': 1.0}, # {'meta': 0.75, 'word': 1.0,", "as oinf, open(event_idx_file) as einf: oinf.readline() einf.readline() for line in oinf: elems =", "'word': 0.5, 'char': 1.0}, # {'meta': 1.0, 'word': 0.5, 'char': 0.75}, # {'meta':", "= pairwise_eval(probs) exit(0) ''' grid_search.fit(train_data[0], train_data[1]) print(\"done in %0.3fs\" % (time() - t0))", "in finf: elems = line.strip()#.split('\\t') contents.append(elems) labels.append(0) print(\"data size:\", len(contents)) return [contents, labels]", "event_orig_mapping(sys.argv[9], sys.argv[10]) # add event-to-event info #train_data[0] = add_e2e_scores(train_data[0], train_event[0], train_e2o) #test_data[0] =", "pairwise_eval(probs): mid = int(len(probs) / 2) print('middle point: %d' % mid) pos =", "0.75, 1.0), 'vect__max_features': (None, 5000, 10000, 50000)} done in 1737.030s Best score: 0.940", "enumerate(posts): elems = text.split('\\t') words, cs, s, ns, lp = elems[:5] #print(elems) features['words'][i]", "])), ('char', Pipeline([ ('selector', ItemSelector(key='words')), ('vect', CountVectorizer(ngram_range=(1,5), analyzer='char', max_df=0.8)), ('tfidf', TfidfTransformer()), ])), ],", "1.0, 'char': 1.0}, # {'meta': 1.0, 'word': 1.0, 'char': 0.75}, # {'meta': 1.0,", "#'vect__max_features': (None, 5000, 10000, 50000), #'union__word__vect__ngram_range': ((1, 4), (1, 5)), # trigram or", "# takes pos tag text and counts number of noun pos tags (NN,", "#'union__char__vect__ngram_range': ((1, 4), (1, 5)), # trigram or 5-grams #'tfidf__use_idf': (True, False), #'tfidf__norm':", "for categories: ['alt.atheism', 'talk.religion.misc'] 1427 documents 2 categories Performing grid search... pipeline: ['vect',", "output of a run on a quad-core machine:: Loading 20 newsgroups dataset for", "counts number of noun pos tags (NN, NNS etc.) # X_count_nouns.append(count_nouns(sentence)) X =", "clf__alpha: 9.9999999999999995e-07 clf__n_iter: 50 clf__penalty: 'elasticnet' tfidf__use_idf: True vect__max_n: 2 vect__max_df: 0.75 vect__max_features:", "elems = line.strip()#.split('\\t') contents.append(elems) labels.append(1) for line in finf: elems = line.strip()#.split('\\t') contents.append(elems)", "# {'meta': 0.75, 'word': 0.5, 'char': 1.0}, # {'meta': 0.75, 'word': 0.5, 'char':", "params in grid_params: print('Current parameters:', params) pipeline.set_params(**params) pipeline.fit(train_data[0], train_data[1]) probs = pipeline.predict_proba(test_data[0]) acc", "pass. Takes a sequence of strings and produces a dict of sequences. Keys", "%d' % mid) pos = probs[:mid] neg = probs[mid:] assert len(pos) == len(neg)", "finf: for line in tinf: elems = line.strip()#.split('\\t') contents.append(elems) labels.append(1) for line in", ")), ('clf', SGDClassifier(loss='log', alpha=0.0005, tol=0.005, random_state=0)), ]) # uncommenting more parameters will give", "== \"__main__\": # multiprocessing requires the fork to happen in a __main__ protected", "#print(i, origin_to_event[i-half_len], len(origin_to_event)) original_data_array[i] = elems + '\\t' + event_data_array[origin_to_event[i-half_len] + len(origin_to_event)] return", "{'meta': 0.5, 'word': 1.0, 'char': 1.0}, # {'meta': 0.5, 'word': 1.0, 'char': 0.75},", "documents, y=None): return self def transform(self, x_dataset): X_num_token = list() #X_count_nouns = list()", "import ParameterGrid, GridSearchCV from sklearn.base import BaseEstimator, TransformerMixin from sklearn.pipeline import FeatureUnion from", "'char': 0.5}, ), 'union__word__vect__max_df': (0.7, 0.8, 0.9, 1.0), #0.5, 'union__char__vect__max_df': (0.7, 0.8, 0.9,", "0.9, 1.0), #0.5, #'vect__max_features': (None, 5000, 10000, 50000), #'union__word__vect__ngram_range': ((1, 4), (1, 5)),", "len(neg) count = 0.0 for p, n in zip(pos, neg): if p[1] >", "# {'meta': 0.5, 'word': 1.0, 'char': 1.0}, # {'meta': 0.5, 'word': 1.0, 'char':", "'word': 0.75, 'char': 0.75}, # {'meta': 0.5, 'word': 0.75, 'char': 0.5}, # {'meta':", "= time() #pipeline.fit(train_data[0], train_data[1]) #.contents, train_data.labels) '''for params in grid_params: print('Current parameters:', params)", "# {'meta': 1.0, 'word': 0.75, 'char': 1.0}, # {'meta': 1.0, 'word': 0.75, 'char':", "[], [] #data = StoryData() with open(filename+'.true.'+suffix) as tinf, open(filename+'.false.'+suffix) as finf: for", "'word': 0.5, 'char': 0.75}, # {'meta': 1.0, 'word': 0.5, 'char': 0.5}, {'meta': 0.7,", "['alt.atheism', 'talk.religion.misc'] 1427 documents 2 categories Performing grid search... pipeline: ['vect', 'tfidf', 'clf']", "from pprint import pprint from time import time import logging import sys import", "einf: elems = line.strip().split() event_idx_dict[elems[0]] = counter counter += 1 origin_to_event = {}", "sys.argv[8]) #test_e2o = event_orig_mapping(sys.argv[9], sys.argv[10]) # add event-to-event info #train_data[0] = add_e2e_scores(train_data[0], train_event[0],", "(param_name, best_parameters[param_name])) print('predicting on the test data...') score = grid_search.score(test_data[0], test_data[1]) print('Test score:", "downloaded and then cached and reused for the document classification example. You can", "# {'meta': 0.5, 'word': 0.5, 'char': 1.0}, # {'meta': 0.5, 'word': 0.5, 'char':", "5-grams #'tfidf__use_idf': (True, False), #'tfidf__norm': ('l1', 'l2'), 'clf__alpha': (0.001, 0.0005, 0.0001), #'clf__penalty': ('l2',", "True vect__max_n: 2 vect__max_df: 0.75 vect__max_features: 50000 \"\"\" # Author: <NAME> <<EMAIL>> #", "test def load_data(filename, suffix): contents, labels = [], [] #data = StoryData() with", "{'meta': 1.0, 'word': 0.75, 'char': 0.75}, # {'meta': 1.0, 'word': 0.75, 'char': 0.5},", "event_orig_mapping(orig_idx_file, event_idx_file): orig_idx_array = [] event_idx_dict = {} with open(orig_idx_file) as oinf, open(event_idx_file)", "'tfidf__use_idf': (True, False), 'vect__max_n': (1, 2), 'vect__max_df': (0.5, 0.75, 1.0), 'vect__max_features': (None, 5000,", "<NAME> <<EMAIL>> # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # License: BSD 3 clause", "############################################################################# # Load data test def load_data(filename, suffix): contents, labels = [], []", "0.8, 0.9, 1.0), #0.5, 'union__char__vect__max_df': (0.7, 0.8, 0.9, 1.0), #0.5, #'vect__max_features': (None, 5000,", "count = 0.0 for p, n in zip(pos, neg): if p[1] > n[1]:", "y=None): return self def transform(self, data_dict): return data_dict[self.key] class CustomFeatures(BaseEstimator): def __init__(self): pass", "50 clf__penalty: 'elasticnet' tfidf__use_idf: True vect__max_n: 2 vect__max_df: 0.75 vect__max_features: 50000 \"\"\" #", "if not hasattr(self, 'scalar'): self.scalar = StandardScaler().fit(X) return self.scalar.transform(X) class FeatureExtractor(BaseEstimator, TransformerMixin): \"\"\"Extract", "in event_idx_dict: origin_to_event[i] = event_idx_dict[oidx] print ('map dictionary size:', len(origin_to_event)) return origin_to_event def", "])), ('word', Pipeline([ ('selector', ItemSelector(key='words')), ('vect', CountVectorizer(ngram_range=(1,5), max_df=0.9)), ('tfidf', TfidfTransformer()), ])), ('char', Pipeline([", "4), #'union__char__vect__ngram_range': ((1, 4), (1, 5)), # trigram or 5-grams #'tfidf__use_idf': (True, False),", "best_parameters = grid_search.best_estimator_.get_params() for param_name in sorted(parameters.keys()): print(\"\\t%s: %r\" % (param_name, best_parameters[param_name])) print('predicting", "\"\"\" ========================================================== Sample pipeline for text feature extraction and evaluation ========================================================== The dataset", "50000 \"\"\" # Author: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> #", "def __init__(self, key): self.key = key def fit(self, x, y=None): return self def", "line.strip()#.split('\\t') contents.append(elems) labels.append(1) for line in finf: elems = line.strip()#.split('\\t') contents.append(elems) labels.append(0) print(\"data", "load_data(sys.argv[4], sys.argv[6]) #test_event = load_data(sys.argv[5], sys.argv[6]) #train_e2o = event_orig_mapping(sys.argv[7], sys.argv[8]) #test_e2o = event_orig_mapping(sys.argv[9],", "import print_function from pprint import pprint from time import time import logging import", "{'meta': 0.75, 'word': 0.75, 'char': 0.5}, # {'meta': 0.75, 'word': 0.5, 'char': 1.0},", "tinf: elems = line.strip()#.split('\\t') contents.append(elems) labels.append(1) for line in finf: elems = line.strip()#.split('\\t')", "newsgroups dataset for categories: ['alt.atheism', 'talk.religion.misc'] 1427 documents 2 categories Performing grid search...", "1.0), 'vect__max_features': (None, 5000, 10000, 50000)} done in 1737.030s Best score: 0.940 Best", "both the feature extraction and the # classifier # pipeline.fit(train_data[0], train_data[1]) # probs", "}, )), ('clf', SGDClassifier(loss='log', alpha=0.0005, tol=0.005, random_state=0)), ]) # uncommenting more parameters will", "TransformerMixin): def __init__(self, key): self.key = key def fit(self, x, y=None): return self", "10000, 50000), #'union__word__vect__ngram_range': ((1, 4), (1, 5)), # trigram or 5-grams (1, 4),", "setting them to None to get the 20 of them. Here is a", "'word': 0.75, 'char': 1.0}, # {'meta': 1.0, 'word': 0.75, 'char': 0.75}, # {'meta':", "{'meta': 0.5, 'word': 1.0, 'char': 0.5}, # {'meta': 0.5, 'word': 0.75, 'char': 1.0},", "transform(self, x_dataset): X_num_token = list() #X_count_nouns = list() for sentence in x_dataset: #", "0.5, 'char': 0.5}, ), 'union__word__vect__max_df': (0.7, 0.8, 0.9, 1.0), #0.5, 'union__char__vect__max_df': (0.7, 0.8,", "None to get the 20 of them. Here is a sample output of", "if len(elems) > 5: ecs, es, ens, ep = elems[5:] features['meta'][i].update({'event_condscore': float(ecs), 'event_score':", "as einf: oinf.readline() einf.readline() for line in oinf: elems = line.strip().split() orig_idx_array.append(elems[0]) counter", "0.940 Best parameters set: clf__alpha: 9.9999999999999995e-07 clf__n_iter: 50 clf__penalty: 'elasticnet' tfidf__use_idf: True vect__max_n:", "vect__max_features: 50000 \"\"\" # Author: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # <NAME> <<EMAIL>>", "0.5}, # {'meta': 0.5, 'word': 1.0, 'char': 1.0}, # {'meta': 0.5, 'word': 1.0,", "warnings.filterwarnings(\"ignore\",category=Warning) #DeprecationWarning) # Display progress logs on stdout logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') class", "1.0, 'word': 0.75, 'char': 0.75}, # {'meta': 1.0, 'word': 0.75, 'char': 0.5}, #", "categories: ['alt.atheism', 'talk.religion.misc'] 1427 documents 2 categories Performing grid search... pipeline: ['vect', 'tfidf',", "len(event_data_array) == 2 * len(origin_to_event), (len(event_data_array), len(origin_to_event)) assert len(original_data_array) >= len(event_data_array) half_len =", "analyzer='char', max_df=0.8)), ('tfidf', TfidfTransformer()), ])), ], transformer_weights={ 'meta': 0.3, 'word': 1.0, 'char': 1.0,", "# multiprocessing requires the fork to happen in a __main__ protected # block", "# Load data test def load_data(filename, suffix): contents, labels = [], [] #data", "categories Performing grid search... pipeline: ['vect', 'tfidf', 'clf'] parameters: {'clf__alpha': (1.0000000000000001e-05, 9.9999999999999995e-07), 'clf__n_iter':", "i, text in enumerate(posts): elems = text.split('\\t') words, cs, s, ns, lp =", "len(original_data_array) / 2 for i, elems in enumerate(original_data_array): if i in origin_to_event: original_data_array[i]", "'word': 0.75, 'char': 1.0}, # {'meta': 0.5, 'word': 0.75, 'char': 0.75}, # {'meta':", "2 vect__max_df: 0.75 vect__max_features: 50000 \"\"\" # Author: <NAME> <<EMAIL>> # <NAME> <<EMAIL>>", "sample output of a run on a quad-core machine:: Loading 20 newsgroups dataset", "def fit(self, documents, y=None): return self def transform(self, x_dataset): X_num_token = list() #X_count_nouns", "CountVectorizer(ngram_range=(1,5), analyzer='char', max_df=0.8)), ('tfidf', TfidfTransformer()), ])), ], transformer_weights={ 'meta': 0.3, 'word': 1.0, 'char':", "0.5, 'char': 0.5}, {'meta': 0.7, 'word': 1.0, 'char': 1.0}, {'meta': 0.5, 'word': 1.0,", "import FeatureUnion from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler #print(__doc__) import warnings", "+ event_data_array[origin_to_event[i-half_len] + len(origin_to_event)] return original_data_array def pairwise_eval(probs): mid = int(len(probs) / 2)", "1.0, 'word': 0.75, 'char': 1.0}, # {'meta': 1.0, 'word': 0.75, 'char': 0.75}, #", "#0.5, #'vect__max_features': (None, 5000, 10000, 50000), #'union__word__vect__ngram_range': ((1, 4), (1, 5)), # trigram", "run on a quad-core machine:: Loading 20 newsgroups dataset for categories: ['alt.atheism', 'talk.religion.misc']", "feature extraction and the # classifier # pipeline.fit(train_data[0], train_data[1]) # probs = pipeline.predict_proba(test_data[0])", "= pipeline.predict_proba(test_data[0]) acc = pairwise_eval(probs) exit(0) ''' grid_search.fit(train_data[0], train_data[1]) print(\"done in %0.3fs\" %", "for param_name in sorted(parameters.keys()): print(\"\\t%s: %r\" % (param_name, best_parameters[param_name])) print('predicting on the test", "X = np.array([X_num_token]).T #, X_count_nouns]).T if not hasattr(self, 'scalar'): self.scalar = StandardScaler().fit(X) return", "train_event[0], train_e2o) #test_data[0] = add_e2e_scores(test_data[0], test_event[0], test_e2o) print('Finished data loading!!') for elem in", "# ############################################################################# # Define a pipeline combining a text feature extractor with a", "transformer_list=[ ('meta', Pipeline([ ('selector', ItemSelector(key='meta')), ('vect', DictVectorizer()), ('scale', StandardScaler(with_mean=False)), ])), ('word', Pipeline([ ('selector',", "1.0}, {'meta': 0.4, 'word': 1.0, 'char': 1.0}, {'meta': 0.3, 'word': 1.0, 'char': 1.0},", "'word': 0.5, 'char': 1.0}, # {'meta': 0.5, 'word': 0.5, 'char': 0.75}, # {'meta':", "self.key = key def fit(self, x, y=None): return self def transform(self, data_dict): return", "__main__ protected # block # find the best parameters for both the feature", "with warnings.catch_warnings(): warnings.filterwarnings(\"ignore\",category=Warning) #DeprecationWarning) # Display progress logs on stdout logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s", "oinf: elems = line.strip().split() orig_idx_array.append(elems[0]) counter = 0 for line in einf: elems", "(elem) # ############################################################################# # Define a pipeline combining a text feature extractor with", "1427 documents 2 categories Performing grid search... pipeline: ['vect', 'tfidf', 'clf'] parameters: {'clf__alpha':", "object), ('condscore', object), ('score', object), ('normscore', object), ('langpred', bool)]) for i, text in", "[name for name, _ in pipeline.steps]) print(\"parameters:\") pprint(parameters) t0 = time() #pipeline.fit(train_data[0], train_data[1])", "'clf__tol': (5e-3, 1e-3, 5e-4), #'clf__n_iter': (10, 50, 80), } if __name__ == \"__main__\":", "DictVectorizer from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.linear_model import SGDClassifier", "fork to happen in a __main__ protected # block # find the best", "# print('False') acc = count/mid print('Test result: %.3f' % acc) return acc train_data", "in a single pass. Takes a sequence of strings and produces a dict", "0.5, 'char': 0.75}, # {'meta': 1.0, 'word': 0.5, 'char': 0.5}, {'meta': 0.7, 'word':", "by giving their names to the dataset loader or setting them to None", "= text.split('\\t') words, cs, s, ns, lp = elems[:5] #print(elems) features['words'][i] = words", "* len(origin_to_event), (len(event_data_array), len(origin_to_event)) assert len(original_data_array) >= len(event_data_array) half_len = len(original_data_array) / 2", "{'meta': 0.5, 'word': 0.75, 'char': 0.75}, # {'meta': 0.5, 'word': 0.75, 'char': 0.5},", "<<EMAIL>> # <NAME> <<EMAIL>> # License: BSD 3 clause from __future__ import print_function", "t0)) print() print(\"Best score: %0.3f\" % grid_search.best_score_) print(\"Best parameters set:\") best_parameters = grid_search.best_estimator_.get_params()", "features # ############################################################################# # Load data test def load_data(filename, suffix): contents, labels =", "object), ('score', object), ('normscore', object), ('langpred', bool)]) for i, text in enumerate(posts): elems", "), 'union__word__vect__max_df': (0.7, 0.8, 0.9, 1.0), #0.5, 'union__char__vect__max_df': (0.7, 0.8, 0.9, 1.0), #0.5,", "Sample pipeline for text feature extraction and evaluation ========================================================== The dataset used in", "exit(0) ''' grid_search.fit(train_data[0], train_data[1]) print(\"done in %0.3fs\" % (time() - t0)) print() print(\"Best", "progress logs on stdout logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') class ItemSelector(BaseEstimator, TransformerMixin): def __init__(self,", "pprint import pprint from time import time import logging import sys import numpy", "ns, lp = elems[:5] #print(elems) features['words'][i] = words features['meta'][i] = {'length': len(words.split()), 'condscore':", "ep = elems[5:] features['meta'][i].update({'event_condscore': float(ecs), 'event_score': float(es), 'event_normscore': float(ens), 'event_pred': bool(ep)}) return features", "'char': 1.0, }, )), ('clf', SGDClassifier(loss='log', alpha=0.0005, tol=0.005, random_state=0)), ]) # uncommenting more", "line in oinf: elems = line.strip().split() orig_idx_array.append(elems[0]) counter = 0 for line in", "'char': 1.0}, # {'meta': 0.5, 'word': 1.0, 'char': 0.75}, # {'meta': 0.5, 'word':", "train_data[1]) # probs = pipeline.predict_proba(test_data[0]) # acc = pairwise_eval(probs) # exit(0) #grid_params =", "elems + '\\t' + event_data_array[origin_to_event[i-half_len] + len(origin_to_event)] return original_data_array def pairwise_eval(probs): mid =", "+ '\\t' + event_data_array[origin_to_event[i-half_len] + len(origin_to_event)] return original_data_array def pairwise_eval(probs): mid = int(len(probs)", "'meta': 0.3, 'word': 1.0, 'char': 1.0, }, )), ('clf', SGDClassifier(loss='log', alpha=0.0005, tol=0.005, random_state=0)),", "ItemSelector(key='words')), ('vect', CountVectorizer(ngram_range=(1,5), max_df=0.9)), ('tfidf', TfidfTransformer()), ])), ('char', Pipeline([ ('selector', ItemSelector(key='words')), ('vect', CountVectorizer(ngram_range=(1,5),", "len(origin_to_event)] return original_data_array def pairwise_eval(probs): mid = int(len(probs) / 2) print('middle point: %d'", "original_data_array def pairwise_eval(probs): mid = int(len(probs) / 2) print('middle point: %d' % mid)", "\"\"\" def fit(self, x, y=None): return self def transform(self, posts): features = np.recarray(shape=(len(posts),),", "{'meta': 0.75, 'word': 0.75, 'char': 1.0}, # {'meta': 0.75, 'word': 0.75, 'char': 0.75},", "def transform(self, posts): features = np.recarray(shape=(len(posts),), dtype=[('words', object), ('meta', object)]) #('length', object), ('condscore',", "(5e-3, 1e-3, 5e-4), #'clf__n_iter': (10, 50, 80), } if __name__ == \"__main__\": #", "on a quad-core machine:: Loading 20 newsgroups dataset for categories: ['alt.atheism', 'talk.religion.misc'] 1427", "# exit(0) #grid_params = list(ParameterGrid(parameters)) grid_search = GridSearchCV(pipeline, parameters, cv=5, n_jobs=-1, verbose=1) print(\"Performing", "20 newsgroups dataset which will be automatically downloaded and then cached and reused", "= list() #X_count_nouns = list() for sentence in x_dataset: # takes raw text", "{'meta': 0.5, 'word': 0.5, 'char': 1.0}, # {'meta': 0.5, 'word': 0.5, 'char': 0.75},", "count/mid print('Test result: %.3f' % acc) return acc train_data = load_data(sys.argv[1], sys.argv[3]) test_data", "('vect', CountVectorizer(ngram_range=(1,5), analyzer='char', max_df=0.8)), ('tfidf', TfidfTransformer()), ])), ], transformer_weights={ 'meta': 0.3, 'word': 1.0,", "1 origin_to_event = {} for i, oidx in enumerate(orig_idx_array): if oidx in event_idx_dict:", "power but will # increase processing time in a combinatorial way parameters =", "0.5}, # {'meta': 1.0, 'word': 0.5, 'char': 1.0}, # {'meta': 1.0, 'word': 0.5,", "np.recarray(shape=(len(posts),), dtype=[('words', object), ('meta', object)]) #('length', object), ('condscore', object), ('score', object), ('normscore', object),", "0.4, 'word': 1.0, 'char': 1.0}, {'meta': 0.3, 'word': 1.0, 'char': 1.0}, # {'meta':", "ItemSelector(key='words')), ('vect', CountVectorizer(ngram_range=(1,5), analyzer='char', max_df=0.8)), ('tfidf', TfidfTransformer()), ])), ], transformer_weights={ 'meta': 0.3, 'word':", "cv=5, n_jobs=-1, verbose=1) print(\"Performing grid search...\") print(\"pipeline:\", [name for name, _ in pipeline.steps])", "train_data[1]) print(\"done in %0.3fs\" % (time() - t0)) print() print(\"Best score: %0.3f\" %", "parameters set:\") best_parameters = grid_search.best_estimator_.get_params() for param_name in sorted(parameters.keys()): print(\"\\t%s: %r\" % (param_name,", "[] #data = StoryData() with open(filename+'.true.'+suffix) as tinf, open(filename+'.false.'+suffix) as finf: for line", "np.array([X_num_token]).T #, X_count_nouns]).T if not hasattr(self, 'scalar'): self.scalar = StandardScaler().fit(X) return self.scalar.transform(X) class", "set:\") best_parameters = grid_search.best_estimator_.get_params() for param_name in sorted(parameters.keys()): print(\"\\t%s: %r\" % (param_name, best_parameters[param_name]))", "logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') class ItemSelector(BaseEstimator, TransformerMixin): def __init__(self, key): self.key = key", "print (elem) # ############################################################################# # Define a pipeline combining a text feature extractor", "size:', len(origin_to_event)) return origin_to_event def add_e2e_scores(original_data_array, event_data_array, origin_to_event): assert len(event_data_array) == 2 *", "# {'meta': 1.0, 'word': 1.0, 'char': 0.5}, # {'meta': 1.0, 'word': 0.75, 'char':", "warnings with warnings.catch_warnings(): warnings.filterwarnings(\"ignore\",category=Warning) #DeprecationWarning) # Display progress logs on stdout logging.basicConfig(level=logging.INFO, format='%(asctime)s", "{'meta': 1.0, 'word': 0.75, 'char': 1.0}, # {'meta': 1.0, 'word': 0.75, 'char': 0.75},", "and produces a dict of sequences. Keys are `subject` and `body`. \"\"\" def", "acc) return acc train_data = load_data(sys.argv[1], sys.argv[3]) test_data = load_data(sys.argv[2], sys.argv[3]) #train_event =", "origin_to_event: original_data_array[i] = elems + '\\t' + event_data_array[origin_to_event[i]] if i - half_len in", "# Author: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # License: BSD", "return features # ############################################################################# # Load data test def load_data(filename, suffix): contents, labels", "= list() for sentence in x_dataset: # takes raw text and calculates type", "in enumerate(posts): elems = text.split('\\t') words, cs, s, ns, lp = elems[:5] #print(elems)", "contents.append(elems) labels.append(0) print(\"data size:\", len(contents)) return [contents, labels] def event_orig_mapping(orig_idx_file, event_idx_file): orig_idx_array =", "event_idx_dict[elems[0]] = counter counter += 1 origin_to_event = {} for i, oidx in", "and counts number of noun pos tags (NN, NNS etc.) # X_count_nouns.append(count_nouns(sentence)) X", "assert len(pos) == len(neg) count = 0.0 for p, n in zip(pos, neg):", "'l2'), 'clf__alpha': (0.001, 0.0005, 0.0001), #'clf__penalty': ('l2', 'l1'), 'clf__tol': (5e-3, 1e-3, 5e-4), #'clf__n_iter':", "from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.linear_model import SGDClassifier from", "x, y=None): return self def transform(self, posts): features = np.recarray(shape=(len(posts),), dtype=[('words', object), ('meta',", "'char': 0.75}, # {'meta': 0.5, 'word': 0.75, 'char': 0.5}, # {'meta': 0.5, 'word':", "event_data_array, origin_to_event): assert len(event_data_array) == 2 * len(origin_to_event), (len(event_data_array), len(origin_to_event)) assert len(original_data_array) >=", "0.5, 'word': 1.0, 'char': 0.5}, # {'meta': 0.5, 'word': 0.75, 'char': 1.0}, #", "('l1', 'l2'), 'clf__alpha': (0.001, 0.0005, 0.0001), #'clf__penalty': ('l2', 'l1'), 'clf__tol': (5e-3, 1e-3, 5e-4),", "the # classifier # pipeline.fit(train_data[0], train_data[1]) # probs = pipeline.predict_proba(test_data[0]) # acc =", "labels.append(0) print(\"data size:\", len(contents)) return [contents, labels] def event_orig_mapping(orig_idx_file, event_idx_file): orig_idx_array = []", "len(origin_to_event), (len(event_data_array), len(origin_to_event)) assert len(original_data_array) >= len(event_data_array) half_len = len(original_data_array) / 2 for", "print('middle point: %d' % mid) pos = probs[:mid] neg = probs[mid:] assert len(pos)", "# uncommenting more parameters will give better exploring power but will # increase", "0.5, 'char': 1.0}, # {'meta': 0.75, 'word': 0.5, 'char': 0.75}, # {'meta': 0.75,", "0.75}, # {'meta': 0.75, 'word': 0.75, 'char': 0.5}, # {'meta': 0.75, 'word': 0.5,", "on the test data...') score = grid_search.score(test_data[0], test_data[1]) print('Test score: %.3f' % score)", "acc = pairwise_eval(probs) exit(0) ''' grid_search.fit(train_data[0], train_data[1]) print(\"done in %0.3fs\" % (time() -", "posts): features = np.recarray(shape=(len(posts),), dtype=[('words', object), ('meta', object)]) #('length', object), ('condscore', object), ('score',", "to None to get the 20 of them. Here is a sample output", "5: ecs, es, ens, ep = elems[5:] features['meta'][i].update({'event_condscore': float(ecs), 'event_score': float(es), 'event_normscore': float(ens),", "= event_idx_dict[oidx] print ('map dictionary size:', len(origin_to_event)) return origin_to_event def add_e2e_scores(original_data_array, event_data_array, origin_to_event):", "len(event_data_array) half_len = len(original_data_array) / 2 for i, elems in enumerate(original_data_array): if i", "event_data_array[origin_to_event[i]] if i - half_len in origin_to_event: #print(i, origin_to_event[i-half_len], len(origin_to_event)) original_data_array[i] = elems", "# {'meta': 0.75, 'word': 1.0, 'char': 0.75}, # {'meta': 0.75, 'word': 1.0, 'char':", "# {'meta': 0.75, 'word': 0.5, 'char': 0.5}, # {'meta': 0.5, 'word': 1.0, 'char':", "= grid_search.best_estimator_.get_params() for param_name in sorted(parameters.keys()): print(\"\\t%s: %r\" % (param_name, best_parameters[param_name])) print('predicting on", "float(s), 'normscore': float(ns), 'langpred': bool(lp)} if len(elems) > 5: ecs, es, ens, ep", "= event_orig_mapping(sys.argv[7], sys.argv[8]) #test_e2o = event_orig_mapping(sys.argv[9], sys.argv[10]) # add event-to-event info #train_data[0] =", "more parameters will give better exploring power but will # increase processing time", "<NAME> <<EMAIL>> # License: BSD 3 clause from __future__ import print_function from pprint", "1.0, 'word': 0.5, 'char': 0.75}, # {'meta': 1.0, 'word': 0.5, 'char': 0.5}, {'meta':", "License: BSD 3 clause from __future__ import print_function from pprint import pprint from", "logs on stdout logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') class ItemSelector(BaseEstimator, TransformerMixin): def __init__(self, key):", "from sklearn.preprocessing import StandardScaler #print(__doc__) import warnings with warnings.catch_warnings(): warnings.filterwarnings(\"ignore\",category=Warning) #DeprecationWarning) # Display", "on stdout logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') class ItemSelector(BaseEstimator, TransformerMixin): def __init__(self, key): self.key", "= elems[:5] #print(elems) features['words'][i] = words features['meta'][i] = {'length': len(words.split()), 'condscore': float(cs), 'score':", "size:\", len(contents)) return [contents, labels] def event_orig_mapping(orig_idx_file, event_idx_file): orig_idx_array = [] event_idx_dict =", "oinf.readline() einf.readline() for line in oinf: elems = line.strip().split() orig_idx_array.append(elems[0]) counter = 0", "result: %.3f' % acc) return acc train_data = load_data(sys.argv[1], sys.argv[3]) test_data = load_data(sys.argv[2],", "1.0, 'char': 0.75}, # {'meta': 1.0, 'word': 1.0, 'char': 0.5}, # {'meta': 1.0,", "the best parameters for both the feature extraction and the # classifier #", "#grid_params = list(ParameterGrid(parameters)) grid_search = GridSearchCV(pipeline, parameters, cv=5, n_jobs=-1, verbose=1) print(\"Performing grid search...\")", "text.split('\\t') words, cs, s, ns, lp = elems[:5] #print(elems) features['words'][i] = words features['meta'][i]", "0.75 vect__max_features: 50000 \"\"\" # Author: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # <NAME>", "2 * len(origin_to_event), (len(event_data_array), len(origin_to_event)) assert len(original_data_array) >= len(event_data_array) half_len = len(original_data_array) /", "finf: elems = line.strip()#.split('\\t') contents.append(elems) labels.append(0) print(\"data size:\", len(contents)) return [contents, labels] def", "'\\t' + event_data_array[origin_to_event[i-half_len] + len(origin_to_event)] return original_data_array def pairwise_eval(probs): mid = int(len(probs) /", "zip(pos, neg): if p[1] > n[1]: count += 1.0 # print('True') # else:", "else: # print('False') acc = count/mid print('Test result: %.3f' % acc) return acc", "a simple # classifier pipeline = Pipeline([ ('featextract', FeatureExtractor()), ('union', FeatureUnion( transformer_list=[ ('meta',", "object), ('normscore', object), ('langpred', bool)]) for i, text in enumerate(posts): elems = text.split('\\t')", "elems in enumerate(original_data_array): if i in origin_to_event: original_data_array[i] = elems + '\\t' +", "# {'meta': 1.0, 'word': 0.75, 'char': 0.5}, # {'meta': 1.0, 'word': 0.5, 'char':", "assert len(event_data_array) == 2 * len(origin_to_event), (len(event_data_array), len(origin_to_event)) assert len(original_data_array) >= len(event_data_array) half_len", "# {'meta': 1.0, 'word': 0.5, 'char': 0.75}, # {'meta': 1.0, 'word': 0.5, 'char':", "sys.argv[3]) #train_event = load_data(sys.argv[4], sys.argv[6]) #test_event = load_data(sys.argv[5], sys.argv[6]) #train_e2o = event_orig_mapping(sys.argv[7], sys.argv[8])", "{'meta': 0.75, 'word': 1.0, 'char': 0.75}, # {'meta': 0.75, 'word': 1.0, 'char': 0.5},", "0.5}, # {'meta': 1.0, 'word': 0.75, 'char': 1.0}, # {'meta': 1.0, 'word': 0.75,", "#0.5, 'union__char__vect__max_df': (0.7, 0.8, 0.9, 1.0), #0.5, #'vect__max_features': (None, 5000, 10000, 50000), #'union__word__vect__ngram_range':", "0.5, 'word': 0.5, 'char': 1.0}, # {'meta': 0.5, 'word': 0.5, 'char': 0.75}, #", "(True, False), #'tfidf__norm': ('l1', 'l2'), 'clf__alpha': (0.001, 0.0005, 0.0001), #'clf__penalty': ('l2', 'l1'), 'clf__tol':", "combining a text feature extractor with a simple # classifier pipeline = Pipeline([", "object)]) #('length', object), ('condscore', object), ('score', object), ('normscore', object), ('langpred', bool)]) for i,", "({'meta': 0.6, 'word': 1.0, 'char': 1.0}, # {'meta': 1.0, 'word': 1.0, 'char': 0.75},", "in origin_to_event: original_data_array[i] = elems + '\\t' + event_data_array[origin_to_event[i]] if i - half_len", "# {'meta': 0.5, 'word': 0.5, 'char': 0.5}, ), 'union__word__vect__max_df': (0.7, 0.8, 0.9, 1.0),", "clf__penalty: 'elasticnet' tfidf__use_idf: True vect__max_n: 2 vect__max_df: 0.75 vect__max_features: 50000 \"\"\" # Author:", "1.0), #0.5, 'union__char__vect__max_df': (0.7, 0.8, 0.9, 1.0), #0.5, #'vect__max_features': (None, 5000, 10000, 50000),", "sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.linear_model import SGDClassifier from sklearn.model_selection", "automatically downloaded and then cached and reused for the document classification example. You", "1.0}, # {'meta': 1.0, 'word': 0.75, 'char': 0.75}, # {'meta': 1.0, 'word': 0.75,", "elems[:5] #print(elems) features['words'][i] = words features['meta'][i] = {'length': len(words.split()), 'condscore': float(cs), 'score': float(s),", "assert len(original_data_array) >= len(event_data_array) half_len = len(original_data_array) / 2 for i, elems in", "add_e2e_scores(original_data_array, event_data_array, origin_to_event): assert len(event_data_array) == 2 * len(origin_to_event), (len(event_data_array), len(origin_to_event)) assert len(original_data_array)", "0.75, 'word': 1.0, 'char': 0.5}, # {'meta': 0.75, 'word': 0.75, 'char': 1.0}, #", "bool)]) for i, text in enumerate(posts): elems = text.split('\\t') words, cs, s, ns,", "get_feature_names(self): return np.array(['sent_len']) #, 'lang_prob']) def fit(self, documents, y=None): return self def transform(self,", "+= 1.0 # print('True') # else: # print('False') acc = count/mid print('Test result:", "#train_event = load_data(sys.argv[4], sys.argv[6]) #test_event = load_data(sys.argv[5], sys.argv[6]) #train_e2o = event_orig_mapping(sys.argv[7], sys.argv[8]) #test_e2o", "processing time in a combinatorial way parameters = { 'union__transformer_weights': ({'meta': 0.6, 'word':", "{'meta': 0.75, 'word': 1.0, 'char': 0.5}, # {'meta': 0.75, 'word': 0.75, 'char': 1.0},", "line.strip().split() orig_idx_array.append(elems[0]) counter = 0 for line in einf: elems = line.strip().split() event_idx_dict[elems[0]]", "tfidf__use_idf: True vect__max_n: 2 vect__max_df: 0.75 vect__max_features: 50000 \"\"\" # Author: <NAME> <<EMAIL>>", "= counter counter += 1 origin_to_event = {} for i, oidx in enumerate(orig_idx_array):", "> n[1]: count += 1.0 # print('True') # else: # print('False') acc =", "load_data(sys.argv[2], sys.argv[3]) #train_event = load_data(sys.argv[4], sys.argv[6]) #test_event = load_data(sys.argv[5], sys.argv[6]) #train_e2o = event_orig_mapping(sys.argv[7],", "0.7, 'word': 1.0, 'char': 1.0}, {'meta': 0.5, 'word': 1.0, 'char': 1.0}, {'meta': 0.4,", "# trigram or 5-grams (1, 4), #'union__char__vect__ngram_range': ((1, 4), (1, 5)), # trigram", "{'clf__alpha': (1.0000000000000001e-05, 9.9999999999999995e-07), 'clf__n_iter': (10, 50, 80), 'clf__penalty': ('l2', 'elasticnet'), 'tfidf__use_idf': (True, False),", "text feature extraction and evaluation ========================================================== The dataset used in this example is", "`body`. \"\"\" def fit(self, x, y=None): return self def transform(self, posts): features =", "open(filename+'.true.'+suffix) as tinf, open(filename+'.false.'+suffix) as finf: for line in tinf: elems = line.strip()#.split('\\t')", "event_idx_dict: origin_to_event[i] = event_idx_dict[oidx] print ('map dictionary size:', len(origin_to_event)) return origin_to_event def add_e2e_scores(original_data_array,", "acc = count/mid print('Test result: %.3f' % acc) return acc train_data = load_data(sys.argv[1],", "0.75, 'word': 0.75, 'char': 1.0}, # {'meta': 0.75, 'word': 0.75, 'char': 0.75}, #", "score: 0.940 Best parameters set: clf__alpha: 9.9999999999999995e-07 clf__n_iter: 50 clf__penalty: 'elasticnet' tfidf__use_idf: True", "0.75}, # {'meta': 1.0, 'word': 1.0, 'char': 0.5}, # {'meta': 1.0, 'word': 0.75,", "score: %0.3f\" % grid_search.best_score_) print(\"Best parameters set:\") best_parameters = grid_search.best_estimator_.get_params() for param_name in", "grid search... pipeline: ['vect', 'tfidf', 'clf'] parameters: {'clf__alpha': (1.0000000000000001e-05, 9.9999999999999995e-07), 'clf__n_iter': (10, 50,", "grid_params: print('Current parameters:', params) pipeline.set_params(**params) pipeline.fit(train_data[0], train_data[1]) probs = pipeline.predict_proba(test_data[0]) acc = pairwise_eval(probs)", "parameters:', params) pipeline.set_params(**params) pipeline.fit(train_data[0], train_data[1]) probs = pipeline.predict_proba(test_data[0]) acc = pairwise_eval(probs) exit(0) '''", "for elem in train_data[0][:10]: print (elem) # ############################################################################# # Define a pipeline combining", "2 for i, elems in enumerate(original_data_array): if i in origin_to_event: original_data_array[i] = elems", "GridSearchCV from sklearn.base import BaseEstimator, TransformerMixin from sklearn.pipeline import FeatureUnion from sklearn.pipeline import", "x_dataset): X_num_token = list() #X_count_nouns = list() for sentence in x_dataset: # takes", "with open(filename+'.true.'+suffix) as tinf, open(filename+'.false.'+suffix) as finf: for line in tinf: elems =", "grid_search.fit(train_data[0], train_data[1]) print(\"done in %0.3fs\" % (time() - t0)) print() print(\"Best score: %0.3f\"", "'word': 0.75, 'char': 0.5}, # {'meta': 0.5, 'word': 0.5, 'char': 1.0}, # {'meta':", "origin_to_event[i-half_len], len(origin_to_event)) original_data_array[i] = elems + '\\t' + event_data_array[origin_to_event[i-half_len] + len(origin_to_event)] return original_data_array", "orig_idx_array.append(elems[0]) counter = 0 for line in einf: elems = line.strip().split() event_idx_dict[elems[0]] =", "takes pos tag text and counts number of noun pos tags (NN, NNS", "Best score: 0.940 Best parameters set: clf__alpha: 9.9999999999999995e-07 clf__n_iter: 50 clf__penalty: 'elasticnet' tfidf__use_idf:", "info #train_data[0] = add_e2e_scores(train_data[0], train_event[0], train_e2o) #test_data[0] = add_e2e_scores(test_data[0], test_event[0], test_e2o) print('Finished data", "1.0}, # {'meta': 0.75, 'word': 0.5, 'char': 0.75}, # {'meta': 0.75, 'word': 0.5,", "0.75}, # {'meta': 0.75, 'word': 0.5, 'char': 0.5}, # {'meta': 0.5, 'word': 1.0,", "the fork to happen in a __main__ protected # block # find the", "return np.array(['sent_len']) #, 'lang_prob']) def fit(self, documents, y=None): return self def transform(self, x_dataset):", "self.scalar = StandardScaler().fit(X) return self.scalar.transform(X) class FeatureExtractor(BaseEstimator, TransformerMixin): \"\"\"Extract the subject & body", "in grid_params: print('Current parameters:', params) pipeline.set_params(**params) pipeline.fit(train_data[0], train_data[1]) probs = pipeline.predict_proba(test_data[0]) acc =", "return self def transform(self, x_dataset): X_num_token = list() #X_count_nouns = list() for sentence", "type token ratio X_num_token.append(len(sentence)) # takes pos tag text and counts number of", "+ len(origin_to_event)] return original_data_array def pairwise_eval(probs): mid = int(len(probs) / 2) print('middle point:", "= [] event_idx_dict = {} with open(orig_idx_file) as oinf, open(event_idx_file) as einf: oinf.readline()", "#('length', object), ('condscore', object), ('score', object), ('normscore', object), ('langpred', bool)]) for i, text", "('vect', CountVectorizer(ngram_range=(1,5), max_df=0.9)), ('tfidf', TfidfTransformer()), ])), ('char', Pipeline([ ('selector', ItemSelector(key='words')), ('vect', CountVectorizer(ngram_range=(1,5), analyzer='char',", "pairwise_eval(probs) exit(0) ''' grid_search.fit(train_data[0], train_data[1]) print(\"done in %0.3fs\" % (time() - t0)) print()", "{} for i, oidx in enumerate(orig_idx_array): if oidx in event_idx_dict: origin_to_event[i] = event_idx_dict[oidx]", "#'clf__penalty': ('l2', 'l1'), 'clf__tol': (5e-3, 1e-3, 5e-4), #'clf__n_iter': (10, 50, 80), } if", "body from a usenet post in a single pass. Takes a sequence of", "the 20 of them. Here is a sample output of a run on", "clf__n_iter: 50 clf__penalty: 'elasticnet' tfidf__use_idf: True vect__max_n: 2 vect__max_df: 0.75 vect__max_features: 50000 \"\"\"", "\"\"\" # Author: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # License:", "'word': 0.75, 'char': 0.75}, # {'meta': 1.0, 'word': 0.75, 'char': 0.5}, # {'meta':", "feature extractor with a simple # classifier pipeline = Pipeline([ ('featextract', FeatureExtractor()), ('union',", "acc = pairwise_eval(probs) # exit(0) #grid_params = list(ParameterGrid(parameters)) grid_search = GridSearchCV(pipeline, parameters, cv=5,", "numpy as np from sklearn.feature_extraction import DictVectorizer from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text", "# {'meta': 0.75, 'word': 0.75, 'char': 0.75}, # {'meta': 0.75, 'word': 0.75, 'char':", "# {'meta': 0.5, 'word': 0.75, 'char': 0.75}, # {'meta': 0.5, 'word': 0.75, 'char':", "((1, 4), (1, 5)), # trigram or 5-grams (1, 4), #'union__char__vect__ngram_range': ((1, 4),", "4), (1, 5)), # trigram or 5-grams (1, 4), #'union__char__vect__ngram_range': ((1, 4), (1,", "print(\"\\t%s: %r\" % (param_name, best_parameters[param_name])) print('predicting on the test data...') score = grid_search.score(test_data[0],", "words features['meta'][i] = {'length': len(words.split()), 'condscore': float(cs), 'score': float(s), 'normscore': float(ns), 'langpred': bool(lp)}", "('selector', ItemSelector(key='meta')), ('vect', DictVectorizer()), ('scale', StandardScaler(with_mean=False)), ])), ('word', Pipeline([ ('selector', ItemSelector(key='words')), ('vect', CountVectorizer(ngram_range=(1,5),", "and calculates type token ratio X_num_token.append(len(sentence)) # takes pos tag text and counts", "= elems[5:] features['meta'][i].update({'event_condscore': float(ecs), 'event_score': float(es), 'event_normscore': float(ens), 'event_pred': bool(ep)}) return features #", "line in tinf: elems = line.strip()#.split('\\t') contents.append(elems) labels.append(1) for line in finf: elems", "= 0.0 for p, n in zip(pos, neg): if p[1] > n[1]: count", "test_e2o) print('Finished data loading!!') for elem in train_data[0][:10]: print (elem) # ############################################################################# #", "__future__ import print_function from pprint import pprint from time import time import logging", "sklearn.model_selection import ParameterGrid, GridSearchCV from sklearn.base import BaseEstimator, TransformerMixin from sklearn.pipeline import FeatureUnion", "ItemSelector(BaseEstimator, TransformerMixin): def __init__(self, key): self.key = key def fit(self, x, y=None): return", "original_data_array[i] = elems + '\\t' + event_data_array[origin_to_event[i]] if i - half_len in origin_to_event:", "'char': 1.0}, # {'meta': 0.5, 'word': 0.75, 'char': 0.75}, # {'meta': 0.5, 'word':", "int(len(probs) / 2) print('middle point: %d' % mid) pos = probs[:mid] neg =", "return self def transform(self, data_dict): return data_dict[self.key] class CustomFeatures(BaseEstimator): def __init__(self): pass def", "class ItemSelector(BaseEstimator, TransformerMixin): def __init__(self, key): self.key = key def fit(self, x, y=None):", "return origin_to_event def add_e2e_scores(original_data_array, event_data_array, origin_to_event): assert len(event_data_array) == 2 * len(origin_to_event), (len(event_data_array),", "Performing grid search... pipeline: ['vect', 'tfidf', 'clf'] parameters: {'clf__alpha': (1.0000000000000001e-05, 9.9999999999999995e-07), 'clf__n_iter': (10,", "best parameters for both the feature extraction and the # classifier # pipeline.fit(train_data[0],", "= len(original_data_array) / 2 for i, elems in enumerate(original_data_array): if i in origin_to_event:", "'char': 0.5}, # {'meta': 0.75, 'word': 0.75, 'char': 1.0}, # {'meta': 0.75, 'word':", "oidx in event_idx_dict: origin_to_event[i] = event_idx_dict[oidx] print ('map dictionary size:', len(origin_to_event)) return origin_to_event", "#DeprecationWarning) # Display progress logs on stdout logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') class ItemSelector(BaseEstimator,", "'char': 0.5}, # {'meta': 0.5, 'word': 1.0, 'char': 1.0}, # {'meta': 0.5, 'word':", "0.0 for p, n in zip(pos, neg): if p[1] > n[1]: count +=", "'char': 0.75}, # {'meta': 0.5, 'word': 0.5, 'char': 0.5}, ), 'union__word__vect__max_df': (0.7, 0.8,", "es, ens, ep = elems[5:] features['meta'][i].update({'event_condscore': float(ecs), 'event_score': float(es), 'event_normscore': float(ens), 'event_pred': bool(ep)})", "1.0, 'char': 0.5}, # {'meta': 0.5, 'word': 0.75, 'char': 1.0}, # {'meta': 0.5,", "block # find the best parameters for both the feature extraction and the", "load_data(filename, suffix): contents, labels = [], [] #data = StoryData() with open(filename+'.true.'+suffix) as", "= {} with open(orig_idx_file) as oinf, open(event_idx_file) as einf: oinf.readline() einf.readline() for line", "= key def fit(self, x, y=None): return self def transform(self, data_dict): return data_dict[self.key]", "'word': 1.0, 'char': 0.75}, # {'meta': 0.5, 'word': 1.0, 'char': 0.5}, # {'meta':", "dataset for categories: ['alt.atheism', 'talk.religion.misc'] 1427 documents 2 categories Performing grid search... pipeline:", "len(contents)) return [contents, labels] def event_orig_mapping(orig_idx_file, event_idx_file): orig_idx_array = [] event_idx_dict = {}", "takes raw text and calculates type token ratio X_num_token.append(len(sentence)) # takes pos tag", "X_count_nouns]).T if not hasattr(self, 'scalar'): self.scalar = StandardScaler().fit(X) return self.scalar.transform(X) class FeatureExtractor(BaseEstimator, TransformerMixin):", "sys.argv[10]) # add event-to-event info #train_data[0] = add_e2e_scores(train_data[0], train_event[0], train_e2o) #test_data[0] = add_e2e_scores(test_data[0],", "20 newsgroups dataset for categories: ['alt.atheism', 'talk.religion.misc'] 1427 documents 2 categories Performing grid", "set: clf__alpha: 9.9999999999999995e-07 clf__n_iter: 50 clf__penalty: 'elasticnet' tfidf__use_idf: True vect__max_n: 2 vect__max_df: 0.75", "event_idx_file): orig_idx_array = [] event_idx_dict = {} with open(orig_idx_file) as oinf, open(event_idx_file) as", "# Define a pipeline combining a text feature extractor with a simple #", "{'meta': 1.0, 'word': 0.5, 'char': 0.75}, # {'meta': 1.0, 'word': 0.5, 'char': 0.5},", "0.75}, # {'meta': 0.75, 'word': 1.0, 'char': 0.5}, # {'meta': 0.75, 'word': 0.75,", "origin_to_event): assert len(event_data_array) == 2 * len(origin_to_event), (len(event_data_array), len(origin_to_event)) assert len(original_data_array) >= len(event_data_array)", "will give better exploring power but will # increase processing time in a", "'word': 0.75, 'char': 0.5}, # {'meta': 0.75, 'word': 0.5, 'char': 1.0}, # {'meta':", "#'union__word__vect__ngram_range': ((1, 4), (1, 5)), # trigram or 5-grams (1, 4), #'union__char__vect__ngram_range': ((1,", "'condscore': float(cs), 'score': float(s), 'normscore': float(ns), 'langpred': bool(lp)} if len(elems) > 5: ecs,", "80), } if __name__ == \"__main__\": # multiprocessing requires the fork to happen", "features['meta'][i] = {'length': len(words.split()), 'condscore': float(cs), 'score': float(s), 'normscore': float(ns), 'langpred': bool(lp)} if", "('word', Pipeline([ ('selector', ItemSelector(key='words')), ('vect', CountVectorizer(ngram_range=(1,5), max_df=0.9)), ('tfidf', TfidfTransformer()), ])), ('char', Pipeline([ ('selector',", "# {'meta': 1.0, 'word': 0.5, 'char': 1.0}, # {'meta': 1.0, 'word': 0.5, 'char':", "will # increase processing time in a combinatorial way parameters = { 'union__transformer_weights':", "'word': 1.0, 'char': 1.0}, {'meta': 0.3, 'word': 1.0, 'char': 1.0}, # {'meta': 0.75,", "'char': 0.5}, # {'meta': 0.75, 'word': 0.5, 'char': 1.0}, # {'meta': 0.75, 'word':", "'langpred': bool(lp)} if len(elems) > 5: ecs, es, ens, ep = elems[5:] features['meta'][i].update({'event_condscore':", "__name__ == \"__main__\": # multiprocessing requires the fork to happen in a __main__", "])), ], transformer_weights={ 'meta': 0.3, 'word': 1.0, 'char': 1.0, }, )), ('clf', SGDClassifier(loss='log',", "train_data.labels) '''for params in grid_params: print('Current parameters:', params) pipeline.set_params(**params) pipeline.fit(train_data[0], train_data[1]) probs =", "'word': 1.0, 'char': 1.0}, {'meta': 0.5, 'word': 1.0, 'char': 1.0}, {'meta': 0.4, 'word':", "text feature extractor with a simple # classifier pipeline = Pipeline([ ('featextract', FeatureExtractor()),", "them. Here is a sample output of a run on a quad-core machine::", "% grid_search.best_score_) print(\"Best parameters set:\") best_parameters = grid_search.best_estimator_.get_params() for param_name in sorted(parameters.keys()): print(\"\\t%s:", "('tfidf', TfidfTransformer()), ])), ], transformer_weights={ 'meta': 0.3, 'word': 1.0, 'char': 1.0, }, )),", "exit(0) #grid_params = list(ParameterGrid(parameters)) grid_search = GridSearchCV(pipeline, parameters, cv=5, n_jobs=-1, verbose=1) print(\"Performing grid", "'char': 1.0}, # {'meta': 0.75, 'word': 0.5, 'char': 0.75}, # {'meta': 0.75, 'word':", "# {'meta': 0.75, 'word': 0.5, 'char': 0.75}, # {'meta': 0.75, 'word': 0.5, 'char':", "in this example is the 20 newsgroups dataset which will be automatically downloaded", "#print(__doc__) import warnings with warnings.catch_warnings(): warnings.filterwarnings(\"ignore\",category=Warning) #DeprecationWarning) # Display progress logs on stdout", "transform(self, posts): features = np.recarray(shape=(len(posts),), dtype=[('words', object), ('meta', object)]) #('length', object), ('condscore', object),", "return acc train_data = load_data(sys.argv[1], sys.argv[3]) test_data = load_data(sys.argv[2], sys.argv[3]) #train_event = load_data(sys.argv[4],", "line in einf: elems = line.strip().split() event_idx_dict[elems[0]] = counter counter += 1 origin_to_event", "% (time() - t0)) print() print(\"Best score: %0.3f\" % grid_search.best_score_) print(\"Best parameters set:\")", "0.5, 'char': 1.0}, # {'meta': 1.0, 'word': 0.5, 'char': 0.75}, # {'meta': 1.0,", "# classifier # pipeline.fit(train_data[0], train_data[1]) # probs = pipeline.predict_proba(test_data[0]) # acc = pairwise_eval(probs)", "in zip(pos, neg): if p[1] > n[1]: count += 1.0 # print('True') #", "'char': 0.75}, # {'meta': 1.0, 'word': 1.0, 'char': 0.5}, # {'meta': 1.0, 'word':", "0.5, 'word': 1.0, 'char': 1.0}, # {'meta': 0.5, 'word': 1.0, 'char': 0.75}, #", "sys import numpy as np from sklearn.feature_extraction import DictVectorizer from sklearn.feature_extraction.text import CountVectorizer", "= Pipeline([ ('featextract', FeatureExtractor()), ('union', FeatureUnion( transformer_list=[ ('meta', Pipeline([ ('selector', ItemSelector(key='meta')), ('vect', DictVectorizer()),", "parameters, cv=5, n_jobs=-1, verbose=1) print(\"Performing grid search...\") print(\"pipeline:\", [name for name, _ in", "from sklearn.feature_extraction import DictVectorizer from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from", "and reused for the document classification example. You can adjust the number of", "tags (NN, NNS etc.) # X_count_nouns.append(count_nouns(sentence)) X = np.array([X_num_token]).T #, X_count_nouns]).T if not", "'clf__penalty': ('l2', 'elasticnet'), 'tfidf__use_idf': (True, False), 'vect__max_n': (1, 2), 'vect__max_df': (0.5, 0.75, 1.0),", "number of categories by giving their names to the dataset loader or setting", "(time() - t0)) print() print(\"Best score: %0.3f\" % grid_search.best_score_) print(\"Best parameters set:\") best_parameters", "'word': 1.0, 'char': 0.5}, # {'meta': 1.0, 'word': 0.75, 'char': 1.0}, # {'meta':", "categories by giving their names to the dataset loader or setting them to", "the feature extraction and the # classifier # pipeline.fit(train_data[0], train_data[1]) # probs =", "#train_e2o = event_orig_mapping(sys.argv[7], sys.argv[8]) #test_e2o = event_orig_mapping(sys.argv[9], sys.argv[10]) # add event-to-event info #train_data[0]", "a run on a quad-core machine:: Loading 20 newsgroups dataset for categories: ['alt.atheism',", "random_state=0)), ]) # uncommenting more parameters will give better exploring power but will", "if i - half_len in origin_to_event: #print(i, origin_to_event[i-half_len], len(origin_to_event)) original_data_array[i] = elems +", "words, cs, s, ns, lp = elems[:5] #print(elems) features['words'][i] = words features['meta'][i] =", "for p, n in zip(pos, neg): if p[1] > n[1]: count += 1.0", "grid_search.best_score_) print(\"Best parameters set:\") best_parameters = grid_search.best_estimator_.get_params() for param_name in sorted(parameters.keys()): print(\"\\t%s: %r\"", "# {'meta': 0.5, 'word': 1.0, 'char': 0.5}, # {'meta': 0.5, 'word': 0.75, 'char':", "print(\"parameters:\") pprint(parameters) t0 = time() #pipeline.fit(train_data[0], train_data[1]) #.contents, train_data.labels) '''for params in grid_params:", "dict of sequences. Keys are `subject` and `body`. \"\"\" def fit(self, x, y=None):", "{'meta': 1.0, 'word': 0.75, 'char': 0.5}, # {'meta': 1.0, 'word': 0.5, 'char': 1.0},", "Define a pipeline combining a text feature extractor with a simple # classifier", "a sample output of a run on a quad-core machine:: Loading 20 newsgroups", "import numpy as np from sklearn.feature_extraction import DictVectorizer from sklearn.feature_extraction.text import CountVectorizer from", "'union__word__vect__max_df': (0.7, 0.8, 0.9, 1.0), #0.5, 'union__char__vect__max_df': (0.7, 0.8, 0.9, 1.0), #0.5, #'vect__max_features':", "test data...') score = grid_search.score(test_data[0], test_data[1]) print('Test score: %.3f' % score) probs =", "point: %d' % mid) pos = probs[:mid] neg = probs[mid:] assert len(pos) ==", "of them. Here is a sample output of a run on a quad-core", "1737.030s Best score: 0.940 Best parameters set: clf__alpha: 9.9999999999999995e-07 clf__n_iter: 50 clf__penalty: 'elasticnet'", "NNS etc.) # X_count_nouns.append(count_nouns(sentence)) X = np.array([X_num_token]).T #, X_count_nouns]).T if not hasattr(self, 'scalar'):", "from sklearn.feature_extraction.text import TfidfTransformer from sklearn.linear_model import SGDClassifier from sklearn.model_selection import ParameterGrid, GridSearchCV", "float(ens), 'event_pred': bool(ep)}) return features # ############################################################################# # Load data test def load_data(filename,", "50000)} done in 1737.030s Best score: 0.940 Best parameters set: clf__alpha: 9.9999999999999995e-07 clf__n_iter:", "= line.strip().split() orig_idx_array.append(elems[0]) counter = 0 for line in einf: elems = line.strip().split()", "# {'meta': 1.0, 'word': 0.75, 'char': 0.75}, # {'meta': 1.0, 'word': 0.75, 'char':", "#'clf__n_iter': (10, 50, 80), } if __name__ == \"__main__\": # multiprocessing requires the", "pipeline = Pipeline([ ('featextract', FeatureExtractor()), ('union', FeatureUnion( transformer_list=[ ('meta', Pipeline([ ('selector', ItemSelector(key='meta')), ('vect',", "happen in a __main__ protected # block # find the best parameters for", "self.scalar.transform(X) class FeatureExtractor(BaseEstimator, TransformerMixin): \"\"\"Extract the subject & body from a usenet post", "'event_normscore': float(ens), 'event_pred': bool(ep)}) return features # ############################################################################# # Load data test def", "'char': 0.5}, # {'meta': 1.0, 'word': 0.75, 'char': 1.0}, # {'meta': 1.0, 'word':", "= pairwise_eval(probs) # exit(0) #grid_params = list(ParameterGrid(parameters)) grid_search = GridSearchCV(pipeline, parameters, cv=5, n_jobs=-1,", "sys.argv[6]) #train_e2o = event_orig_mapping(sys.argv[7], sys.argv[8]) #test_e2o = event_orig_mapping(sys.argv[9], sys.argv[10]) # add event-to-event info", "text and calculates type token ratio X_num_token.append(len(sentence)) # takes pos tag text and", "0.5}, # {'meta': 0.75, 'word': 0.75, 'char': 1.0}, # {'meta': 0.75, 'word': 0.75,", "t0 = time() #pipeline.fit(train_data[0], train_data[1]) #.contents, train_data.labels) '''for params in grid_params: print('Current parameters:',", "event_idx_dict[oidx] print ('map dictionary size:', len(origin_to_event)) return origin_to_event def add_e2e_scores(original_data_array, event_data_array, origin_to_event): assert", "uncommenting more parameters will give better exploring power but will # increase processing", "def get_feature_names(self): return np.array(['sent_len']) #, 'lang_prob']) def fit(self, documents, y=None): return self def", "probs[:mid] neg = probs[mid:] assert len(pos) == len(neg) count = 0.0 for p,", "1.0}, # {'meta': 1.0, 'word': 0.5, 'char': 0.75}, # {'meta': 1.0, 'word': 0.5,", "{'meta': 0.5, 'word': 0.5, 'char': 0.75}, # {'meta': 0.5, 'word': 0.5, 'char': 0.5},", "#, 'lang_prob']) def fit(self, documents, y=None): return self def transform(self, x_dataset): X_num_token =", "print(\"Best parameters set:\") best_parameters = grid_search.best_estimator_.get_params() for param_name in sorted(parameters.keys()): print(\"\\t%s: %r\" %", "float(cs), 'score': float(s), 'normscore': float(ns), 'langpred': bool(lp)} if len(elems) > 5: ecs, es,", "5000, 10000, 50000)} done in 1737.030s Best score: 0.940 Best parameters set: clf__alpha:", "(NN, NNS etc.) # X_count_nouns.append(count_nouns(sentence)) X = np.array([X_num_token]).T #, X_count_nouns]).T if not hasattr(self,", "names to the dataset loader or setting them to None to get the", "'char': 0.75}, # {'meta': 1.0, 'word': 0.75, 'char': 0.5}, # {'meta': 1.0, 'word':", "'char': 0.75}, # {'meta': 0.75, 'word': 0.5, 'char': 0.5}, # {'meta': 0.5, 'word':", "StandardScaler #print(__doc__) import warnings with warnings.catch_warnings(): warnings.filterwarnings(\"ignore\",category=Warning) #DeprecationWarning) # Display progress logs on", "'word': 1.0, 'char': 0.75}, # {'meta': 0.75, 'word': 1.0, 'char': 0.5}, # {'meta':", "############################################################################# # Define a pipeline combining a text feature extractor with a simple", "0.75}, # {'meta': 0.5, 'word': 0.5, 'char': 0.5}, ), 'union__word__vect__max_df': (0.7, 0.8, 0.9,", "ecs, es, ens, ep = elems[5:] features['meta'][i].update({'event_condscore': float(ecs), 'event_score': float(es), 'event_normscore': float(ens), 'event_pred':", "1.0, 'word': 1.0, 'char': 0.75}, # {'meta': 1.0, 'word': 1.0, 'char': 0.5}, #", "protected # block # find the best parameters for both the feature extraction", "document classification example. You can adjust the number of categories by giving their", "StoryData() with open(filename+'.true.'+suffix) as tinf, open(filename+'.false.'+suffix) as finf: for line in tinf: elems", "1.0, 'word': 0.75, 'char': 0.5}, # {'meta': 1.0, 'word': 0.5, 'char': 1.0}, #", "# probs = pipeline.predict_proba(test_data[0]) # acc = pairwise_eval(probs) # exit(0) #grid_params = list(ParameterGrid(parameters))", "\"__main__\": # multiprocessing requires the fork to happen in a __main__ protected #", "FeatureUnion( transformer_list=[ ('meta', Pipeline([ ('selector', ItemSelector(key='meta')), ('vect', DictVectorizer()), ('scale', StandardScaler(with_mean=False)), ])), ('word', Pipeline([", "tinf, open(filename+'.false.'+suffix) as finf: for line in tinf: elems = line.strip()#.split('\\t') contents.append(elems) labels.append(1)", "in oinf: elems = line.strip().split() orig_idx_array.append(elems[0]) counter = 0 for line in einf:", "ratio X_num_token.append(len(sentence)) # takes pos tag text and counts number of noun pos", "pipeline for text feature extraction and evaluation ========================================================== The dataset used in this", "= line.strip()#.split('\\t') contents.append(elems) labels.append(1) for line in finf: elems = line.strip()#.split('\\t') contents.append(elems) labels.append(0)", "], transformer_weights={ 'meta': 0.3, 'word': 1.0, 'char': 1.0, }, )), ('clf', SGDClassifier(loss='log', alpha=0.0005,", "object), ('langpred', bool)]) for i, text in enumerate(posts): elems = text.split('\\t') words, cs,", "in origin_to_event: #print(i, origin_to_event[i-half_len], len(origin_to_event)) original_data_array[i] = elems + '\\t' + event_data_array[origin_to_event[i-half_len] +", "= line.strip().split() event_idx_dict[elems[0]] = counter counter += 1 origin_to_event = {} for i,", "Pipeline([ ('selector', ItemSelector(key='meta')), ('vect', DictVectorizer()), ('scale', StandardScaler(with_mean=False)), ])), ('word', Pipeline([ ('selector', ItemSelector(key='words')), ('vect',", "of categories by giving their names to the dataset loader or setting them", "2 categories Performing grid search... pipeline: ['vect', 'tfidf', 'clf'] parameters: {'clf__alpha': (1.0000000000000001e-05, 9.9999999999999995e-07),", "p[1] > n[1]: count += 1.0 # print('True') # else: # print('False') acc", "a pipeline combining a text feature extractor with a simple # classifier pipeline", "1.0, 'char': 1.0, }, )), ('clf', SGDClassifier(loss='log', alpha=0.0005, tol=0.005, random_state=0)), ]) # uncommenting", "FeatureUnion from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler #print(__doc__) import warnings with", "0.75, 'word': 0.5, 'char': 0.75}, # {'meta': 0.75, 'word': 0.5, 'char': 0.5}, #", "open(event_idx_file) as einf: oinf.readline() einf.readline() for line in oinf: elems = line.strip().split() orig_idx_array.append(elems[0])", "fit(self, documents, y=None): return self def transform(self, x_dataset): X_num_token = list() #X_count_nouns =", "def __init__(self): pass def get_feature_names(self): return np.array(['sent_len']) #, 'lang_prob']) def fit(self, documents, y=None):", "('selector', ItemSelector(key='words')), ('vect', CountVectorizer(ngram_range=(1,5), analyzer='char', max_df=0.8)), ('tfidf', TfidfTransformer()), ])), ], transformer_weights={ 'meta': 0.3,", "+ '\\t' + event_data_array[origin_to_event[i]] if i - half_len in origin_to_event: #print(i, origin_to_event[i-half_len], len(origin_to_event))", "a single pass. Takes a sequence of strings and produces a dict of", "0.75, 'char': 0.75}, # {'meta': 1.0, 'word': 0.75, 'char': 0.5}, # {'meta': 1.0,", "n[1]: count += 1.0 # print('True') # else: # print('False') acc = count/mid", "but will # increase processing time in a combinatorial way parameters = {", "verbose=1) print(\"Performing grid search...\") print(\"pipeline:\", [name for name, _ in pipeline.steps]) print(\"parameters:\") pprint(parameters)", "logging import sys import numpy as np from sklearn.feature_extraction import DictVectorizer from sklearn.feature_extraction.text", "extraction and evaluation ========================================================== The dataset used in this example is the 20", "# increase processing time in a combinatorial way parameters = { 'union__transformer_weights': ({'meta':", "vect__max_df: 0.75 vect__max_features: 50000 \"\"\" # Author: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> #", "not hasattr(self, 'scalar'): self.scalar = StandardScaler().fit(X) return self.scalar.transform(X) class FeatureExtractor(BaseEstimator, TransformerMixin): \"\"\"Extract the", "# ############################################################################# # Load data test def load_data(filename, suffix): contents, labels = [],", "('map dictionary size:', len(origin_to_event)) return origin_to_event def add_e2e_scores(original_data_array, event_data_array, origin_to_event): assert len(event_data_array) ==", "and evaluation ========================================================== The dataset used in this example is the 20 newsgroups", "== 2 * len(origin_to_event), (len(event_data_array), len(origin_to_event)) assert len(original_data_array) >= len(event_data_array) half_len = len(original_data_array)", "{'meta': 0.75, 'word': 0.75, 'char': 0.75}, # {'meta': 0.75, 'word': 0.75, 'char': 0.5},", "of a run on a quad-core machine:: Loading 20 newsgroups dataset for categories:", "give better exploring power but will # increase processing time in a combinatorial", "Pipeline([ ('selector', ItemSelector(key='words')), ('vect', CountVectorizer(ngram_range=(1,5), max_df=0.9)), ('tfidf', TfidfTransformer()), ])), ('char', Pipeline([ ('selector', ItemSelector(key='words')),", "elems + '\\t' + event_data_array[origin_to_event[i]] if i - half_len in origin_to_event: #print(i, origin_to_event[i-half_len],", "from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler #print(__doc__) import warnings with warnings.catch_warnings():", "float(ns), 'langpred': bool(lp)} if len(elems) > 5: ecs, es, ens, ep = elems[5:]", "the dataset loader or setting them to None to get the 20 of", "len(words.split()), 'condscore': float(cs), 'score': float(s), 'normscore': float(ns), 'langpred': bool(lp)} if len(elems) > 5:", "print ('map dictionary size:', len(origin_to_event)) return origin_to_event def add_e2e_scores(original_data_array, event_data_array, origin_to_event): assert len(event_data_array)", "return original_data_array def pairwise_eval(probs): mid = int(len(probs) / 2) print('middle point: %d' %", "simple # classifier pipeline = Pipeline([ ('featextract', FeatureExtractor()), ('union', FeatureUnion( transformer_list=[ ('meta', Pipeline([", "0.75, 'char': 0.5}, # {'meta': 1.0, 'word': 0.5, 'char': 1.0}, # {'meta': 1.0,", "= np.array([X_num_token]).T #, X_count_nouns]).T if not hasattr(self, 'scalar'): self.scalar = StandardScaler().fit(X) return self.scalar.transform(X)", "'word': 0.5, 'char': 0.5}, {'meta': 0.7, 'word': 1.0, 'char': 1.0}, {'meta': 0.5, 'word':", "list(ParameterGrid(parameters)) grid_search = GridSearchCV(pipeline, parameters, cv=5, n_jobs=-1, verbose=1) print(\"Performing grid search...\") print(\"pipeline:\", [name", "will be automatically downloaded and then cached and reused for the document classification", "StandardScaler().fit(X) return self.scalar.transform(X) class FeatureExtractor(BaseEstimator, TransformerMixin): \"\"\"Extract the subject & body from a", "print(\"Best score: %0.3f\" % grid_search.best_score_) print(\"Best parameters set:\") best_parameters = grid_search.best_estimator_.get_params() for param_name", "y=None): return self def transform(self, x_dataset): X_num_token = list() #X_count_nouns = list() for", "suffix): contents, labels = [], [] #data = StoryData() with open(filename+'.true.'+suffix) as tinf,", "#'tfidf__use_idf': (True, False), #'tfidf__norm': ('l1', 'l2'), 'clf__alpha': (0.001, 0.0005, 0.0001), #'clf__penalty': ('l2', 'l1'),", "multiprocessing requires the fork to happen in a __main__ protected # block #", "# {'meta': 1.0, 'word': 0.5, 'char': 0.5}, {'meta': 0.7, 'word': 1.0, 'char': 1.0},", "time import logging import sys import numpy as np from sklearn.feature_extraction import DictVectorizer", "(True, False), 'vect__max_n': (1, 2), 'vect__max_df': (0.5, 0.75, 1.0), 'vect__max_features': (None, 5000, 10000,", "= line.strip()#.split('\\t') contents.append(elems) labels.append(0) print(\"data size:\", len(contents)) return [contents, labels] def event_orig_mapping(orig_idx_file, event_idx_file):", "adjust the number of categories by giving their names to the dataset loader", "elems = text.split('\\t') words, cs, s, ns, lp = elems[:5] #print(elems) features['words'][i] =", "1.0, 'char': 0.75}, # {'meta': 0.75, 'word': 1.0, 'char': 0.5}, # {'meta': 0.75,", "0.5, 'word': 0.5, 'char': 0.75}, # {'meta': 0.5, 'word': 0.5, 'char': 0.5}, ),", "to get the 20 of them. Here is a sample output of a", "which will be automatically downloaded and then cached and reused for the document", "line in finf: elems = line.strip()#.split('\\t') contents.append(elems) labels.append(0) print(\"data size:\", len(contents)) return [contents,", "0.75, 'word': 0.75, 'char': 0.5}, # {'meta': 0.75, 'word': 0.5, 'char': 1.0}, #", "clause from __future__ import print_function from pprint import pprint from time import time", "__init__(self): pass def get_feature_names(self): return np.array(['sent_len']) #, 'lang_prob']) def fit(self, documents, y=None): return", "test_data = load_data(sys.argv[2], sys.argv[3]) #train_event = load_data(sys.argv[4], sys.argv[6]) #test_event = load_data(sys.argv[5], sys.argv[6]) #train_e2o", "('clf', SGDClassifier(loss='log', alpha=0.0005, tol=0.005, random_state=0)), ]) # uncommenting more parameters will give better", "float(ecs), 'event_score': float(es), 'event_normscore': float(ens), 'event_pred': bool(ep)}) return features # ############################################################################# # Load", "= int(len(probs) / 2) print('middle point: %d' % mid) pos = probs[:mid] neg", "train_data = load_data(sys.argv[1], sys.argv[3]) test_data = load_data(sys.argv[2], sys.argv[3]) #train_event = load_data(sys.argv[4], sys.argv[6]) #test_event", "# {'meta': 0.75, 'word': 0.75, 'char': 0.5}, # {'meta': 0.75, 'word': 0.5, 'char':", "def transform(self, x_dataset): X_num_token = list() #X_count_nouns = list() for sentence in x_dataset:", "{'meta': 0.7, 'word': 1.0, 'char': 1.0}, {'meta': 0.5, 'word': 1.0, 'char': 1.0}, {'meta':", "test_event[0], test_e2o) print('Finished data loading!!') for elem in train_data[0][:10]: print (elem) # #############################################################################", "'vect__max_features': (None, 5000, 10000, 50000)} done in 1737.030s Best score: 0.940 Best parameters", "= probs[:mid] neg = probs[mid:] assert len(pos) == len(neg) count = 0.0 for", "origin_to_event = {} for i, oidx in enumerate(orig_idx_array): if oidx in event_idx_dict: origin_to_event[i]", "Here is a sample output of a run on a quad-core machine:: Loading", "('l2', 'elasticnet'), 'tfidf__use_idf': (True, False), 'vect__max_n': (1, 2), 'vect__max_df': (0.5, 0.75, 1.0), 'vect__max_features':", "pipeline.steps]) print(\"parameters:\") pprint(parameters) t0 = time() #pipeline.fit(train_data[0], train_data[1]) #.contents, train_data.labels) '''for params in", "params) pipeline.set_params(**params) pipeline.fit(train_data[0], train_data[1]) probs = pipeline.predict_proba(test_data[0]) acc = pairwise_eval(probs) exit(0) ''' grid_search.fit(train_data[0],", "and `body`. \"\"\" def fit(self, x, y=None): return self def transform(self, posts): features", "example. You can adjust the number of categories by giving their names to", "mid) pos = probs[:mid] neg = probs[mid:] assert len(pos) == len(neg) count =", "# License: BSD 3 clause from __future__ import print_function from pprint import pprint", "self def transform(self, data_dict): return data_dict[self.key] class CustomFeatures(BaseEstimator): def __init__(self): pass def get_feature_names(self):", "event_orig_mapping(sys.argv[7], sys.argv[8]) #test_e2o = event_orig_mapping(sys.argv[9], sys.argv[10]) # add event-to-event info #train_data[0] = add_e2e_scores(train_data[0],", "('union', FeatureUnion( transformer_list=[ ('meta', Pipeline([ ('selector', ItemSelector(key='meta')), ('vect', DictVectorizer()), ('scale', StandardScaler(with_mean=False)), ])), ('word',", "0.5}, # {'meta': 0.5, 'word': 0.75, 'char': 1.0}, # {'meta': 0.5, 'word': 0.75,", "((1, 4), (1, 5)), # trigram or 5-grams #'tfidf__use_idf': (True, False), #'tfidf__norm': ('l1',", "quad-core machine:: Loading 20 newsgroups dataset for categories: ['alt.atheism', 'talk.religion.misc'] 1427 documents 2", "event_data_array[origin_to_event[i-half_len] + len(origin_to_event)] return original_data_array def pairwise_eval(probs): mid = int(len(probs) / 2) print('middle", "data loading!!') for elem in train_data[0][:10]: print (elem) # ############################################################################# # Define a", "0.5}, {'meta': 0.7, 'word': 1.0, 'char': 1.0}, {'meta': 0.5, 'word': 1.0, 'char': 1.0},", "list() #X_count_nouns = list() for sentence in x_dataset: # takes raw text and", "'lang_prob']) def fit(self, documents, y=None): return self def transform(self, x_dataset): X_num_token = list()", "def add_e2e_scores(original_data_array, event_data_array, origin_to_event): assert len(event_data_array) == 2 * len(origin_to_event), (len(event_data_array), len(origin_to_event)) assert", "parameters = { 'union__transformer_weights': ({'meta': 0.6, 'word': 1.0, 'char': 1.0}, # {'meta': 1.0,", "{'meta': 0.5, 'word': 0.75, 'char': 0.5}, # {'meta': 0.5, 'word': 0.5, 'char': 1.0},", "for both the feature extraction and the # classifier # pipeline.fit(train_data[0], train_data[1]) #", "0.5, 'word': 1.0, 'char': 1.0}, {'meta': 0.4, 'word': 1.0, 'char': 1.0}, {'meta': 0.3,", "('condscore', object), ('score', object), ('normscore', object), ('langpred', bool)]) for i, text in enumerate(posts):", "(0.5, 0.75, 1.0), 'vect__max_features': (None, 5000, 10000, 50000)} done in 1737.030s Best score:", "labels] def event_orig_mapping(orig_idx_file, event_idx_file): orig_idx_array = [] event_idx_dict = {} with open(orig_idx_file) as", "data...') score = grid_search.score(test_data[0], test_data[1]) print('Test score: %.3f' % score) probs = grid_search.predict_proba(test_data[0])", "%.3f' % acc) return acc train_data = load_data(sys.argv[1], sys.argv[3]) test_data = load_data(sys.argv[2], sys.argv[3])", "DictVectorizer()), ('scale', StandardScaler(with_mean=False)), ])), ('word', Pipeline([ ('selector', ItemSelector(key='words')), ('vect', CountVectorizer(ngram_range=(1,5), max_df=0.9)), ('tfidf', TfidfTransformer()),", "# Display progress logs on stdout logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') class ItemSelector(BaseEstimator, TransformerMixin):", "time() #pipeline.fit(train_data[0], train_data[1]) #.contents, train_data.labels) '''for params in grid_params: print('Current parameters:', params) pipeline.set_params(**params)", "= {'length': len(words.split()), 'condscore': float(cs), 'score': float(s), 'normscore': float(ns), 'langpred': bool(lp)} if len(elems)", "#test_data[0] = add_e2e_scores(test_data[0], test_event[0], test_e2o) print('Finished data loading!!') for elem in train_data[0][:10]: print", "in tinf: elems = line.strip()#.split('\\t') contents.append(elems) labels.append(1) for line in finf: elems =", "BSD 3 clause from __future__ import print_function from pprint import pprint from time", "'char': 0.5}, # {'meta': 0.5, 'word': 0.5, 'char': 1.0}, # {'meta': 0.5, 'word':", "['vect', 'tfidf', 'clf'] parameters: {'clf__alpha': (1.0000000000000001e-05, 9.9999999999999995e-07), 'clf__n_iter': (10, 50, 80), 'clf__penalty': ('l2',", "and the # classifier # pipeline.fit(train_data[0], train_data[1]) # probs = pipeline.predict_proba(test_data[0]) # acc", "'char': 1.0}, # {'meta': 1.0, 'word': 0.75, 'char': 0.75}, # {'meta': 1.0, 'word':", "sklearn.pipeline import FeatureUnion from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler #print(__doc__) import", "= StandardScaler().fit(X) return self.scalar.transform(X) class FeatureExtractor(BaseEstimator, TransformerMixin): \"\"\"Extract the subject & body from", "('featextract', FeatureExtractor()), ('union', FeatureUnion( transformer_list=[ ('meta', Pipeline([ ('selector', ItemSelector(key='meta')), ('vect', DictVectorizer()), ('scale', StandardScaler(with_mean=False)),", "classification example. You can adjust the number of categories by giving their names", "BaseEstimator, TransformerMixin from sklearn.pipeline import FeatureUnion from sklearn.pipeline import Pipeline from sklearn.preprocessing import", "np.array(['sent_len']) #, 'lang_prob']) def fit(self, documents, y=None): return self def transform(self, x_dataset): X_num_token", "enumerate(original_data_array): if i in origin_to_event: original_data_array[i] = elems + '\\t' + event_data_array[origin_to_event[i]] if", "for i, elems in enumerate(original_data_array): if i in origin_to_event: original_data_array[i] = elems +", "fit(self, x, y=None): return self def transform(self, posts): features = np.recarray(shape=(len(posts),), dtype=[('words', object),", "{'length': len(words.split()), 'condscore': float(cs), 'score': float(s), 'normscore': float(ns), 'langpred': bool(lp)} if len(elems) >", "pprint(parameters) t0 = time() #pipeline.fit(train_data[0], train_data[1]) #.contents, train_data.labels) '''for params in grid_params: print('Current", "tol=0.005, random_state=0)), ]) # uncommenting more parameters will give better exploring power but", "# {'meta': 0.5, 'word': 0.5, 'char': 0.75}, # {'meta': 0.5, 'word': 0.5, 'char':", "len(pos) == len(neg) count = 0.0 for p, n in zip(pos, neg): if", "1.0 # print('True') # else: # print('False') acc = count/mid print('Test result: %.3f'", "# acc = pairwise_eval(probs) # exit(0) #grid_params = list(ParameterGrid(parameters)) grid_search = GridSearchCV(pipeline, parameters,", "search...\") print(\"pipeline:\", [name for name, _ in pipeline.steps]) print(\"parameters:\") pprint(parameters) t0 = time()", "%r\" % (param_name, best_parameters[param_name])) print('predicting on the test data...') score = grid_search.score(test_data[0], test_data[1])", "FeatureExtractor(BaseEstimator, TransformerMixin): \"\"\"Extract the subject & body from a usenet post in a", "newsgroups dataset which will be automatically downloaded and then cached and reused for", "search... pipeline: ['vect', 'tfidf', 'clf'] parameters: {'clf__alpha': (1.0000000000000001e-05, 9.9999999999999995e-07), 'clf__n_iter': (10, 50, 80),", "pipeline.fit(train_data[0], train_data[1]) probs = pipeline.predict_proba(test_data[0]) acc = pairwise_eval(probs) exit(0) ''' grid_search.fit(train_data[0], train_data[1]) print(\"done", "for line in tinf: elems = line.strip()#.split('\\t') contents.append(elems) labels.append(1) for line in finf:", "event-to-event info #train_data[0] = add_e2e_scores(train_data[0], train_event[0], train_e2o) #test_data[0] = add_e2e_scores(test_data[0], test_event[0], test_e2o) print('Finished", "pairwise_eval(probs) # exit(0) #grid_params = list(ParameterGrid(parameters)) grid_search = GridSearchCV(pipeline, parameters, cv=5, n_jobs=-1, verbose=1)", "classifier pipeline = Pipeline([ ('featextract', FeatureExtractor()), ('union', FeatureUnion( transformer_list=[ ('meta', Pipeline([ ('selector', ItemSelector(key='meta')),", "TfidfTransformer from sklearn.linear_model import SGDClassifier from sklearn.model_selection import ParameterGrid, GridSearchCV from sklearn.base import", "import Pipeline from sklearn.preprocessing import StandardScaler #print(__doc__) import warnings with warnings.catch_warnings(): warnings.filterwarnings(\"ignore\",category=Warning) #DeprecationWarning)", "as tinf, open(filename+'.false.'+suffix) as finf: for line in tinf: elems = line.strip()#.split('\\t') contents.append(elems)", "# {'meta': 0.75, 'word': 0.75, 'char': 1.0}, # {'meta': 0.75, 'word': 0.75, 'char':", "them to None to get the 20 of them. Here is a sample", "sklearn.linear_model import SGDClassifier from sklearn.model_selection import ParameterGrid, GridSearchCV from sklearn.base import BaseEstimator, TransformerMixin", "time import time import logging import sys import numpy as np from sklearn.feature_extraction", "print('True') # else: # print('False') acc = count/mid print('Test result: %.3f' % acc)", "mid = int(len(probs) / 2) print('middle point: %d' % mid) pos = probs[:mid]", "/ 2) print('middle point: %d' % mid) pos = probs[:mid] neg = probs[mid:]", "1.0}, # {'meta': 0.75, 'word': 1.0, 'char': 0.75}, # {'meta': 0.75, 'word': 1.0,", "parameters for both the feature extraction and the # classifier # pipeline.fit(train_data[0], train_data[1])", "if p[1] > n[1]: count += 1.0 # print('True') # else: # print('False')", "self def transform(self, posts): features = np.recarray(shape=(len(posts),), dtype=[('words', object), ('meta', object)]) #('length', object),", "('vect', DictVectorizer()), ('scale', StandardScaler(with_mean=False)), ])), ('word', Pipeline([ ('selector', ItemSelector(key='words')), ('vect', CountVectorizer(ngram_range=(1,5), max_df=0.9)), ('tfidf',", "i, elems in enumerate(original_data_array): if i in origin_to_event: original_data_array[i] = elems + '\\t'", "0.75, 'char': 0.75}, # {'meta': 0.5, 'word': 0.75, 'char': 0.5}, # {'meta': 0.5,", "'char': 1.0}, # {'meta': 1.0, 'word': 1.0, 'char': 0.75}, # {'meta': 1.0, 'word':", "of noun pos tags (NN, NNS etc.) # X_count_nouns.append(count_nouns(sentence)) X = np.array([X_num_token]).T #,", "0.3, 'word': 1.0, 'char': 1.0, }, )), ('clf', SGDClassifier(loss='log', alpha=0.0005, tol=0.005, random_state=0)), ])", "pprint from time import time import logging import sys import numpy as np", "= count/mid print('Test result: %.3f' % acc) return acc train_data = load_data(sys.argv[1], sys.argv[3])", "0.75}, # {'meta': 0.5, 'word': 0.75, 'char': 0.5}, # {'meta': 0.5, 'word': 0.5,", "80), 'clf__penalty': ('l2', 'elasticnet'), 'tfidf__use_idf': (True, False), 'vect__max_n': (1, 2), 'vect__max_df': (0.5, 0.75,", "'union__char__vect__max_df': (0.7, 0.8, 0.9, 1.0), #0.5, #'vect__max_features': (None, 5000, 10000, 50000), #'union__word__vect__ngram_range': ((1,", "= add_e2e_scores(test_data[0], test_event[0], test_e2o) print('Finished data loading!!') for elem in train_data[0][:10]: print (elem)", "loader or setting them to None to get the 20 of them. Here", "from sklearn.linear_model import SGDClassifier from sklearn.model_selection import ParameterGrid, GridSearchCV from sklearn.base import BaseEstimator,", "transformer_weights={ 'meta': 0.3, 'word': 1.0, 'char': 1.0, }, )), ('clf', SGDClassifier(loss='log', alpha=0.0005, tol=0.005,", "x, y=None): return self def transform(self, data_dict): return data_dict[self.key] class CustomFeatures(BaseEstimator): def __init__(self):", "in sorted(parameters.keys()): print(\"\\t%s: %r\" % (param_name, best_parameters[param_name])) print('predicting on the test data...') score", "a text feature extractor with a simple # classifier pipeline = Pipeline([ ('featextract',", "1.0, 'char': 1.0}, {'meta': 0.4, 'word': 1.0, 'char': 1.0}, {'meta': 0.3, 'word': 1.0,", "[contents, labels] def event_orig_mapping(orig_idx_file, event_idx_file): orig_idx_array = [] event_idx_dict = {} with open(orig_idx_file)", "9.9999999999999995e-07), 'clf__n_iter': (10, 50, 80), 'clf__penalty': ('l2', 'elasticnet'), 'tfidf__use_idf': (True, False), 'vect__max_n': (1,", "parameters: {'clf__alpha': (1.0000000000000001e-05, 9.9999999999999995e-07), 'clf__n_iter': (10, 50, 80), 'clf__penalty': ('l2', 'elasticnet'), 'tfidf__use_idf': (True,", "SGDClassifier from sklearn.model_selection import ParameterGrid, GridSearchCV from sklearn.base import BaseEstimator, TransformerMixin from sklearn.pipeline", "0.5}, # {'meta': 0.75, 'word': 0.5, 'char': 1.0}, # {'meta': 0.75, 'word': 0.5,", "for line in oinf: elems = line.strip().split() orig_idx_array.append(elems[0]) counter = 0 for line", "#, X_count_nouns]).T if not hasattr(self, 'scalar'): self.scalar = StandardScaler().fit(X) return self.scalar.transform(X) class FeatureExtractor(BaseEstimator,", "increase processing time in a combinatorial way parameters = { 'union__transformer_weights': ({'meta': 0.6,", "{'meta': 0.5, 'word': 1.0, 'char': 0.75}, # {'meta': 0.5, 'word': 1.0, 'char': 0.5},", "Loading 20 newsgroups dataset for categories: ['alt.atheism', 'talk.religion.misc'] 1427 documents 2 categories Performing", "= np.recarray(shape=(len(posts),), dtype=[('words', object), ('meta', object)]) #('length', object), ('condscore', object), ('score', object), ('normscore',", "<NAME> <<EMAIL>> # <NAME> <<EMAIL>> # License: BSD 3 clause from __future__ import", "3 clause from __future__ import print_function from pprint import pprint from time import", "from sklearn.pipeline import FeatureUnion from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler #print(__doc__)", "open(filename+'.false.'+suffix) as finf: for line in tinf: elems = line.strip()#.split('\\t') contents.append(elems) labels.append(1) for", "print('predicting on the test data...') score = grid_search.score(test_data[0], test_data[1]) print('Test score: %.3f' %", "#train_data[0] = add_e2e_scores(train_data[0], train_event[0], train_e2o) #test_data[0] = add_e2e_scores(test_data[0], test_event[0], test_e2o) print('Finished data loading!!')", "= load_data(sys.argv[1], sys.argv[3]) test_data = load_data(sys.argv[2], sys.argv[3]) #train_event = load_data(sys.argv[4], sys.argv[6]) #test_event =", "# <NAME> <<EMAIL>> # License: BSD 3 clause from __future__ import print_function from", "('score', object), ('normscore', object), ('langpred', bool)]) for i, text in enumerate(posts): elems =", "neg): if p[1] > n[1]: count += 1.0 # print('True') # else: #", "\"\"\"Extract the subject & body from a usenet post in a single pass.", "1.0}, # {'meta': 0.75, 'word': 0.75, 'char': 0.75}, # {'meta': 0.75, 'word': 0.75,", "subject & body from a usenet post in a single pass. Takes a", "0.75, 'word': 1.0, 'char': 0.75}, # {'meta': 0.75, 'word': 1.0, 'char': 0.5}, #", "text and counts number of noun pos tags (NN, NNS etc.) # X_count_nouns.append(count_nouns(sentence))", "TfidfTransformer()), ])), ], transformer_weights={ 'meta': 0.3, 'word': 1.0, 'char': 1.0, }, )), ('clf',", "pipeline.predict_proba(test_data[0]) acc = pairwise_eval(probs) exit(0) ''' grid_search.fit(train_data[0], train_data[1]) print(\"done in %0.3fs\" % (time()", "(0.7, 0.8, 0.9, 1.0), #0.5, #'vect__max_features': (None, 5000, 10000, 50000), #'union__word__vect__ngram_range': ((1, 4),", "{'meta': 1.0, 'word': 1.0, 'char': 0.75}, # {'meta': 1.0, 'word': 1.0, 'char': 0.5},", "'word': 1.0, 'char': 1.0}, # {'meta': 0.5, 'word': 1.0, 'char': 0.75}, # {'meta':", "% acc) return acc train_data = load_data(sys.argv[1], sys.argv[3]) test_data = load_data(sys.argv[2], sys.argv[3]) #train_event", "FeatureExtractor()), ('union', FeatureUnion( transformer_list=[ ('meta', Pipeline([ ('selector', ItemSelector(key='meta')), ('vect', DictVectorizer()), ('scale', StandardScaler(with_mean=False)), ])),", "1.0}, {'meta': 0.5, 'word': 1.0, 'char': 1.0}, {'meta': 0.4, 'word': 1.0, 'char': 1.0},", "grid_search = GridSearchCV(pipeline, parameters, cv=5, n_jobs=-1, verbose=1) print(\"Performing grid search...\") print(\"pipeline:\", [name for", "'word': 0.75, 'char': 1.0}, # {'meta': 0.75, 'word': 0.75, 'char': 0.75}, # {'meta':", "add_e2e_scores(test_data[0], test_event[0], test_e2o) print('Finished data loading!!') for elem in train_data[0][:10]: print (elem) #", "in %0.3fs\" % (time() - t0)) print() print(\"Best score: %0.3f\" % grid_search.best_score_) print(\"Best", "/ 2 for i, elems in enumerate(original_data_array): if i in origin_to_event: original_data_array[i] =", "1.0, 'char': 1.0}, {'meta': 0.5, 'word': 1.0, 'char': 1.0}, {'meta': 0.4, 'word': 1.0,", "for text feature extraction and evaluation ========================================================== The dataset used in this example", "the subject & body from a usenet post in a single pass. Takes", "You can adjust the number of categories by giving their names to the", "# <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # License: BSD 3 clause from __future__", "========================================================== The dataset used in this example is the 20 newsgroups dataset which", "> 5: ecs, es, ens, ep = elems[5:] features['meta'][i].update({'event_condscore': float(ecs), 'event_score': float(es), 'event_normscore':", "time in a combinatorial way parameters = { 'union__transformer_weights': ({'meta': 0.6, 'word': 1.0,", "= load_data(sys.argv[2], sys.argv[3]) #train_event = load_data(sys.argv[4], sys.argv[6]) #test_event = load_data(sys.argv[5], sys.argv[6]) #train_e2o =", "counter += 1 origin_to_event = {} for i, oidx in enumerate(orig_idx_array): if oidx", "i, oidx in enumerate(orig_idx_array): if oidx in event_idx_dict: origin_to_event[i] = event_idx_dict[oidx] print ('map", "__init__(self, key): self.key = key def fit(self, x, y=None): return self def transform(self,", "'char': 0.5}, {'meta': 0.7, 'word': 1.0, 'char': 1.0}, {'meta': 0.5, 'word': 1.0, 'char':", "# find the best parameters for both the feature extraction and the #", "50, 80), } if __name__ == \"__main__\": # multiprocessing requires the fork to", "(0.001, 0.0005, 0.0001), #'clf__penalty': ('l2', 'l1'), 'clf__tol': (5e-3, 1e-3, 5e-4), #'clf__n_iter': (10, 50,", "classifier # pipeline.fit(train_data[0], train_data[1]) # probs = pipeline.predict_proba(test_data[0]) # acc = pairwise_eval(probs) #", "sklearn.feature_extraction import DictVectorizer from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.linear_model", "return [contents, labels] def event_orig_mapping(orig_idx_file, event_idx_file): orig_idx_array = [] event_idx_dict = {} with", "0 for line in einf: elems = line.strip().split() event_idx_dict[elems[0]] = counter counter +=", "in enumerate(orig_idx_array): if oidx in event_idx_dict: origin_to_event[i] = event_idx_dict[oidx] print ('map dictionary size:',", "for the document classification example. You can adjust the number of categories by", "1.0, 'char': 0.5}, # {'meta': 0.75, 'word': 0.75, 'char': 1.0}, # {'meta': 0.75,", "for name, _ in pipeline.steps]) print(\"parameters:\") pprint(parameters) t0 = time() #pipeline.fit(train_data[0], train_data[1]) #.contents,", "5e-4), #'clf__n_iter': (10, 50, 80), } if __name__ == \"__main__\": # multiprocessing requires", "#.contents, train_data.labels) '''for params in grid_params: print('Current parameters:', params) pipeline.set_params(**params) pipeline.fit(train_data[0], train_data[1]) probs", "len(origin_to_event)) assert len(original_data_array) >= len(event_data_array) half_len = len(original_data_array) / 2 for i, elems", "this example is the 20 newsgroups dataset which will be automatically downloaded and", "raw text and calculates type token ratio X_num_token.append(len(sentence)) # takes pos tag text", "0.5, 'char': 0.75}, # {'meta': 0.5, 'word': 0.5, 'char': 0.5}, ), 'union__word__vect__max_df': (0.7,", "import logging import sys import numpy as np from sklearn.feature_extraction import DictVectorizer from", "{'meta': 1.0, 'word': 0.5, 'char': 0.5}, {'meta': 0.7, 'word': 1.0, 'char': 1.0}, {'meta':", "oinf, open(event_idx_file) as einf: oinf.readline() einf.readline() for line in oinf: elems = line.strip().split()", "0.75}, # {'meta': 1.0, 'word': 0.75, 'char': 0.5}, # {'meta': 1.0, 'word': 0.5,", "1.0, 'word': 0.5, 'char': 0.5}, {'meta': 0.7, 'word': 1.0, 'char': 1.0}, {'meta': 0.5,", "('meta', object)]) #('length', object), ('condscore', object), ('score', object), ('normscore', object), ('langpred', bool)]) for", "#data = StoryData() with open(filename+'.true.'+suffix) as tinf, open(filename+'.false.'+suffix) as finf: for line in", "= probs[mid:] assert len(pos) == len(neg) count = 0.0 for p, n in", "to happen in a __main__ protected # block # find the best parameters", "= words features['meta'][i] = {'length': len(words.split()), 'condscore': float(cs), 'score': float(s), 'normscore': float(ns), 'langpred':", "0.5, 'word': 1.0, 'char': 0.75}, # {'meta': 0.5, 'word': 1.0, 'char': 0.5}, #", "5)), # trigram or 5-grams #'tfidf__use_idf': (True, False), #'tfidf__norm': ('l1', 'l2'), 'clf__alpha': (0.001,", "import warnings with warnings.catch_warnings(): warnings.filterwarnings(\"ignore\",category=Warning) #DeprecationWarning) # Display progress logs on stdout logging.basicConfig(level=logging.INFO,", "= add_e2e_scores(train_data[0], train_event[0], train_e2o) #test_data[0] = add_e2e_scores(test_data[0], test_event[0], test_e2o) print('Finished data loading!!') for", "(None, 5000, 10000, 50000), #'union__word__vect__ngram_range': ((1, 4), (1, 5)), # trigram or 5-grams", "alpha=0.0005, tol=0.005, random_state=0)), ]) # uncommenting more parameters will give better exploring power", "import BaseEstimator, TransformerMixin from sklearn.pipeline import FeatureUnion from sklearn.pipeline import Pipeline from sklearn.preprocessing", "'word': 1.0, 'char': 0.5}, # {'meta': 0.5, 'word': 0.75, 'char': 1.0}, # {'meta':", "%0.3f\" % grid_search.best_score_) print(\"Best parameters set:\") best_parameters = grid_search.best_estimator_.get_params() for param_name in sorted(parameters.keys()):", "cached and reused for the document classification example. You can adjust the number", "p, n in zip(pos, neg): if p[1] > n[1]: count += 1.0 #", "grid_search.best_estimator_.get_params() for param_name in sorted(parameters.keys()): print(\"\\t%s: %r\" % (param_name, best_parameters[param_name])) print('predicting on the", "einf: oinf.readline() einf.readline() for line in oinf: elems = line.strip().split() orig_idx_array.append(elems[0]) counter =", "# takes raw text and calculates type token ratio X_num_token.append(len(sentence)) # takes pos", "= {} for i, oidx in enumerate(orig_idx_array): if oidx in event_idx_dict: origin_to_event[i] =", "0.5}, # {'meta': 0.5, 'word': 0.5, 'char': 1.0}, # {'meta': 0.5, 'word': 0.5,", "origin_to_event[i] = event_idx_dict[oidx] print ('map dictionary size:', len(origin_to_event)) return origin_to_event def add_e2e_scores(original_data_array, event_data_array,", "1e-3, 5e-4), #'clf__n_iter': (10, 50, 80), } if __name__ == \"__main__\": # multiprocessing", "('scale', StandardScaler(with_mean=False)), ])), ('word', Pipeline([ ('selector', ItemSelector(key='words')), ('vect', CountVectorizer(ngram_range=(1,5), max_df=0.9)), ('tfidf', TfidfTransformer()), ])),", "dataset used in this example is the 20 newsgroups dataset which will be", "0.5, 'char': 1.0}, # {'meta': 0.5, 'word': 0.5, 'char': 0.75}, # {'meta': 0.5,", "einf.readline() for line in oinf: elems = line.strip().split() orig_idx_array.append(elems[0]) counter = 0 for", "= elems + '\\t' + event_data_array[origin_to_event[i]] if i - half_len in origin_to_event: #print(i,", "the number of categories by giving their names to the dataset loader or", "1.0}, # {'meta': 1.0, 'word': 1.0, 'char': 0.75}, # {'meta': 1.0, 'word': 1.0,", "warnings.catch_warnings(): warnings.filterwarnings(\"ignore\",category=Warning) #DeprecationWarning) # Display progress logs on stdout logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')", "%(levelname)s %(message)s') class ItemSelector(BaseEstimator, TransformerMixin): def __init__(self, key): self.key = key def fit(self,", "lp = elems[:5] #print(elems) features['words'][i] = words features['meta'][i] = {'length': len(words.split()), 'condscore': float(cs),", "dataset loader or setting them to None to get the 20 of them.", "of sequences. Keys are `subject` and `body`. \"\"\" def fit(self, x, y=None): return", "0.0001), #'clf__penalty': ('l2', 'l1'), 'clf__tol': (5e-3, 1e-3, 5e-4), #'clf__n_iter': (10, 50, 80), }", "import TfidfTransformer from sklearn.linear_model import SGDClassifier from sklearn.model_selection import ParameterGrid, GridSearchCV from sklearn.base", "format='%(asctime)s %(levelname)s %(message)s') class ItemSelector(BaseEstimator, TransformerMixin): def __init__(self, key): self.key = key def", "{'meta': 0.75, 'word': 0.5, 'char': 0.75}, # {'meta': 0.75, 'word': 0.5, 'char': 0.5},", "'scalar'): self.scalar = StandardScaler().fit(X) return self.scalar.transform(X) class FeatureExtractor(BaseEstimator, TransformerMixin): \"\"\"Extract the subject &", "'char': 0.75}, # {'meta': 0.5, 'word': 1.0, 'char': 0.5}, # {'meta': 0.5, 'word':", "noun pos tags (NN, NNS etc.) # X_count_nouns.append(count_nouns(sentence)) X = np.array([X_num_token]).T #, X_count_nouns]).T", "5-grams (1, 4), #'union__char__vect__ngram_range': ((1, 4), (1, 5)), # trigram or 5-grams #'tfidf__use_idf':", "the 20 newsgroups dataset which will be automatically downloaded and then cached and", "labels = [], [] #data = StoryData() with open(filename+'.true.'+suffix) as tinf, open(filename+'.false.'+suffix) as", "elems[5:] features['meta'][i].update({'event_condscore': float(ecs), 'event_score': float(es), 'event_normscore': float(ens), 'event_pred': bool(ep)}) return features # #############################################################################", "features['meta'][i].update({'event_condscore': float(ecs), 'event_score': float(es), 'event_normscore': float(ens), 'event_pred': bool(ep)}) return features # ############################################################################# #", "contents.append(elems) labels.append(1) for line in finf: elems = line.strip()#.split('\\t') contents.append(elems) labels.append(0) print(\"data size:\",", "# add event-to-event info #train_data[0] = add_e2e_scores(train_data[0], train_event[0], train_e2o) #test_data[0] = add_e2e_scores(test_data[0], test_event[0],", "or 5-grams #'tfidf__use_idf': (True, False), #'tfidf__norm': ('l1', 'l2'), 'clf__alpha': (0.001, 0.0005, 0.0001), #'clf__penalty':", "calculates type token ratio X_num_token.append(len(sentence)) # takes pos tag text and counts number", "enumerate(orig_idx_array): if oidx in event_idx_dict: origin_to_event[i] = event_idx_dict[oidx] print ('map dictionary size:', len(origin_to_event))", "= [], [] #data = StoryData() with open(filename+'.true.'+suffix) as tinf, open(filename+'.false.'+suffix) as finf:", "train_data[1]) probs = pipeline.predict_proba(test_data[0]) acc = pairwise_eval(probs) exit(0) ''' grid_search.fit(train_data[0], train_data[1]) print(\"done in", "'word': 1.0, 'char': 1.0}, {'meta': 0.4, 'word': 1.0, 'char': 1.0}, {'meta': 0.3, 'word':", "single pass. Takes a sequence of strings and produces a dict of sequences.", "extraction and the # classifier # pipeline.fit(train_data[0], train_data[1]) # probs = pipeline.predict_proba(test_data[0]) #", "half_len in origin_to_event: #print(i, origin_to_event[i-half_len], len(origin_to_event)) original_data_array[i] = elems + '\\t' + event_data_array[origin_to_event[i-half_len]", "to the dataset loader or setting them to None to get the 20", "def pairwise_eval(probs): mid = int(len(probs) / 2) print('middle point: %d' % mid) pos", "1.0, 'word': 0.5, 'char': 1.0}, # {'meta': 1.0, 'word': 0.5, 'char': 0.75}, #", "in a __main__ protected # block # find the best parameters for both", "ItemSelector(key='meta')), ('vect', DictVectorizer()), ('scale', StandardScaler(with_mean=False)), ])), ('word', Pipeline([ ('selector', ItemSelector(key='words')), ('vect', CountVectorizer(ngram_range=(1,5), max_df=0.9)),", "usenet post in a single pass. Takes a sequence of strings and produces", "event_idx_dict = {} with open(orig_idx_file) as oinf, open(event_idx_file) as einf: oinf.readline() einf.readline() for", "0.75, 'char': 1.0}, # {'meta': 0.5, 'word': 0.75, 'char': 0.75}, # {'meta': 0.5,", "train_data[0][:10]: print (elem) # ############################################################################# # Define a pipeline combining a text feature", "s, ns, lp = elems[:5] #print(elems) features['words'][i] = words features['meta'][i] = {'length': len(words.split()),", "from time import time import logging import sys import numpy as np from", "oidx in enumerate(orig_idx_array): if oidx in event_idx_dict: origin_to_event[i] = event_idx_dict[oidx] print ('map dictionary", "origin_to_event: #print(i, origin_to_event[i-half_len], len(origin_to_event)) original_data_array[i] = elems + '\\t' + event_data_array[origin_to_event[i-half_len] + len(origin_to_event)]", "% mid) pos = probs[:mid] neg = probs[mid:] assert len(pos) == len(neg) count", "dataset which will be automatically downloaded and then cached and reused for the", "and then cached and reused for the document classification example. You can adjust", "are `subject` and `body`. \"\"\" def fit(self, x, y=None): return self def transform(self,", "sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler #print(__doc__) import warnings with warnings.catch_warnings(): warnings.filterwarnings(\"ignore\",category=Warning)", "SGDClassifier(loss='log', alpha=0.0005, tol=0.005, random_state=0)), ]) # uncommenting more parameters will give better exploring", "X_num_token = list() #X_count_nouns = list() for sentence in x_dataset: # takes raw", "is the 20 newsgroups dataset which will be automatically downloaded and then cached", "X_num_token.append(len(sentence)) # takes pos tag text and counts number of noun pos tags", "0.5}, ), 'union__word__vect__max_df': (0.7, 0.8, 0.9, 1.0), #0.5, 'union__char__vect__max_df': (0.7, 0.8, 0.9, 1.0),", "grid search...\") print(\"pipeline:\", [name for name, _ in pipeline.steps]) print(\"parameters:\") pprint(parameters) t0 =", "def event_orig_mapping(orig_idx_file, event_idx_file): orig_idx_array = [] event_idx_dict = {} with open(orig_idx_file) as oinf,", "%(message)s') class ItemSelector(BaseEstimator, TransformerMixin): def __init__(self, key): self.key = key def fit(self, x,", "pos tag text and counts number of noun pos tags (NN, NNS etc.)", "parameters will give better exploring power but will # increase processing time in", "{ 'union__transformer_weights': ({'meta': 0.6, 'word': 1.0, 'char': 1.0}, # {'meta': 1.0, 'word': 1.0,", "_ in pipeline.steps]) print(\"parameters:\") pprint(parameters) t0 = time() #pipeline.fit(train_data[0], train_data[1]) #.contents, train_data.labels) '''for", "number of noun pos tags (NN, NNS etc.) # X_count_nouns.append(count_nouns(sentence)) X = np.array([X_num_token]).T", "in pipeline.steps]) print(\"parameters:\") pprint(parameters) t0 = time() #pipeline.fit(train_data[0], train_data[1]) #.contents, train_data.labels) '''for params", "False), #'tfidf__norm': ('l1', 'l2'), 'clf__alpha': (0.001, 0.0005, 0.0001), #'clf__penalty': ('l2', 'l1'), 'clf__tol': (5e-3,", "0.5, 'word': 0.75, 'char': 0.5}, # {'meta': 0.5, 'word': 0.5, 'char': 1.0}, #", "len(origin_to_event)) original_data_array[i] = elems + '\\t' + event_data_array[origin_to_event[i-half_len] + len(origin_to_event)] return original_data_array def", "0.9, 1.0), #0.5, 'union__char__vect__max_df': (0.7, 0.8, 0.9, 1.0), #0.5, #'vect__max_features': (None, 5000, 10000,", "(1, 5)), # trigram or 5-grams #'tfidf__use_idf': (True, False), #'tfidf__norm': ('l1', 'l2'), 'clf__alpha':", "in a combinatorial way parameters = { 'union__transformer_weights': ({'meta': 0.6, 'word': 1.0, 'char':", "np from sklearn.feature_extraction import DictVectorizer from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer", "sequence of strings and produces a dict of sequences. Keys are `subject` and", "for i, oidx in enumerate(orig_idx_array): if oidx in event_idx_dict: origin_to_event[i] = event_idx_dict[oidx] print", "'word': 0.5, 'char': 0.75}, # {'meta': 0.75, 'word': 0.5, 'char': 0.5}, # {'meta':", "# {'meta': 0.75, 'word': 1.0, 'char': 0.5}, # {'meta': 0.75, 'word': 0.75, 'char':", "0.75, 'char': 0.5}, # {'meta': 0.75, 'word': 0.5, 'char': 1.0}, # {'meta': 0.75,", "if oidx in event_idx_dict: origin_to_event[i] = event_idx_dict[oidx] print ('map dictionary size:', len(origin_to_event)) return", "# else: # print('False') acc = count/mid print('Test result: %.3f' % acc) return" ]
[ "comb_mod(n,r,mod): if n-r<r: r=n-r N=n R=r u=1 d=1 for i in range(r): u*=N", "def comb_mod(n,r,mod): if n-r<r: r=n-r N=n R=r u=1 d=1 for i in range(r):", "N=n R=r u=1 d=1 for i in range(r): u*=N u%=mod N-=1 d*=R d%=mod", "if n-r<r: r=n-r N=n R=r u=1 d=1 for i in range(r): u*=N u%=mod", "R=r u=1 d=1 for i in range(r): u*=N u%=mod N-=1 d*=R d%=mod R-=1", "n-r<r: r=n-r N=n R=r u=1 d=1 for i in range(r): u*=N u%=mod N-=1", "r=n-r N=n R=r u=1 d=1 for i in range(r): u*=N u%=mod N-=1 d*=R", "<gh_stars>0 def comb_mod(n,r,mod): if n-r<r: r=n-r N=n R=r u=1 d=1 for i in", "u=1 d=1 for i in range(r): u*=N u%=mod N-=1 d*=R d%=mod R-=1 return", "d=1 for i in range(r): u*=N u%=mod N-=1 d*=R d%=mod R-=1 return u*pow(d,mod-2,mod)%mod" ]
[ "\"\"\"QuestionnarieForm Class. TThis class contains the treatments of the existents forms on create", "\"\"\" class Meta: \"\"\"Meta Class. This class defines the informations that will be", "MessageForm(forms.ModelForm): \"\"\"MessageForm Class. TThis class contains the treatments of the existents forms on", "ugettext, ugettext_lazy as _ from models import Message, Questionnaire class MessageForm(forms.ModelForm): \"\"\"MessageForm Class.", "class Meta: \"\"\"Meta Class. This class defines the informations that will be used", "models import Message, Questionnaire class MessageForm(forms.ModelForm): \"\"\"MessageForm Class. TThis class contains the treatments", "based on existent set from Message Model. \"\"\" model = Message fields =", "class QuestionnarieForm(forms.ModelForm): \"\"\"QuestionnarieForm Class. TThis class contains the treatments of the existents forms", "from Message Model. \"\"\" model = Message fields = '__all__' class QuestionnarieForm(forms.ModelForm): \"\"\"QuestionnarieForm", "message page. \"\"\" class Meta: \"\"\"Meta Class. This class defines the informations that", "Class. This class defines the informations that will be used based on existent", "used based on existent set from Questionnarie Model. \"\"\" model = Questionnaire fields", "defines the informations that will be used based on existent set from Message", "Message Model. \"\"\" model = Message fields = '__all__' class QuestionnarieForm(forms.ModelForm): \"\"\"QuestionnarieForm Class.", "as _ from models import Message, Questionnaire class MessageForm(forms.ModelForm): \"\"\"MessageForm Class. TThis class", "import forms from django.utils.translation import ugettext, ugettext_lazy as _ from models import Message,", "Class. TThis class contains the treatments of the existents forms on create message", "This class defines the informations that will be used based on existent set", "that will be used based on existent set from Message Model. \"\"\" model", "django.utils.translation import ugettext, ugettext_lazy as _ from models import Message, Questionnaire class MessageForm(forms.ModelForm):", "page. \"\"\" class Meta: \"\"\"Meta Class. This class defines the informations that will", "'__all__' class QuestionnarieForm(forms.ModelForm): \"\"\"QuestionnarieForm Class. TThis class contains the treatments of the existents", "django import forms from django.utils.translation import ugettext, ugettext_lazy as _ from models import", "existent set from Message Model. \"\"\" model = Message fields = '__all__' class", "the treatments of the existents forms on create message page. \"\"\" class Meta:", "from django.utils.translation import ugettext, ugettext_lazy as _ from models import Message, Questionnaire class", "the existents forms on create message page. \"\"\" class Meta: \"\"\"Meta Class. This", "existents forms on create message page. \"\"\" class Meta: \"\"\"Meta Class. This class", "\"\"\" model = Message fields = '__all__' class QuestionnarieForm(forms.ModelForm): \"\"\"QuestionnarieForm Class. TThis class", "= '__all__' class QuestionnarieForm(forms.ModelForm): \"\"\"QuestionnarieForm Class. TThis class contains the treatments of the", "on create message page. \"\"\" class Meta: \"\"\"Meta Class. This class defines the", "set from Message Model. \"\"\" model = Message fields = '__all__' class QuestionnarieForm(forms.ModelForm):", "will be used based on existent set from Message Model. \"\"\" model =", "import Message, Questionnaire class MessageForm(forms.ModelForm): \"\"\"MessageForm Class. TThis class contains the treatments of", "Questionnaire class MessageForm(forms.ModelForm): \"\"\"MessageForm Class. TThis class contains the treatments of the existents", "= Message fields = '__all__' class QuestionnarieForm(forms.ModelForm): \"\"\"QuestionnarieForm Class. TThis class contains the", "Message fields = '__all__' class QuestionnarieForm(forms.ModelForm): \"\"\"QuestionnarieForm Class. TThis class contains the treatments", "be used based on existent set from Questionnarie Model. \"\"\" model = Questionnaire", "model = Message fields = '__all__' class QuestionnarieForm(forms.ModelForm): \"\"\"QuestionnarieForm Class. TThis class contains", "informations that will be used based on existent set from Questionnarie Model. \"\"\"", "from models import Message, Questionnaire class MessageForm(forms.ModelForm): \"\"\"MessageForm Class. TThis class contains the", "TThis class contains the treatments of the existents forms on create message page.", "used based on existent set from Message Model. \"\"\" model = Message fields", "create message page. \"\"\" class Meta: \"\"\"Meta Class. This class defines the informations", "forms from django.utils.translation import ugettext, ugettext_lazy as _ from models import Message, Questionnaire", "that will be used based on existent set from Questionnarie Model. \"\"\" model", "will be used based on existent set from Questionnarie Model. \"\"\" model =", "QuestionnarieForm(forms.ModelForm): \"\"\"QuestionnarieForm Class. TThis class contains the treatments of the existents forms on", "_ from models import Message, Questionnaire class MessageForm(forms.ModelForm): \"\"\"MessageForm Class. TThis class contains", "from django import forms from django.utils.translation import ugettext, ugettext_lazy as _ from models", "\"\"\"MessageForm Class. TThis class contains the treatments of the existents forms on create", "class contains the treatments of the existents forms on create message page. \"\"\"", "of the existents forms on create message page. \"\"\" class Meta: \"\"\"Meta Class.", "contains the treatments of the existents forms on create message page. \"\"\" class", "the informations that will be used based on existent set from Message Model.", "on existent set from Message Model. \"\"\" model = Message fields = '__all__'", "Message, Questionnaire class MessageForm(forms.ModelForm): \"\"\"MessageForm Class. TThis class contains the treatments of the", "\"\"\"Meta Class. This class defines the informations that will be used based on", "class MessageForm(forms.ModelForm): \"\"\"MessageForm Class. TThis class contains the treatments of the existents forms", "Meta: \"\"\"Meta Class. This class defines the informations that will be used based", "import ugettext, ugettext_lazy as _ from models import Message, Questionnaire class MessageForm(forms.ModelForm): \"\"\"MessageForm", "Model. \"\"\" model = Message fields = '__all__' class QuestionnarieForm(forms.ModelForm): \"\"\"QuestionnarieForm Class. TThis", "class defines the informations that will be used based on existent set from", "ugettext_lazy as _ from models import Message, Questionnaire class MessageForm(forms.ModelForm): \"\"\"MessageForm Class. TThis", "treatments of the existents forms on create message page. \"\"\" class Meta: \"\"\"Meta", "be used based on existent set from Message Model. \"\"\" model = Message", "the informations that will be used based on existent set from Questionnarie Model.", "on existent set from Questionnarie Model. \"\"\" model = Questionnaire fields = '__all__'", "fields = '__all__' class QuestionnarieForm(forms.ModelForm): \"\"\"QuestionnarieForm Class. TThis class contains the treatments of", "forms on create message page. \"\"\" class Meta: \"\"\"Meta Class. This class defines", "defines the informations that will be used based on existent set from Questionnarie", "informations that will be used based on existent set from Message Model. \"\"\"", "based on existent set from Questionnarie Model. \"\"\" model = Questionnaire fields =" ]
[ "def func(): a = int(input(\"enter a number : \")) if a < 0:", "number : \")) if a < 0: print(\"Negative\") elif a > 0: print(\"Positive\")", "if a < 0: print(\"Negative\") elif a > 0: print(\"Positive\") else: print(\"zero\") func()", ": \")) if a < 0: print(\"Negative\") elif a > 0: print(\"Positive\") else:", "\")) if a < 0: print(\"Negative\") elif a > 0: print(\"Positive\") else: print(\"zero\")", "func(): a = int(input(\"enter a number : \")) if a < 0: print(\"Negative\")", "a = int(input(\"enter a number : \")) if a < 0: print(\"Negative\") elif", "a number : \")) if a < 0: print(\"Negative\") elif a > 0:", "= int(input(\"enter a number : \")) if a < 0: print(\"Negative\") elif a", "int(input(\"enter a number : \")) if a < 0: print(\"Negative\") elif a >" ]
[ "tf.Session(config=session_conf) with self.sess.as_default(): # Load the saved meta graph and restore variables saver", "Nagar\\\\n\\\\n Regards.\"\"\" else: template = \"\"\" Dear Sir,\\\\n\\\\n The transaction to the account", "'.join(reqStrArr) print(\"reqStr\") print(reqStr) requestBody = json.loads(reqStr) print(requestBody) if requestBody['message'] is not None: query", "1: template = \"\"\" Dear Sir,\\\\n\\\\n The status of your outward transaction is", "scores[0] + scores[1]*-1 else: score = 0 res = \"Unable to classify request\"", "A/c =>1111111111116452\\\\n 6. Remitter Name =>E456946\\\\n 7. Remitter Details =>ABC Cop DC Nagar\\\\n\\\\n\\\\n", "DC Nagar\\\\n\\\\n Regards.\"\"\" else: if _class == 1: template = \"\"\" Dear Sir,\\\\n\\\\n", "= str(request.body,'utf-8') reqStrArr = reqStr.split() reqStr = ' '.join(reqStrArr) print(\"reqStr\") print(reqStr) requestBody =", "follows:\\\\n 1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n 2. Date =>15-03-2017\\\\n 3. Amount =>1234.00\\\\n 4. Sending", "= graph.get_operation_by_name(\"input_x\").outputs[0] self.scores = graph.get_operation_by_name(\"output/scores\").outputs[0] # input_y = graph.get_operation_by_name(\"input_y\").outputs[0] self.dropout_keep_prob = graph.get_operation_by_name(\"dropout_keep_prob\").outputs[0] #", "Cop DC Nagar\\\\n\\\\n Regards.\"\"\" else: template = \"\"\" Dear Sir,\\\\n\\\\n The transaction to", "e @csrf_exempt def log(self, request): if request.method == \"POST\": print(\"request\") print(request.body) #Java sends", "graph.get_operation_by_name(\"input_y\").outputs[0] self.dropout_keep_prob = graph.get_operation_by_name(\"dropout_keep_prob\").outputs[0] # Tensors we want to evaluate self.predictions = graph.get_operation_by_name(\"output/predictions\").outputs[0]", "=>1111111111116452\\\\n 6. Remitter Name =>E456946\\\\n 7. Remitter Details =>ABC Cop DC Nagar\\\\n\\\\n Regards.\"\"\"", "Dear Sir,\\\\n\\\\n The status of your outward transaction is as follows:\\\\n 1. UTR", "Beneficiary Name =>E456946\\\\n 7. Beneficiary Details =>ABC Cop DC Nagar\\\\n\\\\n Regards.\"\"\" else: template", "Dear Sir,\\\\n\\\\n The transaction to the account mentioned in the mail trail has", "self.input_x = graph.get_operation_by_name(\"input_x\").outputs[0] self.scores = graph.get_operation_by_name(\"output/scores\").outputs[0] # input_y = graph.get_operation_by_name(\"input_y\").outputs[0] self.dropout_keep_prob = graph.get_operation_by_name(\"dropout_keep_prob\").outputs[0]", "as f: # noOfClasses = EmailClasses.getNoOfClasses() f.write(EmailClasses(_class).name+\"\\n\") except Exception as e: raise e", "import AppConfig import os import numpy as np import json import re from", "as np import json import re from enum import Enum import tensorflow as", "import os import numpy as np import json import re from enum import", "class Sentiment(AppConfig): def __init__(self): print(\"initialising module\") self.checkpoint_dir = \"/home/anson/Desktop/hackathons/crypto/sentiment/runs/1528569664/checkpoints\" self.allow_soft_placement = True self.log_device_placement", "as f: f.write(query+\"\\n\") except Exception as e: raise e try: with open(logFileL,\"a\") as", "UTR No. =>XXXXXxxxxxxxxxxx\\\\n 2. Date =>15-03-2017\\\\n 3. Amount =>1234.00\\\\n 4. Receiving IFSC =>XXXXX0176600\\\\n", "self.dropout_keep_prob: 1.0}) batch_scores = self.sess.run(self.scores, {self.input_x: x_test, self.dropout_keep_prob: 1.0}) # answer = batch_predictions[0]", "= \"\" if utr is None: template = \"No utr found\" else: m", "True self.log_device_placement = False checkpoint_file = tf.train.latest_checkpoint(self.checkpoint_dir) graph = tf.Graph() with graph.as_default(): session_conf", "remitted back to the remitter account as requested.\\\\n The details of the inward", "try: with open(logFile,\"a\") as f: f.write(reqStr+\"\\n\") except Exception as e: raise e return", "logFile= \"server/Log/log.txt\" try: with open(logFile,\"a\") as f: f.write(reqStr+\"\\n\") except Exception as e: raise", "Enum import tensorflow as tf from tensorflow.contrib import learn class EmailClasses(Enum): recall =", "print(requestBody) logFile= \"server/Log/log.txt\" try: with open(logFile,\"a\") as f: f.write(reqStr+\"\\n\") except Exception as e:", "== \"POST\": print(\"request\") print(request.body) print(request.POST) reqStr = str(request.body,'utf-8') reqStrArr = reqStr.split() reqStr =", "=>1234.00\\\\n 4. Receiving IFSC =>XXXXX0176600\\\\n 5. Beneficiary A/c =>1111111111116452\\\\n 6. Beneficiary Name =>E456946\\\\n", "re from enum import Enum import tensorflow as tf from tensorflow.contrib import learn", "scores = (scores*scores)/sum(scores*scores) print(scores) pred = np.argmax(scores) score = scores[0] + scores[1]*-1 else:", "batch_scores = self.sess.run(self.scores, {self.input_x: x_test, self.dropout_keep_prob: 1.0}) # answer = batch_predictions[0] scores =", "reqStr = ' '.join(reqStrArr) print(\"reqStr\") print(reqStr) requestBody = json.loads(reqStr) print(requestBody) logFile= \"server/Log/log.txt\" try:", "of your outward transaction is as follows:\\\\n 1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n 2. Date", "query = requestBody['message'] # Map data into vocabulary vocab_path = os.path.join(self.checkpoint_dir, \"..\", \"vocab\")", "= os.path.join(self.checkpoint_dir, \"..\", \"vocab\") vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path) x_test = np.array(list(vocab_processor.transform([query]))) # batch_predictions =", "django.views.decorators.csrf import csrf_exempt from django.apps import AppConfig import os import numpy as np", "np.array(list(vocab_processor.transform([query]))) # batch_predictions = self.sess.run(self.predictions, {self.input_x: x_test, self.dropout_keep_prob: 1.0}) batch_scores = self.sess.run(self.scores, {self.input_x:", "return HttpResponse(answer) # print(HttpResponse(res,content_type=\"text/plain\",charset=\"utf-8\")) # print(HttpResponse(res)) # print(HttpResponse(res,content_type=\"text/plain\",charset=\"utf-8\").getvalue()) return HttpResponse(score,content_type=\"text/plain\",charset=\"utf-8\") def getTemplate(self,_class, utr):", "batch_scores[0] scores = scores-np.min(scores) print(scores) scores = (scores*scores)/sum(scores*scores) print(scores) pred = np.argmax(scores) score", "2. Date =>15-03-2017\\\\n 3. Amount =>1234.00\\\\n 4. Receiving IFSC =>XXXXX0176600\\\\n 5. Beneficiary A/c", "vocabulary vocab_path = os.path.join(self.checkpoint_dir, \"..\", \"vocab\") vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path) x_test = np.array(list(vocab_processor.transform([query]))) #", "account as requested.\\\\n The details of the inward transaction are as follows:\\\\n 1.", "reqStr = ' '.join(reqStrArr) print(\"reqStr\") print(reqStr) requestBody = json.loads(reqStr) print(requestBody) if requestBody['message'] is", "Sentiment(AppConfig): def __init__(self): print(\"initialising module\") self.checkpoint_dir = \"/home/anson/Desktop/hackathons/crypto/sentiment/runs/1528569664/checkpoints\" self.allow_soft_placement = True self.log_device_placement =", "A/c =>1111111111116452\\\\n 6. Remitter Name =>E456946\\\\n 7. Remitter Details =>ABC Cop DC Nagar\\\\n\\\\n", "# print(HttpResponse(res)) # print(HttpResponse(res,content_type=\"text/plain\",charset=\"utf-8\").getvalue()) return HttpResponse(score,content_type=\"text/plain\",charset=\"utf-8\") def getTemplate(self,_class, utr): template = \"\" if", "scores = batch_scores[0] scores = scores-np.min(scores) print(scores) scores = (scores*scores)/sum(scores*scores) print(scores) pred =", "print(requestBody) if requestBody['message'] is not None: query = requestBody['message'] # Map data into", "f.write(query+\"\\n\") except Exception as e: raise e try: with open(logFileL,\"a\") as f: #", "= \"Unable to classify request\" # return HttpResponse(answer) # print(HttpResponse(res,content_type=\"text/plain\",charset=\"utf-8\")) # print(HttpResponse(res)) #", "6. Beneficiary Name =>E456946\\\\n 7. Beneficiary Details =>ABC Cop DC Nagar\\\\n\\\\n Regards.\"\"\" return", "graph.get_operation_by_name(\"output/scores\").outputs[0] # input_y = graph.get_operation_by_name(\"input_y\").outputs[0] self.dropout_keep_prob = graph.get_operation_by_name(\"dropout_keep_prob\").outputs[0] # Tensors we want to", "sys.argv for x in ['makemigrations', 'migrate']): # HACK: Avoid initialisation while migrate #do", "requestBody = json.loads(reqStr) print(requestBody) if requestBody['message'] is not None: query = requestBody['message'] #", "Sir,\\\\n\\\\n The amount credited to the account xxxxxx mentioned in the mail trail", "else: template = \"\"\" Dear Sir,\\\\n\\\\n The amount credited to the account xxxxxx", "be launched only once) # if not any(x in sys.argv for x in", "= \"\"\" Dear Sir,\\\\n\\\\n The amount credited to the account xxxxxx mentioned in", "return template def saveLog(self, query, _class): logFileQ= \"server/Log/query.txt\" logFileL = \"server/Log/labels.txt\" try: with", "with open(logFileL,\"a\") as f: # noOfClasses = EmailClasses.getNoOfClasses() f.write(EmailClasses(_class).name+\"\\n\") except Exception as e:", "transaction is as follows:\\\\n 1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n 2. Date =>15-03-2017\\\\n 3. Amount", "credited to the account xxxxxx mentioned in the mail trail has been remitted", "try: with open(logFileQ,\"a\") as f: f.write(query+\"\\n\") except Exception as e: raise e try:", "logFileL = \"server/Log/labels.txt\" try: with open(logFileQ,\"a\") as f: f.write(query+\"\\n\") except Exception as e:", "print(request.body) #Java sends string encoded in this format reqStr = str(request.body,'ISO 8859-1') print(\"reqStr", "the saved meta graph and restore variables saver = tf.train.import_meta_graph(\"{}.meta\".format(checkpoint_file)) saver.restore(self.sess, checkpoint_file) #", "classify request\" # return HttpResponse(answer) # print(HttpResponse(res,content_type=\"text/plain\",charset=\"utf-8\")) # print(HttpResponse(res)) # print(HttpResponse(res,content_type=\"text/plain\",charset=\"utf-8\").getvalue()) return HttpResponse(score,content_type=\"text/plain\",charset=\"utf-8\")", "= str(request.body,'ISO 8859-1') print(\"reqStr ISO\") print(reqStr) # reqStr.replace(u'\\xa0', u' ').encode('utf-8') # reqStr =", "status of your outward transaction is as follows:\\\\n 1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n 2.", "migrate #do something print(\"In ready\") @csrf_exempt def getResponse(self, request): if request.method == \"POST\":", "to the remitter account as requested.\\\\n The details of the inward transaction are", "\"server/Log/query.txt\" logFileL = \"server/Log/labels.txt\" try: with open(logFileQ,\"a\") as f: f.write(query+\"\\n\") except Exception as", "Get the placeholders from the graph by name self.input_x = graph.get_operation_by_name(\"input_x\").outputs[0] self.scores =", "graph = tf.Graph() with graph.as_default(): session_conf = tf.ConfigProto( allow_soft_placement=self.allow_soft_placement, log_device_placement=self.log_device_placement) self.sess = tf.Session(config=session_conf)", "= \"/home/anson/Desktop/hackathons/crypto/sentiment/runs/1528569664/checkpoints\" self.allow_soft_placement = True self.log_device_placement = False checkpoint_file = tf.train.latest_checkpoint(self.checkpoint_dir) graph =", "3. Amount =>1234.00\\\\n 4. Receiving IFSC =>XXXXX0176600\\\\n 5. Beneficiary A/c =>1111111111116452\\\\n 6. Beneficiary", "else: template = \"\"\" Dear Sir,\\\\n\\\\n The transaction to the account mentioned in", "trail has been remitted back to the remitter account as requested.\\\\n The details", "Date =>15-03-2017\\\\n 3. Amount =>1234.00\\\\n 4. Receiving IFSC =>XXXXX0176600\\\\n 5. Beneficiary A/c =>1111111111116452\\\\n", "enum import Enum import tensorflow as tf from tensorflow.contrib import learn class EmailClasses(Enum):", "\"POST\": print(\"request\") print(request.body) #Java sends string encoded in this format reqStr = str(request.body,'ISO", "try: with open(logFileL,\"a\") as f: # noOfClasses = EmailClasses.getNoOfClasses() f.write(EmailClasses(_class).name+\"\\n\") except Exception as", "1.0}) batch_scores = self.sess.run(self.scores, {self.input_x: x_test, self.dropout_keep_prob: 1.0}) # answer = batch_predictions[0] scores", "template = \"\" if utr is None: template = \"No utr found\" else:", "The status of your outward transaction is as follows:\\\\n 1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n", "ready(self): \"\"\" Called by Django only once during startup \"\"\" # Initialize the", "HACK: Avoid initialisation while migrate #do something print(\"In ready\") @csrf_exempt def getResponse(self, request):", "Amount =>1234.00\\\\n 4. Receiving IFSC =>XXXXX0176600\\\\n 5. Beneficiary A/c =>1111111111116452\\\\n 6. Beneficiary Name", "5. Beneficiary A/c =>1111111111116452\\\\n 6. Beneficiary Name =>E456946\\\\n 7. Beneficiary Details =>ABC Cop", "launched only once) # if not any(x in sys.argv for x in ['makemigrations',", "else: score = 0 res = \"Unable to classify request\" # return HttpResponse(answer)", "import csrf_exempt from django.apps import AppConfig import os import numpy as np import", "x_test, self.dropout_keep_prob: 1.0}) # answer = batch_predictions[0] scores = batch_scores[0] scores = scores-np.min(scores)", "7. Remitter Details =>ABC Cop DC Nagar\\\\n\\\\n Regards.\"\"\" else: if _class == 1:", "@csrf_exempt def log(self, request): if request.method == \"POST\": print(\"request\") print(request.body) #Java sends string", "is not None: query = requestBody['message'] # Map data into vocabulary vocab_path =", "something print(\"In ready\") @csrf_exempt def getResponse(self, request): if request.method == \"POST\": print(\"request\") print(request.body)", "f.write(EmailClasses(_class).name+\"\\n\") except Exception as e: raise e @csrf_exempt def log(self, request): if request.method", "getTemplate(self,_class, utr): template = \"\" if utr is None: template = \"No utr", "in sys.argv for x in ['makemigrations', 'migrate']): # HACK: Avoid initialisation while migrate", "encoded in this format reqStr = str(request.body,'ISO 8859-1') print(\"reqStr ISO\") print(reqStr) # reqStr.replace(u'\\xa0',", "# if not any(x in sys.argv for x in ['makemigrations', 'migrate']): # HACK:", "1 def getNoOfClasses(): return len(list(EmailClasses)) print(EmailClasses(0)) class Sentiment(AppConfig): def __init__(self): print(\"initialising module\") self.checkpoint_dir", "3. Amount =>1234.00\\\\n 4. Sending IFSC =>XXXXX0176600\\\\n 5. Remitter A/c =>1111111111116452\\\\n 6. Remitter", "f: f.write(query+\"\\n\") except Exception as e: raise e try: with open(logFileL,\"a\") as f:", "if requestBody['message'] is not None: query = requestBody['message'] # Map data into vocabulary", "as e: raise e @csrf_exempt def log(self, request): if request.method == \"POST\": print(\"request\")", "Map data into vocabulary vocab_path = os.path.join(self.checkpoint_dir, \"..\", \"vocab\") vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path) x_test", "of the outward transaction are as follows:\\\\n 1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n 2. Date", "class EmailClasses(Enum): recall = 0 status = 1 def getNoOfClasses(): return len(list(EmailClasses)) print(EmailClasses(0))", "False checkpoint_file = tf.train.latest_checkpoint(self.checkpoint_dir) graph = tf.Graph() with graph.as_default(): session_conf = tf.ConfigProto( allow_soft_placement=self.allow_soft_placement,", "batch_predictions[0] scores = batch_scores[0] scores = scores-np.min(scores) print(scores) scores = (scores*scores)/sum(scores*scores) print(scores) pred", "print(\"reqStr\") print(reqStr) requestBody = json.loads(reqStr) print(requestBody) if requestBody['message'] is not None: query =", "res = \"Unable to classify request\" # return HttpResponse(answer) # print(HttpResponse(res,content_type=\"text/plain\",charset=\"utf-8\")) # print(HttpResponse(res))", "except Exception as e: raise e try: with open(logFileL,\"a\") as f: # noOfClasses", "\"\"\" Dear Sir,\\\\n\\\\n The amount credited to the account xxxxxx mentioned in the", "request): if request.method == \"POST\": print(\"request\") print(request.body) #Java sends string encoded in this", "status = 1 def getNoOfClasses(): return len(list(EmailClasses)) print(EmailClasses(0)) class Sentiment(AppConfig): def __init__(self): print(\"initialising", "x in ['makemigrations', 'migrate']): # HACK: Avoid initialisation while migrate #do something print(\"In", "learn class EmailClasses(Enum): recall = 0 status = 1 def getNoOfClasses(): return len(list(EmailClasses))", "= \"\"\" Dear Sir,\\\\n\\\\n The status of your inward transaction is as follows:\\\\n", "variables saver = tf.train.import_meta_graph(\"{}.meta\".format(checkpoint_file)) saver.restore(self.sess, checkpoint_file) # Get the placeholders from the graph", "HttpResponse(score,content_type=\"text/plain\",charset=\"utf-8\") def getTemplate(self,_class, utr): template = \"\" if utr is None: template =", "=>ABC Cop DC Nagar\\\\n\\\\n Regards.\"\"\" return template def saveLog(self, query, _class): logFileQ= \"server/Log/query.txt\"", "Regards.\"\"\" return template def saveLog(self, query, _class): logFileQ= \"server/Log/query.txt\" logFileL = \"server/Log/labels.txt\" try:", "{self.input_x: x_test, self.dropout_keep_prob: 1.0}) batch_scores = self.sess.run(self.scores, {self.input_x: x_test, self.dropout_keep_prob: 1.0}) # answer", "Details =>ABC Cop DC Nagar\\\\n\\\\n Regards.\"\"\" else: template = \"\"\" Dear Sir,\\\\n\\\\n The", "been recalled.\\\\n The details of the outward transaction are as follows:\\\\n 1. UTR", "= tf.train.import_meta_graph(\"{}.meta\".format(checkpoint_file)) saver.restore(self.sess, checkpoint_file) # Get the placeholders from the graph by name", "AppConfig import os import numpy as np import json import re from enum", "session_conf = tf.ConfigProto( allow_soft_placement=self.allow_soft_placement, log_device_placement=self.log_device_placement) self.sess = tf.Session(config=session_conf) with self.sess.as_default(): # Load the", "def getNoOfClasses(): return len(list(EmailClasses)) print(EmailClasses(0)) class Sentiment(AppConfig): def __init__(self): print(\"initialising module\") self.checkpoint_dir =", "the outward transaction are as follows:\\\\n 1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n 2. Date =>15-03-2017\\\\n", "not None: query = requestBody['message'] # Map data into vocabulary vocab_path = os.path.join(self.checkpoint_dir,", "scores = scores-np.min(scores) print(scores) scores = (scores*scores)/sum(scores*scores) print(scores) pred = np.argmax(scores) score =", "ready\") @csrf_exempt def getResponse(self, request): if request.method == \"POST\": print(\"request\") print(request.body) print(request.POST) reqStr", "found\" else: m = re.match(r'SBI', str(utr)) print(\"utr\") print(utr) print(\"m\") print(m) if m is", "The amount credited to the account xxxxxx mentioned in the mail trail has", "# answer = batch_predictions[0] scores = batch_scores[0] scores = scores-np.min(scores) print(scores) scores =", "saved meta graph and restore variables saver = tf.train.import_meta_graph(\"{}.meta\".format(checkpoint_file)) saver.restore(self.sess, checkpoint_file) # Get", "batch_predictions = self.sess.run(self.predictions, {self.input_x: x_test, self.dropout_keep_prob: 1.0}) batch_scores = self.sess.run(self.scores, {self.input_x: x_test, self.dropout_keep_prob:", "Details =>ABC Cop DC Nagar\\\\n\\\\n Regards.\"\"\" else: if _class == 1: template =", "logFileQ= \"server/Log/query.txt\" logFileL = \"server/Log/labels.txt\" try: with open(logFileQ,\"a\") as f: f.write(query+\"\\n\") except Exception", "# Map data into vocabulary vocab_path = os.path.join(self.checkpoint_dir, \"..\", \"vocab\") vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path)", "2. Date =>15-03-2017\\\\n 3. Amount =>1234.00\\\\n 4. Sending IFSC =>XXXXX0176600\\\\n 5. Remitter A/c", "follows:\\\\n 1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n 2. Date =>15-03-2017\\\\n 3. Amount =>1234.00\\\\n 4. Receiving", "pred = np.argmax(scores) score = scores[0] + scores[1]*-1 else: score = 0 res", "if utr is None: template = \"No utr found\" else: m = re.match(r'SBI',", "string encoded in this format reqStr = str(request.body,'ISO 8859-1') print(\"reqStr ISO\") print(reqStr) #", "'migrate']): # HACK: Avoid initialisation while migrate #do something print(\"In ready\") @csrf_exempt def", "=>E456946\\\\n 7. Remitter Details =>ABC Cop DC Nagar\\\\n\\\\n\\\\n Regards.\"\"\" else: template = \"\"\"", "the placeholders from the graph by name self.input_x = graph.get_operation_by_name(\"input_x\").outputs[0] self.scores = graph.get_operation_by_name(\"output/scores\").outputs[0]", "to the account xxxxxx mentioned in the mail trail has been remitted back", "{self.input_x: x_test, self.dropout_keep_prob: 1.0}) # answer = batch_predictions[0] scores = batch_scores[0] scores =", "by Django only once during startup \"\"\" # Initialize the auto reply model(should", "# Initialize the auto reply model(should be launched only once) # if not", "len(list(EmailClasses)) print(EmailClasses(0)) class Sentiment(AppConfig): def __init__(self): print(\"initialising module\") self.checkpoint_dir = \"/home/anson/Desktop/hackathons/crypto/sentiment/runs/1528569664/checkpoints\" self.allow_soft_placement =", "amount credited to the account xxxxxx mentioned in the mail trail has been", "raise e @csrf_exempt def log(self, request): if request.method == \"POST\": print(\"request\") print(request.body) #Java", "\"/home/anson/Desktop/hackathons/crypto/sentiment/runs/1528569664/checkpoints\" self.allow_soft_placement = True self.log_device_placement = False checkpoint_file = tf.train.latest_checkpoint(self.checkpoint_dir) graph = tf.Graph()", "+ scores[1]*-1 else: score = 0 res = \"Unable to classify request\" #", "recall = 0 status = 1 def getNoOfClasses(): return len(list(EmailClasses)) print(EmailClasses(0)) class Sentiment(AppConfig):", "Remitter Details =>ABC Cop DC Nagar\\\\n\\\\n Regards.\"\"\" else: if _class == 1: template", "csrf_exempt from django.apps import AppConfig import os import numpy as np import json", "__init__(self): print(\"initialising module\") self.checkpoint_dir = \"/home/anson/Desktop/hackathons/crypto/sentiment/runs/1528569664/checkpoints\" self.allow_soft_placement = True self.log_device_placement = False checkpoint_file", "\"POST\": print(\"request\") print(request.body) print(request.POST) reqStr = str(request.body,'utf-8') reqStrArr = reqStr.split() reqStr = '", "= True self.log_device_placement = False checkpoint_file = tf.train.latest_checkpoint(self.checkpoint_dir) graph = tf.Graph() with graph.as_default():", "=>1111111111116452\\\\n 6. Beneficiary Name =>E456946\\\\n 7. Beneficiary Details =>ABC Cop DC Nagar\\\\n\\\\n Regards.\"\"\"", "= tf.Session(config=session_conf) with self.sess.as_default(): # Load the saved meta graph and restore variables", "json import re from enum import Enum import tensorflow as tf from tensorflow.contrib", "= EmailClasses.getNoOfClasses() f.write(EmailClasses(_class).name+\"\\n\") except Exception as e: raise e @csrf_exempt def log(self, request):", "import re from enum import Enum import tensorflow as tf from tensorflow.contrib import", "meta graph and restore variables saver = tf.train.import_meta_graph(\"{}.meta\".format(checkpoint_file)) saver.restore(self.sess, checkpoint_file) # Get the", "7. Beneficiary Details =>ABC Cop DC Nagar\\\\n\\\\n Regards.\"\"\" else: template = \"\"\" Dear", "from django.views.decorators.csrf import csrf_exempt from django.apps import AppConfig import os import numpy as", "Dear Sir,\\\\n\\\\n The amount credited to the account xxxxxx mentioned in the mail", "outward transaction is as follows:\\\\n 1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n 2. Date =>15-03-2017\\\\n 3.", "graph.get_operation_by_name(\"dropout_keep_prob\").outputs[0] # Tensors we want to evaluate self.predictions = graph.get_operation_by_name(\"output/predictions\").outputs[0] def ready(self): \"\"\"", "print(\"request\") print(request.body) print(request.POST) reqStr = str(request.body,'utf-8') reqStrArr = reqStr.split() reqStr = ' '.join(reqStrArr)", "we want to evaluate self.predictions = graph.get_operation_by_name(\"output/predictions\").outputs[0] def ready(self): \"\"\" Called by Django", "1.0}) # answer = batch_predictions[0] scores = batch_scores[0] scores = scores-np.min(scores) print(scores) scores", "restore variables saver = tf.train.import_meta_graph(\"{}.meta\".format(checkpoint_file)) saver.restore(self.sess, checkpoint_file) # Get the placeholders from the", "checkpoint_file) # Get the placeholders from the graph by name self.input_x = graph.get_operation_by_name(\"input_x\").outputs[0]", "@csrf_exempt def getResponse(self, request): if request.method == \"POST\": print(\"request\") print(request.body) print(request.POST) reqStr =", "= self.sess.run(self.predictions, {self.input_x: x_test, self.dropout_keep_prob: 1.0}) batch_scores = self.sess.run(self.scores, {self.input_x: x_test, self.dropout_keep_prob: 1.0})", "inward transaction are as follows:\\\\n 1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n 2. Date =>15-03-2017\\\\n 3.", "Remitter Details =>ABC Cop DC Nagar\\\\n\\\\n\\\\n Regards.\"\"\" else: template = \"\"\" Dear Sir,\\\\n\\\\n", "= \"\"\" Dear Sir,\\\\n\\\\n The status of your outward transaction is as follows:\\\\n", "#Java sends string encoded in this format reqStr = str(request.body,'ISO 8859-1') print(\"reqStr ISO\")", "reqStr.split() reqStr = ' '.join(reqStrArr) print(\"reqStr\") print(reqStr) requestBody = json.loads(reqStr) print(requestBody) logFile= \"server/Log/log.txt\"", "vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path) x_test = np.array(list(vocab_processor.transform([query]))) # batch_predictions = self.sess.run(self.predictions, {self.input_x: x_test, self.dropout_keep_prob:", "= 1 def getNoOfClasses(): return len(list(EmailClasses)) print(EmailClasses(0)) class Sentiment(AppConfig): def __init__(self): print(\"initialising module\")", "= False checkpoint_file = tf.train.latest_checkpoint(self.checkpoint_dir) graph = tf.Graph() with graph.as_default(): session_conf = tf.ConfigProto(", "score = 0 res = \"Unable to classify request\" # return HttpResponse(answer) #", "= reqStr.split() reqStr = ' '.join(reqStrArr) print(\"reqStr\") print(reqStr) requestBody = json.loads(reqStr) print(requestBody) if", "else: if _class == 1: template = \"\"\" Dear Sir,\\\\n\\\\n The status of", "Remitter Name =>E456946\\\\n 7. Remitter Details =>ABC Cop DC Nagar\\\\n\\\\n\\\\n Regards.\"\"\" else: template", "scores[1]*-1 else: score = 0 res = \"Unable to classify request\" # return", "xxxxxx mentioned in the mail trail has been remitted back to the remitter", "been remitted back to the remitter account as requested.\\\\n The details of the", "\"\"\" Called by Django only once during startup \"\"\" # Initialize the auto", "= tf.Graph() with graph.as_default(): session_conf = tf.ConfigProto( allow_soft_placement=self.allow_soft_placement, log_device_placement=self.log_device_placement) self.sess = tf.Session(config=session_conf) with", "= graph.get_operation_by_name(\"output/predictions\").outputs[0] def ready(self): \"\"\" Called by Django only once during startup \"\"\"", "print(m) if m is None: if _class == 1: template = \"\"\" Dear", "not any(x in sys.argv for x in ['makemigrations', 'migrate']): # HACK: Avoid initialisation", "tensorflow.contrib import learn class EmailClasses(Enum): recall = 0 status = 1 def getNoOfClasses():", "7. Beneficiary Details =>ABC Cop DC Nagar\\\\n\\\\n Regards.\"\"\" return template def saveLog(self, query,", "as e: raise e try: with open(logFileL,\"a\") as f: # noOfClasses = EmailClasses.getNoOfClasses()", "if request.method == \"POST\": print(\"request\") print(request.body) print(request.POST) reqStr = str(request.body,'utf-8') reqStrArr = reqStr.split()", "DC Nagar\\\\n\\\\n\\\\n Regards.\"\"\" else: template = \"\"\" Dear Sir,\\\\n\\\\n The amount credited to", "Cop DC Nagar\\\\n\\\\n\\\\n Regards.\"\"\" else: template = \"\"\" Dear Sir,\\\\n\\\\n The amount credited", "DC Nagar\\\\n\\\\n Regards.\"\"\" else: template = \"\"\" Dear Sir,\\\\n\\\\n The transaction to the", "Initialize the auto reply model(should be launched only once) # if not any(x", "log(self, request): if request.method == \"POST\": print(\"request\") print(request.body) #Java sends string encoded in", "status of your inward transaction is as follows:\\\\n 1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n 2.", "= batch_scores[0] scores = scores-np.min(scores) print(scores) scores = (scores*scores)/sum(scores*scores) print(scores) pred = np.argmax(scores)", "the account xxxxxx mentioned in the mail trail has been remitted back to", "# Load the saved meta graph and restore variables saver = tf.train.import_meta_graph(\"{}.meta\".format(checkpoint_file)) saver.restore(self.sess,", "getResponse(self, request): if request.method == \"POST\": print(\"request\") print(request.body) print(request.POST) reqStr = str(request.body,'utf-8') reqStrArr", "Avoid initialisation while migrate #do something print(\"In ready\") @csrf_exempt def getResponse(self, request): if", "from the graph by name self.input_x = graph.get_operation_by_name(\"input_x\").outputs[0] self.scores = graph.get_operation_by_name(\"output/scores\").outputs[0] # input_y", "back to the remitter account as requested.\\\\n The details of the inward transaction", "template = \"\"\" Dear Sir,\\\\n\\\\n The status of your inward transaction is as", "the mail trail has been recalled.\\\\n The details of the outward transaction are", "os import numpy as np import json import re from enum import Enum", "=>15-03-2017\\\\n 3. Amount =>1234.00\\\\n 4. Sending IFSC =>XXXXX0176600\\\\n 5. Remitter A/c =>1111111111116452\\\\n 6.", "with self.sess.as_default(): # Load the saved meta graph and restore variables saver =", "answer = batch_predictions[0] scores = batch_scores[0] scores = scores-np.min(scores) print(scores) scores = (scores*scores)/sum(scores*scores)", "None: template = \"No utr found\" else: m = re.match(r'SBI', str(utr)) print(\"utr\") print(utr)", "<gh_stars>1-10 from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.csrf import csrf_protect", "Name =>E456946\\\\n 7. Beneficiary Details =>ABC Cop DC Nagar\\\\n\\\\n Regards.\"\"\" return template def", "self.dropout_keep_prob = graph.get_operation_by_name(\"dropout_keep_prob\").outputs[0] # Tensors we want to evaluate self.predictions = graph.get_operation_by_name(\"output/predictions\").outputs[0] def", "m = re.match(r'SBI', str(utr)) print(\"utr\") print(utr) print(\"m\") print(m) if m is None: if", "as follows:\\\\n 1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n 2. Date =>15-03-2017\\\\n 3. Amount =>1234.00\\\\n 4.", "from django.http import HttpResponse from django.views.decorators.csrf import csrf_protect from django.views.decorators.csrf import csrf_exempt from", "=>E456946\\\\n 7. Beneficiary Details =>ABC Cop DC Nagar\\\\n\\\\n Regards.\"\"\" return template def saveLog(self,", "def __init__(self): print(\"initialising module\") self.checkpoint_dir = \"/home/anson/Desktop/hackathons/crypto/sentiment/runs/1528569664/checkpoints\" self.allow_soft_placement = True self.log_device_placement = False", "trail has been recalled.\\\\n The details of the outward transaction are as follows:\\\\n", "reqStr.split() reqStr = ' '.join(reqStrArr) print(\"reqStr\") print(reqStr) requestBody = json.loads(reqStr) print(requestBody) if requestBody['message']", "has been recalled.\\\\n The details of the outward transaction are as follows:\\\\n 1.", "\"vocab\") vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path) x_test = np.array(list(vocab_processor.transform([query]))) # batch_predictions = self.sess.run(self.predictions, {self.input_x: x_test,", "as requested.\\\\n The details of the inward transaction are as follows:\\\\n 1. UTR", "Dear Sir,\\\\n\\\\n The status of your inward transaction is as follows:\\\\n 1. UTR", "=>E456946\\\\n 7. Beneficiary Details =>ABC Cop DC Nagar\\\\n\\\\n Regards.\"\"\" else: template = \"\"\"", "noOfClasses = EmailClasses.getNoOfClasses() f.write(EmailClasses(_class).name+\"\\n\") except Exception as e: raise e @csrf_exempt def log(self,", "to classify request\" # return HttpResponse(answer) # print(HttpResponse(res,content_type=\"text/plain\",charset=\"utf-8\")) # print(HttpResponse(res)) # print(HttpResponse(res,content_type=\"text/plain\",charset=\"utf-8\").getvalue()) return", "remitter account as requested.\\\\n The details of the inward transaction are as follows:\\\\n", "request\" # return HttpResponse(answer) # print(HttpResponse(res,content_type=\"text/plain\",charset=\"utf-8\")) # print(HttpResponse(res)) # print(HttpResponse(res,content_type=\"text/plain\",charset=\"utf-8\").getvalue()) return HttpResponse(score,content_type=\"text/plain\",charset=\"utf-8\") def", "graph.get_operation_by_name(\"output/predictions\").outputs[0] def ready(self): \"\"\" Called by Django only once during startup \"\"\" #", "IFSC =>XXXXX0176600\\\\n 5. Beneficiary A/c =>1111111111116452\\\\n 6. Beneficiary Name =>E456946\\\\n 7. Beneficiary Details", "django.views.decorators.csrf import csrf_protect from django.views.decorators.csrf import csrf_exempt from django.apps import AppConfig import os", "account xxxxxx mentioned in the mail trail has been remitted back to the", "None: if _class == 1: template = \"\"\" Dear Sir,\\\\n\\\\n The status of", "with open(logFile,\"a\") as f: f.write(reqStr+\"\\n\") except Exception as e: raise e return HttpResponse(\"Success\")", "transaction to the account mentioned in the mail trail has been recalled.\\\\n The", "has been remitted back to the remitter account as requested.\\\\n The details of", "print(\"request\") print(request.body) #Java sends string encoded in this format reqStr = str(request.body,'ISO 8859-1')", "Django only once during startup \"\"\" # Initialize the auto reply model(should be", "score = scores[0] + scores[1]*-1 else: score = 0 res = \"Unable to", "8859-1') print(\"reqStr ISO\") print(reqStr) # reqStr.replace(u'\\xa0', u' ').encode('utf-8') # reqStr = str(request.body,'utf-8') reqStrArr", "# print(HttpResponse(res,content_type=\"text/plain\",charset=\"utf-8\")) # print(HttpResponse(res)) # print(HttpResponse(res,content_type=\"text/plain\",charset=\"utf-8\").getvalue()) return HttpResponse(score,content_type=\"text/plain\",charset=\"utf-8\") def getTemplate(self,_class, utr): template =", "os.path.join(self.checkpoint_dir, \"..\", \"vocab\") vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path) x_test = np.array(list(vocab_processor.transform([query]))) # batch_predictions = self.sess.run(self.predictions,", "inward transaction is as follows:\\\\n 1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n 2. Date =>15-03-2017\\\\n 3.", "with open(logFileQ,\"a\") as f: f.write(query+\"\\n\") except Exception as e: raise e try: with", "= graph.get_operation_by_name(\"dropout_keep_prob\").outputs[0] # Tensors we want to evaluate self.predictions = graph.get_operation_by_name(\"output/predictions\").outputs[0] def ready(self):", "json.loads(reqStr) print(requestBody) if requestBody['message'] is not None: query = requestBody['message'] # Map data", "requestBody['message'] # Map data into vocabulary vocab_path = os.path.join(self.checkpoint_dir, \"..\", \"vocab\") vocab_processor =", "x_test, self.dropout_keep_prob: 1.0}) batch_scores = self.sess.run(self.scores, {self.input_x: x_test, self.dropout_keep_prob: 1.0}) # answer =", "of the inward transaction are as follows:\\\\n 1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n 2. Date", "Exception as e: raise e try: with open(logFileL,\"a\") as f: # noOfClasses =", "Cop DC Nagar\\\\n\\\\n Regards.\"\"\" else: if _class == 1: template = \"\"\" Dear", "= 0 status = 1 def getNoOfClasses(): return len(list(EmailClasses)) print(EmailClasses(0)) class Sentiment(AppConfig): def", "\"\"\" Dear Sir,\\\\n\\\\n The transaction to the account mentioned in the mail trail", "def log(self, request): if request.method == \"POST\": print(\"request\") print(request.body) #Java sends string encoded", "this format reqStr = str(request.body,'ISO 8859-1') print(\"reqStr ISO\") print(reqStr) # reqStr.replace(u'\\xa0', u' ').encode('utf-8')", "self.dropout_keep_prob: 1.0}) # answer = batch_predictions[0] scores = batch_scores[0] scores = scores-np.min(scores) print(scores)", "tf from tensorflow.contrib import learn class EmailClasses(Enum): recall = 0 status = 1", "print(\"initialising module\") self.checkpoint_dir = \"/home/anson/Desktop/hackathons/crypto/sentiment/runs/1528569664/checkpoints\" self.allow_soft_placement = True self.log_device_placement = False checkpoint_file =", "\"\" if utr is None: template = \"No utr found\" else: m =", "4. Receiving IFSC =>XXXXX0176600\\\\n 5. Beneficiary A/c =>1111111111116452\\\\n 6. Beneficiary Name =>E456946\\\\n 7.", "DC Nagar\\\\n\\\\n Regards.\"\"\" return template def saveLog(self, query, _class): logFileQ= \"server/Log/query.txt\" logFileL =", "Regards.\"\"\" else: template = \"\"\" Dear Sir,\\\\n\\\\n The amount credited to the account", "print(scores) scores = (scores*scores)/sum(scores*scores) print(scores) pred = np.argmax(scores) score = scores[0] + scores[1]*-1", "= scores[0] + scores[1]*-1 else: score = 0 res = \"Unable to classify", "4. Sending IFSC =>XXXXX0176600\\\\n 5. Remitter A/c =>1111111111116452\\\\n 6. Remitter Name =>E456946\\\\n 7.", "The transaction to the account mentioned in the mail trail has been recalled.\\\\n", "mentioned in the mail trail has been remitted back to the remitter account", "0 status = 1 def getNoOfClasses(): return len(list(EmailClasses)) print(EmailClasses(0)) class Sentiment(AppConfig): def __init__(self):", "= ' '.join(reqStrArr) print(\"reqStr\") print(reqStr) requestBody = json.loads(reqStr) print(requestBody) if requestBody['message'] is not", "are as follows:\\\\n 1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n 2. Date =>15-03-2017\\\\n 3. Amount =>1234.00\\\\n", "sends string encoded in this format reqStr = str(request.body,'ISO 8859-1') print(\"reqStr ISO\") print(reqStr)", "_class): logFileQ= \"server/Log/query.txt\" logFileL = \"server/Log/labels.txt\" try: with open(logFileQ,\"a\") as f: f.write(query+\"\\n\") except", "\"..\", \"vocab\") vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path) x_test = np.array(list(vocab_processor.transform([query]))) # batch_predictions = self.sess.run(self.predictions, {self.input_x:", "and restore variables saver = tf.train.import_meta_graph(\"{}.meta\".format(checkpoint_file)) saver.restore(self.sess, checkpoint_file) # Get the placeholders from", "print(request.body) print(request.POST) reqStr = str(request.body,'utf-8') reqStrArr = reqStr.split() reqStr = ' '.join(reqStrArr) print(\"reqStr\")", "placeholders from the graph by name self.input_x = graph.get_operation_by_name(\"input_x\").outputs[0] self.scores = graph.get_operation_by_name(\"output/scores\").outputs[0] #", "print(\"reqStr\") print(reqStr) requestBody = json.loads(reqStr) print(requestBody) logFile= \"server/Log/log.txt\" try: with open(logFile,\"a\") as f:", "Sir,\\\\n\\\\n The status of your inward transaction is as follows:\\\\n 1. UTR No.", "Remitter Name =>E456946\\\\n 7. Remitter Details =>ABC Cop DC Nagar\\\\n\\\\n Regards.\"\"\" else: if", "Name =>E456946\\\\n 7. Remitter Details =>ABC Cop DC Nagar\\\\n\\\\n Regards.\"\"\" else: if _class", "to the account mentioned in the mail trail has been recalled.\\\\n The details", "= \"\"\" Dear Sir,\\\\n\\\\n The transaction to the account mentioned in the mail", "A/c =>1111111111116452\\\\n 6. Beneficiary Name =>E456946\\\\n 7. Beneficiary Details =>ABC Cop DC Nagar\\\\n\\\\n", "learn.preprocessing.VocabularyProcessor.restore(vocab_path) x_test = np.array(list(vocab_processor.transform([query]))) # batch_predictions = self.sess.run(self.predictions, {self.input_x: x_test, self.dropout_keep_prob: 1.0}) batch_scores", "from django.views.decorators.csrf import csrf_protect from django.views.decorators.csrf import csrf_exempt from django.apps import AppConfig import", "only once during startup \"\"\" # Initialize the auto reply model(should be launched", "x_test = np.array(list(vocab_processor.transform([query]))) # batch_predictions = self.sess.run(self.predictions, {self.input_x: x_test, self.dropout_keep_prob: 1.0}) batch_scores =", "any(x in sys.argv for x in ['makemigrations', 'migrate']): # HACK: Avoid initialisation while", "else: m = re.match(r'SBI', str(utr)) print(\"utr\") print(utr) print(\"m\") print(m) if m is None:", "initialisation while migrate #do something print(\"In ready\") @csrf_exempt def getResponse(self, request): if request.method", "1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n 2. Date =>15-03-2017\\\\n 3. Amount =>1234.00\\\\n 4. Receiving IFSC", "# Tensors we want to evaluate self.predictions = graph.get_operation_by_name(\"output/predictions\").outputs[0] def ready(self): \"\"\" Called", "Beneficiary Details =>ABC Cop DC Nagar\\\\n\\\\n Regards.\"\"\" return template def saveLog(self, query, _class):", "requestBody = json.loads(reqStr) print(requestBody) logFile= \"server/Log/log.txt\" try: with open(logFile,\"a\") as f: f.write(reqStr+\"\\n\") except", "is None: if _class == 1: template = \"\"\" Dear Sir,\\\\n\\\\n The status", "account mentioned in the mail trail has been recalled.\\\\n The details of the", "import HttpResponse from django.views.decorators.csrf import csrf_protect from django.views.decorators.csrf import csrf_exempt from django.apps import", "model(should be launched only once) # if not any(x in sys.argv for x", "template = \"\"\" Dear Sir,\\\\n\\\\n The amount credited to the account xxxxxx mentioned", "print(reqStr) requestBody = json.loads(reqStr) print(requestBody) if requestBody['message'] is not None: query = requestBody['message']", "= tf.train.latest_checkpoint(self.checkpoint_dir) graph = tf.Graph() with graph.as_default(): session_conf = tf.ConfigProto( allow_soft_placement=self.allow_soft_placement, log_device_placement=self.log_device_placement) self.sess", "import render from django.http import HttpResponse from django.views.decorators.csrf import csrf_protect from django.views.decorators.csrf import", "HttpResponse(answer) # print(HttpResponse(res,content_type=\"text/plain\",charset=\"utf-8\")) # print(HttpResponse(res)) # print(HttpResponse(res,content_type=\"text/plain\",charset=\"utf-8\").getvalue()) return HttpResponse(score,content_type=\"text/plain\",charset=\"utf-8\") def getTemplate(self,_class, utr): template", "self.scores = graph.get_operation_by_name(\"output/scores\").outputs[0] # input_y = graph.get_operation_by_name(\"input_y\").outputs[0] self.dropout_keep_prob = graph.get_operation_by_name(\"dropout_keep_prob\").outputs[0] # Tensors we", "Cop DC Nagar\\\\n\\\\n Regards.\"\"\" return template def saveLog(self, query, _class): logFileQ= \"server/Log/query.txt\" logFileL", "== 1: template = \"\"\" Dear Sir,\\\\n\\\\n The status of your inward transaction", "if request.method == \"POST\": print(\"request\") print(request.body) #Java sends string encoded in this format", "str(request.body,'ISO 8859-1') print(\"reqStr ISO\") print(reqStr) # reqStr.replace(u'\\xa0', u' ').encode('utf-8') # reqStr = str(request.body,'utf-8')", "= requestBody['message'] # Map data into vocabulary vocab_path = os.path.join(self.checkpoint_dir, \"..\", \"vocab\") vocab_processor", "Beneficiary A/c =>1111111111116452\\\\n 6. Beneficiary Name =>E456946\\\\n 7. Beneficiary Details =>ABC Cop DC", "Name =>E456946\\\\n 7. Remitter Details =>ABC Cop DC Nagar\\\\n\\\\n\\\\n Regards.\"\"\" else: template =", "tf.Graph() with graph.as_default(): session_conf = tf.ConfigProto( allow_soft_placement=self.allow_soft_placement, log_device_placement=self.log_device_placement) self.sess = tf.Session(config=session_conf) with self.sess.as_default():", "reqStr = str(request.body,'utf-8') reqStrArr = reqStr.split() reqStr = ' '.join(reqStrArr) print(\"reqStr\") print(reqStr) requestBody", "scores-np.min(scores) print(scores) scores = (scores*scores)/sum(scores*scores) print(scores) pred = np.argmax(scores) score = scores[0] +", "into vocabulary vocab_path = os.path.join(self.checkpoint_dir, \"..\", \"vocab\") vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path) x_test = np.array(list(vocab_processor.transform([query])))", "getNoOfClasses(): return len(list(EmailClasses)) print(EmailClasses(0)) class Sentiment(AppConfig): def __init__(self): print(\"initialising module\") self.checkpoint_dir = \"/home/anson/Desktop/hackathons/crypto/sentiment/runs/1528569664/checkpoints\"", "print(HttpResponse(res,content_type=\"text/plain\",charset=\"utf-8\")) # print(HttpResponse(res)) # print(HttpResponse(res,content_type=\"text/plain\",charset=\"utf-8\").getvalue()) return HttpResponse(score,content_type=\"text/plain\",charset=\"utf-8\") def getTemplate(self,_class, utr): template = \"\"", "Sir,\\\\n\\\\n The status of your outward transaction is as follows:\\\\n 1. UTR No.", "= 0 res = \"Unable to classify request\" # return HttpResponse(answer) # print(HttpResponse(res,content_type=\"text/plain\",charset=\"utf-8\"))", "utr): template = \"\" if utr is None: template = \"No utr found\"", "raise e try: with open(logFileL,\"a\") as f: # noOfClasses = EmailClasses.getNoOfClasses() f.write(EmailClasses(_class).name+\"\\n\") except", "1: template = \"\"\" Dear Sir,\\\\n\\\\n The status of your inward transaction is", "from django.apps import AppConfig import os import numpy as np import json import", "self.log_device_placement = False checkpoint_file = tf.train.latest_checkpoint(self.checkpoint_dir) graph = tf.Graph() with graph.as_default(): session_conf =", "# noOfClasses = EmailClasses.getNoOfClasses() f.write(EmailClasses(_class).name+\"\\n\") except Exception as e: raise e @csrf_exempt def", "\"\"\" Dear Sir,\\\\n\\\\n The status of your outward transaction is as follows:\\\\n 1.", "numpy as np import json import re from enum import Enum import tensorflow", "=>ABC Cop DC Nagar\\\\n\\\\n Regards.\"\"\" else: if _class == 1: template = \"\"\"", "log_device_placement=self.log_device_placement) self.sess = tf.Session(config=session_conf) with self.sess.as_default(): # Load the saved meta graph and", "== 1: template = \"\"\" Dear Sir,\\\\n\\\\n The status of your outward transaction", "json.loads(reqStr) print(requestBody) logFile= \"server/Log/log.txt\" try: with open(logFile,\"a\") as f: f.write(reqStr+\"\\n\") except Exception as", "if m is None: if _class == 1: template = \"\"\" Dear Sir,\\\\n\\\\n", "for x in ['makemigrations', 'migrate']): # HACK: Avoid initialisation while migrate #do something", "Nagar\\\\n\\\\n\\\\n Regards.\"\"\" else: template = \"\"\" Dear Sir,\\\\n\\\\n The amount credited to the", "django.http import HttpResponse from django.views.decorators.csrf import csrf_protect from django.views.decorators.csrf import csrf_exempt from django.apps", "=>XXXXXxxxxxxxxxxx\\\\n 2. Date =>15-03-2017\\\\n 3. Amount =>1234.00\\\\n 4. Receiving IFSC =>XXXXX0176600\\\\n 5. Beneficiary", "print(\"In ready\") @csrf_exempt def getResponse(self, request): if request.method == \"POST\": print(\"request\") print(request.body) print(request.POST)", "reqStrArr = reqStr.split() reqStr = ' '.join(reqStrArr) print(\"reqStr\") print(reqStr) requestBody = json.loads(reqStr) print(requestBody)", "u' ').encode('utf-8') # reqStr = str(request.body,'utf-8') reqStrArr = reqStr.split() reqStr = ' '.join(reqStrArr)", "=>E456946\\\\n 7. Remitter Details =>ABC Cop DC Nagar\\\\n\\\\n Regards.\"\"\" else: if _class ==", "reply model(should be launched only once) # if not any(x in sys.argv for", "=>XXXXX0176600\\\\n 5. Beneficiary A/c =>1111111111116452\\\\n 6. Beneficiary Name =>E456946\\\\n 7. Beneficiary Details =>ABC", "ISO\") print(reqStr) # reqStr.replace(u'\\xa0', u' ').encode('utf-8') # reqStr = str(request.body,'utf-8') reqStrArr = reqStr.split()", "while migrate #do something print(\"In ready\") @csrf_exempt def getResponse(self, request): if request.method ==", "\"server/Log/labels.txt\" try: with open(logFileQ,\"a\") as f: f.write(query+\"\\n\") except Exception as e: raise e", "import Enum import tensorflow as tf from tensorflow.contrib import learn class EmailClasses(Enum): recall", "module\") self.checkpoint_dir = \"/home/anson/Desktop/hackathons/crypto/sentiment/runs/1528569664/checkpoints\" self.allow_soft_placement = True self.log_device_placement = False checkpoint_file = tf.train.latest_checkpoint(self.checkpoint_dir)", "= re.match(r'SBI', str(utr)) print(\"utr\") print(utr) print(\"m\") print(m) if m is None: if _class", "saveLog(self, query, _class): logFileQ= \"server/Log/query.txt\" logFileL = \"server/Log/labels.txt\" try: with open(logFileQ,\"a\") as f:", "utr found\" else: m = re.match(r'SBI', str(utr)) print(\"utr\") print(utr) print(\"m\") print(m) if m", "graph and restore variables saver = tf.train.import_meta_graph(\"{}.meta\".format(checkpoint_file)) saver.restore(self.sess, checkpoint_file) # Get the placeholders", "Nagar\\\\n\\\\n Regards.\"\"\" else: if _class == 1: template = \"\"\" Dear Sir,\\\\n\\\\n The", "mentioned in the mail trail has been recalled.\\\\n The details of the outward", "= json.loads(reqStr) print(requestBody) logFile= \"server/Log/log.txt\" try: with open(logFile,\"a\") as f: f.write(reqStr+\"\\n\") except Exception", "= json.loads(reqStr) print(requestBody) if requestBody['message'] is not None: query = requestBody['message'] # Map", "request): if request.method == \"POST\": print(\"request\") print(request.body) print(request.POST) reqStr = str(request.body,'utf-8') reqStrArr =", "open(logFileL,\"a\") as f: # noOfClasses = EmailClasses.getNoOfClasses() f.write(EmailClasses(_class).name+\"\\n\") except Exception as e: raise", "graph.as_default(): session_conf = tf.ConfigProto( allow_soft_placement=self.allow_soft_placement, log_device_placement=self.log_device_placement) self.sess = tf.Session(config=session_conf) with self.sess.as_default(): # Load", "request.method == \"POST\": print(\"request\") print(request.body) print(request.POST) reqStr = str(request.body,'utf-8') reqStrArr = reqStr.split() reqStr", "print(EmailClasses(0)) class Sentiment(AppConfig): def __init__(self): print(\"initialising module\") self.checkpoint_dir = \"/home/anson/Desktop/hackathons/crypto/sentiment/runs/1528569664/checkpoints\" self.allow_soft_placement = True", "\"server/Log/log.txt\" try: with open(logFile,\"a\") as f: f.write(reqStr+\"\\n\") except Exception as e: raise e", "np import json import re from enum import Enum import tensorflow as tf", "UTR No. =>XXXXXxxxxxxxxxxx\\\\n 2. Date =>15-03-2017\\\\n 3. Amount =>1234.00\\\\n 4. Sending IFSC =>XXXXX0176600\\\\n", "def getResponse(self, request): if request.method == \"POST\": print(\"request\") print(request.body) print(request.POST) reqStr = str(request.body,'utf-8')", "except Exception as e: raise e @csrf_exempt def log(self, request): if request.method ==", "' '.join(reqStrArr) print(\"reqStr\") print(reqStr) requestBody = json.loads(reqStr) print(requestBody) logFile= \"server/Log/log.txt\" try: with open(logFile,\"a\")", "# input_y = graph.get_operation_by_name(\"input_y\").outputs[0] self.dropout_keep_prob = graph.get_operation_by_name(\"dropout_keep_prob\").outputs[0] # Tensors we want to evaluate", "# print(HttpResponse(res,content_type=\"text/plain\",charset=\"utf-8\").getvalue()) return HttpResponse(score,content_type=\"text/plain\",charset=\"utf-8\") def getTemplate(self,_class, utr): template = \"\" if utr is", "details of the outward transaction are as follows:\\\\n 1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n 2.", "0 res = \"Unable to classify request\" # return HttpResponse(answer) # print(HttpResponse(res,content_type=\"text/plain\",charset=\"utf-8\")) #", "import learn class EmailClasses(Enum): recall = 0 status = 1 def getNoOfClasses(): return", "str(request.body,'utf-8') reqStrArr = reqStr.split() reqStr = ' '.join(reqStrArr) print(\"reqStr\") print(reqStr) requestBody = json.loads(reqStr)", "' '.join(reqStrArr) print(\"reqStr\") print(reqStr) requestBody = json.loads(reqStr) print(requestBody) if requestBody['message'] is not None:", "allow_soft_placement=self.allow_soft_placement, log_device_placement=self.log_device_placement) self.sess = tf.Session(config=session_conf) with self.sess.as_default(): # Load the saved meta graph", "print(request.POST) reqStr = str(request.body,'utf-8') reqStrArr = reqStr.split() reqStr = ' '.join(reqStrArr) print(\"reqStr\") print(reqStr)", "\"\"\" Dear Sir,\\\\n\\\\n The status of your inward transaction is as follows:\\\\n 1.", "=>XXXXX0176600\\\\n 5. Remitter A/c =>1111111111116452\\\\n 6. Remitter Name =>E456946\\\\n 7. Remitter Details =>ABC", "template def saveLog(self, query, _class): logFileQ= \"server/Log/query.txt\" logFileL = \"server/Log/labels.txt\" try: with open(logFileQ,\"a\")", "self.sess.run(self.predictions, {self.input_x: x_test, self.dropout_keep_prob: 1.0}) batch_scores = self.sess.run(self.scores, {self.input_x: x_test, self.dropout_keep_prob: 1.0}) #", "Amount =>1234.00\\\\n 4. Sending IFSC =>XXXXX0176600\\\\n 5. Remitter A/c =>1111111111116452\\\\n 6. Remitter Name", "HttpResponse from django.views.decorators.csrf import csrf_protect from django.views.decorators.csrf import csrf_exempt from django.apps import AppConfig", "# Get the placeholders from the graph by name self.input_x = graph.get_operation_by_name(\"input_x\").outputs[0] self.scores", "reqStr = str(request.body,'ISO 8859-1') print(\"reqStr ISO\") print(reqStr) # reqStr.replace(u'\\xa0', u' ').encode('utf-8') # reqStr", "Nagar\\\\n\\\\n Regards.\"\"\" return template def saveLog(self, query, _class): logFileQ= \"server/Log/query.txt\" logFileL = \"server/Log/labels.txt\"", "Receiving IFSC =>XXXXX0176600\\\\n 5. Beneficiary A/c =>1111111111116452\\\\n 6. Beneficiary Name =>E456946\\\\n 7. Beneficiary", "# reqStr.replace(u'\\xa0', u' ').encode('utf-8') # reqStr = str(request.body,'utf-8') reqStrArr = reqStr.split() reqStr =", "if _class == 1: template = \"\"\" Dear Sir,\\\\n\\\\n The status of your", "print(reqStr) requestBody = json.loads(reqStr) print(requestBody) logFile= \"server/Log/log.txt\" try: with open(logFile,\"a\") as f: f.write(reqStr+\"\\n\")", "Beneficiary Details =>ABC Cop DC Nagar\\\\n\\\\n Regards.\"\"\" else: template = \"\"\" Dear Sir,\\\\n\\\\n", "the graph by name self.input_x = graph.get_operation_by_name(\"input_x\").outputs[0] self.scores = graph.get_operation_by_name(\"output/scores\").outputs[0] # input_y =", "your outward transaction is as follows:\\\\n 1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n 2. Date =>15-03-2017\\\\n", "tf.train.import_meta_graph(\"{}.meta\".format(checkpoint_file)) saver.restore(self.sess, checkpoint_file) # Get the placeholders from the graph by name self.input_x", "checkpoint_file = tf.train.latest_checkpoint(self.checkpoint_dir) graph = tf.Graph() with graph.as_default(): session_conf = tf.ConfigProto( allow_soft_placement=self.allow_soft_placement, log_device_placement=self.log_device_placement)", "Exception as e: raise e @csrf_exempt def log(self, request): if request.method == \"POST\":", "with graph.as_default(): session_conf = tf.ConfigProto( allow_soft_placement=self.allow_soft_placement, log_device_placement=self.log_device_placement) self.sess = tf.Session(config=session_conf) with self.sess.as_default(): #", "import csrf_protect from django.views.decorators.csrf import csrf_exempt from django.apps import AppConfig import os import", "= graph.get_operation_by_name(\"input_y\").outputs[0] self.dropout_keep_prob = graph.get_operation_by_name(\"dropout_keep_prob\").outputs[0] # Tensors we want to evaluate self.predictions =", "= tf.ConfigProto( allow_soft_placement=self.allow_soft_placement, log_device_placement=self.log_device_placement) self.sess = tf.Session(config=session_conf) with self.sess.as_default(): # Load the saved", "import numpy as np import json import re from enum import Enum import", "details of the inward transaction are as follows:\\\\n 1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n 2.", "Called by Django only once during startup \"\"\" # Initialize the auto reply", "print(reqStr) # reqStr.replace(u'\\xa0', u' ').encode('utf-8') # reqStr = str(request.body,'utf-8') reqStrArr = reqStr.split() reqStr", "auto reply model(should be launched only once) # if not any(x in sys.argv", "from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.csrf import csrf_protect from", "= scores-np.min(scores) print(scores) scores = (scores*scores)/sum(scores*scores) print(scores) pred = np.argmax(scores) score = scores[0]", "Regards.\"\"\" else: template = \"\"\" Dear Sir,\\\\n\\\\n The transaction to the account mentioned", "the mail trail has been remitted back to the remitter account as requested.\\\\n", "self.checkpoint_dir = \"/home/anson/Desktop/hackathons/crypto/sentiment/runs/1528569664/checkpoints\" self.allow_soft_placement = True self.log_device_placement = False checkpoint_file = tf.train.latest_checkpoint(self.checkpoint_dir) graph", "outward transaction are as follows:\\\\n 1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n 2. Date =>15-03-2017\\\\n 3.", "as tf from tensorflow.contrib import learn class EmailClasses(Enum): recall = 0 status =", "= np.argmax(scores) score = scores[0] + scores[1]*-1 else: score = 0 res =", "your inward transaction is as follows:\\\\n 1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n 2. Date =>15-03-2017\\\\n", "reqStr.replace(u'\\xa0', u' ').encode('utf-8') # reqStr = str(request.body,'utf-8') reqStrArr = reqStr.split() reqStr = '", "to evaluate self.predictions = graph.get_operation_by_name(\"output/predictions\").outputs[0] def ready(self): \"\"\" Called by Django only once", "self.predictions = graph.get_operation_by_name(\"output/predictions\").outputs[0] def ready(self): \"\"\" Called by Django only once during startup", "input_y = graph.get_operation_by_name(\"input_y\").outputs[0] self.dropout_keep_prob = graph.get_operation_by_name(\"dropout_keep_prob\").outputs[0] # Tensors we want to evaluate self.predictions", "').encode('utf-8') # reqStr = str(request.body,'utf-8') reqStrArr = reqStr.split() reqStr = ' '.join(reqStrArr) print(\"reqStr\")", "django.apps import AppConfig import os import numpy as np import json import re", "def getTemplate(self,_class, utr): template = \"\" if utr is None: template = \"No", "= reqStr.split() reqStr = ' '.join(reqStrArr) print(\"reqStr\") print(reqStr) requestBody = json.loads(reqStr) print(requestBody) logFile=", "=>XXXXXxxxxxxxxxxx\\\\n 2. Date =>15-03-2017\\\\n 3. Amount =>1234.00\\\\n 4. Sending IFSC =>XXXXX0176600\\\\n 5. Remitter", "want to evaluate self.predictions = graph.get_operation_by_name(\"output/predictions\").outputs[0] def ready(self): \"\"\" Called by Django only", "requested.\\\\n The details of the inward transaction are as follows:\\\\n 1. UTR No.", "No. =>XXXXXxxxxxxxxxxx\\\\n 2. Date =>15-03-2017\\\\n 3. Amount =>1234.00\\\\n 4. Receiving IFSC =>XXXXX0176600\\\\n 5.", "saver = tf.train.import_meta_graph(\"{}.meta\".format(checkpoint_file)) saver.restore(self.sess, checkpoint_file) # Get the placeholders from the graph by", "print(\"m\") print(m) if m is None: if _class == 1: template = \"\"\"", "tf.ConfigProto( allow_soft_placement=self.allow_soft_placement, log_device_placement=self.log_device_placement) self.sess = tf.Session(config=session_conf) with self.sess.as_default(): # Load the saved meta", "# return HttpResponse(answer) # print(HttpResponse(res,content_type=\"text/plain\",charset=\"utf-8\")) # print(HttpResponse(res)) # print(HttpResponse(res,content_type=\"text/plain\",charset=\"utf-8\").getvalue()) return HttpResponse(score,content_type=\"text/plain\",charset=\"utf-8\") def getTemplate(self,_class,", "Name =>E456946\\\\n 7. Beneficiary Details =>ABC Cop DC Nagar\\\\n\\\\n Regards.\"\"\" else: template =", "self.sess = tf.Session(config=session_conf) with self.sess.as_default(): # Load the saved meta graph and restore", "IFSC =>XXXXX0176600\\\\n 5. Remitter A/c =>1111111111116452\\\\n 6. Remitter Name =>E456946\\\\n 7. Remitter Details", "Sir,\\\\n\\\\n The transaction to the account mentioned in the mail trail has been", "# HACK: Avoid initialisation while migrate #do something print(\"In ready\") @csrf_exempt def getResponse(self,", "Sending IFSC =>XXXXX0176600\\\\n 5. Remitter A/c =>1111111111116452\\\\n 6. Remitter Name =>E456946\\\\n 7. Remitter", "# batch_predictions = self.sess.run(self.predictions, {self.input_x: x_test, self.dropout_keep_prob: 1.0}) batch_scores = self.sess.run(self.scores, {self.input_x: x_test,", "== \"POST\": print(\"request\") print(request.body) #Java sends string encoded in this format reqStr =", "=>1234.00\\\\n 4. Sending IFSC =>XXXXX0176600\\\\n 5. Remitter A/c =>1111111111116452\\\\n 6. Remitter Name =>E456946\\\\n", "The details of the inward transaction are as follows:\\\\n 1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n", "print(scores) pred = np.argmax(scores) score = scores[0] + scores[1]*-1 else: score = 0", "import tensorflow as tf from tensorflow.contrib import learn class EmailClasses(Enum): recall = 0", "utr is None: template = \"No utr found\" else: m = re.match(r'SBI', str(utr))", "= learn.preprocessing.VocabularyProcessor.restore(vocab_path) x_test = np.array(list(vocab_processor.transform([query]))) # batch_predictions = self.sess.run(self.predictions, {self.input_x: x_test, self.dropout_keep_prob: 1.0})", "Details =>ABC Cop DC Nagar\\\\n\\\\n Regards.\"\"\" return template def saveLog(self, query, _class): logFileQ=", "e: raise e try: with open(logFileL,\"a\") as f: # noOfClasses = EmailClasses.getNoOfClasses() f.write(EmailClasses(_class).name+\"\\n\")", "\"Unable to classify request\" # return HttpResponse(answer) # print(HttpResponse(res,content_type=\"text/plain\",charset=\"utf-8\")) # print(HttpResponse(res)) # print(HttpResponse(res,content_type=\"text/plain\",charset=\"utf-8\").getvalue())", "is as follows:\\\\n 1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n 2. Date =>15-03-2017\\\\n 3. Amount =>1234.00\\\\n", "6. Beneficiary Name =>E456946\\\\n 7. Beneficiary Details =>ABC Cop DC Nagar\\\\n\\\\n Regards.\"\"\" else:", "= \"No utr found\" else: m = re.match(r'SBI', str(utr)) print(\"utr\") print(utr) print(\"m\") print(m)", "open(logFileQ,\"a\") as f: f.write(query+\"\\n\") except Exception as e: raise e try: with open(logFileL,\"a\")", "= graph.get_operation_by_name(\"output/scores\").outputs[0] # input_y = graph.get_operation_by_name(\"input_y\").outputs[0] self.dropout_keep_prob = graph.get_operation_by_name(\"dropout_keep_prob\").outputs[0] # Tensors we want", "csrf_protect from django.views.decorators.csrf import csrf_exempt from django.apps import AppConfig import os import numpy", "= (scores*scores)/sum(scores*scores) print(scores) pred = np.argmax(scores) score = scores[0] + scores[1]*-1 else: score", "e try: with open(logFileL,\"a\") as f: # noOfClasses = EmailClasses.getNoOfClasses() f.write(EmailClasses(_class).name+\"\\n\") except Exception", "only once) # if not any(x in sys.argv for x in ['makemigrations', 'migrate']):", "Tensors we want to evaluate self.predictions = graph.get_operation_by_name(\"output/predictions\").outputs[0] def ready(self): \"\"\" Called by", "EmailClasses.getNoOfClasses() f.write(EmailClasses(_class).name+\"\\n\") except Exception as e: raise e @csrf_exempt def log(self, request): if", "the remitter account as requested.\\\\n The details of the inward transaction are as", "\"\"\" # Initialize the auto reply model(should be launched only once) # if", "=>1111111111116452\\\\n 6. Remitter Name =>E456946\\\\n 7. Remitter Details =>ABC Cop DC Nagar\\\\n\\\\n\\\\n Regards.\"\"\"", "transaction are as follows:\\\\n 1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n 2. Date =>15-03-2017\\\\n 3. Amount", "The details of the outward transaction are as follows:\\\\n 1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n", "= batch_predictions[0] scores = batch_scores[0] scores = scores-np.min(scores) print(scores) scores = (scores*scores)/sum(scores*scores) print(scores)", "No. =>XXXXXxxxxxxxxxxx\\\\n 2. Date =>15-03-2017\\\\n 3. Amount =>1234.00\\\\n 4. Sending IFSC =>XXXXX0176600\\\\n 5.", "render from django.http import HttpResponse from django.views.decorators.csrf import csrf_protect from django.views.decorators.csrf import csrf_exempt", "6. Remitter Name =>E456946\\\\n 7. Remitter Details =>ABC Cop DC Nagar\\\\n\\\\n\\\\n Regards.\"\"\" else:", "return HttpResponse(score,content_type=\"text/plain\",charset=\"utf-8\") def getTemplate(self,_class, utr): template = \"\" if utr is None: template", "=>ABC Cop DC Nagar\\\\n\\\\n\\\\n Regards.\"\"\" else: template = \"\"\" Dear Sir,\\\\n\\\\n The amount", "vocab_path = os.path.join(self.checkpoint_dir, \"..\", \"vocab\") vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path) x_test = np.array(list(vocab_processor.transform([query]))) # batch_predictions", "once) # if not any(x in sys.argv for x in ['makemigrations', 'migrate']): #", "The status of your inward transaction is as follows:\\\\n 1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n", "e: raise e @csrf_exempt def log(self, request): if request.method == \"POST\": print(\"request\") print(request.body)", "in this format reqStr = str(request.body,'ISO 8859-1') print(\"reqStr ISO\") print(reqStr) # reqStr.replace(u'\\xa0', u'", "Details =>ABC Cop DC Nagar\\\\n\\\\n\\\\n Regards.\"\"\" else: template = \"\"\" Dear Sir,\\\\n\\\\n The", "Load the saved meta graph and restore variables saver = tf.train.import_meta_graph(\"{}.meta\".format(checkpoint_file)) saver.restore(self.sess, checkpoint_file)", "in the mail trail has been remitted back to the remitter account as", "query, _class): logFileQ= \"server/Log/query.txt\" logFileL = \"server/Log/labels.txt\" try: with open(logFileQ,\"a\") as f: f.write(query+\"\\n\")", "evaluate self.predictions = graph.get_operation_by_name(\"output/predictions\").outputs[0] def ready(self): \"\"\" Called by Django only once during", "Remitter A/c =>1111111111116452\\\\n 6. Remitter Name =>E456946\\\\n 7. Remitter Details =>ABC Cop DC", "return len(list(EmailClasses)) print(EmailClasses(0)) class Sentiment(AppConfig): def __init__(self): print(\"initialising module\") self.checkpoint_dir = \"/home/anson/Desktop/hackathons/crypto/sentiment/runs/1528569664/checkpoints\" self.allow_soft_placement", "requestBody['message'] is not None: query = requestBody['message'] # Map data into vocabulary vocab_path", "from enum import Enum import tensorflow as tf from tensorflow.contrib import learn class", "Date =>15-03-2017\\\\n 3. Amount =>1234.00\\\\n 4. Sending IFSC =>XXXXX0176600\\\\n 5. Remitter A/c =>1111111111116452\\\\n", "= ' '.join(reqStrArr) print(\"reqStr\") print(reqStr) requestBody = json.loads(reqStr) print(requestBody) logFile= \"server/Log/log.txt\" try: with", "['makemigrations', 'migrate']): # HACK: Avoid initialisation while migrate #do something print(\"In ready\") @csrf_exempt", "None: query = requestBody['message'] # Map data into vocabulary vocab_path = os.path.join(self.checkpoint_dir, \"..\",", "in the mail trail has been recalled.\\\\n The details of the outward transaction", "startup \"\"\" # Initialize the auto reply model(should be launched only once) #", "self.sess.as_default(): # Load the saved meta graph and restore variables saver = tf.train.import_meta_graph(\"{}.meta\".format(checkpoint_file))", "once during startup \"\"\" # Initialize the auto reply model(should be launched only", "print(utr) print(\"m\") print(m) if m is None: if _class == 1: template =", "template = \"\"\" Dear Sir,\\\\n\\\\n The transaction to the account mentioned in the", "=>ABC Cop DC Nagar\\\\n\\\\n Regards.\"\"\" else: template = \"\"\" Dear Sir,\\\\n\\\\n The transaction", "django.shortcuts import render from django.http import HttpResponse from django.views.decorators.csrf import csrf_protect from django.views.decorators.csrf", "the account mentioned in the mail trail has been recalled.\\\\n The details of", "graph.get_operation_by_name(\"input_x\").outputs[0] self.scores = graph.get_operation_by_name(\"output/scores\").outputs[0] # input_y = graph.get_operation_by_name(\"input_y\").outputs[0] self.dropout_keep_prob = graph.get_operation_by_name(\"dropout_keep_prob\").outputs[0] # Tensors", "m is None: if _class == 1: template = \"\"\" Dear Sir,\\\\n\\\\n The", "Regards.\"\"\" else: if _class == 1: template = \"\"\" Dear Sir,\\\\n\\\\n The status", "graph by name self.input_x = graph.get_operation_by_name(\"input_x\").outputs[0] self.scores = graph.get_operation_by_name(\"output/scores\").outputs[0] # input_y = graph.get_operation_by_name(\"input_y\").outputs[0]", "template = \"\"\" Dear Sir,\\\\n\\\\n The status of your outward transaction is as", "the auto reply model(should be launched only once) # if not any(x in", "mail trail has been remitted back to the remitter account as requested.\\\\n The", "(scores*scores)/sum(scores*scores) print(scores) pred = np.argmax(scores) score = scores[0] + scores[1]*-1 else: score =", "\"No utr found\" else: m = re.match(r'SBI', str(utr)) print(\"utr\") print(utr) print(\"m\") print(m) if", "mail trail has been recalled.\\\\n The details of the outward transaction are as", "= self.sess.run(self.scores, {self.input_x: x_test, self.dropout_keep_prob: 1.0}) # answer = batch_predictions[0] scores = batch_scores[0]", "5. Remitter A/c =>1111111111116452\\\\n 6. Remitter Name =>E456946\\\\n 7. Remitter Details =>ABC Cop", "is None: template = \"No utr found\" else: m = re.match(r'SBI', str(utr)) print(\"utr\")", "self.allow_soft_placement = True self.log_device_placement = False checkpoint_file = tf.train.latest_checkpoint(self.checkpoint_dir) graph = tf.Graph() with", "1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n 2. Date =>15-03-2017\\\\n 3. Amount =>1234.00\\\\n 4. Sending IFSC", "=>15-03-2017\\\\n 3. Amount =>1234.00\\\\n 4. Receiving IFSC =>XXXXX0176600\\\\n 5. Beneficiary A/c =>1111111111116452\\\\n 6.", "f: # noOfClasses = EmailClasses.getNoOfClasses() f.write(EmailClasses(_class).name+\"\\n\") except Exception as e: raise e @csrf_exempt", "the inward transaction are as follows:\\\\n 1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n 2. Date =>15-03-2017\\\\n", "re.match(r'SBI', str(utr)) print(\"utr\") print(utr) print(\"m\") print(m) if m is None: if _class ==", "saver.restore(self.sess, checkpoint_file) # Get the placeholders from the graph by name self.input_x =", "tensorflow as tf from tensorflow.contrib import learn class EmailClasses(Enum): recall = 0 status", "print(\"reqStr ISO\") print(reqStr) # reqStr.replace(u'\\xa0', u' ').encode('utf-8') # reqStr = str(request.body,'utf-8') reqStrArr =", "during startup \"\"\" # Initialize the auto reply model(should be launched only once)", "in ['makemigrations', 'migrate']): # HACK: Avoid initialisation while migrate #do something print(\"In ready\")", "print(HttpResponse(res,content_type=\"text/plain\",charset=\"utf-8\").getvalue()) return HttpResponse(score,content_type=\"text/plain\",charset=\"utf-8\") def getTemplate(self,_class, utr): template = \"\" if utr is None:", "request.method == \"POST\": print(\"request\") print(request.body) #Java sends string encoded in this format reqStr", "'.join(reqStrArr) print(\"reqStr\") print(reqStr) requestBody = json.loads(reqStr) print(requestBody) logFile= \"server/Log/log.txt\" try: with open(logFile,\"a\") as", "np.argmax(scores) score = scores[0] + scores[1]*-1 else: score = 0 res = \"Unable", "if not any(x in sys.argv for x in ['makemigrations', 'migrate']): # HACK: Avoid", "EmailClasses(Enum): recall = 0 status = 1 def getNoOfClasses(): return len(list(EmailClasses)) print(EmailClasses(0)) class", "recalled.\\\\n The details of the outward transaction are as follows:\\\\n 1. UTR No.", "name self.input_x = graph.get_operation_by_name(\"input_x\").outputs[0] self.scores = graph.get_operation_by_name(\"output/scores\").outputs[0] # input_y = graph.get_operation_by_name(\"input_y\").outputs[0] self.dropout_keep_prob =", "tf.train.latest_checkpoint(self.checkpoint_dir) graph = tf.Graph() with graph.as_default(): session_conf = tf.ConfigProto( allow_soft_placement=self.allow_soft_placement, log_device_placement=self.log_device_placement) self.sess =", "print(HttpResponse(res)) # print(HttpResponse(res,content_type=\"text/plain\",charset=\"utf-8\").getvalue()) return HttpResponse(score,content_type=\"text/plain\",charset=\"utf-8\") def getTemplate(self,_class, utr): template = \"\" if utr", "#do something print(\"In ready\") @csrf_exempt def getResponse(self, request): if request.method == \"POST\": print(\"request\")", "from tensorflow.contrib import learn class EmailClasses(Enum): recall = 0 status = 1 def", "of your inward transaction is as follows:\\\\n 1. UTR No. =>XXXXXxxxxxxxxxxx\\\\n 2. Date", "self.sess.run(self.scores, {self.input_x: x_test, self.dropout_keep_prob: 1.0}) # answer = batch_predictions[0] scores = batch_scores[0] scores", "7. Remitter Details =>ABC Cop DC Nagar\\\\n\\\\n\\\\n Regards.\"\"\" else: template = \"\"\" Dear", "_class == 1: template = \"\"\" Dear Sir,\\\\n\\\\n The status of your outward", "import json import re from enum import Enum import tensorflow as tf from", "by name self.input_x = graph.get_operation_by_name(\"input_x\").outputs[0] self.scores = graph.get_operation_by_name(\"output/scores\").outputs[0] # input_y = graph.get_operation_by_name(\"input_y\").outputs[0] self.dropout_keep_prob", "# reqStr = str(request.body,'utf-8') reqStrArr = reqStr.split() reqStr = ' '.join(reqStrArr) print(\"reqStr\") print(reqStr)", "data into vocabulary vocab_path = os.path.join(self.checkpoint_dir, \"..\", \"vocab\") vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path) x_test =", "Beneficiary Name =>E456946\\\\n 7. Beneficiary Details =>ABC Cop DC Nagar\\\\n\\\\n Regards.\"\"\" return template", "def saveLog(self, query, _class): logFileQ= \"server/Log/query.txt\" logFileL = \"server/Log/labels.txt\" try: with open(logFileQ,\"a\") as", "print(\"utr\") print(utr) print(\"m\") print(m) if m is None: if _class == 1: template", "_class == 1: template = \"\"\" Dear Sir,\\\\n\\\\n The status of your inward", "def ready(self): \"\"\" Called by Django only once during startup \"\"\" # Initialize", "template = \"No utr found\" else: m = re.match(r'SBI', str(utr)) print(\"utr\") print(utr) print(\"m\")", "= np.array(list(vocab_processor.transform([query]))) # batch_predictions = self.sess.run(self.predictions, {self.input_x: x_test, self.dropout_keep_prob: 1.0}) batch_scores = self.sess.run(self.scores,", "= \"server/Log/labels.txt\" try: with open(logFileQ,\"a\") as f: f.write(query+\"\\n\") except Exception as e: raise", "format reqStr = str(request.body,'ISO 8859-1') print(\"reqStr ISO\") print(reqStr) # reqStr.replace(u'\\xa0', u' ').encode('utf-8') #", "str(utr)) print(\"utr\") print(utr) print(\"m\") print(m) if m is None: if _class == 1:", "6. Remitter Name =>E456946\\\\n 7. Remitter Details =>ABC Cop DC Nagar\\\\n\\\\n Regards.\"\"\" else:" ]
[ "Canvas(window, height=30, width=30) back.pack() diamonds = 0 def morediamonds(): global diamonds diamonds +=", "-=15 Cursor = Button(window, text=\"Cursor: Clicks every second (Cost: 15). Lasts 20 seconds.\",", "\" + str(diamonds) + \" diamonds!\") def cursorworking(): global diamonds for x in", "from tkinter import * from time import sleep window = Tk() window.title(\"Diamond Clicker\")", "diamonds for x in range(20): if diamonds < 15: print (\"Not enough diamonds!\")", "Button(window, text=\"Cursor: Clicks every second (Cost: 15). Lasts 20 seconds.\", command=cursorworking) PlusOneDiamonds =", "have \" + str(diamonds) + \" diamonds!\") def cursorworking(): global diamonds for x", "def morediamonds(): global diamonds diamonds += 1 print (\"You have \" + str(diamonds)", "diamonds < 15: print (\"Not enough diamonds!\") break diamonds -= 15 diamonds +=", "break diamonds -= 15 diamonds += 1 print (\"You now have \" +", "diamonds!\") break diamonds -= 15 diamonds += 1 print (\"You now have \"", "enough diamonds!\") break diamonds -= 15 diamonds += 1 print (\"You now have", "+= 1 print (\"You have \" + str(diamonds) + \" diamonds!\") def cursorworking():", "(\"You now have \" + str(diamonds) + \" diamonds!\") sleep(1) def minerworking(): global", "\" diamonds!\") sleep(1) def minerworking(): global diamonds diamonds -=15 Cursor = Button(window, text=\"Cursor:", "import * from time import sleep window = Tk() window.title(\"Diamond Clicker\") back =", "from time import sleep window = Tk() window.title(\"Diamond Clicker\") back = Canvas(window, height=30,", "import sleep window = Tk() window.title(\"Diamond Clicker\") back = Canvas(window, height=30, width=30) back.pack()", "second (Cost: 15). Lasts 20 seconds.\", command=cursorworking) PlusOneDiamonds = Button(window, text=\"+1 Diamond\", command=morediamonds)", "= Canvas(window, height=30, width=30) back.pack() diamonds = 0 def morediamonds(): global diamonds diamonds", "for x in range(20): if diamonds < 15: print (\"Not enough diamonds!\") break", "global diamonds for x in range(20): if diamonds < 15: print (\"Not enough", "+ \" diamonds!\") sleep(1) def minerworking(): global diamonds diamonds -=15 Cursor = Button(window,", "now have \" + str(diamonds) + \" diamonds!\") sleep(1) def minerworking(): global diamonds", "sleep(1) def minerworking(): global diamonds diamonds -=15 Cursor = Button(window, text=\"Cursor: Clicks every", "+= 1 print (\"You now have \" + str(diamonds) + \" diamonds!\") sleep(1)", "every second (Cost: 15). Lasts 20 seconds.\", command=cursorworking) PlusOneDiamonds = Button(window, text=\"+1 Diamond\",", "diamonds diamonds += 1 print (\"You have \" + str(diamonds) + \" diamonds!\")", "Cursor = Button(window, text=\"Cursor: Clicks every second (Cost: 15). Lasts 20 seconds.\", command=cursorworking)", "diamonds!\") def cursorworking(): global diamonds for x in range(20): if diamonds < 15:", "cursorworking(): global diamonds for x in range(20): if diamonds < 15: print (\"Not", "range(20): if diamonds < 15: print (\"Not enough diamonds!\") break diamonds -= 15", "tkinter import * from time import sleep window = Tk() window.title(\"Diamond Clicker\") back", "diamonds += 1 print (\"You have \" + str(diamonds) + \" diamonds!\") def", "15). Lasts 20 seconds.\", command=cursorworking) PlusOneDiamonds = Button(window, text=\"+1 Diamond\", command=morediamonds) PlusOneDiamonds.pack() Cursor.pack()", "global diamonds diamonds -=15 Cursor = Button(window, text=\"Cursor: Clicks every second (Cost: 15).", "height=30, width=30) back.pack() diamonds = 0 def morediamonds(): global diamonds diamonds += 1", "15 diamonds += 1 print (\"You now have \" + str(diamonds) + \"", "text=\"Cursor: Clicks every second (Cost: 15). Lasts 20 seconds.\", command=cursorworking) PlusOneDiamonds = Button(window,", "def minerworking(): global diamonds diamonds -=15 Cursor = Button(window, text=\"Cursor: Clicks every second", "diamonds += 1 print (\"You now have \" + str(diamonds) + \" diamonds!\")", "\" + str(diamonds) + \" diamonds!\") sleep(1) def minerworking(): global diamonds diamonds -=15", "* from time import sleep window = Tk() window.title(\"Diamond Clicker\") back = Canvas(window,", "window = Tk() window.title(\"Diamond Clicker\") back = Canvas(window, height=30, width=30) back.pack() diamonds =", "= 0 def morediamonds(): global diamonds diamonds += 1 print (\"You have \"", "morediamonds(): global diamonds diamonds += 1 print (\"You have \" + str(diamonds) +", "x in range(20): if diamonds < 15: print (\"Not enough diamonds!\") break diamonds", "minerworking(): global diamonds diamonds -=15 Cursor = Button(window, text=\"Cursor: Clicks every second (Cost:", "Tk() window.title(\"Diamond Clicker\") back = Canvas(window, height=30, width=30) back.pack() diamonds = 0 def", "time import sleep window = Tk() window.title(\"Diamond Clicker\") back = Canvas(window, height=30, width=30)", "str(diamonds) + \" diamonds!\") def cursorworking(): global diamonds for x in range(20): if", "= Tk() window.title(\"Diamond Clicker\") back = Canvas(window, height=30, width=30) back.pack() diamonds = 0", "diamonds -=15 Cursor = Button(window, text=\"Cursor: Clicks every second (Cost: 15). Lasts 20", "diamonds diamonds -=15 Cursor = Button(window, text=\"Cursor: Clicks every second (Cost: 15). Lasts", "(\"You have \" + str(diamonds) + \" diamonds!\") def cursorworking(): global diamonds for", "print (\"You have \" + str(diamonds) + \" diamonds!\") def cursorworking(): global diamonds", "if diamonds < 15: print (\"Not enough diamonds!\") break diamonds -= 15 diamonds", "+ str(diamonds) + \" diamonds!\") def cursorworking(): global diamonds for x in range(20):", "back = Canvas(window, height=30, width=30) back.pack() diamonds = 0 def morediamonds(): global diamonds", "in range(20): if diamonds < 15: print (\"Not enough diamonds!\") break diamonds -=", "def cursorworking(): global diamonds for x in range(20): if diamonds < 15: print", "(Cost: 15). Lasts 20 seconds.\", command=cursorworking) PlusOneDiamonds = Button(window, text=\"+1 Diamond\", command=morediamonds) PlusOneDiamonds.pack()", "global diamonds diamonds += 1 print (\"You have \" + str(diamonds) + \"", "diamonds = 0 def morediamonds(): global diamonds diamonds += 1 print (\"You have", "1 print (\"You have \" + str(diamonds) + \" diamonds!\") def cursorworking(): global", "sleep window = Tk() window.title(\"Diamond Clicker\") back = Canvas(window, height=30, width=30) back.pack() diamonds", "GUI.py from tkinter import * from time import sleep window = Tk() window.title(\"Diamond", "print (\"Not enough diamonds!\") break diamonds -= 15 diamonds += 1 print (\"You", "-= 15 diamonds += 1 print (\"You now have \" + str(diamonds) +", "diamonds -= 15 diamonds += 1 print (\"You now have \" + str(diamonds)", "str(diamonds) + \" diamonds!\") sleep(1) def minerworking(): global diamonds diamonds -=15 Cursor =", "<filename>Interactive GUI.py from tkinter import * from time import sleep window = Tk()", "width=30) back.pack() diamonds = 0 def morediamonds(): global diamonds diamonds += 1 print", "(\"Not enough diamonds!\") break diamonds -= 15 diamonds += 1 print (\"You now", "+ str(diamonds) + \" diamonds!\") sleep(1) def minerworking(): global diamonds diamonds -=15 Cursor", "Clicker\") back = Canvas(window, height=30, width=30) back.pack() diamonds = 0 def morediamonds(): global", "print (\"You now have \" + str(diamonds) + \" diamonds!\") sleep(1) def minerworking():", "have \" + str(diamonds) + \" diamonds!\") sleep(1) def minerworking(): global diamonds diamonds", "15: print (\"Not enough diamonds!\") break diamonds -= 15 diamonds += 1 print", "+ \" diamonds!\") def cursorworking(): global diamonds for x in range(20): if diamonds", "1 print (\"You now have \" + str(diamonds) + \" diamonds!\") sleep(1) def", "< 15: print (\"Not enough diamonds!\") break diamonds -= 15 diamonds += 1", "= Button(window, text=\"Cursor: Clicks every second (Cost: 15). Lasts 20 seconds.\", command=cursorworking) PlusOneDiamonds", "diamonds!\") sleep(1) def minerworking(): global diamonds diamonds -=15 Cursor = Button(window, text=\"Cursor: Clicks", "back.pack() diamonds = 0 def morediamonds(): global diamonds diamonds += 1 print (\"You", "\" diamonds!\") def cursorworking(): global diamonds for x in range(20): if diamonds <", "Clicks every second (Cost: 15). Lasts 20 seconds.\", command=cursorworking) PlusOneDiamonds = Button(window, text=\"+1", "window.title(\"Diamond Clicker\") back = Canvas(window, height=30, width=30) back.pack() diamonds = 0 def morediamonds():", "0 def morediamonds(): global diamonds diamonds += 1 print (\"You have \" +" ]
[ "if not hasattr(cls, \"_instance\"): cls._instance = super().__call__(*args, **kwargs) return cls._instance #@Singleton #class TestClass(Singleton2):", "a = TestClass() b = TestClass() print(\"id of a:\",id(a)) print(\"id of b:\",id(b)) #https://segmentfault.com/q/1010000007818814", "_instance if _instance is None: _instance = cls(*args, **kwargs) return _instance return wrap", "__name__ == \"__main__\": a = TestClass() b = TestClass() print(\"id of a:\",id(a)) print(\"id", "class Singleton2(): \"\"\"继承,依赖类变量_instance,\"\"\" def __new__(cls, *args, **kwargs): if not hasattr(cls, \"_instance\"): cls._instance =", "\"\"\"继承,依赖类变量_instance,\"\"\" def __new__(cls, *args, **kwargs): if not hasattr(cls, \"_instance\"): cls._instance = super().__new__(cls, *args,", "\"\"\"MetaClass\"\"\" def __call__(cls, *args, **kwargs): if not hasattr(cls, \"_instance\"): cls._instance = super().__call__(*args, **kwargs)", "if _instance is None: _instance = cls(*args, **kwargs) return _instance return wrap class", "__call__(cls, *args, **kwargs): if not hasattr(cls, \"_instance\"): cls._instance = super().__call__(*args, **kwargs) return cls._instance", "wrap class Singleton2(): \"\"\"继承,依赖类变量_instance,\"\"\" def __new__(cls, *args, **kwargs): if not hasattr(cls, \"_instance\"): cls._instance", "**kwargs): if not hasattr(cls, \"_instance\"): cls._instance = super().__new__(cls, *args, **kwargs) return cls._instance class", "\"\"\"装饰器,依赖闭包,python3以前没有nonlocal,所以需要定义为可变对象,比如,_instance={}\"\"\" _instance = None def wrap(*args, **kwargs): nonlocal _instance if _instance is None:", "return wrap class Singleton2(): \"\"\"继承,依赖类变量_instance,\"\"\" def __new__(cls, *args, **kwargs): if not hasattr(cls, \"_instance\"):", "*args, **kwargs): if not hasattr(cls, \"_instance\"): cls._instance = super().__new__(cls, *args, **kwargs) return cls._instance", "cls._instance class Singleton3(type): \"\"\"MetaClass\"\"\" def __call__(cls, *args, **kwargs): if not hasattr(cls, \"_instance\"): cls._instance", "def __new__(cls, *args, **kwargs): if not hasattr(cls, \"_instance\"): cls._instance = super().__new__(cls, *args, **kwargs)", "def wrap(*args, **kwargs): nonlocal _instance if _instance is None: _instance = cls(*args, **kwargs)", "__new__(cls, *args, **kwargs): if not hasattr(cls, \"_instance\"): cls._instance = super().__new__(cls, *args, **kwargs) return", "\"_instance\"): cls._instance = super().__new__(cls, *args, **kwargs) return cls._instance class Singleton3(type): \"\"\"MetaClass\"\"\" def __call__(cls,", "= super().__new__(cls, *args, **kwargs) return cls._instance class Singleton3(type): \"\"\"MetaClass\"\"\" def __call__(cls, *args, **kwargs):", "class TestClass(metaclass = Singleton3): def __init__(self): print(\"TestClass init\") if __name__ == \"__main__\": a", "__init__(self): print(\"TestClass init\") if __name__ == \"__main__\": a = TestClass() b = TestClass()", "= None def wrap(*args, **kwargs): nonlocal _instance if _instance is None: _instance =", "return _instance return wrap class Singleton2(): \"\"\"继承,依赖类变量_instance,\"\"\" def __new__(cls, *args, **kwargs): if not", "not hasattr(cls, \"_instance\"): cls._instance = super().__call__(*args, **kwargs) return cls._instance #@Singleton #class TestClass(Singleton2): class", "_instance = None def wrap(*args, **kwargs): nonlocal _instance if _instance is None: _instance", "TestClass(metaclass = Singleton3): def __init__(self): print(\"TestClass init\") if __name__ == \"__main__\": a =", "#class TestClass(Singleton2): class TestClass(metaclass = Singleton3): def __init__(self): print(\"TestClass init\") if __name__ ==", "None def wrap(*args, **kwargs): nonlocal _instance if _instance is None: _instance = cls(*args,", "= cls(*args, **kwargs) return _instance return wrap class Singleton2(): \"\"\"继承,依赖类变量_instance,\"\"\" def __new__(cls, *args,", "Singleton3(type): \"\"\"MetaClass\"\"\" def __call__(cls, *args, **kwargs): if not hasattr(cls, \"_instance\"): cls._instance = super().__call__(*args,", "cls._instance #@Singleton #class TestClass(Singleton2): class TestClass(metaclass = Singleton3): def __init__(self): print(\"TestClass init\") if", "hasattr(cls, \"_instance\"): cls._instance = super().__call__(*args, **kwargs) return cls._instance #@Singleton #class TestClass(Singleton2): class TestClass(metaclass", "Singleton(cls): \"\"\"装饰器,依赖闭包,python3以前没有nonlocal,所以需要定义为可变对象,比如,_instance={}\"\"\" _instance = None def wrap(*args, **kwargs): nonlocal _instance if _instance is", "_instance = cls(*args, **kwargs) return _instance return wrap class Singleton2(): \"\"\"继承,依赖类变量_instance,\"\"\" def __new__(cls,", "super().__call__(*args, **kwargs) return cls._instance #@Singleton #class TestClass(Singleton2): class TestClass(metaclass = Singleton3): def __init__(self):", "if __name__ == \"__main__\": a = TestClass() b = TestClass() print(\"id of a:\",id(a))", "== \"__main__\": a = TestClass() b = TestClass() print(\"id of a:\",id(a)) print(\"id of", "#@Singleton #class TestClass(Singleton2): class TestClass(metaclass = Singleton3): def __init__(self): print(\"TestClass init\") if __name__", "not hasattr(cls, \"_instance\"): cls._instance = super().__new__(cls, *args, **kwargs) return cls._instance class Singleton3(type): \"\"\"MetaClass\"\"\"", "TestClass(Singleton2): class TestClass(metaclass = Singleton3): def __init__(self): print(\"TestClass init\") if __name__ == \"__main__\":", "return cls._instance class Singleton3(type): \"\"\"MetaClass\"\"\" def __call__(cls, *args, **kwargs): if not hasattr(cls, \"_instance\"):", "hasattr(cls, \"_instance\"): cls._instance = super().__new__(cls, *args, **kwargs) return cls._instance class Singleton3(type): \"\"\"MetaClass\"\"\" def", "*args, **kwargs): if not hasattr(cls, \"_instance\"): cls._instance = super().__call__(*args, **kwargs) return cls._instance #@Singleton", "\"_instance\"): cls._instance = super().__call__(*args, **kwargs) return cls._instance #@Singleton #class TestClass(Singleton2): class TestClass(metaclass =", "= Singleton3): def __init__(self): print(\"TestClass init\") if __name__ == \"__main__\": a = TestClass()", "def __init__(self): print(\"TestClass init\") if __name__ == \"__main__\": a = TestClass() b =", "cls(*args, **kwargs) return _instance return wrap class Singleton2(): \"\"\"继承,依赖类变量_instance,\"\"\" def __new__(cls, *args, **kwargs):", "if not hasattr(cls, \"_instance\"): cls._instance = super().__new__(cls, *args, **kwargs) return cls._instance class Singleton3(type):", "super().__new__(cls, *args, **kwargs) return cls._instance class Singleton3(type): \"\"\"MetaClass\"\"\" def __call__(cls, *args, **kwargs): if", "wrap(*args, **kwargs): nonlocal _instance if _instance is None: _instance = cls(*args, **kwargs) return", "def __call__(cls, *args, **kwargs): if not hasattr(cls, \"_instance\"): cls._instance = super().__call__(*args, **kwargs) return", "is None: _instance = cls(*args, **kwargs) return _instance return wrap class Singleton2(): \"\"\"继承,依赖类变量_instance,\"\"\"", "**kwargs) return _instance return wrap class Singleton2(): \"\"\"继承,依赖类变量_instance,\"\"\" def __new__(cls, *args, **kwargs): if", "**kwargs): if not hasattr(cls, \"_instance\"): cls._instance = super().__call__(*args, **kwargs) return cls._instance #@Singleton #class", "**kwargs) return cls._instance #@Singleton #class TestClass(Singleton2): class TestClass(metaclass = Singleton3): def __init__(self): print(\"TestClass", "Singleton3): def __init__(self): print(\"TestClass init\") if __name__ == \"__main__\": a = TestClass() b", "cls._instance = super().__call__(*args, **kwargs) return cls._instance #@Singleton #class TestClass(Singleton2): class TestClass(metaclass = Singleton3):", "class Singleton3(type): \"\"\"MetaClass\"\"\" def __call__(cls, *args, **kwargs): if not hasattr(cls, \"_instance\"): cls._instance =", "def Singleton(cls): \"\"\"装饰器,依赖闭包,python3以前没有nonlocal,所以需要定义为可变对象,比如,_instance={}\"\"\" _instance = None def wrap(*args, **kwargs): nonlocal _instance if _instance", "**kwargs): nonlocal _instance if _instance is None: _instance = cls(*args, **kwargs) return _instance", "Singleton2(): \"\"\"继承,依赖类变量_instance,\"\"\" def __new__(cls, *args, **kwargs): if not hasattr(cls, \"_instance\"): cls._instance = super().__new__(cls,", "= super().__call__(*args, **kwargs) return cls._instance #@Singleton #class TestClass(Singleton2): class TestClass(metaclass = Singleton3): def", "init\") if __name__ == \"__main__\": a = TestClass() b = TestClass() print(\"id of", "_instance return wrap class Singleton2(): \"\"\"继承,依赖类变量_instance,\"\"\" def __new__(cls, *args, **kwargs): if not hasattr(cls,", "\"__main__\": a = TestClass() b = TestClass() print(\"id of a:\",id(a)) print(\"id of b:\",id(b))", "print(\"TestClass init\") if __name__ == \"__main__\": a = TestClass() b = TestClass() print(\"id", "nonlocal _instance if _instance is None: _instance = cls(*args, **kwargs) return _instance return", "*args, **kwargs) return cls._instance class Singleton3(type): \"\"\"MetaClass\"\"\" def __call__(cls, *args, **kwargs): if not", "None: _instance = cls(*args, **kwargs) return _instance return wrap class Singleton2(): \"\"\"继承,依赖类变量_instance,\"\"\" def", "cls._instance = super().__new__(cls, *args, **kwargs) return cls._instance class Singleton3(type): \"\"\"MetaClass\"\"\" def __call__(cls, *args,", "_instance is None: _instance = cls(*args, **kwargs) return _instance return wrap class Singleton2():", "**kwargs) return cls._instance class Singleton3(type): \"\"\"MetaClass\"\"\" def __call__(cls, *args, **kwargs): if not hasattr(cls,", "return cls._instance #@Singleton #class TestClass(Singleton2): class TestClass(metaclass = Singleton3): def __init__(self): print(\"TestClass init\")" ]
[]
[ "# filename='log.log', format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) parser = argparse.ArgumentParser() print(Configer.ip_address, Configer.port,", "elif args.action == 'crawl_webpages': # TODO: parameters export_dir = '../data/webpages' concept_dir = '../data'", "type=int, help='number of process') parser.add_argument( '-cd', '--concept_dir', default='../data', help='directory to store concept definition')", "concept_dir=args.concept_dir) elif args.action == 'create_los_dataset': create_cvd_los_dataset(export_dir=args.export_dir, concept_dir=args.concept_dir) elif args.action == 'crawl_webpages': # TODO:", "'cluster', 'backup', 'restore', 'create_los_dataset'], help='define action for preprocess' ) parser.add_argument('-p', '--process', default=2, type=int,", ": %(levelname)s : %(message)s', level=logging.INFO) parser = argparse.ArgumentParser() print(Configer.ip_address, Configer.port, Configer.ssh_username, Configer.ssh_password) print(Configer.db_name,", "train data)') args = parser.parse_args() if args.action == 'define_concepts': define_concepts(output_dir=args.concept_dir, processes=args.process) elif args.action", "'-cd', '--concept_dir', default='../data', help='directory to store concept definition') # options for create train", "create train data)') args = parser.parse_args() if args.action == 'define_concepts': define_concepts(output_dir=args.concept_dir, processes=args.process) elif", "== 'define_concepts': define_concepts(output_dir=args.concept_dir, processes=args.process) elif args.action == 'update_chartevents': update_chartevents_value(concept_dir=args.concept_dir) elif args.action == 'create_train_dataset':", "= '../data' crawl_webpages(concept_dir, export_dir) elif args.action == 'tfidf_medical_webpages': tfidf.train_tfidf(min_count=5, chunksize=5000, ngrams=(1, 1), model_dir='../models')", "processes=args.process, concept_dir=args.concept_dir) elif args.action == 'create_los_dataset': create_cvd_los_dataset(export_dir=args.export_dir, concept_dir=args.concept_dir) elif args.action == 'crawl_webpages': #", "crawl_webpages(concept_dir, export_dir) elif args.action == 'tfidf_medical_webpages': tfidf.train_tfidf(min_count=5, chunksize=5000, ngrams=(1, 1), model_dir='../models') elif args.action", "print(Configer.ip_address, Configer.port, Configer.ssh_username, Configer.ssh_password) print(Configer.db_name, Configer.db_username, Configer.db_password) if __name__ == '__main__': parser.add_argument( 'action',", "from src import tfidf Configer = Configer('setting.ini') logging.basicConfig( # filename='log.log', format='%(asctime)s : %(levelname)s", "'-ed', '--export_dir', help='directory to store train data (options for create train data)') args", "'--export_dir', help='directory to store train data (options for create train data)') args =", "create_train_feature_dataset(export_dir=args.export_dir, processes=args.process, concept_dir=args.concept_dir) elif args.action == 'create_los_dataset': create_cvd_los_dataset(export_dir=args.export_dir, concept_dir=args.concept_dir) elif args.action == 'crawl_webpages':", "Configer('setting.ini') logging.basicConfig( # filename='log.log', format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) parser = argparse.ArgumentParser()", "'crawl_webpages': # TODO: parameters export_dir = '../data/webpages' concept_dir = '../data' crawl_webpages(concept_dir, export_dir) elif", "preprocess' ) parser.add_argument('-p', '--process', default=2, type=int, help='number of process') parser.add_argument( '-cd', '--concept_dir', default='../data',", "parser.add_argument( '-cd', '--concept_dir', default='../data', help='directory to store concept definition') # options for create", "data)') args = parser.parse_args() if args.action == 'define_concepts': define_concepts(output_dir=args.concept_dir, processes=args.process) elif args.action ==", "store train data (options for create train data)') args = parser.parse_args() if args.action", "for preprocess' ) parser.add_argument('-p', '--process', default=2, type=int, help='number of process') parser.add_argument( '-cd', '--concept_dir',", "concept definition') # options for create train data parser.add_argument( '-ed', '--export_dir', help='directory to", "argparse from src.preprocess import * from src.item_preprocessor import * from src.configer import *", "'define_concepts': define_concepts(output_dir=args.concept_dir, processes=args.process) elif args.action == 'update_chartevents': update_chartevents_value(concept_dir=args.concept_dir) elif args.action == 'create_train_dataset': create_train_feature_dataset(export_dir=args.export_dir,", "if args.action == 'define_concepts': define_concepts(output_dir=args.concept_dir, processes=args.process) elif args.action == 'update_chartevents': update_chartevents_value(concept_dir=args.concept_dir) elif args.action", "== '__main__': parser.add_argument( 'action', choices=['define_concepts', 'update_chartevents', 'create_train_dataset', 'crawl_webpages', 'tfidf_medical_webpages', 'cluster', 'backup', 'restore', 'create_los_dataset'],", "if __name__ == '__main__': parser.add_argument( 'action', choices=['define_concepts', 'update_chartevents', 'create_train_dataset', 'crawl_webpages', 'tfidf_medical_webpages', 'cluster', 'backup',", "for create train data parser.add_argument( '-ed', '--export_dir', help='directory to store train data (options", "'--process', default=2, type=int, help='number of process') parser.add_argument( '-cd', '--concept_dir', default='../data', help='directory to store", "'create_los_dataset': create_cvd_los_dataset(export_dir=args.export_dir, concept_dir=args.concept_dir) elif args.action == 'crawl_webpages': # TODO: parameters export_dir = '../data/webpages'", "'crawl_webpages', 'tfidf_medical_webpages', 'cluster', 'backup', 'restore', 'create_los_dataset'], help='define action for preprocess' ) parser.add_argument('-p', '--process',", "format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) parser = argparse.ArgumentParser() print(Configer.ip_address, Configer.port, Configer.ssh_username, Configer.ssh_password)", "Configer = Configer('setting.ini') logging.basicConfig( # filename='log.log', format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) parser", "processes=args.process) elif args.action == 'update_chartevents': update_chartevents_value(concept_dir=args.concept_dir) elif args.action == 'create_train_dataset': create_train_feature_dataset(export_dir=args.export_dir, processes=args.process, concept_dir=args.concept_dir)", "1), model_dir='../models') elif args.action == 'cluster': cluster() elif args.action == 'backup': backup_merge_data() elif", "'action', choices=['define_concepts', 'update_chartevents', 'create_train_dataset', 'crawl_webpages', 'tfidf_medical_webpages', 'cluster', 'backup', 'restore', 'create_los_dataset'], help='define action for", "level=logging.INFO) parser = argparse.ArgumentParser() print(Configer.ip_address, Configer.port, Configer.ssh_username, Configer.ssh_password) print(Configer.db_name, Configer.db_username, Configer.db_password) if __name__", "create_cvd_los_dataset(export_dir=args.export_dir, concept_dir=args.concept_dir) elif args.action == 'crawl_webpages': # TODO: parameters export_dir = '../data/webpages' concept_dir", "* from src.configer import * from src import tfidf Configer = Configer('setting.ini') logging.basicConfig(", "logging.basicConfig( # filename='log.log', format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) parser = argparse.ArgumentParser() print(Configer.ip_address,", "'create_los_dataset'], help='define action for preprocess' ) parser.add_argument('-p', '--process', default=2, type=int, help='number of process')", "options for create train data parser.add_argument( '-ed', '--export_dir', help='directory to store train data", "help='directory to store train data (options for create train data)') args = parser.parse_args()", "parser.add_argument( '-ed', '--export_dir', help='directory to store train data (options for create train data)')", "parameters export_dir = '../data/webpages' concept_dir = '../data' crawl_webpages(concept_dir, export_dir) elif args.action == 'tfidf_medical_webpages':", "from src.configer import * from src import tfidf Configer = Configer('setting.ini') logging.basicConfig( #", "args.action == 'cluster': cluster() elif args.action == 'backup': backup_merge_data() elif args.action == 'restore':", "action for preprocess' ) parser.add_argument('-p', '--process', default=2, type=int, help='number of process') parser.add_argument( '-cd',", "args.action == 'create_los_dataset': create_cvd_los_dataset(export_dir=args.export_dir, concept_dir=args.concept_dir) elif args.action == 'crawl_webpages': # TODO: parameters export_dir", "%(message)s', level=logging.INFO) parser = argparse.ArgumentParser() print(Configer.ip_address, Configer.port, Configer.ssh_username, Configer.ssh_password) print(Configer.db_name, Configer.db_username, Configer.db_password) if", "src.configer import * from src import tfidf Configer = Configer('setting.ini') logging.basicConfig( # filename='log.log',", "store concept definition') # options for create train data parser.add_argument( '-ed', '--export_dir', help='directory", "ngrams=(1, 1), model_dir='../models') elif args.action == 'cluster': cluster() elif args.action == 'backup': backup_merge_data()", "* from src.item_preprocessor import * from src.configer import * from src import tfidf", "data (options for create train data)') args = parser.parse_args() if args.action == 'define_concepts':", "'tfidf_medical_webpages': tfidf.train_tfidf(min_count=5, chunksize=5000, ngrams=(1, 1), model_dir='../models') elif args.action == 'cluster': cluster() elif args.action", "parser.add_argument( 'action', choices=['define_concepts', 'update_chartevents', 'create_train_dataset', 'crawl_webpages', 'tfidf_medical_webpages', 'cluster', 'backup', 'restore', 'create_los_dataset'], help='define action", "src.preprocess import * from src.item_preprocessor import * from src.configer import * from src", "help='number of process') parser.add_argument( '-cd', '--concept_dir', default='../data', help='directory to store concept definition') #", "parser = argparse.ArgumentParser() print(Configer.ip_address, Configer.port, Configer.ssh_username, Configer.ssh_password) print(Configer.db_name, Configer.db_username, Configer.db_password) if __name__ ==", "'__main__': parser.add_argument( 'action', choices=['define_concepts', 'update_chartevents', 'create_train_dataset', 'crawl_webpages', 'tfidf_medical_webpages', 'cluster', 'backup', 'restore', 'create_los_dataset'], help='define", "Configer.ssh_username, Configer.ssh_password) print(Configer.db_name, Configer.db_username, Configer.db_password) if __name__ == '__main__': parser.add_argument( 'action', choices=['define_concepts', 'update_chartevents',", "= parser.parse_args() if args.action == 'define_concepts': define_concepts(output_dir=args.concept_dir, processes=args.process) elif args.action == 'update_chartevents': update_chartevents_value(concept_dir=args.concept_dir)", "'create_train_dataset', 'crawl_webpages', 'tfidf_medical_webpages', 'cluster', 'backup', 'restore', 'create_los_dataset'], help='define action for preprocess' ) parser.add_argument('-p',", "Description \"\"\" import logging import argparse from src.preprocess import * from src.item_preprocessor import", "Configer (TYPE): Description \"\"\" import logging import argparse from src.preprocess import * from", "Configer.ssh_password) print(Configer.db_name, Configer.db_username, Configer.db_password) if __name__ == '__main__': parser.add_argument( 'action', choices=['define_concepts', 'update_chartevents', 'create_train_dataset',", "'update_chartevents', 'create_train_dataset', 'crawl_webpages', 'tfidf_medical_webpages', 'cluster', 'backup', 'restore', 'create_los_dataset'], help='define action for preprocess' )", "args.action == 'update_chartevents': update_chartevents_value(concept_dir=args.concept_dir) elif args.action == 'create_train_dataset': create_train_feature_dataset(export_dir=args.export_dir, processes=args.process, concept_dir=args.concept_dir) elif args.action", "== 'update_chartevents': update_chartevents_value(concept_dir=args.concept_dir) elif args.action == 'create_train_dataset': create_train_feature_dataset(export_dir=args.export_dir, processes=args.process, concept_dir=args.concept_dir) elif args.action ==", "argparse.ArgumentParser() print(Configer.ip_address, Configer.port, Configer.ssh_username, Configer.ssh_password) print(Configer.db_name, Configer.db_username, Configer.db_password) if __name__ == '__main__': parser.add_argument(", "tfidf Configer = Configer('setting.ini') logging.basicConfig( # filename='log.log', format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)", "== 'create_train_dataset': create_train_feature_dataset(export_dir=args.export_dir, processes=args.process, concept_dir=args.concept_dir) elif args.action == 'create_los_dataset': create_cvd_los_dataset(export_dir=args.export_dir, concept_dir=args.concept_dir) elif args.action", "TODO: parameters export_dir = '../data/webpages' concept_dir = '../data' crawl_webpages(concept_dir, export_dir) elif args.action ==", "concept_dir=args.concept_dir) elif args.action == 'crawl_webpages': # TODO: parameters export_dir = '../data/webpages' concept_dir =", "args.action == 'crawl_webpages': # TODO: parameters export_dir = '../data/webpages' concept_dir = '../data' crawl_webpages(concept_dir,", "args = parser.parse_args() if args.action == 'define_concepts': define_concepts(output_dir=args.concept_dir, processes=args.process) elif args.action == 'update_chartevents':", "== 'create_los_dataset': create_cvd_los_dataset(export_dir=args.export_dir, concept_dir=args.concept_dir) elif args.action == 'crawl_webpages': # TODO: parameters export_dir =", "import logging import argparse from src.preprocess import * from src.item_preprocessor import * from", "\"\"\" import logging import argparse from src.preprocess import * from src.item_preprocessor import *", "help='directory to store concept definition') # options for create train data parser.add_argument( '-ed',", "'create_train_dataset': create_train_feature_dataset(export_dir=args.export_dir, processes=args.process, concept_dir=args.concept_dir) elif args.action == 'create_los_dataset': create_cvd_los_dataset(export_dir=args.export_dir, concept_dir=args.concept_dir) elif args.action ==", "'backup', 'restore', 'create_los_dataset'], help='define action for preprocess' ) parser.add_argument('-p', '--process', default=2, type=int, help='number", "elif args.action == 'create_los_dataset': create_cvd_los_dataset(export_dir=args.export_dir, concept_dir=args.concept_dir) elif args.action == 'crawl_webpages': # TODO: parameters", "'../data' crawl_webpages(concept_dir, export_dir) elif args.action == 'tfidf_medical_webpages': tfidf.train_tfidf(min_count=5, chunksize=5000, ngrams=(1, 1), model_dir='../models') elif", "process') parser.add_argument( '-cd', '--concept_dir', default='../data', help='directory to store concept definition') # options for", "data parser.add_argument( '-ed', '--export_dir', help='directory to store train data (options for create train", "import tfidf Configer = Configer('setting.ini') logging.basicConfig( # filename='log.log', format='%(asctime)s : %(levelname)s : %(message)s',", "print(Configer.db_name, Configer.db_username, Configer.db_password) if __name__ == '__main__': parser.add_argument( 'action', choices=['define_concepts', 'update_chartevents', 'create_train_dataset', 'crawl_webpages',", "filename='log.log', format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) parser = argparse.ArgumentParser() print(Configer.ip_address, Configer.port, Configer.ssh_username,", "help='define action for preprocess' ) parser.add_argument('-p', '--process', default=2, type=int, help='number of process') parser.add_argument(", "__name__ == '__main__': parser.add_argument( 'action', choices=['define_concepts', 'update_chartevents', 'create_train_dataset', 'crawl_webpages', 'tfidf_medical_webpages', 'cluster', 'backup', 'restore',", "import * from src import tfidf Configer = Configer('setting.ini') logging.basicConfig( # filename='log.log', format='%(asctime)s", "default=2, type=int, help='number of process') parser.add_argument( '-cd', '--concept_dir', default='../data', help='directory to store concept", "export_dir = '../data/webpages' concept_dir = '../data' crawl_webpages(concept_dir, export_dir) elif args.action == 'tfidf_medical_webpages': tfidf.train_tfidf(min_count=5,", "args.action == 'tfidf_medical_webpages': tfidf.train_tfidf(min_count=5, chunksize=5000, ngrams=(1, 1), model_dir='../models') elif args.action == 'cluster': cluster()", "tfidf.train_tfidf(min_count=5, chunksize=5000, ngrams=(1, 1), model_dir='../models') elif args.action == 'cluster': cluster() elif args.action ==", "'tfidf_medical_webpages', 'cluster', 'backup', 'restore', 'create_los_dataset'], help='define action for preprocess' ) parser.add_argument('-p', '--process', default=2,", "= argparse.ArgumentParser() print(Configer.ip_address, Configer.port, Configer.ssh_username, Configer.ssh_password) print(Configer.db_name, Configer.db_username, Configer.db_password) if __name__ == '__main__':", "args.action == 'define_concepts': define_concepts(output_dir=args.concept_dir, processes=args.process) elif args.action == 'update_chartevents': update_chartevents_value(concept_dir=args.concept_dir) elif args.action ==", "choices=['define_concepts', 'update_chartevents', 'create_train_dataset', 'crawl_webpages', 'tfidf_medical_webpages', 'cluster', 'backup', 'restore', 'create_los_dataset'], help='define action for preprocess'", "Attributes: Configer (TYPE): Description \"\"\" import logging import argparse from src.preprocess import *", "(TYPE): Description \"\"\" import logging import argparse from src.preprocess import * from src.item_preprocessor", "logging import argparse from src.preprocess import * from src.item_preprocessor import * from src.configer", "'restore', 'create_los_dataset'], help='define action for preprocess' ) parser.add_argument('-p', '--process', default=2, type=int, help='number of", "train data parser.add_argument( '-ed', '--export_dir', help='directory to store train data (options for create", "update_chartevents_value(concept_dir=args.concept_dir) elif args.action == 'create_train_dataset': create_train_feature_dataset(export_dir=args.export_dir, processes=args.process, concept_dir=args.concept_dir) elif args.action == 'create_los_dataset': create_cvd_los_dataset(export_dir=args.export_dir,", "import argparse from src.preprocess import * from src.item_preprocessor import * from src.configer import", "elif args.action == 'tfidf_medical_webpages': tfidf.train_tfidf(min_count=5, chunksize=5000, ngrams=(1, 1), model_dir='../models') elif args.action == 'cluster':", "== 'tfidf_medical_webpages': tfidf.train_tfidf(min_count=5, chunksize=5000, ngrams=(1, 1), model_dir='../models') elif args.action == 'cluster': cluster() elif", "'update_chartevents': update_chartevents_value(concept_dir=args.concept_dir) elif args.action == 'create_train_dataset': create_train_feature_dataset(export_dir=args.export_dir, processes=args.process, concept_dir=args.concept_dir) elif args.action == 'create_los_dataset':", "definition') # options for create train data parser.add_argument( '-ed', '--export_dir', help='directory to store", "to store train data (options for create train data)') args = parser.parse_args() if", "parser.parse_args() if args.action == 'define_concepts': define_concepts(output_dir=args.concept_dir, processes=args.process) elif args.action == 'update_chartevents': update_chartevents_value(concept_dir=args.concept_dir) elif", "src.item_preprocessor import * from src.configer import * from src import tfidf Configer =", ": %(message)s', level=logging.INFO) parser = argparse.ArgumentParser() print(Configer.ip_address, Configer.port, Configer.ssh_username, Configer.ssh_password) print(Configer.db_name, Configer.db_username, Configer.db_password)", "elif args.action == 'update_chartevents': update_chartevents_value(concept_dir=args.concept_dir) elif args.action == 'create_train_dataset': create_train_feature_dataset(export_dir=args.export_dir, processes=args.process, concept_dir=args.concept_dir) elif", "from src.item_preprocessor import * from src.configer import * from src import tfidf Configer", "elif args.action == 'create_train_dataset': create_train_feature_dataset(export_dir=args.export_dir, processes=args.process, concept_dir=args.concept_dir) elif args.action == 'create_los_dataset': create_cvd_los_dataset(export_dir=args.export_dir, concept_dir=args.concept_dir)", "== 'cluster': cluster() elif args.action == 'backup': backup_merge_data() elif args.action == 'restore': restore_merge_data()", "import * from src.configer import * from src import tfidf Configer = Configer('setting.ini')", "'--concept_dir', default='../data', help='directory to store concept definition') # options for create train data", "import * from src.item_preprocessor import * from src.configer import * from src import", "Configer.db_password) if __name__ == '__main__': parser.add_argument( 'action', choices=['define_concepts', 'update_chartevents', 'create_train_dataset', 'crawl_webpages', 'tfidf_medical_webpages', 'cluster',", "args.action == 'create_train_dataset': create_train_feature_dataset(export_dir=args.export_dir, processes=args.process, concept_dir=args.concept_dir) elif args.action == 'create_los_dataset': create_cvd_los_dataset(export_dir=args.export_dir, concept_dir=args.concept_dir) elif", "model_dir='../models') elif args.action == 'cluster': cluster() elif args.action == 'backup': backup_merge_data() elif args.action", "concept_dir = '../data' crawl_webpages(concept_dir, export_dir) elif args.action == 'tfidf_medical_webpages': tfidf.train_tfidf(min_count=5, chunksize=5000, ngrams=(1, 1),", "create train data parser.add_argument( '-ed', '--export_dir', help='directory to store train data (options for", "define_concepts(output_dir=args.concept_dir, processes=args.process) elif args.action == 'update_chartevents': update_chartevents_value(concept_dir=args.concept_dir) elif args.action == 'create_train_dataset': create_train_feature_dataset(export_dir=args.export_dir, processes=args.process,", "src import tfidf Configer = Configer('setting.ini') logging.basicConfig( # filename='log.log', format='%(asctime)s : %(levelname)s :", "= '../data/webpages' concept_dir = '../data' crawl_webpages(concept_dir, export_dir) elif args.action == 'tfidf_medical_webpages': tfidf.train_tfidf(min_count=5, chunksize=5000,", "'../data/webpages' concept_dir = '../data' crawl_webpages(concept_dir, export_dir) elif args.action == 'tfidf_medical_webpages': tfidf.train_tfidf(min_count=5, chunksize=5000, ngrams=(1,", "* from src import tfidf Configer = Configer('setting.ini') logging.basicConfig( # filename='log.log', format='%(asctime)s :", "for create train data)') args = parser.parse_args() if args.action == 'define_concepts': define_concepts(output_dir=args.concept_dir, processes=args.process)", "\"\"\"Summary Attributes: Configer (TYPE): Description \"\"\" import logging import argparse from src.preprocess import", "default='../data', help='directory to store concept definition') # options for create train data parser.add_argument(", "elif args.action == 'cluster': cluster() elif args.action == 'backup': backup_merge_data() elif args.action ==", "train data (options for create train data)') args = parser.parse_args() if args.action ==", "# TODO: parameters export_dir = '../data/webpages' concept_dir = '../data' crawl_webpages(concept_dir, export_dir) elif args.action", "(options for create train data)') args = parser.parse_args() if args.action == 'define_concepts': define_concepts(output_dir=args.concept_dir,", "chunksize=5000, ngrams=(1, 1), model_dir='../models') elif args.action == 'cluster': cluster() elif args.action == 'backup':", "from src.preprocess import * from src.item_preprocessor import * from src.configer import * from", "= Configer('setting.ini') logging.basicConfig( # filename='log.log', format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) parser =", "to store concept definition') # options for create train data parser.add_argument( '-ed', '--export_dir',", "# options for create train data parser.add_argument( '-ed', '--export_dir', help='directory to store train", "== 'crawl_webpages': # TODO: parameters export_dir = '../data/webpages' concept_dir = '../data' crawl_webpages(concept_dir, export_dir)", "export_dir) elif args.action == 'tfidf_medical_webpages': tfidf.train_tfidf(min_count=5, chunksize=5000, ngrams=(1, 1), model_dir='../models') elif args.action ==", "Configer.port, Configer.ssh_username, Configer.ssh_password) print(Configer.db_name, Configer.db_username, Configer.db_password) if __name__ == '__main__': parser.add_argument( 'action', choices=['define_concepts',", "Configer.db_username, Configer.db_password) if __name__ == '__main__': parser.add_argument( 'action', choices=['define_concepts', 'update_chartevents', 'create_train_dataset', 'crawl_webpages', 'tfidf_medical_webpages',", "parser.add_argument('-p', '--process', default=2, type=int, help='number of process') parser.add_argument( '-cd', '--concept_dir', default='../data', help='directory to", "%(levelname)s : %(message)s', level=logging.INFO) parser = argparse.ArgumentParser() print(Configer.ip_address, Configer.port, Configer.ssh_username, Configer.ssh_password) print(Configer.db_name, Configer.db_username,", "of process') parser.add_argument( '-cd', '--concept_dir', default='../data', help='directory to store concept definition') # options", ") parser.add_argument('-p', '--process', default=2, type=int, help='number of process') parser.add_argument( '-cd', '--concept_dir', default='../data', help='directory" ]
[ "element of the array to the key. \"\"\" def linear_search(array, key): len_array =", "in the array.\".format(key)) array = list(map(int, input(\"Enter elements of array separated by space:", "{} in the array.\".format(key, t)) else: print(\"{} not present in the array.\".format(key)) array", "def linear_search(array, key): len_array = len(array) t = None for i in range(len_array):", "to the key. \"\"\" def linear_search(array, key): len_array = len(array) t = None", "\"\"\" def linear_search(array, key): len_array = len(array) t = None for i in", "position {} in the array.\".format(key, t)) else: print(\"{} not present in the array.\".format(key))", "== key: t = i else: pass if t != None: print(\"Found {}", "len(array) t = None for i in range(len_array): if array[i] == key: t", "implements linear search algorithms having a time complexity of O[n]. It compares every", "It compares every element of the array to the key. \"\"\" def linear_search(array,", "in the array.\".format(key, t)) else: print(\"{} not present in the array.\".format(key)) array =", "key): len_array = len(array) t = None for i in range(len_array): if array[i]", "print(\"{} not present in the array.\".format(key)) array = list(map(int, input(\"Enter elements of array", "program implements linear search algorithms having a time complexity of O[n]. It compares", "of array separated by space: \").split())) key = input(\"Enter element to find: \")", "array to the key. \"\"\" def linear_search(array, key): len_array = len(array) t =", "else: pass if t != None: print(\"Found {} at position {} in the", "the array to the key. \"\"\" def linear_search(array, key): len_array = len(array) t", "array = list(map(int, input(\"Enter elements of array separated by space: \").split())) key =", "list(map(int, input(\"Enter elements of array separated by space: \").split())) key = input(\"Enter element", "of the array to the key. \"\"\" def linear_search(array, key): len_array = len(array)", "t = None for i in range(len_array): if array[i] == key: t =", "array separated by space: \").split())) key = input(\"Enter element to find: \") linear_search(array,", "of O[n]. It compares every element of the array to the key. \"\"\"", "i in range(len_array): if array[i] == key: t = i else: pass if", "pass if t != None: print(\"Found {} at position {} in the array.\".format(key,", "not present in the array.\".format(key)) array = list(map(int, input(\"Enter elements of array separated", "len_array = len(array) t = None for i in range(len_array): if array[i] ==", "t)) else: print(\"{} not present in the array.\".format(key)) array = list(map(int, input(\"Enter elements", "complexity of O[n]. It compares every element of the array to the key.", "the array.\".format(key)) array = list(map(int, input(\"Enter elements of array separated by space: \").split()))", "array.\".format(key)) array = list(map(int, input(\"Enter elements of array separated by space: \").split())) key", "None for i in range(len_array): if array[i] == key: t = i else:", "key: t = i else: pass if t != None: print(\"Found {} at", "{} at position {} in the array.\".format(key, t)) else: print(\"{} not present in", "if array[i] == key: t = i else: pass if t != None:", "present in the array.\".format(key)) array = list(map(int, input(\"Enter elements of array separated by", "t = i else: pass if t != None: print(\"Found {} at position", "compares every element of the array to the key. \"\"\" def linear_search(array, key):", "time complexity of O[n]. It compares every element of the array to the", "O[n]. It compares every element of the array to the key. \"\"\" def", "the array.\".format(key, t)) else: print(\"{} not present in the array.\".format(key)) array = list(map(int,", "key. \"\"\" def linear_search(array, key): len_array = len(array) t = None for i", "array.\".format(key, t)) else: print(\"{} not present in the array.\".format(key)) array = list(map(int, input(\"Enter", "in range(len_array): if array[i] == key: t = i else: pass if t", "search algorithms having a time complexity of O[n]. It compares every element of", "separated by space: \").split())) key = input(\"Enter element to find: \") linear_search(array, key)", "if t != None: print(\"Found {} at position {} in the array.\".format(key, t))", "else: print(\"{} not present in the array.\".format(key)) array = list(map(int, input(\"Enter elements of", "= None for i in range(len_array): if array[i] == key: t = i", "having a time complexity of O[n]. It compares every element of the array", "a time complexity of O[n]. It compares every element of the array to", "linear search algorithms having a time complexity of O[n]. It compares every element", "\"\"\"This program implements linear search algorithms having a time complexity of O[n]. It", "= len(array) t = None for i in range(len_array): if array[i] == key:", "the key. \"\"\" def linear_search(array, key): len_array = len(array) t = None for", "i else: pass if t != None: print(\"Found {} at position {} in", "= list(map(int, input(\"Enter elements of array separated by space: \").split())) key = input(\"Enter", "elements of array separated by space: \").split())) key = input(\"Enter element to find:", "for i in range(len_array): if array[i] == key: t = i else: pass", "print(\"Found {} at position {} in the array.\".format(key, t)) else: print(\"{} not present", "linear_search(array, key): len_array = len(array) t = None for i in range(len_array): if", "algorithms having a time complexity of O[n]. It compares every element of the", "!= None: print(\"Found {} at position {} in the array.\".format(key, t)) else: print(\"{}", "every element of the array to the key. \"\"\" def linear_search(array, key): len_array", "input(\"Enter elements of array separated by space: \").split())) key = input(\"Enter element to", "= i else: pass if t != None: print(\"Found {} at position {}", "array[i] == key: t = i else: pass if t != None: print(\"Found", "None: print(\"Found {} at position {} in the array.\".format(key, t)) else: print(\"{} not", "range(len_array): if array[i] == key: t = i else: pass if t !=", "at position {} in the array.\".format(key, t)) else: print(\"{} not present in the", "t != None: print(\"Found {} at position {} in the array.\".format(key, t)) else:" ]
[ "input length input_lengths, ids_sorted_decreasing = torch.sort( torch.LongTensor([len(x[0]) for x in batch]), dim=0, descending=True)", ":text.size(0)] = text # Right zero-pad mel-spec num_mels = batch[0][1].size(0) max_target_len = max([x[1].size(1)", "self.get_mel(audiopath) if speaker_id is not None: speaker_id = self.get_speaker_id(speaker_id) return text, mel, speaker_id", "self.n_frames_per_step == 0 # include mel padded and gate padded mel_padded = torch.FloatTensor(len(batch),", "{}'.format( melspec.size(0), self.stft.n_mel_channels)) return melspec def get_text(self, text: str) -> torch.IntTensor: text_norm =", "audio_norm = audio_norm.clone().detach() melspec = self.stft.mel_spectrogram(audio_norm) melspec = torch.squeeze(melspec, 0) else: melspec =", "= self.create_speaker_lookup_table(self.audiopaths_and_text) def get_data_sample(self, audiopath_and_text: List) -> Tuple[torch.IntTensor, torch.Tensor, torch.Tensor]: # separate filename", "typing import List, Tuple import torch import numpy as np import torch.utils.data from", "return text_norm def get_speaker_id(self, speaker_id) -> torch.Tensor: return torch.LongTensor([self.speaker_ids[int(speaker_id)]]) def __getitem__(self, index: int):", "[text_normalized, mel_normalized] \"\"\" # Right zero-pad all one-hot text sequences to max input", "in range(len(ids_sorted_decreasing)): text = batch[ids_sorted_decreasing[i]][0] text_padded[i, :text.size(0)] = text # Right zero-pad mel-spec", "mel gate_padded[i, mel.size(1) - 1:] = 1 output_lengths[i] = mel.size(1) if use_speaker_embedding: speaker_ids[i]", "use_speaker_embedding = batch[0][2] is not None if use_speaker_embedding: speaker_ids = torch.LongTensor(len(batch)) else: speaker_ids", "= self.stft.mel_spectrogram(audio_norm) melspec = torch.squeeze(melspec, 0) else: melspec = torch.from_numpy(np.load(filename)) assert melspec.size(0) ==", "torch.FloatTensor(len(batch), num_mels, max_target_len) mel_padded.zero_() gate_padded = torch.FloatTensor(len(batch), max_target_len) gate_padded.zero_() output_lengths = torch.LongTensor(len(batch)) use_speaker_embedding", "text_to_sequence from tacotron2_gst.utils import load_filepaths_and_text from tacotron2_gst.audio_processing import load_wav_to_torch class TextMelLoader(torch.utils.data.Dataset): \"\"\" 1)", "get_text(self, text: str) -> torch.IntTensor: text_norm = torch.IntTensor(text_to_sequence(text, self.text_cleaners)) return text_norm def get_speaker_id(self,", "audiopaths_and_text: str, hparams): self.audiopaths_and_text = load_filepaths_and_text(audiopaths_and_text) self.text_cleaners = hparams.data.text_cleaners self.max_wav_value = hparams.data.max_wav_value self.sampling_rate", "= torch.from_numpy(np.load(filename)) assert melspec.size(0) == self.stft.n_mel_channels, ( 'Mel dimension mismatch: given {}, expected", "output_lengths[i] = mel.size(1) if use_speaker_embedding: speaker_ids[i] = batch[ids_sorted_decreasing[i]][2] return text_padded, input_lengths, mel_padded, speaker_ids,", "SR\".format( sampling_rate, self.stft.sampling_rate)) audio_norm = audio / self.max_wav_value audio_norm = audio_norm.unsqueeze(0) audio_norm =", "\"\"\" import random from typing import List, Tuple import torch import numpy as", "def get_text(self, text: str) -> torch.IntTensor: text_norm = torch.IntTensor(text_to_sequence(text, self.text_cleaners)) return text_norm def", "from tacotron2_gst.text import text_to_sequence from tacotron2_gst.utils import load_filepaths_and_text from tacotron2_gst.audio_processing import load_wav_to_torch class", "torch.Tensor, torch.Tensor]: # separate filename and text audiopath, text = audiopath_and_text[0], audiopath_and_text[1] speaker_id", "layers.TacotronSTFT( hparams.data.filter_length, hparams.data.hop_length, hparams.data.win_length, hparams.data.n_mel_channels, hparams.data.sampling_rate, hparams.data.mel_fmin, hparams.data.mel_fmax) random.seed(1234) random.shuffle(self.audiopaths_and_text) self.use_speaker_embedding = hparams.use_speaker_embedding", "max input length input_lengths, ids_sorted_decreasing = torch.sort( torch.LongTensor([len(x[0]) for x in batch]), dim=0,", ":\", len(d)) return d def get_mel(self, filename: str) -> torch.Tensor: if not self.load_mel_from_disk:", "to max input length input_lengths, ids_sorted_decreasing = torch.sort( torch.LongTensor([len(x[0]) for x in batch]),", "assert melspec.size(0) == self.stft.n_mel_channels, ( 'Mel dimension mismatch: given {}, expected {}'.format( melspec.size(0),", "= batch[ids_sorted_decreasing[i]][0] text_padded[i, :text.size(0)] = text # Right zero-pad mel-spec num_mels = batch[0][1].size(0)", "speaker_ids = torch.LongTensor(len(batch)) else: speaker_ids = None for i in range(len(ids_sorted_decreasing)): mel =", "import text_to_sequence from tacotron2_gst.utils import load_filepaths_and_text from tacotron2_gst.audio_processing import load_wav_to_torch class TextMelLoader(torch.utils.data.Dataset): \"\"\"", "from tacotron2_gst.utils import load_filepaths_and_text from tacotron2_gst.audio_processing import load_wav_to_torch class TextMelLoader(torch.utils.data.Dataset): \"\"\" 1) loads", "= None if self.use_speaker_embedding: speaker_id = audiopath_and_text[2] text = self.get_text(text) mel = self.get_mel(audiopath)", "------ batch: [text_normalized, mel_normalized] \"\"\" # Right zero-pad all one-hot text sequences to", "index: int): return self.get_data_sample(self.audiopaths_and_text[index]) def __len__(self): return len(self.audiopaths_and_text) class TextMelCollate(): \"\"\" Zero-pads model", "self.n_frames_per_step != 0: max_target_len += self.n_frames_per_step - max_target_len % self.n_frames_per_step assert max_target_len %", "text = self.get_text(text) mel = self.get_mel(audiopath) if speaker_id is not None: speaker_id =", "- max_target_len % self.n_frames_per_step assert max_target_len % self.n_frames_per_step == 0 # include mel", "( 'Mel dimension mismatch: given {}, expected {}'.format( melspec.size(0), self.stft.n_mel_channels)) return melspec def", "all one-hot text sequences to max input length input_lengths, ids_sorted_decreasing = torch.sort( torch.LongTensor([len(x[0])", "% self.n_frames_per_step == 0 # include mel padded and gate padded mel_padded =", "= torch.LongTensor(len(batch), max_input_len) text_padded.zero_() for i in range(len(ids_sorted_decreasing)): text = batch[ids_sorted_decreasing[i]][0] text_padded[i, :text.size(0)]", "Tuple import torch import numpy as np import torch.utils.data from tacotron2_gst import layers", "= load_filepaths_and_text(audiopaths_and_text) self.text_cleaners = hparams.data.text_cleaners self.max_wav_value = hparams.data.max_wav_value self.sampling_rate = hparams.data.sampling_rate self.load_mel_from_disk =", "include mel padded and gate padded mel_padded = torch.FloatTensor(len(batch), num_mels, max_target_len) mel_padded.zero_() gate_padded", "speaker_id = self.get_speaker_id(speaker_id) return text, mel, speaker_id def create_speaker_lookup_table(self, audiopaths_and_text): speaker_ids = np.sort(np.unique([x[2]", "create_speaker_lookup_table(self, audiopaths_and_text): speaker_ids = np.sort(np.unique([x[2] for x in audiopaths_and_text])) d = {int(speaker_ids[i]): i", "self.stft.n_mel_channels, ( 'Mel dimension mismatch: given {}, expected {}'.format( melspec.size(0), self.stft.n_mel_channels)) return melspec", "hparams.data.hop_length, hparams.data.win_length, hparams.data.n_mel_channels, hparams.data.sampling_rate, hparams.data.mel_fmin, hparams.data.mel_fmax) random.seed(1234) random.shuffle(self.audiopaths_and_text) self.use_speaker_embedding = hparams.use_speaker_embedding if self.use_speaker_embedding:", "sampling_rate = load_wav_to_torch(filename) if sampling_rate != self.stft.sampling_rate: raise ValueError(\"{} SR doesn't match target", "Zero-pads model inputs and targets based on number of frames per setep \"\"\"", "audiopath_and_text[0], audiopath_and_text[1] speaker_id = None if self.use_speaker_embedding: speaker_id = audiopath_and_text[2] text = self.get_text(text)", "PARAMS ------ batch: [text_normalized, mel_normalized] \"\"\" # Right zero-pad all one-hot text sequences", "of speakers :\", len(d)) return d def get_mel(self, filename: str) -> torch.Tensor: if", "max_target_len) gate_padded.zero_() output_lengths = torch.LongTensor(len(batch)) use_speaker_embedding = batch[0][2] is not None if use_speaker_embedding:", "= torch.sort( torch.LongTensor([len(x[0]) for x in batch]), dim=0, descending=True) max_input_len = input_lengths[0] text_padded", "!= self.stft.sampling_rate: raise ValueError(\"{} SR doesn't match target {} SR\".format( sampling_rate, self.stft.sampling_rate)) audio_norm", "audiopaths_and_text])) d = {int(speaker_ids[i]): i for i in range(len(speaker_ids))} print(\"Number of speakers :\",", "i in range(len(ids_sorted_decreasing)): mel = batch[ids_sorted_decreasing[i]][1] mel_padded[i, :, :mel.size(1)] = mel gate_padded[i, mel.size(1)", "based on number of frames per setep \"\"\" def __init__(self, n_frames_per_step: int): self.n_frames_per_step", "torch.LongTensor(len(batch), max_input_len) text_padded.zero_() for i in range(len(ids_sorted_decreasing)): text = batch[ids_sorted_decreasing[i]][0] text_padded[i, :text.size(0)] =", "batch]) if max_target_len % self.n_frames_per_step != 0: max_target_len += self.n_frames_per_step - max_target_len %", "torch.IntTensor(text_to_sequence(text, self.text_cleaners)) return text_norm def get_speaker_id(self, speaker_id) -> torch.Tensor: return torch.LongTensor([self.speaker_ids[int(speaker_id)]]) def __getitem__(self,", "computes mel-spectrograms from audio files. \"\"\" def __init__(self, audiopaths_and_text: str, hparams): self.audiopaths_and_text =", "def __call__(self, batch): \"\"\"Collate's training batch from normalized text and mel-spectrogram PARAMS ------", "self.load_mel_from_disk: audio, sampling_rate = load_wav_to_torch(filename) if sampling_rate != self.stft.sampling_rate: raise ValueError(\"{} SR doesn't", "melspec.size(0) == self.stft.n_mel_channels, ( 'Mel dimension mismatch: given {}, expected {}'.format( melspec.size(0), self.stft.n_mel_channels))", "self.use_speaker_embedding: speaker_id = audiopath_and_text[2] text = self.get_text(text) mel = self.get_mel(audiopath) if speaker_id is", "torch.LongTensor(len(batch)) use_speaker_embedding = batch[0][2] is not None if use_speaker_embedding: speaker_ids = torch.LongTensor(len(batch)) else:", "mel-spectrogram PARAMS ------ batch: [text_normalized, mel_normalized] \"\"\" # Right zero-pad all one-hot text", "for x in batch]) if max_target_len % self.n_frames_per_step != 0: max_target_len += self.n_frames_per_step", "https://github.com/mozilla/TTS \"\"\" import random from typing import List, Tuple import torch import numpy", "padded mel_padded = torch.FloatTensor(len(batch), num_mels, max_target_len) mel_padded.zero_() gate_padded = torch.FloatTensor(len(batch), max_target_len) gate_padded.zero_() output_lengths", "melspec = torch.squeeze(melspec, 0) else: melspec = torch.from_numpy(np.load(filename)) assert melspec.size(0) == self.stft.n_mel_channels, (", "self.n_frames_per_step = n_frames_per_step def __call__(self, batch): \"\"\"Collate's training batch from normalized text and", "training batch from normalized text and mel-spectrogram PARAMS ------ batch: [text_normalized, mel_normalized] \"\"\"", "mel-spectrograms from audio files. \"\"\" def __init__(self, audiopaths_and_text: str, hparams): self.audiopaths_and_text = load_filepaths_and_text(audiopaths_and_text)", "audio_norm.unsqueeze(0) audio_norm = audio_norm.clone().detach() melspec = self.stft.mel_spectrogram(audio_norm) melspec = torch.squeeze(melspec, 0) else: melspec", "else: melspec = torch.from_numpy(np.load(filename)) assert melspec.size(0) == self.stft.n_mel_channels, ( 'Mel dimension mismatch: given", "= audiopath_and_text[0], audiopath_and_text[1] speaker_id = None if self.use_speaker_embedding: speaker_id = audiopath_and_text[2] text =", "torch.LongTensor(len(batch)) else: speaker_ids = None for i in range(len(ids_sorted_decreasing)): mel = batch[ids_sorted_decreasing[i]][1] mel_padded[i,", "{int(speaker_ids[i]): i for i in range(len(speaker_ids))} print(\"Number of speakers :\", len(d)) return d", "n_frames_per_step: int): self.n_frames_per_step = n_frames_per_step def __call__(self, batch): \"\"\"Collate's training batch from normalized", "audio, sampling_rate = load_wav_to_torch(filename) if sampling_rate != self.stft.sampling_rate: raise ValueError(\"{} SR doesn't match", "zero-pad mel-spec num_mels = batch[0][1].size(0) max_target_len = max([x[1].size(1) for x in batch]) if", "+= self.n_frames_per_step - max_target_len % self.n_frames_per_step assert max_target_len % self.n_frames_per_step == 0 #", "None for i in range(len(ids_sorted_decreasing)): mel = batch[ids_sorted_decreasing[i]][1] mel_padded[i, :, :mel.size(1)] = mel", "text = batch[ids_sorted_decreasing[i]][0] text_padded[i, :text.size(0)] = text # Right zero-pad mel-spec num_mels =", "None: speaker_id = self.get_speaker_id(speaker_id) return text, mel, speaker_id def create_speaker_lookup_table(self, audiopaths_and_text): speaker_ids =", "= torch.FloatTensor(len(batch), max_target_len) gate_padded.zero_() output_lengths = torch.LongTensor(len(batch)) use_speaker_embedding = batch[0][2] is not None", "max_target_len % self.n_frames_per_step == 0 # include mel padded and gate padded mel_padded", "- https://github.com/mozilla/TTS \"\"\" import random from typing import List, Tuple import torch import", "zero-pad all one-hot text sequences to max input length input_lengths, ids_sorted_decreasing = torch.sort(", "% self.n_frames_per_step != 0: max_target_len += self.n_frames_per_step - max_target_len % self.n_frames_per_step assert max_target_len", "audio_norm.clone().detach() melspec = self.stft.mel_spectrogram(audio_norm) melspec = torch.squeeze(melspec, 0) else: melspec = torch.from_numpy(np.load(filename)) assert", "= batch[0][2] is not None if use_speaker_embedding: speaker_ids = torch.LongTensor(len(batch)) else: speaker_ids =", "layers from tacotron2_gst.text import text_to_sequence from tacotron2_gst.utils import load_filepaths_and_text from tacotron2_gst.audio_processing import load_wav_to_torch", "{} SR\".format( sampling_rate, self.stft.sampling_rate)) audio_norm = audio / self.max_wav_value audio_norm = audio_norm.unsqueeze(0) audio_norm", "tacotron2_gst.text import text_to_sequence from tacotron2_gst.utils import load_filepaths_and_text from tacotron2_gst.audio_processing import load_wav_to_torch class TextMelLoader(torch.utils.data.Dataset):", "torch import numpy as np import torch.utils.data from tacotron2_gst import layers from tacotron2_gst.text", "i for i in range(len(speaker_ids))} print(\"Number of speakers :\", len(d)) return d def", "melspec def get_text(self, text: str) -> torch.IntTensor: text_norm = torch.IntTensor(text_to_sequence(text, self.text_cleaners)) return text_norm", "None if self.use_speaker_embedding: speaker_id = audiopath_and_text[2] text = self.get_text(text) mel = self.get_mel(audiopath) if", "mel_padded = torch.FloatTensor(len(batch), num_mels, max_target_len) mel_padded.zero_() gate_padded = torch.FloatTensor(len(batch), max_target_len) gate_padded.zero_() output_lengths =", "gate_padded[i, mel.size(1) - 1:] = 1 output_lengths[i] = mel.size(1) if use_speaker_embedding: speaker_ids[i] =", "gate_padded.zero_() output_lengths = torch.LongTensor(len(batch)) use_speaker_embedding = batch[0][2] is not None if use_speaker_embedding: speaker_ids", "gate_padded = torch.FloatTensor(len(batch), max_target_len) gate_padded.zero_() output_lengths = torch.LongTensor(len(batch)) use_speaker_embedding = batch[0][2] is not", "text_norm def get_speaker_id(self, speaker_id) -> torch.Tensor: return torch.LongTensor([self.speaker_ids[int(speaker_id)]]) def __getitem__(self, index: int): return", "frames per setep \"\"\" def __init__(self, n_frames_per_step: int): self.n_frames_per_step = n_frames_per_step def __call__(self,", "return torch.LongTensor([self.speaker_ids[int(speaker_id)]]) def __getitem__(self, index: int): return self.get_data_sample(self.audiopaths_and_text[index]) def __len__(self): return len(self.audiopaths_and_text) class", "in range(len(ids_sorted_decreasing)): mel = batch[ids_sorted_decreasing[i]][1] mel_padded[i, :, :mel.size(1)] = mel gate_padded[i, mel.size(1) -", "def __init__(self, n_frames_per_step: int): self.n_frames_per_step = n_frames_per_step def __call__(self, batch): \"\"\"Collate's training batch", "sampling_rate != self.stft.sampling_rate: raise ValueError(\"{} SR doesn't match target {} SR\".format( sampling_rate, self.stft.sampling_rate))", "speaker_id) -> torch.Tensor: return torch.LongTensor([self.speaker_ids[int(speaker_id)]]) def __getitem__(self, index: int): return self.get_data_sample(self.audiopaths_and_text[index]) def __len__(self):", "mel.size(1) - 1:] = 1 output_lengths[i] = mel.size(1) if use_speaker_embedding: speaker_ids[i] = batch[ids_sorted_decreasing[i]][2]", "import load_filepaths_and_text from tacotron2_gst.audio_processing import load_wav_to_torch class TextMelLoader(torch.utils.data.Dataset): \"\"\" 1) loads audio,text pairs", "speaker_ids = np.sort(np.unique([x[2] for x in audiopaths_and_text])) d = {int(speaker_ids[i]): i for i", "\"\"\" Adapted from: - https://github.com/NVIDIA/tacotron2 - https://github.com/mozilla/TTS \"\"\" import random from typing import", "1:] = 1 output_lengths[i] = mel.size(1) if use_speaker_embedding: speaker_ids[i] = batch[ids_sorted_decreasing[i]][2] return text_padded,", "audio files. \"\"\" def __init__(self, audiopaths_and_text: str, hparams): self.audiopaths_and_text = load_filepaths_and_text(audiopaths_and_text) self.text_cleaners =", "x in batch]) if max_target_len % self.n_frames_per_step != 0: max_target_len += self.n_frames_per_step -", "/ self.max_wav_value audio_norm = audio_norm.unsqueeze(0) audio_norm = audio_norm.clone().detach() melspec = self.stft.mel_spectrogram(audio_norm) melspec =", "text # Right zero-pad mel-spec num_mels = batch[0][1].size(0) max_target_len = max([x[1].size(1) for x", "= load_wav_to_torch(filename) if sampling_rate != self.stft.sampling_rate: raise ValueError(\"{} SR doesn't match target {}", "torch.Tensor: if not self.load_mel_from_disk: audio, sampling_rate = load_wav_to_torch(filename) if sampling_rate != self.stft.sampling_rate: raise", "random.shuffle(self.audiopaths_and_text) self.use_speaker_embedding = hparams.use_speaker_embedding if self.use_speaker_embedding: self.speaker_ids = self.create_speaker_lookup_table(self.audiopaths_and_text) def get_data_sample(self, audiopath_and_text: List)", "from tacotron2_gst import layers from tacotron2_gst.text import text_to_sequence from tacotron2_gst.utils import load_filepaths_and_text from", "self.use_speaker_embedding: self.speaker_ids = self.create_speaker_lookup_table(self.audiopaths_and_text) def get_data_sample(self, audiopath_and_text: List) -> Tuple[torch.IntTensor, torch.Tensor, torch.Tensor]: #", "text_padded.zero_() for i in range(len(ids_sorted_decreasing)): text = batch[ids_sorted_decreasing[i]][0] text_padded[i, :text.size(0)] = text #", "get_mel(self, filename: str) -> torch.Tensor: if not self.load_mel_from_disk: audio, sampling_rate = load_wav_to_torch(filename) if", "= audio_norm.clone().detach() melspec = self.stft.mel_spectrogram(audio_norm) melspec = torch.squeeze(melspec, 0) else: melspec = torch.from_numpy(np.load(filename))", "and text audiopath, text = audiopath_and_text[0], audiopath_and_text[1] speaker_id = None if self.use_speaker_embedding: speaker_id", "\"\"\" 1) loads audio,text pairs 2) normalizes text and converts them to sequences", "= torch.LongTensor(len(batch)) use_speaker_embedding = batch[0][2] is not None if use_speaker_embedding: speaker_ids = torch.LongTensor(len(batch))", "print(\"Number of speakers :\", len(d)) return d def get_mel(self, filename: str) -> torch.Tensor:", "= {int(speaker_ids[i]): i for i in range(len(speaker_ids))} print(\"Number of speakers :\", len(d)) return", "given {}, expected {}'.format( melspec.size(0), self.stft.n_mel_channels)) return melspec def get_text(self, text: str) ->", "self.stft.mel_spectrogram(audio_norm) melspec = torch.squeeze(melspec, 0) else: melspec = torch.from_numpy(np.load(filename)) assert melspec.size(0) == self.stft.n_mel_channels,", "{}, expected {}'.format( melspec.size(0), self.stft.n_mel_channels)) return melspec def get_text(self, text: str) -> torch.IntTensor:", "not None if use_speaker_embedding: speaker_ids = torch.LongTensor(len(batch)) else: speaker_ids = None for i", "== self.stft.n_mel_channels, ( 'Mel dimension mismatch: given {}, expected {}'.format( melspec.size(0), self.stft.n_mel_channels)) return", "self.max_wav_value audio_norm = audio_norm.unsqueeze(0) audio_norm = audio_norm.clone().detach() melspec = self.stft.mel_spectrogram(audio_norm) melspec = torch.squeeze(melspec,", "mismatch: given {}, expected {}'.format( melspec.size(0), self.stft.n_mel_channels)) return melspec def get_text(self, text: str)", "mel_normalized] \"\"\" # Right zero-pad all one-hot text sequences to max input length", "max_target_len) mel_padded.zero_() gate_padded = torch.FloatTensor(len(batch), max_target_len) gate_padded.zero_() output_lengths = torch.LongTensor(len(batch)) use_speaker_embedding = batch[0][2]", "loads audio,text pairs 2) normalizes text and converts them to sequences of one-hot", "load_wav_to_torch(filename) if sampling_rate != self.stft.sampling_rate: raise ValueError(\"{} SR doesn't match target {} SR\".format(", "audiopath_and_text[1] speaker_id = None if self.use_speaker_embedding: speaker_id = audiopath_and_text[2] text = self.get_text(text) mel", "self.load_mel_from_disk = hparams.data.load_mel_from_disk self.stft = layers.TacotronSTFT( hparams.data.filter_length, hparams.data.hop_length, hparams.data.win_length, hparams.data.n_mel_channels, hparams.data.sampling_rate, hparams.data.mel_fmin, hparams.data.mel_fmax)", "# Right zero-pad mel-spec num_mels = batch[0][1].size(0) max_target_len = max([x[1].size(1) for x in", "= input_lengths[0] text_padded = torch.LongTensor(len(batch), max_input_len) text_padded.zero_() for i in range(len(ids_sorted_decreasing)): text =", "import load_wav_to_torch class TextMelLoader(torch.utils.data.Dataset): \"\"\" 1) loads audio,text pairs 2) normalizes text and", "not None: speaker_id = self.get_speaker_id(speaker_id) return text, mel, speaker_id def create_speaker_lookup_table(self, audiopaths_and_text): speaker_ids", "raise ValueError(\"{} SR doesn't match target {} SR\".format( sampling_rate, self.stft.sampling_rate)) audio_norm = audio", "num_mels, max_target_len) mel_padded.zero_() gate_padded = torch.FloatTensor(len(batch), max_target_len) gate_padded.zero_() output_lengths = torch.LongTensor(len(batch)) use_speaker_embedding =", "= torch.LongTensor(len(batch)) else: speaker_ids = None for i in range(len(ids_sorted_decreasing)): mel = batch[ids_sorted_decreasing[i]][1]", "speaker_ids = None for i in range(len(ids_sorted_decreasing)): mel = batch[ids_sorted_decreasing[i]][1] mel_padded[i, :, :mel.size(1)]", "= np.sort(np.unique([x[2] for x in audiopaths_and_text])) d = {int(speaker_ids[i]): i for i in", "= audio / self.max_wav_value audio_norm = audio_norm.unsqueeze(0) audio_norm = audio_norm.clone().detach() melspec = self.stft.mel_spectrogram(audio_norm)", "import random from typing import List, Tuple import torch import numpy as np", "else: speaker_ids = None for i in range(len(ids_sorted_decreasing)): mel = batch[ids_sorted_decreasing[i]][1] mel_padded[i, :,", "= hparams.data.max_wav_value self.sampling_rate = hparams.data.sampling_rate self.load_mel_from_disk = hparams.data.load_mel_from_disk self.stft = layers.TacotronSTFT( hparams.data.filter_length, hparams.data.hop_length,", "def __getitem__(self, index: int): return self.get_data_sample(self.audiopaths_and_text[index]) def __len__(self): return len(self.audiopaths_and_text) class TextMelCollate(): \"\"\"", "max_target_len % self.n_frames_per_step != 0: max_target_len += self.n_frames_per_step - max_target_len % self.n_frames_per_step assert", "if speaker_id is not None: speaker_id = self.get_speaker_id(speaker_id) return text, mel, speaker_id def", "from normalized text and mel-spectrogram PARAMS ------ batch: [text_normalized, mel_normalized] \"\"\" # Right", "text and mel-spectrogram PARAMS ------ batch: [text_normalized, mel_normalized] \"\"\" # Right zero-pad all", "import List, Tuple import torch import numpy as np import torch.utils.data from tacotron2_gst", "= audiopath_and_text[2] text = self.get_text(text) mel = self.get_mel(audiopath) if speaker_id is not None:", "text_padded[i, :text.size(0)] = text # Right zero-pad mel-spec num_mels = batch[0][1].size(0) max_target_len =", "torch.FloatTensor(len(batch), max_target_len) gate_padded.zero_() output_lengths = torch.LongTensor(len(batch)) use_speaker_embedding = batch[0][2] is not None if", "= batch[ids_sorted_decreasing[i]][1] mel_padded[i, :, :mel.size(1)] = mel gate_padded[i, mel.size(1) - 1:] = 1", "max([x[1].size(1) for x in batch]) if max_target_len % self.n_frames_per_step != 0: max_target_len +=", "match target {} SR\".format( sampling_rate, self.stft.sampling_rate)) audio_norm = audio / self.max_wav_value audio_norm =", "self.n_frames_per_step - max_target_len % self.n_frames_per_step assert max_target_len % self.n_frames_per_step == 0 # include", "audiopaths_and_text): speaker_ids = np.sort(np.unique([x[2] for x in audiopaths_and_text])) d = {int(speaker_ids[i]): i for", "= batch[0][1].size(0) max_target_len = max([x[1].size(1) for x in batch]) if max_target_len % self.n_frames_per_step", "-> Tuple[torch.IntTensor, torch.Tensor, torch.Tensor]: # separate filename and text audiopath, text = audiopath_and_text[0],", "= self.get_speaker_id(speaker_id) return text, mel, speaker_id def create_speaker_lookup_table(self, audiopaths_and_text): speaker_ids = np.sort(np.unique([x[2] for", "str, hparams): self.audiopaths_and_text = load_filepaths_and_text(audiopaths_and_text) self.text_cleaners = hparams.data.text_cleaners self.max_wav_value = hparams.data.max_wav_value self.sampling_rate =", "== 0 # include mel padded and gate padded mel_padded = torch.FloatTensor(len(batch), num_mels,", "def __init__(self, audiopaths_and_text: str, hparams): self.audiopaths_and_text = load_filepaths_and_text(audiopaths_and_text) self.text_cleaners = hparams.data.text_cleaners self.max_wav_value =", "if not self.load_mel_from_disk: audio, sampling_rate = load_wav_to_torch(filename) if sampling_rate != self.stft.sampling_rate: raise ValueError(\"{}", "from: - https://github.com/NVIDIA/tacotron2 - https://github.com/mozilla/TTS \"\"\" import random from typing import List, Tuple", "to sequences of one-hot vectors 3) computes mel-spectrograms from audio files. \"\"\" def", "self.stft.sampling_rate)) audio_norm = audio / self.max_wav_value audio_norm = audio_norm.unsqueeze(0) audio_norm = audio_norm.clone().detach() melspec", "batch[ids_sorted_decreasing[i]][0] text_padded[i, :text.size(0)] = text # Right zero-pad mel-spec num_mels = batch[0][1].size(0) max_target_len", "get_speaker_id(self, speaker_id) -> torch.Tensor: return torch.LongTensor([self.speaker_ids[int(speaker_id)]]) def __getitem__(self, index: int): return self.get_data_sample(self.audiopaths_and_text[index]) def", "List, Tuple import torch import numpy as np import torch.utils.data from tacotron2_gst import", "mel-spec num_mels = batch[0][1].size(0) max_target_len = max([x[1].size(1) for x in batch]) if max_target_len", "np.sort(np.unique([x[2] for x in audiopaths_and_text])) d = {int(speaker_ids[i]): i for i in range(len(speaker_ids))}", "inputs and targets based on number of frames per setep \"\"\" def __init__(self,", "0) else: melspec = torch.from_numpy(np.load(filename)) assert melspec.size(0) == self.stft.n_mel_channels, ( 'Mel dimension mismatch:", "and mel-spectrogram PARAMS ------ batch: [text_normalized, mel_normalized] \"\"\" # Right zero-pad all one-hot", "i in range(len(speaker_ids))} print(\"Number of speakers :\", len(d)) return d def get_mel(self, filename:", "normalizes text and converts them to sequences of one-hot vectors 3) computes mel-spectrograms", "filename and text audiopath, text = audiopath_and_text[0], audiopath_and_text[1] speaker_id = None if self.use_speaker_embedding:", "if self.use_speaker_embedding: speaker_id = audiopath_and_text[2] text = self.get_text(text) mel = self.get_mel(audiopath) if speaker_id", "text and converts them to sequences of one-hot vectors 3) computes mel-spectrograms from", "\"\"\" def __init__(self, n_frames_per_step: int): self.n_frames_per_step = n_frames_per_step def __call__(self, batch): \"\"\"Collate's training", "Adapted from: - https://github.com/NVIDIA/tacotron2 - https://github.com/mozilla/TTS \"\"\" import random from typing import List,", "= n_frames_per_step def __call__(self, batch): \"\"\"Collate's training batch from normalized text and mel-spectrogram", "mel = self.get_mel(audiopath) if speaker_id is not None: speaker_id = self.get_speaker_id(speaker_id) return text,", "from tacotron2_gst.audio_processing import load_wav_to_torch class TextMelLoader(torch.utils.data.Dataset): \"\"\" 1) loads audio,text pairs 2) normalizes", "audio_norm = audio / self.max_wav_value audio_norm = audio_norm.unsqueeze(0) audio_norm = audio_norm.clone().detach() melspec =", "random.seed(1234) random.shuffle(self.audiopaths_and_text) self.use_speaker_embedding = hparams.use_speaker_embedding if self.use_speaker_embedding: self.speaker_ids = self.create_speaker_lookup_table(self.audiopaths_and_text) def get_data_sample(self, audiopath_and_text:", "not self.load_mel_from_disk: audio, sampling_rate = load_wav_to_torch(filename) if sampling_rate != self.stft.sampling_rate: raise ValueError(\"{} SR", "melspec.size(0), self.stft.n_mel_channels)) return melspec def get_text(self, text: str) -> torch.IntTensor: text_norm = torch.IntTensor(text_to_sequence(text,", "torch.Tensor: return torch.LongTensor([self.speaker_ids[int(speaker_id)]]) def __getitem__(self, index: int): return self.get_data_sample(self.audiopaths_and_text[index]) def __len__(self): return len(self.audiopaths_and_text)", "max_input_len) text_padded.zero_() for i in range(len(ids_sorted_decreasing)): text = batch[ids_sorted_decreasing[i]][0] text_padded[i, :text.size(0)] = text", "self.sampling_rate = hparams.data.sampling_rate self.load_mel_from_disk = hparams.data.load_mel_from_disk self.stft = layers.TacotronSTFT( hparams.data.filter_length, hparams.data.hop_length, hparams.data.win_length, hparams.data.n_mel_channels,", "import torch import numpy as np import torch.utils.data from tacotron2_gst import layers from", "x in batch]), dim=0, descending=True) max_input_len = input_lengths[0] text_padded = torch.LongTensor(len(batch), max_input_len) text_padded.zero_()", "and converts them to sequences of one-hot vectors 3) computes mel-spectrograms from audio", "audio_norm = audio_norm.unsqueeze(0) audio_norm = audio_norm.clone().detach() melspec = self.stft.mel_spectrogram(audio_norm) melspec = torch.squeeze(melspec, 0)", "TextMelCollate(): \"\"\" Zero-pads model inputs and targets based on number of frames per", "of one-hot vectors 3) computes mel-spectrograms from audio files. \"\"\" def __init__(self, audiopaths_and_text:", "speaker_id = None if self.use_speaker_embedding: speaker_id = audiopath_and_text[2] text = self.get_text(text) mel =", "int): self.n_frames_per_step = n_frames_per_step def __call__(self, batch): \"\"\"Collate's training batch from normalized text", "per setep \"\"\" def __init__(self, n_frames_per_step: int): self.n_frames_per_step = n_frames_per_step def __call__(self, batch):", "ids_sorted_decreasing = torch.sort( torch.LongTensor([len(x[0]) for x in batch]), dim=0, descending=True) max_input_len = input_lengths[0]", "batch): \"\"\"Collate's training batch from normalized text and mel-spectrogram PARAMS ------ batch: [text_normalized,", "= self.get_text(text) mel = self.get_mel(audiopath) if speaker_id is not None: speaker_id = self.get_speaker_id(speaker_id)", "range(len(ids_sorted_decreasing)): text = batch[ids_sorted_decreasing[i]][0] text_padded[i, :text.size(0)] = text # Right zero-pad mel-spec num_mels", "batch[ids_sorted_decreasing[i]][1] mel_padded[i, :, :mel.size(1)] = mel gate_padded[i, mel.size(1) - 1:] = 1 output_lengths[i]", ":mel.size(1)] = mel gate_padded[i, mel.size(1) - 1:] = 1 output_lengths[i] = mel.size(1) if", "3) computes mel-spectrograms from audio files. \"\"\" def __init__(self, audiopaths_and_text: str, hparams): self.audiopaths_and_text", "speaker_id = audiopath_and_text[2] text = self.get_text(text) mel = self.get_mel(audiopath) if speaker_id is not", "def create_speaker_lookup_table(self, audiopaths_and_text): speaker_ids = np.sort(np.unique([x[2] for x in audiopaths_and_text])) d = {int(speaker_ids[i]):", "0: max_target_len += self.n_frames_per_step - max_target_len % self.n_frames_per_step assert max_target_len % self.n_frames_per_step ==", "in range(len(speaker_ids))} print(\"Number of speakers :\", len(d)) return d def get_mel(self, filename: str)", "class TextMelLoader(torch.utils.data.Dataset): \"\"\" 1) loads audio,text pairs 2) normalizes text and converts them", "target {} SR\".format( sampling_rate, self.stft.sampling_rate)) audio_norm = audio / self.max_wav_value audio_norm = audio_norm.unsqueeze(0)", "melspec = torch.from_numpy(np.load(filename)) assert melspec.size(0) == self.stft.n_mel_channels, ( 'Mel dimension mismatch: given {},", "def get_speaker_id(self, speaker_id) -> torch.Tensor: return torch.LongTensor([self.speaker_ids[int(speaker_id)]]) def __getitem__(self, index: int): return self.get_data_sample(self.audiopaths_and_text[index])", "'Mel dimension mismatch: given {}, expected {}'.format( melspec.size(0), self.stft.n_mel_channels)) return melspec def get_text(self,", "hparams.data.n_mel_channels, hparams.data.sampling_rate, hparams.data.mel_fmin, hparams.data.mel_fmax) random.seed(1234) random.shuffle(self.audiopaths_and_text) self.use_speaker_embedding = hparams.use_speaker_embedding if self.use_speaker_embedding: self.speaker_ids =", "input_lengths, ids_sorted_decreasing = torch.sort( torch.LongTensor([len(x[0]) for x in batch]), dim=0, descending=True) max_input_len =", "text = audiopath_and_text[0], audiopath_and_text[1] speaker_id = None if self.use_speaker_embedding: speaker_id = audiopath_and_text[2] text", "hparams.use_speaker_embedding if self.use_speaker_embedding: self.speaker_ids = self.create_speaker_lookup_table(self.audiopaths_and_text) def get_data_sample(self, audiopath_and_text: List) -> Tuple[torch.IntTensor, torch.Tensor,", "as np import torch.utils.data from tacotron2_gst import layers from tacotron2_gst.text import text_to_sequence from", "int): return self.get_data_sample(self.audiopaths_and_text[index]) def __len__(self): return len(self.audiopaths_and_text) class TextMelCollate(): \"\"\" Zero-pads model inputs", "np import torch.utils.data from tacotron2_gst import layers from tacotron2_gst.text import text_to_sequence from tacotron2_gst.utils", "= torch.FloatTensor(len(batch), num_mels, max_target_len) mel_padded.zero_() gate_padded = torch.FloatTensor(len(batch), max_target_len) gate_padded.zero_() output_lengths = torch.LongTensor(len(batch))", "hparams.data.load_mel_from_disk self.stft = layers.TacotronSTFT( hparams.data.filter_length, hparams.data.hop_length, hparams.data.win_length, hparams.data.n_mel_channels, hparams.data.sampling_rate, hparams.data.mel_fmin, hparams.data.mel_fmax) random.seed(1234) random.shuffle(self.audiopaths_and_text)", "batch: [text_normalized, mel_normalized] \"\"\" # Right zero-pad all one-hot text sequences to max", "text, mel, speaker_id def create_speaker_lookup_table(self, audiopaths_and_text): speaker_ids = np.sort(np.unique([x[2] for x in audiopaths_and_text]))", "mel_padded.zero_() gate_padded = torch.FloatTensor(len(batch), max_target_len) gate_padded.zero_() output_lengths = torch.LongTensor(len(batch)) use_speaker_embedding = batch[0][2] is", "normalized text and mel-spectrogram PARAMS ------ batch: [text_normalized, mel_normalized] \"\"\" # Right zero-pad", "class TextMelCollate(): \"\"\" Zero-pads model inputs and targets based on number of frames", "speaker_id def create_speaker_lookup_table(self, audiopaths_and_text): speaker_ids = np.sort(np.unique([x[2] for x in audiopaths_and_text])) d =", "https://github.com/NVIDIA/tacotron2 - https://github.com/mozilla/TTS \"\"\" import random from typing import List, Tuple import torch", "return text, mel, speaker_id def create_speaker_lookup_table(self, audiopaths_and_text): speaker_ids = np.sort(np.unique([x[2] for x in", "tacotron2_gst.utils import load_filepaths_and_text from tacotron2_gst.audio_processing import load_wav_to_torch class TextMelLoader(torch.utils.data.Dataset): \"\"\" 1) loads audio,text", "self.get_data_sample(self.audiopaths_and_text[index]) def __len__(self): return len(self.audiopaths_and_text) class TextMelCollate(): \"\"\" Zero-pads model inputs and targets", "= hparams.data.sampling_rate self.load_mel_from_disk = hparams.data.load_mel_from_disk self.stft = layers.TacotronSTFT( hparams.data.filter_length, hparams.data.hop_length, hparams.data.win_length, hparams.data.n_mel_channels, hparams.data.sampling_rate,", "audiopath, text = audiopath_and_text[0], audiopath_and_text[1] speaker_id = None if self.use_speaker_embedding: speaker_id = audiopath_and_text[2]", "batch[0][1].size(0) max_target_len = max([x[1].size(1) for x in batch]) if max_target_len % self.n_frames_per_step !=", "torch.Tensor]: # separate filename and text audiopath, text = audiopath_and_text[0], audiopath_and_text[1] speaker_id =", "= hparams.data.text_cleaners self.max_wav_value = hparams.data.max_wav_value self.sampling_rate = hparams.data.sampling_rate self.load_mel_from_disk = hparams.data.load_mel_from_disk self.stft =", "for i in range(len(ids_sorted_decreasing)): text = batch[ids_sorted_decreasing[i]][0] text_padded[i, :text.size(0)] = text # Right", "mel.size(1) if use_speaker_embedding: speaker_ids[i] = batch[ids_sorted_decreasing[i]][2] return text_padded, input_lengths, mel_padded, speaker_ids, gate_padded, output_lengths", "sequences of one-hot vectors 3) computes mel-spectrograms from audio files. \"\"\" def __init__(self,", "None if use_speaker_embedding: speaker_ids = torch.LongTensor(len(batch)) else: speaker_ids = None for i in", "self.audiopaths_and_text = load_filepaths_and_text(audiopaths_and_text) self.text_cleaners = hparams.data.text_cleaners self.max_wav_value = hparams.data.max_wav_value self.sampling_rate = hparams.data.sampling_rate self.load_mel_from_disk", "self.max_wav_value = hparams.data.max_wav_value self.sampling_rate = hparams.data.sampling_rate self.load_mel_from_disk = hparams.data.load_mel_from_disk self.stft = layers.TacotronSTFT( hparams.data.filter_length,", "for i in range(len(speaker_ids))} print(\"Number of speakers :\", len(d)) return d def get_mel(self,", "Right zero-pad all one-hot text sequences to max input length input_lengths, ids_sorted_decreasing =", "descending=True) max_input_len = input_lengths[0] text_padded = torch.LongTensor(len(batch), max_input_len) text_padded.zero_() for i in range(len(ids_sorted_decreasing)):", "% self.n_frames_per_step assert max_target_len % self.n_frames_per_step == 0 # include mel padded and", "import numpy as np import torch.utils.data from tacotron2_gst import layers from tacotron2_gst.text import", "0 # include mel padded and gate padded mel_padded = torch.FloatTensor(len(batch), num_mels, max_target_len)", "Right zero-pad mel-spec num_mels = batch[0][1].size(0) max_target_len = max([x[1].size(1) for x in batch])", "hparams.data.text_cleaners self.max_wav_value = hparams.data.max_wav_value self.sampling_rate = hparams.data.sampling_rate self.load_mel_from_disk = hparams.data.load_mel_from_disk self.stft = layers.TacotronSTFT(", "is not None if use_speaker_embedding: speaker_ids = torch.LongTensor(len(batch)) else: speaker_ids = None for", "x in audiopaths_and_text])) d = {int(speaker_ids[i]): i for i in range(len(speaker_ids))} print(\"Number of", "SR doesn't match target {} SR\".format( sampling_rate, self.stft.sampling_rate)) audio_norm = audio / self.max_wav_value", "tacotron2_gst.audio_processing import load_wav_to_torch class TextMelLoader(torch.utils.data.Dataset): \"\"\" 1) loads audio,text pairs 2) normalizes text", "length input_lengths, ids_sorted_decreasing = torch.sort( torch.LongTensor([len(x[0]) for x in batch]), dim=0, descending=True) max_input_len", "= 1 output_lengths[i] = mel.size(1) if use_speaker_embedding: speaker_ids[i] = batch[ids_sorted_decreasing[i]][2] return text_padded, input_lengths,", "self.stft.n_mel_channels)) return melspec def get_text(self, text: str) -> torch.IntTensor: text_norm = torch.IntTensor(text_to_sequence(text, self.text_cleaners))", "output_lengths = torch.LongTensor(len(batch)) use_speaker_embedding = batch[0][2] is not None if use_speaker_embedding: speaker_ids =", "\"\"\" def __init__(self, audiopaths_and_text: str, hparams): self.audiopaths_and_text = load_filepaths_and_text(audiopaths_and_text) self.text_cleaners = hparams.data.text_cleaners self.max_wav_value", "torch.IntTensor: text_norm = torch.IntTensor(text_to_sequence(text, self.text_cleaners)) return text_norm def get_speaker_id(self, speaker_id) -> torch.Tensor: return", "doesn't match target {} SR\".format( sampling_rate, self.stft.sampling_rate)) audio_norm = audio / self.max_wav_value audio_norm", "random from typing import List, Tuple import torch import numpy as np import", "audiopath_and_text[2] text = self.get_text(text) mel = self.get_mel(audiopath) if speaker_id is not None: speaker_id", "expected {}'.format( melspec.size(0), self.stft.n_mel_channels)) return melspec def get_text(self, text: str) -> torch.IntTensor: text_norm", "gate padded mel_padded = torch.FloatTensor(len(batch), num_mels, max_target_len) mel_padded.zero_() gate_padded = torch.FloatTensor(len(batch), max_target_len) gate_padded.zero_()", "- 1:] = 1 output_lengths[i] = mel.size(1) if use_speaker_embedding: speaker_ids[i] = batch[ids_sorted_decreasing[i]][2] return", "in batch]) if max_target_len % self.n_frames_per_step != 0: max_target_len += self.n_frames_per_step - max_target_len", "for i in range(len(ids_sorted_decreasing)): mel = batch[ids_sorted_decreasing[i]][1] mel_padded[i, :, :mel.size(1)] = mel gate_padded[i,", "__call__(self, batch): \"\"\"Collate's training batch from normalized text and mel-spectrogram PARAMS ------ batch:", "self.get_speaker_id(speaker_id) return text, mel, speaker_id def create_speaker_lookup_table(self, audiopaths_and_text): speaker_ids = np.sort(np.unique([x[2] for x", "audiopath_and_text: List) -> Tuple[torch.IntTensor, torch.Tensor, torch.Tensor]: # separate filename and text audiopath, text", "= mel gate_padded[i, mel.size(1) - 1:] = 1 output_lengths[i] = mel.size(1) if use_speaker_embedding:", "for x in batch]), dim=0, descending=True) max_input_len = input_lengths[0] text_padded = torch.LongTensor(len(batch), max_input_len)", "Tuple[torch.IntTensor, torch.Tensor, torch.Tensor]: # separate filename and text audiopath, text = audiopath_and_text[0], audiopath_and_text[1]", "self.stft = layers.TacotronSTFT( hparams.data.filter_length, hparams.data.hop_length, hparams.data.win_length, hparams.data.n_mel_channels, hparams.data.sampling_rate, hparams.data.mel_fmin, hparams.data.mel_fmax) random.seed(1234) random.shuffle(self.audiopaths_and_text) self.use_speaker_embedding", "i in range(len(ids_sorted_decreasing)): text = batch[ids_sorted_decreasing[i]][0] text_padded[i, :text.size(0)] = text # Right zero-pad", "str) -> torch.IntTensor: text_norm = torch.IntTensor(text_to_sequence(text, self.text_cleaners)) return text_norm def get_speaker_id(self, speaker_id) ->", "<reponame>tilde-nlp/pip2-expressive-speech-synthesis-for-dialogs \"\"\" Adapted from: - https://github.com/NVIDIA/tacotron2 - https://github.com/mozilla/TTS \"\"\" import random from typing", "len(d)) return d def get_mel(self, filename: str) -> torch.Tensor: if not self.load_mel_from_disk: audio,", "range(len(ids_sorted_decreasing)): mel = batch[ids_sorted_decreasing[i]][1] mel_padded[i, :, :mel.size(1)] = mel gate_padded[i, mel.size(1) - 1:]", "= mel.size(1) if use_speaker_embedding: speaker_ids[i] = batch[ids_sorted_decreasing[i]][2] return text_padded, input_lengths, mel_padded, speaker_ids, gate_padded,", "max_target_len % self.n_frames_per_step assert max_target_len % self.n_frames_per_step == 0 # include mel padded", "use_speaker_embedding: speaker_ids = torch.LongTensor(len(batch)) else: speaker_ids = None for i in range(len(ids_sorted_decreasing)): mel", "hparams): self.audiopaths_and_text = load_filepaths_and_text(audiopaths_and_text) self.text_cleaners = hparams.data.text_cleaners self.max_wav_value = hparams.data.max_wav_value self.sampling_rate = hparams.data.sampling_rate", "self.text_cleaners)) return text_norm def get_speaker_id(self, speaker_id) -> torch.Tensor: return torch.LongTensor([self.speaker_ids[int(speaker_id)]]) def __getitem__(self, index:", "speaker_id is not None: speaker_id = self.get_speaker_id(speaker_id) return text, mel, speaker_id def create_speaker_lookup_table(self,", "= torch.IntTensor(text_to_sequence(text, self.text_cleaners)) return text_norm def get_speaker_id(self, speaker_id) -> torch.Tensor: return torch.LongTensor([self.speaker_ids[int(speaker_id)]]) def", ":, :mel.size(1)] = mel gate_padded[i, mel.size(1) - 1:] = 1 output_lengths[i] = mel.size(1)", "!= 0: max_target_len += self.n_frames_per_step - max_target_len % self.n_frames_per_step assert max_target_len % self.n_frames_per_step", "pairs 2) normalizes text and converts them to sequences of one-hot vectors 3)", "audio / self.max_wav_value audio_norm = audio_norm.unsqueeze(0) audio_norm = audio_norm.clone().detach() melspec = self.stft.mel_spectrogram(audio_norm) melspec", "model inputs and targets based on number of frames per setep \"\"\" def", "self.n_frames_per_step assert max_target_len % self.n_frames_per_step == 0 # include mel padded and gate", "in audiopaths_and_text])) d = {int(speaker_ids[i]): i for i in range(len(speaker_ids))} print(\"Number of speakers", "them to sequences of one-hot vectors 3) computes mel-spectrograms from audio files. \"\"\"", "batch from normalized text and mel-spectrogram PARAMS ------ batch: [text_normalized, mel_normalized] \"\"\" #", "= layers.TacotronSTFT( hparams.data.filter_length, hparams.data.hop_length, hparams.data.win_length, hparams.data.n_mel_channels, hparams.data.sampling_rate, hparams.data.mel_fmin, hparams.data.mel_fmax) random.seed(1234) random.shuffle(self.audiopaths_and_text) self.use_speaker_embedding =", "return d def get_mel(self, filename: str) -> torch.Tensor: if not self.load_mel_from_disk: audio, sampling_rate", "__init__(self, n_frames_per_step: int): self.n_frames_per_step = n_frames_per_step def __call__(self, batch): \"\"\"Collate's training batch from", "one-hot text sequences to max input length input_lengths, ids_sorted_decreasing = torch.sort( torch.LongTensor([len(x[0]) for", "import layers from tacotron2_gst.text import text_to_sequence from tacotron2_gst.utils import load_filepaths_and_text from tacotron2_gst.audio_processing import", "assert max_target_len % self.n_frames_per_step == 0 # include mel padded and gate padded", "text_padded = torch.LongTensor(len(batch), max_input_len) text_padded.zero_() for i in range(len(ids_sorted_decreasing)): text = batch[ids_sorted_decreasing[i]][0] text_padded[i,", "mel padded and gate padded mel_padded = torch.FloatTensor(len(batch), num_mels, max_target_len) mel_padded.zero_() gate_padded =", "self.text_cleaners = hparams.data.text_cleaners self.max_wav_value = hparams.data.max_wav_value self.sampling_rate = hparams.data.sampling_rate self.load_mel_from_disk = hparams.data.load_mel_from_disk self.stft", "padded and gate padded mel_padded = torch.FloatTensor(len(batch), num_mels, max_target_len) mel_padded.zero_() gate_padded = torch.FloatTensor(len(batch),", "= text # Right zero-pad mel-spec num_mels = batch[0][1].size(0) max_target_len = max([x[1].size(1) for", "of frames per setep \"\"\" def __init__(self, n_frames_per_step: int): self.n_frames_per_step = n_frames_per_step def", "TextMelLoader(torch.utils.data.Dataset): \"\"\" 1) loads audio,text pairs 2) normalizes text and converts them to", "hparams.data.sampling_rate, hparams.data.mel_fmin, hparams.data.mel_fmax) random.seed(1234) random.shuffle(self.audiopaths_and_text) self.use_speaker_embedding = hparams.use_speaker_embedding if self.use_speaker_embedding: self.speaker_ids = self.create_speaker_lookup_table(self.audiopaths_and_text)", "= max([x[1].size(1) for x in batch]) if max_target_len % self.n_frames_per_step != 0: max_target_len", "torch.LongTensor([self.speaker_ids[int(speaker_id)]]) def __getitem__(self, index: int): return self.get_data_sample(self.audiopaths_and_text[index]) def __len__(self): return len(self.audiopaths_and_text) class TextMelCollate():", "d def get_mel(self, filename: str) -> torch.Tensor: if not self.load_mel_from_disk: audio, sampling_rate =", "n_frames_per_step def __call__(self, batch): \"\"\"Collate's training batch from normalized text and mel-spectrogram PARAMS", "torch.squeeze(melspec, 0) else: melspec = torch.from_numpy(np.load(filename)) assert melspec.size(0) == self.stft.n_mel_channels, ( 'Mel dimension", "-> torch.Tensor: if not self.load_mel_from_disk: audio, sampling_rate = load_wav_to_torch(filename) if sampling_rate != self.stft.sampling_rate:", "= hparams.use_speaker_embedding if self.use_speaker_embedding: self.speaker_ids = self.create_speaker_lookup_table(self.audiopaths_and_text) def get_data_sample(self, audiopath_and_text: List) -> Tuple[torch.IntTensor,", "2) normalizes text and converts them to sequences of one-hot vectors 3) computes", "num_mels = batch[0][1].size(0) max_target_len = max([x[1].size(1) for x in batch]) if max_target_len %", "= torch.squeeze(melspec, 0) else: melspec = torch.from_numpy(np.load(filename)) assert melspec.size(0) == self.stft.n_mel_channels, ( 'Mel", "self.get_text(text) mel = self.get_mel(audiopath) if speaker_id is not None: speaker_id = self.get_speaker_id(speaker_id) return", "return melspec def get_text(self, text: str) -> torch.IntTensor: text_norm = torch.IntTensor(text_to_sequence(text, self.text_cleaners)) return", "mel, speaker_id def create_speaker_lookup_table(self, audiopaths_and_text): speaker_ids = np.sort(np.unique([x[2] for x in audiopaths_and_text])) d", "get_data_sample(self, audiopath_and_text: List) -> Tuple[torch.IntTensor, torch.Tensor, torch.Tensor]: # separate filename and text audiopath,", "ValueError(\"{} SR doesn't match target {} SR\".format( sampling_rate, self.stft.sampling_rate)) audio_norm = audio /", "text: str) -> torch.IntTensor: text_norm = torch.IntTensor(text_to_sequence(text, self.text_cleaners)) return text_norm def get_speaker_id(self, speaker_id)", "if sampling_rate != self.stft.sampling_rate: raise ValueError(\"{} SR doesn't match target {} SR\".format( sampling_rate,", "converts them to sequences of one-hot vectors 3) computes mel-spectrograms from audio files.", "= None for i in range(len(ids_sorted_decreasing)): mel = batch[ids_sorted_decreasing[i]][1] mel_padded[i, :, :mel.size(1)] =", "and gate padded mel_padded = torch.FloatTensor(len(batch), num_mels, max_target_len) mel_padded.zero_() gate_padded = torch.FloatTensor(len(batch), max_target_len)", "\"\"\"Collate's training batch from normalized text and mel-spectrogram PARAMS ------ batch: [text_normalized, mel_normalized]", "max_target_len = max([x[1].size(1) for x in batch]) if max_target_len % self.n_frames_per_step != 0:", "List) -> Tuple[torch.IntTensor, torch.Tensor, torch.Tensor]: # separate filename and text audiopath, text =", "\"\"\" # Right zero-pad all one-hot text sequences to max input length input_lengths,", "__getitem__(self, index: int): return self.get_data_sample(self.audiopaths_and_text[index]) def __len__(self): return len(self.audiopaths_and_text) class TextMelCollate(): \"\"\" Zero-pads", "sequences to max input length input_lengths, ids_sorted_decreasing = torch.sort( torch.LongTensor([len(x[0]) for x in", "mel_padded[i, :, :mel.size(1)] = mel gate_padded[i, mel.size(1) - 1:] = 1 output_lengths[i] =", "load_wav_to_torch class TextMelLoader(torch.utils.data.Dataset): \"\"\" 1) loads audio,text pairs 2) normalizes text and converts", "torch.LongTensor([len(x[0]) for x in batch]), dim=0, descending=True) max_input_len = input_lengths[0] text_padded = torch.LongTensor(len(batch),", "torch.utils.data from tacotron2_gst import layers from tacotron2_gst.text import text_to_sequence from tacotron2_gst.utils import load_filepaths_and_text", "hparams.data.mel_fmin, hparams.data.mel_fmax) random.seed(1234) random.shuffle(self.audiopaths_and_text) self.use_speaker_embedding = hparams.use_speaker_embedding if self.use_speaker_embedding: self.speaker_ids = self.create_speaker_lookup_table(self.audiopaths_and_text) def", "len(self.audiopaths_and_text) class TextMelCollate(): \"\"\" Zero-pads model inputs and targets based on number of", "tacotron2_gst import layers from tacotron2_gst.text import text_to_sequence from tacotron2_gst.utils import load_filepaths_and_text from tacotron2_gst.audio_processing", "def get_mel(self, filename: str) -> torch.Tensor: if not self.load_mel_from_disk: audio, sampling_rate = load_wav_to_torch(filename)", "__len__(self): return len(self.audiopaths_and_text) class TextMelCollate(): \"\"\" Zero-pads model inputs and targets based on", "load_filepaths_and_text(audiopaths_and_text) self.text_cleaners = hparams.data.text_cleaners self.max_wav_value = hparams.data.max_wav_value self.sampling_rate = hparams.data.sampling_rate self.load_mel_from_disk = hparams.data.load_mel_from_disk", "torch.sort( torch.LongTensor([len(x[0]) for x in batch]), dim=0, descending=True) max_input_len = input_lengths[0] text_padded =", "__init__(self, audiopaths_and_text: str, hparams): self.audiopaths_and_text = load_filepaths_and_text(audiopaths_and_text) self.text_cleaners = hparams.data.text_cleaners self.max_wav_value = hparams.data.max_wav_value", "vectors 3) computes mel-spectrograms from audio files. \"\"\" def __init__(self, audiopaths_and_text: str, hparams):", "melspec = self.stft.mel_spectrogram(audio_norm) melspec = torch.squeeze(melspec, 0) else: melspec = torch.from_numpy(np.load(filename)) assert melspec.size(0)", "self.create_speaker_lookup_table(self.audiopaths_and_text) def get_data_sample(self, audiopath_and_text: List) -> Tuple[torch.IntTensor, torch.Tensor, torch.Tensor]: # separate filename and", "torch.from_numpy(np.load(filename)) assert melspec.size(0) == self.stft.n_mel_channels, ( 'Mel dimension mismatch: given {}, expected {}'.format(", "targets based on number of frames per setep \"\"\" def __init__(self, n_frames_per_step: int):", "dimension mismatch: given {}, expected {}'.format( melspec.size(0), self.stft.n_mel_channels)) return melspec def get_text(self, text:", "hparams.data.max_wav_value self.sampling_rate = hparams.data.sampling_rate self.load_mel_from_disk = hparams.data.load_mel_from_disk self.stft = layers.TacotronSTFT( hparams.data.filter_length, hparams.data.hop_length, hparams.data.win_length,", "hparams.data.mel_fmax) random.seed(1234) random.shuffle(self.audiopaths_and_text) self.use_speaker_embedding = hparams.use_speaker_embedding if self.use_speaker_embedding: self.speaker_ids = self.create_speaker_lookup_table(self.audiopaths_and_text) def get_data_sample(self,", "d = {int(speaker_ids[i]): i for i in range(len(speaker_ids))} print(\"Number of speakers :\", len(d))", "text_norm = torch.IntTensor(text_to_sequence(text, self.text_cleaners)) return text_norm def get_speaker_id(self, speaker_id) -> torch.Tensor: return torch.LongTensor([self.speaker_ids[int(speaker_id)]])", "dim=0, descending=True) max_input_len = input_lengths[0] text_padded = torch.LongTensor(len(batch), max_input_len) text_padded.zero_() for i in", "separate filename and text audiopath, text = audiopath_and_text[0], audiopath_and_text[1] speaker_id = None if", "text audiopath, text = audiopath_and_text[0], audiopath_and_text[1] speaker_id = None if self.use_speaker_embedding: speaker_id =", "numpy as np import torch.utils.data from tacotron2_gst import layers from tacotron2_gst.text import text_to_sequence", "1) loads audio,text pairs 2) normalizes text and converts them to sequences of", "= self.get_mel(audiopath) if speaker_id is not None: speaker_id = self.get_speaker_id(speaker_id) return text, mel,", "return self.get_data_sample(self.audiopaths_and_text[index]) def __len__(self): return len(self.audiopaths_and_text) class TextMelCollate(): \"\"\" Zero-pads model inputs and", "filename: str) -> torch.Tensor: if not self.load_mel_from_disk: audio, sampling_rate = load_wav_to_torch(filename) if sampling_rate", "mel = batch[ids_sorted_decreasing[i]][1] mel_padded[i, :, :mel.size(1)] = mel gate_padded[i, mel.size(1) - 1:] =", "audio,text pairs 2) normalizes text and converts them to sequences of one-hot vectors", "setep \"\"\" def __init__(self, n_frames_per_step: int): self.n_frames_per_step = n_frames_per_step def __call__(self, batch): \"\"\"Collate's", "if self.use_speaker_embedding: self.speaker_ids = self.create_speaker_lookup_table(self.audiopaths_and_text) def get_data_sample(self, audiopath_and_text: List) -> Tuple[torch.IntTensor, torch.Tensor, torch.Tensor]:", "batch]), dim=0, descending=True) max_input_len = input_lengths[0] text_padded = torch.LongTensor(len(batch), max_input_len) text_padded.zero_() for i", "def __len__(self): return len(self.audiopaths_and_text) class TextMelCollate(): \"\"\" Zero-pads model inputs and targets based", "for x in audiopaths_and_text])) d = {int(speaker_ids[i]): i for i in range(len(speaker_ids))} print(\"Number", "max_target_len += self.n_frames_per_step - max_target_len % self.n_frames_per_step assert max_target_len % self.n_frames_per_step == 0", "in batch]), dim=0, descending=True) max_input_len = input_lengths[0] text_padded = torch.LongTensor(len(batch), max_input_len) text_padded.zero_() for", "str) -> torch.Tensor: if not self.load_mel_from_disk: audio, sampling_rate = load_wav_to_torch(filename) if sampling_rate !=", "if use_speaker_embedding: speaker_ids = torch.LongTensor(len(batch)) else: speaker_ids = None for i in range(len(ids_sorted_decreasing)):", "is not None: speaker_id = self.get_speaker_id(speaker_id) return text, mel, speaker_id def create_speaker_lookup_table(self, audiopaths_and_text):", "hparams.data.filter_length, hparams.data.hop_length, hparams.data.win_length, hparams.data.n_mel_channels, hparams.data.sampling_rate, hparams.data.mel_fmin, hparams.data.mel_fmax) random.seed(1234) random.shuffle(self.audiopaths_and_text) self.use_speaker_embedding = hparams.use_speaker_embedding if", "# separate filename and text audiopath, text = audiopath_and_text[0], audiopath_and_text[1] speaker_id = None", "- https://github.com/NVIDIA/tacotron2 - https://github.com/mozilla/TTS \"\"\" import random from typing import List, Tuple import", "1 output_lengths[i] = mel.size(1) if use_speaker_embedding: speaker_ids[i] = batch[ids_sorted_decreasing[i]][2] return text_padded, input_lengths, mel_padded,", "from typing import List, Tuple import torch import numpy as np import torch.utils.data", "input_lengths[0] text_padded = torch.LongTensor(len(batch), max_input_len) text_padded.zero_() for i in range(len(ids_sorted_decreasing)): text = batch[ids_sorted_decreasing[i]][0]", "-> torch.IntTensor: text_norm = torch.IntTensor(text_to_sequence(text, self.text_cleaners)) return text_norm def get_speaker_id(self, speaker_id) -> torch.Tensor:", "number of frames per setep \"\"\" def __init__(self, n_frames_per_step: int): self.n_frames_per_step = n_frames_per_step", "def get_data_sample(self, audiopath_and_text: List) -> Tuple[torch.IntTensor, torch.Tensor, torch.Tensor]: # separate filename and text", "self.speaker_ids = self.create_speaker_lookup_table(self.audiopaths_and_text) def get_data_sample(self, audiopath_and_text: List) -> Tuple[torch.IntTensor, torch.Tensor, torch.Tensor]: # separate", "# include mel padded and gate padded mel_padded = torch.FloatTensor(len(batch), num_mels, max_target_len) mel_padded.zero_()", "= audio_norm.unsqueeze(0) audio_norm = audio_norm.clone().detach() melspec = self.stft.mel_spectrogram(audio_norm) melspec = torch.squeeze(melspec, 0) else:", "hparams.data.win_length, hparams.data.n_mel_channels, hparams.data.sampling_rate, hparams.data.mel_fmin, hparams.data.mel_fmax) random.seed(1234) random.shuffle(self.audiopaths_and_text) self.use_speaker_embedding = hparams.use_speaker_embedding if self.use_speaker_embedding: self.speaker_ids", "hparams.data.sampling_rate self.load_mel_from_disk = hparams.data.load_mel_from_disk self.stft = layers.TacotronSTFT( hparams.data.filter_length, hparams.data.hop_length, hparams.data.win_length, hparams.data.n_mel_channels, hparams.data.sampling_rate, hparams.data.mel_fmin,", "-> torch.Tensor: return torch.LongTensor([self.speaker_ids[int(speaker_id)]]) def __getitem__(self, index: int): return self.get_data_sample(self.audiopaths_and_text[index]) def __len__(self): return", "self.stft.sampling_rate: raise ValueError(\"{} SR doesn't match target {} SR\".format( sampling_rate, self.stft.sampling_rate)) audio_norm =", "from audio files. \"\"\" def __init__(self, audiopaths_and_text: str, hparams): self.audiopaths_and_text = load_filepaths_and_text(audiopaths_and_text) self.text_cleaners", "if max_target_len % self.n_frames_per_step != 0: max_target_len += self.n_frames_per_step - max_target_len % self.n_frames_per_step", "= hparams.data.load_mel_from_disk self.stft = layers.TacotronSTFT( hparams.data.filter_length, hparams.data.hop_length, hparams.data.win_length, hparams.data.n_mel_channels, hparams.data.sampling_rate, hparams.data.mel_fmin, hparams.data.mel_fmax) random.seed(1234)", "max_input_len = input_lengths[0] text_padded = torch.LongTensor(len(batch), max_input_len) text_padded.zero_() for i in range(len(ids_sorted_decreasing)): text", "load_filepaths_and_text from tacotron2_gst.audio_processing import load_wav_to_torch class TextMelLoader(torch.utils.data.Dataset): \"\"\" 1) loads audio,text pairs 2)", "speakers :\", len(d)) return d def get_mel(self, filename: str) -> torch.Tensor: if not", "text sequences to max input length input_lengths, ids_sorted_decreasing = torch.sort( torch.LongTensor([len(x[0]) for x", "sampling_rate, self.stft.sampling_rate)) audio_norm = audio / self.max_wav_value audio_norm = audio_norm.unsqueeze(0) audio_norm = audio_norm.clone().detach()", "on number of frames per setep \"\"\" def __init__(self, n_frames_per_step: int): self.n_frames_per_step =", "import torch.utils.data from tacotron2_gst import layers from tacotron2_gst.text import text_to_sequence from tacotron2_gst.utils import", "and targets based on number of frames per setep \"\"\" def __init__(self, n_frames_per_step:", "return len(self.audiopaths_and_text) class TextMelCollate(): \"\"\" Zero-pads model inputs and targets based on number", "one-hot vectors 3) computes mel-spectrograms from audio files. \"\"\" def __init__(self, audiopaths_and_text: str,", "# Right zero-pad all one-hot text sequences to max input length input_lengths, ids_sorted_decreasing", "batch[0][2] is not None if use_speaker_embedding: speaker_ids = torch.LongTensor(len(batch)) else: speaker_ids = None", "\"\"\" Zero-pads model inputs and targets based on number of frames per setep", "self.use_speaker_embedding = hparams.use_speaker_embedding if self.use_speaker_embedding: self.speaker_ids = self.create_speaker_lookup_table(self.audiopaths_and_text) def get_data_sample(self, audiopath_and_text: List) ->", "files. \"\"\" def __init__(self, audiopaths_and_text: str, hparams): self.audiopaths_and_text = load_filepaths_and_text(audiopaths_and_text) self.text_cleaners = hparams.data.text_cleaners", "range(len(speaker_ids))} print(\"Number of speakers :\", len(d)) return d def get_mel(self, filename: str) ->" ]
[ "= input(\"What year were you born?\") age = 2019 - int(birth_year) print(f\"Your age", "<filename>type_conversion.py birth_year = input(\"What year were you born?\") age = 2019 - int(birth_year)", "year were you born?\") age = 2019 - int(birth_year) print(f\"Your age is: {age}\")", "input(\"What year were you born?\") age = 2019 - int(birth_year) print(f\"Your age is:", "birth_year = input(\"What year were you born?\") age = 2019 - int(birth_year) print(f\"Your" ]
[ "map.token_value} headers1 = {'content-type': 'application/json'} def insertintomnogo(Xmldata, build_id): try: # insert parsed xml", "rel_no, build_no, junit_url, branch_name): try: # insert parsed xml data into mongodb for", "MONGO_PERF_COLLECTION.insert_one(query) # call defect creation service resp = requests.post(map.defect_service_url, data=json.dumps(gitdata), headers=headers1) return resp.text", "= map.giturl headers = {map.token_name: map.token_value} headers1 = {'content-type': 'application/json'} def insertintomnogo(Xmldata, build_id):", "MongoClient import requests from flask import jsonify import json import logging logging.basicConfig(level=logging.DEBUG) remotevalue", "jenkinsdata = {} build_id = '' giturl = map.giturl headers = {map.token_name: map.token_value}", "mongodb CLIENT = MongoClient(map.DB_IP, map.DB_PORT) MONGO_PERF_DB = CLIENT.perf_db MONGO_PERF_DB.authenticate(map.DB_USERNAME, map.DB_PASSWORD) MONGO_PERF_COLLECTION = MONGO_PERF_DB.junit_test_suite", "'URL': map.jenkins_public_url_prefix + build_id + map.jenkins_url_result, 'Junit_test': Xmldata} MONGO_PERF_COLLECTION.insert_one(query) # call defect creation", "build CLIENT = MongoClient(map.DB_IP, map.DB_PORT) MONGO_PERF_DB = CLIENT.perf_db MONGO_PERF_DB.authenticate(map.DB_USERNAME, map.DB_PASSWORD) MONGO_PERF_COLLECTION = MONGO_PERF_DB.junit_nightly_build", "'Build No': build_no, 'JunitURL': junit_url, 'JunitData': Xmldata} MONGO_PERF_COLLECTION.insert_one(data) return 'SUCCESS' except Exception as", "xml data into mongodb CLIENT = MongoClient(map.DB_IP, map.DB_PORT) MONGO_PERF_DB = CLIENT.perf_db MONGO_PERF_DB.authenticate(map.DB_USERNAME, map.DB_PASSWORD)", "as e: response = { \"success\": \"false\", \"data\": { \"Result\": \"Build Failed\" },", "build_no, junit_url, branch_name): try: # insert parsed xml data into mongodb for nightly", "= getjenkinsdata(build_id) logging.debug(\" Jenkinsdata\" + json.dumps(jenkinsdata)) # get commit detials from git server", "logging.debug(\" Jenkinsdata\" + json.dumps(jenkinsdata)) # get commit detials from git server gitdata =", "git server gitdata = getgitcommitdata(jenkinsdata['commitid']) logging.debug(\" GitData\" + json.dumps(gitdata)) CommitMessage = gitdata['message'].split('<')[1].split(':')[0] query", "CommitMessage = gitdata['message'].split('<')[1].split(':')[0] query = {'CommitID': gitdata['id'], 'SHA': gitdata['short_id'], 'CommitMessage': gitdata['message'], 'AuthorName': gitdata['author_name'],", "# call defect creation service resp = requests.post(map.defect_service_url, data=json.dumps(gitdata), headers=headers1) return resp.text except", "requests.post(map.defect_service_url, data=json.dumps(gitdata), headers=headers1) return resp.text except Exception as e: response = { \"success\":", "# get commit detials from git server gitdata = getgitcommitdata(jenkinsdata['commitid']) logging.debug(\" GitData\" +", "import MongoClient import requests from flask import jsonify import json import logging logging.basicConfig(level=logging.DEBUG)", "{ \"Result\": \"Build Failed\" }, \"error\": {\"Message\": str(e)} } return jsonify(response) def getjenkinsdata(build_id):", "\"error\": {\"Message\": str(e)} } return jsonify(response) def getjenkinsdata(build_id): r = requests.get(map.jenkins_url_prefix + build_id", "headers, proxies={'http': '10.0.10.251:<proxy_url>'},timeout=5) return response.json() def junit_nightlybuild_data(Xmldata, rel_no, build_no, junit_url, branch_name): try: #", "junit_nightlybuild_data(Xmldata, rel_no, build_no, junit_url, branch_name): try: # insert parsed xml data into mongodb", "Xmldata} MONGO_PERF_COLLECTION.insert_one(query) # call defect creation service resp = requests.post(map.defect_service_url, data=json.dumps(gitdata), headers=headers1) return", "from pymongo import MongoClient import requests from flask import jsonify import json import", "'BuildNumber': build_id, 'Branchname': jenkinsdata['branchname'], 'Ownercode': CommitMessage, 'URL': map.jenkins_public_url_prefix + build_id + map.jenkins_url_result, 'Junit_test':", "+ build_id + map.jenkins_url_result, 'Junit_test': Xmldata} MONGO_PERF_COLLECTION.insert_one(query) # call defect creation service resp", "def junit_nightlybuild_data(Xmldata, rel_no, build_no, junit_url, branch_name): try: # insert parsed xml data into", "logging logging.basicConfig(level=logging.DEBUG) remotevalue = map.remotevalue jenkinsdata = {} build_id = '' giturl =", "= '' giturl = map.giturl headers = {map.token_name: map.token_value} headers1 = {'content-type': 'application/json'}", "CLIENT.perf_db MONGO_PERF_DB.authenticate(map.DB_USERNAME, map.DB_PASSWORD) MONGO_PERF_COLLECTION = MONGO_PERF_DB.junit_nightly_build data = {'BranchName': branch_name, 'Release No': rel_no,", "{} build_id = '' giturl = map.giturl headers = {map.token_name: map.token_value} headers1 =", "searchremotevalue = remotevalue + jenkinsdata['branchname'] for item in data['actions']: if 'buildsByBranchName' in item:", "To get data for nightly build\" }, \"error\": {\"Message\": str(e)} } return jsonify(response)", "= {} build_id = '' giturl = map.giturl headers = {map.token_name: map.token_value} headers1", "= headers, proxies={'http': '10.0.10.251:<proxy_url>'},timeout=5) return response.json() def junit_nightlybuild_data(Xmldata, rel_no, build_no, junit_url, branch_name): try:", "= requests.post(map.defect_service_url, data=json.dumps(gitdata), headers=headers1) return resp.text except Exception as e: response = {", "= MongoClient(map.DB_IP, map.DB_PORT) MONGO_PERF_DB = CLIENT.perf_db MONGO_PERF_DB.authenticate(map.DB_USERNAME, map.DB_PASSWORD) MONGO_PERF_COLLECTION = MONGO_PERF_DB.junit_test_suite # get", "from git server gitdata = getgitcommitdata(jenkinsdata['commitid']) logging.debug(\" GitData\" + json.dumps(gitdata)) CommitMessage = gitdata['message'].split('<')[1].split(':')[0]", "'SHA': gitdata['short_id'], 'CommitMessage': gitdata['message'], 'AuthorName': gitdata['author_name'], 'Author_Email': gitdata['author_email'], 'BuildNumber': build_id, 'Branchname': jenkinsdata['branchname'], 'Ownercode':", "into mongodb CLIENT = MongoClient(map.DB_IP, map.DB_PORT) MONGO_PERF_DB = CLIENT.perf_db MONGO_PERF_DB.authenticate(map.DB_USERNAME, map.DB_PASSWORD) MONGO_PERF_COLLECTION =", "jenkinsdata def getgitcommitdata(commit_id): response = requests.get(giturl+commit_id, headers = headers, proxies={'http': '10.0.10.251:<proxy_url>'},timeout=5) return response.json()", "\"false\", \"data\": { \"Result\": \"Build Failed\" }, \"error\": {\"Message\": str(e)} } return jsonify(response)", "map.DB_PORT) MONGO_PERF_DB = CLIENT.perf_db MONGO_PERF_DB.authenticate(map.DB_USERNAME, map.DB_PASSWORD) MONGO_PERF_COLLECTION = MONGO_PERF_DB.junit_nightly_build data = {'BranchName': branch_name,", "response = { \"success\": \"false\", \"data\": { \"Result\": \"Build Failed To get data", "= MongoClient(map.DB_IP, map.DB_PORT) MONGO_PERF_DB = CLIENT.perf_db MONGO_PERF_DB.authenticate(map.DB_USERNAME, map.DB_PASSWORD) MONGO_PERF_COLLECTION = MONGO_PERF_DB.junit_nightly_build data =", "{map.token_name: map.token_value} headers1 = {'content-type': 'application/json'} def insertintomnogo(Xmldata, build_id): try: # insert parsed", "auth=(map.jenkins_username, map.jenkins_password)) data = r.json() for item in data['actions']: if 'parameters' in item:", "item: jenkinsdata['branchname'] = item['parameters'][0]['value'] searchremotevalue = remotevalue + jenkinsdata['branchname'] for item in data['actions']:", "gitdata = getgitcommitdata(jenkinsdata['commitid']) logging.debug(\" GitData\" + json.dumps(gitdata)) CommitMessage = gitdata['message'].split('<')[1].split(':')[0] query = {'CommitID':", "MONGO_PERF_DB.junit_nightly_build data = {'BranchName': branch_name, 'Release No': rel_no, 'Build No': build_no, 'JunitURL': junit_url,", "MongoClient(map.DB_IP, map.DB_PORT) MONGO_PERF_DB = CLIENT.perf_db MONGO_PERF_DB.authenticate(map.DB_USERNAME, map.DB_PASSWORD) MONGO_PERF_COLLECTION = MONGO_PERF_DB.junit_test_suite # get commit", "pymongo import MongoClient import requests from flask import jsonify import json import logging", "CLIENT = MongoClient(map.DB_IP, map.DB_PORT) MONGO_PERF_DB = CLIENT.perf_db MONGO_PERF_DB.authenticate(map.DB_USERNAME, map.DB_PASSWORD) MONGO_PERF_COLLECTION = MONGO_PERF_DB.junit_nightly_build data", "GitData\" + json.dumps(gitdata)) CommitMessage = gitdata['message'].split('<')[1].split(':')[0] query = {'CommitID': gitdata['id'], 'SHA': gitdata['short_id'], 'CommitMessage':", "r = requests.get(map.jenkins_url_prefix + build_id + map.jenkins_url_postfix, auth=(map.jenkins_username, map.jenkins_password)) data = r.json() for", "item['parameters'][0]['value'] searchremotevalue = remotevalue + jenkinsdata['branchname'] for item in data['actions']: if 'buildsByBranchName' in", "data=json.dumps(gitdata), headers=headers1) return resp.text except Exception as e: response = { \"success\": \"false\",", "import map from pymongo import MongoClient import requests from flask import jsonify import", "json import logging logging.basicConfig(level=logging.DEBUG) remotevalue = map.remotevalue jenkinsdata = {} build_id = ''", "item in data['actions']: if 'buildsByBranchName' in item: if searchremotevalue in item['buildsByBranchName']: jenkinsdata['commitid'] =", "if 'parameters' in item: jenkinsdata['branchname'] = item['parameters'][0]['value'] searchremotevalue = remotevalue + jenkinsdata['branchname'] for", "<reponame>swiftops/JUNIT_RESULT_AGGREGATION<filename>method.py<gh_stars>1-10 import map from pymongo import MongoClient import requests from flask import jsonify", "remotevalue + jenkinsdata['branchname'] for item in data['actions']: if 'buildsByBranchName' in item: if searchremotevalue", "response = requests.get(giturl+commit_id, headers = headers, proxies={'http': '10.0.10.251:<proxy_url>'},timeout=5) return response.json() def junit_nightlybuild_data(Xmldata, rel_no,", "build_id + map.jenkins_url_postfix, auth=(map.jenkins_username, map.jenkins_password)) data = r.json() for item in data['actions']: if", "rel_no, 'Build No': build_no, 'JunitURL': junit_url, 'JunitData': Xmldata} MONGO_PERF_COLLECTION.insert_one(data) return 'SUCCESS' except Exception", "= { \"success\": \"false\", \"data\": { \"Result\": \"Build Failed\" }, \"error\": {\"Message\": str(e)}", "branch_name, 'Release No': rel_no, 'Build No': build_no, 'JunitURL': junit_url, 'JunitData': Xmldata} MONGO_PERF_COLLECTION.insert_one(data) return", "def getjenkinsdata(build_id): r = requests.get(map.jenkins_url_prefix + build_id + map.jenkins_url_postfix, auth=(map.jenkins_username, map.jenkins_password)) data =", "MONGO_PERF_DB = CLIENT.perf_db MONGO_PERF_DB.authenticate(map.DB_USERNAME, map.DB_PASSWORD) MONGO_PERF_COLLECTION = MONGO_PERF_DB.junit_nightly_build data = {'BranchName': branch_name, 'Release", "{'content-type': 'application/json'} def insertintomnogo(Xmldata, build_id): try: # insert parsed xml data into mongodb", "MONGO_PERF_COLLECTION = MONGO_PERF_DB.junit_test_suite # get commit id from jenkins server jenkinsdata = getjenkinsdata(build_id)", "MONGO_PERF_COLLECTION = MONGO_PERF_DB.junit_nightly_build data = {'BranchName': branch_name, 'Release No': rel_no, 'Build No': build_no,", "'parameters' in item: jenkinsdata['branchname'] = item['parameters'][0]['value'] searchremotevalue = remotevalue + jenkinsdata['branchname'] for item", "import json import logging logging.basicConfig(level=logging.DEBUG) remotevalue = map.remotevalue jenkinsdata = {} build_id =", "+ build_id + map.jenkins_url_postfix, auth=(map.jenkins_username, map.jenkins_password)) data = r.json() for item in data['actions']:", "if 'buildsByBranchName' in item: if searchremotevalue in item['buildsByBranchName']: jenkinsdata['commitid'] = item['buildsByBranchName'][searchremotevalue]['marked']['SHA1'] return jenkinsdata", "CLIENT = MongoClient(map.DB_IP, map.DB_PORT) MONGO_PERF_DB = CLIENT.perf_db MONGO_PERF_DB.authenticate(map.DB_USERNAME, map.DB_PASSWORD) MONGO_PERF_COLLECTION = MONGO_PERF_DB.junit_test_suite #", "{ \"success\": \"false\", \"data\": { \"Result\": \"Build Failed\" }, \"error\": {\"Message\": str(e)} }", "build_id + map.jenkins_url_result, 'Junit_test': Xmldata} MONGO_PERF_COLLECTION.insert_one(query) # call defect creation service resp =", "flask import jsonify import json import logging logging.basicConfig(level=logging.DEBUG) remotevalue = map.remotevalue jenkinsdata =", "parsed xml data into mongodb CLIENT = MongoClient(map.DB_IP, map.DB_PORT) MONGO_PERF_DB = CLIENT.perf_db MONGO_PERF_DB.authenticate(map.DB_USERNAME,", "requests.get(map.jenkins_url_prefix + build_id + map.jenkins_url_postfix, auth=(map.jenkins_username, map.jenkins_password)) data = r.json() for item in", "\"data\": { \"Result\": \"Build Failed To get data for nightly build\" }, \"error\":", "Failed To get data for nightly build\" }, \"error\": {\"Message\": str(e)} } return", "= CLIENT.perf_db MONGO_PERF_DB.authenticate(map.DB_USERNAME, map.DB_PASSWORD) MONGO_PERF_COLLECTION = MONGO_PERF_DB.junit_test_suite # get commit id from jenkins", "build_id, 'Branchname': jenkinsdata['branchname'], 'Ownercode': CommitMessage, 'URL': map.jenkins_public_url_prefix + build_id + map.jenkins_url_result, 'Junit_test': Xmldata}", "= item['buildsByBranchName'][searchremotevalue]['marked']['SHA1'] return jenkinsdata def getgitcommitdata(commit_id): response = requests.get(giturl+commit_id, headers = headers, proxies={'http':", "logging.debug(\" GitData\" + json.dumps(gitdata)) CommitMessage = gitdata['message'].split('<')[1].split(':')[0] query = {'CommitID': gitdata['id'], 'SHA': gitdata['short_id'],", "get commit id from jenkins server jenkinsdata = getjenkinsdata(build_id) logging.debug(\" Jenkinsdata\" + json.dumps(jenkinsdata))", "in data['actions']: if 'buildsByBranchName' in item: if searchremotevalue in item['buildsByBranchName']: jenkinsdata['commitid'] = item['buildsByBranchName'][searchremotevalue]['marked']['SHA1']", "getgitcommitdata(commit_id): response = requests.get(giturl+commit_id, headers = headers, proxies={'http': '10.0.10.251:<proxy_url>'},timeout=5) return response.json() def junit_nightlybuild_data(Xmldata,", "'Branchname': jenkinsdata['branchname'], 'Ownercode': CommitMessage, 'URL': map.jenkins_public_url_prefix + build_id + map.jenkins_url_result, 'Junit_test': Xmldata} MONGO_PERF_COLLECTION.insert_one(query)", "'Author_Email': gitdata['author_email'], 'BuildNumber': build_id, 'Branchname': jenkinsdata['branchname'], 'Ownercode': CommitMessage, 'URL': map.jenkins_public_url_prefix + build_id +", "= {'content-type': 'application/json'} def insertintomnogo(Xmldata, build_id): try: # insert parsed xml data into", "headers1 = {'content-type': 'application/json'} def insertintomnogo(Xmldata, build_id): try: # insert parsed xml data", "try: # insert parsed xml data into mongodb CLIENT = MongoClient(map.DB_IP, map.DB_PORT) MONGO_PERF_DB", "MONGO_PERF_DB.authenticate(map.DB_USERNAME, map.DB_PASSWORD) MONGO_PERF_COLLECTION = MONGO_PERF_DB.junit_test_suite # get commit id from jenkins server jenkinsdata", "gitdata['author_name'], 'Author_Email': gitdata['author_email'], 'BuildNumber': build_id, 'Branchname': jenkinsdata['branchname'], 'Ownercode': CommitMessage, 'URL': map.jenkins_public_url_prefix + build_id", "# insert parsed xml data into mongodb CLIENT = MongoClient(map.DB_IP, map.DB_PORT) MONGO_PERF_DB =", "# get commit id from jenkins server jenkinsdata = getjenkinsdata(build_id) logging.debug(\" Jenkinsdata\" +", "MONGO_PERF_DB = CLIENT.perf_db MONGO_PERF_DB.authenticate(map.DB_USERNAME, map.DB_PASSWORD) MONGO_PERF_COLLECTION = MONGO_PERF_DB.junit_test_suite # get commit id from", "item in data['actions']: if 'parameters' in item: jenkinsdata['branchname'] = item['parameters'][0]['value'] searchremotevalue = remotevalue", "gitdata['id'], 'SHA': gitdata['short_id'], 'CommitMessage': gitdata['message'], 'AuthorName': gitdata['author_name'], 'Author_Email': gitdata['author_email'], 'BuildNumber': build_id, 'Branchname': jenkinsdata['branchname'],", "in data['actions']: if 'parameters' in item: jenkinsdata['branchname'] = item['parameters'][0]['value'] searchremotevalue = remotevalue +", "\"Result\": \"Build Failed\" }, \"error\": {\"Message\": str(e)} } return jsonify(response) def getjenkinsdata(build_id): r", "insertintomnogo(Xmldata, build_id): try: # insert parsed xml data into mongodb CLIENT = MongoClient(map.DB_IP,", "Jenkinsdata\" + json.dumps(jenkinsdata)) # get commit detials from git server gitdata = getgitcommitdata(jenkinsdata['commitid'])", "insert parsed xml data into mongodb for nightly build CLIENT = MongoClient(map.DB_IP, map.DB_PORT)", "+ map.jenkins_url_result, 'Junit_test': Xmldata} MONGO_PERF_COLLECTION.insert_one(query) # call defect creation service resp = requests.post(map.defect_service_url,", "+ json.dumps(jenkinsdata)) # get commit detials from git server gitdata = getgitcommitdata(jenkinsdata['commitid']) logging.debug(\"", "'buildsByBranchName' in item: if searchremotevalue in item['buildsByBranchName']: jenkinsdata['commitid'] = item['buildsByBranchName'][searchremotevalue]['marked']['SHA1'] return jenkinsdata def", "{ \"success\": \"false\", \"data\": { \"Result\": \"Build Failed To get data for nightly", "Xmldata} MONGO_PERF_COLLECTION.insert_one(data) return 'SUCCESS' except Exception as e: response = { \"success\": \"false\",", "mongodb for nightly build CLIENT = MongoClient(map.DB_IP, map.DB_PORT) MONGO_PERF_DB = CLIENT.perf_db MONGO_PERF_DB.authenticate(map.DB_USERNAME, map.DB_PASSWORD)", "resp.text except Exception as e: response = { \"success\": \"false\", \"data\": { \"Result\":", "giturl = map.giturl headers = {map.token_name: map.token_value} headers1 = {'content-type': 'application/json'} def insertintomnogo(Xmldata,", "jenkinsdata = getjenkinsdata(build_id) logging.debug(\" Jenkinsdata\" + json.dumps(jenkinsdata)) # get commit detials from git", "map.jenkins_password)) data = r.json() for item in data['actions']: if 'parameters' in item: jenkinsdata['branchname']", "jenkinsdata['branchname'] = item['parameters'][0]['value'] searchremotevalue = remotevalue + jenkinsdata['branchname'] for item in data['actions']: if", "for item in data['actions']: if 'buildsByBranchName' in item: if searchremotevalue in item['buildsByBranchName']: jenkinsdata['commitid']", "'JunitData': Xmldata} MONGO_PERF_COLLECTION.insert_one(data) return 'SUCCESS' except Exception as e: response = { \"success\":", "Failed\" }, \"error\": {\"Message\": str(e)} } return jsonify(response) def getjenkinsdata(build_id): r = requests.get(map.jenkins_url_prefix", "json.dumps(jenkinsdata)) # get commit detials from git server gitdata = getgitcommitdata(jenkinsdata['commitid']) logging.debug(\" GitData\"", "server gitdata = getgitcommitdata(jenkinsdata['commitid']) logging.debug(\" GitData\" + json.dumps(gitdata)) CommitMessage = gitdata['message'].split('<')[1].split(':')[0] query =", "'JunitURL': junit_url, 'JunitData': Xmldata} MONGO_PERF_COLLECTION.insert_one(data) return 'SUCCESS' except Exception as e: response =", "CommitMessage, 'URL': map.jenkins_public_url_prefix + build_id + map.jenkins_url_result, 'Junit_test': Xmldata} MONGO_PERF_COLLECTION.insert_one(query) # call defect", "insert parsed xml data into mongodb CLIENT = MongoClient(map.DB_IP, map.DB_PORT) MONGO_PERF_DB = CLIENT.perf_db", "junit_url, 'JunitData': Xmldata} MONGO_PERF_COLLECTION.insert_one(data) return 'SUCCESS' except Exception as e: response = {", "\"success\": \"false\", \"data\": { \"Result\": \"Build Failed\" }, \"error\": {\"Message\": str(e)} } return", "= {'CommitID': gitdata['id'], 'SHA': gitdata['short_id'], 'CommitMessage': gitdata['message'], 'AuthorName': gitdata['author_name'], 'Author_Email': gitdata['author_email'], 'BuildNumber': build_id,", "in item['buildsByBranchName']: jenkinsdata['commitid'] = item['buildsByBranchName'][searchremotevalue]['marked']['SHA1'] return jenkinsdata def getgitcommitdata(commit_id): response = requests.get(giturl+commit_id, headers", "data into mongodb for nightly build CLIENT = MongoClient(map.DB_IP, map.DB_PORT) MONGO_PERF_DB = CLIENT.perf_db", "map.DB_PORT) MONGO_PERF_DB = CLIENT.perf_db MONGO_PERF_DB.authenticate(map.DB_USERNAME, map.DB_PASSWORD) MONGO_PERF_COLLECTION = MONGO_PERF_DB.junit_test_suite # get commit id", "str(e)} } return jsonify(response) def getjenkinsdata(build_id): r = requests.get(map.jenkins_url_prefix + build_id + map.jenkins_url_postfix,", "nightly build CLIENT = MongoClient(map.DB_IP, map.DB_PORT) MONGO_PERF_DB = CLIENT.perf_db MONGO_PERF_DB.authenticate(map.DB_USERNAME, map.DB_PASSWORD) MONGO_PERF_COLLECTION =", "headers=headers1) return resp.text except Exception as e: response = { \"success\": \"false\", \"data\":", "parsed xml data into mongodb for nightly build CLIENT = MongoClient(map.DB_IP, map.DB_PORT) MONGO_PERF_DB", "= MONGO_PERF_DB.junit_nightly_build data = {'BranchName': branch_name, 'Release No': rel_no, 'Build No': build_no, 'JunitURL':", "map.giturl headers = {map.token_name: map.token_value} headers1 = {'content-type': 'application/json'} def insertintomnogo(Xmldata, build_id): try:", "No': build_no, 'JunitURL': junit_url, 'JunitData': Xmldata} MONGO_PERF_COLLECTION.insert_one(data) return 'SUCCESS' except Exception as e:", "{'CommitID': gitdata['id'], 'SHA': gitdata['short_id'], 'CommitMessage': gitdata['message'], 'AuthorName': gitdata['author_name'], 'Author_Email': gitdata['author_email'], 'BuildNumber': build_id, 'Branchname':", "service resp = requests.post(map.defect_service_url, data=json.dumps(gitdata), headers=headers1) return resp.text except Exception as e: response", "if searchremotevalue in item['buildsByBranchName']: jenkinsdata['commitid'] = item['buildsByBranchName'][searchremotevalue]['marked']['SHA1'] return jenkinsdata def getgitcommitdata(commit_id): response =", "+ jenkinsdata['branchname'] for item in data['actions']: if 'buildsByBranchName' in item: if searchremotevalue in", "try: # insert parsed xml data into mongodb for nightly build CLIENT =", "= item['parameters'][0]['value'] searchremotevalue = remotevalue + jenkinsdata['branchname'] for item in data['actions']: if 'buildsByBranchName'", "\"Build Failed\" }, \"error\": {\"Message\": str(e)} } return jsonify(response) def getjenkinsdata(build_id): r =", "gitdata['author_email'], 'BuildNumber': build_id, 'Branchname': jenkinsdata['branchname'], 'Ownercode': CommitMessage, 'URL': map.jenkins_public_url_prefix + build_id + map.jenkins_url_result,", "= { \"success\": \"false\", \"data\": { \"Result\": \"Build Failed To get data for", "map.jenkins_url_result, 'Junit_test': Xmldata} MONGO_PERF_COLLECTION.insert_one(query) # call defect creation service resp = requests.post(map.defect_service_url, data=json.dumps(gitdata),", "server jenkinsdata = getjenkinsdata(build_id) logging.debug(\" Jenkinsdata\" + json.dumps(jenkinsdata)) # get commit detials from", "Exception as e: response = { \"success\": \"false\", \"data\": { \"Result\": \"Build Failed", "= MONGO_PERF_DB.junit_test_suite # get commit id from jenkins server jenkinsdata = getjenkinsdata(build_id) logging.debug(\"", "\"Build Failed To get data for nightly build\" }, \"error\": {\"Message\": str(e)} }", "jenkinsdata['branchname'], 'Ownercode': CommitMessage, 'URL': map.jenkins_public_url_prefix + build_id + map.jenkins_url_result, 'Junit_test': Xmldata} MONGO_PERF_COLLECTION.insert_one(query) #", "jsonify import json import logging logging.basicConfig(level=logging.DEBUG) remotevalue = map.remotevalue jenkinsdata = {} build_id", "= requests.get(map.jenkins_url_prefix + build_id + map.jenkins_url_postfix, auth=(map.jenkins_username, map.jenkins_password)) data = r.json() for item", "return jenkinsdata def getgitcommitdata(commit_id): response = requests.get(giturl+commit_id, headers = headers, proxies={'http': '10.0.10.251:<proxy_url>'},timeout=5) return", "detials from git server gitdata = getgitcommitdata(jenkinsdata['commitid']) logging.debug(\" GitData\" + json.dumps(gitdata)) CommitMessage =", "MONGO_PERF_COLLECTION.insert_one(data) return 'SUCCESS' except Exception as e: response = { \"success\": \"false\", \"data\":", "import logging logging.basicConfig(level=logging.DEBUG) remotevalue = map.remotevalue jenkinsdata = {} build_id = '' giturl", "jenkinsdata['branchname'] for item in data['actions']: if 'buildsByBranchName' in item: if searchremotevalue in item['buildsByBranchName']:", "response.json() def junit_nightlybuild_data(Xmldata, rel_no, build_no, junit_url, branch_name): try: # insert parsed xml data", "MONGO_PERF_DB.junit_test_suite # get commit id from jenkins server jenkinsdata = getjenkinsdata(build_id) logging.debug(\" Jenkinsdata\"", "\"false\", \"data\": { \"Result\": \"Build Failed To get data for nightly build\" },", "'SUCCESS' except Exception as e: response = { \"success\": \"false\", \"data\": { \"Result\":", "getjenkinsdata(build_id): r = requests.get(map.jenkins_url_prefix + build_id + map.jenkins_url_postfix, auth=(map.jenkins_username, map.jenkins_password)) data = r.json()", "No': rel_no, 'Build No': build_no, 'JunitURL': junit_url, 'JunitData': Xmldata} MONGO_PERF_COLLECTION.insert_one(data) return 'SUCCESS' except", "map.DB_PASSWORD) MONGO_PERF_COLLECTION = MONGO_PERF_DB.junit_test_suite # get commit id from jenkins server jenkinsdata =", "# insert parsed xml data into mongodb for nightly build CLIENT = MongoClient(map.DB_IP,", "commit id from jenkins server jenkinsdata = getjenkinsdata(build_id) logging.debug(\" Jenkinsdata\" + json.dumps(jenkinsdata)) #", "= remotevalue + jenkinsdata['branchname'] for item in data['actions']: if 'buildsByBranchName' in item: if", "commit detials from git server gitdata = getgitcommitdata(jenkinsdata['commitid']) logging.debug(\" GitData\" + json.dumps(gitdata)) CommitMessage", "headers = {map.token_name: map.token_value} headers1 = {'content-type': 'application/json'} def insertintomnogo(Xmldata, build_id): try: #", "getgitcommitdata(jenkinsdata['commitid']) logging.debug(\" GitData\" + json.dumps(gitdata)) CommitMessage = gitdata['message'].split('<')[1].split(':')[0] query = {'CommitID': gitdata['id'], 'SHA':", "for item in data['actions']: if 'parameters' in item: jenkinsdata['branchname'] = item['parameters'][0]['value'] searchremotevalue =", "proxies={'http': '10.0.10.251:<proxy_url>'},timeout=5) return response.json() def junit_nightlybuild_data(Xmldata, rel_no, build_no, junit_url, branch_name): try: # insert", "'application/json'} def insertintomnogo(Xmldata, build_id): try: # insert parsed xml data into mongodb CLIENT", "branch_name): try: # insert parsed xml data into mongodb for nightly build CLIENT", "data = {'BranchName': branch_name, 'Release No': rel_no, 'Build No': build_no, 'JunitURL': junit_url, 'JunitData':", "MONGO_PERF_DB.authenticate(map.DB_USERNAME, map.DB_PASSWORD) MONGO_PERF_COLLECTION = MONGO_PERF_DB.junit_nightly_build data = {'BranchName': branch_name, 'Release No': rel_no, 'Build", "map.remotevalue jenkinsdata = {} build_id = '' giturl = map.giturl headers = {map.token_name:", "jsonify(response) def getjenkinsdata(build_id): r = requests.get(map.jenkins_url_prefix + build_id + map.jenkins_url_postfix, auth=(map.jenkins_username, map.jenkins_password)) data", "build_id = '' giturl = map.giturl headers = {map.token_name: map.token_value} headers1 = {'content-type':", "id from jenkins server jenkinsdata = getjenkinsdata(build_id) logging.debug(\" Jenkinsdata\" + json.dumps(jenkinsdata)) # get", "return jsonify(response) def getjenkinsdata(build_id): r = requests.get(map.jenkins_url_prefix + build_id + map.jenkins_url_postfix, auth=(map.jenkins_username, map.jenkins_password))", "= r.json() for item in data['actions']: if 'parameters' in item: jenkinsdata['branchname'] = item['parameters'][0]['value']", "requests.get(giturl+commit_id, headers = headers, proxies={'http': '10.0.10.251:<proxy_url>'},timeout=5) return response.json() def junit_nightlybuild_data(Xmldata, rel_no, build_no, junit_url,", "import jsonify import json import logging logging.basicConfig(level=logging.DEBUG) remotevalue = map.remotevalue jenkinsdata = {}", "as e: response = { \"success\": \"false\", \"data\": { \"Result\": \"Build Failed To", "e: response = { \"success\": \"false\", \"data\": { \"Result\": \"Build Failed\" }, \"error\":", "resp = requests.post(map.defect_service_url, data=json.dumps(gitdata), headers=headers1) return resp.text except Exception as e: response =", "jenkinsdata['commitid'] = item['buildsByBranchName'][searchremotevalue]['marked']['SHA1'] return jenkinsdata def getgitcommitdata(commit_id): response = requests.get(giturl+commit_id, headers = headers,", "headers = headers, proxies={'http': '10.0.10.251:<proxy_url>'},timeout=5) return response.json() def junit_nightlybuild_data(Xmldata, rel_no, build_no, junit_url, branch_name):", "'' giturl = map.giturl headers = {map.token_name: map.token_value} headers1 = {'content-type': 'application/json'} def", "get commit detials from git server gitdata = getgitcommitdata(jenkinsdata['commitid']) logging.debug(\" GitData\" + json.dumps(gitdata))", "+ map.jenkins_url_postfix, auth=(map.jenkins_username, map.jenkins_password)) data = r.json() for item in data['actions']: if 'parameters'", "data['actions']: if 'parameters' in item: jenkinsdata['branchname'] = item['parameters'][0]['value'] searchremotevalue = remotevalue + jenkinsdata['branchname']", "= {'BranchName': branch_name, 'Release No': rel_no, 'Build No': build_no, 'JunitURL': junit_url, 'JunitData': Xmldata}", "import requests from flask import jsonify import json import logging logging.basicConfig(level=logging.DEBUG) remotevalue =", "gitdata['message'].split('<')[1].split(':')[0] query = {'CommitID': gitdata['id'], 'SHA': gitdata['short_id'], 'CommitMessage': gitdata['message'], 'AuthorName': gitdata['author_name'], 'Author_Email': gitdata['author_email'],", "'AuthorName': gitdata['author_name'], 'Author_Email': gitdata['author_email'], 'BuildNumber': build_id, 'Branchname': jenkinsdata['branchname'], 'Ownercode': CommitMessage, 'URL': map.jenkins_public_url_prefix +", "response = { \"success\": \"false\", \"data\": { \"Result\": \"Build Failed\" }, \"error\": {\"Message\":", "}, \"error\": {\"Message\": str(e)} } return jsonify(response) def getjenkinsdata(build_id): r = requests.get(map.jenkins_url_prefix +", "map.jenkins_url_postfix, auth=(map.jenkins_username, map.jenkins_password)) data = r.json() for item in data['actions']: if 'parameters' in", "r.json() for item in data['actions']: if 'parameters' in item: jenkinsdata['branchname'] = item['parameters'][0]['value'] searchremotevalue", "searchremotevalue in item['buildsByBranchName']: jenkinsdata['commitid'] = item['buildsByBranchName'][searchremotevalue]['marked']['SHA1'] return jenkinsdata def getgitcommitdata(commit_id): response = requests.get(giturl+commit_id,", "return response.json() def junit_nightlybuild_data(Xmldata, rel_no, build_no, junit_url, branch_name): try: # insert parsed xml", "{\"Message\": str(e)} } return jsonify(response) def getjenkinsdata(build_id): r = requests.get(map.jenkins_url_prefix + build_id +", "build_id): try: # insert parsed xml data into mongodb CLIENT = MongoClient(map.DB_IP, map.DB_PORT)", "item: if searchremotevalue in item['buildsByBranchName']: jenkinsdata['commitid'] = item['buildsByBranchName'][searchremotevalue]['marked']['SHA1'] return jenkinsdata def getgitcommitdata(commit_id): response", "'Junit_test': Xmldata} MONGO_PERF_COLLECTION.insert_one(query) # call defect creation service resp = requests.post(map.defect_service_url, data=json.dumps(gitdata), headers=headers1)", "MongoClient(map.DB_IP, map.DB_PORT) MONGO_PERF_DB = CLIENT.perf_db MONGO_PERF_DB.authenticate(map.DB_USERNAME, map.DB_PASSWORD) MONGO_PERF_COLLECTION = MONGO_PERF_DB.junit_nightly_build data = {'BranchName':", "build_no, 'JunitURL': junit_url, 'JunitData': Xmldata} MONGO_PERF_COLLECTION.insert_one(data) return 'SUCCESS' except Exception as e: response", "= gitdata['message'].split('<')[1].split(':')[0] query = {'CommitID': gitdata['id'], 'SHA': gitdata['short_id'], 'CommitMessage': gitdata['message'], 'AuthorName': gitdata['author_name'], 'Author_Email':", "} return jsonify(response) def getjenkinsdata(build_id): r = requests.get(map.jenkins_url_prefix + build_id + map.jenkins_url_postfix, auth=(map.jenkins_username,", "in item: if searchremotevalue in item['buildsByBranchName']: jenkinsdata['commitid'] = item['buildsByBranchName'][searchremotevalue]['marked']['SHA1'] return jenkinsdata def getgitcommitdata(commit_id):", "= CLIENT.perf_db MONGO_PERF_DB.authenticate(map.DB_USERNAME, map.DB_PASSWORD) MONGO_PERF_COLLECTION = MONGO_PERF_DB.junit_nightly_build data = {'BranchName': branch_name, 'Release No':", "item['buildsByBranchName']: jenkinsdata['commitid'] = item['buildsByBranchName'][searchremotevalue]['marked']['SHA1'] return jenkinsdata def getgitcommitdata(commit_id): response = requests.get(giturl+commit_id, headers =", "creation service resp = requests.post(map.defect_service_url, data=json.dumps(gitdata), headers=headers1) return resp.text except Exception as e:", "logging.basicConfig(level=logging.DEBUG) remotevalue = map.remotevalue jenkinsdata = {} build_id = '' giturl = map.giturl", "junit_url, branch_name): try: # insert parsed xml data into mongodb for nightly build", "getjenkinsdata(build_id) logging.debug(\" Jenkinsdata\" + json.dumps(jenkinsdata)) # get commit detials from git server gitdata", "{ \"Result\": \"Build Failed To get data for nightly build\" }, \"error\": {\"Message\":", "'10.0.10.251:<proxy_url>'},timeout=5) return response.json() def junit_nightlybuild_data(Xmldata, rel_no, build_no, junit_url, branch_name): try: # insert parsed", "for nightly build CLIENT = MongoClient(map.DB_IP, map.DB_PORT) MONGO_PERF_DB = CLIENT.perf_db MONGO_PERF_DB.authenticate(map.DB_USERNAME, map.DB_PASSWORD) MONGO_PERF_COLLECTION", "item['buildsByBranchName'][searchremotevalue]['marked']['SHA1'] return jenkinsdata def getgitcommitdata(commit_id): response = requests.get(giturl+commit_id, headers = headers, proxies={'http': '10.0.10.251:<proxy_url>'},timeout=5)", "return resp.text except Exception as e: response = { \"success\": \"false\", \"data\": {", "from flask import jsonify import json import logging logging.basicConfig(level=logging.DEBUG) remotevalue = map.remotevalue jenkinsdata", "CLIENT.perf_db MONGO_PERF_DB.authenticate(map.DB_USERNAME, map.DB_PASSWORD) MONGO_PERF_COLLECTION = MONGO_PERF_DB.junit_test_suite # get commit id from jenkins server", "map.jenkins_public_url_prefix + build_id + map.jenkins_url_result, 'Junit_test': Xmldata} MONGO_PERF_COLLECTION.insert_one(query) # call defect creation service", "\"success\": \"false\", \"data\": { \"Result\": \"Build Failed To get data for nightly build\"", "'Release No': rel_no, 'Build No': build_no, 'JunitURL': junit_url, 'JunitData': Xmldata} MONGO_PERF_COLLECTION.insert_one(data) return 'SUCCESS'", "json.dumps(gitdata)) CommitMessage = gitdata['message'].split('<')[1].split(':')[0] query = {'CommitID': gitdata['id'], 'SHA': gitdata['short_id'], 'CommitMessage': gitdata['message'], 'AuthorName':", "{'BranchName': branch_name, 'Release No': rel_no, 'Build No': build_no, 'JunitURL': junit_url, 'JunitData': Xmldata} MONGO_PERF_COLLECTION.insert_one(data)", "data['actions']: if 'buildsByBranchName' in item: if searchremotevalue in item['buildsByBranchName']: jenkinsdata['commitid'] = item['buildsByBranchName'][searchremotevalue]['marked']['SHA1'] return", "gitdata['message'], 'AuthorName': gitdata['author_name'], 'Author_Email': gitdata['author_email'], 'BuildNumber': build_id, 'Branchname': jenkinsdata['branchname'], 'Ownercode': CommitMessage, 'URL': map.jenkins_public_url_prefix", "query = {'CommitID': gitdata['id'], 'SHA': gitdata['short_id'], 'CommitMessage': gitdata['message'], 'AuthorName': gitdata['author_name'], 'Author_Email': gitdata['author_email'], 'BuildNumber':", "call defect creation service resp = requests.post(map.defect_service_url, data=json.dumps(gitdata), headers=headers1) return resp.text except Exception", "map.DB_PASSWORD) MONGO_PERF_COLLECTION = MONGO_PERF_DB.junit_nightly_build data = {'BranchName': branch_name, 'Release No': rel_no, 'Build No':", "\"Result\": \"Build Failed To get data for nightly build\" }, \"error\": {\"Message\": str(e)}", "in item: jenkinsdata['branchname'] = item['parameters'][0]['value'] searchremotevalue = remotevalue + jenkinsdata['branchname'] for item in", "def getgitcommitdata(commit_id): response = requests.get(giturl+commit_id, headers = headers, proxies={'http': '10.0.10.251:<proxy_url>'},timeout=5) return response.json() def", "def insertintomnogo(Xmldata, build_id): try: # insert parsed xml data into mongodb CLIENT =", "return 'SUCCESS' except Exception as e: response = { \"success\": \"false\", \"data\": {", "= {map.token_name: map.token_value} headers1 = {'content-type': 'application/json'} def insertintomnogo(Xmldata, build_id): try: # insert", "+ json.dumps(gitdata)) CommitMessage = gitdata['message'].split('<')[1].split(':')[0] query = {'CommitID': gitdata['id'], 'SHA': gitdata['short_id'], 'CommitMessage': gitdata['message'],", "gitdata['short_id'], 'CommitMessage': gitdata['message'], 'AuthorName': gitdata['author_name'], 'Author_Email': gitdata['author_email'], 'BuildNumber': build_id, 'Branchname': jenkinsdata['branchname'], 'Ownercode': CommitMessage,", "requests from flask import jsonify import json import logging logging.basicConfig(level=logging.DEBUG) remotevalue = map.remotevalue", "Exception as e: response = { \"success\": \"false\", \"data\": { \"Result\": \"Build Failed\"", "from jenkins server jenkinsdata = getjenkinsdata(build_id) logging.debug(\" Jenkinsdata\" + json.dumps(jenkinsdata)) # get commit", "defect creation service resp = requests.post(map.defect_service_url, data=json.dumps(gitdata), headers=headers1) return resp.text except Exception as", "remotevalue = map.remotevalue jenkinsdata = {} build_id = '' giturl = map.giturl headers", "'CommitMessage': gitdata['message'], 'AuthorName': gitdata['author_name'], 'Author_Email': gitdata['author_email'], 'BuildNumber': build_id, 'Branchname': jenkinsdata['branchname'], 'Ownercode': CommitMessage, 'URL':", "xml data into mongodb for nightly build CLIENT = MongoClient(map.DB_IP, map.DB_PORT) MONGO_PERF_DB =", "data into mongodb CLIENT = MongoClient(map.DB_IP, map.DB_PORT) MONGO_PERF_DB = CLIENT.perf_db MONGO_PERF_DB.authenticate(map.DB_USERNAME, map.DB_PASSWORD) MONGO_PERF_COLLECTION", "= getgitcommitdata(jenkinsdata['commitid']) logging.debug(\" GitData\" + json.dumps(gitdata)) CommitMessage = gitdata['message'].split('<')[1].split(':')[0] query = {'CommitID': gitdata['id'],", "'Ownercode': CommitMessage, 'URL': map.jenkins_public_url_prefix + build_id + map.jenkins_url_result, 'Junit_test': Xmldata} MONGO_PERF_COLLECTION.insert_one(query) # call", "into mongodb for nightly build CLIENT = MongoClient(map.DB_IP, map.DB_PORT) MONGO_PERF_DB = CLIENT.perf_db MONGO_PERF_DB.authenticate(map.DB_USERNAME,", "= map.remotevalue jenkinsdata = {} build_id = '' giturl = map.giturl headers =", "except Exception as e: response = { \"success\": \"false\", \"data\": { \"Result\": \"Build", "= requests.get(giturl+commit_id, headers = headers, proxies={'http': '10.0.10.251:<proxy_url>'},timeout=5) return response.json() def junit_nightlybuild_data(Xmldata, rel_no, build_no,", "map from pymongo import MongoClient import requests from flask import jsonify import json", "data = r.json() for item in data['actions']: if 'parameters' in item: jenkinsdata['branchname'] =", "\"data\": { \"Result\": \"Build Failed\" }, \"error\": {\"Message\": str(e)} } return jsonify(response) def", "jenkins server jenkinsdata = getjenkinsdata(build_id) logging.debug(\" Jenkinsdata\" + json.dumps(jenkinsdata)) # get commit detials", "e: response = { \"success\": \"false\", \"data\": { \"Result\": \"Build Failed To get" ]
[ "= pd.DataFrame.from_dict(data_dict, orient='columns') df.reset_index(inplace=True) boxplot_environment(df) if __name__ == \"__main__\": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-r',", "'--root', type=str, default=\"\", help='Root filepath of the log data') parser.add_argument('-s', '--soil', type=str, default=\"soil_moisture_sensor_1.txt\",", "1.5 * IQR (IQR = Q3 - Q1) from the edges of the", "the range of the data. The position of the whiskers is set by", "whiskers is set by default to 1.5 * IQR (IQR = Q3 -", "ax[1].set_ylabel(\"VOC (kΩ)\") ax[2].set_ylabel(\"Humidity (%)\") plt.subplots_adjust(top=0.95) DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) plt.savefig('Environment_Boxplot.png', dpi=500) # plt.show()", "plt.title(\"Soil Moisture % Past 24 Hrs\") ax.xaxis.set_major_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) plt.savefig('Moisture_vs_Time_24H.png', dpi=500) plt.savefig('Moisture_vs_Time.png', dpi=500) #", "use for matching. \"\"\" matches = list() for line in data: matches.append(re.match(pattern, line))", "ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) plt.savefig('Temperature_vs_Time_24H.png', dpi=500) plt.savefig('Temperature_vs_Time.png', dpi=500) # plt.show() def boxplot_environment(df): \"\"\"! Creates a boxplot", "plt.show() def plot_temperature(dict, past24): \"\"\"! Plots temperature data in simple line chart @param", "temperature_dict = dict() data_dict['Temperature'] = {} data_dict['VOC'] = {} data_dict['Humidity'] = {} for", "plt.title(\"Soil Moisture % vs Time\") DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) if past24: datemin =", "import matplotlib.dates as mdates import matplotlib.image as image import pandas as pd import", "dpi=500) # plt.show() def plot_temperature(dict, past24): \"\"\"! Plots temperature data in simple line", "https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.boxplot.html: The box extends from the Q1 to Q3 quartile values of the", "(IQR = Q3 - Q1) from the edges of the box. Outlier points", "myfile: data = myfile.readlines() matches = extract_data_from_log(data, soil_moisture_pattern) data_dict = dict() for match", "{} data_dict['VOC'] = {} data_dict['Humidity'] = {} for match in matches: index_time =", "alpha=0.2) ax.xaxis.set_minor_locator(hours3) ax.tick_params(which='major', length=7, width=2, color='black') ax.tick_params(which='minor', length=4, width=2, color='black') ax.xaxis.set_major_locator(hours6) ax.xaxis.set_major_formatter(mdates.DateFormatter('%d -", "'h') ax.set_xlim(datemin, datemax) plt.xlabel(\"Hour\") plt.title('Temperature Past 24 Hrs') ax.xaxis.set_major_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) plt.savefig('Temperature_vs_Time_24H.png', dpi=500) plt.savefig('Temperature_vs_Time.png',", "match objects. @param data: Raw data from the log file. @param pattern: Regex", "fig, ax = plt.subplots(1, 3) fig.suptitle('Environment Sensor Data') df.boxplot('Temperature', ax=ax[0]) df.boxplot('VOC', ax=ax[1], fontsize=12)", "the relevant environment sensor data. What is a boxplot? Text from https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.boxplot.html: The", "= {} data_dict['Humidity'] = {} for match in matches: index_time = match.group(1) +", "with open(root+environment_sensor_log, \"r\") as myfile: data = myfile.readlines() matches = extract_data_from_log(data, environment_sensor_pattern) data_dict", "ax.xaxis.set_minor_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%d - %H')) ax.tick_params(which='major', length=7, width=2, color='black') ax.tick_params(which='minor', length=4, width=2, color='black') ax.grid()", "box. Outlier points are those past the end of the whiskers. @param df:", "# Plot temperature data with open(root+environment_sensor_log, \"r\") as myfile: data = myfile.readlines() matches", "\"r\") as myfile: data = myfile.readlines() matches = extract_data_from_log(data, soil_moisture_pattern) data_dict = dict()", "of the envrionment sensor log file') args = parser.parse_args() if args.root: root_folder =", "__name__ == \"__main__\": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-r', '--root', type=str, default=\"\", help='Root filepath of", "+ match.group(2) index_dt = dt.datetime.strptime(index_time, \"%Y-%m-%d %H:%M:%S.%f\") data_dict[index_dt] = current_val plot_soil_moisture(data_dict, True) plot_soil_moisture(data_dict,", "plt.xlabel(\"Time (Month-Day Hour)\") plt.ylabel(\"Temperature (°C)\") DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) if past24: datemin =", "width=2, color='black') ax.tick_params(which='minor', length=4, width=2, color='black') ax.xaxis.set_major_locator(hours6) ax.xaxis.set_major_formatter(mdates.DateFormatter('%d - %H')) ax.grid() plt.xlabel(\"Day -", "- Hour\") plt.ylabel(\"Moisture Percentage (%)\") plt.title(\"Soil Moisture % vs Time\") DPI = fig.get_dpi()", "plt.ylabel(\"Moisture Percentage (%)\") plt.title(\"Soil Moisture % vs Time\") DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) if", "def extract_data_from_log(data, pattern): \"\"\"! Function for extracting data out of a log file", "match.group(2) index_dt = dt.datetime.strptime(index_time, \"%Y-%m-%d %H:%M:%S.%f\") data_dict['Temperature'][index_dt] = float(match.group(3)) data_dict['VOC'][index_dt] = float(match.group(4)) data_dict['Humidity'][index_dt]", "parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-r', '--root', type=str, default=\"\", help='Root filepath of the log data')", "the end of the whiskers. @param df: dataframe object from which we generate", "in data: matches.append(re.match(pattern, line)) return matches def generate_plots(root=\"./logs/\", soil_sensor_log=\"soil_moisture_sensor_1.txt\", environment_sensor_log=\"environment_sensor.txt\"): # Plot soil", "matches: # current_val = float(match.group(4)) # Raw voltage reading current_val = float(match.group(5)) #", "Raw data from the log file. @param pattern: Regex pattern to use for", "sensor log file') parser.add_argument('-e', '--environment', type=str, default=\"environment_sensor.txt\", help='Name of the envrionment sensor log", "True) plot_temperature(data_dict['Temperature'], False) # Plot environment sensor data df = pd.DataFrame.from_dict(data_dict, orient='columns') df.reset_index(inplace=True)", "for extracting data out of a log file using regex matching. Returns all", "# fig.figimage(im, 300, 0, zorder=3, alpha=0.2) ax.xaxis.set_minor_locator(hours3) ax.tick_params(which='major', length=7, width=2, color='black') ax.tick_params(which='minor', length=4,", "= fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) if past24: datemin = np.datetime64(x[-1], 'h') - np.timedelta64(24, 'h') datemax", "# plt.show() def plot_temperature(dict, past24): \"\"\"! Plots temperature data in simple line chart", "Hrs') ax.xaxis.set_major_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) plt.savefig('Temperature_vs_Time_24H.png', dpi=500) plt.savefig('Temperature_vs_Time.png', dpi=500) # plt.show() def boxplot_environment(df): \"\"\"! Creates", "range of the data. The position of the whiskers is set by default", "== \"__main__\": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-r', '--root', type=str, default=\"\", help='Root filepath of the", "which we generate a boxplot. \"\"\" df['VOC'] = df['VOC'].div(1000) # with plt.style.context(\"seaborn\"): fig,", "plt.show() def extract_data_from_log(data, pattern): \"\"\"! Function for extracting data out of a log", "Function for extracting data out of a log file using regex matching. Returns", "matches: index_time = match.group(1) + \" \" + match.group(2) index_dt = dt.datetime.strptime(index_time, \"%Y-%m-%d", "# fig.figimage(im, 650, 0, zorder=3, alpha=0.2) ax.xaxis.set_major_locator(hours6) ax.xaxis.set_minor_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%d - %H')) ax.tick_params(which='major', length=7,", "quartile values of the data, with a line at the median (Q2). The", "\"\"\" import matplotlib.pylab as plt import matplotlib.dates as mdates import matplotlib.image as image", "of soil moisture sensor log file') parser.add_argument('-e', '--environment', type=str, default=\"environment_sensor.txt\", help='Name of the", "moisture data with open(root+soil_sensor_log, \"r\") as myfile: data = myfile.readlines() matches = extract_data_from_log(data,", "DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) if past24: datemin = np.datetime64(x[-1], 'h') - np.timedelta64(24, 'h')", "y, 'k', linewidth=2) fig.autofmt_xdate() hours6 = mdates.HourLocator(interval=6) hours3 = mdates.HourLocator(interval=3) # im =", "to show the range of the data. The position of the whiskers is", "for match in matches: index_time = match.group(1) + \" \" + match.group(2) index_dt", "past the end of the whiskers. @param df: dataframe object from which we", "- np.timedelta64(24, 'h') datemax = np.datetime64(x[-1], 'h') ax.set_xlim(datemin, datemax) plt.xlabel(\"Hour\") plt.title('Temperature Past 24", "False) # Plot temperature data with open(root+environment_sensor_log, \"r\") as myfile: data = myfile.readlines()", "from the Q1 to Q3 quartile values of the data, with a line", "plt.ylabel(\"Temperature (°C)\") DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) if past24: datemin = np.datetime64(x[-1], 'h') -", "from the edges of box to show the range of the data. The", "soil_moisture_pattern = re.compile(r\"([0-9-]+)\\s([0-9.:]+):\\s\\[([0-9]+),\\s([0-9.]+),\\s([0-9.]+)\\]\", re.MULTILINE) def plot_soil_moisture(dict, past24): \"\"\"! Plots soil moisture data in", "with open(root+soil_sensor_log, \"r\") as myfile: data = myfile.readlines() matches = extract_data_from_log(data, soil_moisture_pattern) data_dict", "data = myfile.readlines() matches = extract_data_from_log(data, soil_moisture_pattern) data_dict = dict() for match in", "dict() temperature_dict = dict() data_dict['Temperature'] = {} data_dict['VOC'] = {} data_dict['Humidity'] = {}", "\"\"\"! Plots temperature data in simple line chart @param dict: Dicitonary containing timestamps", "fig.figimage(im, 650, 0, zorder=3, alpha=0.2) ax.xaxis.set_major_locator(hours6) ax.xaxis.set_minor_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%d - %H')) ax.tick_params(which='major', length=7, width=2,", "= extract_data_from_log(data, soil_moisture_pattern) data_dict = dict() for match in matches: # current_val =", "'h') datemax = np.datetime64(x[-1], 'h') ax.set_xlim(datemin, datemax) plt.xlabel(\"Hour\") plt.title('Temperature Past 24 Hrs') ax.xaxis.set_major_locator(hours3)", "plt.title(\"Temperature Over Time\") plt.xlabel(\"Time (Month-Day Hour)\") plt.ylabel(\"Temperature (°C)\") DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) if", "= list() for line in data: matches.append(re.match(pattern, line)) return matches def generate_plots(root=\"./logs/\", soil_sensor_log=\"soil_moisture_sensor_1.txt\",", "log data') parser.add_argument('-s', '--soil', type=str, default=\"soil_moisture_sensor_1.txt\", help='Name of soil moisture sensor log file')", "file') parser.add_argument('-e', '--environment', type=str, default=\"environment_sensor.txt\", help='Name of the envrionment sensor log file') args", "alpha=0.2) ax.xaxis.set_major_locator(hours6) ax.xaxis.set_minor_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%d - %H')) ax.tick_params(which='major', length=7, width=2, color='black') ax.tick_params(which='minor', length=4, width=2,", "'--soil', type=str, default=\"soil_moisture_sensor_1.txt\", help='Name of soil moisture sensor log file') parser.add_argument('-e', '--environment', type=str,", "'h') - np.timedelta64(24, 'h') datemax = np.datetime64(x[-1], 'h') ax.set_xlim(datemin, datemax) plt.xlabel(\"Hour\") plt.title('Temperature Past", "hours6 = mdates.HourLocator(interval=6) hours3 = mdates.HourLocator(interval=3) # im = image.imread('./icons/Grow_Space_Logo.png') # fig.figimage(im, 650,", "orient='columns') df.reset_index(inplace=True) boxplot_environment(df) if __name__ == \"__main__\": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-r', '--root', type=str,", "if __name__ == \"__main__\": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-r', '--root', type=str, default=\"\", help='Root filepath", "boxplot. \"\"\" df['VOC'] = df['VOC'].div(1000) # with plt.style.context(\"seaborn\"): fig, ax = plt.subplots(1, 3)", "log file. @param pattern: Regex pattern to use for matching. \"\"\" matches =", "Hrs\") ax.xaxis.set_major_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) plt.savefig('Moisture_vs_Time_24H.png', dpi=500) plt.savefig('Moisture_vs_Time.png', dpi=500) # plt.show() def plot_temperature(dict, past24): \"\"\"!", "matching. \"\"\" matches = list() for line in data: matches.append(re.match(pattern, line)) return matches", "line)) return matches def generate_plots(root=\"./logs/\", soil_sensor_log=\"soil_moisture_sensor_1.txt\", environment_sensor_log=\"environment_sensor.txt\"): # Plot soil moisture data with", "pd.DataFrame.from_dict(data_dict, orient='columns') df.reset_index(inplace=True) boxplot_environment(df) if __name__ == \"__main__\": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-r', '--root',", "ax.tick_params(which='minor', length=4, width=2, color='black') ax.xaxis.set_major_locator(hours6) ax.xaxis.set_major_formatter(mdates.DateFormatter('%d - %H')) ax.grid() plt.xlabel(\"Day - Hour\") plt.ylabel(\"Moisture", "mdates import matplotlib.image as image import pandas as pd import re import argparse", "fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) if past24: datemin = np.datetime64(x[-1], 'h') - np.timedelta64(24, 'h') datemax = np.datetime64(x[-1],", "plt.savefig('Moisture_vs_Time_24H.png', dpi=500) plt.savefig('Moisture_vs_Time.png', dpi=500) # plt.show() def plot_temperature(dict, past24): \"\"\"! Plots temperature data", "= plt.subplots() ax.plot(x, y, 'k', linewidth=2) fig.autofmt_xdate() hours6 = mdates.HourLocator(interval=6) hours3 = mdates.HourLocator(interval=3)", "Moisture % Past 24 Hrs\") ax.xaxis.set_major_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) plt.savefig('Moisture_vs_Time_24H.png', dpi=500) plt.savefig('Moisture_vs_Time.png', dpi=500) # plt.show()", "\" \" + match.group(2) index_dt = dt.datetime.strptime(index_time, \"%Y-%m-%d %H:%M:%S.%f\") data_dict[index_dt] = current_val plot_soil_moisture(data_dict,", "matching. Returns all regex match objects. @param data: Raw data from the log", "past24: datemin = np.datetime64(x[-1], 'h') - np.timedelta64(24, 'h') datemax = np.datetime64(x[-1], 'h') ax.set_xlim(datemin,", "environment sensor data df = pd.DataFrame.from_dict(data_dict, orient='columns') df.reset_index(inplace=True) boxplot_environment(df) if __name__ == \"__main__\":", "data_dict['Temperature'] = {} data_dict['VOC'] = {} data_dict['Humidity'] = {} for match in matches:", "Sensor Data') df.boxplot('Temperature', ax=ax[0]) df.boxplot('VOC', ax=ax[1], fontsize=12) df.boxplot('Humidity', ax=ax[2]) ax[0].set_ylabel(\"Temperature (°C)\") ax[1].set_ylabel(\"VOC (kΩ)\")", "The box extends from the Q1 to Q3 quartile values of the data,", "to 1.5 * IQR (IQR = Q3 - Q1) from the edges of", "moisture sensor log file') parser.add_argument('-e', '--environment', type=str, default=\"environment_sensor.txt\", help='Name of the envrionment sensor", "# Raw voltage reading current_val = float(match.group(5)) # Percentage reading index_time = match.group(1)", "% vs Time\") DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) if past24: datemin = np.datetime64(x[-1], 'h')", "The position of the whiskers is set by default to 1.5 * IQR", "data = myfile.readlines() matches = extract_data_from_log(data, environment_sensor_pattern) data_dict = dict() temperature_dict = dict()", "= mdates.HourLocator(interval=3) # im = image.imread('./icons/Grow_Space_Logo.png') # fig.figimage(im, 300, 0, zorder=3, alpha=0.2) ax.xaxis.set_minor_locator(hours3)", "parser.add_argument('-e', '--environment', type=str, default=\"environment_sensor.txt\", help='Name of the envrionment sensor log file') args =", "from the edges of the box. Outlier points are those past the end", "is a boxplot? Text from https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.boxplot.html: The box extends from the Q1 to", "for line in data: matches.append(re.match(pattern, line)) return matches def generate_plots(root=\"./logs/\", soil_sensor_log=\"soil_moisture_sensor_1.txt\", environment_sensor_log=\"environment_sensor.txt\"): #", "length=4, width=2, color='black') ax.xaxis.set_major_locator(hours6) ax.xaxis.set_major_formatter(mdates.DateFormatter('%d - %H')) ax.grid() plt.xlabel(\"Day - Hour\") plt.ylabel(\"Moisture Percentage", "plt.subplots_adjust(top=0.95) DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) plt.savefig('Environment_Boxplot.png', dpi=500) # plt.show() def extract_data_from_log(data, pattern): \"\"\"!", "\"\"\" df['VOC'] = df['VOC'].div(1000) # with plt.style.context(\"seaborn\"): fig, ax = plt.subplots(1, 3) fig.suptitle('Environment", "data_dict['Temperature'][index_dt] = float(match.group(3)) data_dict['VOC'][index_dt] = float(match.group(4)) data_dict['Humidity'][index_dt] = float(match.group(5)) plot_temperature(data_dict['Temperature'], True) plot_temperature(data_dict['Temperature'], False)", "+ match.group(2) index_dt = dt.datetime.strptime(index_time, \"%Y-%m-%d %H:%M:%S.%f\") data_dict['Temperature'][index_dt] = float(match.group(3)) data_dict['VOC'][index_dt] = float(match.group(4))", "parser.add_argument('-s', '--soil', type=str, default=\"soil_moisture_sensor_1.txt\", help='Name of soil moisture sensor log file') parser.add_argument('-e', '--environment',", "matches def generate_plots(root=\"./logs/\", soil_sensor_log=\"soil_moisture_sensor_1.txt\", environment_sensor_log=\"environment_sensor.txt\"): # Plot soil moisture data with open(root+soil_sensor_log, \"r\")", "plt.savefig('Temperature_vs_Time.png', dpi=500) # plt.show() def boxplot_environment(df): \"\"\"! Creates a boxplot of all the", "def plot_soil_moisture(dict, past24): \"\"\"! Plots soil moisture data in simple line chart @param", "plt.show() def boxplot_environment(df): \"\"\"! Creates a boxplot of all the relevant environment sensor", "the edges of the box. Outlier points are those past the end of", "float(match.group(5)) # Percentage reading index_time = match.group(1) + \" \" + match.group(2) index_dt", "= extract_data_from_log(data, environment_sensor_pattern) data_dict = dict() temperature_dict = dict() data_dict['Temperature'] = {} data_dict['VOC']", "(Q2). The whiskers extend from the edges of box to show the range", "= dict() for match in matches: # current_val = float(match.group(4)) # Raw voltage", "+ \" \" + match.group(2) index_dt = dt.datetime.strptime(index_time, \"%Y-%m-%d %H:%M:%S.%f\") data_dict['Temperature'][index_dt] = float(match.group(3))", "Percentage reading index_time = match.group(1) + \" \" + match.group(2) index_dt = dt.datetime.strptime(index_time,", "= float(match.group(4)) data_dict['Humidity'][index_dt] = float(match.group(5)) plot_temperature(data_dict['Temperature'], True) plot_temperature(data_dict['Temperature'], False) # Plot environment sensor", "match in matches: # current_val = float(match.group(4)) # Raw voltage reading current_val =", "re.MULTILINE) def plot_soil_moisture(dict, past24): \"\"\"! Plots soil moisture data in simple line chart", "extract_data_from_log(data, soil_moisture_pattern) data_dict = dict() for match in matches: # current_val = float(match.group(4))", "'k', linewidth=2) fig.autofmt_xdate() hours6 = mdates.HourLocator(interval=6) hours3 = mdates.HourLocator(interval=3) # im = image.imread('./icons/Grow_Space_Logo.png')", "True) plot_soil_moisture(data_dict, False) # Plot temperature data with open(root+environment_sensor_log, \"r\") as myfile: data", "# Percentage reading index_time = match.group(1) + \" \" + match.group(2) index_dt =", "%H:%M:%S.%f\") data_dict[index_dt] = current_val plot_soil_moisture(data_dict, True) plot_soil_moisture(data_dict, False) # Plot temperature data with", "Plot environment sensor data df = pd.DataFrame.from_dict(data_dict, orient='columns') df.reset_index(inplace=True) boxplot_environment(df) if __name__ ==", "numpy as np from pandas.plotting import register_matplotlib_converters from datetime import datetime register_matplotlib_converters() plt.rcParams.update({'font.size':", "re.compile(r\"([0-9-]+)\\s([0-9:.]+):\\stemperature:\\s([0-9.]+),\\sgas:\\s([0-9]+),\\shumidity:\\s([0-9.]+),\\spressure:\\s([0-9.]+),\\saltitude:\\s([0-9.]+)\", re.MULTILINE) soil_moisture_pattern = re.compile(r\"([0-9-]+)\\s([0-9.:]+):\\s\\[([0-9]+),\\s([0-9.]+),\\s([0-9.]+)\\]\", re.MULTILINE) def plot_soil_moisture(dict, past24): \"\"\"! Plots soil moisture", "= {} data_dict['VOC'] = {} data_dict['Humidity'] = {} for match in matches: index_time", "df['VOC'] = df['VOC'].div(1000) # with plt.style.context(\"seaborn\"): fig, ax = plt.subplots(1, 3) fig.suptitle('Environment Sensor", "soil moisture sensor log file') parser.add_argument('-e', '--environment', type=str, default=\"environment_sensor.txt\", help='Name of the envrionment", "@param data: Raw data from the log file. @param pattern: Regex pattern to", "color='black') ax.xaxis.set_major_locator(hours6) ax.xaxis.set_major_formatter(mdates.DateFormatter('%d - %H')) ax.grid() plt.xlabel(\"Day - Hour\") plt.ylabel(\"Moisture Percentage (%)\") plt.title(\"Soil", "\" + match.group(2) index_dt = dt.datetime.strptime(index_time, \"%Y-%m-%d %H:%M:%S.%f\") data_dict[index_dt] = current_val plot_soil_moisture(data_dict, True)", "soil_moisture_pattern) data_dict = dict() for match in matches: # current_val = float(match.group(4)) #", "import re import argparse import datetime as dt import numpy as np from", "data_dict['VOC'] = {} data_dict['Humidity'] = {} for match in matches: index_time = match.group(1)", "\"\"\" matches = list() for line in data: matches.append(re.match(pattern, line)) return matches def", "help='Name of soil moisture sensor log file') parser.add_argument('-e', '--environment', type=str, default=\"environment_sensor.txt\", help='Name of", "ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) plt.savefig('Moisture_vs_Time_24H.png', dpi=500) plt.savefig('Moisture_vs_Time.png', dpi=500) # plt.show() def plot_temperature(dict, past24): \"\"\"! Plots temperature", "out of a log file using regex matching. Returns all regex match objects.", "= match.group(1) + \" \" + match.group(2) index_dt = dt.datetime.strptime(index_time, \"%Y-%m-%d %H:%M:%S.%f\") data_dict[index_dt]", "Outlier points are those past the end of the whiskers. @param df: dataframe", "from datetime import datetime register_matplotlib_converters() plt.rcParams.update({'font.size': 22}) environment_sensor_pattern = re.compile(r\"([0-9-]+)\\s([0-9:.]+):\\stemperature:\\s([0-9.]+),\\sgas:\\s([0-9]+),\\shumidity:\\s([0-9.]+),\\spressure:\\s([0-9.]+),\\saltitude:\\s([0-9.]+)\", re.MULTILINE) soil_moisture_pattern =", "relevant environment sensor data. What is a boxplot? Text from https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.boxplot.html: The box", "ax=ax[2]) ax[0].set_ylabel(\"Temperature (°C)\") ax[1].set_ylabel(\"VOC (kΩ)\") ax[2].set_ylabel(\"Humidity (%)\") plt.subplots_adjust(top=0.95) DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) plt.savefig('Environment_Boxplot.png',", "np.datetime64(x[-1], 'h') - np.timedelta64(24, 'h') datemax = np.datetime64(x[-1], 'h') ax.set_xlim(datemin, datemax) plt.xlabel(\"Hour\") plt.title('Temperature", "the box. Outlier points are those past the end of the whiskers. @param", "ax.xaxis.set_major_locator(hours6) ax.xaxis.set_minor_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%d - %H')) ax.tick_params(which='major', length=7, width=2, color='black') ax.tick_params(which='minor', length=4, width=2, color='black')", "dataframe object from which we generate a boxplot. \"\"\" df['VOC'] = df['VOC'].div(1000) #", "(°C)\") DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) if past24: datemin = np.datetime64(x[-1], 'h') - np.timedelta64(24,", "(°C)\") ax[1].set_ylabel(\"VOC (kΩ)\") ax[2].set_ylabel(\"Humidity (%)\") plt.subplots_adjust(top=0.95) DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) plt.savefig('Environment_Boxplot.png', dpi=500) #", "\" + match.group(2) index_dt = dt.datetime.strptime(index_time, \"%Y-%m-%d %H:%M:%S.%f\") data_dict['Temperature'][index_dt] = float(match.group(3)) data_dict['VOC'][index_dt] =", "False) # Plot environment sensor data df = pd.DataFrame.from_dict(data_dict, orient='columns') df.reset_index(inplace=True) boxplot_environment(df) if", "df = pd.DataFrame.from_dict(data_dict, orient='columns') df.reset_index(inplace=True) boxplot_environment(df) if __name__ == \"__main__\": parser = argparse.ArgumentParser(description=__doc__)", "@param dict: Dicitonary containing timestamps and associated readings. \"\"\" lists = sorted(dict.items()) x,", "of the data, with a line at the median (Q2). The whiskers extend", "return matches def generate_plots(root=\"./logs/\", soil_sensor_log=\"soil_moisture_sensor_1.txt\", environment_sensor_log=\"environment_sensor.txt\"): # Plot soil moisture data with open(root+soil_sensor_log,", "pd import re import argparse import datetime as dt import numpy as np", "length=4, width=2, color='black') ax.grid() plt.title(\"Temperature Over Time\") plt.xlabel(\"Time (Month-Day Hour)\") plt.ylabel(\"Temperature (°C)\") DPI", "is set by default to 1.5 * IQR (IQR = Q3 - Q1)", "object from which we generate a boxplot. \"\"\" df['VOC'] = df['VOC'].div(1000) # with", "type=str, default=\"soil_moisture_sensor_1.txt\", help='Name of soil moisture sensor log file') parser.add_argument('-e', '--environment', type=str, default=\"environment_sensor.txt\",", "as plt import matplotlib.dates as mdates import matplotlib.image as image import pandas as", "of a log file using regex matching. Returns all regex match objects. @param", "extract_data_from_log(data, pattern): \"\"\"! Function for extracting data out of a log file using", "Hour)\") plt.ylabel(\"Temperature (°C)\") DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) if past24: datemin = np.datetime64(x[-1], 'h')", "\"__main__\": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-r', '--root', type=str, default=\"\", help='Root filepath of the log", "{} for match in matches: index_time = match.group(1) + \" \" + match.group(2)", "# Plot soil moisture data with open(root+soil_sensor_log, \"r\") as myfile: data = myfile.readlines()", "a boxplot? Text from https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.boxplot.html: The box extends from the Q1 to Q3", "Moisture % vs Time\") DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) if past24: datemin = np.datetime64(x[-1],", "edges of the box. Outlier points are those past the end of the", "data in simple line chart @param dict: Dicitonary containing timestamps and associated readings.", "the envrionment sensor log file') args = parser.parse_args() if args.root: root_folder = \"./logs/\"+args.root+\"/\"", "@param df: dataframe object from which we generate a boxplot. \"\"\" df['VOC'] =", "Q3 quartile values of the data, with a line at the median (Q2).", "at the median (Q2). The whiskers extend from the edges of box to", "= mdates.HourLocator(interval=6) hours3 = mdates.HourLocator(interval=3) # im = image.imread('./icons/Grow_Space_Logo.png') # fig.figimage(im, 300, 0,", "0, zorder=3, alpha=0.2) ax.xaxis.set_minor_locator(hours3) ax.tick_params(which='major', length=7, width=2, color='black') ax.tick_params(which='minor', length=4, width=2, color='black') ax.xaxis.set_major_locator(hours6)", "'h') - np.timedelta64(24, 'h') datemax = np.datetime64(x[-1], 'h') ax.set_xlim(datemin, datemax) plt.xlabel(\"Hour\") plt.title(\"Soil Moisture", "functionalities. \"\"\" import matplotlib.pylab as plt import matplotlib.dates as mdates import matplotlib.image as", "whiskers extend from the edges of box to show the range of the", "regex matching. Returns all regex match objects. @param data: Raw data from the", "= re.compile(r\"([0-9-]+)\\s([0-9:.]+):\\stemperature:\\s([0-9.]+),\\sgas:\\s([0-9]+),\\shumidity:\\s([0-9.]+),\\spressure:\\s([0-9.]+),\\saltitude:\\s([0-9.]+)\", re.MULTILINE) soil_moisture_pattern = re.compile(r\"([0-9-]+)\\s([0-9.:]+):\\s\\[([0-9]+),\\s([0-9.]+),\\s([0-9.]+)\\]\", re.MULTILINE) def plot_soil_moisture(dict, past24): \"\"\"! Plots soil", "zorder=3, alpha=0.2) ax.xaxis.set_minor_locator(hours3) ax.tick_params(which='major', length=7, width=2, color='black') ax.tick_params(which='minor', length=4, width=2, color='black') ax.xaxis.set_major_locator(hours6) ax.xaxis.set_major_formatter(mdates.DateFormatter('%d", "from the log file. @param pattern: Regex pattern to use for matching. \"\"\"", "environment_sensor_pattern = re.compile(r\"([0-9-]+)\\s([0-9:.]+):\\stemperature:\\s([0-9.]+),\\sgas:\\s([0-9]+),\\shumidity:\\s([0-9.]+),\\spressure:\\s([0-9.]+),\\saltitude:\\s([0-9.]+)\", re.MULTILINE) soil_moisture_pattern = re.compile(r\"([0-9-]+)\\s([0-9.:]+):\\s\\[([0-9]+),\\s([0-9.]+),\\s([0-9.]+)\\]\", re.MULTILINE) def plot_soil_moisture(dict, past24): \"\"\"! Plots", "as mdates import matplotlib.image as image import pandas as pd import re import", "= dict() temperature_dict = dict() data_dict['Temperature'] = {} data_dict['VOC'] = {} data_dict['Humidity'] =", "file using regex matching. Returns all regex match objects. @param data: Raw data", "chart @param dict: Dicitonary containing timestamps and associated readings. \"\"\" lists = sorted(dict.items())", "= df['VOC'].div(1000) # with plt.style.context(\"seaborn\"): fig, ax = plt.subplots(1, 3) fig.suptitle('Environment Sensor Data')", "width=2, color='black') ax.xaxis.set_major_locator(hours6) ax.xaxis.set_major_formatter(mdates.DateFormatter('%d - %H')) ax.grid() plt.xlabel(\"Day - Hour\") plt.ylabel(\"Moisture Percentage (%)\")", "Q3 - Q1) from the edges of the box. Outlier points are those", "ax=ax[0]) df.boxplot('VOC', ax=ax[1], fontsize=12) df.boxplot('Humidity', ax=ax[2]) ax[0].set_ylabel(\"Temperature (°C)\") ax[1].set_ylabel(\"VOC (kΩ)\") ax[2].set_ylabel(\"Humidity (%)\") plt.subplots_adjust(top=0.95)", "pandas as pd import re import argparse import datetime as dt import numpy", "with plt.style.context(\"seaborn\"): fig, ax = plt.subplots(1, 3) fig.suptitle('Environment Sensor Data') df.boxplot('Temperature', ax=ax[0]) df.boxplot('VOC',", "%H')) ax.tick_params(which='major', length=7, width=2, color='black') ax.tick_params(which='minor', length=4, width=2, color='black') ax.grid() plt.title(\"Temperature Over Time\")", "import numpy as np from pandas.plotting import register_matplotlib_converters from datetime import datetime register_matplotlib_converters()", "df.boxplot('VOC', ax=ax[1], fontsize=12) df.boxplot('Humidity', ax=ax[2]) ax[0].set_ylabel(\"Temperature (°C)\") ax[1].set_ylabel(\"VOC (kΩ)\") ax[2].set_ylabel(\"Humidity (%)\") plt.subplots_adjust(top=0.95) DPI", "= re.compile(r\"([0-9-]+)\\s([0-9.:]+):\\s\\[([0-9]+),\\s([0-9.]+),\\s([0-9.]+)\\]\", re.MULTILINE) def plot_soil_moisture(dict, past24): \"\"\"! Plots soil moisture data in simple", "for match in matches: # current_val = float(match.group(4)) # Raw voltage reading current_val", "providing plotting functionalities. \"\"\" import matplotlib.pylab as plt import matplotlib.dates as mdates import", "{} data_dict['Humidity'] = {} for match in matches: index_time = match.group(1) + \"", "past24): \"\"\"! Plots soil moisture data in simple line chart @param dict: Dicitonary", "import pandas as pd import re import argparse import datetime as dt import", "of the data. The position of the whiskers is set by default to", "= image.imread('./icons/Grow_Space_Logo.png') # fig.figimage(im, 300, 0, zorder=3, alpha=0.2) ax.xaxis.set_minor_locator(hours3) ax.tick_params(which='major', length=7, width=2, color='black')", "\"%Y-%m-%d %H:%M:%S.%f\") data_dict['Temperature'][index_dt] = float(match.group(3)) data_dict['VOC'][index_dt] = float(match.group(4)) data_dict['Humidity'][index_dt] = float(match.group(5)) plot_temperature(data_dict['Temperature'], True)", "type=str, default=\"environment_sensor.txt\", help='Name of the envrionment sensor log file') args = parser.parse_args() if", "mdates.HourLocator(interval=3) # im = image.imread('./icons/Grow_Space_Logo.png') # fig.figimage(im, 300, 0, zorder=3, alpha=0.2) ax.xaxis.set_minor_locator(hours3) ax.tick_params(which='major',", "Past 24 Hrs') ax.xaxis.set_major_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) plt.savefig('Temperature_vs_Time_24H.png', dpi=500) plt.savefig('Temperature_vs_Time.png', dpi=500) # plt.show() def boxplot_environment(df):", "fig.suptitle('Environment Sensor Data') df.boxplot('Temperature', ax=ax[0]) df.boxplot('VOC', ax=ax[1], fontsize=12) df.boxplot('Humidity', ax=ax[2]) ax[0].set_ylabel(\"Temperature (°C)\") ax[1].set_ylabel(\"VOC", "y = zip(*lists) fig, ax = plt.subplots() ax.plot(x, y, 'k', linewidth=2) fig.autofmt_xdate() hours6", "%H:%M:%S.%f\") data_dict['Temperature'][index_dt] = float(match.group(3)) data_dict['VOC'][index_dt] = float(match.group(4)) data_dict['Humidity'][index_dt] = float(match.group(5)) plot_temperature(data_dict['Temperature'], True) plot_temperature(data_dict['Temperature'],", "Data') df.boxplot('Temperature', ax=ax[0]) df.boxplot('VOC', ax=ax[1], fontsize=12) df.boxplot('Humidity', ax=ax[2]) ax[0].set_ylabel(\"Temperature (°C)\") ax[1].set_ylabel(\"VOC (kΩ)\") ax[2].set_ylabel(\"Humidity", "environment_sensor_pattern) data_dict = dict() temperature_dict = dict() data_dict['Temperature'] = {} data_dict['VOC'] = {}", "of the whiskers. @param df: dataframe object from which we generate a boxplot.", "for matching. \"\"\" matches = list() for line in data: matches.append(re.match(pattern, line)) return", "datemax = np.datetime64(x[-1], 'h') ax.set_xlim(datemin, datemax) plt.xlabel(\"Hour\") plt.title('Temperature Past 24 Hrs') ax.xaxis.set_major_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))", "0, zorder=3, alpha=0.2) ax.xaxis.set_major_locator(hours6) ax.xaxis.set_minor_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%d - %H')) ax.tick_params(which='major', length=7, width=2, color='black') ax.tick_params(which='minor',", "plot_temperature(data_dict['Temperature'], True) plot_temperature(data_dict['Temperature'], False) # Plot environment sensor data df = pd.DataFrame.from_dict(data_dict, orient='columns')", "ax.tick_params(which='major', length=7, width=2, color='black') ax.tick_params(which='minor', length=4, width=2, color='black') ax.xaxis.set_major_locator(hours6) ax.xaxis.set_major_formatter(mdates.DateFormatter('%d - %H')) ax.grid()", "the whiskers. @param df: dataframe object from which we generate a boxplot. \"\"\"", "Percentage (%)\") plt.title(\"Soil Moisture % vs Time\") DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) if past24:", "moisture data in simple line chart @param dict: Dicitonary containing timestamps and associated", "Plot soil moisture data with open(root+soil_sensor_log, \"r\") as myfile: data = myfile.readlines() matches", "ax.xaxis.set_major_locator(hours6) ax.xaxis.set_major_formatter(mdates.DateFormatter('%d - %H')) ax.grid() plt.xlabel(\"Day - Hour\") plt.ylabel(\"Moisture Percentage (%)\") plt.title(\"Soil Moisture", "generate_plots(root=\"./logs/\", soil_sensor_log=\"soil_moisture_sensor_1.txt\", environment_sensor_log=\"environment_sensor.txt\"): # Plot soil moisture data with open(root+soil_sensor_log, \"r\") as myfile:", "myfile.readlines() matches = extract_data_from_log(data, soil_moisture_pattern) data_dict = dict() for match in matches: #", "np.datetime64(x[-1], 'h') ax.set_xlim(datemin, datemax) plt.xlabel(\"Hour\") plt.title(\"Soil Moisture % Past 24 Hrs\") ax.xaxis.set_major_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))", "@param pattern: Regex pattern to use for matching. \"\"\" matches = list() for", "= image.imread('./icons/Grow_Space_Logo.png') # fig.figimage(im, 650, 0, zorder=3, alpha=0.2) ax.xaxis.set_major_locator(hours6) ax.xaxis.set_minor_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%d - %H'))", "dt.datetime.strptime(index_time, \"%Y-%m-%d %H:%M:%S.%f\") data_dict['Temperature'][index_dt] = float(match.group(3)) data_dict['VOC'][index_dt] = float(match.group(4)) data_dict['Humidity'][index_dt] = float(match.group(5)) plot_temperature(data_dict['Temperature'],", "fig, ax = plt.subplots() ax.plot(x, y, 'k', linewidth=2) fig.autofmt_xdate() hours6 = mdates.HourLocator(interval=6) hours3", "matches = extract_data_from_log(data, environment_sensor_pattern) data_dict = dict() temperature_dict = dict() data_dict['Temperature'] = {}", "register_matplotlib_converters from datetime import datetime register_matplotlib_converters() plt.rcParams.update({'font.size': 22}) environment_sensor_pattern = re.compile(r\"([0-9-]+)\\s([0-9:.]+):\\stemperature:\\s([0-9.]+),\\sgas:\\s([0-9]+),\\shumidity:\\s([0-9.]+),\\spressure:\\s([0-9.]+),\\saltitude:\\s([0-9.]+)\", re.MULTILINE) soil_moisture_pattern", "to Q3 quartile values of the data, with a line at the median", "extracting data out of a log file using regex matching. Returns all regex", "ax.plot(x, y, 'k', linewidth=2) fig.autofmt_xdate() hours6 = mdates.HourLocator(interval=6) hours3 = mdates.HourLocator(interval=3) # im", "temperature data with open(root+environment_sensor_log, \"r\") as myfile: data = myfile.readlines() matches = extract_data_from_log(data,", "fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) plt.savefig('Environment_Boxplot.png', dpi=500) # plt.show() def extract_data_from_log(data, pattern): \"\"\"! Function for extracting data", "dpi=500) # plt.show() def extract_data_from_log(data, pattern): \"\"\"! Function for extracting data out of", "match.group(1) + \" \" + match.group(2) index_dt = dt.datetime.strptime(index_time, \"%Y-%m-%d %H:%M:%S.%f\") data_dict[index_dt] =", "Hour\") plt.ylabel(\"Moisture Percentage (%)\") plt.title(\"Soil Moisture % vs Time\") DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI))", "containing timestamps and associated readings. \"\"\" lists = sorted(dict.items()) x, y = zip(*lists)", "ax.set_xlim(datemin, datemax) plt.xlabel(\"Hour\") plt.title(\"Soil Moisture % Past 24 Hrs\") ax.xaxis.set_major_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) plt.savefig('Moisture_vs_Time_24H.png', dpi=500)", "ax = plt.subplots() ax.plot(x, y, 'k', linewidth=2) fig.autofmt_xdate() hours6 = mdates.HourLocator(interval=6) hours3 =", "zorder=3, alpha=0.2) ax.xaxis.set_major_locator(hours6) ax.xaxis.set_minor_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%d - %H')) ax.tick_params(which='major', length=7, width=2, color='black') ax.tick_params(which='minor', length=4,", "# plt.show() def extract_data_from_log(data, pattern): \"\"\"! Function for extracting data out of a", "\"\"\"! Function for extracting data out of a log file using regex matching.", "= Q3 - Q1) from the edges of the box. Outlier points are", "open(root+soil_sensor_log, \"r\") as myfile: data = myfile.readlines() matches = extract_data_from_log(data, soil_moisture_pattern) data_dict =", "# current_val = float(match.group(4)) # Raw voltage reading current_val = float(match.group(5)) # Percentage", "the log file. @param pattern: Regex pattern to use for matching. \"\"\" matches", "median (Q2). The whiskers extend from the edges of box to show the", "all the relevant environment sensor data. What is a boxplot? Text from https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.boxplot.html:", "ax.xaxis.set_major_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) plt.savefig('Moisture_vs_Time_24H.png', dpi=500) plt.savefig('Moisture_vs_Time.png', dpi=500) # plt.show() def plot_temperature(dict, past24): \"\"\"! Plots", "datetime import datetime register_matplotlib_converters() plt.rcParams.update({'font.size': 22}) environment_sensor_pattern = re.compile(r\"([0-9-]+)\\s([0-9:.]+):\\stemperature:\\s([0-9.]+),\\sgas:\\s([0-9]+),\\shumidity:\\s([0-9.]+),\\spressure:\\s([0-9.]+),\\saltitude:\\s([0-9.]+)\", re.MULTILINE) soil_moisture_pattern = re.compile(r\"([0-9-]+)\\s([0-9.:]+):\\s\\[([0-9]+),\\s([0-9.]+),\\s([0-9.]+)\\]\",", "ax[2].set_ylabel(\"Humidity (%)\") plt.subplots_adjust(top=0.95) DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) plt.savefig('Environment_Boxplot.png', dpi=500) # plt.show() def extract_data_from_log(data,", "of the whiskers is set by default to 1.5 * IQR (IQR =", "data') parser.add_argument('-s', '--soil', type=str, default=\"soil_moisture_sensor_1.txt\", help='Name of soil moisture sensor log file') parser.add_argument('-e',", "df.boxplot('Temperature', ax=ax[0]) df.boxplot('VOC', ax=ax[1], fontsize=12) df.boxplot('Humidity', ax=ax[2]) ax[0].set_ylabel(\"Temperature (°C)\") ax[1].set_ylabel(\"VOC (kΩ)\") ax[2].set_ylabel(\"Humidity (%)\")", "ax.tick_params(which='major', length=7, width=2, color='black') ax.tick_params(which='minor', length=4, width=2, color='black') ax.grid() plt.title(\"Temperature Over Time\") plt.xlabel(\"Time", "pandas.plotting import register_matplotlib_converters from datetime import datetime register_matplotlib_converters() plt.rcParams.update({'font.size': 22}) environment_sensor_pattern = re.compile(r\"([0-9-]+)\\s([0-9:.]+):\\stemperature:\\s([0-9.]+),\\sgas:\\s([0-9]+),\\shumidity:\\s([0-9.]+),\\spressure:\\s([0-9.]+),\\saltitude:\\s([0-9.]+)\",", "np.timedelta64(24, 'h') datemax = np.datetime64(x[-1], 'h') ax.set_xlim(datemin, datemax) plt.xlabel(\"Hour\") plt.title('Temperature Past 24 Hrs')", "voltage reading current_val = float(match.group(5)) # Percentage reading index_time = match.group(1) + \"", "# Plot environment sensor data df = pd.DataFrame.from_dict(data_dict, orient='columns') df.reset_index(inplace=True) boxplot_environment(df) if __name__", "data_dict = dict() for match in matches: # current_val = float(match.group(4)) # Raw", "np.datetime64(x[-1], 'h') - np.timedelta64(24, 'h') datemax = np.datetime64(x[-1], 'h') ax.set_xlim(datemin, datemax) plt.xlabel(\"Hour\") plt.title(\"Soil", "those past the end of the whiskers. @param df: dataframe object from which", "objects. @param data: Raw data from the log file. @param pattern: Regex pattern", "the edges of box to show the range of the data. The position", "image import pandas as pd import re import argparse import datetime as dt", "ax.grid() plt.xlabel(\"Day - Hour\") plt.ylabel(\"Moisture Percentage (%)\") plt.title(\"Soil Moisture % vs Time\") DPI", "mdates.HourLocator(interval=3) # im = image.imread('./icons/Grow_Space_Logo.png') # fig.figimage(im, 650, 0, zorder=3, alpha=0.2) ax.xaxis.set_major_locator(hours6) ax.xaxis.set_minor_locator(hours3)", "color='black') ax.grid() plt.title(\"Temperature Over Time\") plt.xlabel(\"Time (Month-Day Hour)\") plt.ylabel(\"Temperature (°C)\") DPI = fig.get_dpi()", "dpi=500) plt.savefig('Temperature_vs_Time.png', dpi=500) # plt.show() def boxplot_environment(df): \"\"\"! Creates a boxplot of all", "data_dict = dict() temperature_dict = dict() data_dict['Temperature'] = {} data_dict['VOC'] = {} data_dict['Humidity']", "the data. The position of the whiskers is set by default to 1.5", "show the range of the data. The position of the whiskers is set", "soil_sensor_log=\"soil_moisture_sensor_1.txt\", environment_sensor_log=\"environment_sensor.txt\"): # Plot soil moisture data with open(root+soil_sensor_log, \"r\") as myfile: data", "(%)\") plt.title(\"Soil Moisture % vs Time\") DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) if past24: datemin", "mdates.HourLocator(interval=6) hours3 = mdates.HourLocator(interval=3) # im = image.imread('./icons/Grow_Space_Logo.png') # fig.figimage(im, 300, 0, zorder=3,", "matplotlib.pylab as plt import matplotlib.dates as mdates import matplotlib.image as image import pandas", "lists = sorted(dict.items()) x, y = zip(*lists) fig, ax = plt.subplots() ax.plot(x, y,", "datetime as dt import numpy as np from pandas.plotting import register_matplotlib_converters from datetime", "Plot temperature data with open(root+environment_sensor_log, \"r\") as myfile: data = myfile.readlines() matches =", "- np.timedelta64(24, 'h') datemax = np.datetime64(x[-1], 'h') ax.set_xlim(datemin, datemax) plt.xlabel(\"Hour\") plt.title(\"Soil Moisture %", "the data, with a line at the median (Q2). The whiskers extend from", "log file') args = parser.parse_args() if args.root: root_folder = \"./logs/\"+args.root+\"/\" else: root_folder =", "the Q1 to Q3 quartile values of the data, with a line at", "All functions providing plotting functionalities. \"\"\" import matplotlib.pylab as plt import matplotlib.dates as", "Plots temperature data in simple line chart @param dict: Dicitonary containing timestamps and", "* IQR (IQR = Q3 - Q1) from the edges of the box.", "as dt import numpy as np from pandas.plotting import register_matplotlib_converters from datetime import", "vs Time\") DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) if past24: datemin = np.datetime64(x[-1], 'h') -", "- %H')) ax.tick_params(which='major', length=7, width=2, color='black') ax.tick_params(which='minor', length=4, width=2, color='black') ax.grid() plt.title(\"Temperature Over", "whiskers. @param df: dataframe object from which we generate a boxplot. \"\"\" df['VOC']", "in simple line chart @param dict: Dicitonary containing timestamps and associated readings. \"\"\"", "plot_soil_moisture(data_dict, True) plot_soil_moisture(data_dict, False) # Plot temperature data with open(root+environment_sensor_log, \"r\") as myfile:", "data df = pd.DataFrame.from_dict(data_dict, orient='columns') df.reset_index(inplace=True) boxplot_environment(df) if __name__ == \"__main__\": parser =", "= fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) plt.savefig('Environment_Boxplot.png', dpi=500) # plt.show() def extract_data_from_log(data, pattern): \"\"\"! Function for", "associated readings. \"\"\" lists = sorted(dict.items()) x, y = zip(*lists) fig, ax =", "list() for line in data: matches.append(re.match(pattern, line)) return matches def generate_plots(root=\"./logs/\", soil_sensor_log=\"soil_moisture_sensor_1.txt\", environment_sensor_log=\"environment_sensor.txt\"):", "envrionment sensor log file') args = parser.parse_args() if args.root: root_folder = \"./logs/\"+args.root+\"/\" else:", "match in matches: index_time = match.group(1) + \" \" + match.group(2) index_dt =", "ax=ax[1], fontsize=12) df.boxplot('Humidity', ax=ax[2]) ax[0].set_ylabel(\"Temperature (°C)\") ax[1].set_ylabel(\"VOC (kΩ)\") ax[2].set_ylabel(\"Humidity (%)\") plt.subplots_adjust(top=0.95) DPI =", "650, 0, zorder=3, alpha=0.2) ax.xaxis.set_major_locator(hours6) ax.xaxis.set_minor_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%d - %H')) ax.tick_params(which='major', length=7, width=2, color='black')", "# im = image.imread('./icons/Grow_Space_Logo.png') # fig.figimage(im, 300, 0, zorder=3, alpha=0.2) ax.xaxis.set_minor_locator(hours3) ax.tick_params(which='major', length=7,", "np from pandas.plotting import register_matplotlib_converters from datetime import datetime register_matplotlib_converters() plt.rcParams.update({'font.size': 22}) environment_sensor_pattern", "current_val = float(match.group(4)) # Raw voltage reading current_val = float(match.group(5)) # Percentage reading", "matplotlib.dates as mdates import matplotlib.image as image import pandas as pd import re", "Q1 to Q3 quartile values of the data, with a line at the", "= dt.datetime.strptime(index_time, \"%Y-%m-%d %H:%M:%S.%f\") data_dict[index_dt] = current_val plot_soil_moisture(data_dict, True) plot_soil_moisture(data_dict, False) # Plot", "with a line at the median (Q2). The whiskers extend from the edges", "dt.datetime.strptime(index_time, \"%Y-%m-%d %H:%M:%S.%f\") data_dict[index_dt] = current_val plot_soil_moisture(data_dict, True) plot_soil_moisture(data_dict, False) # Plot temperature", "= myfile.readlines() matches = extract_data_from_log(data, environment_sensor_pattern) data_dict = dict() temperature_dict = dict() data_dict['Temperature']", "= argparse.ArgumentParser(description=__doc__) parser.add_argument('-r', '--root', type=str, default=\"\", help='Root filepath of the log data') parser.add_argument('-s',", "in matches: index_time = match.group(1) + \" \" + match.group(2) index_dt = dt.datetime.strptime(index_time,", "ax = plt.subplots(1, 3) fig.suptitle('Environment Sensor Data') df.boxplot('Temperature', ax=ax[0]) df.boxplot('VOC', ax=ax[1], fontsize=12) df.boxplot('Humidity',", "x, y = zip(*lists) fig, ax = plt.subplots() ax.plot(x, y, 'k', linewidth=2) fig.autofmt_xdate()", "+ \" \" + match.group(2) index_dt = dt.datetime.strptime(index_time, \"%Y-%m-%d %H:%M:%S.%f\") data_dict[index_dt] = current_val", "file. @param pattern: Regex pattern to use for matching. \"\"\" matches = list()", "datetime register_matplotlib_converters() plt.rcParams.update({'font.size': 22}) environment_sensor_pattern = re.compile(r\"([0-9-]+)\\s([0-9:.]+):\\stemperature:\\s([0-9.]+),\\sgas:\\s([0-9]+),\\shumidity:\\s([0-9.]+),\\spressure:\\s([0-9.]+),\\saltitude:\\s([0-9.]+)\", re.MULTILINE) soil_moisture_pattern = re.compile(r\"([0-9-]+)\\s([0-9.:]+):\\s\\[([0-9]+),\\s([0-9.]+),\\s([0-9.]+)\\]\", re.MULTILINE) def", "ax.grid() plt.title(\"Temperature Over Time\") plt.xlabel(\"Time (Month-Day Hour)\") plt.ylabel(\"Temperature (°C)\") DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI))", "Regex pattern to use for matching. \"\"\" matches = list() for line in", "# with plt.style.context(\"seaborn\"): fig, ax = plt.subplots(1, 3) fig.suptitle('Environment Sensor Data') df.boxplot('Temperature', ax=ax[0])", "float(match.group(3)) data_dict['VOC'][index_dt] = float(match.group(4)) data_dict['Humidity'][index_dt] = float(match.group(5)) plot_temperature(data_dict['Temperature'], True) plot_temperature(data_dict['Temperature'], False) # Plot", "re.MULTILINE) soil_moisture_pattern = re.compile(r\"([0-9-]+)\\s([0-9.:]+):\\s\\[([0-9]+),\\s([0-9.]+),\\s([0-9.]+)\\]\", re.MULTILINE) def plot_soil_moisture(dict, past24): \"\"\"! Plots soil moisture data", "default=\"environment_sensor.txt\", help='Name of the envrionment sensor log file') args = parser.parse_args() if args.root:", "plt.xlabel(\"Hour\") plt.title('Temperature Past 24 Hrs') ax.xaxis.set_major_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) plt.savefig('Temperature_vs_Time_24H.png', dpi=500) plt.savefig('Temperature_vs_Time.png', dpi=500) # plt.show()", "as myfile: data = myfile.readlines() matches = extract_data_from_log(data, soil_moisture_pattern) data_dict = dict() for", "ax[0].set_ylabel(\"Temperature (°C)\") ax[1].set_ylabel(\"VOC (kΩ)\") ax[2].set_ylabel(\"Humidity (%)\") plt.subplots_adjust(top=0.95) DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) plt.savefig('Environment_Boxplot.png', dpi=500)", "regex match objects. @param data: Raw data from the log file. @param pattern:", "args = parser.parse_args() if args.root: root_folder = \"./logs/\"+args.root+\"/\" else: root_folder = \"./logs/\" generate_plots(root_folder,", "plt import matplotlib.dates as mdates import matplotlib.image as image import pandas as pd", "from https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.boxplot.html: The box extends from the Q1 to Q3 quartile values of", "of the box. Outlier points are those past the end of the whiskers.", "generate a boxplot. \"\"\" df['VOC'] = df['VOC'].div(1000) # with plt.style.context(\"seaborn\"): fig, ax =", "= sorted(dict.items()) x, y = zip(*lists) fig, ax = plt.subplots() ax.plot(x, y, 'k',", "= float(match.group(5)) # Percentage reading index_time = match.group(1) + \" \" + match.group(2)", "fig.figimage(im, 300, 0, zorder=3, alpha=0.2) ax.xaxis.set_minor_locator(hours3) ax.tick_params(which='major', length=7, width=2, color='black') ax.tick_params(which='minor', length=4, width=2,", "type=str, default=\"\", help='Root filepath of the log data') parser.add_argument('-s', '--soil', type=str, default=\"soil_moisture_sensor_1.txt\", help='Name", "import datetime as dt import numpy as np from pandas.plotting import register_matplotlib_converters from", "extend from the edges of box to show the range of the data.", "\"%Y-%m-%d %H:%M:%S.%f\") data_dict[index_dt] = current_val plot_soil_moisture(data_dict, True) plot_soil_moisture(data_dict, False) # Plot temperature data", "position of the whiskers is set by default to 1.5 * IQR (IQR", "to use for matching. \"\"\" matches = list() for line in data: matches.append(re.match(pattern,", "extends from the Q1 to Q3 quartile values of the data, with a", "log file') parser.add_argument('-e', '--environment', type=str, default=\"environment_sensor.txt\", help='Name of the envrionment sensor log file')", "file') args = parser.parse_args() if args.root: root_folder = \"./logs/\"+args.root+\"/\" else: root_folder = \"./logs/\"", "24 Hrs') ax.xaxis.set_major_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) plt.savefig('Temperature_vs_Time_24H.png', dpi=500) plt.savefig('Temperature_vs_Time.png', dpi=500) # plt.show() def boxplot_environment(df): \"\"\"!", "datemax) plt.xlabel(\"Hour\") plt.title(\"Soil Moisture % Past 24 Hrs\") ax.xaxis.set_major_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) plt.savefig('Moisture_vs_Time_24H.png', dpi=500) plt.savefig('Moisture_vs_Time.png',", "data: matches.append(re.match(pattern, line)) return matches def generate_plots(root=\"./logs/\", soil_sensor_log=\"soil_moisture_sensor_1.txt\", environment_sensor_log=\"environment_sensor.txt\"): # Plot soil moisture", "im = image.imread('./icons/Grow_Space_Logo.png') # fig.figimage(im, 300, 0, zorder=3, alpha=0.2) ax.xaxis.set_minor_locator(hours3) ax.tick_params(which='major', length=7, width=2,", "- Q1) from the edges of the box. Outlier points are those past", "a boxplot. \"\"\" df['VOC'] = df['VOC'].div(1000) # with plt.style.context(\"seaborn\"): fig, ax = plt.subplots(1,", "matches = extract_data_from_log(data, soil_moisture_pattern) data_dict = dict() for match in matches: # current_val", "image.imread('./icons/Grow_Space_Logo.png') # fig.figimage(im, 300, 0, zorder=3, alpha=0.2) ax.xaxis.set_minor_locator(hours3) ax.tick_params(which='major', length=7, width=2, color='black') ax.tick_params(which='minor',", "the log data') parser.add_argument('-s', '--soil', type=str, default=\"soil_moisture_sensor_1.txt\", help='Name of soil moisture sensor log", "match.group(2) index_dt = dt.datetime.strptime(index_time, \"%Y-%m-%d %H:%M:%S.%f\") data_dict[index_dt] = current_val plot_soil_moisture(data_dict, True) plot_soil_moisture(data_dict, False)", "datemax = np.datetime64(x[-1], 'h') ax.set_xlim(datemin, datemax) plt.xlabel(\"Hour\") plt.title(\"Soil Moisture % Past 24 Hrs\")", "Past 24 Hrs\") ax.xaxis.set_major_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) plt.savefig('Moisture_vs_Time_24H.png', dpi=500) plt.savefig('Moisture_vs_Time.png', dpi=500) # plt.show() def plot_temperature(dict,", "a line at the median (Q2). The whiskers extend from the edges of", "from pandas.plotting import register_matplotlib_converters from datetime import datetime register_matplotlib_converters() plt.rcParams.update({'font.size': 22}) environment_sensor_pattern =", "data out of a log file using regex matching. Returns all regex match", "of all the relevant environment sensor data. What is a boxplot? Text from", "data with open(root+environment_sensor_log, \"r\") as myfile: data = myfile.readlines() matches = extract_data_from_log(data, environment_sensor_pattern)", "plot_soil_moisture(data_dict, False) # Plot temperature data with open(root+environment_sensor_log, \"r\") as myfile: data =", "def boxplot_environment(df): \"\"\"! Creates a boxplot of all the relevant environment sensor data.", "pattern): \"\"\"! Function for extracting data out of a log file using regex", "plot_temperature(data_dict['Temperature'], False) # Plot environment sensor data df = pd.DataFrame.from_dict(data_dict, orient='columns') df.reset_index(inplace=True) boxplot_environment(df)", "plt.subplots(1, 3) fig.suptitle('Environment Sensor Data') df.boxplot('Temperature', ax=ax[0]) df.boxplot('VOC', ax=ax[1], fontsize=12) df.boxplot('Humidity', ax=ax[2]) ax[0].set_ylabel(\"Temperature", "float(match.group(4)) # Raw voltage reading current_val = float(match.group(5)) # Percentage reading index_time =", "boxplot_environment(df): \"\"\"! Creates a boxplot of all the relevant environment sensor data. What", "sensor data. What is a boxplot? Text from https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.boxplot.html: The box extends from", "3) fig.suptitle('Environment Sensor Data') df.boxplot('Temperature', ax=ax[0]) df.boxplot('VOC', ax=ax[1], fontsize=12) df.boxplot('Humidity', ax=ax[2]) ax[0].set_ylabel(\"Temperature (°C)\")", "myfile: data = myfile.readlines() matches = extract_data_from_log(data, environment_sensor_pattern) data_dict = dict() temperature_dict =", "\"r\") as myfile: data = myfile.readlines() matches = extract_data_from_log(data, environment_sensor_pattern) data_dict = dict()", "the median (Q2). The whiskers extend from the edges of box to show", "register_matplotlib_converters() plt.rcParams.update({'font.size': 22}) environment_sensor_pattern = re.compile(r\"([0-9-]+)\\s([0-9:.]+):\\stemperature:\\s([0-9.]+),\\sgas:\\s([0-9]+),\\shumidity:\\s([0-9.]+),\\spressure:\\s([0-9.]+),\\saltitude:\\s([0-9.]+)\", re.MULTILINE) soil_moisture_pattern = re.compile(r\"([0-9-]+)\\s([0-9.:]+):\\s\\[([0-9]+),\\s([0-9.]+),\\s([0-9.]+)\\]\", re.MULTILINE) def plot_soil_moisture(dict,", "%H')) ax.grid() plt.xlabel(\"Day - Hour\") plt.ylabel(\"Moisture Percentage (%)\") plt.title(\"Soil Moisture % vs Time\")", "Text from https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.boxplot.html: The box extends from the Q1 to Q3 quartile values", "boxplot? Text from https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.boxplot.html: The box extends from the Q1 to Q3 quartile", "df.boxplot('Humidity', ax=ax[2]) ax[0].set_ylabel(\"Temperature (°C)\") ax[1].set_ylabel(\"VOC (kΩ)\") ax[2].set_ylabel(\"Humidity (%)\") plt.subplots_adjust(top=0.95) DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI))", "open(root+environment_sensor_log, \"r\") as myfile: data = myfile.readlines() matches = extract_data_from_log(data, environment_sensor_pattern) data_dict =", "environment_sensor_log=\"environment_sensor.txt\"): # Plot soil moisture data with open(root+soil_sensor_log, \"r\") as myfile: data =", "plt.subplots() ax.plot(x, y, 'k', linewidth=2) fig.autofmt_xdate() hours6 = mdates.HourLocator(interval=6) hours3 = mdates.HourLocator(interval=3) #", "end of the whiskers. @param df: dataframe object from which we generate a", "reading current_val = float(match.group(5)) # Percentage reading index_time = match.group(1) + \" \"", "plot_soil_moisture(dict, past24): \"\"\"! Plots soil moisture data in simple line chart @param dict:", "22}) environment_sensor_pattern = re.compile(r\"([0-9-]+)\\s([0-9:.]+):\\stemperature:\\s([0-9.]+),\\sgas:\\s([0-9]+),\\shumidity:\\s([0-9.]+),\\spressure:\\s([0-9.]+),\\saltitude:\\s([0-9.]+)\", re.MULTILINE) soil_moisture_pattern = re.compile(r\"([0-9-]+)\\s([0-9.:]+):\\s\\[([0-9]+),\\s([0-9.]+),\\s([0-9.]+)\\]\", re.MULTILINE) def plot_soil_moisture(dict, past24): \"\"\"!", "zip(*lists) fig, ax = plt.subplots() ax.plot(x, y, 'k', linewidth=2) fig.autofmt_xdate() hours6 = mdates.HourLocator(interval=6)", "color='black') ax.tick_params(which='minor', length=4, width=2, color='black') ax.grid() plt.title(\"Temperature Over Time\") plt.xlabel(\"Time (Month-Day Hour)\") plt.ylabel(\"Temperature", "Q1) from the edges of the box. Outlier points are those past the", "df.reset_index(inplace=True) boxplot_environment(df) if __name__ == \"__main__\": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-r', '--root', type=str, default=\"\",", "boxplot_environment(df) if __name__ == \"__main__\": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-r', '--root', type=str, default=\"\", help='Root", "argparse.ArgumentParser(description=__doc__) parser.add_argument('-r', '--root', type=str, default=\"\", help='Root filepath of the log data') parser.add_argument('-s', '--soil',", "(Month-Day Hour)\") plt.ylabel(\"Temperature (°C)\") DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) if past24: datemin = np.datetime64(x[-1],", "df: dataframe object from which we generate a boxplot. \"\"\" df['VOC'] = df['VOC'].div(1000)", "= mdates.HourLocator(interval=3) # im = image.imread('./icons/Grow_Space_Logo.png') # fig.figimage(im, 650, 0, zorder=3, alpha=0.2) ax.xaxis.set_major_locator(hours6)", "% Past 24 Hrs\") ax.xaxis.set_major_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) plt.savefig('Moisture_vs_Time_24H.png', dpi=500) plt.savefig('Moisture_vs_Time.png', dpi=500) # plt.show() def", "as pd import re import argparse import datetime as dt import numpy as", "current_val = float(match.group(5)) # Percentage reading index_time = match.group(1) + \" \" +", "= float(match.group(3)) data_dict['VOC'][index_dt] = float(match.group(4)) data_dict['Humidity'][index_dt] = float(match.group(5)) plot_temperature(data_dict['Temperature'], True) plot_temperature(data_dict['Temperature'], False) #", "hours3 = mdates.HourLocator(interval=3) # im = image.imread('./icons/Grow_Space_Logo.png') # fig.figimage(im, 300, 0, zorder=3, alpha=0.2)", "temperature data in simple line chart @param dict: Dicitonary containing timestamps and associated", "ax.xaxis.set_minor_locator(hours3) ax.tick_params(which='major', length=7, width=2, color='black') ax.tick_params(which='minor', length=4, width=2, color='black') ax.xaxis.set_major_locator(hours6) ax.xaxis.set_major_formatter(mdates.DateFormatter('%d - %H'))", "plt.savefig('Temperature_vs_Time_24H.png', dpi=500) plt.savefig('Temperature_vs_Time.png', dpi=500) # plt.show() def boxplot_environment(df): \"\"\"! Creates a boxplot of", "The whiskers extend from the edges of box to show the range of", "color='black') ax.tick_params(which='minor', length=4, width=2, color='black') ax.xaxis.set_major_locator(hours6) ax.xaxis.set_major_formatter(mdates.DateFormatter('%d - %H')) ax.grid() plt.xlabel(\"Day - Hour\")", "Time\") DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) if past24: datemin = np.datetime64(x[-1], 'h') - np.timedelta64(24,", "\"\"\"! All functions providing plotting functionalities. \"\"\" import matplotlib.pylab as plt import matplotlib.dates", "= parser.parse_args() if args.root: root_folder = \"./logs/\"+args.root+\"/\" else: root_folder = \"./logs/\" generate_plots(root_folder, args.soil,", "dt import numpy as np from pandas.plotting import register_matplotlib_converters from datetime import datetime", "= {} for match in matches: index_time = match.group(1) + \" \" +", "as image import pandas as pd import re import argparse import datetime as", "as np from pandas.plotting import register_matplotlib_converters from datetime import datetime register_matplotlib_converters() plt.rcParams.update({'font.size': 22})", "as myfile: data = myfile.readlines() matches = extract_data_from_log(data, environment_sensor_pattern) data_dict = dict() temperature_dict", "plt.xlabel(\"Hour\") plt.title(\"Soil Moisture % Past 24 Hrs\") ax.xaxis.set_major_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) plt.savefig('Moisture_vs_Time_24H.png', dpi=500) plt.savefig('Moisture_vs_Time.png', dpi=500)", "line chart @param dict: Dicitonary containing timestamps and associated readings. \"\"\" lists =", "float(match.group(5)) plot_temperature(data_dict['Temperature'], True) plot_temperature(data_dict['Temperature'], False) # Plot environment sensor data df = pd.DataFrame.from_dict(data_dict,", "sensor log file') args = parser.parse_args() if args.root: root_folder = \"./logs/\"+args.root+\"/\" else: root_folder", "width=2, color='black') ax.tick_params(which='minor', length=4, width=2, color='black') ax.grid() plt.title(\"Temperature Over Time\") plt.xlabel(\"Time (Month-Day Hour)\")", "= dict() data_dict['Temperature'] = {} data_dict['VOC'] = {} data_dict['Humidity'] = {} for match", "re import argparse import datetime as dt import numpy as np from pandas.plotting", "ax.tick_params(which='minor', length=4, width=2, color='black') ax.grid() plt.title(\"Temperature Over Time\") plt.xlabel(\"Time (Month-Day Hour)\") plt.ylabel(\"Temperature (°C)\")", "(%)\") plt.subplots_adjust(top=0.95) DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) plt.savefig('Environment_Boxplot.png', dpi=500) # plt.show() def extract_data_from_log(data, pattern):", "edges of box to show the range of the data. The position of", "filepath of the log data') parser.add_argument('-s', '--soil', type=str, default=\"soil_moisture_sensor_1.txt\", help='Name of soil moisture", "# plt.show() def boxplot_environment(df): \"\"\"! Creates a boxplot of all the relevant environment", "fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) plt.savefig('Environment_Boxplot.png', dpi=500) # plt.show() def extract_data_from_log(data, pattern): \"\"\"! Function for extracting", "data_dict['VOC'][index_dt] = float(match.group(4)) data_dict['Humidity'][index_dt] = float(match.group(5)) plot_temperature(data_dict['Temperature'], True) plot_temperature(data_dict['Temperature'], False) # Plot environment", "points are those past the end of the whiskers. @param df: dataframe object", "Returns all regex match objects. @param data: Raw data from the log file.", "plot_temperature(dict, past24): \"\"\"! Plots temperature data in simple line chart @param dict: Dicitonary", "def plot_temperature(dict, past24): \"\"\"! Plots temperature data in simple line chart @param dict:", "'--environment', type=str, default=\"environment_sensor.txt\", help='Name of the envrionment sensor log file') args = parser.parse_args()", "hours6 = mdates.HourLocator(interval=6) hours3 = mdates.HourLocator(interval=3) # im = image.imread('./icons/Grow_Space_Logo.png') # fig.figimage(im, 300,", "help='Root filepath of the log data') parser.add_argument('-s', '--soil', type=str, default=\"soil_moisture_sensor_1.txt\", help='Name of soil", "in matches: # current_val = float(match.group(4)) # Raw voltage reading current_val = float(match.group(5))", "Dicitonary containing timestamps and associated readings. \"\"\" lists = sorted(dict.items()) x, y =", "matches = list() for line in data: matches.append(re.match(pattern, line)) return matches def generate_plots(root=\"./logs/\",", "are those past the end of the whiskers. @param df: dataframe object from", "and associated readings. \"\"\" lists = sorted(dict.items()) x, y = zip(*lists) fig, ax", "Over Time\") plt.xlabel(\"Time (Month-Day Hour)\") plt.ylabel(\"Temperature (°C)\") DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) if past24:", "data_dict['Humidity'] = {} for match in matches: index_time = match.group(1) + \" \"", "Time\") plt.xlabel(\"Time (Month-Day Hour)\") plt.ylabel(\"Temperature (°C)\") DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) if past24: datemin", "dict() for match in matches: # current_val = float(match.group(4)) # Raw voltage reading", "import matplotlib.pylab as plt import matplotlib.dates as mdates import matplotlib.image as image import", "ax.xaxis.set_major_formatter(mdates.DateFormatter('%d - %H')) ax.tick_params(which='major', length=7, width=2, color='black') ax.tick_params(which='minor', length=4, width=2, color='black') ax.grid() plt.title(\"Temperature", "myfile.readlines() matches = extract_data_from_log(data, environment_sensor_pattern) data_dict = dict() temperature_dict = dict() data_dict['Temperature'] =", "environment sensor data. What is a boxplot? Text from https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.boxplot.html: The box extends", "all regex match objects. @param data: Raw data from the log file. @param", "'h') datemax = np.datetime64(x[-1], 'h') ax.set_xlim(datemin, datemax) plt.xlabel(\"Hour\") plt.title(\"Soil Moisture % Past 24", "current_val plot_soil_moisture(data_dict, True) plot_soil_moisture(data_dict, False) # Plot temperature data with open(root+environment_sensor_log, \"r\") as", "plt.style.context(\"seaborn\"): fig, ax = plt.subplots(1, 3) fig.suptitle('Environment Sensor Data') df.boxplot('Temperature', ax=ax[0]) df.boxplot('VOC', ax=ax[1],", "- %H')) ax.grid() plt.xlabel(\"Day - Hour\") plt.ylabel(\"Moisture Percentage (%)\") plt.title(\"Soil Moisture % vs", "\" \" + match.group(2) index_dt = dt.datetime.strptime(index_time, \"%Y-%m-%d %H:%M:%S.%f\") data_dict['Temperature'][index_dt] = float(match.group(3)) data_dict['VOC'][index_dt]", "= float(match.group(4)) # Raw voltage reading current_val = float(match.group(5)) # Percentage reading index_time", "import register_matplotlib_converters from datetime import datetime register_matplotlib_converters() plt.rcParams.update({'font.size': 22}) environment_sensor_pattern = re.compile(r\"([0-9-]+)\\s([0-9:.]+):\\stemperature:\\s([0-9.]+),\\sgas:\\s([0-9]+),\\shumidity:\\s([0-9.]+),\\spressure:\\s([0-9.]+),\\saltitude:\\s([0-9.]+)\", re.MULTILINE)", "import argparse import datetime as dt import numpy as np from pandas.plotting import", "using regex matching. Returns all regex match objects. @param data: Raw data from", "= current_val plot_soil_moisture(data_dict, True) plot_soil_moisture(data_dict, False) # Plot temperature data with open(root+environment_sensor_log, \"r\")", "= dt.datetime.strptime(index_time, \"%Y-%m-%d %H:%M:%S.%f\") data_dict['Temperature'][index_dt] = float(match.group(3)) data_dict['VOC'][index_dt] = float(match.group(4)) data_dict['Humidity'][index_dt] = float(match.group(5))", "np.timedelta64(24, 'h') datemax = np.datetime64(x[-1], 'h') ax.set_xlim(datemin, datemax) plt.xlabel(\"Hour\") plt.title(\"Soil Moisture % Past", "pattern to use for matching. \"\"\" matches = list() for line in data:", "matches.append(re.match(pattern, line)) return matches def generate_plots(root=\"./logs/\", soil_sensor_log=\"soil_moisture_sensor_1.txt\", environment_sensor_log=\"environment_sensor.txt\"): # Plot soil moisture data", "we generate a boxplot. \"\"\" df['VOC'] = df['VOC'].div(1000) # with plt.style.context(\"seaborn\"): fig, ax", "reading index_time = match.group(1) + \" \" + match.group(2) index_dt = dt.datetime.strptime(index_time, \"%Y-%m-%d", "Raw voltage reading current_val = float(match.group(5)) # Percentage reading index_time = match.group(1) +", "fontsize=12) df.boxplot('Humidity', ax=ax[2]) ax[0].set_ylabel(\"Temperature (°C)\") ax[1].set_ylabel(\"VOC (kΩ)\") ax[2].set_ylabel(\"Humidity (%)\") plt.subplots_adjust(top=0.95) DPI = fig.get_dpi()", "pattern: Regex pattern to use for matching. \"\"\" matches = list() for line", "default to 1.5 * IQR (IQR = Q3 - Q1) from the edges", "# im = image.imread('./icons/Grow_Space_Logo.png') # fig.figimage(im, 650, 0, zorder=3, alpha=0.2) ax.xaxis.set_major_locator(hours6) ax.xaxis.set_minor_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%d", "match.group(1) + \" \" + match.group(2) index_dt = dt.datetime.strptime(index_time, \"%Y-%m-%d %H:%M:%S.%f\") data_dict['Temperature'][index_dt] =", "data. What is a boxplot? Text from https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.boxplot.html: The box extends from the", "data from the log file. @param pattern: Regex pattern to use for matching.", "index_dt = dt.datetime.strptime(index_time, \"%Y-%m-%d %H:%M:%S.%f\") data_dict['Temperature'][index_dt] = float(match.group(3)) data_dict['VOC'][index_dt] = float(match.group(4)) data_dict['Humidity'][index_dt] =", "= np.datetime64(x[-1], 'h') ax.set_xlim(datemin, datemax) plt.xlabel(\"Hour\") plt.title(\"Soil Moisture % Past 24 Hrs\") ax.xaxis.set_major_locator(hours3)", "help='Name of the envrionment sensor log file') args = parser.parse_args() if args.root: root_folder", "box extends from the Q1 to Q3 quartile values of the data, with", "default=\"soil_moisture_sensor_1.txt\", help='Name of soil moisture sensor log file') parser.add_argument('-e', '--environment', type=str, default=\"environment_sensor.txt\", help='Name", "\"\"\"! Plots soil moisture data in simple line chart @param dict: Dicitonary containing", "= np.datetime64(x[-1], 'h') - np.timedelta64(24, 'h') datemax = np.datetime64(x[-1], 'h') ax.set_xlim(datemin, datemax) plt.xlabel(\"Hour\")", "sensor data df = pd.DataFrame.from_dict(data_dict, orient='columns') df.reset_index(inplace=True) boxplot_environment(df) if __name__ == \"__main__\": parser", "hours3 = mdates.HourLocator(interval=3) # im = image.imread('./icons/Grow_Space_Logo.png') # fig.figimage(im, 650, 0, zorder=3, alpha=0.2)", "by default to 1.5 * IQR (IQR = Q3 - Q1) from the", "plt.xlabel(\"Day - Hour\") plt.ylabel(\"Moisture Percentage (%)\") plt.title(\"Soil Moisture % vs Time\") DPI =", "timestamps and associated readings. \"\"\" lists = sorted(dict.items()) x, y = zip(*lists) fig,", "index_dt = dt.datetime.strptime(index_time, \"%Y-%m-%d %H:%M:%S.%f\") data_dict[index_dt] = current_val plot_soil_moisture(data_dict, True) plot_soil_moisture(data_dict, False) #", "functions providing plotting functionalities. \"\"\" import matplotlib.pylab as plt import matplotlib.dates as mdates", "DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) plt.savefig('Environment_Boxplot.png', dpi=500) # plt.show() def extract_data_from_log(data, pattern): \"\"\"! Function", "'h') ax.set_xlim(datemin, datemax) plt.xlabel(\"Hour\") plt.title(\"Soil Moisture % Past 24 Hrs\") ax.xaxis.set_major_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) plt.savefig('Moisture_vs_Time_24H.png',", "a log file using regex matching. Returns all regex match objects. @param data:", "box to show the range of the data. The position of the whiskers", "plt.title('Temperature Past 24 Hrs') ax.xaxis.set_major_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) plt.savefig('Temperature_vs_Time_24H.png', dpi=500) plt.savefig('Temperature_vs_Time.png', dpi=500) # plt.show() def", "300, 0, zorder=3, alpha=0.2) ax.xaxis.set_minor_locator(hours3) ax.tick_params(which='major', length=7, width=2, color='black') ax.tick_params(which='minor', length=4, width=2, color='black')", "im = image.imread('./icons/Grow_Space_Logo.png') # fig.figimage(im, 650, 0, zorder=3, alpha=0.2) ax.xaxis.set_major_locator(hours6) ax.xaxis.set_minor_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%d -", "width=2, color='black') ax.grid() plt.title(\"Temperature Over Time\") plt.xlabel(\"Time (Month-Day Hour)\") plt.ylabel(\"Temperature (°C)\") DPI =", "if past24: datemin = np.datetime64(x[-1], 'h') - np.timedelta64(24, 'h') datemax = np.datetime64(x[-1], 'h')", "image.imread('./icons/Grow_Space_Logo.png') # fig.figimage(im, 650, 0, zorder=3, alpha=0.2) ax.xaxis.set_major_locator(hours6) ax.xaxis.set_minor_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%d - %H')) ax.tick_params(which='major',", "dpi=500) # plt.show() def boxplot_environment(df): \"\"\"! Creates a boxplot of all the relevant", "dict: Dicitonary containing timestamps and associated readings. \"\"\" lists = sorted(dict.items()) x, y", "IQR (IQR = Q3 - Q1) from the edges of the box. Outlier", "sorted(dict.items()) x, y = zip(*lists) fig, ax = plt.subplots() ax.plot(x, y, 'k', linewidth=2)", "plt.rcParams.update({'font.size': 22}) environment_sensor_pattern = re.compile(r\"([0-9-]+)\\s([0-9:.]+):\\stemperature:\\s([0-9.]+),\\sgas:\\s([0-9]+),\\shumidity:\\s([0-9.]+),\\spressure:\\s([0-9.]+),\\saltitude:\\s([0-9.]+)\", re.MULTILINE) soil_moisture_pattern = re.compile(r\"([0-9-]+)\\s([0-9.:]+):\\s\\[([0-9]+),\\s([0-9.]+),\\s([0-9.]+)\\]\", re.MULTILINE) def plot_soil_moisture(dict, past24):", "24 Hrs\") ax.xaxis.set_major_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) plt.savefig('Moisture_vs_Time_24H.png', dpi=500) plt.savefig('Moisture_vs_Time.png', dpi=500) # plt.show() def plot_temperature(dict, past24):", "dict() data_dict['Temperature'] = {} data_dict['VOC'] = {} data_dict['Humidity'] = {} for match in", "readings. \"\"\" lists = sorted(dict.items()) x, y = zip(*lists) fig, ax = plt.subplots()", "float(match.group(4)) data_dict['Humidity'][index_dt] = float(match.group(5)) plot_temperature(data_dict['Temperature'], True) plot_temperature(data_dict['Temperature'], False) # Plot environment sensor data", "linewidth=2) fig.autofmt_xdate() hours6 = mdates.HourLocator(interval=6) hours3 = mdates.HourLocator(interval=3) # im = image.imread('./icons/Grow_Space_Logo.png') #", "parser.parse_args() if args.root: root_folder = \"./logs/\"+args.root+\"/\" else: root_folder = \"./logs/\" generate_plots(root_folder, args.soil, args.environment)", "fig.autofmt_xdate() hours6 = mdates.HourLocator(interval=6) hours3 = mdates.HourLocator(interval=3) # im = image.imread('./icons/Grow_Space_Logo.png') # fig.figimage(im,", "What is a boxplot? Text from https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.boxplot.html: The box extends from the Q1", "simple line chart @param dict: Dicitonary containing timestamps and associated readings. \"\"\" lists", "ax.xaxis.set_major_formatter(mdates.DateFormatter('%d - %H')) ax.grid() plt.xlabel(\"Day - Hour\") plt.ylabel(\"Moisture Percentage (%)\") plt.title(\"Soil Moisture %", "of box to show the range of the data. The position of the", "= myfile.readlines() matches = extract_data_from_log(data, soil_moisture_pattern) data_dict = dict() for match in matches:", "parser.add_argument('-r', '--root', type=str, default=\"\", help='Root filepath of the log data') parser.add_argument('-s', '--soil', type=str,", "data. The position of the whiskers is set by default to 1.5 *", "import matplotlib.image as image import pandas as pd import re import argparse import", "values of the data, with a line at the median (Q2). The whiskers", "index_time = match.group(1) + \" \" + match.group(2) index_dt = dt.datetime.strptime(index_time, \"%Y-%m-%d %H:%M:%S.%f\")", "the whiskers is set by default to 1.5 * IQR (IQR = Q3", "(kΩ)\") ax[2].set_ylabel(\"Humidity (%)\") plt.subplots_adjust(top=0.95) DPI = fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) plt.savefig('Environment_Boxplot.png', dpi=500) # plt.show() def", "plt.savefig('Moisture_vs_Time.png', dpi=500) # plt.show() def plot_temperature(dict, past24): \"\"\"! Plots temperature data in simple", "mdates.HourLocator(interval=6) hours3 = mdates.HourLocator(interval=3) # im = image.imread('./icons/Grow_Space_Logo.png') # fig.figimage(im, 650, 0, zorder=3,", "Creates a boxplot of all the relevant environment sensor data. What is a", "df['VOC'].div(1000) # with plt.style.context(\"seaborn\"): fig, ax = plt.subplots(1, 3) fig.suptitle('Environment Sensor Data') df.boxplot('Temperature',", "past24): \"\"\"! Plots temperature data in simple line chart @param dict: Dicitonary containing", "length=7, width=2, color='black') ax.tick_params(which='minor', length=4, width=2, color='black') ax.xaxis.set_major_locator(hours6) ax.xaxis.set_major_formatter(mdates.DateFormatter('%d - %H')) ax.grid() plt.xlabel(\"Day", "re.compile(r\"([0-9-]+)\\s([0-9.:]+):\\s\\[([0-9]+),\\s([0-9.]+),\\s([0-9.]+)\\]\", re.MULTILINE) def plot_soil_moisture(dict, past24): \"\"\"! Plots soil moisture data in simple line", "datemin = np.datetime64(x[-1], 'h') - np.timedelta64(24, 'h') datemax = np.datetime64(x[-1], 'h') ax.set_xlim(datemin, datemax)", "np.datetime64(x[-1], 'h') ax.set_xlim(datemin, datemax) plt.xlabel(\"Hour\") plt.title('Temperature Past 24 Hrs') ax.xaxis.set_major_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) plt.savefig('Temperature_vs_Time_24H.png', dpi=500)", "soil moisture data with open(root+soil_sensor_log, \"r\") as myfile: data = myfile.readlines() matches =", "import datetime register_matplotlib_converters() plt.rcParams.update({'font.size': 22}) environment_sensor_pattern = re.compile(r\"([0-9-]+)\\s([0-9:.]+):\\stemperature:\\s([0-9.]+),\\sgas:\\s([0-9]+),\\shumidity:\\s([0-9.]+),\\spressure:\\s([0-9.]+),\\saltitude:\\s([0-9.]+)\", re.MULTILINE) soil_moisture_pattern = re.compile(r\"([0-9-]+)\\s([0-9.:]+):\\s\\[([0-9]+),\\s([0-9.]+),\\s([0-9.]+)\\]\", re.MULTILINE)", "of the log data') parser.add_argument('-s', '--soil', type=str, default=\"soil_moisture_sensor_1.txt\", help='Name of soil moisture sensor", "argparse import datetime as dt import numpy as np from pandas.plotting import register_matplotlib_converters", "data, with a line at the median (Q2). The whiskers extend from the", "data: Raw data from the log file. @param pattern: Regex pattern to use", "= match.group(1) + \" \" + match.group(2) index_dt = dt.datetime.strptime(index_time, \"%Y-%m-%d %H:%M:%S.%f\") data_dict['Temperature'][index_dt]", "extract_data_from_log(data, environment_sensor_pattern) data_dict = dict() temperature_dict = dict() data_dict['Temperature'] = {} data_dict['VOC'] =", "set by default to 1.5 * IQR (IQR = Q3 - Q1) from", "\"\"\" lists = sorted(dict.items()) x, y = zip(*lists) fig, ax = plt.subplots() ax.plot(x,", "plt.savefig('Environment_Boxplot.png', dpi=500) # plt.show() def extract_data_from_log(data, pattern): \"\"\"! Function for extracting data out", "= zip(*lists) fig, ax = plt.subplots() ax.plot(x, y, 'k', linewidth=2) fig.autofmt_xdate() hours6 =", "ax.xaxis.set_major_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) plt.savefig('Temperature_vs_Time_24H.png', dpi=500) plt.savefig('Temperature_vs_Time.png', dpi=500) # plt.show() def boxplot_environment(df): \"\"\"! Creates a", "data_dict['Humidity'][index_dt] = float(match.group(5)) plot_temperature(data_dict['Temperature'], True) plot_temperature(data_dict['Temperature'], False) # Plot environment sensor data df", "matplotlib.image as image import pandas as pd import re import argparse import datetime", "a boxplot of all the relevant environment sensor data. What is a boxplot?", "= np.datetime64(x[-1], 'h') ax.set_xlim(datemin, datemax) plt.xlabel(\"Hour\") plt.title('Temperature Past 24 Hrs') ax.xaxis.set_major_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) plt.savefig('Temperature_vs_Time_24H.png',", "ax.set_xlim(datemin, datemax) plt.xlabel(\"Hour\") plt.title('Temperature Past 24 Hrs') ax.xaxis.set_major_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) plt.savefig('Temperature_vs_Time_24H.png', dpi=500) plt.savefig('Temperature_vs_Time.png', dpi=500)", "boxplot of all the relevant environment sensor data. What is a boxplot? Text", "Plots soil moisture data in simple line chart @param dict: Dicitonary containing timestamps", "\"\"\"! Creates a boxplot of all the relevant environment sensor data. What is", "= float(match.group(5)) plot_temperature(data_dict['Temperature'], True) plot_temperature(data_dict['Temperature'], False) # Plot environment sensor data df =", "length=7, width=2, color='black') ax.tick_params(which='minor', length=4, width=2, color='black') ax.grid() plt.title(\"Temperature Over Time\") plt.xlabel(\"Time (Month-Day", "line in data: matches.append(re.match(pattern, line)) return matches def generate_plots(root=\"./logs/\", soil_sensor_log=\"soil_moisture_sensor_1.txt\", environment_sensor_log=\"environment_sensor.txt\"): # Plot", "= plt.subplots(1, 3) fig.suptitle('Environment Sensor Data') df.boxplot('Temperature', ax=ax[0]) df.boxplot('VOC', ax=ax[1], fontsize=12) df.boxplot('Humidity', ax=ax[2])", "data_dict[index_dt] = current_val plot_soil_moisture(data_dict, True) plot_soil_moisture(data_dict, False) # Plot temperature data with open(root+environment_sensor_log,", "fig.get_dpi() fig.set_size_inches(2400.0/float(DPI),1220.0/float(DPI)) if past24: datemin = np.datetime64(x[-1], 'h') - np.timedelta64(24, 'h') datemax =", "dpi=500) plt.savefig('Moisture_vs_Time.png', dpi=500) # plt.show() def plot_temperature(dict, past24): \"\"\"! Plots temperature data in", "log file using regex matching. Returns all regex match objects. @param data: Raw", "= mdates.HourLocator(interval=6) hours3 = mdates.HourLocator(interval=3) # im = image.imread('./icons/Grow_Space_Logo.png') # fig.figimage(im, 650, 0,", "line at the median (Q2). The whiskers extend from the edges of box", "plotting functionalities. \"\"\" import matplotlib.pylab as plt import matplotlib.dates as mdates import matplotlib.image", "datemax) plt.xlabel(\"Hour\") plt.title('Temperature Past 24 Hrs') ax.xaxis.set_major_locator(hours3) ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) plt.savefig('Temperature_vs_Time_24H.png', dpi=500) plt.savefig('Temperature_vs_Time.png', dpi=500) #", "default=\"\", help='Root filepath of the log data') parser.add_argument('-s', '--soil', type=str, default=\"soil_moisture_sensor_1.txt\", help='Name of", "from which we generate a boxplot. \"\"\" df['VOC'] = df['VOC'].div(1000) # with plt.style.context(\"seaborn\"):", "def generate_plots(root=\"./logs/\", soil_sensor_log=\"soil_moisture_sensor_1.txt\", environment_sensor_log=\"environment_sensor.txt\"): # Plot soil moisture data with open(root+soil_sensor_log, \"r\") as", "data with open(root+soil_sensor_log, \"r\") as myfile: data = myfile.readlines() matches = extract_data_from_log(data, soil_moisture_pattern)", "soil moisture data in simple line chart @param dict: Dicitonary containing timestamps and" ]
[ "series values_x will contain 1 list of of x-axis values per series. The", "number of dimensions max_dimensions - limits to generics with max number of dimensions", "the dimension indices to use as variables (1st one must be X axis;", "subset of generic data as a 2D matrix Users passes in the dimension", "Values object. The Values will either contain the scalar type in the original", "of String, parameter \"dimension_ids\" of list of String, parameter \"convert_to_string\" of type \"boolean\",", "in the 2nd dimension) to an index in the list of unique labels", "in the original format, or if the convert_to_string flag is set, will convert", ":returns: instance of type \"ImportResult\" -> structure: parameter \"object_ref\" of String \"\"\" return", "generic object. User will pass in the numeric indices of all dimensions they", "\"boolean_values\" of list of type \"boolean\", parameter \"string_values\" of list of String, parameter", "1 list of of x-axis values per series. The number of series depends", "number of variable dimensions. In each series, values where either the X and", "user_id=None, password=<PASSWORD>, token=<PASSWORD>, ignore_authrc=False, trust_all_ssl_certificates=False, auth_svc='https://kbase.us/services/authorization/Sessions/Login'): if url is None: raise ValueError('A url", "list of String, parameter \"dimension_scalar_types\" of list of list of String \"\"\" return", "of type \"boolean\", parameter \"dimension_value_types\" of list of list of String, parameter \"dimension_scalar_types\"", "\"ExportResult\" -> structure: parameter \"shock_id\" of String \"\"\" return self._client.call_method( 'GenericsUtil.export_csv', [params], self._service_ver,", "of type \"GetGenericDataParams\" (gets subset of generic data as a 2D matrix Users", "of one or more generic objects) -> structure: parameter \"object_ids\" of list of", "String \"\"\" return self._client.call_method( 'GenericsUtil.get_generic_data', [params], self._service_ver, context) def status(self, context=None): return self._client.call_method('GenericsUtil.status',", "\"workspace_name\" of String, parameter \"object_name\" of String, parameter \"object_type\" of String, parameter \"metadata\"", "objects. if 2, returns only umapped objects) -> structure: parameter \"workspace_names\" of list", "scalar types, e.g., object_ref, int, float (see KBaseGenerics.spec for valid types). HNDArrays must", "dimension index. returns: series_labels will show which variable index values correspond to which", "object (there will only be 1 for NDArray objects), e.g., \"specific activity\" scalar_types", "of scalar types in the object (there will only be 1 for NDArray", "made here will be overwritten # ############################################################ from __future__ import print_function # the", "activity\" scalar_types - list of scalar types in the object (there will only", "all dimensions they care about (e.g., 1/1 will mean 1st dimension, 1st data", "of String, parameter \"allowed_data_types\" of list of String, parameter \"allowed_scalar_types\" of list of", "context=None): \"\"\" :param params: instance of type \"GetGenericDataParams\" (gets subset of generic data", "of String, parameter \"dimension_types\" of list of String, parameter \"dimension_sizes\" of list of", "or by fixing a dimension index (e.g., \"2/3\" for the 3rd type of", "\"object_ids\" of list of String \"\"\" return self._client.call_method( 'GenericsUtil.list_generic_objects', [params], self._service_ver, context) def", "for NDArray objects), e.g., \"specific activity\" scalar_types - list of scalar types in", "the X and Y data are null are removed.) -> structure: parameter \"object_id\"", "list of Double, parameter \"boolean_values\" of list of type \"boolean\", parameter \"string_values\" of", "parameter \"file\" of type \"File\" (Import a CSV file into a NDArray or", "def export_csv(self, params, context=None): \"\"\" :param params: instance of type \"ExportParams\" (Exporter for", "object, e.g., KBaseGenerics.NDArray (version number is optional) allowed_data_types - limits to specific data", "the original format, or if the convert_to_string flag is set, will convert the", "to additional series being returned). User selects which dimension indices to fix to", "2, returns only umapped objects) -> structure: parameter \"workspace_names\" of list of String,", "each series, values where either the X and Y data are null are", "\"object_name\" of String, parameter \"object_type\" of String, parameter \"metadata\" of type \"usermeta\" ->", "parameter \"constant_dimension_ids\" of mapping from String to Long :returns: instance of type \"GetGenericDataResult\"", "of String, parameter \"n_dimensions\" of Long, parameter \"is_mapped\" of type \"boolean\", parameter \"value_types\"", ":returns: instance of type \"ListGenericObjectsResult\" -> structure: parameter \"object_ids\" of list of String", "\"file\" of type \"File\" (Import a CSV file into a NDArray or HNDArray.", "of type \"boolean\", parameter \"unique_values\" of type \"boolean\" :returns: instance of type \"GetGenericDimensionLabelsResult\"", "e.g., \"float\" dimension_types - a string describing each dimension (e.g., \"media name\") dimension_sizes", "\"\"\" return self._client.call_method( 'GenericsUtil.import_obo', [params], self._service_ver, context) def export_csv(self, params, context=None): \"\"\" :param", "type \"ExportResult\" -> structure: parameter \"shock_id\" of String \"\"\" return self._client.call_method( 'GenericsUtil.export_csv', [params],", "or if the convert_to_string flag is set, will convert the scalar type to", "Values array may be a different length).) -> structure: parameter \"object_id\" of String,", "(gets subset of generic data as a 2D matrix Users passes in the", "(e.g., \"2/3\" for the 3rd type of values in the 2nd dimension) to", "X axis; additional variables will lead to additional series being returned). User selects", "by the KBase type compiler - # any changes made here will be", "if url is None: raise ValueError('A url is required') self._service_ver = None self._client", "e.g., microbial growth allowed_scalar_types - limits to specific scalar types, e.g., object_ref, int,", "each dimension (e.g., \"int\")) -> structure: parameter \"object_type\" of String, parameter \"data_type\" of", "a package from .baseclient import BaseClient as _BaseClient # @UnusedImport except: # no", "generics with max number of dimensions limit_mapped - if 0 (or unset) returns", "\"int\")) -> structure: parameter \"object_type\" of String, parameter \"data_type\" of String, parameter \"n_dimensions\"", ":returns: instance of type \"GetGenericDataResult\" -> structure: parameter \"series_labels\" of list of String,", "of String, parameter \"shock_id\" of String, parameter \"workspace_name\" of String, parameter \"object_name\" of", "(Exporter for generic objects as CSV files) -> structure: parameter \"input_ref\" of String", "will either contain the scalar type in the original format, or if the", "- list of scalar types in the object (there will only be 1", "parameter \"scalar_type\" of type \"data_type\", parameter \"object_refs\" of list of type \"object_ref\", parameter", "of values in the 2nd dimension) to an index in the list of", "60, user_id=None, password=<PASSWORD>, token=<PASSWORD>, ignore_authrc=False, trust_all_ssl_certificates=False, auth_svc='https://kbase.us/services/authorization/Sessions/Login'): if url is None: raise ValueError('A", "CSV files) -> structure: parameter \"input_ref\" of String :returns: instance of type \"ExportResult\"", "for generic objects as CSV files) -> structure: parameter \"input_ref\" of String :returns:", "will contain 1 list of of y-axis values per series. The number of", "if the convert_to_string flag is set, will convert the scalar type to strings.", "# baseclient and this client are in a package from .baseclient import BaseClient", "- limits to specific data types, e.g., microbial growth allowed_scalar_types - limits to", "series. The number of series depends on the number of variable dimensions. values_y", "- a string describing each context of each dimension (e.g., \"media name\") dimension_scalar_types", "be re-indexed, but not resorted, so the Values array may be a different", "\"string_values\" of list of String \"\"\" return self._client.call_method( 'GenericsUtil.get_generic_data', [params], self._service_ver, context) def", "of list of type \"boolean\", parameter \"dimension_value_types\" of list of list of String,", "instance of type \"GetGenericDataParams\" (gets subset of generic data as a 2D matrix", "of Double, parameter \"boolean_values\" of list of type \"boolean\", parameter \"string_values\" of list", "the dimension indices to a Values object. The Values will either contain the", "def get_generic_metadata(self, params, context=None): \"\"\" :param params: instance of type \"GetGenericMetadataParams\" (Get metadata", "to strings. If unique_values is set, the API will only return the unique", "of list of String, parameter \"min_dimensions\" of Long, parameter \"max_dimensions\" of Long, parameter", "that dimension index. returns: series_labels will show which variable index values correspond to", "\"\"\" return self._client.call_method( 'GenericsUtil.get_generic_data', [params], self._service_ver, context) def status(self, context=None): return self._client.call_method('GenericsUtil.status', [],", "valid types). HNDArrays must have at least one dimension that passes. min_dimensions -", "parameter \"min_dimensions\" of Long, parameter \"max_dimensions\" of Long, parameter \"limit_mapped\" of Long :returns:", "dimension) to an index in the list of unique labels for that dimension", "of list of String \"\"\" return self._client.call_method( 'GenericsUtil.get_generic_data', [params], self._service_ver, context) def status(self,", "dimension that passes. min_dimensions - limits to generics with minimum number of dimensions", "unset) returns all objects. if 1, returns only mapped objects. if 2, returns", "additional series being returned). User selects which dimension indices to fix to particular", "list of String, parameter \"allowed_object_types\" of list of String, parameter \"allowed_data_types\" of list", "of type \"ImportOBOParams\" (Import an OBO file into an OntologyDictionary) -> structure: parameter", "of list of String, parameter \"allowed_scalar_types\" of list of String, parameter \"min_dimensions\" of", "type \"object_ref\", parameter \"oterm_refs\" of list of type \"oterm_ref\", parameter \"int_values\" of list", "This can be done one of two ways: either by fixing an entire", "as variables (1st one must be X axis; additional variables will lead to", "params: instance of type \"GetGenericMetadataParams\" (Get metadata describing the dimensions of one or", "hash mapping each of the dimension indices to a Values object. The Values", "will lead to additional series being returned). User selects which dimension indices to", "-> structure: parameter \"workspace_names\" of list of String, parameter \"allowed_object_types\" of list of", "self._service_ver, context) def get_generic_metadata(self, params, context=None): \"\"\" :param params: instance of type \"GetGenericMetadataParams\"", "[params], self._service_ver, context) def get_generic_dimension_labels(self, params, context=None): \"\"\" :param params: instance of type", "list of of y-axis values per series. The number of series depends on", "String \"\"\" return self._client.call_method( 'GenericsUtil.get_generic_metadata', [params], self._service_ver, context) def get_generic_dimension_labels(self, params, context=None): \"\"\"", "list_generic_objects(self, params, context=None): \"\"\" :param params: instance of type \"ListGenericObjectsParams\" (List generic objects", "object_refs oterm_refs int_values float_values string_values boolean_values) -> structure: parameter \"scalar_type\" of type \"data_type\",", "import_obo(self, params, context=None): \"\"\" :param params: instance of type \"ImportOBOParams\" (Import an OBO", "1st dimension, 1st data type, 2/1 = 2nd dimension, 1st data type), and", "one or more generic objects) -> structure: parameter \"object_ids\" of list of String", "the baseclient to import whether we're in a # package or not. This", "KBase type compiler - # any changes made here will be overwritten #", "variables (1st one must be X axis; additional variables will lead to additional", "describing each dimension (e.g., \"media name\") dimension_sizes - size (length) of each dimension", "constants. This can be done one of two ways: either by fixing an", "in the object (there will only be 1 for NDArray objects), e.g., \"specific", "scalar types in the object (there will only be 1 for NDArray objects),", "contain 1 list of of x-axis values per series. The number of series", "object. User will pass in the numeric indices of all dimensions they care", "\"object_ref\" of String \"\"\" return self._client.call_method( 'GenericsUtil.import_obo', [params], self._service_ver, context) def export_csv(self, params,", "String \"\"\" return self._client.call_method( 'GenericsUtil.export_csv', [params], self._service_ver, context) def list_generic_objects(self, params, context=None): \"\"\"", "one dimension that passes. min_dimensions - limits to generics with minimum number of", "will return a hash mapping each of the dimension indices to a Values", "This makes pep8 unhappy hence the annotations. try: # baseclient and this client", "OntologyDictionary) -> structure: parameter \"file\" of type \"File\" (Import a CSV file into", "generic objects as CSV files) -> structure: parameter \"input_ref\" of String :returns: instance", "value types in the object (there will only be 1 for NDArray objects),", "structure: parameter \"shock_id\" of String \"\"\" return self._client.call_method( 'GenericsUtil.export_csv', [params], self._service_ver, context) def", "context) def list_generic_objects(self, params, context=None): \"\"\" :param params: instance of type \"ListGenericObjectsParams\" (List", "dimension (e.g., \"media name\") dimension_sizes - size (length) of each dimension dimension_value_types -", "\"variable_dimension_ids\" of list of String, parameter \"constant_dimension_ids\" of mapping from String to Long", "are common to all import methods.) -> structure: parameter \"path\" of String, parameter", "re-indexed, but not resorted, so the Values array may be a different length).)", "where either the X and Y data are null are removed.) -> structure:", "-> structure: parameter \"object_id\" of String, parameter \"variable_dimension_ids\" of list of String, parameter", "return the unique values in each dimension (these will also be re-indexed, but", "parameter \"values_y\" of list of type \"Values\" (@optional object_refs oterm_refs int_values float_values string_values", "an optional flag, convert_to_string. The API will return a hash mapping each of", "'GenericsUtil.get_generic_dimension_labels', [params], self._service_ver, context) def get_generic_data(self, params, context=None): \"\"\" :param params: instance of", "-> structure: parameter \"shock_id\" of String \"\"\" return self._client.call_method( 'GenericsUtil.export_csv', [params], self._service_ver, context)", "of String \"\"\" return self._client.call_method( 'GenericsUtil.export_csv', [params], self._service_ver, context) def list_generic_objects(self, params, context=None):", "type \"usermeta\" -> mapping from String to String :returns: instance of type \"ImportResult\"", "with minimum number of dimensions max_dimensions - limits to generics with max number", "-> structure: parameter \"object_ids\" of list of String :returns: instance of type \"GetGenericMetadataResult\"", "objects in one or more workspaces optional parameters: allowed_object_types - limits to specific", "in the numeric indices of all dimensions they care about (e.g., 1/1 will", "data_type - e.g., microbial growth n_dimensions - number of dimensions is_mapped - 0", "dimension (these will also be re-indexed, but not resorted, so the Values array", "(@optional object_refs oterm_refs int_values float_values string_values boolean_values) -> structure: parameter \"scalar_type\" of type", "\"scalar_type\" of type \"data_type\", parameter \"object_refs\" of list of type \"object_ref\", parameter \"oterm_refs\"", "of list of list of String, parameter \"dimension_scalar_types\" of list of list of", "series being returned). User selects which dimension indices to fix to particular constants.", "dimension, 1st data type), and an optional flag, convert_to_string. The API will return", "done one of two ways: either by fixing an entire dimension (e.g., \"2\"", "labels, or by fixing a dimension index (e.g., \"2/3\" for the 3rd type", ":param params: instance of type \"ImportCSVParams\" -> structure: parameter \"file\" of type \"File\"", "have at least one dimension that passes. min_dimensions - limits to generics with", "unhappy hence the annotations. try: # baseclient and this client are in a", "1st data type), and an optional flag, convert_to_string. The API will return a", "parameter \"float_values\" of list of Double, parameter \"boolean_values\" of list of type \"boolean\",", "self._client.call_method( 'GenericsUtil.import_obo', [params], self._service_ver, context) def export_csv(self, params, context=None): \"\"\" :param params: instance", "dimensions. values_y will contain 1 list of of y-axis values per series. The", "types in the object (there will only be 1 for NDArray objects), e.g.,", "of String, parameter \"dimension_sizes\" of list of Long, parameter \"has_unique_subindices\" of list of", "about (e.g., 1/1 will mean 1st dimension, 1st data type, 2/1 = 2nd", "can be done one of two ways: either by fixing an entire dimension", "labels for list of dimension axes for a generic object. User will pass", "type \"ImportResult\" -> structure: parameter \"object_ref\" of String \"\"\" return self._client.call_method( 'GenericsUtil.import_obo', [params],", "convert the scalar type to strings. If unique_values is set, the API will", "type, 2/1 = 2nd dimension, 1st data type), and an optional flag, convert_to_string.", "to a Values object. The Values will either contain the scalar type in", "\"GetGenericDimensionLabelsResult\" -> structure: parameter \"dimension_labels\" of mapping from String to type \"Values\" (@optional", "parameter \"shock_id\" of String, parameter \"workspace_name\" of String, parameter \"object_name\" of String, parameter", "\"boolean\", parameter \"value_types\" of list of String, parameter \"scalar_types\" of list of String,", "they aren't from baseclient import BaseClient as _BaseClient # @Reimport class GenericsUtil(object): def", "only umapped objects) -> structure: parameter \"workspace_names\" of list of String, parameter \"allowed_object_types\"", "each dimension (e.g., \"media name\") dimension_scalar_types - type of values in each context", "depends on the number of variable dimensions. In each series, values where either", "return self._client.call_method( 'GenericsUtil.import_csv', [params], self._service_ver, context) def import_obo(self, params, context=None): \"\"\" :param params:", "string describing each context of each dimension (e.g., \"media name\") dimension_scalar_types - type", "list of Long, parameter \"has_unique_subindices\" of list of type \"boolean\", parameter \"dimension_value_types\" of", "\"boolean\", parameter \"string_values\" of list of String \"\"\" return self._client.call_method( 'GenericsUtil.get_generic_dimension_labels', [params], self._service_ver,", "following is a hack to get the baseclient to import whether we're in", "import whether we're in a # package or not. This makes pep8 unhappy", "String \"\"\" return self._client.call_method( 'GenericsUtil.import_obo', [params], self._service_ver, context) def export_csv(self, params, context=None): \"\"\"", "of String, parameter \"allowed_scalar_types\" of list of String, parameter \"min_dimensions\" of Long, parameter", "that passes. min_dimensions - limits to generics with minimum number of dimensions max_dimensions", "of list of type \"oterm_ref\", parameter \"int_values\" of list of Long, parameter \"float_values\"", "utf-8 -*- ############################################################ # # Autogenerated by the KBase type compiler - #", "object ids to structure with metadata) -> structure: parameter \"object_info\" of mapping from", "each dimension dimension_value_types - a string describing each context of each dimension (e.g.,", "self._service_ver, context) def get_generic_dimension_labels(self, params, context=None): \"\"\" :param params: instance of type \"GetGenericDimensionLabelsParams\"", "of String, parameter \"values_y\" of list of type \"Values\" (@optional object_refs oterm_refs int_values", "of dimensions max_dimensions - limits to generics with max number of dimensions limit_mapped", "type \"GenericMetadata\" (Basic metadata about an object: object_type - e.g., KBaseGenerics.HNDArray‑4.0 data_type -", "structure: parameter \"object_id\" of String, parameter \"variable_dimension_ids\" of list of String, parameter \"constant_dimension_ids\"", "list of String, parameter \"values_x\" of list of type \"Values\" (@optional object_refs oterm_refs", "of String, parameter \"object_name\" of String, parameter \"metadata\" of type \"usermeta\" -> mapping", "name\") dimension_sizes - size (length) of each dimension dimension_value_types - a string describing", "dimension (e.g., \"media name\") dimension_scalar_types - type of values in each context of", "of list of Long, parameter \"float_values\" of list of Double, parameter \"boolean_values\" of", "1 indicating mapped status value_types - list of value types in the object", "String, parameter \"constant_dimension_ids\" of mapping from String to Long :returns: instance of type", "print_function # the following is a hack to get the baseclient to import", "def import_csv(self, params, context=None): \"\"\" :param params: instance of type \"ImportCSVParams\" -> structure:", "Long, parameter \"limit_mapped\" of Long :returns: instance of type \"ListGenericObjectsResult\" -> structure: parameter", "String, parameter \"min_dimensions\" of Long, parameter \"max_dimensions\" of Long, parameter \"limit_mapped\" of Long", "of mapping from String to Long :returns: instance of type \"GetGenericDataResult\" -> structure:", "parameter \"string_values\" of list of String, parameter \"values_y\" of list of type \"Values\"", "-> structure: parameter \"object_ref\" of String \"\"\" return self._client.call_method( 'GenericsUtil.import_csv', [params], self._service_ver, context)", "the number of variable dimensions. values_y will contain 1 list of of y-axis", ":param params: instance of type \"GetGenericDataParams\" (gets subset of generic data as a", "original format, or if the convert_to_string flag is set, will convert the scalar", "objects), e.g., \"specific activity\" scalar_types - list of scalar types in the object", "of list of String, parameter \"scalar_types\" of list of String, parameter \"dimension_types\" of", "or more generic objects) -> structure: parameter \"object_ids\" of list of String :returns:", "- limits to generics with minimum number of dimensions max_dimensions - limits to", "type), and an optional flag, convert_to_string. The API will return a hash mapping", "API will return a hash mapping each of the dimension indices to a", "return self._client.call_method( 'GenericsUtil.get_generic_data', [params], self._service_ver, context) def status(self, context=None): return self._client.call_method('GenericsUtil.status', [], self._service_ver,", "type \"boolean\", parameter \"dimension_value_types\" of list of list of String, parameter \"dimension_scalar_types\" of", "String, parameter \"dimension_types\" of list of String, parameter \"dimension_sizes\" of list of Long,", "will only be 1 for NDArray objects), e.g., \"specific activity\" scalar_types - list", "type \"boolean\", parameter \"string_values\" of list of String \"\"\" return self._client.call_method( 'GenericsUtil.get_generic_data', [params],", "NDArray objects), e.g., \"specific activity\" scalar_types - list of scalar types in the", "of x-axis values per series. The number of series depends on the number", "number is optional) allowed_data_types - limits to specific data types, e.g., microbial growth", "type \"data_type\", parameter \"object_refs\" of list of type \"object_ref\", parameter \"oterm_refs\" of list", "all import methods.) -> structure: parameter \"path\" of String, parameter \"shock_id\" of String,", "specific scalar types, e.g., object_ref, int, float (see KBaseGenerics.spec for valid types). HNDArrays", "number of series depends on the number of variable dimensions. In each series,", "\"ImportResult\" -> structure: parameter \"object_ref\" of String \"\"\" return self._client.call_method( 'GenericsUtil.import_csv', [params], self._service_ver,", "parameter \"max_dimensions\" of Long, parameter \"limit_mapped\" of Long :returns: instance of type \"ListGenericObjectsResult\"", "ValueError('A url is required') self._service_ver = None self._client = _BaseClient( url, timeout=timeout, user_id=user_id,", "params: instance of type \"GetGenericDataParams\" (gets subset of generic data as a 2D", "of String \"\"\" return self._client.call_method( 'GenericsUtil.import_csv', [params], self._service_ver, context) def import_obo(self, params, context=None):", "\"object_info\" of mapping from String to type \"GenericMetadata\" (Basic metadata about an object:", "self._client.call_method( 'GenericsUtil.export_csv', [params], self._service_ver, context) def list_generic_objects(self, params, context=None): \"\"\" :param params: instance", "(e.g., \"2\" for the 2nd dimension) to an index in the complete list", "parameter \"has_unique_subindices\" of list of type \"boolean\", parameter \"dimension_value_types\" of list of list", "self._client.call_method( 'GenericsUtil.get_generic_data', [params], self._service_ver, context) def status(self, context=None): return self._client.call_method('GenericsUtil.status', [], self._service_ver, context)", "Values will either contain the scalar type in the original format, or if", "ignore_authrc=False, trust_all_ssl_certificates=False, auth_svc='https://kbase.us/services/authorization/Sessions/Login'): if url is None: raise ValueError('A url is required') self._service_ver", "is None: raise ValueError('A url is required') self._service_ver = None self._client = _BaseClient(", "type \"GetGenericMetadataResult\" (maps object ids to structure with metadata) -> structure: parameter \"object_info\"", "dimension_sizes - size (length) of each dimension dimension_value_types - a string describing each", "a string describing each context of each dimension (e.g., \"media name\") dimension_scalar_types -", "they care about (e.g., 1/1 will mean 1st dimension, 1st data type, 2/1", "get_generic_dimension_labels(self, params, context=None): \"\"\" :param params: instance of type \"GetGenericDimensionLabelsParams\" (gets labels for", "an OntologyDictionary) -> structure: parameter \"file\" of type \"File\" (Import a CSV file", "of String, parameter \"metadata\" of type \"usermeta\" -> mapping from String to String", "series depends on the number of variable dimensions. values_y will contain 1 list", "parameter \"int_values\" of list of Long, parameter \"float_values\" of list of Double, parameter", "\"dimension_sizes\" of list of Long, parameter \"has_unique_subindices\" of list of type \"boolean\", parameter", "as _BaseClient # @Reimport class GenericsUtil(object): def __init__( self, url=None, timeout=30 * 60,", "structure: parameter \"workspace_names\" of list of String, parameter \"allowed_object_types\" of list of String,", "minimum number of dimensions max_dimensions - limits to generics with max number of", "parameter \"limit_mapped\" of Long :returns: instance of type \"ListGenericObjectsResult\" -> structure: parameter \"object_ids\"", "lead to additional series being returned). User selects which dimension indices to fix", "API will only return the unique values in each dimension (these will also", "variable dimensions. In each series, values where either the X and Y data", "-> structure: parameter \"object_ref\" of String \"\"\" return self._client.call_method( 'GenericsUtil.import_obo', [params], self._service_ver, context)", "parameters: allowed_object_types - limits to specific types of object, e.g., KBaseGenerics.NDArray (version number", "'GenericsUtil.get_generic_metadata', [params], self._service_ver, context) def get_generic_dimension_labels(self, params, context=None): \"\"\" :param params: instance of", "def get_generic_dimension_labels(self, params, context=None): \"\"\" :param params: instance of type \"GetGenericDimensionLabelsParams\" (gets labels", "data type, 2/1 = 2nd dimension, 1st data type), and an optional flag,", "String :returns: instance of type \"ImportResult\" -> structure: parameter \"object_ref\" of String \"\"\"", "parameter \"input_ref\" of String :returns: instance of type \"ExportResult\" -> structure: parameter \"shock_id\"", "self, url=None, timeout=30 * 60, user_id=None, password=<PASSWORD>, token=<PASSWORD>, ignore_authrc=False, trust_all_ssl_certificates=False, auth_svc='https://kbase.us/services/authorization/Sessions/Login'): if url", "the annotations. try: # baseclient and this client are in a package from", "to type \"Values\" (@optional object_refs oterm_refs int_values float_values string_values boolean_values) -> structure: parameter", "list of type \"boolean\", parameter \"string_values\" of list of String \"\"\" return self._client.call_method(", "particular constants. This can be done one of two ways: either by fixing", "complete list of labels, or by fixing a dimension index (e.g., \"2/3\" for", "dimensions is_mapped - 0 or 1 indicating mapped status value_types - list of", "in each dimension (these will also be re-indexed, but not resorted, so the", "instance of type \"ExportParams\" (Exporter for generic objects as CSV files) -> structure:", "\"unique_values\" of type \"boolean\" :returns: instance of type \"GetGenericDimensionLabelsResult\" -> structure: parameter \"dimension_labels\"", "of type \"ImportCSVParams\" -> structure: parameter \"file\" of type \"File\" (Import a CSV", "parameter \"object_name\" of String, parameter \"object_type\" of String, parameter \"metadata\" of type \"usermeta\"", "- a string describing each dimension (e.g., \"media name\") dimension_sizes - size (length)", "(there will only be 1 for NDArray objects), e.g., \"specific activity\" scalar_types -", "list of type \"boolean\", parameter \"string_values\" of list of String, parameter \"values_y\" of", "'GenericsUtil.import_obo', [params], self._service_ver, context) def export_csv(self, params, context=None): \"\"\" :param params: instance of", "parameter \"boolean_values\" of list of type \"boolean\", parameter \"string_values\" of list of String,", "context=None): \"\"\" :param params: instance of type \"GetGenericDimensionLabelsParams\" (gets labels for list of", "String, parameter \"object_name\" of String, parameter \"metadata\" of type \"usermeta\" -> mapping from", "structure with metadata) -> structure: parameter \"object_info\" of mapping from String to type", "of String \"\"\" return self._client.call_method( 'GenericsUtil.import_obo', [params], self._service_ver, context) def export_csv(self, params, context=None):", "float_values string_values boolean_values) -> structure: parameter \"scalar_type\" of type \"data_type\", parameter \"object_refs\" of", "are removed.) -> structure: parameter \"object_id\" of String, parameter \"variable_dimension_ids\" of list of", "indices of all dimensions they care about (e.g., 1/1 will mean 1st dimension,", "instance of type \"ImportOBOParams\" (Import an OBO file into an OntologyDictionary) -> structure:", "of type \"ExportParams\" (Exporter for generic objects as CSV files) -> structure: parameter", "allowed_scalar_types - limits to specific scalar types, e.g., object_ref, int, float (see KBaseGenerics.spec", "growth n_dimensions - number of dimensions is_mapped - 0 or 1 indicating mapped", "number of variable dimensions. values_y will contain 1 list of of y-axis values", "\"metadata\" of type \"usermeta\" -> mapping from String to String :returns: instance of", "auth_svc='https://kbase.us/services/authorization/Sessions/Login'): if url is None: raise ValueError('A url is required') self._service_ver = None", "one must be X axis; additional variables will lead to additional series being", "structure: parameter \"series_labels\" of list of String, parameter \"values_x\" of list of type", "of type \"ListGenericObjectsParams\" (List generic objects in one or more workspaces optional parameters:", "data are null are removed.) -> structure: parameter \"object_id\" of String, parameter \"variable_dimension_ids\"", "\"is_mapped\" of type \"boolean\", parameter \"value_types\" of list of String, parameter \"scalar_types\" of", "of values in each context of each dimension (e.g., \"int\")) -> structure: parameter", "parameter \"dimension_value_types\" of list of list of String, parameter \"dimension_scalar_types\" of list of", "dimension_value_types - a string describing each context of each dimension (e.g., \"media name\")", "set, will convert the scalar type to strings. If unique_values is set, the", "parameter \"dimension_ids\" of list of String, parameter \"convert_to_string\" of type \"boolean\", parameter \"unique_values\"", "a CSV file into a NDArray or HNDArray. \"File\" and \"usermeta\" are common", "client are in a package from .baseclient import BaseClient as _BaseClient # @UnusedImport", "String \"\"\" return self._client.call_method( 'GenericsUtil.list_generic_objects', [params], self._service_ver, context) def get_generic_metadata(self, params, context=None): \"\"\"", "parameter \"scalar_types\" of list of String, parameter \"dimension_types\" of list of String, parameter", "a # package or not. This makes pep8 unhappy hence the annotations. try:", ":param params: instance of type \"ImportOBOParams\" (Import an OBO file into an OntologyDictionary)", "list of String \"\"\" return self._client.call_method( 'GenericsUtil.list_generic_objects', [params], self._service_ver, context) def get_generic_metadata(self, params,", "\"path\" of String, parameter \"shock_id\" of String, parameter \"workspace_name\" of String, parameter \"object_name\"", "The Values will either contain the scalar type in the original format, or", "############################################################ from __future__ import print_function # the following is a hack to get", "describing the dimensions of one or more generic objects) -> structure: parameter \"object_ids\"", "0 or 1 indicating mapped status value_types - list of value types in", ":returns: instance of type \"GetGenericDimensionLabelsResult\" -> structure: parameter \"dimension_labels\" of mapping from String", "structure: parameter \"file\" of type \"File\" (Import a CSV file into a NDArray", "scalar type in the original format, or if the convert_to_string flag is set,", "or 1 indicating mapped status value_types - list of value types in the", "type \"GetGenericDimensionLabelsParams\" (gets labels for list of dimension axes for a generic object.", "int_values float_values string_values boolean_values) -> structure: parameter \"scalar_type\" of type \"data_type\", parameter \"object_refs\"", "password=<PASSWORD>, token=<PASSWORD>, ignore_authrc=False, trust_all_ssl_certificates=False, auth_svc='https://kbase.us/services/authorization/Sessions/Login'): if url is None: raise ValueError('A url is", "of type \"object_ref\", parameter \"oterm_refs\" of list of type \"oterm_ref\", parameter \"int_values\" of", "fix to particular constants. This can be done one of two ways: either", "which variable index values correspond to which series values_x will contain 1 list", "max number of dimensions limit_mapped - if 0 (or unset) returns all objects.", "if 0 (or unset) returns all objects. if 1, returns only mapped objects.", "mapping from String to String :returns: instance of type \"ImportResult\" -> structure: parameter", "of String, parameter \"dimension_scalar_types\" of list of list of String \"\"\" return self._client.call_method(", "HNDArray. \"File\" and \"usermeta\" are common to all import methods.) -> structure: parameter", "structure: parameter \"input_ref\" of String :returns: instance of type \"ExportResult\" -> structure: parameter", "variable dimensions. values_y will contain 1 list of of y-axis values per series.", "of type \"Values\" (@optional object_refs oterm_refs int_values float_values string_values boolean_values) -> structure: parameter", "\"max_dimensions\" of Long, parameter \"limit_mapped\" of Long :returns: instance of type \"ListGenericObjectsResult\" ->", "is required') self._service_ver = None self._client = _BaseClient( url, timeout=timeout, user_id=user_id, password=password, token=token,", "each dimension (these will also be re-indexed, but not resorted, so the Values", "type of values in the 2nd dimension) to an index in the list", "[params], self._service_ver, context) def export_csv(self, params, context=None): \"\"\" :param params: instance of type", "from .baseclient import BaseClient as _BaseClient # @UnusedImport except: # no they aren't", "instance of type \"ExportResult\" -> structure: parameter \"shock_id\" of String \"\"\" return self._client.call_method(", "String, parameter \"allowed_scalar_types\" of list of String, parameter \"min_dimensions\" of Long, parameter \"max_dimensions\"", "which dimension indices to fix to particular constants. This can be done one", "additional variables will lead to additional series being returned). User selects which dimension", "= 2nd dimension, 1st data type), and an optional flag, convert_to_string. The API", "params, context=None): \"\"\" :param params: instance of type \"ImportOBOParams\" (Import an OBO file", "mapping from String to Long :returns: instance of type \"GetGenericDataResult\" -> structure: parameter", "context) def get_generic_dimension_labels(self, params, context=None): \"\"\" :param params: instance of type \"GetGenericDimensionLabelsParams\" (gets", "a 2D matrix Users passes in the dimension indices to use as variables", "an index in the list of unique labels for that dimension index. returns:", "of String \"\"\" return self._client.call_method( 'GenericsUtil.list_generic_objects', [params], self._service_ver, context) def get_generic_metadata(self, params, context=None):", "set, the API will only return the unique values in each dimension (these", "list of list of String, parameter \"dimension_scalar_types\" of list of list of String", "parameter \"boolean_values\" of list of type \"boolean\", parameter \"string_values\" of list of String", "instance of type \"ListGenericObjectsParams\" (List generic objects in one or more workspaces optional", "baseclient and this client are in a package from .baseclient import BaseClient as", "of type \"GetGenericDimensionLabelsParams\" (gets labels for list of dimension axes for a generic", "(Basic metadata about an object: object_type - e.g., KBaseGenerics.HNDArray‑4.0 data_type - e.g., microbial", "the object (there will only be 1 for NDArray objects), e.g., \"float\" dimension_types", "of String \"\"\" return self._client.call_method( 'GenericsUtil.get_generic_metadata', [params], self._service_ver, context) def get_generic_dimension_labels(self, params, context=None):", "object (there will only be 1 for NDArray objects), e.g., \"float\" dimension_types -", "a different length).) -> structure: parameter \"object_id\" of String, parameter \"dimension_ids\" of list", "dimension, 1st data type, 2/1 = 2nd dimension, 1st data type), and an", "for the 2nd dimension) to an index in the complete list of labels,", "parameter \"object_id\" of String, parameter \"variable_dimension_ids\" of list of String, parameter \"constant_dimension_ids\" of", "about an object: object_type - e.g., KBaseGenerics.HNDArray‑4.0 data_type - e.g., microbial growth n_dimensions", "type \"GetGenericDimensionLabelsResult\" -> structure: parameter \"dimension_labels\" of mapping from String to type \"Values\"", "\"2/3\" for the 3rd type of values in the 2nd dimension) to an", "in a # package or not. This makes pep8 unhappy hence the annotations.", "common to all import methods.) -> structure: parameter \"path\" of String, parameter \"shock_id\"", "0 (or unset) returns all objects. if 1, returns only mapped objects. if", "dimension axes for a generic object. User will pass in the numeric indices", "parameter \"unique_values\" of type \"boolean\" :returns: instance of type \"GetGenericDimensionLabelsResult\" -> structure: parameter", "String, parameter \"values_y\" of list of type \"Values\" (@optional object_refs oterm_refs int_values float_values", "params, context=None): \"\"\" :param params: instance of type \"ImportCSVParams\" -> structure: parameter \"file\"", "baseclient import BaseClient as _BaseClient # @Reimport class GenericsUtil(object): def __init__( self, url=None,", "of type \"GetGenericDimensionLabelsResult\" -> structure: parameter \"dimension_labels\" of mapping from String to type", "list of String \"\"\" return self._client.call_method( 'GenericsUtil.get_generic_data', [params], self._service_ver, context) def status(self, context=None):", "each dimension (e.g., \"media name\") dimension_sizes - size (length) of each dimension dimension_value_types", "parameter \"object_type\" of String, parameter \"metadata\" of type \"usermeta\" -> mapping from String", "dimension_types - a string describing each dimension (e.g., \"media name\") dimension_sizes - size", "on the number of variable dimensions. values_y will contain 1 list of of", "type \"ImportCSVParams\" -> structure: parameter \"file\" of type \"File\" (Import a CSV file", "parameter \"metadata\" of type \"usermeta\" -> mapping from String to String :returns: instance", "if 2, returns only umapped objects) -> structure: parameter \"workspace_names\" of list of", "object_type - e.g., KBaseGenerics.HNDArray‑4.0 data_type - e.g., microbial growth n_dimensions - number of", "\"object_refs\" of list of type \"object_ref\", parameter \"oterm_refs\" of list of type \"oterm_ref\",", "overwritten # ############################################################ from __future__ import print_function # the following is a hack", "dimension indices to a Values object. The Values will either contain the scalar", "list of String, parameter \"allowed_data_types\" of list of String, parameter \"allowed_scalar_types\" of list", "type \"Values\" (@optional object_refs oterm_refs int_values float_values string_values boolean_values) -> structure: parameter \"scalar_type\"", "of mapping from String to type \"GenericMetadata\" (Basic metadata about an object: object_type", "\"oterm_refs\" of list of type \"oterm_ref\", parameter \"int_values\" of list of Long, parameter", "of String, parameter \"values_x\" of list of type \"Values\" (@optional object_refs oterm_refs int_values", "object. The Values will either contain the scalar type in the original format,", "of dimension axes for a generic object. User will pass in the numeric", "only be 1 for NDArray objects), e.g., \"float\" dimension_types - a string describing", "boolean_values) -> structure: parameter \"scalar_type\" of type \"data_type\", parameter \"object_refs\" of list of", "values where either the X and Y data are null are removed.) ->", "1, returns only mapped objects. if 2, returns only umapped objects) -> structure:", "at least one dimension that passes. min_dimensions - limits to generics with minimum", "of each dimension (e.g., \"int\")) -> structure: parameter \"object_type\" of String, parameter \"data_type\"", "be done one of two ways: either by fixing an entire dimension (e.g.,", "params, context=None): \"\"\" :param params: instance of type \"GetGenericMetadataParams\" (Get metadata describing the", "number of series depends on the number of variable dimensions. values_y will contain", "of list of String, parameter \"values_x\" of list of type \"Values\" (@optional object_refs", "type \"ImportOBOParams\" (Import an OBO file into an OntologyDictionary) -> structure: parameter \"file\"", "dimension (e.g., \"int\")) -> structure: parameter \"object_type\" of String, parameter \"data_type\" of String,", "data as a 2D matrix Users passes in the dimension indices to use", "\"input_ref\" of String :returns: instance of type \"ExportResult\" -> structure: parameter \"shock_id\" of", "KBaseGenerics.HNDArray‑4.0 data_type - e.g., microbial growth n_dimensions - number of dimensions is_mapped -", "- e.g., microbial growth n_dimensions - number of dimensions is_mapped - 0 or", "list of String, parameter \"allowed_scalar_types\" of list of String, parameter \"min_dimensions\" of Long,", "the Values array may be a different length).) -> structure: parameter \"object_id\" of", "Users passes in the dimension indices to use as variables (1st one must", "of variable dimensions. In each series, values where either the X and Y", "instance of type \"ListGenericObjectsResult\" -> structure: parameter \"object_ids\" of list of String \"\"\"", "-> structure: parameter \"input_ref\" of String :returns: instance of type \"ExportResult\" -> structure:", "\"object_ids\" of list of String :returns: instance of type \"GetGenericMetadataResult\" (maps object ids", "String, parameter \"metadata\" of type \"usermeta\" -> mapping from String to String :returns:", "of Long, parameter \"max_dimensions\" of Long, parameter \"limit_mapped\" of Long :returns: instance of", "care about (e.g., 1/1 will mean 1st dimension, 1st data type, 2/1 =", "metadata) -> structure: parameter \"object_info\" of mapping from String to type \"GenericMetadata\" (Basic", ":param params: instance of type \"GetGenericDimensionLabelsParams\" (gets labels for list of dimension axes", "baseclient to import whether we're in a # package or not. This makes", "String, parameter \"convert_to_string\" of type \"boolean\", parameter \"unique_values\" of type \"boolean\" :returns: instance", "3rd type of values in the 2nd dimension) to an index in the", "number of dimensions limit_mapped - if 0 (or unset) returns all objects. if", "(Get metadata describing the dimensions of one or more generic objects) -> structure:", "parameter \"workspace_name\" of String, parameter \"object_name\" of String, parameter \"metadata\" of type \"usermeta\"", "1 for NDArray objects), e.g., \"specific activity\" scalar_types - list of scalar types", "to an index in the list of unique labels for that dimension index.", "a hash mapping each of the dimension indices to a Values object. The", "= _BaseClient( url, timeout=timeout, user_id=user_id, password=password, token=token, ignore_authrc=ignore_authrc, trust_all_ssl_certificates=trust_all_ssl_certificates, auth_svc=auth_svc) def import_csv(self, params,", "types). HNDArrays must have at least one dimension that passes. min_dimensions - limits", "the number of variable dimensions. In each series, values where either the X", "[params], self._service_ver, context) def get_generic_metadata(self, params, context=None): \"\"\" :param params: instance of type", "self._client.call_method( 'GenericsUtil.get_generic_metadata', [params], self._service_ver, context) def get_generic_dimension_labels(self, params, context=None): \"\"\" :param params: instance", "parameter \"convert_to_string\" of type \"boolean\", parameter \"unique_values\" of type \"boolean\" :returns: instance of", "of list of String, parameter \"values_y\" of list of type \"Values\" (@optional object_refs", "pass in the numeric indices of all dimensions they care about (e.g., 1/1", "annotations. try: # baseclient and this client are in a package from .baseclient", ".baseclient import BaseClient as _BaseClient # @UnusedImport except: # no they aren't from", "values_y will contain 1 list of of y-axis values per series. The number", "for list of dimension axes for a generic object. User will pass in", "to use as variables (1st one must be X axis; additional variables will", "types, e.g., object_ref, int, float (see KBaseGenerics.spec for valid types). HNDArrays must have", "\"\"\" return self._client.call_method( 'GenericsUtil.import_csv', [params], self._service_ver, context) def import_obo(self, params, context=None): \"\"\" :param", "params: instance of type \"GetGenericDimensionLabelsParams\" (gets labels for list of dimension axes for", "the 2nd dimension) to an index in the list of unique labels for", "Double, parameter \"boolean_values\" of list of type \"boolean\", parameter \"string_values\" of list of", "a generic object. User will pass in the numeric indices of all dimensions", "pep8 unhappy hence the annotations. try: # baseclient and this client are in", "in each context of each dimension (e.g., \"int\")) -> structure: parameter \"object_type\" of", "list of dimension axes for a generic object. User will pass in the", "axis; additional variables will lead to additional series being returned). User selects which", "may be a different length).) -> structure: parameter \"object_id\" of String, parameter \"dimension_ids\"", "must have at least one dimension that passes. min_dimensions - limits to generics", "\"\"\" :param params: instance of type \"ListGenericObjectsParams\" (List generic objects in one or", "(Import a CSV file into a NDArray or HNDArray. \"File\" and \"usermeta\" are", "[params], self._service_ver, context) def list_generic_objects(self, params, context=None): \"\"\" :param params: instance of type", "each context of each dimension (e.g., \"int\")) -> structure: parameter \"object_type\" of String,", "from String to type \"Values\" (@optional object_refs oterm_refs int_values float_values string_values boolean_values) ->", "to an index in the complete list of labels, or by fixing a", "\"boolean\" :returns: instance of type \"GetGenericDimensionLabelsResult\" -> structure: parameter \"dimension_labels\" of mapping from", "try: # baseclient and this client are in a package from .baseclient import", "\"ImportResult\" -> structure: parameter \"object_ref\" of String \"\"\" return self._client.call_method( 'GenericsUtil.import_obo', [params], self._service_ver,", "of list of String, parameter \"allowed_data_types\" of list of String, parameter \"allowed_scalar_types\" of", "params, context=None): \"\"\" :param params: instance of type \"GetGenericDimensionLabelsParams\" (gets labels for list", "to structure with metadata) -> structure: parameter \"object_info\" of mapping from String to", "dimension indices to use as variables (1st one must be X axis; additional", "- list of value types in the object (there will only be 1", "unique labels for that dimension index. returns: series_labels will show which variable index", "variable index values correspond to which series values_x will contain 1 list of", "Long, parameter \"has_unique_subindices\" of list of type \"boolean\", parameter \"dimension_value_types\" of list of", "-> structure: parameter \"dimension_labels\" of mapping from String to type \"Values\" (@optional object_refs", "in the complete list of labels, or by fixing a dimension index (e.g.,", "optional flag, convert_to_string. The API will return a hash mapping each of the", "token=token, ignore_authrc=ignore_authrc, trust_all_ssl_certificates=trust_all_ssl_certificates, auth_svc=auth_svc) def import_csv(self, params, context=None): \"\"\" :param params: instance of", "values in each dimension (these will also be re-indexed, but not resorted, so", "ways: either by fixing an entire dimension (e.g., \"2\" for the 2nd dimension)", "\"oterm_ref\", parameter \"int_values\" of list of Long, parameter \"float_values\" of list of Double,", "be 1 for NDArray objects), e.g., \"specific activity\" scalar_types - list of scalar", "an object: object_type - e.g., KBaseGenerics.HNDArray‑4.0 data_type - e.g., microbial growth n_dimensions -", "instance of type \"ImportCSVParams\" -> structure: parameter \"file\" of type \"File\" (Import a", "of type \"ImportResult\" -> structure: parameter \"object_ref\" of String \"\"\" return self._client.call_method( 'GenericsUtil.import_obo',", "of String, parameter \"scalar_types\" of list of String, parameter \"dimension_types\" of list of", "parameter \"dimension_scalar_types\" of list of list of String \"\"\" return self._client.call_method( 'GenericsUtil.get_generic_metadata', [params],", "parameter \"object_type\" of String, parameter \"data_type\" of String, parameter \"n_dimensions\" of Long, parameter", "an index in the complete list of labels, or by fixing a dimension", "instance of type \"GetGenericDataResult\" -> structure: parameter \"series_labels\" of list of String, parameter", "makes pep8 unhappy hence the annotations. try: # baseclient and this client are", "aren't from baseclient import BaseClient as _BaseClient # @Reimport class GenericsUtil(object): def __init__(", "\"ListGenericObjectsParams\" (List generic objects in one or more workspaces optional parameters: allowed_object_types -", "workspaces optional parameters: allowed_object_types - limits to specific types of object, e.g., KBaseGenerics.NDArray", "\"workspace_names\" of list of String, parameter \"allowed_object_types\" of list of String, parameter \"allowed_data_types\"", "of String :returns: instance of type \"ExportResult\" -> structure: parameter \"shock_id\" of String", "of variable dimensions. values_y will contain 1 list of of y-axis values per", "\"workspace_name\" of String, parameter \"object_name\" of String, parameter \"metadata\" of type \"usermeta\" ->", "Autogenerated by the KBase type compiler - # any changes made here will", "resorted, so the Values array may be a different length).) -> structure: parameter", "contain 1 list of of y-axis values per series. The number of series", "from String to Long :returns: instance of type \"GetGenericDataResult\" -> structure: parameter \"series_labels\"", "-> structure: parameter \"series_labels\" of list of String, parameter \"values_x\" of list of", "dimension index (e.g., \"2/3\" for the 3rd type of values in the 2nd", "params, context=None): \"\"\" :param params: instance of type \"GetGenericDataParams\" (gets subset of generic", "are in a package from .baseclient import BaseClient as _BaseClient # @UnusedImport except:", "is set, the API will only return the unique values in each dimension", "of String, parameter \"convert_to_string\" of type \"boolean\", parameter \"unique_values\" of type \"boolean\" :returns:", "parameter \"dimension_labels\" of mapping from String to type \"Values\" (@optional object_refs oterm_refs int_values", "Long :returns: instance of type \"ListGenericObjectsResult\" -> structure: parameter \"object_ids\" of list of", "\"ImportCSVParams\" -> structure: parameter \"file\" of type \"File\" (Import a CSV file into", "import print_function # the following is a hack to get the baseclient to", "of list of type \"boolean\", parameter \"string_values\" of list of String \"\"\" return", "values per series. The number of series depends on the number of variable", "_BaseClient # @Reimport class GenericsUtil(object): def __init__( self, url=None, timeout=30 * 60, user_id=None,", "- limits to generics with max number of dimensions limit_mapped - if 0", "metadata describing the dimensions of one or more generic objects) -> structure: parameter", "instance of type \"ImportResult\" -> structure: parameter \"object_ref\" of String \"\"\" return self._client.call_method(", "instance of type \"GetGenericDimensionLabelsResult\" -> structure: parameter \"dimension_labels\" of mapping from String to", "\"usermeta\" are common to all import methods.) -> structure: parameter \"path\" of String,", "of unique labels for that dimension index. returns: series_labels will show which variable", "umapped objects) -> structure: parameter \"workspace_names\" of list of String, parameter \"allowed_object_types\" of", "X and Y data are null are removed.) -> structure: parameter \"object_id\" of", "an OBO file into an OntologyDictionary) -> structure: parameter \"file\" of type \"File\"", "for that dimension index. returns: series_labels will show which variable index values correspond", ":param params: instance of type \"ExportParams\" (Exporter for generic objects as CSV files)", "or more workspaces optional parameters: allowed_object_types - limits to specific types of object,", "of object, e.g., KBaseGenerics.NDArray (version number is optional) allowed_data_types - limits to specific", "microbial growth allowed_scalar_types - limits to specific scalar types, e.g., object_ref, int, float", "max_dimensions - limits to generics with max number of dimensions limit_mapped - if", "not. This makes pep8 unhappy hence the annotations. try: # baseclient and this", "min_dimensions - limits to generics with minimum number of dimensions max_dimensions - limits", "all objects. if 1, returns only mapped objects. if 2, returns only umapped", "of type \"GetGenericMetadataParams\" (Get metadata describing the dimensions of one or more generic", "of type \"oterm_ref\", parameter \"int_values\" of list of Long, parameter \"float_values\" of list", "\"string_values\" of list of String, parameter \"values_y\" of list of type \"Values\" (@optional", "values in each context of each dimension (e.g., \"int\")) -> structure: parameter \"object_type\"", "to which series values_x will contain 1 list of of x-axis values per", "list of String \"\"\" return self._client.call_method( 'GenericsUtil.get_generic_dimension_labels', [params], self._service_ver, context) def get_generic_data(self, params,", "self._service_ver, context) def import_obo(self, params, context=None): \"\"\" :param params: instance of type \"ImportOBOParams\"", "optional parameters: allowed_object_types - limits to specific types of object, e.g., KBaseGenerics.NDArray (version", "- limits to specific scalar types, e.g., object_ref, int, float (see KBaseGenerics.spec for", "strings. If unique_values is set, the API will only return the unique values", "'GenericsUtil.export_csv', [params], self._service_ver, context) def list_generic_objects(self, params, context=None): \"\"\" :param params: instance of", "methods.) -> structure: parameter \"path\" of String, parameter \"shock_id\" of String, parameter \"workspace_name\"", "to get the baseclient to import whether we're in a # package or", "object: object_type - e.g., KBaseGenerics.HNDArray‑4.0 data_type - e.g., microbial growth n_dimensions - number", "of list of String, parameter \"dimension_sizes\" of list of Long, parameter \"has_unique_subindices\" of", "\"limit_mapped\" of Long :returns: instance of type \"ListGenericObjectsResult\" -> structure: parameter \"object_ids\" of", "types, e.g., microbial growth allowed_scalar_types - limits to specific scalar types, e.g., object_ref,", "@UnusedImport except: # no they aren't from baseclient import BaseClient as _BaseClient #", "url is required') self._service_ver = None self._client = _BaseClient( url, timeout=timeout, user_id=user_id, password=password,", "2nd dimension, 1st data type), and an optional flag, convert_to_string. The API will", "context=None): \"\"\" :param params: instance of type \"ExportParams\" (Exporter for generic objects as", "objects. if 1, returns only mapped objects. if 2, returns only umapped objects)", "trust_all_ssl_certificates=False, auth_svc='https://kbase.us/services/authorization/Sessions/Login'): if url is None: raise ValueError('A url is required') self._service_ver =", "\"allowed_data_types\" of list of String, parameter \"allowed_scalar_types\" of list of String, parameter \"min_dimensions\"", "list of Long, parameter \"float_values\" of list of Double, parameter \"boolean_values\" of list", "# @UnusedImport except: # no they aren't from baseclient import BaseClient as _BaseClient", "String, parameter \"workspace_name\" of String, parameter \"object_name\" of String, parameter \"object_type\" of String,", "must be X axis; additional variables will lead to additional series being returned).", "a string describing each dimension (e.g., \"media name\") dimension_sizes - size (length) of", "# the following is a hack to get the baseclient to import whether", "__init__( self, url=None, timeout=30 * 60, user_id=None, password=<PASSWORD>, token=<PASSWORD>, ignore_authrc=False, trust_all_ssl_certificates=False, auth_svc='https://kbase.us/services/authorization/Sessions/Login'): if", "of String, parameter \"min_dimensions\" of Long, parameter \"max_dimensions\" of Long, parameter \"limit_mapped\" of", "with max number of dimensions limit_mapped - if 0 (or unset) returns all", "of type \"boolean\", parameter \"value_types\" of list of String, parameter \"scalar_types\" of list", "selects which dimension indices to fix to particular constants. This can be done", "of list of String \"\"\" return self._client.call_method( 'GenericsUtil.get_generic_metadata', [params], self._service_ver, context) def get_generic_dimension_labels(self,", "String \"\"\" return self._client.call_method( 'GenericsUtil.import_csv', [params], self._service_ver, context) def import_obo(self, params, context=None): \"\"\"", "for a generic object. User will pass in the numeric indices of all", "will mean 1st dimension, 1st data type, 2/1 = 2nd dimension, 1st data", "hence the annotations. try: # baseclient and this client are in a package", "value_types - list of value types in the object (there will only be", "of String, parameter \"variable_dimension_ids\" of list of String, parameter \"constant_dimension_ids\" of mapping from", "indices to a Values object. The Values will either contain the scalar type", "of list of String \"\"\" return self._client.call_method( 'GenericsUtil.get_generic_dimension_labels', [params], self._service_ver, context) def get_generic_data(self,", "self._service_ver, context) def list_generic_objects(self, params, context=None): \"\"\" :param params: instance of type \"ListGenericObjectsParams\"", "\"GetGenericDataParams\" (gets subset of generic data as a 2D matrix Users passes in", "mapping from String to type \"GenericMetadata\" (Basic metadata about an object: object_type -", "variables will lead to additional series being returned). User selects which dimension indices", "for the 3rd type of values in the 2nd dimension) to an index", "limits to specific scalar types, e.g., object_ref, int, float (see KBaseGenerics.spec for valid", "with metadata) -> structure: parameter \"object_info\" of mapping from String to type \"GenericMetadata\"", "parameter \"variable_dimension_ids\" of list of String, parameter \"constant_dimension_ids\" of mapping from String to", "OBO file into an OntologyDictionary) -> structure: parameter \"file\" of type \"File\" (Import", "of dimensions is_mapped - 0 or 1 indicating mapped status value_types - list", "to import whether we're in a # package or not. This makes pep8", "type \"boolean\", parameter \"unique_values\" of type \"boolean\" :returns: instance of type \"GetGenericDimensionLabelsResult\" ->", "the 3rd type of values in the 2nd dimension) to an index in", "ids to structure with metadata) -> structure: parameter \"object_info\" of mapping from String", "BaseClient as _BaseClient # @Reimport class GenericsUtil(object): def __init__( self, url=None, timeout=30 *", "(maps object ids to structure with metadata) -> structure: parameter \"object_info\" of mapping", "flag is set, will convert the scalar type to strings. If unique_values is", "\"min_dimensions\" of Long, parameter \"max_dimensions\" of Long, parameter \"limit_mapped\" of Long :returns: instance", "of the dimension indices to a Values object. The Values will either contain", "HNDArrays must have at least one dimension that passes. min_dimensions - limits to", "(these will also be re-indexed, but not resorted, so the Values array may", "data type), and an optional flag, convert_to_string. The API will return a hash", "of type \"GetGenericMetadataResult\" (maps object ids to structure with metadata) -> structure: parameter", "\"shock_id\" of String, parameter \"workspace_name\" of String, parameter \"object_name\" of String, parameter \"metadata\"", "the object (there will only be 1 for NDArray objects), e.g., \"specific activity\"", "token=<PASSWORD>, ignore_authrc=False, trust_all_ssl_certificates=False, auth_svc='https://kbase.us/services/authorization/Sessions/Login'): if url is None: raise ValueError('A url is required')", "an entire dimension (e.g., \"2\" for the 2nd dimension) to an index in", "parameter \"values_x\" of list of type \"Values\" (@optional object_refs oterm_refs int_values float_values string_values", "(length) of each dimension dimension_value_types - a string describing each context of each", "(List generic objects in one or more workspaces optional parameters: allowed_object_types - limits", "parameter \"dimension_types\" of list of String, parameter \"dimension_sizes\" of list of Long, parameter", "the scalar type to strings. If unique_values is set, the API will only", "\"\"\" :param params: instance of type \"ImportOBOParams\" (Import an OBO file into an", "this client are in a package from .baseclient import BaseClient as _BaseClient #", "objects as CSV files) -> structure: parameter \"input_ref\" of String :returns: instance of", "one or more workspaces optional parameters: allowed_object_types - limits to specific types of", "self._client.call_method( 'GenericsUtil.list_generic_objects', [params], self._service_ver, context) def get_generic_metadata(self, params, context=None): \"\"\" :param params: instance", "\"object_type\" of String, parameter \"data_type\" of String, parameter \"n_dimensions\" of Long, parameter \"is_mapped\"", "\"scalar_types\" of list of String, parameter \"dimension_types\" of list of String, parameter \"dimension_sizes\"", "\"object_type\" of String, parameter \"metadata\" of type \"usermeta\" -> mapping from String to", "return a hash mapping each of the dimension indices to a Values object.", "index (e.g., \"2/3\" for the 3rd type of values in the 2nd dimension)", "In each series, values where either the X and Y data are null", "which series values_x will contain 1 list of of x-axis values per series.", "n_dimensions - number of dimensions is_mapped - 0 or 1 indicating mapped status", "of type \"GetGenericDataResult\" -> structure: parameter \"series_labels\" of list of String, parameter \"values_x\"", "context) def import_obo(self, params, context=None): \"\"\" :param params: instance of type \"ImportOBOParams\" (Import", "of Long, parameter \"limit_mapped\" of Long :returns: instance of type \"ListGenericObjectsResult\" -> structure:", "in the object (there will only be 1 for NDArray objects), e.g., \"float\"", "context=None): \"\"\" :param params: instance of type \"ImportOBOParams\" (Import an OBO file into", "metadata about an object: object_type - e.g., KBaseGenerics.HNDArray‑4.0 data_type - e.g., microbial growth", "axes for a generic object. User will pass in the numeric indices of", "in the dimension indices to use as variables (1st one must be X", "# # Autogenerated by the KBase type compiler - # any changes made", "mapping from String to type \"Values\" (@optional object_refs oterm_refs int_values float_values string_values boolean_values)", "to particular constants. This can be done one of two ways: either by", ":param params: instance of type \"GetGenericMetadataParams\" (Get metadata describing the dimensions of one", "KBaseGenerics.spec for valid types). HNDArrays must have at least one dimension that passes.", "contain the scalar type in the original format, or if the convert_to_string flag", "params, context=None): \"\"\" :param params: instance of type \"ListGenericObjectsParams\" (List generic objects in", "type \"boolean\", parameter \"string_values\" of list of String, parameter \"values_y\" of list of", "parameter \"object_ref\" of String \"\"\" return self._client.call_method( 'GenericsUtil.import_csv', [params], self._service_ver, context) def import_obo(self,", "context=None): \"\"\" :param params: instance of type \"ImportCSVParams\" -> structure: parameter \"file\" of", "parameter \"object_id\" of String, parameter \"dimension_ids\" of list of String, parameter \"convert_to_string\" of", "\"File\" (Import a CSV file into a NDArray or HNDArray. \"File\" and \"usermeta\"", "\"ExportParams\" (Exporter for generic objects as CSV files) -> structure: parameter \"input_ref\" of", "length).) -> structure: parameter \"object_id\" of String, parameter \"dimension_ids\" of list of String,", "\"boolean_values\" of list of type \"boolean\", parameter \"string_values\" of list of String \"\"\"", "show which variable index values correspond to which series values_x will contain 1", "String, parameter \"allowed_data_types\" of list of String, parameter \"allowed_scalar_types\" of list of String,", "series_labels will show which variable index values correspond to which series values_x will", "parameter \"object_ids\" of list of String :returns: instance of type \"GetGenericMetadataResult\" (maps object", "def __init__( self, url=None, timeout=30 * 60, user_id=None, password=<PASSWORD>, token=<PASSWORD>, ignore_authrc=False, trust_all_ssl_certificates=False, auth_svc='https://kbase.us/services/authorization/Sessions/Login'):", "-> structure: parameter \"object_info\" of mapping from String to type \"GenericMetadata\" (Basic metadata", "of two ways: either by fixing an entire dimension (e.g., \"2\" for the", "\"\"\" return self._client.call_method( 'GenericsUtil.list_generic_objects', [params], self._service_ver, context) def get_generic_metadata(self, params, context=None): \"\"\" :param", "of String :returns: instance of type \"GetGenericMetadataResult\" (maps object ids to structure with", "context) def get_generic_metadata(self, params, context=None): \"\"\" :param params: instance of type \"GetGenericMetadataParams\" (Get", "limit_mapped - if 0 (or unset) returns all objects. if 1, returns only", "type \"boolean\", parameter \"string_values\" of list of String \"\"\" return self._client.call_method( 'GenericsUtil.get_generic_dimension_labels', [params],", "\"dimension_value_types\" of list of list of String, parameter \"dimension_scalar_types\" of list of list", "either contain the scalar type in the original format, or if the convert_to_string", "type in the original format, or if the convert_to_string flag is set, will", "only mapped objects. if 2, returns only umapped objects) -> structure: parameter \"workspace_names\"", "indicating mapped status value_types - list of value types in the object (there", "of type \"boolean\" :returns: instance of type \"GetGenericDimensionLabelsResult\" -> structure: parameter \"dimension_labels\" of", "required') self._service_ver = None self._client = _BaseClient( url, timeout=timeout, user_id=user_id, password=password, token=token, ignore_authrc=ignore_authrc,", "as a 2D matrix Users passes in the dimension indices to use as", "is set, will convert the scalar type to strings. If unique_values is set,", "\"boolean\", parameter \"string_values\" of list of String, parameter \"values_y\" of list of type", "values_x will contain 1 list of of x-axis values per series. The number", "to String :returns: instance of type \"ImportResult\" -> structure: parameter \"object_ref\" of String", "index in the list of unique labels for that dimension index. returns: series_labels", "2/1 = 2nd dimension, 1st data type), and an optional flag, convert_to_string. The", "\"allowed_scalar_types\" of list of String, parameter \"min_dimensions\" of Long, parameter \"max_dimensions\" of Long,", ":returns: instance of type \"GetGenericMetadataResult\" (maps object ids to structure with metadata) ->", "type \"boolean\", parameter \"value_types\" of list of String, parameter \"scalar_types\" of list of", "of type \"File\" (Import a CSV file into a NDArray or HNDArray. \"File\"", "list of String, parameter \"scalar_types\" of list of String, parameter \"dimension_types\" of list", "-*- coding: utf-8 -*- ############################################################ # # Autogenerated by the KBase type compiler", "to Long :returns: instance of type \"GetGenericDataResult\" -> structure: parameter \"series_labels\" of list", "Long :returns: instance of type \"GetGenericDataResult\" -> structure: parameter \"series_labels\" of list of", "\"specific activity\" scalar_types - list of scalar types in the object (there will", "of list of list of String \"\"\" return self._client.call_method( 'GenericsUtil.get_generic_metadata', [params], self._service_ver, context)", "of type \"ListGenericObjectsResult\" -> structure: parameter \"object_ids\" of list of String \"\"\" return", "- size (length) of each dimension dimension_value_types - a string describing each context", "correspond to which series values_x will contain 1 list of of x-axis values", "import methods.) -> structure: parameter \"path\" of String, parameter \"shock_id\" of String, parameter", "so the Values array may be a different length).) -> structure: parameter \"object_id\"", "context) def get_generic_data(self, params, context=None): \"\"\" :param params: instance of type \"GetGenericDataParams\" (gets", "type compiler - # any changes made here will be overwritten # ############################################################", "parameter \"workspace_name\" of String, parameter \"object_name\" of String, parameter \"object_type\" of String, parameter", "parameter \"shock_id\" of String \"\"\" return self._client.call_method( 'GenericsUtil.export_csv', [params], self._service_ver, context) def list_generic_objects(self,", "\"values_y\" of list of type \"Values\" (@optional object_refs oterm_refs int_values float_values string_values boolean_values)", "The API will return a hash mapping each of the dimension indices to", "unique values in each dimension (these will also be re-indexed, but not resorted,", "file into an OntologyDictionary) -> structure: parameter \"file\" of type \"File\" (Import a", "get_generic_data(self, params, context=None): \"\"\" :param params: instance of type \"GetGenericDataParams\" (gets subset of", "\"\"\" :param params: instance of type \"GetGenericDataParams\" (gets subset of generic data as", "is a hack to get the baseclient to import whether we're in a", "data types, e.g., microbial growth allowed_scalar_types - limits to specific scalar types, e.g.,", "package or not. This makes pep8 unhappy hence the annotations. try: # baseclient", "the dimensions of one or more generic objects) -> structure: parameter \"object_ids\" of", "self._service_ver, context) def get_generic_data(self, params, context=None): \"\"\" :param params: instance of type \"GetGenericDataParams\"", "# -*- coding: utf-8 -*- ############################################################ # # Autogenerated by the KBase type", "String, parameter \"dimension_ids\" of list of String, parameter \"convert_to_string\" of type \"boolean\", parameter", "-> structure: parameter \"object_ids\" of list of String \"\"\" return self._client.call_method( 'GenericsUtil.list_generic_objects', [params],", "numeric indices of all dimensions they care about (e.g., 1/1 will mean 1st", "series depends on the number of variable dimensions. In each series, values where", "of list of type \"boolean\", parameter \"string_values\" of list of String, parameter \"values_y\"", "of list of String :returns: instance of type \"GetGenericMetadataResult\" (maps object ids to", "from String to String :returns: instance of type \"ImportResult\" -> structure: parameter \"object_ref\"", "list of list of String \"\"\" return self._client.call_method( 'GenericsUtil.get_generic_metadata', [params], self._service_ver, context) def", "- type of values in each context of each dimension (e.g., \"int\")) ->", "list of type \"Values\" (@optional object_refs oterm_refs int_values float_values string_values boolean_values) -> structure:", "# any changes made here will be overwritten # ############################################################ from __future__ import", "\"n_dimensions\" of Long, parameter \"is_mapped\" of type \"boolean\", parameter \"value_types\" of list of", "a hack to get the baseclient to import whether we're in a #", "to specific scalar types, e.g., object_ref, int, float (see KBaseGenerics.spec for valid types).", "format, or if the convert_to_string flag is set, will convert the scalar type", "\"float_values\" of list of Double, parameter \"boolean_values\" of list of type \"boolean\", parameter", "return self._client.call_method( 'GenericsUtil.export_csv', [params], self._service_ver, context) def list_generic_objects(self, params, context=None): \"\"\" :param params:", "parameter \"series_labels\" of list of String, parameter \"values_x\" of list of type \"Values\"", "of generic data as a 2D matrix Users passes in the dimension indices", "\"GetGenericMetadataParams\" (Get metadata describing the dimensions of one or more generic objects) ->", "list of String :returns: instance of type \"GetGenericMetadataResult\" (maps object ids to structure", "NDArray objects), e.g., \"float\" dimension_types - a string describing each dimension (e.g., \"media", "use as variables (1st one must be X axis; additional variables will lead", "list of String, parameter \"values_y\" of list of type \"Values\" (@optional object_refs oterm_refs", "as _BaseClient # @UnusedImport except: # no they aren't from baseclient import BaseClient", "values in the 2nd dimension) to an index in the list of unique", "-> structure: parameter \"object_id\" of String, parameter \"dimension_ids\" of list of String, parameter", "type \"ExportParams\" (Exporter for generic objects as CSV files) -> structure: parameter \"input_ref\"", "only be 1 for NDArray objects), e.g., \"specific activity\" scalar_types - list of", "will show which variable index values correspond to which series values_x will contain", "returns: series_labels will show which variable index values correspond to which series values_x", "optional) allowed_data_types - limits to specific data types, e.g., microbial growth allowed_scalar_types -", "- number of dimensions is_mapped - 0 or 1 indicating mapped status value_types", "url is None: raise ValueError('A url is required') self._service_ver = None self._client =", "null are removed.) -> structure: parameter \"object_id\" of String, parameter \"variable_dimension_ids\" of list", "more generic objects) -> structure: parameter \"object_ids\" of list of String :returns: instance", "from baseclient import BaseClient as _BaseClient # @Reimport class GenericsUtil(object): def __init__( self,", "context) def export_csv(self, params, context=None): \"\"\" :param params: instance of type \"ExportParams\" (Exporter", "returned). User selects which dimension indices to fix to particular constants. This can", "trust_all_ssl_certificates=trust_all_ssl_certificates, auth_svc=auth_svc) def import_csv(self, params, context=None): \"\"\" :param params: instance of type \"ImportCSVParams\"", "will pass in the numeric indices of all dimensions they care about (e.g.,", "The number of series depends on the number of variable dimensions. values_y will", "\"boolean\", parameter \"unique_values\" of type \"boolean\" :returns: instance of type \"GetGenericDimensionLabelsResult\" -> structure:", "'GenericsUtil.list_generic_objects', [params], self._service_ver, context) def get_generic_metadata(self, params, context=None): \"\"\" :param params: instance of", "String, parameter \"shock_id\" of String, parameter \"workspace_name\" of String, parameter \"object_name\" of String,", "import BaseClient as _BaseClient # @Reimport class GenericsUtil(object): def __init__( self, url=None, timeout=30", "parameter \"dimension_sizes\" of list of Long, parameter \"has_unique_subindices\" of list of type \"boolean\",", "if 1, returns only mapped objects. if 2, returns only umapped objects) ->", "dimensions limit_mapped - if 0 (or unset) returns all objects. if 1, returns", "type \"ImportResult\" -> structure: parameter \"object_ref\" of String \"\"\" return self._client.call_method( 'GenericsUtil.import_csv', [params],", "except: # no they aren't from baseclient import BaseClient as _BaseClient # @Reimport", "be X axis; additional variables will lead to additional series being returned). User", "by fixing an entire dimension (e.g., \"2\" for the 2nd dimension) to an", "name\") dimension_scalar_types - type of values in each context of each dimension (e.g.,", "of String, parameter \"data_type\" of String, parameter \"n_dimensions\" of Long, parameter \"is_mapped\" of", "to specific data types, e.g., microbial growth allowed_scalar_types - limits to specific scalar", "- 0 or 1 indicating mapped status value_types - list of value types", "of list of String, parameter \"dimension_types\" of list of String, parameter \"dimension_sizes\" of", "\"dimension_scalar_types\" of list of list of String \"\"\" return self._client.call_method( 'GenericsUtil.get_generic_metadata', [params], self._service_ver,", "the convert_to_string flag is set, will convert the scalar type to strings. If", "list of String \"\"\" return self._client.call_method( 'GenericsUtil.get_generic_metadata', [params], self._service_ver, context) def get_generic_dimension_labels(self, params,", "only return the unique values in each dimension (these will also be re-indexed,", "list of String, parameter \"min_dimensions\" of Long, parameter \"max_dimensions\" of Long, parameter \"limit_mapped\"", "\"object_ref\" of String \"\"\" return self._client.call_method( 'GenericsUtil.import_csv', [params], self._service_ver, context) def import_obo(self, params,", "of list of type \"object_ref\", parameter \"oterm_refs\" of list of type \"oterm_ref\", parameter", "string describing each dimension (e.g., \"media name\") dimension_sizes - size (length) of each", "url=None, timeout=30 * 60, user_id=None, password=<PASSWORD>, token=<PASSWORD>, ignore_authrc=False, trust_all_ssl_certificates=False, auth_svc='https://kbase.us/services/authorization/Sessions/Login'): if url is", "# Autogenerated by the KBase type compiler - # any changes made here", "of of x-axis values per series. The number of series depends on the", "parameter \"allowed_object_types\" of list of String, parameter \"allowed_data_types\" of list of String, parameter", "e.g., KBaseGenerics.NDArray (version number is optional) allowed_data_types - limits to specific data types,", "String, parameter \"values_x\" of list of type \"Values\" (@optional object_refs oterm_refs int_values float_values", "describing each context of each dimension (e.g., \"media name\") dimension_scalar_types - type of", "return self._client.call_method( 'GenericsUtil.get_generic_metadata', [params], self._service_ver, context) def get_generic_dimension_labels(self, params, context=None): \"\"\" :param params:", "get the baseclient to import whether we're in a # package or not.", "mapping each of the dimension indices to a Values object. The Values will", "parameter \"string_values\" of list of String \"\"\" return self._client.call_method( 'GenericsUtil.get_generic_dimension_labels', [params], self._service_ver, context)", "generics with minimum number of dimensions max_dimensions - limits to generics with max", "unique_values is set, the API will only return the unique values in each", "type \"oterm_ref\", parameter \"int_values\" of list of Long, parameter \"float_values\" of list of", ":returns: instance of type \"ExportResult\" -> structure: parameter \"shock_id\" of String \"\"\" return", "either by fixing an entire dimension (e.g., \"2\" for the 2nd dimension) to", "url, timeout=timeout, user_id=user_id, password=password, token=token, ignore_authrc=ignore_authrc, trust_all_ssl_certificates=trust_all_ssl_certificates, auth_svc=auth_svc) def import_csv(self, params, context=None): \"\"\"", "\"\"\" :param params: instance of type \"ExportParams\" (Exporter for generic objects as CSV", "list of unique labels for that dimension index. returns: series_labels will show which", "type \"ListGenericObjectsResult\" -> structure: parameter \"object_ids\" of list of String \"\"\" return self._client.call_method(", "passes. min_dimensions - limits to generics with minimum number of dimensions max_dimensions -", "class GenericsUtil(object): def __init__( self, url=None, timeout=30 * 60, user_id=None, password=<PASSWORD>, token=<PASSWORD>, ignore_authrc=False,", "\"dimension_labels\" of mapping from String to type \"Values\" (@optional object_refs oterm_refs int_values float_values", "of list of String, parameter \"convert_to_string\" of type \"boolean\", parameter \"unique_values\" of type", "@Reimport class GenericsUtil(object): def __init__( self, url=None, timeout=30 * 60, user_id=None, password=<PASSWORD>, token=<PASSWORD>,", "any changes made here will be overwritten # ############################################################ from __future__ import print_function", "limits to generics with max number of dimensions limit_mapped - if 0 (or", "parameter \"is_mapped\" of type \"boolean\", parameter \"value_types\" of list of String, parameter \"scalar_types\"", "types of object, e.g., KBaseGenerics.NDArray (version number is optional) allowed_data_types - limits to", "User will pass in the numeric indices of all dimensions they care about", "of String, parameter \"constant_dimension_ids\" of mapping from String to Long :returns: instance of", "a NDArray or HNDArray. \"File\" and \"usermeta\" are common to all import methods.)", "one of two ways: either by fixing an entire dimension (e.g., \"2\" for", "parameter \"string_values\" of list of String \"\"\" return self._client.call_method( 'GenericsUtil.get_generic_data', [params], self._service_ver, context)", "If unique_values is set, the API will only return the unique values in", "being returned). User selects which dimension indices to fix to particular constants. This", "# @Reimport class GenericsUtil(object): def __init__( self, url=None, timeout=30 * 60, user_id=None, password=<PASSWORD>,", "\"File\" and \"usermeta\" are common to all import methods.) -> structure: parameter \"path\"", "# package or not. This makes pep8 unhappy hence the annotations. try: #", "(e.g., \"media name\") dimension_scalar_types - type of values in each context of each", "\"constant_dimension_ids\" of mapping from String to Long :returns: instance of type \"GetGenericDataResult\" ->", "\"value_types\" of list of String, parameter \"scalar_types\" of list of String, parameter \"dimension_types\"", "of list of String, parameter \"dimension_scalar_types\" of list of list of String \"\"\"", "KBaseGenerics.NDArray (version number is optional) allowed_data_types - limits to specific data types, e.g.,", "1/1 will mean 1st dimension, 1st data type, 2/1 = 2nd dimension, 1st", "will be overwritten # ############################################################ from __future__ import print_function # the following is", "Long, parameter \"is_mapped\" of type \"boolean\", parameter \"value_types\" of list of String, parameter", "of list of Long, parameter \"has_unique_subindices\" of list of type \"boolean\", parameter \"dimension_value_types\"", "of all dimensions they care about (e.g., 1/1 will mean 1st dimension, 1st", "of type \"ExportResult\" -> structure: parameter \"shock_id\" of String \"\"\" return self._client.call_method( 'GenericsUtil.export_csv',", "index values correspond to which series values_x will contain 1 list of of", "-*- ############################################################ # # Autogenerated by the KBase type compiler - # any", "to all import methods.) -> structure: parameter \"path\" of String, parameter \"shock_id\" of", "params: instance of type \"ImportCSVParams\" -> structure: parameter \"file\" of type \"File\" (Import", "\"\"\" return self._client.call_method( 'GenericsUtil.get_generic_metadata', [params], self._service_ver, context) def get_generic_dimension_labels(self, params, context=None): \"\"\" :param", "or HNDArray. \"File\" and \"usermeta\" are common to all import methods.) -> structure:", "allowed_object_types - limits to specific types of object, e.g., KBaseGenerics.NDArray (version number is", "of list of String \"\"\" return self._client.call_method( 'GenericsUtil.list_generic_objects', [params], self._service_ver, context) def get_generic_metadata(self,", "Long, parameter \"max_dimensions\" of Long, parameter \"limit_mapped\" of Long :returns: instance of type", "parameter \"path\" of String, parameter \"shock_id\" of String, parameter \"workspace_name\" of String, parameter", "\"GetGenericDataResult\" -> structure: parameter \"series_labels\" of list of String, parameter \"values_x\" of list", "parameter \"allowed_scalar_types\" of list of String, parameter \"min_dimensions\" of Long, parameter \"max_dimensions\" of", "object_ref, int, float (see KBaseGenerics.spec for valid types). HNDArrays must have at least", "the list of unique labels for that dimension index. returns: series_labels will show", "-> structure: parameter \"object_type\" of String, parameter \"data_type\" of String, parameter \"n_dimensions\" of", "and this client are in a package from .baseclient import BaseClient as _BaseClient", "will convert the scalar type to strings. If unique_values is set, the API", "\"ImportOBOParams\" (Import an OBO file into an OntologyDictionary) -> structure: parameter \"file\" of", "structure: parameter \"path\" of String, parameter \"shock_id\" of String, parameter \"workspace_name\" of String,", "String :returns: instance of type \"ExportResult\" -> structure: parameter \"shock_id\" of String \"\"\"", "list of String, parameter \"dimension_sizes\" of list of Long, parameter \"has_unique_subindices\" of list", "Long, parameter \"float_values\" of list of Double, parameter \"boolean_values\" of list of type", "String, parameter \"scalar_types\" of list of String, parameter \"dimension_types\" of list of String,", "[params], self._service_ver, context) def get_generic_data(self, params, context=None): \"\"\" :param params: instance of type", "- limits to specific types of object, e.g., KBaseGenerics.NDArray (version number is optional)", "will only return the unique values in each dimension (these will also be", "list of labels, or by fixing a dimension index (e.g., \"2/3\" for the", "series. The number of series depends on the number of variable dimensions. In", "removed.) -> structure: parameter \"object_id\" of String, parameter \"variable_dimension_ids\" of list of String,", "[params], self._service_ver, context) def import_obo(self, params, context=None): \"\"\" :param params: instance of type", "returns only umapped objects) -> structure: parameter \"workspace_names\" of list of String, parameter", "list of value types in the object (there will only be 1 for", "self._service_ver = None self._client = _BaseClient( url, timeout=timeout, user_id=user_id, password=password, token=token, ignore_authrc=ignore_authrc, trust_all_ssl_certificates=trust_all_ssl_certificates,", "and \"usermeta\" are common to all import methods.) -> structure: parameter \"path\" of", "returns only mapped objects. if 2, returns only umapped objects) -> structure: parameter", "\"\"\" return self._client.call_method( 'GenericsUtil.get_generic_dimension_labels', [params], self._service_ver, context) def get_generic_data(self, params, context=None): \"\"\" :param", "generic objects) -> structure: parameter \"object_ids\" of list of String :returns: instance of", "NDArray or HNDArray. \"File\" and \"usermeta\" are common to all import methods.) ->", "indices to use as variables (1st one must be X axis; additional variables", "- if 0 (or unset) returns all objects. if 1, returns only mapped", "hack to get the baseclient to import whether we're in a # package", "\"GetGenericMetadataResult\" (maps object ids to structure with metadata) -> structure: parameter \"object_info\" of", "of String, parameter \"object_type\" of String, parameter \"metadata\" of type \"usermeta\" -> mapping", "\"allowed_object_types\" of list of String, parameter \"allowed_data_types\" of list of String, parameter \"allowed_scalar_types\"", "structure: parameter \"object_info\" of mapping from String to type \"GenericMetadata\" (Basic metadata about", "- e.g., KBaseGenerics.HNDArray‑4.0 data_type - e.g., microbial growth n_dimensions - number of dimensions", "scalar type to strings. If unique_values is set, the API will only return", "-> structure: parameter \"scalar_type\" of type \"data_type\", parameter \"object_refs\" of list of type", "dimension indices to fix to particular constants. This can be done one of", "index. returns: series_labels will show which variable index values correspond to which series", "String, parameter \"object_name\" of String, parameter \"object_type\" of String, parameter \"metadata\" of type", "specific data types, e.g., microbial growth allowed_scalar_types - limits to specific scalar types,", "parameter \"allowed_data_types\" of list of String, parameter \"allowed_scalar_types\" of list of String, parameter", "# no they aren't from baseclient import BaseClient as _BaseClient # @Reimport class", "instance of type \"GetGenericDimensionLabelsParams\" (gets labels for list of dimension axes for a", "string_values boolean_values) -> structure: parameter \"scalar_type\" of type \"data_type\", parameter \"object_refs\" of list", "array may be a different length).) -> structure: parameter \"object_id\" of String, parameter", "of list of type \"Values\" (@optional object_refs oterm_refs int_values float_values string_values boolean_values) ->", "\"GetGenericDimensionLabelsParams\" (gets labels for list of dimension axes for a generic object. User", "the 2nd dimension) to an index in the complete list of labels, or", "String :returns: instance of type \"GetGenericMetadataResult\" (maps object ids to structure with metadata)", "here will be overwritten # ############################################################ from __future__ import print_function # the following", "String, parameter \"dimension_sizes\" of list of Long, parameter \"has_unique_subindices\" of list of type", "def get_generic_data(self, params, context=None): \"\"\" :param params: instance of type \"GetGenericDataParams\" (gets subset", "\"series_labels\" of list of String, parameter \"values_x\" of list of type \"Values\" (@optional", "list of String, parameter \"constant_dimension_ids\" of mapping from String to Long :returns: instance", "\"usermeta\" -> mapping from String to String :returns: instance of type \"ImportResult\" ->", "\"\"\" :param params: instance of type \"GetGenericDimensionLabelsParams\" (gets labels for list of dimension", "passes in the dimension indices to use as variables (1st one must be", "of of y-axis values per series. The number of series depends on the", "params, context=None): \"\"\" :param params: instance of type \"ExportParams\" (Exporter for generic objects", "dimensions of one or more generic objects) -> structure: parameter \"object_ids\" of list", "objects) -> structure: parameter \"object_ids\" of list of String :returns: instance of type", "from String to type \"GenericMetadata\" (Basic metadata about an object: object_type - e.g.,", "-> mapping from String to String :returns: instance of type \"ImportResult\" -> structure:", "(see KBaseGenerics.spec for valid types). HNDArrays must have at least one dimension that", "or not. This makes pep8 unhappy hence the annotations. try: # baseclient and", "each context of each dimension (e.g., \"media name\") dimension_scalar_types - type of values", "1st data type, 2/1 = 2nd dimension, 1st data type), and an optional", "of type \"boolean\", parameter \"string_values\" of list of String \"\"\" return self._client.call_method( 'GenericsUtil.get_generic_data',", "a Values object. The Values will either contain the scalar type in the", "\"boolean\", parameter \"string_values\" of list of String \"\"\" return self._client.call_method( 'GenericsUtil.get_generic_data', [params], self._service_ver,", "flag, convert_to_string. The API will return a hash mapping each of the dimension", "String, parameter \"data_type\" of String, parameter \"n_dimensions\" of Long, parameter \"is_mapped\" of type", "\"string_values\" of list of String \"\"\" return self._client.call_method( 'GenericsUtil.get_generic_dimension_labels', [params], self._service_ver, context) def", "into a NDArray or HNDArray. \"File\" and \"usermeta\" are common to all import", "structure: parameter \"object_ids\" of list of String :returns: instance of type \"GetGenericMetadataResult\" (maps", "of value types in the object (there will only be 1 for NDArray", "None: raise ValueError('A url is required') self._service_ver = None self._client = _BaseClient( url,", "e.g., microbial growth n_dimensions - number of dimensions is_mapped - 0 or 1", "parameter \"oterm_refs\" of list of type \"oterm_ref\", parameter \"int_values\" of list of Long,", "per series. The number of series depends on the number of variable dimensions.", "self._client = _BaseClient( url, timeout=timeout, user_id=user_id, password=password, token=token, ignore_authrc=ignore_authrc, trust_all_ssl_certificates=trust_all_ssl_certificates, auth_svc=auth_svc) def import_csv(self,", "the KBase type compiler - # any changes made here will be overwritten", "from __future__ import print_function # the following is a hack to get the", "of list of String, parameter \"allowed_object_types\" of list of String, parameter \"allowed_data_types\" of", "\"data_type\", parameter \"object_refs\" of list of type \"object_ref\", parameter \"oterm_refs\" of list of", "of each dimension (e.g., \"media name\") dimension_scalar_types - type of values in each", "String, parameter \"variable_dimension_ids\" of list of String, parameter \"constant_dimension_ids\" of mapping from String", "\"\"\" :param params: instance of type \"ImportCSVParams\" -> structure: parameter \"file\" of type", "2nd dimension) to an index in the complete list of labels, or by", "of String, parameter \"workspace_name\" of String, parameter \"object_name\" of String, parameter \"object_type\" of", "def import_obo(self, params, context=None): \"\"\" :param params: instance of type \"ImportOBOParams\" (Import an", "(gets labels for list of dimension axes for a generic object. User will", "\"object_id\" of String, parameter \"dimension_ids\" of list of String, parameter \"convert_to_string\" of type", "of Long, parameter \"is_mapped\" of type \"boolean\", parameter \"value_types\" of list of String,", "String to Long :returns: instance of type \"GetGenericDataResult\" -> structure: parameter \"series_labels\" of", "generic objects in one or more workspaces optional parameters: allowed_object_types - limits to", "the scalar type in the original format, or if the convert_to_string flag is", "type to strings. If unique_values is set, the API will only return the", "parameter \"object_ref\" of String \"\"\" return self._client.call_method( 'GenericsUtil.import_obo', [params], self._service_ver, context) def export_csv(self,", "and Y data are null are removed.) -> structure: parameter \"object_id\" of String,", "- # any changes made here will be overwritten # ############################################################ from __future__", "(1st one must be X axis; additional variables will lead to additional series", "1 list of of y-axis values per series. The number of series depends", "context of each dimension (e.g., \"int\")) -> structure: parameter \"object_type\" of String, parameter", "\"shock_id\" of String, parameter \"workspace_name\" of String, parameter \"object_name\" of String, parameter \"object_type\"", "-> structure: parameter \"file\" of type \"File\" (Import a CSV file into a", "is optional) allowed_data_types - limits to specific data types, e.g., microbial growth allowed_scalar_types", "whether we're in a # package or not. This makes pep8 unhappy hence", "limits to specific types of object, e.g., KBaseGenerics.NDArray (version number is optional) allowed_data_types", "also be re-indexed, but not resorted, so the Values array may be a", "User selects which dimension indices to fix to particular constants. This can be", "* 60, user_id=None, password=<PASSWORD>, token=<PASSWORD>, ignore_authrc=False, trust_all_ssl_certificates=False, auth_svc='https://kbase.us/services/authorization/Sessions/Login'): if url is None: raise", "fixing a dimension index (e.g., \"2/3\" for the 3rd type of values in", "of String \"\"\" return self._client.call_method( 'GenericsUtil.get_generic_data', [params], self._service_ver, context) def status(self, context=None): return", "\"Values\" (@optional object_refs oterm_refs int_values float_values string_values boolean_values) -> structure: parameter \"scalar_type\" of", "dimensions. In each series, values where either the X and Y data are", "dimension_scalar_types - type of values in each context of each dimension (e.g., \"int\"))", "dimensions max_dimensions - limits to generics with max number of dimensions limit_mapped -", "of type \"data_type\", parameter \"object_refs\" of list of type \"object_ref\", parameter \"oterm_refs\" of", "to type \"GenericMetadata\" (Basic metadata about an object: object_type - e.g., KBaseGenerics.HNDArray‑4.0 data_type", "\"dimension_types\" of list of String, parameter \"dimension_sizes\" of list of Long, parameter \"has_unique_subindices\"", "will contain 1 list of of x-axis values per series. The number of", "of Long, parameter \"has_unique_subindices\" of list of type \"boolean\", parameter \"dimension_value_types\" of list", "raise ValueError('A url is required') self._service_ver = None self._client = _BaseClient( url, timeout=timeout,", "of type \"boolean\", parameter \"string_values\" of list of String \"\"\" return self._client.call_method( 'GenericsUtil.get_generic_dimension_labels',", "index in the complete list of labels, or by fixing a dimension index", "list of type \"object_ref\", parameter \"oterm_refs\" of list of type \"oterm_ref\", parameter \"int_values\"", "no they aren't from baseclient import BaseClient as _BaseClient # @Reimport class GenericsUtil(object):", "dimensions they care about (e.g., 1/1 will mean 1st dimension, 1st data type,", "__future__ import print_function # the following is a hack to get the baseclient", "import_csv(self, params, context=None): \"\"\" :param params: instance of type \"ImportCSVParams\" -> structure: parameter", "in one or more workspaces optional parameters: allowed_object_types - limits to specific types", "of mapping from String to type \"Values\" (@optional object_refs oterm_refs int_values float_values string_values", "either the X and Y data are null are removed.) -> structure: parameter", "in the list of unique labels for that dimension index. returns: series_labels will", "to generics with minimum number of dimensions max_dimensions - limits to generics with", "\"object_id\" of String, parameter \"variable_dimension_ids\" of list of String, parameter \"constant_dimension_ids\" of mapping", "of Long :returns: instance of type \"ListGenericObjectsResult\" -> structure: parameter \"object_ids\" of list", "series, values where either the X and Y data are null are removed.)", "return self._client.call_method( 'GenericsUtil.import_obo', [params], self._service_ver, context) def export_csv(self, params, context=None): \"\"\" :param params:", "float (see KBaseGenerics.spec for valid types). HNDArrays must have at least one dimension", "list of of x-axis values per series. The number of series depends on", "each of the dimension indices to a Values object. The Values will either", "of type \"usermeta\" -> mapping from String to String :returns: instance of type", "self._client.call_method( 'GenericsUtil.import_csv', [params], self._service_ver, context) def import_obo(self, params, context=None): \"\"\" :param params: instance", "mapped status value_types - list of value types in the object (there will", "password=password, token=token, ignore_authrc=ignore_authrc, trust_all_ssl_certificates=trust_all_ssl_certificates, auth_svc=auth_svc) def import_csv(self, params, context=None): \"\"\" :param params: instance", "coding: utf-8 -*- ############################################################ # # Autogenerated by the KBase type compiler -", "the following is a hack to get the baseclient to import whether we're", "growth allowed_scalar_types - limits to specific scalar types, e.g., object_ref, int, float (see", "indices to fix to particular constants. This can be done one of two", "(Import an OBO file into an OntologyDictionary) -> structure: parameter \"file\" of type", "dimension) to an index in the complete list of labels, or by fixing", "limits to generics with minimum number of dimensions max_dimensions - limits to generics", "(there will only be 1 for NDArray objects), e.g., \"float\" dimension_types - a", "of y-axis values per series. The number of series depends on the number", "convert_to_string. The API will return a hash mapping each of the dimension indices", "changes made here will be overwritten # ############################################################ from __future__ import print_function #", "type \"boolean\" :returns: instance of type \"GetGenericDimensionLabelsResult\" -> structure: parameter \"dimension_labels\" of mapping", "parameter \"value_types\" of list of String, parameter \"scalar_types\" of list of String, parameter", "of String, parameter \"allowed_object_types\" of list of String, parameter \"allowed_data_types\" of list of", "the API will only return the unique values in each dimension (these will", "list of String, parameter \"convert_to_string\" of type \"boolean\", parameter \"unique_values\" of type \"boolean\"", "String, parameter \"workspace_name\" of String, parameter \"object_name\" of String, parameter \"metadata\" of type", "timeout=timeout, user_id=user_id, password=password, token=token, ignore_authrc=ignore_authrc, trust_all_ssl_certificates=trust_all_ssl_certificates, auth_svc=auth_svc) def import_csv(self, params, context=None): \"\"\" :param", "CSV file into a NDArray or HNDArray. \"File\" and \"usermeta\" are common to", "type \"File\" (Import a CSV file into a NDArray or HNDArray. \"File\" and", "\"data_type\" of String, parameter \"n_dimensions\" of Long, parameter \"is_mapped\" of type \"boolean\", parameter", "of list of Double, parameter \"boolean_values\" of list of type \"boolean\", parameter \"string_values\"", "are null are removed.) -> structure: parameter \"object_id\" of String, parameter \"variable_dimension_ids\" of", "but not resorted, so the Values array may be a different length).) ->", "more workspaces optional parameters: allowed_object_types - limits to specific types of object, e.g.,", "will only be 1 for NDArray objects), e.g., \"float\" dimension_types - a string", "structure: parameter \"dimension_labels\" of mapping from String to type \"Values\" (@optional object_refs oterm_refs", "e.g., \"specific activity\" scalar_types - list of scalar types in the object (there", "scalar_types - list of scalar types in the object (there will only be", "size (length) of each dimension dimension_value_types - a string describing each context of", "parameter \"data_type\" of String, parameter \"n_dimensions\" of Long, parameter \"is_mapped\" of type \"boolean\",", "1 for NDArray objects), e.g., \"float\" dimension_types - a string describing each dimension", "############################################################ # # Autogenerated by the KBase type compiler - # any changes", "import BaseClient as _BaseClient # @UnusedImport except: # no they aren't from baseclient", "entire dimension (e.g., \"2\" for the 2nd dimension) to an index in the", "<reponame>jsfillman/GenericsUtil # -*- coding: utf-8 -*- ############################################################ # # Autogenerated by the KBase", "dimension (e.g., \"2\" for the 2nd dimension) to an index in the complete", "\"shock_id\" of String \"\"\" return self._client.call_method( 'GenericsUtil.export_csv', [params], self._service_ver, context) def list_generic_objects(self, params,", "ignore_authrc=ignore_authrc, trust_all_ssl_certificates=trust_all_ssl_certificates, auth_svc=auth_svc) def import_csv(self, params, context=None): \"\"\" :param params: instance of type", "the unique values in each dimension (these will also be re-indexed, but not", "x-axis values per series. The number of series depends on the number of", "of series depends on the number of variable dimensions. values_y will contain 1", "2nd dimension) to an index in the list of unique labels for that", "matrix Users passes in the dimension indices to use as variables (1st one", "\"\"\" :param params: instance of type \"GetGenericMetadataParams\" (Get metadata describing the dimensions of", "params: instance of type \"ImportOBOParams\" (Import an OBO file into an OntologyDictionary) ->", "(or unset) returns all objects. if 1, returns only mapped objects. if 2,", "_BaseClient( url, timeout=timeout, user_id=user_id, password=password, token=token, ignore_authrc=ignore_authrc, trust_all_ssl_certificates=trust_all_ssl_certificates, auth_svc=auth_svc) def import_csv(self, params, context=None):", "user_id=user_id, password=password, token=token, ignore_authrc=ignore_authrc, trust_all_ssl_certificates=trust_all_ssl_certificates, auth_svc=auth_svc) def import_csv(self, params, context=None): \"\"\" :param params:", "list of type \"boolean\", parameter \"dimension_value_types\" of list of list of String, parameter", "(e.g., 1/1 will mean 1st dimension, 1st data type, 2/1 = 2nd dimension,", "get_generic_metadata(self, params, context=None): \"\"\" :param params: instance of type \"GetGenericMetadataParams\" (Get metadata describing", "structure: parameter \"object_ref\" of String \"\"\" return self._client.call_method( 'GenericsUtil.import_csv', [params], self._service_ver, context) def", "convert_to_string flag is set, will convert the scalar type to strings. If unique_values", "parameter \"object_ids\" of list of String \"\"\" return self._client.call_method( 'GenericsUtil.list_generic_objects', [params], self._service_ver, context)", "generic data as a 2D matrix Users passes in the dimension indices to", "None self._client = _BaseClient( url, timeout=timeout, user_id=user_id, password=password, token=token, ignore_authrc=ignore_authrc, trust_all_ssl_certificates=trust_all_ssl_certificates, auth_svc=auth_svc) def", "to fix to particular constants. This can be done one of two ways:", "fixing an entire dimension (e.g., \"2\" for the 2nd dimension) to an index", "instance of type \"GetGenericMetadataParams\" (Get metadata describing the dimensions of one or more", "allowed_data_types - limits to specific data types, e.g., microbial growth allowed_scalar_types - limits", "def list_generic_objects(self, params, context=None): \"\"\" :param params: instance of type \"ListGenericObjectsParams\" (List generic", "objects) -> structure: parameter \"workspace_names\" of list of String, parameter \"allowed_object_types\" of list", "e.g., KBaseGenerics.HNDArray‑4.0 data_type - e.g., microbial growth n_dimensions - number of dimensions is_mapped", "String, parameter \"object_type\" of String, parameter \"metadata\" of type \"usermeta\" -> mapping from", "of String, parameter \"workspace_name\" of String, parameter \"object_name\" of String, parameter \"metadata\" of", "and an optional flag, convert_to_string. The API will return a hash mapping each", "depends on the number of variable dimensions. values_y will contain 1 list of", "of list of String, parameter \"constant_dimension_ids\" of mapping from String to Long :returns:", "\"has_unique_subindices\" of list of type \"boolean\", parameter \"dimension_value_types\" of list of list of", "type \"ListGenericObjectsParams\" (List generic objects in one or more workspaces optional parameters: allowed_object_types", "in a package from .baseclient import BaseClient as _BaseClient # @UnusedImport except: #", "status value_types - list of value types in the object (there will only", "parameter \"workspace_names\" of list of String, parameter \"allowed_object_types\" of list of String, parameter", "be overwritten # ############################################################ from __future__ import print_function # the following is a", "Y data are null are removed.) -> structure: parameter \"object_id\" of String, parameter", "a dimension index (e.g., \"2/3\" for the 3rd type of values in the", "type \"GetGenericDataResult\" -> structure: parameter \"series_labels\" of list of String, parameter \"values_x\" of", "list of type \"oterm_ref\", parameter \"int_values\" of list of Long, parameter \"float_values\" of", "the numeric indices of all dimensions they care about (e.g., 1/1 will mean", "not resorted, so the Values array may be a different length).) -> structure:", "of labels, or by fixing a dimension index (e.g., \"2/3\" for the 3rd", "as CSV files) -> structure: parameter \"input_ref\" of String :returns: instance of type", "we're in a # package or not. This makes pep8 unhappy hence the", "specific types of object, e.g., KBaseGenerics.NDArray (version number is optional) allowed_data_types - limits", "oterm_refs int_values float_values string_values boolean_values) -> structure: parameter \"scalar_type\" of type \"data_type\", parameter", "objects), e.g., \"float\" dimension_types - a string describing each dimension (e.g., \"media name\")", "(e.g., \"int\")) -> structure: parameter \"object_type\" of String, parameter \"data_type\" of String, parameter", "params: instance of type \"ExportParams\" (Exporter for generic objects as CSV files) ->", "limits to specific data types, e.g., microbial growth allowed_scalar_types - limits to specific", "is_mapped - 0 or 1 indicating mapped status value_types - list of value", "GenericsUtil(object): def __init__( self, url=None, timeout=30 * 60, user_id=None, password=<PASSWORD>, token=<PASSWORD>, ignore_authrc=False, trust_all_ssl_certificates=False,", "of dimensions limit_mapped - if 0 (or unset) returns all objects. if 1,", "# ############################################################ from __future__ import print_function # the following is a hack to", "params: instance of type \"ListGenericObjectsParams\" (List generic objects in one or more workspaces", "String to type \"GenericMetadata\" (Basic metadata about an object: object_type - e.g., KBaseGenerics.HNDArray‑4.0", "\"media name\") dimension_sizes - size (length) of each dimension dimension_value_types - a string", "return self._client.call_method( 'GenericsUtil.get_generic_dimension_labels', [params], self._service_ver, context) def get_generic_data(self, params, context=None): \"\"\" :param params:", "String, parameter \"n_dimensions\" of Long, parameter \"is_mapped\" of type \"boolean\", parameter \"value_types\" of", "of type \"ImportResult\" -> structure: parameter \"object_ref\" of String \"\"\" return self._client.call_method( 'GenericsUtil.import_csv',", "\"object_name\" of String, parameter \"metadata\" of type \"usermeta\" -> mapping from String to", "to specific types of object, e.g., KBaseGenerics.NDArray (version number is optional) allowed_data_types -", "will also be re-indexed, but not resorted, so the Values array may be", "the complete list of labels, or by fixing a dimension index (e.g., \"2/3\"", "int, float (see KBaseGenerics.spec for valid types). HNDArrays must have at least one", "package from .baseclient import BaseClient as _BaseClient # @UnusedImport except: # no they", "'GenericsUtil.import_csv', [params], self._service_ver, context) def import_obo(self, params, context=None): \"\"\" :param params: instance of", "String to type \"Values\" (@optional object_refs oterm_refs int_values float_values string_values boolean_values) -> structure:", "type of values in each context of each dimension (e.g., \"int\")) -> structure:", "BaseClient as _BaseClient # @UnusedImport except: # no they aren't from baseclient import", "type \"GetGenericMetadataParams\" (Get metadata describing the dimensions of one or more generic objects)", "self._client.call_method( 'GenericsUtil.get_generic_dimension_labels', [params], self._service_ver, context) def get_generic_data(self, params, context=None): \"\"\" :param params: instance", "\"ListGenericObjectsResult\" -> structure: parameter \"object_ids\" of list of String \"\"\" return self._client.call_method( 'GenericsUtil.list_generic_objects',", "_BaseClient # @UnusedImport except: # no they aren't from baseclient import BaseClient as", "structure: parameter \"object_ref\" of String \"\"\" return self._client.call_method( 'GenericsUtil.import_obo', [params], self._service_ver, context) def", "timeout=30 * 60, user_id=None, password=<PASSWORD>, token=<PASSWORD>, ignore_authrc=False, trust_all_ssl_certificates=False, auth_svc='https://kbase.us/services/authorization/Sessions/Login'): if url is None:", "into an OntologyDictionary) -> structure: parameter \"file\" of type \"File\" (Import a CSV", "context=None): \"\"\" :param params: instance of type \"ListGenericObjectsParams\" (List generic objects in one", "(version number is optional) allowed_data_types - limits to specific data types, e.g., microbial", "String, parameter \"allowed_object_types\" of list of String, parameter \"allowed_data_types\" of list of String,", "to generics with max number of dimensions limit_mapped - if 0 (or unset)", "context=None): \"\"\" :param params: instance of type \"GetGenericMetadataParams\" (Get metadata describing the dimensions", "structure: parameter \"object_type\" of String, parameter \"data_type\" of String, parameter \"n_dimensions\" of Long,", "least one dimension that passes. min_dimensions - limits to generics with minimum number", "microbial growth n_dimensions - number of dimensions is_mapped - 0 or 1 indicating", "export_csv(self, params, context=None): \"\"\" :param params: instance of type \"ExportParams\" (Exporter for generic", "String to String :returns: instance of type \"ImportResult\" -> structure: parameter \"object_ref\" of", "-> structure: parameter \"path\" of String, parameter \"shock_id\" of String, parameter \"workspace_name\" of", "structure: parameter \"scalar_type\" of type \"data_type\", parameter \"object_refs\" of list of type \"object_ref\",", "\"object_ref\", parameter \"oterm_refs\" of list of type \"oterm_ref\", parameter \"int_values\" of list of", "dimension dimension_value_types - a string describing each context of each dimension (e.g., \"media", "self._service_ver, context) def export_csv(self, params, context=None): \"\"\" :param params: instance of type \"ExportParams\"", "= None self._client = _BaseClient( url, timeout=timeout, user_id=user_id, password=password, token=token, ignore_authrc=ignore_authrc, trust_all_ssl_certificates=trust_all_ssl_certificates, auth_svc=auth_svc)", "parameter \"object_info\" of mapping from String to type \"GenericMetadata\" (Basic metadata about an", "mapped objects. if 2, returns only umapped objects) -> structure: parameter \"workspace_names\" of", "list of String, parameter \"dimension_types\" of list of String, parameter \"dimension_sizes\" of list", "String, parameter \"dimension_scalar_types\" of list of list of String \"\"\" return self._client.call_method( 'GenericsUtil.get_generic_metadata',", "y-axis values per series. The number of series depends on the number of", "two ways: either by fixing an entire dimension (e.g., \"2\" for the 2nd", "of String, parameter \"object_name\" of String, parameter \"object_type\" of String, parameter \"metadata\" of", "(e.g., \"media name\") dimension_sizes - size (length) of each dimension dimension_value_types - a", "be 1 for NDArray objects), e.g., \"float\" dimension_types - a string describing each", "String \"\"\" return self._client.call_method( 'GenericsUtil.get_generic_dimension_labels', [params], self._service_ver, context) def get_generic_data(self, params, context=None): \"\"\"", "The number of series depends on the number of variable dimensions. In each", "parameter \"object_name\" of String, parameter \"metadata\" of type \"usermeta\" -> mapping from String", "\"GenericMetadata\" (Basic metadata about an object: object_type - e.g., KBaseGenerics.HNDArray‑4.0 data_type - e.g.,", "compiler - # any changes made here will be overwritten # ############################################################ from", "of type \"boolean\", parameter \"string_values\" of list of String, parameter \"values_y\" of list", "auth_svc=auth_svc) def import_csv(self, params, context=None): \"\"\" :param params: instance of type \"ImportCSVParams\" ->", "instance of type \"GetGenericMetadataResult\" (maps object ids to structure with metadata) -> structure:", "mean 1st dimension, 1st data type, 2/1 = 2nd dimension, 1st data type),", "by fixing a dimension index (e.g., \"2/3\" for the 3rd type of values", ":param params: instance of type \"ListGenericObjectsParams\" (List generic objects in one or more", "labels for that dimension index. returns: series_labels will show which variable index values", "\"\"\" return self._client.call_method( 'GenericsUtil.export_csv', [params], self._service_ver, context) def list_generic_objects(self, params, context=None): \"\"\" :param", "\"media name\") dimension_scalar_types - type of values in each context of each dimension", "e.g., object_ref, int, float (see KBaseGenerics.spec for valid types). HNDArrays must have at", "list of scalar types in the object (there will only be 1 for", "for NDArray objects), e.g., \"float\" dimension_types - a string describing each dimension (e.g.,", "on the number of variable dimensions. In each series, values where either the", "structure: parameter \"object_id\" of String, parameter \"dimension_ids\" of list of String, parameter \"convert_to_string\"", "\"boolean\", parameter \"dimension_value_types\" of list of list of String, parameter \"dimension_scalar_types\" of list", "number of dimensions is_mapped - 0 or 1 indicating mapped status value_types -", "of each dimension dimension_value_types - a string describing each context of each dimension", "of series depends on the number of variable dimensions. In each series, values", "\"float\" dimension_types - a string describing each dimension (e.g., \"media name\") dimension_sizes -", "files) -> structure: parameter \"input_ref\" of String :returns: instance of type \"ExportResult\" ->", "parameter \"object_refs\" of list of type \"object_ref\", parameter \"oterm_refs\" of list of type", "\"int_values\" of list of Long, parameter \"float_values\" of list of Double, parameter \"boolean_values\"", "of String \"\"\" return self._client.call_method( 'GenericsUtil.get_generic_dimension_labels', [params], self._service_ver, context) def get_generic_data(self, params, context=None):", "return self._client.call_method( 'GenericsUtil.list_generic_objects', [params], self._service_ver, context) def get_generic_metadata(self, params, context=None): \"\"\" :param params:", "2D matrix Users passes in the dimension indices to use as variables (1st", "structure: parameter \"object_ids\" of list of String \"\"\" return self._client.call_method( 'GenericsUtil.list_generic_objects', [params], self._service_ver,", "\"values_x\" of list of type \"Values\" (@optional object_refs oterm_refs int_values float_values string_values boolean_values)", "file into a NDArray or HNDArray. \"File\" and \"usermeta\" are common to all", "\"convert_to_string\" of type \"boolean\", parameter \"unique_values\" of type \"boolean\" :returns: instance of type", "for valid types). HNDArrays must have at least one dimension that passes. min_dimensions", "type \"GetGenericDataParams\" (gets subset of generic data as a 2D matrix Users passes", "returns all objects. if 1, returns only mapped objects. if 2, returns only", "\"2\" for the 2nd dimension) to an index in the complete list of", "values correspond to which series values_x will contain 1 list of of x-axis", "parameter \"n_dimensions\" of Long, parameter \"is_mapped\" of type \"boolean\", parameter \"value_types\" of list", "be a different length).) -> structure: parameter \"object_id\" of String, parameter \"dimension_ids\" of", "context of each dimension (e.g., \"media name\") dimension_scalar_types - type of values in", "different length).) -> structure: parameter \"object_id\" of String, parameter \"dimension_ids\" of list of", "\"dimension_ids\" of list of String, parameter \"convert_to_string\" of type \"boolean\", parameter \"unique_values\" of", "of Long, parameter \"float_values\" of list of Double, parameter \"boolean_values\" of list of" ]
[ "type: {attachment.content_type}') if header == 'VIDEO': await video.process_file(await save_attachment(attachment, msg), msg, ctx, attachment)", "'AUDIO': await audio.process_file(await save_attachment(attachment, msg), msg, ctx) else: print(f'{Fore.RED}[DISPATCHER] failed to get file", "def header_type(attachment_url): for key in config.FILE_HEADERS.keys(): for header in config.FILE_HEADERS[key]: if attachment_url.__contains__(header): return", "resp.read()) else: print('[EMBED SAVING] embed save requested did not have any content attached", "= msg.content.lower() if msg.attachments: for attachment in msg.attachments: for attachment in msg.attachments: header", "or msgLower.__contains__('media.')): pass ''' for embed in msg.embeds: if header_type(msgLower) is not None:", "attachment) elif header == 'GIF': await video.process_file(await save_attachment(attachment, msg), msg, ctx) elif header", "'GIF': print(await save_embed(embed, msg)) video.process_file(embed, False) elif header == 'PICTURE': print(await save_embed(embed, msg))", "print(await save_embed(embed, msg)) audio.process_file(embed) else: print('failed to get file type from attachment') else:", "print(f'{Fore.RED}[ATTACHMENT SAVING] attachment save requested did not have a .url or a .id{Fore.WHITE}')", "attachment save requested did not have a .url or a .id{Fore.WHITE}') async def", "audio.process_file(embed) else: print('failed to get file type from attachment') else: await msg.reply('good embed')", "from attachment{Fore.WHITE}') elif msg.embeds or (msgLower.__contains__('cdn.') or msgLower.__contains__('media.')): pass ''' for embed in", "in msg.attachments: header = header_type(attachment.url) print(f'{Fore.WHITE}[ATTACHMENT FOUND] type: {attachment.content_type}') if header == 'VIDEO':", "msg): if attachment.url and attachment.id: await attachment.save(f'temp/{msg.id}{attachment.filename}') return(f'temp/{msg.id}{attachment.filename}') else: print(f'{Fore.RED}[ATTACHMENT SAVING] attachment save", "== 'AUDIO': print(await save_embed(embed, msg)) audio.process_file(embed) else: print('failed to get file type from", "return key return None async def save_attachment(attachment, msg): if attachment.url and attachment.id: await", "for header in config.FILE_HEADERS[key]: if attachment_url.__contains__(header): return key return None async def save_attachment(attachment,", "colorama import Fore import video, image, audio, config colorama.init() async def dispatch(msg: discord.Message,", "to get file type from attachment') else: await msg.reply('good embed') print(msgLower) ''' def", "type from attachment{Fore.WHITE}') elif msg.embeds or (msgLower.__contains__('cdn.') or msgLower.__contains__('media.')): pass ''' for embed", "msg.reply('good embed') print(msgLower) ''' def header_type(attachment_url): for key in config.FILE_HEADERS.keys(): for header in", "aiohttp, os, asyncio, colorama from colorama import Fore import video, image, audio, config", "image, audio, config colorama.init() async def dispatch(msg: discord.Message, ctx): msgLower = msg.content.lower() if", "print(await save_embed(embed, msg)) image.process_file(embed) elif header == 'AUDIO': print(await save_embed(embed, msg)) audio.process_file(embed) else:", "msg)) image.process_file(embed) elif header == 'AUDIO': print(await save_embed(embed, msg)) audio.process_file(embed) else: print('failed to", "save_attachment(attachment, msg): if attachment.url and attachment.id: await attachment.save(f'temp/{msg.id}{attachment.filename}') return(f'temp/{msg.id}{attachment.filename}') else: print(f'{Fore.RED}[ATTACHMENT SAVING] attachment", "async def save_embed(embed, msg): if embed.url: async with aiohttp.ClientSession() as session: async with", "video.process_file(embed, True) elif header == 'GIF': print(await save_embed(embed, msg)) video.process_file(embed, False) elif header", "== 'AUDIO': await audio.process_file(await save_attachment(attachment, msg), msg, ctx) else: print(f'{Fore.RED}[DISPATCHER] failed to get", "header == 'AUDIO': print(await save_embed(embed, msg)) audio.process_file(embed) else: print('failed to get file type", "def save_attachment(attachment, msg): if attachment.url and attachment.id: await attachment.save(f'temp/{msg.id}{attachment.filename}') return(f'temp/{msg.id}{attachment.filename}') else: print(f'{Fore.RED}[ATTACHMENT SAVING]", "await msg.reply('good embed') print(msgLower) ''' def header_type(attachment_url): for key in config.FILE_HEADERS.keys(): for header", ".url or a .id{Fore.WHITE}') async def save_embed(embed, msg): if embed.url: async with aiohttp.ClientSession()", "attachment in msg.attachments: header = header_type(attachment.url) print(f'{Fore.WHITE}[ATTACHMENT FOUND] type: {attachment.content_type}') if header ==", "from attachment') else: await msg.reply('good embed') print(msgLower) ''' def header_type(attachment_url): for key in", "ctx) elif header == 'PICTURE': await image.process_file(await save_attachment(attachment, msg), msg, ctx) elif header", "video, image, audio, config colorama.init() async def dispatch(msg: discord.Message, ctx): msgLower = msg.content.lower()", "a .id{Fore.WHITE}') async def save_embed(embed, msg): if embed.url: async with aiohttp.ClientSession() as session:", "colorama.init() async def dispatch(msg: discord.Message, ctx): msgLower = msg.content.lower() if msg.attachments: for attachment", "msg.attachments: for attachment in msg.attachments: header = header_type(attachment.url) print(f'{Fore.WHITE}[ATTACHMENT FOUND] type: {attachment.content_type}') if", "'PICTURE': await image.process_file(await save_attachment(attachment, msg), msg, ctx) elif header == 'AUDIO': await audio.process_file(await", "'VIDEO': print(await save_embed(embed, msg)) video.process_file(embed, True) elif header == 'GIF': print(await save_embed(embed, msg))", "file.write(await resp.read()) else: print('[EMBED SAVING] embed save requested did not have any content", "''' def header_type(attachment_url): for key in config.FILE_HEADERS.keys(): for header in config.FILE_HEADERS[key]: if attachment_url.__contains__(header):", "if header == 'VIDEO': await video.process_file(await save_attachment(attachment, msg), msg, ctx, attachment) elif header", "msg), msg, ctx) elif header == 'PICTURE': await image.process_file(await save_attachment(attachment, msg), msg, ctx)", "attachment{Fore.WHITE}') elif msg.embeds or (msgLower.__contains__('cdn.') or msgLower.__contains__('media.')): pass ''' for embed in msg.embeds:", "embed in msg.embeds: if header_type(msgLower) is not None: header = header_type(msgLower) if header", "have a .url or a .id{Fore.WHITE}') async def save_embed(embed, msg): if embed.url: async", "with open(f'temp/{msg.id}', \"wb\") as file: file.write(await resp.read()) else: print('[EMBED SAVING] embed save requested", "else: print('[EMBED SAVING] embed save requested did not have any content attached to", "image.process_file(await save_attachment(attachment, msg), msg, ctx) elif header == 'AUDIO': await audio.process_file(await save_attachment(attachment, msg),", "msg), msg, ctx) elif header == 'AUDIO': await audio.process_file(await save_attachment(attachment, msg), msg, ctx)", "for attachment in msg.attachments: header = header_type(attachment.url) print(f'{Fore.WHITE}[ATTACHMENT FOUND] type: {attachment.content_type}') if header", "msgLower.__contains__('media.')): pass ''' for embed in msg.embeds: if header_type(msgLower) is not None: header", "in msg.embeds: if header_type(msgLower) is not None: header = header_type(msgLower) if header ==", "in msg.attachments: for attachment in msg.attachments: header = header_type(attachment.url) print(f'{Fore.WHITE}[ATTACHMENT FOUND] type: {attachment.content_type}')", "os.path.basename(embed.url) with open(f'temp/{msg.id}', \"wb\") as file: file.write(await resp.read()) else: print('[EMBED SAVING] embed save", "def save_embed(embed, msg): if embed.url: async with aiohttp.ClientSession() as session: async with session.get(embed.url)", "is not None: header = header_type(msgLower) if header == 'VIDEO': print(await save_embed(embed, msg))", "200: attachment_name = os.path.basename(embed.url) with open(f'temp/{msg.id}', \"wb\") as file: file.write(await resp.read()) else: print('[EMBED", "msg, ctx) elif header == 'AUDIO': await audio.process_file(await save_attachment(attachment, msg), msg, ctx) else:", "elif header == 'AUDIO': await audio.process_file(await save_attachment(attachment, msg), msg, ctx) else: print(f'{Fore.RED}[DISPATCHER] failed", "session: async with session.get(embed.url) as resp: if resp.status == 200: attachment_name = os.path.basename(embed.url)", "from colorama import Fore import video, image, audio, config colorama.init() async def dispatch(msg:", "= header_type(attachment.url) print(f'{Fore.WHITE}[ATTACHMENT FOUND] type: {attachment.content_type}') if header == 'VIDEO': await video.process_file(await save_attachment(attachment,", "== 200: attachment_name = os.path.basename(embed.url) with open(f'temp/{msg.id}', \"wb\") as file: file.write(await resp.read()) else:", "as resp: if resp.status == 200: attachment_name = os.path.basename(embed.url) with open(f'temp/{msg.id}', \"wb\") as", "to get file type from attachment{Fore.WHITE}') elif msg.embeds or (msgLower.__contains__('cdn.') or msgLower.__contains__('media.')): pass", "await attachment.save(f'temp/{msg.id}{attachment.filename}') return(f'temp/{msg.id}{attachment.filename}') else: print(f'{Fore.RED}[ATTACHMENT SAVING] attachment save requested did not have a", "dispatch(msg: discord.Message, ctx): msgLower = msg.content.lower() if msg.attachments: for attachment in msg.attachments: for", "import video, image, audio, config colorama.init() async def dispatch(msg: discord.Message, ctx): msgLower =", "save_attachment(attachment, msg), msg, ctx, attachment) elif header == 'GIF': await video.process_file(await save_attachment(attachment, msg),", "msg, ctx) else: print(f'{Fore.RED}[DISPATCHER] failed to get file type from attachment{Fore.WHITE}') elif msg.embeds", "or a .id{Fore.WHITE}') async def save_embed(embed, msg): if embed.url: async with aiohttp.ClientSession() as", "msg.content.lower() if msg.attachments: for attachment in msg.attachments: for attachment in msg.attachments: header =", "audio.process_file(await save_attachment(attachment, msg), msg, ctx) else: print(f'{Fore.RED}[DISPATCHER] failed to get file type from", "header == 'PICTURE': print(await save_embed(embed, msg)) image.process_file(embed) elif header == 'AUDIO': print(await save_embed(embed,", "''' for embed in msg.embeds: if header_type(msgLower) is not None: header = header_type(msgLower)", "print('failed to get file type from attachment') else: await msg.reply('good embed') print(msgLower) '''", "async def save_attachment(attachment, msg): if attachment.url and attachment.id: await attachment.save(f'temp/{msg.id}{attachment.filename}') return(f'temp/{msg.id}{attachment.filename}') else: print(f'{Fore.RED}[ATTACHMENT", "await audio.process_file(await save_attachment(attachment, msg), msg, ctx) else: print(f'{Fore.RED}[DISPATCHER] failed to get file type", "if attachment_url.__contains__(header): return key return None async def save_attachment(attachment, msg): if attachment.url and", "video.process_file(embed, False) elif header == 'PICTURE': print(await save_embed(embed, msg)) image.process_file(embed) elif header ==", "== 'VIDEO': await video.process_file(await save_attachment(attachment, msg), msg, ctx, attachment) elif header == 'GIF':", "requested did not have a .url or a .id{Fore.WHITE}') async def save_embed(embed, msg):", "image.process_file(embed) elif header == 'AUDIO': print(await save_embed(embed, msg)) audio.process_file(embed) else: print('failed to get", "msg.attachments: for attachment in msg.attachments: for attachment in msg.attachments: header = header_type(attachment.url) print(f'{Fore.WHITE}[ATTACHMENT", "pass ''' for embed in msg.embeds: if header_type(msgLower) is not None: header =", "if header_type(msgLower) is not None: header = header_type(msgLower) if header == 'VIDEO': print(await", "ctx) else: print(f'{Fore.RED}[DISPATCHER] failed to get file type from attachment{Fore.WHITE}') elif msg.embeds or", "msg.embeds: if header_type(msgLower) is not None: header = header_type(msgLower) if header == 'VIDEO':", "if embed.url: async with aiohttp.ClientSession() as session: async with session.get(embed.url) as resp: if", "header_type(msgLower) if header == 'VIDEO': print(await save_embed(embed, msg)) video.process_file(embed, True) elif header ==", "import Fore import video, image, audio, config colorama.init() async def dispatch(msg: discord.Message, ctx):", "None: header = header_type(msgLower) if header == 'VIDEO': print(await save_embed(embed, msg)) video.process_file(embed, True)", "{attachment.content_type}') if header == 'VIDEO': await video.process_file(await save_attachment(attachment, msg), msg, ctx, attachment) elif", "None async def save_attachment(attachment, msg): if attachment.url and attachment.id: await attachment.save(f'temp/{msg.id}{attachment.filename}') return(f'temp/{msg.id}{attachment.filename}') else:", "save_attachment(attachment, msg), msg, ctx) else: print(f'{Fore.RED}[DISPATCHER] failed to get file type from attachment{Fore.WHITE}')", "msg)) video.process_file(embed, True) elif header == 'GIF': print(await save_embed(embed, msg)) video.process_file(embed, False) elif", "in config.FILE_HEADERS.keys(): for header in config.FILE_HEADERS[key]: if attachment_url.__contains__(header): return key return None async", "attachment.id: await attachment.save(f'temp/{msg.id}{attachment.filename}') return(f'temp/{msg.id}{attachment.filename}') else: print(f'{Fore.RED}[ATTACHMENT SAVING] attachment save requested did not have", "header == 'GIF': await video.process_file(await save_attachment(attachment, msg), msg, ctx) elif header == 'PICTURE':", "aiohttp.ClientSession() as session: async with session.get(embed.url) as resp: if resp.status == 200: attachment_name", "if resp.status == 200: attachment_name = os.path.basename(embed.url) with open(f'temp/{msg.id}', \"wb\") as file: file.write(await", "== 'PICTURE': await image.process_file(await save_attachment(attachment, msg), msg, ctx) elif header == 'AUDIO': await", "header == 'PICTURE': await image.process_file(await save_attachment(attachment, msg), msg, ctx) elif header == 'AUDIO':", "audio, config colorama.init() async def dispatch(msg: discord.Message, ctx): msgLower = msg.content.lower() if msg.attachments:", "== 'GIF': print(await save_embed(embed, msg)) video.process_file(embed, False) elif header == 'PICTURE': print(await save_embed(embed,", "attachment_url.__contains__(header): return key return None async def save_attachment(attachment, msg): if attachment.url and attachment.id:", "header == 'VIDEO': print(await save_embed(embed, msg)) video.process_file(embed, True) elif header == 'GIF': print(await", "video.process_file(await save_attachment(attachment, msg), msg, ctx) elif header == 'PICTURE': await image.process_file(await save_attachment(attachment, msg),", "type from attachment') else: await msg.reply('good embed') print(msgLower) ''' def header_type(attachment_url): for key", "\"wb\") as file: file.write(await resp.read()) else: print('[EMBED SAVING] embed save requested did not", "for attachment in msg.attachments: for attachment in msg.attachments: header = header_type(attachment.url) print(f'{Fore.WHITE}[ATTACHMENT FOUND]", "video.process_file(await save_attachment(attachment, msg), msg, ctx, attachment) elif header == 'GIF': await video.process_file(await save_attachment(attachment,", "print(f'{Fore.RED}[DISPATCHER] failed to get file type from attachment{Fore.WHITE}') elif msg.embeds or (msgLower.__contains__('cdn.') or", "msg), msg, ctx) else: print(f'{Fore.RED}[DISPATCHER] failed to get file type from attachment{Fore.WHITE}') elif", "resp: if resp.status == 200: attachment_name = os.path.basename(embed.url) with open(f'temp/{msg.id}', \"wb\") as file:", "async def dispatch(msg: discord.Message, ctx): msgLower = msg.content.lower() if msg.attachments: for attachment in", "save_embed(embed, msg)) video.process_file(embed, True) elif header == 'GIF': print(await save_embed(embed, msg)) video.process_file(embed, False)", "open(f'temp/{msg.id}', \"wb\") as file: file.write(await resp.read()) else: print('[EMBED SAVING] embed save requested did", "embed') print(msgLower) ''' def header_type(attachment_url): for key in config.FILE_HEADERS.keys(): for header in config.FILE_HEADERS[key]:", "attachment') else: await msg.reply('good embed') print(msgLower) ''' def header_type(attachment_url): for key in config.FILE_HEADERS.keys():", "print(await save_embed(embed, msg)) video.process_file(embed, False) elif header == 'PICTURE': print(await save_embed(embed, msg)) image.process_file(embed)", "with session.get(embed.url) as resp: if resp.status == 200: attachment_name = os.path.basename(embed.url) with open(f'temp/{msg.id}',", "FOUND] type: {attachment.content_type}') if header == 'VIDEO': await video.process_file(await save_attachment(attachment, msg), msg, ctx,", "save_embed(embed, msg)) image.process_file(embed) elif header == 'AUDIO': print(await save_embed(embed, msg)) audio.process_file(embed) else: print('failed", "msg), msg, ctx, attachment) elif header == 'GIF': await video.process_file(await save_attachment(attachment, msg), msg,", "elif header == 'GIF': await video.process_file(await save_attachment(attachment, msg), msg, ctx) elif header ==", "ctx) elif header == 'AUDIO': await audio.process_file(await save_attachment(attachment, msg), msg, ctx) else: print(f'{Fore.RED}[DISPATCHER]", "key return None async def save_attachment(attachment, msg): if attachment.url and attachment.id: await attachment.save(f'temp/{msg.id}{attachment.filename}')", "attachment.url and attachment.id: await attachment.save(f'temp/{msg.id}{attachment.filename}') return(f'temp/{msg.id}{attachment.filename}') else: print(f'{Fore.RED}[ATTACHMENT SAVING] attachment save requested did", "else: print(f'{Fore.RED}[DISPATCHER] failed to get file type from attachment{Fore.WHITE}') elif msg.embeds or (msgLower.__contains__('cdn.')", "ctx, attachment) elif header == 'GIF': await video.process_file(await save_attachment(attachment, msg), msg, ctx) elif", "if header == 'VIDEO': print(await save_embed(embed, msg)) video.process_file(embed, True) elif header == 'GIF':", "msgLower = msg.content.lower() if msg.attachments: for attachment in msg.attachments: for attachment in msg.attachments:", "as session: async with session.get(embed.url) as resp: if resp.status == 200: attachment_name =", "for embed in msg.embeds: if header_type(msgLower) is not None: header = header_type(msgLower) if", "SAVING] attachment save requested did not have a .url or a .id{Fore.WHITE}') async", ".id{Fore.WHITE}') async def save_embed(embed, msg): if embed.url: async with aiohttp.ClientSession() as session: async", "file: file.write(await resp.read()) else: print('[EMBED SAVING] embed save requested did not have any", "print(await save_embed(embed, msg)) video.process_file(embed, True) elif header == 'GIF': print(await save_embed(embed, msg)) video.process_file(embed,", "get file type from attachment') else: await msg.reply('good embed') print(msgLower) ''' def header_type(attachment_url):", "header_type(attachment_url): for key in config.FILE_HEADERS.keys(): for header in config.FILE_HEADERS[key]: if attachment_url.__contains__(header): return key", "(msgLower.__contains__('cdn.') or msgLower.__contains__('media.')): pass ''' for embed in msg.embeds: if header_type(msgLower) is not", "'PICTURE': print(await save_embed(embed, msg)) image.process_file(embed) elif header == 'AUDIO': print(await save_embed(embed, msg)) audio.process_file(embed)", "return None async def save_attachment(attachment, msg): if attachment.url and attachment.id: await attachment.save(f'temp/{msg.id}{attachment.filename}') return(f'temp/{msg.id}{attachment.filename}')", "else: print(f'{Fore.RED}[ATTACHMENT SAVING] attachment save requested did not have a .url or a", "msg.attachments: header = header_type(attachment.url) print(f'{Fore.WHITE}[ATTACHMENT FOUND] type: {attachment.content_type}') if header == 'VIDEO': await", "== 'PICTURE': print(await save_embed(embed, msg)) image.process_file(embed) elif header == 'AUDIO': print(await save_embed(embed, msg))", "file type from attachment{Fore.WHITE}') elif msg.embeds or (msgLower.__contains__('cdn.') or msgLower.__contains__('media.')): pass ''' for", "= header_type(msgLower) if header == 'VIDEO': print(await save_embed(embed, msg)) video.process_file(embed, True) elif header", "for key in config.FILE_HEADERS.keys(): for header in config.FILE_HEADERS[key]: if attachment_url.__contains__(header): return key return", "print(f'{Fore.WHITE}[ATTACHMENT FOUND] type: {attachment.content_type}') if header == 'VIDEO': await video.process_file(await save_attachment(attachment, msg), msg,", "in config.FILE_HEADERS[key]: if attachment_url.__contains__(header): return key return None async def save_attachment(attachment, msg): if", "'AUDIO': print(await save_embed(embed, msg)) audio.process_file(embed) else: print('failed to get file type from attachment')", "if msg.attachments: for attachment in msg.attachments: for attachment in msg.attachments: header = header_type(attachment.url)", "elif header == 'PICTURE': print(await save_embed(embed, msg)) image.process_file(embed) elif header == 'AUDIO': print(await", "await video.process_file(await save_attachment(attachment, msg), msg, ctx) elif header == 'PICTURE': await image.process_file(await save_attachment(attachment,", "msg, ctx, attachment) elif header == 'GIF': await video.process_file(await save_attachment(attachment, msg), msg, ctx)", "asyncio, colorama from colorama import Fore import video, image, audio, config colorama.init() async", "attachment in msg.attachments: for attachment in msg.attachments: header = header_type(attachment.url) print(f'{Fore.WHITE}[ATTACHMENT FOUND] type:", "print(msgLower) ''' def header_type(attachment_url): for key in config.FILE_HEADERS.keys(): for header in config.FILE_HEADERS[key]: if", "get file type from attachment{Fore.WHITE}') elif msg.embeds or (msgLower.__contains__('cdn.') or msgLower.__contains__('media.')): pass '''", "True) elif header == 'GIF': print(await save_embed(embed, msg)) video.process_file(embed, False) elif header ==", "elif msg.embeds or (msgLower.__contains__('cdn.') or msgLower.__contains__('media.')): pass ''' for embed in msg.embeds: if", "a .url or a .id{Fore.WHITE}') async def save_embed(embed, msg): if embed.url: async with", "header = header_type(msgLower) if header == 'VIDEO': print(await save_embed(embed, msg)) video.process_file(embed, True) elif", "with aiohttp.ClientSession() as session: async with session.get(embed.url) as resp: if resp.status == 200:", "async with session.get(embed.url) as resp: if resp.status == 200: attachment_name = os.path.basename(embed.url) with", "session.get(embed.url) as resp: if resp.status == 200: attachment_name = os.path.basename(embed.url) with open(f'temp/{msg.id}', \"wb\")", "save requested did not have a .url or a .id{Fore.WHITE}') async def save_embed(embed,", "attachment.save(f'temp/{msg.id}{attachment.filename}') return(f'temp/{msg.id}{attachment.filename}') else: print(f'{Fore.RED}[ATTACHMENT SAVING] attachment save requested did not have a .url", "save_embed(embed, msg)) audio.process_file(embed) else: print('failed to get file type from attachment') else: await", "== 'GIF': await video.process_file(await save_attachment(attachment, msg), msg, ctx) elif header == 'PICTURE': await", "msg): if embed.url: async with aiohttp.ClientSession() as session: async with session.get(embed.url) as resp:", "header = header_type(attachment.url) print(f'{Fore.WHITE}[ATTACHMENT FOUND] type: {attachment.content_type}') if header == 'VIDEO': await video.process_file(await", "== 'VIDEO': print(await save_embed(embed, msg)) video.process_file(embed, True) elif header == 'GIF': print(await save_embed(embed,", "return(f'temp/{msg.id}{attachment.filename}') else: print(f'{Fore.RED}[ATTACHMENT SAVING] attachment save requested did not have a .url or", "Fore import video, image, audio, config colorama.init() async def dispatch(msg: discord.Message, ctx): msgLower", "msg, ctx) elif header == 'PICTURE': await image.process_file(await save_attachment(attachment, msg), msg, ctx) elif", "def dispatch(msg: discord.Message, ctx): msgLower = msg.content.lower() if msg.attachments: for attachment in msg.attachments:", "and attachment.id: await attachment.save(f'temp/{msg.id}{attachment.filename}') return(f'temp/{msg.id}{attachment.filename}') else: print(f'{Fore.RED}[ATTACHMENT SAVING] attachment save requested did not", "header_type(attachment.url) print(f'{Fore.WHITE}[ATTACHMENT FOUND] type: {attachment.content_type}') if header == 'VIDEO': await video.process_file(await save_attachment(attachment, msg),", "await video.process_file(await save_attachment(attachment, msg), msg, ctx, attachment) elif header == 'GIF': await video.process_file(await", "or (msgLower.__contains__('cdn.') or msgLower.__contains__('media.')): pass ''' for embed in msg.embeds: if header_type(msgLower) is", "not have a .url or a .id{Fore.WHITE}') async def save_embed(embed, msg): if embed.url:", "save_embed(embed, msg): if embed.url: async with aiohttp.ClientSession() as session: async with session.get(embed.url) as", "config.FILE_HEADERS.keys(): for header in config.FILE_HEADERS[key]: if attachment_url.__contains__(header): return key return None async def", "config.FILE_HEADERS[key]: if attachment_url.__contains__(header): return key return None async def save_attachment(attachment, msg): if attachment.url", "<reponame>IakovTaranenko/theia<filename>dispatcher.py import discord, aiohttp, os, asyncio, colorama from colorama import Fore import video,", "embed.url: async with aiohttp.ClientSession() as session: async with session.get(embed.url) as resp: if resp.status", "save_attachment(attachment, msg), msg, ctx) elif header == 'PICTURE': await image.process_file(await save_attachment(attachment, msg), msg,", "'GIF': await video.process_file(await save_attachment(attachment, msg), msg, ctx) elif header == 'PICTURE': await image.process_file(await", "discord.Message, ctx): msgLower = msg.content.lower() if msg.attachments: for attachment in msg.attachments: for attachment", "await image.process_file(await save_attachment(attachment, msg), msg, ctx) elif header == 'AUDIO': await audio.process_file(await save_attachment(attachment,", "attachment_name = os.path.basename(embed.url) with open(f'temp/{msg.id}', \"wb\") as file: file.write(await resp.read()) else: print('[EMBED SAVING]", "did not have a .url or a .id{Fore.WHITE}') async def save_embed(embed, msg): if", "elif header == 'GIF': print(await save_embed(embed, msg)) video.process_file(embed, False) elif header == 'PICTURE':", "header == 'GIF': print(await save_embed(embed, msg)) video.process_file(embed, False) elif header == 'PICTURE': print(await", "save_embed(embed, msg)) video.process_file(embed, False) elif header == 'PICTURE': print(await save_embed(embed, msg)) image.process_file(embed) elif", "colorama from colorama import Fore import video, image, audio, config colorama.init() async def", "os, asyncio, colorama from colorama import Fore import video, image, audio, config colorama.init()", "elif header == 'PICTURE': await image.process_file(await save_attachment(attachment, msg), msg, ctx) elif header ==", "header_type(msgLower) is not None: header = header_type(msgLower) if header == 'VIDEO': print(await save_embed(embed,", "else: print('failed to get file type from attachment') else: await msg.reply('good embed') print(msgLower)", "key in config.FILE_HEADERS.keys(): for header in config.FILE_HEADERS[key]: if attachment_url.__contains__(header): return key return None", "async with aiohttp.ClientSession() as session: async with session.get(embed.url) as resp: if resp.status ==", "as file: file.write(await resp.read()) else: print('[EMBED SAVING] embed save requested did not have", "if attachment.url and attachment.id: await attachment.save(f'temp/{msg.id}{attachment.filename}') return(f'temp/{msg.id}{attachment.filename}') else: print(f'{Fore.RED}[ATTACHMENT SAVING] attachment save requested", "file type from attachment') else: await msg.reply('good embed') print(msgLower) ''' def header_type(attachment_url): for", "elif header == 'AUDIO': print(await save_embed(embed, msg)) audio.process_file(embed) else: print('failed to get file", "else: await msg.reply('good embed') print(msgLower) ''' def header_type(attachment_url): for key in config.FILE_HEADERS.keys(): for", "discord, aiohttp, os, asyncio, colorama from colorama import Fore import video, image, audio,", "False) elif header == 'PICTURE': print(await save_embed(embed, msg)) image.process_file(embed) elif header == 'AUDIO':", "import discord, aiohttp, os, asyncio, colorama from colorama import Fore import video, image,", "config colorama.init() async def dispatch(msg: discord.Message, ctx): msgLower = msg.content.lower() if msg.attachments: for", "'VIDEO': await video.process_file(await save_attachment(attachment, msg), msg, ctx, attachment) elif header == 'GIF': await", "not None: header = header_type(msgLower) if header == 'VIDEO': print(await save_embed(embed, msg)) video.process_file(embed,", "resp.status == 200: attachment_name = os.path.basename(embed.url) with open(f'temp/{msg.id}', \"wb\") as file: file.write(await resp.read())", "header == 'VIDEO': await video.process_file(await save_attachment(attachment, msg), msg, ctx, attachment) elif header ==", "save_attachment(attachment, msg), msg, ctx) elif header == 'AUDIO': await audio.process_file(await save_attachment(attachment, msg), msg,", "ctx): msgLower = msg.content.lower() if msg.attachments: for attachment in msg.attachments: for attachment in", "header in config.FILE_HEADERS[key]: if attachment_url.__contains__(header): return key return None async def save_attachment(attachment, msg):", "msg)) audio.process_file(embed) else: print('failed to get file type from attachment') else: await msg.reply('good", "msg)) video.process_file(embed, False) elif header == 'PICTURE': print(await save_embed(embed, msg)) image.process_file(embed) elif header", "msg.embeds or (msgLower.__contains__('cdn.') or msgLower.__contains__('media.')): pass ''' for embed in msg.embeds: if header_type(msgLower)", "= os.path.basename(embed.url) with open(f'temp/{msg.id}', \"wb\") as file: file.write(await resp.read()) else: print('[EMBED SAVING] embed", "failed to get file type from attachment{Fore.WHITE}') elif msg.embeds or (msgLower.__contains__('cdn.') or msgLower.__contains__('media.')):", "print('[EMBED SAVING] embed save requested did not have any content attached to it')", "header == 'AUDIO': await audio.process_file(await save_attachment(attachment, msg), msg, ctx) else: print(f'{Fore.RED}[DISPATCHER] failed to" ]
[]
[]
[ "aberto', help_text='Determina se a compra do carrinho está em aberto.') class Meta: verbose_name", "do carrinho está em aberto.') class Meta: verbose_name = 'carrinho de compras' verbose_name_plural", "carrinho' verbose_name_plural = 'itens dos carrinhos' def __str__(self): return f'Cart #{self.cart.id} - {self.product}'", "__str__(self): return f'Sale #{self.id} - {self.buyer}' def get_items(self): return self.cart.get_items() def get_subtotal(self): subtotal", "de compras' def __str__(self): return f'Carrinho #{self.id}' def get_items(self): return CartItem.objects.filter(cart=self) class CartItem(models.Model):", "0 for i in self.get_items(): subtotal += i.product.price return subtotal def get_total(self): return", "verbose_name_plural = 'itens dos carrinhos' def __str__(self): return f'Cart #{self.cart.id} - {self.product}' class", "<gh_stars>0 from django.db import models from liberaction.users.models import User from liberaction.core.models import BaseProduct", "'venda' verbose_name_plural = 'vendas' def __str__(self): return f'Sale #{self.id} - {self.buyer}' def get_items(self):", "#{self.id}' def get_items(self): return CartItem.objects.filter(cart=self) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE, verbose_name='carrinho de", "#{self.id} - {self.buyer}' def get_items(self): return self.cart.get_items() def get_subtotal(self): subtotal = 0 for", "= models.BooleanField(default=True, verbose_name='Carrinho em aberto', help_text='Determina se a compra do carrinho está em", "return f'Sale #{self.id} - {self.buyer}' def get_items(self): return self.cart.get_items() def get_subtotal(self): subtotal =", "- {self.buyer}' def get_items(self): return self.cart.get_items() def get_subtotal(self): subtotal = 0 for i", "carrinhos' def __str__(self): return f'Cart #{self.cart.id} - {self.product}' class Sale(models.Model): buyer = models.ForeignKey(User,on_delete=models.SET_NULL,", "def __str__(self): return f'Cart #{self.cart.id} - {self.product}' class Sale(models.Model): buyer = models.ForeignKey(User,on_delete=models.SET_NULL, null=True)", "null=True, verbose_name='produto') product_count = models.IntegerField('unidades') class Meta: verbose_name = 'item do carrinho' verbose_name_plural", "in self.get_items(): subtotal += i.product.price return subtotal def get_total(self): return self.get_subtotal() + self.freight", "for i in self.get_items(): subtotal += i.product.price return subtotal def get_total(self): return self.get_subtotal()", "CartItem.objects.filter(cart=self) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE, verbose_name='carrinho de compras') product = models.ForeignKey(BaseProduct,", "on_delete=models.CASCADE, verbose_name='carrinho de compras') product = models.ForeignKey(BaseProduct, on_delete=models.SET_NULL, null=True, verbose_name='produto') product_count = models.IntegerField('unidades')", "f'Carrinho #{self.id}' def get_items(self): return CartItem.objects.filter(cart=self) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE, verbose_name='carrinho", "verbose_name='carrinho de compras') freight = models.FloatField('frete') class Meta: verbose_name = 'venda' verbose_name_plural =", "models.IntegerField('unidades') class Meta: verbose_name = 'item do carrinho' verbose_name_plural = 'itens dos carrinhos'", "class Meta: verbose_name = 'item do carrinho' verbose_name_plural = 'itens dos carrinhos' def", "compras' verbose_name_plural = 'carrinhos de compras' def __str__(self): return f'Carrinho #{self.id}' def get_items(self):", "product_count = models.IntegerField('unidades') class Meta: verbose_name = 'item do carrinho' verbose_name_plural = 'itens", "Meta: verbose_name = 'venda' verbose_name_plural = 'vendas' def __str__(self): return f'Sale #{self.id} -", "class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE, verbose_name='carrinho de compras') product = models.ForeignKey(BaseProduct, on_delete=models.SET_NULL,", "se a compra do carrinho está em aberto.') class Meta: verbose_name = 'carrinho", "def __str__(self): return f'Carrinho #{self.id}' def get_items(self): return CartItem.objects.filter(cart=self) class CartItem(models.Model): cart =", "self.cart.get_items() def get_subtotal(self): subtotal = 0 for i in self.get_items(): subtotal += i.product.price", "Meta: verbose_name = 'item do carrinho' verbose_name_plural = 'itens dos carrinhos' def __str__(self):", "f'Sale #{self.id} - {self.buyer}' def get_items(self): return self.cart.get_items() def get_subtotal(self): subtotal = 0", "'carrinhos de compras' def __str__(self): return f'Carrinho #{self.id}' def get_items(self): return CartItem.objects.filter(cart=self) class", "de compras') product = models.ForeignKey(BaseProduct, on_delete=models.SET_NULL, null=True, verbose_name='produto') product_count = models.IntegerField('unidades') class Meta:", "carrinho está em aberto.') class Meta: verbose_name = 'carrinho de compras' verbose_name_plural =", "'carrinho de compras' verbose_name_plural = 'carrinhos de compras' def __str__(self): return f'Carrinho #{self.id}'", "{self.buyer}' def get_items(self): return self.cart.get_items() def get_subtotal(self): subtotal = 0 for i in", "def __str__(self): return f'Sale #{self.id} - {self.buyer}' def get_items(self): return self.cart.get_items() def get_subtotal(self):", "verbose_name = 'venda' verbose_name_plural = 'vendas' def __str__(self): return f'Sale #{self.id} - {self.buyer}'", "product = models.ForeignKey(BaseProduct, on_delete=models.SET_NULL, null=True, verbose_name='produto') product_count = models.IntegerField('unidades') class Meta: verbose_name =", "models.FloatField('frete') class Meta: verbose_name = 'venda' verbose_name_plural = 'vendas' def __str__(self): return f'Sale", "= 0 for i in self.get_items(): subtotal += i.product.price return subtotal def get_total(self):", "class Cart(models.Model): is_open = models.BooleanField(default=True, verbose_name='Carrinho em aberto', help_text='Determina se a compra do", "return CartItem.objects.filter(cart=self) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE, verbose_name='carrinho de compras') product =", "return self.cart.get_items() def get_subtotal(self): subtotal = 0 for i in self.get_items(): subtotal +=", "= models.ForeignKey(Cart, on_delete=models.CASCADE, verbose_name='carrinho de compras') product = models.ForeignKey(BaseProduct, on_delete=models.SET_NULL, null=True, verbose_name='produto') product_count", "i in self.get_items(): subtotal += i.product.price return subtotal def get_total(self): return self.get_subtotal() +", "Cart(models.Model): is_open = models.BooleanField(default=True, verbose_name='Carrinho em aberto', help_text='Determina se a compra do carrinho", "= models.ForeignKey(BaseProduct, on_delete=models.SET_NULL, null=True, verbose_name='produto') product_count = models.IntegerField('unidades') class Meta: verbose_name = 'item", "aberto.') class Meta: verbose_name = 'carrinho de compras' verbose_name_plural = 'carrinhos de compras'", "= 'vendas' def __str__(self): return f'Sale #{self.id} - {self.buyer}' def get_items(self): return self.cart.get_items()", "= 'carrinho de compras' verbose_name_plural = 'carrinhos de compras' def __str__(self): return f'Carrinho", "class Sale(models.Model): buyer = models.ForeignKey(User,on_delete=models.SET_NULL, null=True) cart = models.OneToOneField(Cart, on_delete=models.CASCADE, verbose_name='carrinho de compras')", "freight = models.FloatField('frete') class Meta: verbose_name = 'venda' verbose_name_plural = 'vendas' def __str__(self):", "dos carrinhos' def __str__(self): return f'Cart #{self.cart.id} - {self.product}' class Sale(models.Model): buyer =", "class Meta: verbose_name = 'venda' verbose_name_plural = 'vendas' def __str__(self): return f'Sale #{self.id}", "verbose_name_plural = 'vendas' def __str__(self): return f'Sale #{self.id} - {self.buyer}' def get_items(self): return", "= 'item do carrinho' verbose_name_plural = 'itens dos carrinhos' def __str__(self): return f'Cart", "buyer = models.ForeignKey(User,on_delete=models.SET_NULL, null=True) cart = models.OneToOneField(Cart, on_delete=models.CASCADE, verbose_name='carrinho de compras') freight =", "verbose_name = 'carrinho de compras' verbose_name_plural = 'carrinhos de compras' def __str__(self): return", "import models from liberaction.users.models import User from liberaction.core.models import BaseProduct class Cart(models.Model): is_open", "from liberaction.core.models import BaseProduct class Cart(models.Model): is_open = models.BooleanField(default=True, verbose_name='Carrinho em aberto', help_text='Determina", "cart = models.ForeignKey(Cart, on_delete=models.CASCADE, verbose_name='carrinho de compras') product = models.ForeignKey(BaseProduct, on_delete=models.SET_NULL, null=True, verbose_name='produto')", "em aberto.') class Meta: verbose_name = 'carrinho de compras' verbose_name_plural = 'carrinhos de", "compras') product = models.ForeignKey(BaseProduct, on_delete=models.SET_NULL, null=True, verbose_name='produto') product_count = models.IntegerField('unidades') class Meta: verbose_name", "null=True) cart = models.OneToOneField(Cart, on_delete=models.CASCADE, verbose_name='carrinho de compras') freight = models.FloatField('frete') class Meta:", "CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE, verbose_name='carrinho de compras') product = models.ForeignKey(BaseProduct, on_delete=models.SET_NULL, null=True,", "está em aberto.') class Meta: verbose_name = 'carrinho de compras' verbose_name_plural = 'carrinhos", "liberaction.users.models import User from liberaction.core.models import BaseProduct class Cart(models.Model): is_open = models.BooleanField(default=True, verbose_name='Carrinho", "'item do carrinho' verbose_name_plural = 'itens dos carrinhos' def __str__(self): return f'Cart #{self.cart.id}", "def get_items(self): return self.cart.get_items() def get_subtotal(self): subtotal = 0 for i in self.get_items():", "verbose_name='Carrinho em aberto', help_text='Determina se a compra do carrinho está em aberto.') class", "de compras') freight = models.FloatField('frete') class Meta: verbose_name = 'venda' verbose_name_plural = 'vendas'", "a compra do carrinho está em aberto.') class Meta: verbose_name = 'carrinho de", "subtotal = 0 for i in self.get_items(): subtotal += i.product.price return subtotal def", "__str__(self): return f'Carrinho #{self.id}' def get_items(self): return CartItem.objects.filter(cart=self) class CartItem(models.Model): cart = models.ForeignKey(Cart,", "get_items(self): return CartItem.objects.filter(cart=self) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE, verbose_name='carrinho de compras') product", "from liberaction.users.models import User from liberaction.core.models import BaseProduct class Cart(models.Model): is_open = models.BooleanField(default=True,", "verbose_name='carrinho de compras') product = models.ForeignKey(BaseProduct, on_delete=models.SET_NULL, null=True, verbose_name='produto') product_count = models.IntegerField('unidades') class", "def get_items(self): return CartItem.objects.filter(cart=self) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE, verbose_name='carrinho de compras')", "em aberto', help_text='Determina se a compra do carrinho está em aberto.') class Meta:", "= models.IntegerField('unidades') class Meta: verbose_name = 'item do carrinho' verbose_name_plural = 'itens dos", "from django.db import models from liberaction.users.models import User from liberaction.core.models import BaseProduct class", "__str__(self): return f'Cart #{self.cart.id} - {self.product}' class Sale(models.Model): buyer = models.ForeignKey(User,on_delete=models.SET_NULL, null=True) cart", "compra do carrinho está em aberto.') class Meta: verbose_name = 'carrinho de compras'", "= 'carrinhos de compras' def __str__(self): return f'Carrinho #{self.id}' def get_items(self): return CartItem.objects.filter(cart=self)", "liberaction.core.models import BaseProduct class Cart(models.Model): is_open = models.BooleanField(default=True, verbose_name='Carrinho em aberto', help_text='Determina se", "models from liberaction.users.models import User from liberaction.core.models import BaseProduct class Cart(models.Model): is_open =", "'itens dos carrinhos' def __str__(self): return f'Cart #{self.cart.id} - {self.product}' class Sale(models.Model): buyer", "class Meta: verbose_name = 'carrinho de compras' verbose_name_plural = 'carrinhos de compras' def", "= 'itens dos carrinhos' def __str__(self): return f'Cart #{self.cart.id} - {self.product}' class Sale(models.Model):", "#{self.cart.id} - {self.product}' class Sale(models.Model): buyer = models.ForeignKey(User,on_delete=models.SET_NULL, null=True) cart = models.OneToOneField(Cart, on_delete=models.CASCADE,", "BaseProduct class Cart(models.Model): is_open = models.BooleanField(default=True, verbose_name='Carrinho em aberto', help_text='Determina se a compra", "'vendas' def __str__(self): return f'Sale #{self.id} - {self.buyer}' def get_items(self): return self.cart.get_items() def", "def get_subtotal(self): subtotal = 0 for i in self.get_items(): subtotal += i.product.price return", "return f'Carrinho #{self.id}' def get_items(self): return CartItem.objects.filter(cart=self) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE,", "do carrinho' verbose_name_plural = 'itens dos carrinhos' def __str__(self): return f'Cart #{self.cart.id} -", "help_text='Determina se a compra do carrinho está em aberto.') class Meta: verbose_name =", "f'Cart #{self.cart.id} - {self.product}' class Sale(models.Model): buyer = models.ForeignKey(User,on_delete=models.SET_NULL, null=True) cart = models.OneToOneField(Cart,", "verbose_name='produto') product_count = models.IntegerField('unidades') class Meta: verbose_name = 'item do carrinho' verbose_name_plural =", "models.BooleanField(default=True, verbose_name='Carrinho em aberto', help_text='Determina se a compra do carrinho está em aberto.')", "= models.OneToOneField(Cart, on_delete=models.CASCADE, verbose_name='carrinho de compras') freight = models.FloatField('frete') class Meta: verbose_name =", "on_delete=models.CASCADE, verbose_name='carrinho de compras') freight = models.FloatField('frete') class Meta: verbose_name = 'venda' verbose_name_plural", "return f'Cart #{self.cart.id} - {self.product}' class Sale(models.Model): buyer = models.ForeignKey(User,on_delete=models.SET_NULL, null=True) cart =", "models.ForeignKey(BaseProduct, on_delete=models.SET_NULL, null=True, verbose_name='produto') product_count = models.IntegerField('unidades') class Meta: verbose_name = 'item do", "models.ForeignKey(Cart, on_delete=models.CASCADE, verbose_name='carrinho de compras') product = models.ForeignKey(BaseProduct, on_delete=models.SET_NULL, null=True, verbose_name='produto') product_count =", "Sale(models.Model): buyer = models.ForeignKey(User,on_delete=models.SET_NULL, null=True) cart = models.OneToOneField(Cart, on_delete=models.CASCADE, verbose_name='carrinho de compras') freight", "= 'venda' verbose_name_plural = 'vendas' def __str__(self): return f'Sale #{self.id} - {self.buyer}' def", "on_delete=models.SET_NULL, null=True, verbose_name='produto') product_count = models.IntegerField('unidades') class Meta: verbose_name = 'item do carrinho'", "models.OneToOneField(Cart, on_delete=models.CASCADE, verbose_name='carrinho de compras') freight = models.FloatField('frete') class Meta: verbose_name = 'venda'", "is_open = models.BooleanField(default=True, verbose_name='Carrinho em aberto', help_text='Determina se a compra do carrinho está", "verbose_name_plural = 'carrinhos de compras' def __str__(self): return f'Carrinho #{self.id}' def get_items(self): return", "import BaseProduct class Cart(models.Model): is_open = models.BooleanField(default=True, verbose_name='Carrinho em aberto', help_text='Determina se a", "= models.FloatField('frete') class Meta: verbose_name = 'venda' verbose_name_plural = 'vendas' def __str__(self): return", "Meta: verbose_name = 'carrinho de compras' verbose_name_plural = 'carrinhos de compras' def __str__(self):", "compras' def __str__(self): return f'Carrinho #{self.id}' def get_items(self): return CartItem.objects.filter(cart=self) class CartItem(models.Model): cart", "get_items(self): return self.cart.get_items() def get_subtotal(self): subtotal = 0 for i in self.get_items(): subtotal", "de compras' verbose_name_plural = 'carrinhos de compras' def __str__(self): return f'Carrinho #{self.id}' def", "User from liberaction.core.models import BaseProduct class Cart(models.Model): is_open = models.BooleanField(default=True, verbose_name='Carrinho em aberto',", "get_subtotal(self): subtotal = 0 for i in self.get_items(): subtotal += i.product.price return subtotal", "compras') freight = models.FloatField('frete') class Meta: verbose_name = 'venda' verbose_name_plural = 'vendas' def", "django.db import models from liberaction.users.models import User from liberaction.core.models import BaseProduct class Cart(models.Model):", "import User from liberaction.core.models import BaseProduct class Cart(models.Model): is_open = models.BooleanField(default=True, verbose_name='Carrinho em", "verbose_name = 'item do carrinho' verbose_name_plural = 'itens dos carrinhos' def __str__(self): return", "= models.ForeignKey(User,on_delete=models.SET_NULL, null=True) cart = models.OneToOneField(Cart, on_delete=models.CASCADE, verbose_name='carrinho de compras') freight = models.FloatField('frete')", "{self.product}' class Sale(models.Model): buyer = models.ForeignKey(User,on_delete=models.SET_NULL, null=True) cart = models.OneToOneField(Cart, on_delete=models.CASCADE, verbose_name='carrinho de", "- {self.product}' class Sale(models.Model): buyer = models.ForeignKey(User,on_delete=models.SET_NULL, null=True) cart = models.OneToOneField(Cart, on_delete=models.CASCADE, verbose_name='carrinho", "models.ForeignKey(User,on_delete=models.SET_NULL, null=True) cart = models.OneToOneField(Cart, on_delete=models.CASCADE, verbose_name='carrinho de compras') freight = models.FloatField('frete') class", "cart = models.OneToOneField(Cart, on_delete=models.CASCADE, verbose_name='carrinho de compras') freight = models.FloatField('frete') class Meta: verbose_name" ]
[ "10:20 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('christelle', '0004_remove_about_fonction'), ]", "Migration(migrations.Migration): dependencies = [ ('christelle', '0004_remove_about_fonction'), ] operations = [ migrations.RenameField( model_name='contact', old_name='nom',", "migrations class Migration(migrations.Migration): dependencies = [ ('christelle', '0004_remove_about_fonction'), ] operations = [ migrations.RenameField(", "Django 3.2.7 on 2021-10-22 10:20 from django.db import migrations class Migration(migrations.Migration): dependencies =", "import migrations class Migration(migrations.Migration): dependencies = [ ('christelle', '0004_remove_about_fonction'), ] operations = [", "2021-10-22 10:20 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('christelle', '0004_remove_about_fonction'),", "3.2.7 on 2021-10-22 10:20 from django.db import migrations class Migration(migrations.Migration): dependencies = [", "django.db import migrations class Migration(migrations.Migration): dependencies = [ ('christelle', '0004_remove_about_fonction'), ] operations =", "on 2021-10-22 10:20 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('christelle',", "Generated by Django 3.2.7 on 2021-10-22 10:20 from django.db import migrations class Migration(migrations.Migration):", "= [ ('christelle', '0004_remove_about_fonction'), ] operations = [ migrations.RenameField( model_name='contact', old_name='nom', new_name='name', ),", "by Django 3.2.7 on 2021-10-22 10:20 from django.db import migrations class Migration(migrations.Migration): dependencies", "class Migration(migrations.Migration): dependencies = [ ('christelle', '0004_remove_about_fonction'), ] operations = [ migrations.RenameField( model_name='contact',", "<reponame>OBAMARIE13/portfolios<filename>christelle/migrations/0005_rename_nom_contact_name.py<gh_stars>0 # Generated by Django 3.2.7 on 2021-10-22 10:20 from django.db import migrations", "[ ('christelle', '0004_remove_about_fonction'), ] operations = [ migrations.RenameField( model_name='contact', old_name='nom', new_name='name', ), ]", "# Generated by Django 3.2.7 on 2021-10-22 10:20 from django.db import migrations class", "dependencies = [ ('christelle', '0004_remove_about_fonction'), ] operations = [ migrations.RenameField( model_name='contact', old_name='nom', new_name='name',", "from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('christelle', '0004_remove_about_fonction'), ] operations" ]
[ "= LpVariable('Car B', lowBound=0, cat=LpInteger) #Objective Function problem += 20000*A + 45000*B, 'Objective", "# VARIABLES # 0 <= Car_A Integer # 0 <= Car_B Integer print(problem)", "= LpVariable('Car A', lowBound=0, cat=LpInteger) B = LpVariable('Car B', lowBound=0, cat=LpInteger) #Objective Function", "20000*A + 45000*B, 'Objective Function' #Constraints problem += 4*A + 5*B <= 30,", "+ 45000*Car_B + 0 # SUBJECT TO # Designer_Constraint: 4 Car_A + 5", "6 Car_B <= 30 # Machine_Constraint: 2 Car_A + 7 Car_B <= 30", "30 # VARIABLES # 0 <= Car_A Integer # 0 <= Car_B Integer", "Made: \", A.varValue) print(\"Number of Car B Made: \", B.varValue) print(\"Total Profit: \",", "Create Decision Variables A = LpVariable('Car A', lowBound=0, cat=LpInteger) B = LpVariable('Car B',", "of LpProblem problem = LpProblem('Car Factory', LpMaximize) # Create Decision Variables A =", "'Objective Function' #Constraints problem += 4*A + 5*B <= 30, 'Designer Constraint' problem", "<= 30 # VARIABLES # 0 <= Car_A Integer # 0 <= Car_B", "Integer print(problem) print(\"Current Status: \", LpStatus[problem.status]) problem.solve() print(\"Number of Car A Made: \",", "+ 7 Car_B <= 30 # VARIABLES # 0 <= Car_A Integer #", "cat=LpInteger) #Objective Function problem += 20000*A + 45000*B, 'Objective Function' #Constraints problem +=", "# Create an Instance of LpProblem problem = LpProblem('Car Factory', LpMaximize) # Create", "print(problem) print(\"Current Status: \", LpStatus[problem.status]) problem.solve() print(\"Number of Car A Made: \", A.varValue)", "Variables A = LpVariable('Car A', lowBound=0, cat=LpInteger) B = LpVariable('Car B', lowBound=0, cat=LpInteger)", "B = LpVariable('Car B', lowBound=0, cat=LpInteger) #Objective Function problem += 20000*A + 45000*B,", "30 # Engineer_Constraint: 3 Car_A + 6 Car_B <= 30 # Machine_Constraint: 2", "<= 30, 'Engineer Constraint' problem += 2*A + 7*B <= 30, 'Machine Constraint'", "#Objective Function problem += 20000*A + 45000*B, 'Objective Function' #Constraints problem += 4*A", "from pulp import * # Create an Instance of LpProblem problem = LpProblem('Car", "Factory', LpMaximize) # Create Decision Variables A = LpVariable('Car A', lowBound=0, cat=LpInteger) B", "Constraint' problem += 2*A + 7*B <= 30, 'Machine Constraint' # Car_Profit: #", "# Car_Profit: # MAXIMIZE # 20000*Car_A + 45000*Car_B + 0 # SUBJECT TO", "Car_B <= 30 # Engineer_Constraint: 3 Car_A + 6 Car_B <= 30 #", "Function problem += 20000*A + 45000*B, 'Objective Function' #Constraints problem += 4*A +", "Decision Variables A = LpVariable('Car A', lowBound=0, cat=LpInteger) B = LpVariable('Car B', lowBound=0,", "<= 30 # Machine_Constraint: 2 Car_A + 7 Car_B <= 30 # VARIABLES", "Engineer_Constraint: 3 Car_A + 6 Car_B <= 30 # Machine_Constraint: 2 Car_A +", "LpMaximize) # Create Decision Variables A = LpVariable('Car A', lowBound=0, cat=LpInteger) B =", "<= 30 # Engineer_Constraint: 3 Car_A + 6 Car_B <= 30 # Machine_Constraint:", "\", A.varValue) print(\"Number of Car B Made: \", B.varValue) print(\"Total Profit: \", value(problem.objective))", "# MAXIMIZE # 20000*Car_A + 45000*Car_B + 0 # SUBJECT TO # Designer_Constraint:", "lowBound=0, cat=LpInteger) #Objective Function problem += 20000*A + 45000*B, 'Objective Function' #Constraints problem", "0 <= Car_B Integer print(problem) print(\"Current Status: \", LpStatus[problem.status]) problem.solve() print(\"Number of Car", "problem += 3*A + 6*B <= 30, 'Engineer Constraint' problem += 2*A +", "7*B <= 30, 'Machine Constraint' # Car_Profit: # MAXIMIZE # 20000*Car_A + 45000*Car_B", "4*A + 5*B <= 30, 'Designer Constraint' problem += 3*A + 6*B <=", "#Constraints problem += 4*A + 5*B <= 30, 'Designer Constraint' problem += 3*A", "45000*B, 'Objective Function' #Constraints problem += 4*A + 5*B <= 30, 'Designer Constraint'", "Car_B <= 30 # Machine_Constraint: 2 Car_A + 7 Car_B <= 30 #", "problem += 4*A + 5*B <= 30, 'Designer Constraint' problem += 3*A +", "problem += 20000*A + 45000*B, 'Objective Function' #Constraints problem += 4*A + 5*B", "Car_A + 6 Car_B <= 30 # Machine_Constraint: 2 Car_A + 7 Car_B", "+ 5 Car_B <= 30 # Engineer_Constraint: 3 Car_A + 6 Car_B <=", "30, 'Designer Constraint' problem += 3*A + 6*B <= 30, 'Engineer Constraint' problem", "+= 4*A + 5*B <= 30, 'Designer Constraint' problem += 3*A + 6*B", "<reponame>aminzayer/Amin-University-Data-Science<filename>Linear-Programing-Optimizing/Car-Factory-Problem.py # Import pulp from pulp import * # Create an Instance of", "30 # Machine_Constraint: 2 Car_A + 7 Car_B <= 30 # VARIABLES #", "print(\"Current Status: \", LpStatus[problem.status]) problem.solve() print(\"Number of Car A Made: \", A.varValue) print(\"Number", "5*B <= 30, 'Designer Constraint' problem += 3*A + 6*B <= 30, 'Engineer", "+ 6*B <= 30, 'Engineer Constraint' problem += 2*A + 7*B <= 30,", "+= 2*A + 7*B <= 30, 'Machine Constraint' # Car_Profit: # MAXIMIZE #", "+ 6 Car_B <= 30 # Machine_Constraint: 2 Car_A + 7 Car_B <=", "MAXIMIZE # 20000*Car_A + 45000*Car_B + 0 # SUBJECT TO # Designer_Constraint: 4", "# Import pulp from pulp import * # Create an Instance of LpProblem", "problem.solve() print(\"Number of Car A Made: \", A.varValue) print(\"Number of Car B Made:", "import * # Create an Instance of LpProblem problem = LpProblem('Car Factory', LpMaximize)", "LpVariable('Car A', lowBound=0, cat=LpInteger) B = LpVariable('Car B', lowBound=0, cat=LpInteger) #Objective Function problem", "cat=LpInteger) B = LpVariable('Car B', lowBound=0, cat=LpInteger) #Objective Function problem += 20000*A +", "<= Car_A Integer # 0 <= Car_B Integer print(problem) print(\"Current Status: \", LpStatus[problem.status])", "Car_A Integer # 0 <= Car_B Integer print(problem) print(\"Current Status: \", LpStatus[problem.status]) problem.solve()", "Car A Made: \", A.varValue) print(\"Number of Car B Made: \", B.varValue) print(\"Total", "+ 0 # SUBJECT TO # Designer_Constraint: 4 Car_A + 5 Car_B <=", "Car_Profit: # MAXIMIZE # 20000*Car_A + 45000*Car_B + 0 # SUBJECT TO #", "+ 5*B <= 30, 'Designer Constraint' problem += 3*A + 6*B <= 30,", "'Designer Constraint' problem += 3*A + 6*B <= 30, 'Engineer Constraint' problem +=", "problem += 2*A + 7*B <= 30, 'Machine Constraint' # Car_Profit: # MAXIMIZE", "4 Car_A + 5 Car_B <= 30 # Engineer_Constraint: 3 Car_A + 6", "Car_A + 5 Car_B <= 30 # Engineer_Constraint: 3 Car_A + 6 Car_B", "3 Car_A + 6 Car_B <= 30 # Machine_Constraint: 2 Car_A + 7", "45000*Car_B + 0 # SUBJECT TO # Designer_Constraint: 4 Car_A + 5 Car_B", "+ 7*B <= 30, 'Machine Constraint' # Car_Profit: # MAXIMIZE # 20000*Car_A +", "Function' #Constraints problem += 4*A + 5*B <= 30, 'Designer Constraint' problem +=", "Machine_Constraint: 2 Car_A + 7 Car_B <= 30 # VARIABLES # 0 <=", "Car_B <= 30 # VARIABLES # 0 <= Car_A Integer # 0 <=", "SUBJECT TO # Designer_Constraint: 4 Car_A + 5 Car_B <= 30 # Engineer_Constraint:", "Car_A + 7 Car_B <= 30 # VARIABLES # 0 <= Car_A Integer", "an Instance of LpProblem problem = LpProblem('Car Factory', LpMaximize) # Create Decision Variables", "= LpProblem('Car Factory', LpMaximize) # Create Decision Variables A = LpVariable('Car A', lowBound=0,", "30, 'Engineer Constraint' problem += 2*A + 7*B <= 30, 'Machine Constraint' #", "TO # Designer_Constraint: 4 Car_A + 5 Car_B <= 30 # Engineer_Constraint: 3", "# SUBJECT TO # Designer_Constraint: 4 Car_A + 5 Car_B <= 30 #", "+= 20000*A + 45000*B, 'Objective Function' #Constraints problem += 4*A + 5*B <=", "+ 45000*B, 'Objective Function' #Constraints problem += 4*A + 5*B <= 30, 'Designer", "# Engineer_Constraint: 3 Car_A + 6 Car_B <= 30 # Machine_Constraint: 2 Car_A", "'Machine Constraint' # Car_Profit: # MAXIMIZE # 20000*Car_A + 45000*Car_B + 0 #", "0 # SUBJECT TO # Designer_Constraint: 4 Car_A + 5 Car_B <= 30", "0 <= Car_A Integer # 0 <= Car_B Integer print(problem) print(\"Current Status: \",", "30, 'Machine Constraint' # Car_Profit: # MAXIMIZE # 20000*Car_A + 45000*Car_B + 0", "Instance of LpProblem problem = LpProblem('Car Factory', LpMaximize) # Create Decision Variables A", "'Engineer Constraint' problem += 2*A + 7*B <= 30, 'Machine Constraint' # Car_Profit:", "pulp from pulp import * # Create an Instance of LpProblem problem =", "* # Create an Instance of LpProblem problem = LpProblem('Car Factory', LpMaximize) #", "5 Car_B <= 30 # Engineer_Constraint: 3 Car_A + 6 Car_B <= 30", "2*A + 7*B <= 30, 'Machine Constraint' # Car_Profit: # MAXIMIZE # 20000*Car_A", "Car_B Integer print(problem) print(\"Current Status: \", LpStatus[problem.status]) problem.solve() print(\"Number of Car A Made:", "LpVariable('Car B', lowBound=0, cat=LpInteger) #Objective Function problem += 20000*A + 45000*B, 'Objective Function'", "Create an Instance of LpProblem problem = LpProblem('Car Factory', LpMaximize) # Create Decision", "LpProblem('Car Factory', LpMaximize) # Create Decision Variables A = LpVariable('Car A', lowBound=0, cat=LpInteger)", "6*B <= 30, 'Engineer Constraint' problem += 2*A + 7*B <= 30, 'Machine", "<= 30, 'Designer Constraint' problem += 3*A + 6*B <= 30, 'Engineer Constraint'", "B', lowBound=0, cat=LpInteger) #Objective Function problem += 20000*A + 45000*B, 'Objective Function' #Constraints", "A Made: \", A.varValue) print(\"Number of Car B Made: \", B.varValue) print(\"Total Profit:", "# 0 <= Car_B Integer print(problem) print(\"Current Status: \", LpStatus[problem.status]) problem.solve() print(\"Number of", "Constraint' problem += 3*A + 6*B <= 30, 'Engineer Constraint' problem += 2*A", "20000*Car_A + 45000*Car_B + 0 # SUBJECT TO # Designer_Constraint: 4 Car_A +", "<= Car_B Integer print(problem) print(\"Current Status: \", LpStatus[problem.status]) problem.solve() print(\"Number of Car A", "Designer_Constraint: 4 Car_A + 5 Car_B <= 30 # Engineer_Constraint: 3 Car_A +", "7 Car_B <= 30 # VARIABLES # 0 <= Car_A Integer # 0", "# 0 <= Car_A Integer # 0 <= Car_B Integer print(problem) print(\"Current Status:", "3*A + 6*B <= 30, 'Engineer Constraint' problem += 2*A + 7*B <=", "Import pulp from pulp import * # Create an Instance of LpProblem problem", "A = LpVariable('Car A', lowBound=0, cat=LpInteger) B = LpVariable('Car B', lowBound=0, cat=LpInteger) #Objective", "lowBound=0, cat=LpInteger) B = LpVariable('Car B', lowBound=0, cat=LpInteger) #Objective Function problem += 20000*A", "LpProblem problem = LpProblem('Car Factory', LpMaximize) # Create Decision Variables A = LpVariable('Car", "\", LpStatus[problem.status]) problem.solve() print(\"Number of Car A Made: \", A.varValue) print(\"Number of Car", "of Car A Made: \", A.varValue) print(\"Number of Car B Made: \", B.varValue)", "Integer # 0 <= Car_B Integer print(problem) print(\"Current Status: \", LpStatus[problem.status]) problem.solve() print(\"Number", "+= 3*A + 6*B <= 30, 'Engineer Constraint' problem += 2*A + 7*B", "# Machine_Constraint: 2 Car_A + 7 Car_B <= 30 # VARIABLES # 0", "pulp import * # Create an Instance of LpProblem problem = LpProblem('Car Factory',", "problem = LpProblem('Car Factory', LpMaximize) # Create Decision Variables A = LpVariable('Car A',", "A', lowBound=0, cat=LpInteger) B = LpVariable('Car B', lowBound=0, cat=LpInteger) #Objective Function problem +=", "# Create Decision Variables A = LpVariable('Car A', lowBound=0, cat=LpInteger) B = LpVariable('Car", "print(\"Number of Car A Made: \", A.varValue) print(\"Number of Car B Made: \",", "Status: \", LpStatus[problem.status]) problem.solve() print(\"Number of Car A Made: \", A.varValue) print(\"Number of", "<= 30, 'Machine Constraint' # Car_Profit: # MAXIMIZE # 20000*Car_A + 45000*Car_B +", "LpStatus[problem.status]) problem.solve() print(\"Number of Car A Made: \", A.varValue) print(\"Number of Car B", "# 20000*Car_A + 45000*Car_B + 0 # SUBJECT TO # Designer_Constraint: 4 Car_A", "# Designer_Constraint: 4 Car_A + 5 Car_B <= 30 # Engineer_Constraint: 3 Car_A", "VARIABLES # 0 <= Car_A Integer # 0 <= Car_B Integer print(problem) print(\"Current", "2 Car_A + 7 Car_B <= 30 # VARIABLES # 0 <= Car_A", "Constraint' # Car_Profit: # MAXIMIZE # 20000*Car_A + 45000*Car_B + 0 # SUBJECT" ]
[ "(2, _('Tuesday')), (3, _('Wednesday')), (4, _('Thursday')), (5, _('Friday')), (6, _('Saturday')), (7, _('Sunday')), )", "DAY_CHOICES = ( (1, _('Monday')), (2, _('Tuesday')), (3, _('Wednesday')), (4, _('Thursday')), (5, _('Friday')),", "= ( (1, _('Monday')), (2, _('Tuesday')), (3, _('Wednesday')), (4, _('Thursday')), (5, _('Friday')), (6,", "(1, _('Monday')), (2, _('Tuesday')), (3, _('Wednesday')), (4, _('Thursday')), (5, _('Friday')), (6, _('Saturday')), (7,", "django.utils.translation import gettext as _ DAY_CHOICES = ( (1, _('Monday')), (2, _('Tuesday')), (3,", "import gettext as _ DAY_CHOICES = ( (1, _('Monday')), (2, _('Tuesday')), (3, _('Wednesday')),", "_ DAY_CHOICES = ( (1, _('Monday')), (2, _('Tuesday')), (3, _('Wednesday')), (4, _('Thursday')), (5,", "gettext as _ DAY_CHOICES = ( (1, _('Monday')), (2, _('Tuesday')), (3, _('Wednesday')), (4,", "_('Monday')), (2, _('Tuesday')), (3, _('Wednesday')), (4, _('Thursday')), (5, _('Friday')), (6, _('Saturday')), (7, _('Sunday')),", "as _ DAY_CHOICES = ( (1, _('Monday')), (2, _('Tuesday')), (3, _('Wednesday')), (4, _('Thursday')),", "( (1, _('Monday')), (2, _('Tuesday')), (3, _('Wednesday')), (4, _('Thursday')), (5, _('Friday')), (6, _('Saturday')),", "from django.utils.translation import gettext as _ DAY_CHOICES = ( (1, _('Monday')), (2, _('Tuesday'))," ]
[ "# Generated by Django 3.1.12 on 2021-07-12 09:25 from django.db import migrations, models", "import migrations, models class Migration(migrations.Migration): dependencies = [ (\"polio\", \"0016_config\"), ] operations =", "class Migration(migrations.Migration): dependencies = [ (\"polio\", \"0016_config\"), ] operations = [ migrations.AddField( model_name=\"campaign\",", "2021-07-12 09:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ (\"polio\",", "09:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ (\"polio\", \"0016_config\"),", "(\"polio\", \"0016_config\"), ] operations = [ migrations.AddField( model_name=\"campaign\", name=\"gpei_email\", field=models.EmailField(blank=True, max_length=254, null=True), ),", "migrations, models class Migration(migrations.Migration): dependencies = [ (\"polio\", \"0016_config\"), ] operations = [", "Generated by Django 3.1.12 on 2021-07-12 09:25 from django.db import migrations, models class", "= [ (\"polio\", \"0016_config\"), ] operations = [ migrations.AddField( model_name=\"campaign\", name=\"gpei_email\", field=models.EmailField(blank=True, max_length=254,", "Django 3.1.12 on 2021-07-12 09:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies", "Migration(migrations.Migration): dependencies = [ (\"polio\", \"0016_config\"), ] operations = [ migrations.AddField( model_name=\"campaign\", name=\"gpei_email\",", "3.1.12 on 2021-07-12 09:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies =", "from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ (\"polio\", \"0016_config\"), ]", "django.db import migrations, models class Migration(migrations.Migration): dependencies = [ (\"polio\", \"0016_config\"), ] operations", "\"0016_config\"), ] operations = [ migrations.AddField( model_name=\"campaign\", name=\"gpei_email\", field=models.EmailField(blank=True, max_length=254, null=True), ), ]", "on 2021-07-12 09:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [", "dependencies = [ (\"polio\", \"0016_config\"), ] operations = [ migrations.AddField( model_name=\"campaign\", name=\"gpei_email\", field=models.EmailField(blank=True,", "models class Migration(migrations.Migration): dependencies = [ (\"polio\", \"0016_config\"), ] operations = [ migrations.AddField(", "by Django 3.1.12 on 2021-07-12 09:25 from django.db import migrations, models class Migration(migrations.Migration):", "[ (\"polio\", \"0016_config\"), ] operations = [ migrations.AddField( model_name=\"campaign\", name=\"gpei_email\", field=models.EmailField(blank=True, max_length=254, null=True)," ]
[ ") grey = threshold.Execute( black ) checker = sitk.CheckerBoardImageFilter(); pattern = [ 0,", "10 ) threshold.SetOutsideValue ( 100 ) white = threshold.Execute( black ) threshold.SetOutsideValue (", "i in [ 0, 1, 2 ] : pattern[ i ] = int(", "threshold = sitk.ThresholdImageFilter() threshold.SetLower( 10 ) threshold.SetOutsideValue ( 100 ) white = threshold.Execute(", "threshold.SetLower( 10 ) threshold.SetOutsideValue ( 100 ) white = threshold.Execute( black ) threshold.SetOutsideValue", "spacing[ i ] / gridSpacing ) pattern[ 0 ] = 1 print pattern", "30; file = sys.argv[1] image = sitk.ReadImage( file ) size = image.GetSize(); black", "black.SetOrigin( image.GetOrigin() ) spacing = image.GetSpacing(); black.SetSpacing( spacing ) black.SetDirection( image.GetDirection() ) threshold", "= [ 0, 0, 0 ] for i in [ 0, 1, 2", "print pattern checker.SetCheckerPattern( pattern ); board = checker.Execute( grey, white ); sitk.WriteImage( board", "image.GetSize(); black = sitk.Image( size, sitk.sitkUInt8 ) black.SetOrigin( image.GetOrigin() ) spacing = image.GetSpacing();", "import SimpleITK as sitk import sys gridSpacing = 30; file = sys.argv[1] image", "50 ) grey = threshold.Execute( black ) checker = sitk.CheckerBoardImageFilter(); pattern = [", "checker = sitk.CheckerBoardImageFilter(); pattern = [ 0, 0, 0 ] for i in", "] / gridSpacing ) pattern[ 0 ] = 1 print pattern checker.SetCheckerPattern( pattern", ") black.SetDirection( image.GetDirection() ) threshold = sitk.ThresholdImageFilter() threshold.SetLower( 10 ) threshold.SetOutsideValue ( 100", ": pattern[ i ] = int( size[ i ] * spacing[ i ]", "spacing ) black.SetDirection( image.GetDirection() ) threshold = sitk.ThresholdImageFilter() threshold.SetLower( 10 ) threshold.SetOutsideValue (", "i ] * spacing[ i ] / gridSpacing ) pattern[ 0 ] =", "<filename>tools/checkerBoard.py import SimpleITK as sitk import sys gridSpacing = 30; file = sys.argv[1]", "gridSpacing = 30; file = sys.argv[1] image = sitk.ReadImage( file ) size =", ") spacing = image.GetSpacing(); black.SetSpacing( spacing ) black.SetDirection( image.GetDirection() ) threshold = sitk.ThresholdImageFilter()", "black.SetSpacing( spacing ) black.SetDirection( image.GetDirection() ) threshold = sitk.ThresholdImageFilter() threshold.SetLower( 10 ) threshold.SetOutsideValue", "white = threshold.Execute( black ) threshold.SetOutsideValue ( 50 ) grey = threshold.Execute( black", "0 ] for i in [ 0, 1, 2 ] : pattern[ i", "sys gridSpacing = 30; file = sys.argv[1] image = sitk.ReadImage( file ) size", "= sitk.ThresholdImageFilter() threshold.SetLower( 10 ) threshold.SetOutsideValue ( 100 ) white = threshold.Execute( black", "100 ) white = threshold.Execute( black ) threshold.SetOutsideValue ( 50 ) grey =", "image.GetOrigin() ) spacing = image.GetSpacing(); black.SetSpacing( spacing ) black.SetDirection( image.GetDirection() ) threshold =", ") threshold = sitk.ThresholdImageFilter() threshold.SetLower( 10 ) threshold.SetOutsideValue ( 100 ) white =", "1, 2 ] : pattern[ i ] = int( size[ i ] *", "= 1 print pattern checker.SetCheckerPattern( pattern ); board = checker.Execute( grey, white );", "black.SetDirection( image.GetDirection() ) threshold = sitk.ThresholdImageFilter() threshold.SetLower( 10 ) threshold.SetOutsideValue ( 100 )", ") checker = sitk.CheckerBoardImageFilter(); pattern = [ 0, 0, 0 ] for i", "[ 0, 0, 0 ] for i in [ 0, 1, 2 ]", "sitk.ThresholdImageFilter() threshold.SetLower( 10 ) threshold.SetOutsideValue ( 100 ) white = threshold.Execute( black )", "i ] / gridSpacing ) pattern[ 0 ] = 1 print pattern checker.SetCheckerPattern(", "= sitk.Image( size, sitk.sitkUInt8 ) black.SetOrigin( image.GetOrigin() ) spacing = image.GetSpacing(); black.SetSpacing( spacing", "checker.SetCheckerPattern( pattern ); board = checker.Execute( grey, white ); sitk.WriteImage( board , \"output.nii.gz\"", "gridSpacing ) pattern[ 0 ] = 1 print pattern checker.SetCheckerPattern( pattern ); board", "pattern checker.SetCheckerPattern( pattern ); board = checker.Execute( grey, white ); sitk.WriteImage( board ,", "= image.GetSize(); black = sitk.Image( size, sitk.sitkUInt8 ) black.SetOrigin( image.GetOrigin() ) spacing =", "( 100 ) white = threshold.Execute( black ) threshold.SetOutsideValue ( 50 ) grey", "= sitk.ReadImage( file ) size = image.GetSize(); black = sitk.Image( size, sitk.sitkUInt8 )", "size, sitk.sitkUInt8 ) black.SetOrigin( image.GetOrigin() ) spacing = image.GetSpacing(); black.SetSpacing( spacing ) black.SetDirection(", "sitk.CheckerBoardImageFilter(); pattern = [ 0, 0, 0 ] for i in [ 0,", "sitk.ReadImage( file ) size = image.GetSize(); black = sitk.Image( size, sitk.sitkUInt8 ) black.SetOrigin(", "] = int( size[ i ] * spacing[ i ] / gridSpacing )", "1 print pattern checker.SetCheckerPattern( pattern ); board = checker.Execute( grey, white ); sitk.WriteImage(", "import sys gridSpacing = 30; file = sys.argv[1] image = sitk.ReadImage( file )", "black ) checker = sitk.CheckerBoardImageFilter(); pattern = [ 0, 0, 0 ] for", "threshold.SetOutsideValue ( 50 ) grey = threshold.Execute( black ) checker = sitk.CheckerBoardImageFilter(); pattern", "] for i in [ 0, 1, 2 ] : pattern[ i ]", "= image.GetSpacing(); black.SetSpacing( spacing ) black.SetDirection( image.GetDirection() ) threshold = sitk.ThresholdImageFilter() threshold.SetLower( 10", "threshold.Execute( black ) checker = sitk.CheckerBoardImageFilter(); pattern = [ 0, 0, 0 ]", "in [ 0, 1, 2 ] : pattern[ i ] = int( size[", "pattern ); board = checker.Execute( grey, white ); sitk.WriteImage( board , \"output.nii.gz\" )", "= 30; file = sys.argv[1] image = sitk.ReadImage( file ) size = image.GetSize();", "black ) threshold.SetOutsideValue ( 50 ) grey = threshold.Execute( black ) checker =", ") threshold.SetOutsideValue ( 100 ) white = threshold.Execute( black ) threshold.SetOutsideValue ( 50", "image.GetSpacing(); black.SetSpacing( spacing ) black.SetDirection( image.GetDirection() ) threshold = sitk.ThresholdImageFilter() threshold.SetLower( 10 )", "black = sitk.Image( size, sitk.sitkUInt8 ) black.SetOrigin( image.GetOrigin() ) spacing = image.GetSpacing(); black.SetSpacing(", ") black.SetOrigin( image.GetOrigin() ) spacing = image.GetSpacing(); black.SetSpacing( spacing ) black.SetDirection( image.GetDirection() )", "= int( size[ i ] * spacing[ i ] / gridSpacing ) pattern[", "threshold.SetOutsideValue ( 100 ) white = threshold.Execute( black ) threshold.SetOutsideValue ( 50 )", "i ] = int( size[ i ] * spacing[ i ] / gridSpacing", "grey = threshold.Execute( black ) checker = sitk.CheckerBoardImageFilter(); pattern = [ 0, 0,", "0, 0, 0 ] for i in [ 0, 1, 2 ] :", ") pattern[ 0 ] = 1 print pattern checker.SetCheckerPattern( pattern ); board =", "file = sys.argv[1] image = sitk.ReadImage( file ) size = image.GetSize(); black =", "file ) size = image.GetSize(); black = sitk.Image( size, sitk.sitkUInt8 ) black.SetOrigin( image.GetOrigin()", "= threshold.Execute( black ) checker = sitk.CheckerBoardImageFilter(); pattern = [ 0, 0, 0", "size = image.GetSize(); black = sitk.Image( size, sitk.sitkUInt8 ) black.SetOrigin( image.GetOrigin() ) spacing", "] : pattern[ i ] = int( size[ i ] * spacing[ i", "/ gridSpacing ) pattern[ 0 ] = 1 print pattern checker.SetCheckerPattern( pattern );", "= sys.argv[1] image = sitk.ReadImage( file ) size = image.GetSize(); black = sitk.Image(", "0, 1, 2 ] : pattern[ i ] = int( size[ i ]", ") white = threshold.Execute( black ) threshold.SetOutsideValue ( 50 ) grey = threshold.Execute(", "* spacing[ i ] / gridSpacing ) pattern[ 0 ] = 1 print", "for i in [ 0, 1, 2 ] : pattern[ i ] =", "as sitk import sys gridSpacing = 30; file = sys.argv[1] image = sitk.ReadImage(", ") threshold.SetOutsideValue ( 50 ) grey = threshold.Execute( black ) checker = sitk.CheckerBoardImageFilter();", "( 50 ) grey = threshold.Execute( black ) checker = sitk.CheckerBoardImageFilter(); pattern =", "= threshold.Execute( black ) threshold.SetOutsideValue ( 50 ) grey = threshold.Execute( black )", "pattern = [ 0, 0, 0 ] for i in [ 0, 1,", "] * spacing[ i ] / gridSpacing ) pattern[ 0 ] = 1", ") size = image.GetSize(); black = sitk.Image( size, sitk.sitkUInt8 ) black.SetOrigin( image.GetOrigin() )", "sys.argv[1] image = sitk.ReadImage( file ) size = image.GetSize(); black = sitk.Image( size,", "sitk.Image( size, sitk.sitkUInt8 ) black.SetOrigin( image.GetOrigin() ) spacing = image.GetSpacing(); black.SetSpacing( spacing )", "= sitk.CheckerBoardImageFilter(); pattern = [ 0, 0, 0 ] for i in [", "2 ] : pattern[ i ] = int( size[ i ] * spacing[", "] = 1 print pattern checker.SetCheckerPattern( pattern ); board = checker.Execute( grey, white", "size[ i ] * spacing[ i ] / gridSpacing ) pattern[ 0 ]", "0 ] = 1 print pattern checker.SetCheckerPattern( pattern ); board = checker.Execute( grey,", "SimpleITK as sitk import sys gridSpacing = 30; file = sys.argv[1] image =", "sitk.sitkUInt8 ) black.SetOrigin( image.GetOrigin() ) spacing = image.GetSpacing(); black.SetSpacing( spacing ) black.SetDirection( image.GetDirection()", "image = sitk.ReadImage( file ) size = image.GetSize(); black = sitk.Image( size, sitk.sitkUInt8", "spacing = image.GetSpacing(); black.SetSpacing( spacing ) black.SetDirection( image.GetDirection() ) threshold = sitk.ThresholdImageFilter() threshold.SetLower(", "threshold.Execute( black ) threshold.SetOutsideValue ( 50 ) grey = threshold.Execute( black ) checker", "image.GetDirection() ) threshold = sitk.ThresholdImageFilter() threshold.SetLower( 10 ) threshold.SetOutsideValue ( 100 ) white", "int( size[ i ] * spacing[ i ] / gridSpacing ) pattern[ 0", "sitk import sys gridSpacing = 30; file = sys.argv[1] image = sitk.ReadImage( file", "pattern[ i ] = int( size[ i ] * spacing[ i ] /", "[ 0, 1, 2 ] : pattern[ i ] = int( size[ i", "0, 0 ] for i in [ 0, 1, 2 ] : pattern[", "pattern[ 0 ] = 1 print pattern checker.SetCheckerPattern( pattern ); board = checker.Execute(" ]
[]
[ "started_field = (3, 'DATETIME(started) as \"started [timestamp]\"', 'From') finished_field = (4, 'DATETIME(finished) as", "as pname, Tasks.description as description, \" \" Tracks.started as started, Tracks.finished as finished", "Tasks.project_id == Projects.id AND \" \" finished == '' \" \" {where_date_clause}\".format( where_date_clause=where_date_clause,", "\"UPDATE Tracks SET finished=? WHERE id=?\", (finished, track_id) ) self.conn.commit() return finished def", "MAX(Tracks.id) FROM Tracks \" \" {where_clause} \" \" GROUP BY Tracks.task_id \" \"", "= pname.encode('utf8') where_project_clause = \"pname == ? AND \" params.append(pname) if started and", "project_field]) if mask & TS_GROUP_BY['project']: clause.add(project_field) if mask & TS_GROUP_BY['track']: clause.update([task_field, project_field, started_field,", "= '' between_clause = '' params = [] if not also_unfinished: where_clause =", "as tid, Tasks.name as tname, Projects.name as pname, \" \" DATE(started) as 'started", "(2, 'pname', 'Project') started_field = (3, 'DATETIME(started) as \"started [timestamp]\"', 'From') finished_field =", "if customer: return customer self.cursor.execute( \"INSERT INTO Customers ('name')\" \"VALUES ('{name:s}')\" .format(name=customer) )", "finished=started+timedelta(seconds=18600)) self.create_track(last_task, started=started+timedelta(seconds=19600), finished=started+timedelta(seconds=20600)) # Add a Project #2 self.create_project('p2', 'Test Project #1')", "import time import datetime from datetime import timedelta import operator from tabulate import", "'pname', 'Project') started_field = (3, 'DATETIME(started) as \"started [timestamp]\"', 'From') finished_field = (4,", "Projects.id AND \" \" trid == %d\" % tid ) return self.cursor.fetchone() def", "mask & TS_GROUP_BY['project']: clause.add(project_field) if mask & TS_GROUP_BY['track']: clause.update([task_field, project_field, started_field, finished_field]) clause.add(spent_field)", "== Projects.id AND \" \" (\" \" DATE(started) BETWEEN ? AND ?\" \"", "Tasks.id as tid, Tasks.name as tname, Projects.name as pname, \" \" Tracks.id as", "self.cursor.fetchone() #print('filled projects', project) # Add the Task tasks = [] last_task =", "\"finished [timestamp]\"', 'To') spent_field = (5, 'spent', 'Time Spent') clause = set() if", "Projects.name as pname, Tasks.description as description, \" \" Tracks.started as started, Tracks.finished as", "== ? AND \" params.append(pname) if started and finished: where_date_clause = \"AND DATE(Tracks.started)", "tid, Tasks.name as tname, Projects.name as pname, \" \" Tracks.id as track_id, Tracks.started", "BY id LIMIT 1\") project = self.cursor.fetchone() #print('filled projects', project) # Add the", "\"\"\"Get list of project including a field is a project is finished\"\"\" where_clause", "== ''\") return self.cursor.fetchall() def get_active_task(self, started='', finished='', tname='', pname=''): \"\"\"Get an active", "the task info\"\"\" self.cursor.execute( \"UPDATE Tasks \" \"SET name=?, description=?\" \"WHERE id=?\", (", "clause = set() if mask & TS_GROUP_BY['date']: clause.add(date_field) if mask & TS_GROUP_BY['task']: clause.update([task_field,", "pname.encode('utf8') where_project_clause = \"pname == ? AND \" params.append(pname) if started and finished:", "Tasks \" \"WHERE \" \" Tasks.project_id == Projects.id AND \" \" Tracks.task_id ==", "update_track(self, track_id, started, finished, is_billed): \"\"\"Updates the time was spend and is billed", "\"\".format(where_clause=where_clause), (started, finished) ) self.conn.commit() # TIMESHEET def get_group_by_clause(self, mask): \"\"\"Makes a GROUP", "? AND ?\" \" {where_clause}\" \"\".format(where_clause=where_clause), (started, finished) ) self.conn.commit() # TIMESHEET def", "\" \" description as description \" \"FROM Projects \" \"WHERE \" \" pid", "{where_project_clause}\" \" Tracks.task_id == tid AND \" \" Tasks.project_id == Projects.id AND \"", "\" \"WHERE \" \" Projects.name == ?\", (pname.encode('utf8'),) ) return self.cursor.fetchone() def update_project(self,", "a GROUP BY clause by bit mask\"\"\" def set_group_by_clause(bits, value, group_by): \"\"\"Add a", "pname, Tasks.description as description, \" \" Tracks.started as started, Tracks.finished as finished \"", "INTEGER PRIMARY KEY, ' ' customer_id INTEGER, ' ' name VARCHAR UNIQUE COLLATE", "# PROJECTS def get_project_by_name(self, pname): self.cursor.execute( \"SELECT \" \" id as pid, name", "where_clause=where_clause, first_limit_clause=first_limit_clause, last_limit_clause=last_limit_clause) ) return self.cursor.fetchall() def create_project(self, pname, description=''): \"\"\"Create a project\"\"\"", "import os import sqlite3 import random import string import time import datetime from", "group_by = \"%s,\" % group_by group_by = '{group_by} {value}'.format(group_by=group_by, value=value) return group_by group_by", "name FROM Customers \" \"WHERE name == '{name:s}'\".format(name=customer) ) customer = self.cursor.fetchone() if", "\" \\ \" AND ? \" params.extend([started, finished]) self.cursor.execute( \"SELECT \" \" Tasks.id", ") return self.cursor.fetchone() def update_task(self, tid, name, description=''): \"\"\"Updates the task info\"\"\" self.cursor.execute(", "def update_track(self, track_id, started, finished, is_billed): \"\"\"Updates the time was spend and is", "where_clause = \"AND NOT finished == '' \" self.cursor.execute( \"DELETE \" \" FROM", "'project_id') \" \"values('%s', '%s')\" % (name, project_id) ) self.conn.commit() return self.cursor.lastrowid def fill(self):", "= \"GROUP BY %s \" % group_by return group_by def get_timesheet_fields(self, mask, get_headers=False):", "\"\"\" Gets the time was spent for a task/project\"\"\" params = [] only_billed_clause", "\"SELECT \" \" Tasks.id as tid, Tasks.name as tname, Projects.name as pname, \"", "if mask & TS_GROUP_BY['project']: clause.add(project_field) if mask & TS_GROUP_BY['track']: clause.update([task_field, project_field, started_field, finished_field])", "limit=10, add_activity=False): \"\"\"Lists of last tasks\"\"\" activity_field = '' if add_activity: activity_field =", "project=0b1000, task=0b0100, track=0b0010, date=0b0001 ) class Database: def init_db(self, db_path): self.conn = sqlite3.connect(", "Add a Project #2 self.create_project('p2', 'Test Project #1') self.cursor.execute(\"SELECT * FROM Projects ORDER", "timedelta(days=3) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3600)) started = datetime.datetime.now() - timedelta(days=2) self.create_track(last_task, started=started,", "\"{first_limit_clause}\" \"SELECT \" \" Tasks.id as tid, Tasks.name as tname, Projects.id as pid,", "{where_task_clause}\" \" {where_project_clause}\" \" Tracks.task_id == tid AND \" \" Tasks.project_id == Projects.id\"", "\"\"\"Add a field to group_by clause\"\"\" if mask & bits: if group_by: group_by", "'%s')\" % (name, project_id) ) self.conn.commit() return self.cursor.lastrowid def fill(self): \"\"\"Fill with the", "track_id, started, finished, is_billed): \"\"\"Updates the time was spend and is billed flag", "customers) # Add a Project self.create_project('p1', 'Test Project #1') self.cursor.execute(\"SELECT * FROM Projects", "to group_by clause\"\"\" if mask & bits: if group_by: group_by = \"%s,\" %", "description): \"\"\"Updates a project\"\"\" self.cursor.execute( \"UPDATE Projects \" \"SET name=?, description=?\" \"WHERE id=?\",", "# TASKS def get_tasks(self, limit=10, add_activity=False): \"\"\"Lists of last tasks\"\"\" activity_field = ''", "list of last tasks between dates including unfinished\"\"\" where_clause = first_limit_clause = last_limit_clause", "as tname, Projects.name as pname, \" \" Tracks.id as trid, Tracks.started as started,", "Projects.id AND \" \" finished == ''\") return self.cursor.fetchall() def get_active_task(self, started='', finished='',", "\"\"\"Get prepared select's clause list of fields\"\"\" fields = self.get_timesheet_fields(mask) return ', '.join(fields)", "finished - 9-item sequence, not float if not started: started = datetime.datetime.now() self.cursor.execute(", "\"ORDER BY Projects.id {last_limit_clause}\".format( where_clause=where_clause, first_limit_clause=first_limit_clause, last_limit_clause=last_limit_clause) ) return self.cursor.fetchall() def create_project(self, pname,", "= datetime.datetime.now() if started and config.BT_TIMESHEET_ROUNDING and config.BT_ROUNDING_INCREMENT: delta = finished - started", "* FROM (\" last_limit_clause = \" DESC LIMIT %d) ORDER BY tid ASC\"", "\" Tasks.description as description \" \"FROM Tracks, Tasks, Projects \" \"WHERE \" \"", "Tracks.id as trid, Tracks.started as started, \" \" Tracks.finished as finished, \" \"", "dates including unfinished\"\"\" where_clause = first_limit_clause = last_limit_clause = '' if started and", "\"pname == ? AND \" if only_billed: only_billed_clause = \" AND Tracks.is_billed ==", "started, \" \" Tracks.finished as finished, \" \" Tracks.is_billed as is_billed \" \"FROM", "? AND ?\" \" AND NOT Tracks.finished == ''\" \" {only_billed_clause}\" \" )", "Tracks \" \" {where_clause} \" \" GROUP BY Tracks.task_id \" \" ) ORDER", "project_id) ) self.conn.commit() return self.cursor.lastrowid def fill(self): \"\"\"Fill with the test tasks\"\"\" self.cursor.execute('DELETE", "' id INTEGER PRIMARY KEY, ' ' project_id INTEGER REFERENCES Projects(id) ON DELETE", "= ''.join(random.choice( string.ascii_uppercase + string.digits) for _ in range(3)) self.cursor.execute( \"insert into Tasks", "self.cursor.execute(\"PRAGMA foreign_keys = ON\") # Create Tables if do the not exist #", "DESC LIMIT {limit:d}\".format( limit=limit, activity_field=activity_field) ) tasks = self.cursor.fetchall() return tasks def get_profiled_tasks(self,", "\" \" Tasks.project_id == Projects.id AND \" \" Tracks.task_id == Tasks.id AND \"", "Tasks ('name', 'project_id') \" \"VALUES \" \" (?, ?)\", ( name.encode('utf8'), pid )", "started=None): finished = datetime.datetime.now() if started and config.BT_TIMESHEET_ROUNDING and config.BT_ROUNDING_INCREMENT: delta = finished", "value, group_by): \"\"\"Add a field to group_by clause\"\"\" if mask & bits: if", "WHERE name == '{name}'\" \"\".format(name=pname.encode('utf8'))) self.conn.commit() # TASKS def get_tasks(self, limit=10, add_activity=False): \"\"\"Lists", "finished=started+timedelta(seconds=26600)) started = datetime.datetime.now() - timedelta(days=3) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3600)) started =", "self.conn.commit() def delete_task(self, tid): \"\"\"\"\"\" self.cursor.execute( \"DELETE FROM Tasks WHERE id == '{tid}'\".format(tid=tid))", "\" \" description as description \" \"FROM Projects \" \"WHERE \" \" Projects.name", "[timestamp]\"', 'To') spent_field = (5, 'spent', 'Time Spent') clause = set() if mask", "finished=finished, where_clause=where_clause, between_clause=between_clause), params ) return self.cursor.fetchall() def get_track_by_id(self, tid): self.cursor.execute( \"SELECT \"", "\"AND NOT finished == '' \" if started and finished: between_clause = \"AND", "\"\".format(started=started, finished=finished, where_task_clause=where_task_clause, where_project_clause=where_project_clause, group_by_clause=group_by_clause, only_billed_clause=only_billed_clause) ) #print(query) if group_by_mask: select_clause = self.get_timesheet_select_clause(group_by_mask)", "Projects ('name', 'description', created)\" \"VALUES (?, ?, ?)\", ( pname.encode('utf8'), description.encode('utf8'), str(datetime.datetime.now()) )", "'' \" self.cursor.execute( \"DELETE \" \" FROM Tracks \" \"WHERE \" \" DATE(started)", "\" Tracks.started as started, \" \" Tracks.finished as finished \" \"FROM Tracks, Tasks,", "{last_limit_clause}\".format( where_clause=where_clause, first_limit_clause=first_limit_clause, last_limit_clause=last_limit_clause) ) return self.cursor.fetchall() def create_project(self, pname, description=''): \"\"\"Create a", "\" SUM(STRFTIME('%s', finished)-STRFTIME('%s', started)) as spent,\" \" Tracks.started as started, \" \" Tracks.finished", "finished: where_date_clause = \"AND DATE(Tracks.started) \" \\ \" BETWEEN ? \" \\ \"", "as tname, Projects.name as pname, \" \" SUM(STRFTIME('%s', finished)-STRFTIME('%s', started)) as spent,\" \"", ") \" \"{group_by_clause} \" \"ORDER BY started, Tasks.id\" \"\".format(started=started, finished=finished, where_task_clause=where_task_clause, where_project_clause=where_project_clause, group_by_clause=group_by_clause,", "EXISTS Customers(' 'id INTEGER PRIMARY KEY, ' 'name VARCHAR UNIQUE COLLATE NOCASE, '", "last_limit_clause=last_limit_clause) ) return self.cursor.fetchall() def create_project(self, pname, description=''): \"\"\"Create a project\"\"\" self.cursor.execute( \"INSERT", "tid): \"\"\"\"\"\" self.cursor.execute( \"DELETE FROM Tasks WHERE id == '{tid}'\".format(tid=tid)) self.conn.commit() # TRACKS", "%d\" % tid ) return self.cursor.fetchone() def create_track(self, task_id, started='', finished='', is_billed=True): #", "\" {where_project_clause}\" \" Tracks.task_id == tid AND \" \" Tasks.project_id == Projects.id\" \"\".format(where_task_clause=where_task_clause,", "return finished def update_track(self, track_id, started, finished, is_billed): \"\"\"Updates the time was spend", "mask\"\"\" def set_group_by_clause(bits, value, group_by): \"\"\"Add a field to group_by clause\"\"\" if mask", "= last_limit_clause = '' if started and finished: where_clause = str( \"WHERE DATE(Tracks.started)", "last_limit_clause = \" DESC LIMIT %d) ORDER BY tid ASC\" % limit self.cursor.execute(", "\"{group_by_clause} \" \"ORDER BY started, Tasks.id\" \"\".format(started=started, finished=finished, where_task_clause=where_task_clause, where_project_clause=where_project_clause, group_by_clause=group_by_clause, only_billed_clause=only_billed_clause) )", "name VARCHAR COLLATE NOCASE, ' ' description TEXT DEFAULT \"\"' ')') # TRACKS", "= \"pname == ? AND \" params.append(pname) self.cursor.execute( \"SELECT \" \" Tasks.id as", "round_to finished = finished + datetime.timedelta(seconds=seconds) self.cursor.execute( \"UPDATE Tracks SET finished=? WHERE id=?\",", "\" params.extend([started, finished]) group_by_clause = self.get_group_by_clause(group_by_mask) query = str( \"SELECT \" \" Tasks.id", "seconds = round_to - delta.seconds % round_to finished = finished + datetime.timedelta(seconds=seconds) self.cursor.execute(", "\" {where_clause} \" \" GROUP BY Tracks.task_id \" \" ) ORDER BY tid", "group_by clause\"\"\" if mask & bits: if group_by: group_by = \"%s,\" % group_by", "created)\" \"VALUES (?, ?, ?)\", ( pname.encode('utf8'), description.encode('utf8'), str(datetime.datetime.now()) ) ) self.conn.commit() return", "= \"%s,\" % group_by group_by = '{group_by} {value}'.format(group_by=group_by, value=value) return group_by group_by =", "project: return project return self.create_project(name) def delete_project_by_name(self, pname): self.cursor.execute( \"DELETE FROM Projects WHERE", "('Andrey', 'Customer Numer One')\") self.cursor.execute(\"SELECT * FROM Customers ORDER BY id LIMIT 1\")", "2 if get_headers else 1 return map(operator.itemgetter(to_get), sorted(clause, key=operator.itemgetter(0))) def get_timesheet_select_clause(self, mask): \"\"\"Get", "\"\".format(task=name.encode('utf8'), project=project_id) ) last = self.cursor.fetchone() if last: return last['tid'] return self.create_task(name, project_id)", "Tasks.project_id == Projects.id\" \"\".format(where_task_clause=where_task_clause, where_project_clause=where_project_clause), params) return self.cursor.fetchone() def get_timesheet(self, started, finished, group_by_mask,", "COLLATE NOCASE, ' ' description TEXT DEFAULT \"\"' ')') # TRACKS self.cursor.execute( 'CREATE", "operator from tabulate import tabulate import config TS_GROUP_BY = dict( timestamp=0b10000, project=0b1000, task=0b0100,", "return self.cursor.fetchone() def update_task(self, tid, name, description=''): \"\"\"Updates the task info\"\"\" self.cursor.execute( \"UPDATE", "\" \"FROM Tracks, Tasks, Projects \" \"WHERE \" \" Tracks.task_id == tid AND", "as \"finished [timestamp]\"', 'To') spent_field = (5, 'spent', 'Time Spent') clause = set()", "pid, name as name, created as created, \" \" description as description \"", "(?, ?, ?, ?)\", (task_id, started, finished, int(is_billed)) ) self.conn.commit() return self.cursor.lastrowid def", "def get_active_task(self, started='', finished='', tname='', pname=''): \"\"\"Get an active task\"\"\" params = []", "as pid, \" \" Projects.name as pname, Tasks.description as description, \" \" Tracks.started", "= \" AND Tracks.is_billed == 1 \" params.extend([started, finished]) group_by_clause = self.get_group_by_clause(group_by_mask) query", "record\"\"\" self.cursor.execute( \"UPDATE Tracks \" \"SET started=?, finished=?, is_billed=? \" \"WHERE id=?\", (started,", "'DATETIME(finished) as \"finished [timestamp]\"', 'To') spent_field = (5, 'spent', 'Time Spent') clause =", "db_name): # create DB self.init_db(db_name) self.create_db() def insert_test_task(self, project_id): name = ''.join(random.choice( string.ascii_uppercase", "was spend and is billed flag of the track record\"\"\" self.cursor.execute( \"UPDATE Tracks", "as name, created as created, \" \" description as description \" \"FROM Projects", ") ) self.conn.commit() def delete_task(self, tid): \"\"\"\"\"\" self.cursor.execute( \"DELETE FROM Tasks WHERE id", "name.encode('utf8'), pid ) ) self.conn.commit() return self.cursor.lastrowid def get_task_or_create(self, name, project_id): \"\"\"Get a", "ON DELETE CASCADE, ' ' name VARCHAR COLLATE NOCASE, ' ' description TEXT", "\" FROM Tracks \" \"WHERE \" \" DATE(started) BETWEEN ? AND ?\" \"", "finished)-STRFTIME('%s', started)) as spent,\" \" Tracks.started as started, \" \" Tracks.finished as finished", "finished, \" \" Tasks.description as description \" \"FROM Tracks, Tasks, Projects \" \"WHERE", "Tracks.is_billed == 1 \" params.extend([started, finished]) group_by_clause = self.get_group_by_clause(group_by_mask) query = str( \"SELECT", "os import sqlite3 import random import string import time import datetime from datetime", "? AND \" if only_billed: only_billed_clause = \" AND Tracks.is_billed == 1 \"", "as finished, \" \" Tracks.is_billed as is_billed \" \"FROM Tracks, Tasks, Projects \"", "list of project including a field is a project is finished\"\"\" where_clause =", "\"{first_limit_clause}\" \"SELECT \" \" Projects.id as pid, Projects.name, Projects.created, \" \" Projects.description, \"", "\" DESC LIMIT %d) ORDER BY tid ASC\" % limit self.cursor.execute( \"{first_limit_clause}\" \"SELECT", "= \"AND NOT finished == '' \" self.cursor.execute( \"DELETE \" \" FROM Tracks", "\" ) \" \"{group_by_clause} \" \"ORDER BY started, Tasks.id\" \"\".format(started=started, finished=finished, where_task_clause=where_task_clause, where_project_clause=where_project_clause,", ") self.conn.commit() def is_project_existent(self, pname, pid): \"\"\"Checks if project already exists \"\"\" self.cursor.execute(", "BY Tasks.id \" \"ORDER BY Tasks.id DESC LIMIT {limit:d}\".format( limit=limit, activity_field=activity_field) ) tasks", "EXISTS (\" \" SELECT id FROM Tasks WHERE \" \" Tasks.project_id == Projects.id", "'{project:s}'\" \"\".format(task=tname.encode('utf8'), project=pname.encode('utf8')) ) return self.cursor.fetchone() def create_task(self, name, pid): self.cursor.execute( \"INSERT INTO", "' 'name VARCHAR UNIQUE COLLATE NOCASE, ' 'description TEXT, ' 'created TIMESTAMP' ')')", "params.append(tname) if pname: pname = pname.encode('utf8') where_project_clause = \"pname == ? AND \"", "), params ) return self.cursor.fetchone() def update_task(self, tid, name, description=''): \"\"\"Updates the task", "\" Tasks.project_id == Projects.id AND \" \" trid == %d\" % tid )", "Tracks \" \" ('task_id', 'started', 'finished', 'is_billed') \" \"VALUES (?, ?, ?, ?)\",", "datetime - 0 # date - 1 # task - 2 # project", "started, finished - 9-item sequence, not float if not started: started = datetime.datetime.now()", "if mask & TS_GROUP_BY['track']: clause.update([task_field, project_field, started_field, finished_field]) clause.add(spent_field) to_get = 2 if", "timedelta(seconds=600)) last_track = self.create_track(last_task) self.cursor.execute(\"SELECT * FROM Tracks \") tracks = self.cursor.fetchall() #print('filled", "Projects.id\" \"\".format(where_task_clause=where_task_clause, where_project_clause=where_project_clause), params) return self.cursor.fetchone() def get_timesheet(self, started, finished, group_by_mask, only_billed=True, tname='',", "id=?\", (finished, track_id) ) self.conn.commit() return finished def update_track(self, track_id, started, finished, is_billed):", "Projects \" \"WHERE \" \" Projects.name == ?\", (pname.encode('utf8'),) ) return self.cursor.fetchone() def", "\"\"\"Checks if project already exists \"\"\" self.cursor.execute( \"SELECT \" \" id as pid,", "' ' started TIMESTAMP, ' ' finished TIMESTAMP, ' ' is_billed INTEGER DEFAULT", "Projects, Tracks \" \"WHERE \" \" Tasks.project_id == Projects.id AND \" \" Tracks.task_id", "\"pname == ? AND \" params.append(pname) self.cursor.execute( \"SELECT \" \" Tasks.id as tid,", "= ON\") # Create Tables if do the not exist # PROJECTS self.cursor.execute(", "'' \" \" {where_date_clause}\".format( where_date_clause=where_date_clause, where_project_clause=where_project_clause, where_task_clause=where_task_clause ), params ) return self.cursor.fetchone() def", "Tracks, Tasks, Projects \" \"WHERE \" \" Tracks.task_id == tid AND \" \"", "WHERE id == '{tid}'\".format(tid=tid)) self.conn.commit() # TRACKS def get_tracks_by_date(self, started='', finished='', also_unfinished=False): \"\"\"Get", "of ordered fields\"\"\" # Priority: # datetime - 0 # date - 1", "def __init__(self, db_name): # create DB self.init_db(db_name) self.create_db() def insert_test_task(self, project_id): name =", "key=operator.itemgetter(0))) def get_timesheet_select_clause(self, mask): \"\"\"Get prepared select's clause list of fields\"\"\" fields =", "self.cursor.lastrowid def get_project_or_create(self, pname): self.cursor.execute( \"SELECT id, name FROM Projects \" \"WHERE name", "already exists \"\"\" self.cursor.execute( \"SELECT \" \" id as pid, name as name,", "\" AND ? \" params.extend([started, finished]) self.cursor.execute( \"SELECT \" \" Tasks.id as tid,", "is a project is finished\"\"\" where_clause = first_limit_clause = last_limit_clause = '' if", "Tasks.project_id == Projects.id AND \" \" trid == %d\" % tid ) return", "tname = tname.encode('utf8') where_task_clause = \"tname == ? AND \" params.append(tname) if pname:", "{where_clause} \" \" {between_clause} \" \"ORDER BY Tracks.id\".format(started=started, finished=finished, where_clause=where_clause, between_clause=between_clause), params )", "%d) ORDER BY tid ASC\" % limit self.cursor.execute( \"{first_limit_clause}\" \"SELECT \" \" Tasks.id", "AND \" params.append(pname) if started and finished: where_date_clause = \"AND DATE(Tracks.started) \" \\", "' ' task_id INTEGER REFERENCES Tasks(id) ON DELETE CASCADE, ' ' started TIMESTAMP,", "Projects.name as pname, \" \" DATE(started) as 'started [date]'\" \"FROM Tracks, Tasks, Projects", "\"\".format(task=tname.encode('utf8'), project=pname.encode('utf8')) ) return self.cursor.fetchone() def create_task(self, name, pid): self.cursor.execute( \"INSERT INTO Tasks", "\"\"\" self.cursor.execute( \"SELECT \" \" id as pid, name as name, created as", "between_clause = \"AND DATE(started) BETWEEN ? AND ?\" params.extend([started, finished]) self.cursor.execute( \"SELECT \"", "INTEGER PRIMARY KEY, ' 'name VARCHAR UNIQUE COLLATE NOCASE, ' 'description TEXT, '", "def get_timesheet(self, started, finished, group_by_mask, only_billed=True, tname='', pname=''): \"\"\" Gets the time was", "def get_task_by_alias(self, tname, pname): \"\"\"Get task by name\"\"\" self.cursor.execute( \"SELECT \" \" Tasks.id", "\"WHERE \" \" DATE(started) BETWEEN ? AND ?\" \" {where_clause}\" \"\".format(where_clause=where_clause), (started, finished)", "\" Tracks.task_id == tid AND \" \" Tasks.project_id == Projects.id\" \"\".format(where_task_clause=where_task_clause, where_project_clause=where_project_clause), params)", "started = datetime.datetime.now() - timedelta(seconds=3300) self.create_track(last_task, started=started, finished=started + timedelta(seconds=600)) last_track = self.create_track(last_task)", "x: x.decode('utf8') #try: #except sqlite3.OperationalError: self.cursor = self.conn.cursor() def close_db(self): self.conn.close() def create_db(self):", "self.cursor.execute( \"INSERT INTO Tasks ('name', 'project_id') \" \"VALUES \" \" (?, ?)\", (", "\" \"FROM Projects \" \"WHERE \" \" pid == '{pid}'\" \" name ==", "IF NOT EXISTS Tracks(' ' id INTEGER PRIMARY KEY, ' ' task_id INTEGER", "clause.update([task_field, project_field, started_field, finished_field]) clause.add(spent_field) to_get = 2 if get_headers else 1 return", "select's clause list of fields\"\"\" fields = self.get_timesheet_fields(mask) return ', '.join(fields) def get_minimal_started_track(self,", "\"FROM Tracks, Tasks, Projects \" \"WHERE \" \" Tracks.task_id == Tasks.id AND \"", "params = [] if not also_unfinished: where_clause = \"AND NOT finished == ''", "Add the Tracks started = datetime.datetime.now() - timedelta(days=4) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3601))", "(5, 'spent', 'Time Spent') clause = set() if mask & TS_GROUP_BY['date']: clause.add(date_field) if", "self.cursor.execute('DELETE FROM Customers') self.cursor.execute('DELETE FROM Projects') self.cursor.execute('DELETE FROM Tasks') self.cursor.execute('DELETE FROM Tracks') #", "started='', finished='', tname='', pname=''): \"\"\"Get an active task\"\"\" params = [] where_date_clause =", "Customers ('name')\" \"VALUES ('{name:s}')\" .format(name=customer) ) self.conn.commit() # PROJECTS def get_project_by_name(self, pname): self.cursor.execute(", "task info\"\"\" self.cursor.execute( \"UPDATE Tasks \" \"SET name=?, description=?\" \"WHERE id=?\", ( name.encode('utf8'),", "Tasks.project_id == Projects.id AND \" \" Tracks.task_id == Tasks.id {where_clause}\" \"GROUP BY Projects.id", "\" \"SET name=?, description=?\" \"WHERE id=?\", (name.encode('utf8'), description.encode('utf8'), pid) ) self.conn.commit() def is_project_existent(self,", "== Projects.id AND \" \" Tracks.task_id == Tasks.id \" \"GROUP BY Tasks.id \"", "'Tracks.task_id', group_by) group_by = set_group_by_clause(TS_GROUP_BY['track'], 'Tracks.id', group_by) if group_by: group_by = \"GROUP BY", "? AND \" params.append(pname) self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as", "if group_by: group_by = \"%s,\" % group_by group_by = '{group_by} {value}'.format(group_by=group_by, value=value) return", "\" \" Tracks.task_id == Tasks.id {where_clause}\" \"GROUP BY Projects.id \" \"UNION SELECT \"", "started=started+timedelta(seconds=19600), finished=started+timedelta(seconds=20600)) # Add a Project #2 self.create_project('p2', 'Test Project #1') self.cursor.execute(\"SELECT *", "int(is_billed)) ) self.conn.commit() return self.cursor.lastrowid def finish_track(self, track_id, started=None): finished = datetime.datetime.now() if", "'CREATE TABLE IF NOT EXISTS Projects(' ' id INTEGER PRIMARY KEY, ' '", "AND \" params.append(pname) self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as tname,", "- 1 # task - 2 # project - 3 # spent -", "delta = finished - started round_to = config.BT_ROUNDING_INCREMENT * 60 seconds = round_to", "== %d\" % tid ) return self.cursor.fetchone() def create_track(self, task_id, started='', finished='', is_billed=True):", "THEN 1 ELSE 0 END) \" self.cursor.execute( \"SELECT \" \" Tasks.id, Tasks.name, Projects.id,", "db_path): self.conn = sqlite3.connect( db_path, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES ) self.conn.row_factory = sqlite3.Row self.conn.text_factory = lambda", "BY Tasks.id DESC LIMIT {limit:d}\".format( limit=limit, activity_field=activity_field) ) tasks = self.cursor.fetchall() return tasks", "TS_GROUP_BY['project']: clause.add(project_field) if mask & TS_GROUP_BY['track']: clause.update([task_field, project_field, started_field, finished_field]) clause.add(spent_field) to_get =", "billed flag of the track record\"\"\" self.cursor.execute( \"UPDATE Tracks \" \"SET started=?, finished=?,", "\" \" pname == '{project:s}'\" \"\".format(task=tname.encode('utf8'), project=pname.encode('utf8')) ) return self.cursor.fetchone() def create_task(self, name,", "= self.cursor.fetchone() if last: return last['tid'] return self.create_task(name, project_id) def _get_active_tasks(self): \"\"\"Get active", "\"tname == ? AND \" params.append(tname) if pname: pname = pname.encode('utf8') where_project_clause =", "= self.cursor.fetchone() if customer: return customer self.cursor.execute( \"INSERT INTO Customers ('name')\" \"VALUES ('{name:s}')\"", "mask): \"\"\"Get prepared select's clause list of fields\"\"\" fields = self.get_timesheet_fields(mask) return ',", "delete_tracks_by_date(self, started, finished, also_unfinished=False): \"\"\"Deletes tracks by the date\"\"\" if not also_unfinished: where_clause", "= [] if not also_unfinished: where_clause = \"AND NOT finished == '' \"", "THEN 1 ELSE 0 end) AS active \" \"FROM Projects, Tracks, Tasks \"", "description=?\" \"WHERE id=?\", (name.encode('utf8'), description.encode('utf8'), pid) ) self.conn.commit() def is_project_existent(self, pname, pid): \"\"\"Checks", "\" \"ORDER BY Tasks.id DESC LIMIT {limit:d}\".format( limit=limit, activity_field=activity_field) ) tasks = self.cursor.fetchall()", "self.create_project('p1', 'Test Project #1') self.cursor.execute(\"SELECT * FROM Projects ORDER BY id LIMIT 1\")", "datetime.timedelta(seconds=seconds) self.cursor.execute( \"UPDATE Tracks SET finished=? WHERE id=?\", (finished, track_id) ) self.conn.commit() return", "not also_unfinished: where_clause = \"AND NOT finished == '' \" self.cursor.execute( \"DELETE \"", "a task or create one\"\"\" self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name", "self.cursor.execute(\"SELECT * FROM Tracks \") tracks = self.cursor.fetchall() #print('filled tracks', tracks) print(tabulate(tracks, ['Track", "['Track id', 'Task id', 'started', 'finished', 'billed'], tablefmt='simple')) return # CUSTOMERS def get_customer(self,", "= (2, 'pname', 'Project') started_field = (3, 'DATETIME(started) as \"started [timestamp]\"', 'From') finished_field", ") self.conn.commit() def delete_tracks_by_date(self, started, finished, also_unfinished=False): \"\"\"Deletes tracks by the date\"\"\" if", "\"GROUP BY %s \" % group_by return group_by def get_timesheet_fields(self, mask, get_headers=False): \"\"\"Makes", "\" GROUP BY Tracks.task_id \" \" ) ORDER BY tid {last_limit_clause}\" \"\".format( where_clause=where_clause,", ") self.conn.commit() def delete_task(self, tid): \"\"\"\"\"\" self.cursor.execute( \"DELETE FROM Tasks WHERE id ==", "self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as tname, \" \" Projects.id", "= '' if limit: first_limit_clause = \"SELECT * FROM (\" last_limit_clause = \"", "= datetime.datetime.now() self.cursor.execute( \"INSERT INTO Tracks \" \" ('task_id', 'started', 'finished', 'is_billed') \"", "started, Tasks.id\" \"\".format(started=started, finished=finished, where_task_clause=where_task_clause, where_project_clause=where_project_clause, group_by_clause=group_by_clause, only_billed_clause=only_billed_clause) ) #print(query) if group_by_mask: select_clause", "ORDER BY pid ASC\" % limit if from_date and to_date: where_clause = \"", "name == '{name:s}'\".format(name=customer) ) customer = self.cursor.fetchone() if customer: return customer self.cursor.execute( \"INSERT", "\"AND DATE(Tracks.started) \" \\ \" BETWEEN ? \" \\ \" AND ? \"", "VARCHAR COLLATE NOCASE, ' ' description TEXT DEFAULT \"\"' ')') # TRACKS self.cursor.execute(", "where_clause=where_clause, between_clause=between_clause), params ) return self.cursor.fetchall() def get_track_by_id(self, tid): self.cursor.execute( \"SELECT \" \"", "= sqlite3.connect( db_path, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES ) self.conn.row_factory = sqlite3.Row self.conn.text_factory = lambda x: x.decode('utf8')", "params = [] only_billed_clause = where_project_clause = where_task_clause = '' if tname: params.append(tname.encode('utf8'))", "\" \" Tracks.finished as finished \" \"FROM Tracks, Tasks, Projects \" \"WHERE \"", "INTEGER REFERENCES Projects(id) ON DELETE CASCADE, ' ' name VARCHAR COLLATE NOCASE, '", "timedelta(days=2) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3600)) started = datetime.datetime.now() - timedelta(days=1) self.create_track(last_task, started=started,", "'Test Project #1') self.cursor.execute(\"SELECT * FROM Projects ORDER BY id LIMIT 1\") project", "str( \"WHERE DATE(Tracks.started) BETWEEN '{started}' AND '{finished}'\" \"\".format(started=started, finished=finished)) if limit: first_limit_clause =", "\"INSERT INTO Customers ('name')\" \"VALUES ('{name:s}')\" .format(name=customer) ) self.conn.commit() # PROJECTS def get_project_by_name(self,", "Tasks.project_id == Projects.id AND \" \" finished == ''\") return self.cursor.fetchall() def get_active_task(self,", "DESC LIMIT %d) ORDER BY tid ASC\" % limit self.cursor.execute( \"{first_limit_clause}\" \"SELECT \"", "return customer self.cursor.execute( \"INSERT INTO Customers ('name')\" \"VALUES ('{name:s}')\" .format(name=customer) ) self.conn.commit() #", "= tname.encode('utf8') where_task_clause = \"tname == ? AND \" params.append(tname) if pname: pname", ") self.conn.row_factory = sqlite3.Row self.conn.text_factory = lambda x: x.decode('utf8') #try: #except sqlite3.OperationalError: self.cursor", "Projects.name, Projects.created, \" \" Projects.description, \" \" SUM(CASE WHEN Tracks.finished == '' THEN", "set() if mask & TS_GROUP_BY['date']: clause.add(date_field) if mask & TS_GROUP_BY['task']: clause.update([task_field, project_field]) if", "DATE(Tracks.started) BETWEEN '{started}' AND '{finished}'\" \"\".format(started=started, finished=finished)) if limit: first_limit_clause = \"SELECT *", "\" \" finished == '' \" \" {where_date_clause}\".format( where_date_clause=where_date_clause, where_project_clause=where_project_clause, where_task_clause=where_task_clause ), params", "started, finished, spent date_field = (0, 'DATE(started) as \"date [date]\"', 'Date') task_field =", "{value}'.format(group_by=group_by, value=value) return group_by group_by = set_group_by_clause(TS_GROUP_BY['date'], 'DATE(started)', '') group_by = set_group_by_clause(TS_GROUP_BY['project'], 'Tasks.project_id',", "{limit:d}\".format( limit=limit, activity_field=activity_field) ) tasks = self.cursor.fetchall() return tasks def get_profiled_tasks(self, started='', finished='',", "AND \" if only_billed: only_billed_clause = \" AND Tracks.is_billed == 1 \" params.extend([started,", "as tid, Tasks.name as tname, \" \" Projects.id as pid, Projects.name as pname,", "params.append(tname.encode('utf8')) where_task_clause = \"tname == ? AND \" if pname: params.append(pname.encode('utf8')) where_project_clause =", "' name VARCHAR UNIQUE COLLATE NOCASE, ' ' description TEXT DEFAULT \"\", '", "self.cursor.execute( \"{first_limit_clause}\" \"SELECT \" \" Tasks.id as tid, Tasks.name as tname, Projects.id as", "' ' name VARCHAR UNIQUE COLLATE NOCASE, ' ' description TEXT DEFAULT \"\",", "== ''\" \" {only_billed_clause}\" \" ) \" \"{group_by_clause} \" \"ORDER BY started, Tasks.id\"", "INTEGER PRIMARY KEY, ' ' project_id INTEGER REFERENCES Projects(id) ON DELETE CASCADE, '", "as finished \" \"FROM Tracks, Tasks, Projects \" \"WHERE \" \" {where_task_clause}\" \"", "= self.cursor.fetchone() return customer def get_customer_or_create(self, customer): self.cursor.execute( \"SELECT id, name FROM Customers", "\" \"values('%s', '%s')\" % (name, project_id) ) self.conn.commit() return self.cursor.lastrowid def fill(self): \"\"\"Fill", ") self.conn.commit() return self.cursor.lastrowid def get_project_or_create(self, pname): self.cursor.execute( \"SELECT id, name FROM Projects", "'{name}'\".format(name=pname.encode('utf8'), pid=pid) ) return self.cursor.fetchone() def get_projects_with_activity_field(self, from_date='', to_date='', limit=0): \"\"\"Get list of", "self.cursor.fetchone() def create_track(self, task_id, started='', finished='', is_billed=True): # started, finished - 9-item sequence,", "delta.seconds % round_to finished = finished + datetime.timedelta(seconds=seconds) self.cursor.execute( \"UPDATE Tracks SET finished=?", "TABLE IF NOT EXISTS Projects(' ' id INTEGER PRIMARY KEY, ' ' customer_id", "= datetime.datetime.now() - timedelta(days=4) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3601)) self.create_track(last_task, started=started+timedelta(seconds=13600), finished=started+timedelta(seconds=14600)) self.create_track(last_task,", "Tasks.project_id == pid AND \" \" pid == '{project!s}'\" \"\".format(task=name.encode('utf8'), project=project_id) ) last", "self.cursor.execute( \"SELECT \" \" Tasks.id, Tasks.name, Projects.id, Projects.name, \" \" Tasks.description {activity_field}\" \"FROM", "\"WHERE DATE(Tracks.started) BETWEEN '{started}' AND '{finished}'\" \"\".format(started=started, finished=finished)) if limit: first_limit_clause = \"SELECT", "add_activity=False): \"\"\"Lists of last tasks\"\"\" activity_field = '' if add_activity: activity_field = \",", "= \", SUM(CASE WHEN Tracks.finished == '' THEN 1 ELSE 0 END) \"", "Projects \" \"WHERE \" \" Tasks.project_id == pid AND \" \" tname ==", "also_unfinished: where_clause = \"AND NOT finished == '' \" self.cursor.execute( \"DELETE \" \"", "Numer One')\") self.cursor.execute(\"SELECT * FROM Customers ORDER BY id LIMIT 1\") customers =", "self.conn.commit() # TRACKS def get_tracks_by_date(self, started='', finished='', also_unfinished=False): \"\"\"Get tracks\"\"\" where_clause = ''", "Projects.id as pid, Projects.name as pname, \" \" Tracks.id as trid, Tracks.started as", "\" Tasks.id as tid, Tasks.name as tname, Projects.name as pname, \" \" Tracks.id", "\" \" Tasks.id, Tasks.name, Projects.id, Projects.name, \" \" Tasks.description {activity_field}\" \"FROM Tasks, Projects,", "minimal tracked date\"\"\" params = [] where_project_clause = where_task_clause = '' if tname:", "= [] where_project_clause = where_task_clause = '' if tname: tname = tname.encode('utf8') where_task_clause", "TIMESTAMP, ' ' finished TIMESTAMP, ' ' is_billed INTEGER DEFAULT 1' ')') #", "\"WHERE \" \" Tracks.task_id == tid AND \" \" Tasks.project_id == pid\" \"", "Tasks.project_id == pid\" \" {where_clause} \" \" {between_clause} \" \"ORDER BY Tracks.id\".format(started=started, finished=finished,", "\" Tracks.finished as finished, \" \" Tasks.description as description \" \"FROM Tracks, Tasks,", "finished, also_unfinished=False): \"\"\"Deletes tracks by the date\"\"\" if not also_unfinished: where_clause = \"AND", "FROM Customers') self.cursor.execute('DELETE FROM Projects') self.cursor.execute('DELETE FROM Tasks') self.cursor.execute('DELETE FROM Tracks') # Add", "description=''): \"\"\"Create a project\"\"\" self.cursor.execute( \"INSERT INTO Projects ('name', 'description', created)\" \"VALUES (?,", "return self.cursor.fetchone() def create_track(self, task_id, started='', finished='', is_billed=True): # started, finished - 9-item", "Task tasks = [] last_task = self.insert_test_task(project_id=2) self.create_track(last_task, started=started+timedelta(seconds=21600), finished=started+timedelta(seconds=22600)) self.create_track(last_task, started=started+timedelta(seconds=23600), finished=started+timedelta(seconds=24600))", "tasks = [] last_task = self.insert_test_task(project_id=2) self.create_track(last_task, started=started+timedelta(seconds=21600), finished=started+timedelta(seconds=22600)) self.create_track(last_task, started=started+timedelta(seconds=23600), finished=started+timedelta(seconds=24600)) self.create_track(last_task,", "params ) return self.cursor.fetchall() def get_track_by_id(self, tid): self.cursor.execute( \"SELECT \" \" Tasks.id as", "customer = self.cursor.fetchone() if customer: return customer self.cursor.execute( \"INSERT INTO Customers ('name')\" \"VALUES", "task - 2 # project - 3 # spent - 4 # date,", "string.digits) for _ in range(3)) self.cursor.execute( \"insert into Tasks ('name', 'project_id') \" \"values('%s',", "?\" params.extend([started, finished]) self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as tname,", "'spent', 'Time Spent') clause = set() if mask & TS_GROUP_BY['date']: clause.add(date_field) if mask", "if not also_unfinished: where_clause = \"AND NOT finished == '' \" if started", "if mask & TS_GROUP_BY['task']: clause.update([task_field, project_field]) if mask & TS_GROUP_BY['project']: clause.add(project_field) if mask", "\" \" Tracks.task_id == Tasks.id AND \" \" Tracks.id IN (\" \" SELECT", "update_task(self, tid, name, description=''): \"\"\"Updates the task info\"\"\" self.cursor.execute( \"UPDATE Tasks \" \"SET", "spent_field = (5, 'spent', 'Time Spent') clause = set() if mask & TS_GROUP_BY['date']:", "is_billed INTEGER DEFAULT 1' ')') # CUSTOMERS self.cursor.execute( 'CREATE TABLE IF NOT EXISTS", "Projects.id as pid, \" \" Projects.name as pname, Tasks.description as description, \" \"", "# Add the Tracks started = datetime.datetime.now() - timedelta(days=4) self.create_track(last_task, started=started, finished=started +", "create DB self.init_db(db_name) self.create_db() def insert_test_task(self, project_id): name = ''.join(random.choice( string.ascii_uppercase + string.digits)", "track_id) ) self.conn.commit() def delete_tracks_by_date(self, started, finished, also_unfinished=False): \"\"\"Deletes tracks by the date\"\"\"", "if only_billed: only_billed_clause = \" AND Tracks.is_billed == 1 \" params.extend([started, finished]) group_by_clause", "params) return self.cursor.fetchone() def get_timesheet(self, started, finished, group_by_mask, only_billed=True, tname='', pname=''): \"\"\" Gets", "do the not exist # PROJECTS self.cursor.execute( 'CREATE TABLE IF NOT EXISTS Projects('", "def get_project_or_create(self, pname): self.cursor.execute( \"SELECT id, name FROM Projects \" \"WHERE name ==", "WHERE \" \" Tasks.project_id == Projects.id \" \") {where_clause}\" \"ORDER BY Projects.id {last_limit_clause}\".format(", "where_task_clause = \"tname == ? AND \" params.append(tname) if pname: pname = pname.encode('utf8')", "'Project') started_field = (3, 'DATETIME(started) as \"started [timestamp]\"', 'From') finished_field = (4, 'DATETIME(finished)", "activity_field = '' if add_activity: activity_field = \", SUM(CASE WHEN Tracks.finished == ''", "'started', 'finished', 'is_billed') \" \"VALUES (?, ?, ?, ?)\", (task_id, started, finished, int(is_billed))", "self.cursor.execute( \"INSERT INTO Tracks \" \" ('task_id', 'started', 'finished', 'is_billed') \" \"VALUES (?,", "finished, int(is_billed)) ) self.conn.commit() return self.cursor.lastrowid def finish_track(self, track_id, started=None): finished = datetime.datetime.now()", "mask, get_headers=False): \"\"\"Makes a list of ordered fields\"\"\" # Priority: # datetime -", "tname, \" \" Projects.id as pid, Projects.name as pname, \" \" Tracks.id as", "'.join(fields) def get_minimal_started_track(self, tname='', pname=''): \"\"\"Get a minimal tracked date\"\"\" params = []", "project return self.create_project(name) def delete_project_by_name(self, pname): self.cursor.execute( \"DELETE FROM Projects WHERE name ==", "not exist # PROJECTS self.cursor.execute( 'CREATE TABLE IF NOT EXISTS Projects(' ' id", "group_by) group_by = set_group_by_clause(TS_GROUP_BY['track'], 'Tracks.id', group_by) if group_by: group_by = \"GROUP BY %s", "Tasks.project_id == pid AND \" \" tname == '{task:s}' AND \" \" pname", "= self.conn.cursor() def close_db(self): self.conn.close() def create_db(self): self.cursor.execute(\"PRAGMA foreign_keys = ON\") # Create", "# datetime - 0 # date - 1 # task - 2 #", "description TEXT DEFAULT \"\"' ')') # TRACKS self.cursor.execute( 'CREATE TABLE IF NOT EXISTS", "\"SELECT id, name FROM Customers \" \"WHERE name == '{name:s}'\".format(name=customer) ) customer =", "{where_clause}\" \"GROUP BY Projects.id \" \"UNION SELECT \" \" Projects.id as pid, Projects.name,", "= where_project_clause = where_task_clause = '' if tname: tname = tname.encode('utf8') where_task_clause =", "AND \" \" Tasks.project_id == Projects.id AND \" \" finished == '' \"", "between dates including unfinished\"\"\" where_clause = first_limit_clause = last_limit_clause = '' if started", "\"SELECT \" \" id as pid, name as name, created as created, \"", "Tracks \" \"WHERE \" \" DATE(started) BETWEEN ? AND ?\" \" {where_clause}\" \"\".format(where_clause=where_clause),", "= self.cursor.fetchall() #print('filled tracks', tracks) print(tabulate(tracks, ['Track id', 'Task id', 'started', 'finished', 'billed'],", "\" Tasks.project_id == Projects.id AND \" \" Tracks.task_id == Tasks.id \" \"GROUP BY", "where_clause = \"AND NOT finished == '' \" if started and finished: between_clause", "\" \" Projects.name == ?\", (pname.encode('utf8'),) ) return self.cursor.fetchone() def update_project(self, pid, name,", "TS_GROUP_BY['task']: clause.update([task_field, project_field]) if mask & TS_GROUP_BY['project']: clause.add(project_field) if mask & TS_GROUP_BY['track']: clause.update([task_field,", "{where_task_clause}\" \" {where_project_clause}\" \" Tracks.task_id == tid AND \" \" Tasks.project_id == Projects.id", "DB self.init_db(db_name) self.create_db() def insert_test_task(self, project_id): name = ''.join(random.choice( string.ascii_uppercase + string.digits) for", "\" Tracks.task_id == tid AND \" \" Tasks.project_id == Projects.id AND \" \"", "test tasks\"\"\" self.cursor.execute('DELETE FROM Customers') self.cursor.execute('DELETE FROM Projects') self.cursor.execute('DELETE FROM Tasks') self.cursor.execute('DELETE FROM", "#1') self.cursor.execute(\"SELECT * FROM Projects ORDER BY id LIMIT 1\") project = self.cursor.fetchone()", "finished='', also_unfinished=False): \"\"\"Get tracks\"\"\" where_clause = '' between_clause = '' params = []", "tid, Tasks.name as tname, Projects.name as pname, \" \" DATE(started) as 'started [date]'\"", "Tracks.started as started, \" \" Tracks.finished as finished \" \"FROM Tracks, Tasks, Projects", "\" \" Tasks.description as description \" \"FROM Tracks, Tasks, Projects \" \"WHERE \"", "self.conn.commit() return self.cursor.lastrowid def fill(self): \"\"\"Fill with the test tasks\"\"\" self.cursor.execute('DELETE FROM Customers')", "\" \"WHERE name == '{name:s}'\".format(name=customer) ) customer = self.cursor.fetchone() if customer: return customer", "'started [date]'\" \"FROM Tracks, Tasks, Projects \" \"WHERE \" \" {where_task_clause}\" \" {where_project_clause}\"", "\"SET name=?, description=?\" \"WHERE id=?\", (name.encode('utf8'), description.encode('utf8'), pid) ) self.conn.commit() def is_project_existent(self, pname,", "def update_project(self, pid, name, description): \"\"\"Updates a project\"\"\" self.cursor.execute( \"UPDATE Projects \" \"SET", "{where_clause} \" \" GROUP BY Tracks.task_id \" \" ) ORDER BY tid {last_limit_clause}\"", "Projects \" \"WHERE \" \" {where_task_clause}\" \" {where_project_clause}\" \" Tracks.task_id == tid AND", "\" Tasks.project_id == pid AND \" \" tname == '{task:s}' AND \" \"", "'From') finished_field = (4, 'DATETIME(finished) as \"finished [timestamp]\"', 'To') spent_field = (5, 'spent',", "self.cursor.execute( \"SELECT \" \" id as pid, name as pname, created as created,", "pid == '{pid}'\" \" name == '{name}'\".format(name=pname.encode('utf8'), pid=pid) ) return self.cursor.fetchone() def get_projects_with_activity_field(self,", "\" tname == '{task}' AND \" \" Tasks.project_id == pid AND \" \"", "AND \" \" tname == '{task:s}' AND \" \" pname == '{project:s}'\" \"\".format(task=tname.encode('utf8'),", "params.append(pname) if started and finished: where_date_clause = \"AND DATE(Tracks.started) \" \\ \" BETWEEN", "' ' name VARCHAR COLLATE NOCASE, ' ' description TEXT DEFAULT \"\"' ')')", "__init__(self, db_name): # create DB self.init_db(db_name) self.create_db() def insert_test_task(self, project_id): name = ''.join(random.choice(", "Projects.name, \" \" Tasks.description {activity_field}\" \"FROM Tasks, Projects, Tracks \" \"WHERE \" \"", "DEFAULT 1' ')') # CUSTOMERS self.cursor.execute( 'CREATE TABLE IF NOT EXISTS Customers(' 'id", "\"WHERE name == '{name:s}'\".format(name=customer) ) customer = self.cursor.fetchone() return customer def get_customer_or_create(self, customer):", "Projects.name as pname, Tasks.description as description \" \"FROM Tasks, Projects \" \"WHERE \"", "(started, finished, is_billed, track_id) ) self.conn.commit() def delete_tracks_by_date(self, started, finished, also_unfinished=False): \"\"\"Deletes tracks", "'' if add_activity: activity_field = \", SUM(CASE WHEN Tracks.finished == '' THEN 1", "# TRACKS self.cursor.execute( 'CREATE TABLE IF NOT EXISTS Tracks(' ' id INTEGER PRIMARY", "only_billed_clause = where_project_clause = where_task_clause = '' if tname: params.append(tname.encode('utf8')) where_task_clause = \"tname", "UNIQUE COLLATE NOCASE, ' 'description TEXT, ' 'created TIMESTAMP' ')') self.conn.commit() def __init__(self,", "where_clause = str( \"WHERE DATE(Tracks.started) BETWEEN '{started}' AND '{finished}'\" \"\".format(started=started, finished=finished)) if limit:", "if group_by_mask: select_clause = self.get_timesheet_select_clause(group_by_mask) query = \"SELECT {clause} FROM ({query})\".format( query=query, clause=select_clause)", "Tracks.finished == ''\" \" {only_billed_clause}\" \" ) \" \"{group_by_clause} \" \"ORDER BY started,", "from_date='', to_date='', limit=0): \"\"\"Get list of project including a field is a project", "activity_field = \", SUM(CASE WHEN Tracks.finished == '' THEN 1 ELSE 0 END)", "+ timedelta(seconds=3601)) self.create_track(last_task, started=started+timedelta(seconds=13600), finished=started+timedelta(seconds=14600)) self.create_track(last_task, started=started+timedelta(seconds=15600), finished=started+timedelta(seconds=16600)) last_task = self.insert_test_task(project_id=1) self.create_track(last_task, started=started+timedelta(seconds=17600),", "\" \" Tasks.project_id == pid AND \" \" tname == '{task:s}' AND \"", "== pid AND \" \" tname == '{task:s}' AND \" \" pname ==", "\" ) ORDER BY tid {last_limit_clause}\" \"\".format( where_clause=where_clause, first_limit_clause=first_limit_clause, last_limit_clause=last_limit_clause) ) tasks =", "\"SET name=?, description=?\" \"WHERE id=?\", ( name.encode('utf8'), description.encode('utf8'), tid ) ) self.conn.commit() def", "def get_profiled_tasks(self, started='', finished='', limit=0): \"\"\"The list of last tasks between dates including", "\" {where_clause}\" \"\".format(where_clause=where_clause), (started, finished) ) self.conn.commit() # TIMESHEET def get_group_by_clause(self, mask): \"\"\"Makes", "NOT Tracks.finished == ''\" \" {only_billed_clause}\" \" ) \" \"{group_by_clause} \" \"ORDER BY", "= self.get_group_by_clause(group_by_mask) query = str( \"SELECT \" \" Tasks.id as tid, Tasks.name as", "clause by bit mask\"\"\" def set_group_by_clause(bits, value, group_by): \"\"\"Add a field to group_by", "Tracks \" \"WHERE \" \" Tasks.project_id == Projects.id AND \" \" Tracks.task_id ==", "def set_group_by_clause(bits, value, group_by): \"\"\"Add a field to group_by clause\"\"\" if mask &", "as pname, \" \" Tracks.id as track_id, Tracks.started as started, \" \" Tracks.finished", "self.cursor.execute( \"SELECT \" \" id as pid, name as name, created as created,", "{where_project_clause}\" \" Tracks.task_id == tid AND \" \" Tasks.project_id == Projects.id\" \"\".format(where_task_clause=where_task_clause, where_project_clause=where_project_clause),", "== Projects.id AND \" \" Tracks.task_id == Tasks.id AND \" \" Tracks.id IN", "\"WHERE id=?\", (name.encode('utf8'), description.encode('utf8'), pid) ) self.conn.commit() def is_project_existent(self, pname, pid): \"\"\"Checks if", "timedelta(seconds=3600)) started = datetime.datetime.now() - timedelta(seconds=3300) self.create_track(last_task, started=started, finished=started + timedelta(seconds=600)) last_track =", "BY Tracks.id\".format(started=started, finished=finished, where_clause=where_clause, between_clause=between_clause), params ) return self.cursor.fetchall() def get_track_by_id(self, tid): self.cursor.execute(", "finished def update_track(self, track_id, started, finished, is_billed): \"\"\"Updates the time was spend and", "TEXT, ' 'created TIMESTAMP' ')') self.conn.commit() def __init__(self, db_name): # create DB self.init_db(db_name)", "Projects.name as pname, \" \" SUM(STRFTIME('%s', finished)-STRFTIME('%s', started)) as spent,\" \" Tracks.started as", "not started: started = datetime.datetime.now() self.cursor.execute( \"INSERT INTO Tracks \" \" ('task_id', 'started',", "FROM Tracks \" \" {where_clause} \" \" GROUP BY Tracks.task_id \" \" )", "?\", (pname.encode('utf8'),) ) return self.cursor.fetchone() def update_project(self, pid, name, description): \"\"\"Updates a project\"\"\"", "= where_task_clause = '' if tname: tname = tname.encode('utf8') where_task_clause = \"tname ==", "tasks\"\"\" self.cursor.execute('DELETE FROM Customers') self.cursor.execute('DELETE FROM Projects') self.cursor.execute('DELETE FROM Tasks') self.cursor.execute('DELETE FROM Tracks')", "self.get_timesheet_select_clause(group_by_mask) query = \"SELECT {clause} FROM ({query})\".format( query=query, clause=select_clause) self.cursor.execute(query, params) return self.cursor.fetchall()", "sqlite3 import random import string import time import datetime from datetime import timedelta", "DESC LIMIT %d) ORDER BY pid ASC\" % limit if from_date and to_date:", "return self.cursor.lastrowid def get_task_or_create(self, name, project_id): \"\"\"Get a task or create one\"\"\" self.cursor.execute(", "self.conn.commit() return finished def update_track(self, track_id, started, finished, is_billed): \"\"\"Updates the time was", "\" Tasks.id as tid, Tasks.name as tname, Projects.name as pname, \" \" DATE(started)", "from tabulate import tabulate import config TS_GROUP_BY = dict( timestamp=0b10000, project=0b1000, task=0b0100, track=0b0010,", "params.extend([started, finished]) group_by_clause = self.get_group_by_clause(group_by_mask) query = str( \"SELECT \" \" Tasks.id as", "lambda x: x.decode('utf8') #try: #except sqlite3.OperationalError: self.cursor = self.conn.cursor() def close_db(self): self.conn.close() def", "finished == ''\") return self.cursor.fetchall() def get_active_task(self, started='', finished='', tname='', pname=''): \"\"\"Get an", "timedelta(seconds=3601)) self.create_track(last_task, started=started+timedelta(seconds=13600), finished=started+timedelta(seconds=14600)) self.create_track(last_task, started=started+timedelta(seconds=15600), finished=started+timedelta(seconds=16600)) last_task = self.insert_test_task(project_id=1) self.create_track(last_task, started=started+timedelta(seconds=17600), finished=started+timedelta(seconds=18600))", "\" finished == ''\") return self.cursor.fetchall() def get_active_task(self, started='', finished='', tname='', pname=''): \"\"\"Get", "\" \" FROM Tracks \" \"WHERE \" \" DATE(started) BETWEEN ? AND ?\"", "60 seconds = round_to - delta.seconds % round_to finished = finished + datetime.timedelta(seconds=seconds)", "\" Tasks.project_id == Projects.id AND \" \" (\" \" DATE(started) BETWEEN ? AND", "\" params.append(pname) self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as tname, Projects.name", "first_limit_clause=first_limit_clause, last_limit_clause=last_limit_clause) ) return self.cursor.fetchall() def create_project(self, pname, description=''): \"\"\"Create a project\"\"\" self.cursor.execute(", "as tname, Projects.id as pid, \" \" Projects.name as pname, Tasks.description as description", "Tracks.task_id == tid AND \" \" Tasks.project_id == Projects.id AND \" \" trid", "tabulate import tabulate import config TS_GROUP_BY = dict( timestamp=0b10000, project=0b1000, task=0b0100, track=0b0010, date=0b0001", "\"\".format( where_clause=where_clause, first_limit_clause=first_limit_clause, last_limit_clause=last_limit_clause) ) tasks = self.cursor.fetchall() return tasks def get_task_by_alias(self, tname,", "\"AND NOT finished == '' \" self.cursor.execute( \"DELETE \" \" FROM Tracks \"", "# TRACKS def get_tracks_by_date(self, started='', finished='', also_unfinished=False): \"\"\"Get tracks\"\"\" where_clause = '' between_clause", "a project\"\"\" self.cursor.execute( \"INSERT INTO Projects ('name', 'description', created)\" \"VALUES (?, ?, ?)\",", "AND \" \" pid == '{project!s}'\" \"\".format(task=name.encode('utf8'), project=project_id) ) last = self.cursor.fetchone() if", "1 \" params.extend([started, finished]) group_by_clause = self.get_group_by_clause(group_by_mask) query = str( \"SELECT \" \"", "Projects.description, \" \" SUM(CASE WHEN Tracks.finished == '' THEN 1 ELSE 0 end)", "self.insert_test_task(project_id=2) self.create_track(last_task, started=started+timedelta(seconds=21600), finished=started+timedelta(seconds=22600)) self.create_track(last_task, started=started+timedelta(seconds=23600), finished=started+timedelta(seconds=24600)) self.create_track(last_task, started=started+timedelta(seconds=25600), finished=started+timedelta(seconds=26600)) started = datetime.datetime.now()", "tid ) ) self.conn.commit() def delete_task(self, tid): \"\"\"\"\"\" self.cursor.execute( \"DELETE FROM Tasks WHERE", "spent - 4 # date, tname, pname, started, finished, spent date_field = (0,", "set_group_by_clause(TS_GROUP_BY['date'], 'DATE(started)', '') group_by = set_group_by_clause(TS_GROUP_BY['project'], 'Tasks.project_id', group_by) group_by = set_group_by_clause(TS_GROUP_BY['task'], 'Tracks.task_id', group_by)", "pname, started, finished, spent date_field = (0, 'DATE(started) as \"date [date]\"', 'Date') task_field", "get_customer_or_create(self, customer): self.cursor.execute( \"SELECT id, name FROM Customers \" \"WHERE name == '{name:s}'\".format(name=customer)", "Tasks, Projects \" \"WHERE \" \" Tracks.task_id == Tasks.id AND \" \" Tasks.project_id", "\" \" Tracks.task_id == Tasks.id \" \"GROUP BY Tasks.id \" \"ORDER BY Tasks.id", "= str( \"SELECT \" \" Tasks.id as tid, Tasks.name as tname, Projects.name as", "Project #2 self.create_project('p2', 'Test Project #1') self.cursor.execute(\"SELECT * FROM Projects ORDER BY id", "ASC\" % limit self.cursor.execute( \"{first_limit_clause}\" \"SELECT \" \" Tasks.id as tid, Tasks.name as", ") tasks = self.cursor.fetchall() return tasks def get_profiled_tasks(self, started='', finished='', limit=0): \"\"\"The list", "id INTEGER PRIMARY KEY, ' ' project_id INTEGER REFERENCES Projects(id) ON DELETE CASCADE,", "\"WHERE \" \" Tracks.task_id == tid AND \" \" Tasks.project_id == Projects.id AND", "\" Tracks.task_id == Tasks.id {where_clause}\" \"GROUP BY Projects.id \" \"UNION SELECT \" \"", "where_project_clause = \"pname == ? AND \" if only_billed: only_billed_clause = \" AND", "\"DELETE FROM Tasks WHERE id == '{tid}'\".format(tid=tid)) self.conn.commit() # TRACKS def get_tracks_by_date(self, started='',", "where_project_clause = \"pname == ? AND \" params.append(pname) if started and finished: where_date_clause", "pid): \"\"\"Checks if project already exists \"\"\" self.cursor.execute( \"SELECT \" \" id as", "tid): self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as tname, Projects.name as", "self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as tname, Projects.id as pid,", "FROM Projects') self.cursor.execute('DELETE FROM Tasks') self.cursor.execute('DELETE FROM Tracks') # Add a Customer self.cursor.execute(", "= \" DESC LIMIT %d) ORDER BY tid ASC\" % limit self.cursor.execute( \"{first_limit_clause}\"", "''.join(random.choice( string.ascii_uppercase + string.digits) for _ in range(3)) self.cursor.execute( \"insert into Tasks ('name',", "limit: first_limit_clause = \"SELECT * FROM (\" last_limit_clause = \" DESC LIMIT %d)", "\" \"WHERE name == '{name:s}'\".format(name=customer) ) customer = self.cursor.fetchone() return customer def get_customer_or_create(self,", "\"tname == ? AND \" if pname: params.append(pname.encode('utf8')) where_project_clause = \"pname == ?", "' description TEXT DEFAULT \"\"' ')') # TRACKS self.cursor.execute( 'CREATE TABLE IF NOT", "\" \"WHERE \" \" DATE(started) BETWEEN ? AND ?\" \" {where_clause}\" \"\".format(where_clause=where_clause), (started,", "self.cursor.execute( \"UPDATE Tasks \" \"SET name=?, description=?\" \"WHERE id=?\", ( name.encode('utf8'), description.encode('utf8'), tid", "task_id, started='', finished='', is_billed=True): # started, finished - 9-item sequence, not float if", "?\" \" {where_clause}\" \"\".format(where_clause=where_clause), (started, finished) ) self.conn.commit() # TIMESHEET def get_group_by_clause(self, mask):", "# date - 1 # task - 2 # project - 3 #", "tname, Projects.id as pid, \" \" Projects.name as pname, Tasks.description as description, \"", "\" \" (?, ?)\", ( name.encode('utf8'), pid ) ) self.conn.commit() return self.cursor.lastrowid def", "finished=started + timedelta(seconds=600)) last_track = self.create_track(last_task) self.cursor.execute(\"SELECT * FROM Tracks \") tracks =", "GROUP BY Tracks.task_id \" \" ) ORDER BY tid {last_limit_clause}\" \"\".format( where_clause=where_clause, first_limit_clause=first_limit_clause,", "return group_by def get_timesheet_fields(self, mask, get_headers=False): \"\"\"Makes a list of ordered fields\"\"\" #", "customer = self.cursor.fetchone() return customer def get_customer_or_create(self, customer): self.cursor.execute( \"SELECT id, name FROM", "as pid, name as name, created as created, \" \" description as description", "add_activity: activity_field = \", SUM(CASE WHEN Tracks.finished == '' THEN 1 ELSE 0", "== '{name}'\".format(name=pname.encode('utf8'), pid=pid) ) return self.cursor.fetchone() def get_projects_with_activity_field(self, from_date='', to_date='', limit=0): \"\"\"Get list", "if mask & bits: if group_by: group_by = \"%s,\" % group_by group_by =", "#except sqlite3.OperationalError: self.cursor = self.conn.cursor() def close_db(self): self.conn.close() def create_db(self): self.cursor.execute(\"PRAGMA foreign_keys =", "Tracks.finished as finished \" \"FROM Tracks, Tasks, Projects \" \"WHERE \" \" {where_task_clause}\"", "\" \"WHERE \" \" Tracks.task_id == Tasks.id AND \" \" Tasks.project_id == Projects.id", "name as pname, created as created, \" \" description as description \" \"FROM", "tname, Projects.name as pname, \" \" Tracks.id as trid, Tracks.started as started, \"", "group_by) group_by = set_group_by_clause(TS_GROUP_BY['task'], 'Tracks.task_id', group_by) group_by = set_group_by_clause(TS_GROUP_BY['track'], 'Tracks.id', group_by) if group_by:", "where_clause = '' between_clause = '' params = [] if not also_unfinished: where_clause", "finished=started+timedelta(seconds=22600)) self.create_track(last_task, started=started+timedelta(seconds=23600), finished=started+timedelta(seconds=24600)) self.create_track(last_task, started=started+timedelta(seconds=25600), finished=started+timedelta(seconds=26600)) started = datetime.datetime.now() - timedelta(days=3) self.create_track(last_task,", "set_group_by_clause(bits, value, group_by): \"\"\"Add a field to group_by clause\"\"\" if mask & bits:", "started = datetime.datetime.now() - timedelta(days=4) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3601)) self.create_track(last_task, started=started+timedelta(seconds=13600), finished=started+timedelta(seconds=14600))", "NOT finished == '' \" if started and finished: between_clause = \"AND DATE(started)", "tname='', pname=''): \"\"\"Get a minimal tracked date\"\"\" params = [] where_project_clause = where_task_clause", "name.encode('utf8'), description.encode('utf8'), tid ) ) self.conn.commit() def delete_task(self, tid): \"\"\"\"\"\" self.cursor.execute( \"DELETE FROM", "started)) as spent,\" \" Tracks.started as started, \" \" Tracks.finished as finished \"", "== '' \" self.cursor.execute( \"DELETE \" \" FROM Tracks \" \"WHERE \" \"", "list of fields\"\"\" fields = self.get_timesheet_fields(mask) return ', '.join(fields) def get_minimal_started_track(self, tname='', pname=''):", "as tid, Tasks.name as tname, Projects.name as pname, \" \" Tracks.id as trid,", "Projects \" \"WHERE NOT EXISTS (\" \" SELECT id FROM Tasks WHERE \"", "\"SELECT \" \" Tasks.id, Tasks.name, Projects.id, Projects.name, \" \" Tasks.description {activity_field}\" \"FROM Tasks,", "\" \" ) ORDER BY tid {last_limit_clause}\" \"\".format( where_clause=where_clause, first_limit_clause=first_limit_clause, last_limit_clause=last_limit_clause) ) tasks", "'is_billed') \" \"VALUES (?, ?, ?, ?)\", (task_id, started, finished, int(is_billed)) ) self.conn.commit()", "== tid AND \" \" Tasks.project_id == Projects.id AND \" \" (\" \"", ") self.conn.commit() # PROJECTS def get_project_by_name(self, pname): self.cursor.execute( \"SELECT \" \" id as", "\" Tracks.task_id == Tasks.id AND \" \" Tasks.project_id == Projects.id AND \" \"", "NOT finished == '' \" self.cursor.execute( \"DELETE \" \" FROM Tracks \" \"WHERE", "\"VALUES ('{name:s}')\" .format(name=customer) ) self.conn.commit() # PROJECTS def get_project_by_name(self, pname): self.cursor.execute( \"SELECT \"", "BETWEEN ? AND ?\" \" {where_clause}\" \"\".format(where_clause=where_clause), (started, finished) ) self.conn.commit() # TIMESHEET", "self.cursor.execute(\"SELECT * FROM Customers ORDER BY id LIMIT 1\") customers = self.cursor.fetchone() #print('filled", "limit=0): \"\"\"The list of last tasks between dates including unfinished\"\"\" where_clause = first_limit_clause", "float if not started: started = datetime.datetime.now() self.cursor.execute( \"INSERT INTO Tracks \" \"", "in range(3)) self.cursor.execute( \"insert into Tasks ('name', 'project_id') \" \"values('%s', '%s')\" % (name,", "WHEN Tracks.finished == '' THEN 1 ELSE 0 END) \" self.cursor.execute( \"SELECT \"", "\"VALUES ('Andrey', 'Customer Numer One')\") self.cursor.execute(\"SELECT * FROM Customers ORDER BY id LIMIT", "'Task id', 'started', 'finished', 'billed'], tablefmt='simple')) return # CUSTOMERS def get_customer(self, customer): self.cursor.execute(", "\" \"WHERE \" \" Tasks.project_id == Projects.id AND \" \" Tracks.task_id == Tasks.id", "including unfinished\"\"\" where_clause = first_limit_clause = last_limit_clause = '' if started and finished:", "' ' finished TIMESTAMP, ' ' is_billed INTEGER DEFAULT 1' ')') # CUSTOMERS", "('name')\" \"VALUES ('{name:s}')\" .format(name=customer) ) self.conn.commit() # PROJECTS def get_project_by_name(self, pname): self.cursor.execute( \"SELECT", "= round_to - delta.seconds % round_to finished = finished + datetime.timedelta(seconds=seconds) self.cursor.execute( \"UPDATE", "NOT EXISTS Customers(' 'id INTEGER PRIMARY KEY, ' 'name VARCHAR UNIQUE COLLATE NOCASE,", "spent for a task/project\"\"\" params = [] only_billed_clause = where_project_clause = where_task_clause =", "Tasks.id \" \"GROUP BY Tasks.id \" \"ORDER BY Tasks.id DESC LIMIT {limit:d}\".format( limit=limit,", "[] if not also_unfinished: where_clause = \"AND NOT finished == '' \" if", "self.create_track(last_task, started=started+timedelta(seconds=17600), finished=started+timedelta(seconds=18600)) self.create_track(last_task, started=started+timedelta(seconds=19600), finished=started+timedelta(seconds=20600)) # Add a Project #2 self.create_project('p2', 'Test", "finished\"\"\" where_clause = first_limit_clause = last_limit_clause = '' if limit: first_limit_clause = \"SELECT", "\" \"FROM Tasks, Projects \" \"WHERE \" \" tname == '{task}' AND \"", ") self.conn.commit() return self.cursor.lastrowid def get_task_or_create(self, name, project_id): \"\"\"Get a task or create", "'{pid}'\" \" name == '{name}'\".format(name=pname.encode('utf8'), pid=pid) ) return self.cursor.fetchone() def get_projects_with_activity_field(self, from_date='', to_date='',", "as started, Tracks.finished as finished \" \"FROM Tasks, Projects, Tracks \" \"WHERE \"", "Projects.created,\" \" Projects.description, '' as active \" \"FROM Projects \" \"WHERE NOT EXISTS", "Tracks.id\".format(started=started, finished=finished, where_clause=where_clause, between_clause=between_clause), params ) return self.cursor.fetchall() def get_track_by_id(self, tid): self.cursor.execute( \"SELECT", "started=started+timedelta(seconds=13600), finished=started+timedelta(seconds=14600)) self.create_track(last_task, started=started+timedelta(seconds=15600), finished=started+timedelta(seconds=16600)) last_task = self.insert_test_task(project_id=1) self.create_track(last_task, started=started+timedelta(seconds=17600), finished=started+timedelta(seconds=18600)) self.create_track(last_task, started=started+timedelta(seconds=19600),", "last_limit_clause = '' if limit: first_limit_clause = \"SELECT * FROM (\" last_limit_clause =", "and is billed flag of the track record\"\"\" self.cursor.execute( \"UPDATE Tracks \" \"SET", "\" Projects.name as pname, Tasks.description as description, \" \" Tracks.started as started, Tracks.finished", "= lambda x: x.decode('utf8') #try: #except sqlite3.OperationalError: self.cursor = self.conn.cursor() def close_db(self): self.conn.close()", "self.cursor.execute( \"UPDATE Projects \" \"SET name=?, description=?\" \"WHERE id=?\", (name.encode('utf8'), description.encode('utf8'), pid) )", "import random import string import time import datetime from datetime import timedelta import", "started, finished, is_billed): \"\"\"Updates the time was spend and is billed flag of", "\" \" Tasks.project_id == Projects.id AND \" \" Tracks.task_id == Tasks.id {where_clause}\" \"GROUP", "Projects.id AND \" \" Tracks.task_id == Tasks.id \" \"GROUP BY Tasks.id \" \"ORDER", "\" Projects.name == ?\", (pname.encode('utf8'),) ) return self.cursor.fetchone() def update_project(self, pid, name, description):", "== tid AND \" \" Tasks.project_id == Projects.id\" \"\".format(where_task_clause=where_task_clause, where_project_clause=where_project_clause), params) return self.cursor.fetchone()", "end) AS active \" \"FROM Projects, Tracks, Tasks \" \"WHERE \" \" Tasks.project_id", "VARCHAR UNIQUE COLLATE NOCASE, ' 'description TEXT, ' 'created TIMESTAMP' ')') self.conn.commit() def", "started and finished: where_clause = str( \"WHERE DATE(Tracks.started) BETWEEN '{started}' AND '{finished}'\" \"\".format(started=started,", "the Task last_task = self.insert_test_task(project_id=1) # Add the Tracks started = datetime.datetime.now() -", ") ) self.conn.commit() return self.cursor.lastrowid def get_task_or_create(self, name, project_id): \"\"\"Get a task or", "date, tname, pname, started, finished, spent date_field = (0, 'DATE(started) as \"date [date]\"',", "== ? AND \" params.append(tname) if pname: pname = pname.encode('utf8') where_project_clause = \"pname", "\"FROM Tasks, Projects, Tracks \" \"WHERE \" \" Tasks.project_id == Projects.id AND \"", "AND \" \" finished == ''\") return self.cursor.fetchall() def get_active_task(self, started='', finished='', tname='',", "tracks by the date\"\"\" if not also_unfinished: where_clause = \"AND NOT finished ==", "finished TIMESTAMP, ' ' is_billed INTEGER DEFAULT 1' ')') # CUSTOMERS self.cursor.execute( 'CREATE", "AND \" \" Tasks.project_id == Projects.id AND \" \" (\" \" DATE(started) BETWEEN", "Projects.name as pname, \" \" Tracks.id as trid, Tracks.started as started, \" \"", "\" \"UNION SELECT \" \" Projects.id as pid, Projects.name, Projects.created,\" \" Projects.description, ''", "PRIMARY KEY, ' ' task_id INTEGER REFERENCES Tasks(id) ON DELETE CASCADE, ' '", "if project already exists \"\"\" self.cursor.execute( \"SELECT \" \" id as pid, name", "Tracks.task_id == Tasks.id AND \" \" Tasks.project_id == Projects.id AND \" \" finished", "\" \" Tasks.project_id == Projects.id\" \"\".format(where_task_clause=where_task_clause, where_project_clause=where_project_clause), params) return self.cursor.fetchone() def get_timesheet(self, started,", "Tracks SET finished=? WHERE id=?\", (finished, track_id) ) self.conn.commit() return finished def update_track(self,", "where_project_clause=where_project_clause), params) return self.cursor.fetchone() def get_timesheet(self, started, finished, group_by_mask, only_billed=True, tname='', pname=''): \"\"\"", "\"SET started=?, finished=?, is_billed=? \" \"WHERE id=?\", (started, finished, is_billed, track_id) ) self.conn.commit()", "pid ASC\" % limit if from_date and to_date: where_clause = \" AND DATE(Projects.created)", "is_billed, track_id) ) self.conn.commit() def delete_tracks_by_date(self, started, finished, also_unfinished=False): \"\"\"Deletes tracks by the", "from datetime import timedelta import operator from tabulate import tabulate import config TS_GROUP_BY", "project - 3 # spent - 4 # date, tname, pname, started, finished,", "class Database: def init_db(self, db_path): self.conn = sqlite3.connect( db_path, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES ) self.conn.row_factory =", "Project self.create_project('p1', 'Test Project #1') self.cursor.execute(\"SELECT * FROM Projects ORDER BY id LIMIT", "\"SELECT \" \" Tasks.id as tid, Tasks.name as tname, Projects.id as pid, \"", "where_date_clause = \"AND DATE(Tracks.started) \" \\ \" BETWEEN ? \" \\ \" AND", "pname): self.cursor.execute( \"DELETE FROM Projects WHERE name == '{name}'\" \"\".format(name=pname.encode('utf8'))) self.conn.commit() # TASKS", "description=''): \"\"\"Updates the task info\"\"\" self.cursor.execute( \"UPDATE Tasks \" \"SET name=?, description=?\" \"WHERE", "return group_by group_by = set_group_by_clause(TS_GROUP_BY['date'], 'DATE(started)', '') group_by = set_group_by_clause(TS_GROUP_BY['project'], 'Tasks.project_id', group_by) group_by", "set_group_by_clause(TS_GROUP_BY['track'], 'Tracks.id', group_by) if group_by: group_by = \"GROUP BY %s \" % group_by", "\" Projects.id as pid, Projects.name as pname, \" \" Tracks.id as trid, Tracks.started", "\" \" Tracks.id IN (\" \" SELECT MAX(Tracks.id) FROM Tracks \" \" {where_clause}", "\" \" pid == '{pid}'\" \" name == '{name}'\".format(name=pname.encode('utf8'), pid=pid) ) return self.cursor.fetchone()", "= first_limit_clause = last_limit_clause = '' if limit: first_limit_clause = \"SELECT * FROM", "\" \"FROM Projects, Tracks, Tasks \" \"WHERE \" \" Tasks.project_id == Projects.id AND", "# CUSTOMERS self.cursor.execute( 'CREATE TABLE IF NOT EXISTS Customers(' 'id INTEGER PRIMARY KEY,", "as trid, Tracks.started as started, \" \" Tracks.finished as finished, \" \" Tracks.is_billed", "pname = pname.encode('utf8') where_project_clause = \"pname == ? AND \" params.append(pname) if started", "Tasks, Projects \" \"WHERE \" \" {where_task_clause}\" \" {where_project_clause}\" \" Tracks.task_id == tid", "KEY, ' ' customer_id INTEGER, ' ' name VARCHAR UNIQUE COLLATE NOCASE, '", "finished='', is_billed=True): # started, finished - 9-item sequence, not float if not started:", "as tname, Projects.name as pname, \" \" Tracks.id as track_id, Tracks.started as started,", "pname, pid): \"\"\"Checks if project already exists \"\"\" self.cursor.execute( \"SELECT \" \" id", "tid, name, description=''): \"\"\"Updates the task info\"\"\" self.cursor.execute( \"UPDATE Tasks \" \"SET name=?,", "tabulate import config TS_GROUP_BY = dict( timestamp=0b10000, project=0b1000, task=0b0100, track=0b0010, date=0b0001 ) class", "Spent') clause = set() if mask & TS_GROUP_BY['date']: clause.add(date_field) if mask & TS_GROUP_BY['task']:", "pid AND \" \" tname == '{task:s}' AND \" \" pname == '{project:s}'\"", "#print('filled projects', project) # Add the Task last_task = self.insert_test_task(project_id=1) # Add the", "\" \"FROM Tasks, Projects, Tracks \" \"WHERE \" \" Tasks.project_id == Projects.id AND", "= first_limit_clause = last_limit_clause = '' if started and finished: where_clause = str(", "1' ')') # CUSTOMERS self.cursor.execute( 'CREATE TABLE IF NOT EXISTS Customers(' 'id INTEGER", "== Tasks.id AND \" \" Tasks.project_id == Projects.id AND \" \" finished ==", "pname, \" \" Tracks.id as track_id, Tracks.started as started, \" \" Tracks.finished as", "\"AND '{to_date}' \".format(from_date=from_date, to_date=to_date) self.cursor.execute( \"{first_limit_clause}\" \"SELECT \" \" Projects.id as pid, Projects.name,", "self.create_track(last_task, started=started+timedelta(seconds=15600), finished=started+timedelta(seconds=16600)) last_task = self.insert_test_task(project_id=1) self.create_track(last_task, started=started+timedelta(seconds=17600), finished=started+timedelta(seconds=18600)) self.create_track(last_task, started=started+timedelta(seconds=19600), finished=started+timedelta(seconds=20600)) #", "if last: return last['tid'] return self.create_task(name, project_id) def _get_active_tasks(self): \"\"\"Get active tasks\"\"\" self.cursor.execute(", "Tasks.id as tid, Tasks.name as tname, Projects.name as pname, \" \" SUM(STRFTIME('%s', finished)-STRFTIME('%s',", "Project #1') self.cursor.execute(\"SELECT * FROM Projects ORDER BY id LIMIT 1\") project =", "= set() if mask & TS_GROUP_BY['date']: clause.add(date_field) if mask & TS_GROUP_BY['task']: clause.update([task_field, project_field])", "self.cursor.fetchone() def get_timesheet(self, started, finished, group_by_mask, only_billed=True, tname='', pname=''): \"\"\" Gets the time", "pid): self.cursor.execute( \"INSERT INTO Tasks ('name', 'project_id') \" \"VALUES \" \" (?, ?)\",", "\"FROM Projects \" \"WHERE \" \" pid == '{pid}'\" \" name == '{name}'\".format(name=pname.encode('utf8'),", "\"\"\"Updates the time was spend and is billed flag of the track record\"\"\"", "clause.add(spent_field) to_get = 2 if get_headers else 1 return map(operator.itemgetter(to_get), sorted(clause, key=operator.itemgetter(0))) def", "\"SELECT \" \" Tasks.id as tid, Tasks.name as tname, \" \" Projects.id as", "description.encode('utf8'), str(datetime.datetime.now()) ) ) self.conn.commit() return self.cursor.lastrowid def get_project_or_create(self, pname): self.cursor.execute( \"SELECT id,", "last['tid'] return self.create_task(name, project_id) def _get_active_tasks(self): \"\"\"Get active tasks\"\"\" self.cursor.execute( \"SELECT \" \"", "str(datetime.datetime.now()) ) ) self.conn.commit() return self.cursor.lastrowid def get_project_or_create(self, pname): self.cursor.execute( \"SELECT id, name", "Tasks.name as tname, Projects.name as pname, \" \" Tracks.id as track_id, Tracks.started as", "name=?, description=?\" \"WHERE id=?\", (name.encode('utf8'), description.encode('utf8'), pid) ) self.conn.commit() def is_project_existent(self, pname, pid):", "AS active \" \"FROM Projects, Tracks, Tasks \" \"WHERE \" \" Tasks.project_id ==", "\"VALUES (?, ?, ?)\", ( pname.encode('utf8'), description.encode('utf8'), str(datetime.datetime.now()) ) ) self.conn.commit() return self.cursor.lastrowid", "tid, Tasks.name as tname, Projects.name as pname, \" \" SUM(STRFTIME('%s', finished)-STRFTIME('%s', started)) as", "finished_field = (4, 'DATETIME(finished) as \"finished [timestamp]\"', 'To') spent_field = (5, 'spent', 'Time", "\" {where_task_clause}\" \" {where_project_clause}\" \" Tracks.task_id == Tasks.id AND \" \" Tasks.project_id ==", "== Tasks.id AND \" \" Tracks.id IN (\" \" SELECT MAX(Tracks.id) FROM Tracks", "' ' description TEXT DEFAULT \"\", ' ' created TIMESTAMP' ')') # TASKS", "time import datetime from datetime import timedelta import operator from tabulate import tabulate", "id LIMIT 1\") customers = self.cursor.fetchone() #print('filled customers', customers) # Add a Project", "IF NOT EXISTS Tasks(' ' id INTEGER PRIMARY KEY, ' ' project_id INTEGER", "\" Projects.id as pid, Projects.name, Projects.created, \" \" Projects.description, \" \" SUM(CASE WHEN", "== tid AND \" \" Tasks.project_id == Projects.id AND \" \" trid ==", "Priority: # datetime - 0 # date - 1 # task - 2", "PROJECTS self.cursor.execute( 'CREATE TABLE IF NOT EXISTS Projects(' ' id INTEGER PRIMARY KEY,", "PRIMARY KEY, ' ' project_id INTEGER REFERENCES Projects(id) ON DELETE CASCADE, ' '", "time was spent for a task/project\"\"\" params = [] only_billed_clause = where_project_clause =", "# TASKS self.cursor.execute( 'CREATE TABLE IF NOT EXISTS Tasks(' ' id INTEGER PRIMARY", "= self.cursor.fetchone() #print('filled projects', project) # Add the Task tasks = [] last_task", "? AND \" params.append(tname) if pname: pname = pname.encode('utf8') where_project_clause = \"pname ==", "\" \"WHERE id=?\", (started, finished, is_billed, track_id) ) self.conn.commit() def delete_tracks_by_date(self, started, finished,", "* FROM (\" last_limit_clause = \" DESC LIMIT %d) ORDER BY pid ASC\"", "group_by return group_by def get_timesheet_fields(self, mask, get_headers=False): \"\"\"Makes a list of ordered fields\"\"\"", "\" {where_project_clause}\" \" Tracks.task_id == Tasks.id AND \" \" Tasks.project_id == Projects.id AND", "customer self.cursor.execute( \"INSERT INTO Customers ('name')\" \"VALUES ('{name:s}')\" .format(name=customer) ) self.conn.commit() # PROJECTS", "self.create_project(name) def delete_project_by_name(self, pname): self.cursor.execute( \"DELETE FROM Projects WHERE name == '{name}'\" \"\".format(name=pname.encode('utf8')))", "finished, group_by_mask, only_billed=True, tname='', pname=''): \"\"\" Gets the time was spent for a", "if started and finished: where_clause = str( \"WHERE DATE(Tracks.started) BETWEEN '{started}' AND '{finished}'\"", "COLLATE NOCASE, ' 'description TEXT, ' 'created TIMESTAMP' ')') self.conn.commit() def __init__(self, db_name):", "#print('filled customers', customers) # Add a Project self.create_project('p1', 'Test Project #1') self.cursor.execute(\"SELECT *", "1 return map(operator.itemgetter(to_get), sorted(clause, key=operator.itemgetter(0))) def get_timesheet_select_clause(self, mask): \"\"\"Get prepared select's clause list", "Tables if do the not exist # PROJECTS self.cursor.execute( 'CREATE TABLE IF NOT", "One')\") self.cursor.execute(\"SELECT * FROM Customers ORDER BY id LIMIT 1\") customers = self.cursor.fetchone()", "VARCHAR UNIQUE COLLATE NOCASE, ' ' description TEXT DEFAULT \"\", ' ' created", "DEFAULT \"\"' ')') # TRACKS self.cursor.execute( 'CREATE TABLE IF NOT EXISTS Tracks(' '", "by bit mask\"\"\" def set_group_by_clause(bits, value, group_by): \"\"\"Add a field to group_by clause\"\"\"", "insert_test_task(self, project_id): name = ''.join(random.choice( string.ascii_uppercase + string.digits) for _ in range(3)) self.cursor.execute(", "self.create_track(last_task, started=started, finished=started + timedelta(seconds=3600)) started = datetime.datetime.now() - timedelta(days=2) self.create_track(last_task, started=started, finished=started", "get_minimal_started_track(self, tname='', pname=''): \"\"\"Get a minimal tracked date\"\"\" params = [] where_project_clause =", "Tasks.id {where_clause}\" \"GROUP BY Projects.id \" \"UNION SELECT \" \" Projects.id as pid,", "UNIQUE COLLATE NOCASE, ' ' description TEXT DEFAULT \"\", ' ' created TIMESTAMP'", "delete_project_by_name(self, pname): self.cursor.execute( \"DELETE FROM Projects WHERE name == '{name}'\" \"\".format(name=pname.encode('utf8'))) self.conn.commit() #", "= '' if tname: params.append(tname.encode('utf8')) where_task_clause = \"tname == ? AND \" if", "= \" AND DATE(Projects.created) BETWEEN '{from_date}' \" \\ \"AND '{to_date}' \".format(from_date=from_date, to_date=to_date) self.cursor.execute(", "including a field is a project is finished\"\"\" where_clause = first_limit_clause = last_limit_clause", "the track record\"\"\" self.cursor.execute( \"UPDATE Tracks \" \"SET started=?, finished=?, is_billed=? \" \"WHERE", "\" \"WHERE \" \" Tracks.task_id == tid AND \" \" Tasks.project_id == Projects.id", "as finished, \" \" Tasks.description as description \" \"FROM Tracks, Tasks, Projects \"", "= (1, 'tname', 'Task') project_field = (2, 'pname', 'Project') started_field = (3, 'DATETIME(started)", "\"SELECT \" \" id as pid, name as pname, created as created, \"", "last_task = self.insert_test_task(project_id=2) self.create_track(last_task, started=started+timedelta(seconds=21600), finished=started+timedelta(seconds=22600)) self.create_track(last_task, started=started+timedelta(seconds=23600), finished=started+timedelta(seconds=24600)) self.create_track(last_task, started=started+timedelta(seconds=25600), finished=started+timedelta(seconds=26600)) started", "finished=?, is_billed=? \" \"WHERE id=?\", (started, finished, is_billed, track_id) ) self.conn.commit() def delete_tracks_by_date(self,", "def get_customer_or_create(self, customer): self.cursor.execute( \"SELECT id, name FROM Customers \" \"WHERE name ==", "as description \" \"FROM Projects \" \"WHERE \" \" Projects.name == ?\", (pname.encode('utf8'),)", "Projects \" \"WHERE \" \" pid == '{pid}'\" \" name == '{name}'\".format(name=pname.encode('utf8'), pid=pid)", "SELECT MAX(Tracks.id) FROM Tracks \" \" {where_clause} \" \" GROUP BY Tracks.task_id \"", "Tracks, Tasks, Projects \" \"WHERE \" \" Tracks.task_id == Tasks.id AND \" \"", "AND \" \" Tracks.task_id == Tasks.id {where_clause}\" \"GROUP BY Projects.id \" \"UNION SELECT", "or create one\"\"\" self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as tname,", "Tracks.task_id == Tasks.id \" \"GROUP BY Tasks.id \" \"ORDER BY Tasks.id DESC LIMIT", "\"date [date]\"', 'Date') task_field = (1, 'tname', 'Task') project_field = (2, 'pname', 'Project')", "NOT EXISTS Projects(' ' id INTEGER PRIMARY KEY, ' ' customer_id INTEGER, '", "name VARCHAR UNIQUE COLLATE NOCASE, ' ' description TEXT DEFAULT \"\", ' '", "self.create_track(last_task, started=started+timedelta(seconds=19600), finished=started+timedelta(seconds=20600)) # Add a Project #2 self.create_project('p2', 'Test Project #1') self.cursor.execute(\"SELECT", "\" \" finished == ''\") return self.cursor.fetchall() def get_active_task(self, started='', finished='', tname='', pname=''):", "self.create_project('p2', 'Test Project #1') self.cursor.execute(\"SELECT * FROM Projects ORDER BY id LIMIT 1\")", "limit self.cursor.execute( \"{first_limit_clause}\" \"SELECT \" \" Tasks.id as tid, Tasks.name as tname, Projects.id", "started=started+timedelta(seconds=23600), finished=started+timedelta(seconds=24600)) self.create_track(last_task, started=started+timedelta(seconds=25600), finished=started+timedelta(seconds=26600)) started = datetime.datetime.now() - timedelta(days=3) self.create_track(last_task, started=started, finished=started", "BETWEEN '{started}' AND '{finished}'\" \"\".format(started=started, finished=finished)) if limit: first_limit_clause = \"SELECT * FROM", "track_id, started=None): finished = datetime.datetime.now() if started and config.BT_TIMESHEET_ROUNDING and config.BT_ROUNDING_INCREMENT: delta =", "Customers') self.cursor.execute('DELETE FROM Projects') self.cursor.execute('DELETE FROM Tasks') self.cursor.execute('DELETE FROM Tracks') # Add a", "Projects.description, '' as active \" \"FROM Projects \" \"WHERE NOT EXISTS (\" \"", "finished]) group_by_clause = self.get_group_by_clause(group_by_mask) query = str( \"SELECT \" \" Tasks.id as tid,", "?\" \" AND NOT Tracks.finished == ''\" \" {only_billed_clause}\" \" ) \" \"{group_by_clause}", "' task_id INTEGER REFERENCES Tasks(id) ON DELETE CASCADE, ' ' started TIMESTAMP, '", "Tracks.started as started, \" \" Tracks.finished as finished, \" \" Tracks.is_billed as is_billed", "\" \"VALUES (?, ?, ?, ?)\", (task_id, started, finished, int(is_billed)) ) self.conn.commit() return", "finished \" \"FROM Tracks, Tasks, Projects \" \"WHERE \" \" {where_task_clause}\" \" {where_project_clause}\"", "Create Tables if do the not exist # PROJECTS self.cursor.execute( 'CREATE TABLE IF", "get_profiled_tasks(self, started='', finished='', limit=0): \"\"\"The list of last tasks between dates including unfinished\"\"\"", "== Projects.id AND \" \" trid == %d\" % tid ) return self.cursor.fetchone()", "#print('filled tracks', tracks) print(tabulate(tracks, ['Track id', 'Task id', 'started', 'finished', 'billed'], tablefmt='simple')) return", "Tracks.task_id == Tasks.id AND \" \" Tracks.id IN (\" \" SELECT MAX(Tracks.id) FROM", "\"SELECT * FROM (\" last_limit_clause = \" DESC LIMIT %d) ORDER BY tid", "\" \"FROM Projects \" \"WHERE \" \" Projects.name == ?\", (pname.encode('utf8'),) ) return", "bits: if group_by: group_by = \"%s,\" % group_by group_by = '{group_by} {value}'.format(group_by=group_by, value=value)", "' started TIMESTAMP, ' ' finished TIMESTAMP, ' ' is_billed INTEGER DEFAULT 1'", "started, finished, group_by_mask, only_billed=True, tname='', pname=''): \"\"\" Gets the time was spent for", "= datetime.datetime.now() - timedelta(days=2) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3600)) started = datetime.datetime.now() -", "+ timedelta(seconds=3600)) started = datetime.datetime.now() - timedelta(seconds=3300) self.create_track(last_task, started=started, finished=started + timedelta(seconds=600)) last_track", "\" tname == '{task:s}' AND \" \" pname == '{project:s}'\" \"\".format(task=tname.encode('utf8'), project=pname.encode('utf8')) )", "== 1 \" params.extend([started, finished]) group_by_clause = self.get_group_by_clause(group_by_mask) query = str( \"SELECT \"", "started = datetime.datetime.now() self.cursor.execute( \"INSERT INTO Tracks \" \" ('task_id', 'started', 'finished', 'is_billed')", "SELECT \" \" Projects.id as pid, Projects.name, Projects.created,\" \" Projects.description, '' as active", "def get_tasks(self, limit=10, add_activity=False): \"\"\"Lists of last tasks\"\"\" activity_field = '' if add_activity:", "Tasks, Projects \" \"WHERE \" \" tname == '{task}' AND \" \" Tasks.project_id", "\" \" Tasks.project_id == pid AND \" \" pid == '{project!s}'\" \"\".format(task=name.encode('utf8'), project=project_id)", "finished, is_billed, track_id) ) self.conn.commit() def delete_tracks_by_date(self, started, finished, also_unfinished=False): \"\"\"Deletes tracks by", "started=started, finished=started + timedelta(seconds=3600)) started = datetime.datetime.now() - timedelta(days=2) self.create_track(last_task, started=started, finished=started +", "tname='', pname=''): \"\"\" Gets the time was spent for a task/project\"\"\" params =", "project = self.cursor.fetchone() #print('filled projects', project) # Add the Task tasks = []", "%s \" % group_by return group_by def get_timesheet_fields(self, mask, get_headers=False): \"\"\"Makes a list", "REFERENCES Projects(id) ON DELETE CASCADE, ' ' name VARCHAR COLLATE NOCASE, ' '", "detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES ) self.conn.row_factory = sqlite3.Row self.conn.text_factory = lambda x: x.decode('utf8') #try: #except sqlite3.OperationalError:", "def fill(self): \"\"\"Fill with the test tasks\"\"\" self.cursor.execute('DELETE FROM Customers') self.cursor.execute('DELETE FROM Projects')", "not float if not started: started = datetime.datetime.now() self.cursor.execute( \"INSERT INTO Tracks \"", "name == '{name:s}'\".format(name=pname.encode('utf8')) ) project = self.cursor.fetchone() if project: return project return self.create_project(name)", "?, ?)\", ( pname.encode('utf8'), description.encode('utf8'), str(datetime.datetime.now()) ) ) self.conn.commit() return self.cursor.lastrowid def get_project_or_create(self,", "ON DELETE CASCADE, ' ' started TIMESTAMP, ' ' finished TIMESTAMP, ' '", "\"UPDATE Projects \" \"SET name=?, description=?\" \"WHERE id=?\", (name.encode('utf8'), description.encode('utf8'), pid) ) self.conn.commit()", "'{to_date}' \".format(from_date=from_date, to_date=to_date) self.cursor.execute( \"{first_limit_clause}\" \"SELECT \" \" Projects.id as pid, Projects.name, Projects.created,", "\" \" Tasks.project_id == Projects.id AND \" \" Tracks.task_id == Tasks.id \" \"GROUP", "= str( \"WHERE DATE(Tracks.started) BETWEEN '{started}' AND '{finished}'\" \"\".format(started=started, finished=finished)) if limit: first_limit_clause", "(started, finished) ) self.conn.commit() # TIMESHEET def get_group_by_clause(self, mask): \"\"\"Makes a GROUP BY", "self.get_timesheet_fields(mask) return ', '.join(fields) def get_minimal_started_track(self, tname='', pname=''): \"\"\"Get a minimal tracked date\"\"\"", "ORDER BY id LIMIT 1\") project = self.cursor.fetchone() #print('filled projects', project) # Add", "return self.cursor.fetchall() def get_active_task(self, started='', finished='', tname='', pname=''): \"\"\"Get an active task\"\"\" params", "started=started+timedelta(seconds=25600), finished=started+timedelta(seconds=26600)) started = datetime.datetime.now() - timedelta(days=3) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3600)) started", "\" \" tname == '{task:s}' AND \" \" pname == '{project:s}'\" \"\".format(task=tname.encode('utf8'), project=pname.encode('utf8'))", "sqlite3.OperationalError: self.cursor = self.conn.cursor() def close_db(self): self.conn.close() def create_db(self): self.cursor.execute(\"PRAGMA foreign_keys = ON\")", "time was spend and is billed flag of the track record\"\"\" self.cursor.execute( \"UPDATE", "Tasks.id as tid, Tasks.name as tname, Projects.name as pname, \" \" DATE(started) as", "finished=started + timedelta(seconds=3600)) started = datetime.datetime.now() - timedelta(days=1) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3600))", "pname, \" \" Tracks.id as trid, Tracks.started as started, \" \" Tracks.finished as", "FROM Customers ORDER BY id LIMIT 1\") customers = self.cursor.fetchone() #print('filled customers', customers)", "also_unfinished=False): \"\"\"Get tracks\"\"\" where_clause = '' between_clause = '' params = [] if", "TABLE IF NOT EXISTS Tasks(' ' id INTEGER PRIMARY KEY, ' ' project_id", "\" DATE(started) BETWEEN ? AND ?\" \" {where_clause}\" \"\".format(where_clause=where_clause), (started, finished) ) self.conn.commit()", "project = self.cursor.fetchone() #print('filled projects', project) # Add the Task last_task = self.insert_test_task(project_id=1)", "# spent - 4 # date, tname, pname, started, finished, spent date_field =", "'{task}' AND \" \" Tasks.project_id == pid AND \" \" pid == '{project!s}'\"", "\" AND Tracks.is_billed == 1 \" params.extend([started, finished]) group_by_clause = self.get_group_by_clause(group_by_mask) query =", "# started, finished - 9-item sequence, not float if not started: started =", "1 ELSE 0 end) AS active \" \"FROM Projects, Tracks, Tasks \" \"WHERE", "Tasks.name as tname, Projects.name as pname, \" \" Tracks.id as trid, Tracks.started as", "Add a Project self.create_project('p1', 'Test Project #1') self.cursor.execute(\"SELECT * FROM Projects ORDER BY", "LIMIT 1\") project = self.cursor.fetchone() #print('filled projects', project) # Add the Task last_task", "started, Tracks.finished as finished \" \"FROM Tasks, Projects, Tracks \" \"WHERE \" \"", "if limit: first_limit_clause = \"SELECT * FROM (\" last_limit_clause = \" DESC LIMIT", "== ? AND \" if pname: params.append(pname.encode('utf8')) where_project_clause = \"pname == ? AND", "= datetime.datetime.now() - timedelta(seconds=3300) self.create_track(last_task, started=started, finished=started + timedelta(seconds=600)) last_track = self.create_track(last_task) self.cursor.execute(\"SELECT", "')') # TRACKS self.cursor.execute( 'CREATE TABLE IF NOT EXISTS Tracks(' ' id INTEGER", "group_by: group_by = \"%s,\" % group_by group_by = '{group_by} {value}'.format(group_by=group_by, value=value) return group_by", "Tracks.task_id == tid AND \" \" Tasks.project_id == Projects.id\" \"\".format(where_task_clause=where_task_clause, where_project_clause=where_project_clause), params) return", "ORDER BY id LIMIT 1\") customers = self.cursor.fetchone() #print('filled customers', customers) # Add", "self.create_track(last_task) self.cursor.execute(\"SELECT * FROM Tracks \") tracks = self.cursor.fetchall() #print('filled tracks', tracks) print(tabulate(tracks,", ") return self.cursor.fetchall() def create_project(self, pname, description=''): \"\"\"Create a project\"\"\" self.cursor.execute( \"INSERT INTO", "project is finished\"\"\" where_clause = first_limit_clause = last_limit_clause = '' if limit: first_limit_clause", "BY Tracks.task_id \" \" ) ORDER BY tid {last_limit_clause}\" \"\".format( where_clause=where_clause, first_limit_clause=first_limit_clause, last_limit_clause=last_limit_clause)", "tid AND \" \" Tasks.project_id == Projects.id AND \" \" trid == %d\"", "project_id INTEGER REFERENCES Projects(id) ON DELETE CASCADE, ' ' name VARCHAR COLLATE NOCASE,", "Tasks, Projects \" \"WHERE \" \" Tasks.project_id == pid AND \" \" tname", "ORDER BY tid ASC\" % limit self.cursor.execute( \"{first_limit_clause}\" \"SELECT \" \" Tasks.id as", "\"WHERE NOT EXISTS (\" \" SELECT id FROM Tasks WHERE \" \" Tasks.project_id", "self.cursor.execute( \"UPDATE Tracks \" \"SET started=?, finished=?, is_billed=? \" \"WHERE id=?\", (started, finished,", "\" \"VALUES ('Andrey', 'Customer Numer One')\") self.cursor.execute(\"SELECT * FROM Customers ORDER BY id", "Projects \" \"WHERE \" \" Tracks.task_id == Tasks.id AND \" \" Tasks.project_id ==", "\" \"SET started=?, finished=?, is_billed=? \" \"WHERE id=?\", (started, finished, is_billed, track_id) )", "set_group_by_clause(TS_GROUP_BY['task'], 'Tracks.task_id', group_by) group_by = set_group_by_clause(TS_GROUP_BY['track'], 'Tracks.id', group_by) if group_by: group_by = \"GROUP", "tasks def get_task_by_alias(self, tname, pname): \"\"\"Get task by name\"\"\" self.cursor.execute( \"SELECT \" \"", "DELETE CASCADE, ' ' started TIMESTAMP, ' ' finished TIMESTAMP, ' ' is_billed", "customers = self.cursor.fetchone() #print('filled customers', customers) # Add a Project self.create_project('p1', 'Test Project", "self.cursor.fetchall() #print('filled tracks', tracks) print(tabulate(tracks, ['Track id', 'Task id', 'started', 'finished', 'billed'], tablefmt='simple'))", "description \" \"FROM Projects \" \"WHERE \" \" Projects.name == ?\", (pname.encode('utf8'),) )", "== Projects.id\" \"\".format(where_task_clause=where_task_clause, where_project_clause=where_project_clause), params) return self.cursor.fetchone() def get_timesheet(self, started, finished, group_by_mask, only_billed=True,", "Tasks WHERE \" \" Tasks.project_id == Projects.id \" \") {where_clause}\" \"ORDER BY Projects.id", "self.cursor.execute( \"INSERT INTO Projects ('name', 'description', created)\" \"VALUES (?, ?, ?)\", ( pname.encode('utf8'),", "\" self.cursor.execute( \"SELECT \" \" Tasks.id, Tasks.name, Projects.id, Projects.name, \" \" Tasks.description {activity_field}\"", "created as created, \" \" description as description \" \"FROM Projects \" \"WHERE", "'started', 'finished', 'billed'], tablefmt='simple')) return # CUSTOMERS def get_customer(self, customer): self.cursor.execute( \"SELECT id,", "\" Tracks.finished as finished \" \"FROM Tracks, Tasks, Projects \" \"WHERE \" \"", "TABLE IF NOT EXISTS Customers(' 'id INTEGER PRIMARY KEY, ' 'name VARCHAR UNIQUE", "\"SELECT \" \" Projects.id as pid, Projects.name, Projects.created, \" \" Projects.description, \" \"", "( pname.encode('utf8'), description.encode('utf8'), str(datetime.datetime.now()) ) ) self.conn.commit() return self.cursor.lastrowid def get_project_or_create(self, pname): self.cursor.execute(", "started=started, finished=started + timedelta(seconds=3601)) self.create_track(last_task, started=started+timedelta(seconds=13600), finished=started+timedelta(seconds=14600)) self.create_track(last_task, started=started+timedelta(seconds=15600), finished=started+timedelta(seconds=16600)) last_task = self.insert_test_task(project_id=1)", "return self.create_project(name) def delete_project_by_name(self, pname): self.cursor.execute( \"DELETE FROM Projects WHERE name == '{name}'\"", "tname='', pname=''): \"\"\"Get an active task\"\"\" params = [] where_date_clause = where_project_clause =", "\"AND DATE(started) BETWEEN ? AND ?\" params.extend([started, finished]) self.cursor.execute( \"SELECT \" \" Tasks.id", "pname): self.cursor.execute( \"SELECT \" \" id as pid, name as pname, created as", "Tasks.description as description \" \"FROM Tracks, Tasks, Projects \" \"WHERE \" \" Tracks.task_id", "self.cursor.lastrowid def fill(self): \"\"\"Fill with the test tasks\"\"\" self.cursor.execute('DELETE FROM Customers') self.cursor.execute('DELETE FROM", "DATE(started) BETWEEN ? AND ?\" \" {where_clause}\" \"\".format(where_clause=where_clause), (started, finished) ) self.conn.commit() #", "self.cursor.execute( \"DELETE FROM Projects WHERE name == '{name}'\" \"\".format(name=pname.encode('utf8'))) self.conn.commit() # TASKS def", "pid, \" \" Projects.name as pname, Tasks.description as description \" \"FROM Tasks, Projects", "- 2 # project - 3 # spent - 4 # date, tname,", "\" \" id as pid, name as pname, created as created, \" \"", "where_clause = first_limit_clause = last_limit_clause = '' if limit: first_limit_clause = \"SELECT *", "Projects.id AND \" \" Tracks.task_id == Tasks.id {where_clause}\" \"GROUP BY Projects.id \" \"UNION", "started=started+timedelta(seconds=15600), finished=started+timedelta(seconds=16600)) last_task = self.insert_test_task(project_id=1) self.create_track(last_task, started=started+timedelta(seconds=17600), finished=started+timedelta(seconds=18600)) self.create_track(last_task, started=started+timedelta(seconds=19600), finished=started+timedelta(seconds=20600)) # Add", "\" \" Tracks.finished as finished, \" \" Tracks.is_billed as is_billed \" \"FROM Tracks,", "as tname, \" \" Projects.id as pid, Projects.name as pname, \" \" Tracks.id", "? \" params.extend([started, finished]) self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as", "pname: params.append(pname.encode('utf8')) where_project_clause = \"pname == ? AND \" if only_billed: only_billed_clause =", "\" \" pid == '{project!s}'\" \"\".format(task=name.encode('utf8'), project=project_id) ) last = self.cursor.fetchone() if last:", "get_task_or_create(self, name, project_id): \"\"\"Get a task or create one\"\"\" self.cursor.execute( \"SELECT \" \"", "return self.cursor.fetchone() def get_timesheet(self, started, finished, group_by_mask, only_billed=True, tname='', pname=''): \"\"\" Gets the", "Tracks \") tracks = self.cursor.fetchall() #print('filled tracks', tracks) print(tabulate(tracks, ['Track id', 'Task id',", "FROM Tasks WHERE \" \" Tasks.project_id == Projects.id \" \") {where_clause}\" \"ORDER BY", "\" Tracks.id as track_id, Tracks.started as started, \" \" Tracks.finished as finished, \"", "(?, ?, ?)\", ( pname.encode('utf8'), description.encode('utf8'), str(datetime.datetime.now()) ) ) self.conn.commit() return self.cursor.lastrowid def", "self.create_task(name, project_id) def _get_active_tasks(self): \"\"\"Get active tasks\"\"\" self.cursor.execute( \"SELECT \" \" Tasks.id as", "Tasks, Projects, Tracks \" \"WHERE \" \" Tasks.project_id == Projects.id AND \" \"", "Tracks.finished as finished \" \"FROM Tasks, Projects, Tracks \" \"WHERE \" \" Tasks.project_id", "first_limit_clause = last_limit_clause = '' if started and finished: where_clause = str( \"WHERE", "return self.cursor.fetchall() def create_project(self, pname, description=''): \"\"\"Create a project\"\"\" self.cursor.execute( \"INSERT INTO Projects", "def get_timesheet_select_clause(self, mask): \"\"\"Get prepared select's clause list of fields\"\"\" fields = self.get_timesheet_fields(mask)", "\" \" ('task_id', 'started', 'finished', 'is_billed') \" \"VALUES (?, ?, ?, ?)\", (task_id,", "pname, Tasks.description as description \" \"FROM Tasks, Projects \" \"WHERE \" \" tname", "a project\"\"\" self.cursor.execute( \"UPDATE Projects \" \"SET name=?, description=?\" \"WHERE id=?\", (name.encode('utf8'), description.encode('utf8'),", "KEY, ' ' task_id INTEGER REFERENCES Tasks(id) ON DELETE CASCADE, ' ' started", "'Task') project_field = (2, 'pname', 'Project') started_field = (3, 'DATETIME(started) as \"started [timestamp]\"',", "was spent for a task/project\"\"\" params = [] only_billed_clause = where_project_clause = where_task_clause", "pname): \"\"\"Get task by name\"\"\" self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name", "tracks', tracks) print(tabulate(tracks, ['Track id', 'Task id', 'started', 'finished', 'billed'], tablefmt='simple')) return #", "tid ASC\" % limit self.cursor.execute( \"{first_limit_clause}\" \"SELECT \" \" Tasks.id as tid, Tasks.name", "= where_project_clause = where_task_clause = '' if tname: params.append(tname.encode('utf8')) where_task_clause = \"tname ==", "TASKS self.cursor.execute( 'CREATE TABLE IF NOT EXISTS Tasks(' ' id INTEGER PRIMARY KEY,", "tname == '{task}' AND \" \" Tasks.project_id == pid AND \" \" pid", "the test tasks\"\"\" self.cursor.execute('DELETE FROM Customers') self.cursor.execute('DELETE FROM Projects') self.cursor.execute('DELETE FROM Tasks') self.cursor.execute('DELETE", "IF NOT EXISTS Customers(' 'id INTEGER PRIMARY KEY, ' 'name VARCHAR UNIQUE COLLATE", "( name.encode('utf8'), description.encode('utf8'), tid ) ) self.conn.commit() def delete_task(self, tid): \"\"\"\"\"\" self.cursor.execute( \"DELETE", "INTEGER DEFAULT 1' ')') # CUSTOMERS self.cursor.execute( 'CREATE TABLE IF NOT EXISTS Customers('", "pid=pid) ) return self.cursor.fetchone() def get_projects_with_activity_field(self, from_date='', to_date='', limit=0): \"\"\"Get list of project", "sorted(clause, key=operator.itemgetter(0))) def get_timesheet_select_clause(self, mask): \"\"\"Get prepared select's clause list of fields\"\"\" fields", "params ) return self.cursor.fetchone() def update_task(self, tid, name, description=''): \"\"\"Updates the task info\"\"\"", "mask & TS_GROUP_BY['date']: clause.add(date_field) if mask & TS_GROUP_BY['task']: clause.update([task_field, project_field]) if mask &", "& TS_GROUP_BY['track']: clause.update([task_field, project_field, started_field, finished_field]) clause.add(spent_field) to_get = 2 if get_headers else", "== '{project:s}'\" \"\".format(task=tname.encode('utf8'), project=pname.encode('utf8')) ) return self.cursor.fetchone() def create_task(self, name, pid): self.cursor.execute( \"INSERT", "TASKS def get_tasks(self, limit=10, add_activity=False): \"\"\"Lists of last tasks\"\"\" activity_field = '' if", "' created TIMESTAMP' ')') # TASKS self.cursor.execute( 'CREATE TABLE IF NOT EXISTS Tasks('", "is_billed=? \" \"WHERE id=?\", (started, finished, is_billed, track_id) ) self.conn.commit() def delete_tracks_by_date(self, started,", "' is_billed INTEGER DEFAULT 1' ')') # CUSTOMERS self.cursor.execute( 'CREATE TABLE IF NOT", "AND \" \" finished == '' \" \" {where_date_clause}\".format( where_date_clause=where_date_clause, where_project_clause=where_project_clause, where_task_clause=where_task_clause ),", "EXISTS Tasks(' ' id INTEGER PRIMARY KEY, ' ' project_id INTEGER REFERENCES Projects(id)", "self.cursor.fetchall() return tasks def get_profiled_tasks(self, started='', finished='', limit=0): \"\"\"The list of last tasks", "customers', customers) # Add a Project self.create_project('p1', 'Test Project #1') self.cursor.execute(\"SELECT * FROM", "if pname: params.append(pname.encode('utf8')) where_project_clause = \"pname == ? AND \" if only_billed: only_billed_clause", "as active \" \"FROM Projects \" \"WHERE NOT EXISTS (\" \" SELECT id", "self.cursor.execute( \"SELECT id, name FROM Customers \" \"WHERE name == '{name:s}'\".format(name=customer) ) customer", "\" \" DATE(started) as 'started [date]'\" \"FROM Tracks, Tasks, Projects \" \"WHERE \"", "KEY, ' 'name VARCHAR UNIQUE COLLATE NOCASE, ' 'description TEXT, ' 'created TIMESTAMP'", "(name, project_id) ) self.conn.commit() return self.cursor.lastrowid def fill(self): \"\"\"Fill with the test tasks\"\"\"", "timedelta(days=1) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3600)) started = datetime.datetime.now() - timedelta(seconds=3300) self.create_track(last_task, started=started,", "'{task:s}' AND \" \" pname == '{project:s}'\" \"\".format(task=tname.encode('utf8'), project=pname.encode('utf8')) ) return self.cursor.fetchone() def", "is finished\"\"\" where_clause = first_limit_clause = last_limit_clause = '' if limit: first_limit_clause =", "is billed flag of the track record\"\"\" self.cursor.execute( \"UPDATE Tracks \" \"SET started=?,", "finished=started + timedelta(seconds=3600)) started = datetime.datetime.now() - timedelta(seconds=3300) self.create_track(last_task, started=started, finished=started + timedelta(seconds=600))", "\" \" trid == %d\" % tid ) return self.cursor.fetchone() def create_track(self, task_id,", "[] where_project_clause = where_task_clause = '' if tname: tname = tname.encode('utf8') where_task_clause =", "self.cursor.fetchall() def create_project(self, pname, description=''): \"\"\"Create a project\"\"\" self.cursor.execute( \"INSERT INTO Projects ('name',", "import datetime from datetime import timedelta import operator from tabulate import tabulate import", "as pid, Projects.name as pname, \" \" Tracks.id as trid, Tracks.started as started,", "Customers \" \"WHERE name == '{name:s}'\".format(name=customer) ) customer = self.cursor.fetchone() return customer def", "Tasks') self.cursor.execute('DELETE FROM Tracks') # Add a Customer self.cursor.execute( \"insert into Customers ('name',", "return map(operator.itemgetter(to_get), sorted(clause, key=operator.itemgetter(0))) def get_timesheet_select_clause(self, mask): \"\"\"Get prepared select's clause list of", "\" Projects.id as pid, Projects.name, Projects.created,\" \" Projects.description, '' as active \" \"FROM", "self.conn.commit() def is_project_existent(self, pname, pid): \"\"\"Checks if project already exists \"\"\" self.cursor.execute( \"SELECT", "\"\"\"The list of last tasks between dates including unfinished\"\"\" where_clause = first_limit_clause =", "- 3 # spent - 4 # date, tname, pname, started, finished, spent", "'{name:s}'\".format(name=customer) ) customer = self.cursor.fetchone() if customer: return customer self.cursor.execute( \"INSERT INTO Customers", "\"INSERT INTO Tracks \" \" ('task_id', 'started', 'finished', 'is_billed') \" \"VALUES (?, ?,", "Tracks, Tasks, Projects \" \"WHERE \" \" {where_task_clause}\" \" {where_project_clause}\" \" Tracks.task_id ==", "group_by_mask, only_billed=True, tname='', pname=''): \"\"\" Gets the time was spent for a task/project\"\"\"", "\" \"{group_by_clause} \" \"ORDER BY started, Tasks.id\" \"\".format(started=started, finished=finished, where_task_clause=where_task_clause, where_project_clause=where_project_clause, group_by_clause=group_by_clause, only_billed_clause=only_billed_clause)", "(task_id, started, finished, int(is_billed)) ) self.conn.commit() return self.cursor.lastrowid def finish_track(self, track_id, started=None): finished", "'id INTEGER PRIMARY KEY, ' 'name VARCHAR UNIQUE COLLATE NOCASE, ' 'description TEXT,", ") return self.cursor.fetchone() def update_project(self, pid, name, description): \"\"\"Updates a project\"\"\" self.cursor.execute( \"UPDATE", "FROM Tasks') self.cursor.execute('DELETE FROM Tracks') # Add a Customer self.cursor.execute( \"insert into Customers", "\" Tracks.finished as finished, \" \" Tracks.is_billed as is_billed \" \"FROM Tracks, Tasks,", "task_id INTEGER REFERENCES Tasks(id) ON DELETE CASCADE, ' ' started TIMESTAMP, ' '", "self.create_track(last_task, started=started, finished=started + timedelta(seconds=3600)) started = datetime.datetime.now() - timedelta(days=1) self.create_track(last_task, started=started, finished=started", "timedelta(days=4) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3601)) self.create_track(last_task, started=started+timedelta(seconds=13600), finished=started+timedelta(seconds=14600)) self.create_track(last_task, started=started+timedelta(seconds=15600), finished=started+timedelta(seconds=16600)) last_task", "\" Projects.name as pname, Tasks.description as description \" \"FROM Tasks, Projects \" \"WHERE", "\" Tracks.task_id == tid AND \" \" Tasks.project_id == pid\" \" {where_clause} \"", "+ timedelta(seconds=3600)) started = datetime.datetime.now() - timedelta(days=2) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3600)) started", "task by name\"\"\" self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as tname,", "tid, Tasks.name as tname, \" \" Projects.id as pid, Projects.name as pname, \"", "if not also_unfinished: where_clause = \"AND NOT finished == '' \" self.cursor.execute( \"DELETE", "\" Tracks.id IN (\" \" SELECT MAX(Tracks.id) FROM Tracks \" \" {where_clause} \"", "if do the not exist # PROJECTS self.cursor.execute( 'CREATE TABLE IF NOT EXISTS", "?, ?)\", (task_id, started, finished, int(is_billed)) ) self.conn.commit() return self.cursor.lastrowid def finish_track(self, track_id,", "'Date') task_field = (1, 'tname', 'Task') project_field = (2, 'pname', 'Project') started_field =", "AND \" \" Tracks.task_id == Tasks.id \" \"GROUP BY Tasks.id \" \"ORDER BY", "1\") customers = self.cursor.fetchone() #print('filled customers', customers) # Add a Project self.create_project('p1', 'Test", "finished_field]) clause.add(spent_field) to_get = 2 if get_headers else 1 return map(operator.itemgetter(to_get), sorted(clause, key=operator.itemgetter(0)))", "started: started = datetime.datetime.now() self.cursor.execute( \"INSERT INTO Tracks \" \" ('task_id', 'started', 'finished',", "[date]\"', 'Date') task_field = (1, 'tname', 'Task') project_field = (2, 'pname', 'Project') started_field", "trid, Tracks.started as started, \" \" Tracks.finished as finished, \" \" Tracks.is_billed as", "(name.encode('utf8'), description.encode('utf8'), pid) ) self.conn.commit() def is_project_existent(self, pname, pid): \"\"\"Checks if project already", "return self.cursor.fetchone() def create_task(self, name, pid): self.cursor.execute( \"INSERT INTO Tasks ('name', 'project_id') \"", "x.decode('utf8') #try: #except sqlite3.OperationalError: self.cursor = self.conn.cursor() def close_db(self): self.conn.close() def create_db(self): self.cursor.execute(\"PRAGMA", "= self.cursor.fetchone() if project: return project return self.create_project(name) def delete_project_by_name(self, pname): self.cursor.execute( \"DELETE", "\" Tasks.id, Tasks.name, Projects.id, Projects.name, \" \" Tasks.description {activity_field}\" \"FROM Tasks, Projects, Tracks", "\" \"WHERE \" \" Tasks.project_id == pid AND \" \" tname == '{task:s}'", "Tasks.name, Projects.id, Projects.name, \" \" Tasks.description {activity_field}\" \"FROM Tasks, Projects, Tracks \" \"WHERE", "tid {last_limit_clause}\" \"\".format( where_clause=where_clause, first_limit_clause=first_limit_clause, last_limit_clause=last_limit_clause) ) tasks = self.cursor.fetchall() return tasks def", "EXISTS Projects(' ' id INTEGER PRIMARY KEY, ' ' customer_id INTEGER, ' '", "if add_activity: activity_field = \", SUM(CASE WHEN Tracks.finished == '' THEN 1 ELSE", "finished]) self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as tname, Projects.name as", ") tasks = self.cursor.fetchall() return tasks def get_task_by_alias(self, tname, pname): \"\"\"Get task by", "finished, \" \" Tracks.is_billed as is_billed \" \"FROM Tracks, Tasks, Projects \" \"WHERE", "Tracks.finished == '' THEN 1 ELSE 0 end) AS active \" \"FROM Projects,", "fields\"\"\" fields = self.get_timesheet_fields(mask) return ', '.join(fields) def get_minimal_started_track(self, tname='', pname=''): \"\"\"Get a", "started and finished: where_date_clause = \"AND DATE(Tracks.started) \" \\ \" BETWEEN ? \"", "\"FROM Projects \" \"WHERE \" \" Projects.name == ?\", (pname.encode('utf8'),) ) return self.cursor.fetchone()", "0 END) \" self.cursor.execute( \"SELECT \" \" Tasks.id, Tasks.name, Projects.id, Projects.name, \" \"", "tasks def get_profiled_tasks(self, started='', finished='', limit=0): \"\"\"The list of last tasks between dates", ") self.conn.commit() return finished def update_track(self, track_id, started, finished, is_billed): \"\"\"Updates the time", "def close_db(self): self.conn.close() def create_db(self): self.cursor.execute(\"PRAGMA foreign_keys = ON\") # Create Tables if", "as pname, created as created, \" \" description as description \" \"FROM Projects", "('{name:s}')\" .format(name=customer) ) self.conn.commit() # PROJECTS def get_project_by_name(self, pname): self.cursor.execute( \"SELECT \" \"", "#2 self.create_project('p2', 'Test Project #1') self.cursor.execute(\"SELECT * FROM Projects ORDER BY id LIMIT", "Projects ORDER BY id LIMIT 1\") project = self.cursor.fetchone() #print('filled projects', project) #", "'{name:s}'\".format(name=customer) ) customer = self.cursor.fetchone() return customer def get_customer_or_create(self, customer): self.cursor.execute( \"SELECT id,", "by name\"\"\" self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as tname, Projects.id", "\" \" Tasks.project_id == Projects.id AND \" \" finished == ''\") return self.cursor.fetchall()", "not also_unfinished: where_clause = \"AND NOT finished == '' \" if started and", "self.cursor.fetchone() def get_projects_with_activity_field(self, from_date='', to_date='', limit=0): \"\"\"Get list of project including a field", "'description') \" \"VALUES ('Andrey', 'Customer Numer One')\") self.cursor.execute(\"SELECT * FROM Customers ORDER BY", "tid, Tasks.name as tname, Projects.name as pname, \" \" Tracks.id as trid, Tracks.started", "\" \" {where_task_clause}\" \" {where_project_clause}\" \" Tracks.task_id == tid AND \" \" Tasks.project_id", "Tracks.started as started, Tracks.finished as finished \" \"FROM Tasks, Projects, Tracks \" \"WHERE", "# Add a Project #2 self.create_project('p2', 'Test Project #1') self.cursor.execute(\"SELECT * FROM Projects", "self.cursor.fetchone() def create_task(self, name, pid): self.cursor.execute( \"INSERT INTO Tasks ('name', 'project_id') \" \"VALUES", "\" \" Tracks.is_billed as is_billed \" \"FROM Tracks, Tasks, Projects \" \"WHERE \"", "a list of ordered fields\"\"\" # Priority: # datetime - 0 # date", "also_unfinished: where_clause = \"AND NOT finished == '' \" if started and finished:", "datetime.datetime.now() - timedelta(days=4) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3601)) self.create_track(last_task, started=started+timedelta(seconds=13600), finished=started+timedelta(seconds=14600)) self.create_track(last_task, started=started+timedelta(seconds=15600),", "\" \" Tasks.id as tid, Tasks.name as tname, Projects.id as pid, \" \"", "\" \" Tracks.finished as finished, \" \" Tasks.description as description \" \"FROM Tracks,", ") class Database: def init_db(self, db_path): self.conn = sqlite3.connect( db_path, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES ) self.conn.row_factory", "== '' \" \" {where_date_clause}\".format( where_date_clause=where_date_clause, where_project_clause=where_project_clause, where_task_clause=where_task_clause ), params ) return self.cursor.fetchone()", "customer_id INTEGER, ' ' name VARCHAR UNIQUE COLLATE NOCASE, ' ' description TEXT", "KEY, ' ' project_id INTEGER REFERENCES Projects(id) ON DELETE CASCADE, ' ' name", "id, name FROM Customers \" \"WHERE name == '{name:s}'\".format(name=customer) ) customer = self.cursor.fetchone()", "== '{tid}'\".format(tid=tid)) self.conn.commit() # TRACKS def get_tracks_by_date(self, started='', finished='', also_unfinished=False): \"\"\"Get tracks\"\"\" where_clause", "the time was spent for a task/project\"\"\" params = [] only_billed_clause = where_project_clause", "\" Tracks.started as started, Tracks.finished as finished \" \"FROM Tasks, Projects, Tracks \"", "\" \" Tracks.task_id == tid AND \" \" Tasks.project_id == pid\" \" {where_clause}", "def create_track(self, task_id, started='', finished='', is_billed=True): # started, finished - 9-item sequence, not", "'project_id') \" \"VALUES \" \" (?, ?)\", ( name.encode('utf8'), pid ) ) self.conn.commit()", "FROM (\" last_limit_clause = \" DESC LIMIT %d) ORDER BY tid ASC\" %", "where_clause=where_clause, first_limit_clause=first_limit_clause, last_limit_clause=last_limit_clause) ) tasks = self.cursor.fetchall() return tasks def get_task_by_alias(self, tname, pname):", "- timedelta(seconds=3300) self.create_track(last_task, started=started, finished=started + timedelta(seconds=600)) last_track = self.create_track(last_task) self.cursor.execute(\"SELECT * FROM", "\"GROUP BY Projects.id \" \"UNION SELECT \" \" Projects.id as pid, Projects.name, Projects.created,\"", "is_billed=True): # started, finished - 9-item sequence, not float if not started: started", "ORDER BY tid {last_limit_clause}\" \"\".format( where_clause=where_clause, first_limit_clause=first_limit_clause, last_limit_clause=last_limit_clause) ) tasks = self.cursor.fetchall() return", "FROM Customers \" \"WHERE name == '{name:s}'\".format(name=customer) ) customer = self.cursor.fetchone() if customer:", "= pname.encode('utf8') where_project_clause = \"pname == ? AND \" params.append(pname) self.cursor.execute( \"SELECT \"", "AND ?\" \" {where_clause}\" \"\".format(where_clause=where_clause), (started, finished) ) self.conn.commit() # TIMESHEET def get_group_by_clause(self,", "'DATETIME(started) as \"started [timestamp]\"', 'From') finished_field = (4, 'DATETIME(finished) as \"finished [timestamp]\"', 'To')", "create_db(self): self.cursor.execute(\"PRAGMA foreign_keys = ON\") # Create Tables if do the not exist", "self.cursor.lastrowid def finish_track(self, track_id, started=None): finished = datetime.datetime.now() if started and config.BT_TIMESHEET_ROUNDING and", "self.cursor.fetchone() if last: return last['tid'] return self.create_task(name, project_id) def _get_active_tasks(self): \"\"\"Get active tasks\"\"\"", "def update_task(self, tid, name, description=''): \"\"\"Updates the task info\"\"\" self.cursor.execute( \"UPDATE Tasks \"", "\" \" {where_task_clause}\" \" {where_project_clause}\" \" Tracks.task_id == Tasks.id AND \" \" Tasks.project_id", "\" \" Tracks.id as track_id, Tracks.started as started, \" \" Tracks.finished as finished,", "\"\"' ')') # TRACKS self.cursor.execute( 'CREATE TABLE IF NOT EXISTS Tracks(' ' id", "\" \"WHERE NOT EXISTS (\" \" SELECT id FROM Tasks WHERE \" \"", "as pname, \" \" DATE(started) as 'started [date]'\" \"FROM Tracks, Tasks, Projects \"", "% tid ) return self.cursor.fetchone() def create_track(self, task_id, started='', finished='', is_billed=True): # started,", "self.create_db() def insert_test_task(self, project_id): name = ''.join(random.choice( string.ascii_uppercase + string.digits) for _ in", "Tracks(' ' id INTEGER PRIMARY KEY, ' ' task_id INTEGER REFERENCES Tasks(id) ON", "and finished: where_date_clause = \"AND DATE(Tracks.started) \" \\ \" BETWEEN ? \" \\", "TS_GROUP_BY['track']: clause.update([task_field, project_field, started_field, finished_field]) clause.add(spent_field) to_get = 2 if get_headers else 1", "1\") project = self.cursor.fetchone() #print('filled projects', project) # Add the Task last_task =", "tracks\"\"\" where_clause = '' between_clause = '' params = [] if not also_unfinished:", "dict( timestamp=0b10000, project=0b1000, task=0b0100, track=0b0010, date=0b0001 ) class Database: def init_db(self, db_path): self.conn", "4 # date, tname, pname, started, finished, spent date_field = (0, 'DATE(started) as", "started and finished: between_clause = \"AND DATE(started) BETWEEN ? AND ?\" params.extend([started, finished])", "' 'description TEXT, ' 'created TIMESTAMP' ')') self.conn.commit() def __init__(self, db_name): # create", "AND \" \" Tracks.task_id == Tasks.id AND \" \" Tracks.id IN (\" \"", "def is_project_existent(self, pname, pid): \"\"\"Checks if project already exists \"\"\" self.cursor.execute( \"SELECT \"", "if started and config.BT_TIMESHEET_ROUNDING and config.BT_ROUNDING_INCREMENT: delta = finished - started round_to =", "\"started [timestamp]\"', 'From') finished_field = (4, 'DATETIME(finished) as \"finished [timestamp]\"', 'To') spent_field =", "else 1 return map(operator.itemgetter(to_get), sorted(clause, key=operator.itemgetter(0))) def get_timesheet_select_clause(self, mask): \"\"\"Get prepared select's clause", "'' \" if started and finished: between_clause = \"AND DATE(started) BETWEEN ? AND", "params.append(pname.encode('utf8')) where_project_clause = \"pname == ? AND \" if only_billed: only_billed_clause = \"", "id=?\", (started, finished, is_billed, track_id) ) self.conn.commit() def delete_tracks_by_date(self, started, finished, also_unfinished=False): \"\"\"Deletes", "as description \" \"FROM Tasks, Projects \" \"WHERE \" \" Tasks.project_id == pid", "'description', created)\" \"VALUES (?, ?, ?)\", ( pname.encode('utf8'), description.encode('utf8'), str(datetime.datetime.now()) ) ) self.conn.commit()", "\" {where_project_clause}\" \" Tracks.task_id == tid AND \" \" Tasks.project_id == Projects.id AND", ") self.conn.commit() return self.cursor.lastrowid def fill(self): \"\"\"Fill with the test tasks\"\"\" self.cursor.execute('DELETE FROM", "AND \" \" Tasks.project_id == pid\" \" {where_clause} \" \" {between_clause} \" \"ORDER", "DATE(started) as 'started [date]'\" \"FROM Tracks, Tasks, Projects \" \"WHERE \" \" {where_task_clause}\"", "\" \" Projects.id as pid, Projects.name, Projects.created,\" \" Projects.description, '' as active \"", "ordered fields\"\"\" # Priority: # datetime - 0 # date - 1 #", "get_timesheet_select_clause(self, mask): \"\"\"Get prepared select's clause list of fields\"\"\" fields = self.get_timesheet_fields(mask) return", "{where_task_clause}\" \" {where_project_clause}\" \" Tracks.task_id == Tasks.id AND \" \" Tasks.project_id == Projects.id", "if group_by: group_by = \"GROUP BY %s \" % group_by return group_by def", "BY %s \" % group_by return group_by def get_timesheet_fields(self, mask, get_headers=False): \"\"\"Makes a", "active tasks\"\"\" self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as tname, Projects.name", "?, ?, ?)\", (task_id, started, finished, int(is_billed)) ) self.conn.commit() return self.cursor.lastrowid def finish_track(self,", "= (5, 'spent', 'Time Spent') clause = set() if mask & TS_GROUP_BY['date']: clause.add(date_field)", "timestamp=0b10000, project=0b1000, task=0b0100, track=0b0010, date=0b0001 ) class Database: def init_db(self, db_path): self.conn =", "as spent,\" \" Tracks.started as started, \" \" Tracks.finished as finished \" \"FROM", "COLLATE NOCASE, ' ' description TEXT DEFAULT \"\", ' ' created TIMESTAMP' ')')", "pid, name as pname, created as created, \" \" description as description \"", "started_field, finished_field]) clause.add(spent_field) to_get = 2 if get_headers else 1 return map(operator.itemgetter(to_get), sorted(clause,", "tracks = self.cursor.fetchall() #print('filled tracks', tracks) print(tabulate(tracks, ['Track id', 'Task id', 'started', 'finished',", "Tasks.id AND \" \" Tracks.id IN (\" \" SELECT MAX(Tracks.id) FROM Tracks \"", "clause\"\"\" if mask & bits: if group_by: group_by = \"%s,\" % group_by group_by", "self.conn.commit() return self.cursor.lastrowid def get_project_or_create(self, pname): self.cursor.execute( \"SELECT id, name FROM Projects \"", "project_id) def _get_active_tasks(self): \"\"\"Get active tasks\"\"\" self.cursor.execute( \"SELECT \" \" Tasks.id as tid,", "last_track = self.create_track(last_task) self.cursor.execute(\"SELECT * FROM Tracks \") tracks = self.cursor.fetchall() #print('filled tracks',", "('task_id', 'started', 'finished', 'is_billed') \" \"VALUES (?, ?, ?, ?)\", (task_id, started, finished,", "CUSTOMERS self.cursor.execute( 'CREATE TABLE IF NOT EXISTS Customers(' 'id INTEGER PRIMARY KEY, '", "return tasks def get_task_by_alias(self, tname, pname): \"\"\"Get task by name\"\"\" self.cursor.execute( \"SELECT \"", "as pid, Projects.name, Projects.created, \" \" Projects.description, \" \" SUM(CASE WHEN Tracks.finished ==", "task_field = (1, 'tname', 'Task') project_field = (2, 'pname', 'Project') started_field = (3,", "''\" \" {only_billed_clause}\" \" ) \" \"{group_by_clause} \" \"ORDER BY started, Tasks.id\" \"\".format(started=started,", "\"\"\"Fill with the test tasks\"\"\" self.cursor.execute('DELETE FROM Customers') self.cursor.execute('DELETE FROM Projects') self.cursor.execute('DELETE FROM", "self.conn.row_factory = sqlite3.Row self.conn.text_factory = lambda x: x.decode('utf8') #try: #except sqlite3.OperationalError: self.cursor =", "BY id LIMIT 1\") customers = self.cursor.fetchone() #print('filled customers', customers) # Add a", "projects', project) # Add the Task last_task = self.insert_test_task(project_id=1) # Add the Tracks", "\" DATE(started) BETWEEN ? AND ?\" \" AND NOT Tracks.finished == ''\" \"", "group_by def get_timesheet_fields(self, mask, get_headers=False): \"\"\"Makes a list of ordered fields\"\"\" # Priority:", "mask & TS_GROUP_BY['track']: clause.update([task_field, project_field, started_field, finished_field]) clause.add(spent_field) to_get = 2 if get_headers", "a project is finished\"\"\" where_clause = first_limit_clause = last_limit_clause = '' if limit:", "group_by group_by = set_group_by_clause(TS_GROUP_BY['date'], 'DATE(started)', '') group_by = set_group_by_clause(TS_GROUP_BY['project'], 'Tasks.project_id', group_by) group_by =", "# project - 3 # spent - 4 # date, tname, pname, started,", "END) \" self.cursor.execute( \"SELECT \" \" Tasks.id, Tasks.name, Projects.id, Projects.name, \" \" Tasks.description", "tasks = self.cursor.fetchall() return tasks def get_profiled_tasks(self, started='', finished='', limit=0): \"\"\"The list of", "\" params.append(pname) if started and finished: where_date_clause = \"AND DATE(Tracks.started) \" \\ \"", "last_task = self.insert_test_task(project_id=1) # Add the Tracks started = datetime.datetime.now() - timedelta(days=4) self.create_track(last_task,", "started and config.BT_TIMESHEET_ROUNDING and config.BT_ROUNDING_INCREMENT: delta = finished - started round_to = config.BT_ROUNDING_INCREMENT", "to_get = 2 if get_headers else 1 return map(operator.itemgetter(to_get), sorted(clause, key=operator.itemgetter(0))) def get_timesheet_select_clause(self,", "LIMIT %d) ORDER BY tid ASC\" % limit self.cursor.execute( \"{first_limit_clause}\" \"SELECT \" \"", "self.conn.commit() return self.cursor.lastrowid def finish_track(self, track_id, started=None): finished = datetime.datetime.now() if started and", "= \"AND DATE(started) BETWEEN ? AND ?\" params.extend([started, finished]) self.cursor.execute( \"SELECT \" \"", "group_by group_by = '{group_by} {value}'.format(group_by=group_by, value=value) return group_by group_by = set_group_by_clause(TS_GROUP_BY['date'], 'DATE(started)', '')", "', '.join(fields) def get_minimal_started_track(self, tname='', pname=''): \"\"\"Get a minimal tracked date\"\"\" params =", "IN (\" \" SELECT MAX(Tracks.id) FROM Tracks \" \" {where_clause} \" \" GROUP", "tname: params.append(tname.encode('utf8')) where_task_clause = \"tname == ? AND \" if pname: params.append(pname.encode('utf8')) where_project_clause", "AND ?\" params.extend([started, finished]) self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as", "self.cursor.execute( \"insert into Tasks ('name', 'project_id') \" \"values('%s', '%s')\" % (name, project_id) )", "pid, Projects.name, Projects.created,\" \" Projects.description, '' as active \" \"FROM Projects \" \"WHERE", "'{started}' AND '{finished}'\" \"\".format(started=started, finished=finished)) if limit: first_limit_clause = \"SELECT * FROM (\"", "started='', finished='', limit=0): \"\"\"The list of last tasks between dates including unfinished\"\"\" where_clause", "name = ''.join(random.choice( string.ascii_uppercase + string.digits) for _ in range(3)) self.cursor.execute( \"insert into", "= datetime.datetime.now() - timedelta(days=1) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3600)) started = datetime.datetime.now() -", "'CREATE TABLE IF NOT EXISTS Tracks(' ' id INTEGER PRIMARY KEY, ' '", "BETWEEN '{from_date}' \" \\ \"AND '{to_date}' \".format(from_date=from_date, to_date=to_date) self.cursor.execute( \"{first_limit_clause}\" \"SELECT \" \"", "# date, tname, pname, started, finished, spent date_field = (0, 'DATE(started) as \"date", "' id INTEGER PRIMARY KEY, ' ' task_id INTEGER REFERENCES Tasks(id) ON DELETE", "Tracks.id IN (\" \" SELECT MAX(Tracks.id) FROM Tracks \" \" {where_clause} \" \"", "Tasks.name as tname, \" \" Projects.id as pid, Projects.name as pname, \" \"", "pname=''): \"\"\"Get a minimal tracked date\"\"\" params = [] where_project_clause = where_task_clause =", "CASCADE, ' ' started TIMESTAMP, ' ' finished TIMESTAMP, ' ' is_billed INTEGER", "as \"started [timestamp]\"', 'From') finished_field = (4, 'DATETIME(finished) as \"finished [timestamp]\"', 'To') spent_field", "Add the Task last_task = self.insert_test_task(project_id=1) # Add the Tracks started = datetime.datetime.now()", "AND \" if pname: params.append(pname.encode('utf8')) where_project_clause = \"pname == ? AND \" if", "'{tid}'\".format(tid=tid)) self.conn.commit() # TRACKS def get_tracks_by_date(self, started='', finished='', also_unfinished=False): \"\"\"Get tracks\"\"\" where_clause =", "pname == '{project:s}'\" \"\".format(task=tname.encode('utf8'), project=pname.encode('utf8')) ) return self.cursor.fetchone() def create_task(self, name, pid): self.cursor.execute(", "as is_billed \" \"FROM Tracks, Tasks, Projects \" \"WHERE \" \" Tracks.task_id ==", "started=started+timedelta(seconds=17600), finished=started+timedelta(seconds=18600)) self.create_track(last_task, started=started+timedelta(seconds=19600), finished=started+timedelta(seconds=20600)) # Add a Project #2 self.create_project('p2', 'Test Project", "self.cursor.fetchone() if customer: return customer self.cursor.execute( \"INSERT INTO Customers ('name')\" \"VALUES ('{name:s}')\" .format(name=customer)", "\"DELETE \" \" FROM Tracks \" \"WHERE \" \" DATE(started) BETWEEN ? AND", "% group_by group_by = '{group_by} {value}'.format(group_by=group_by, value=value) return group_by group_by = set_group_by_clause(TS_GROUP_BY['date'], 'DATE(started)',", "= set_group_by_clause(TS_GROUP_BY['date'], 'DATE(started)', '') group_by = set_group_by_clause(TS_GROUP_BY['project'], 'Tasks.project_id', group_by) group_by = set_group_by_clause(TS_GROUP_BY['task'], 'Tracks.task_id',", "\" if pname: params.append(pname.encode('utf8')) where_project_clause = \"pname == ? AND \" if only_billed:", "started='', finished='', is_billed=True): # started, finished - 9-item sequence, not float if not", "if started and finished: where_date_clause = \"AND DATE(Tracks.started) \" \\ \" BETWEEN ?", "ON\") # Create Tables if do the not exist # PROJECTS self.cursor.execute( 'CREATE", "update_project(self, pid, name, description): \"\"\"Updates a project\"\"\" self.cursor.execute( \"UPDATE Projects \" \"SET name=?,", "id=?\", (name.encode('utf8'), description.encode('utf8'), pid) ) self.conn.commit() def is_project_existent(self, pname, pid): \"\"\"Checks if project", "\" \" {where_clause} \" \" GROUP BY Tracks.task_id \" \" ) ORDER BY", "project_field, started_field, finished_field]) clause.add(spent_field) to_get = 2 if get_headers else 1 return map(operator.itemgetter(to_get),", "\" \"WHERE name == '{name:s}'\".format(name=pname.encode('utf8')) ) project = self.cursor.fetchone() if project: return project", "BETWEEN ? AND ?\" params.extend([started, finished]) self.cursor.execute( \"SELECT \" \" Tasks.id as tid,", "\" \" tname == '{task}' AND \" \" Tasks.project_id == pid AND \"", "Tasks.id as tid, Tasks.name as tname, \" \" Projects.id as pid, Projects.name as", "started = datetime.datetime.now() - timedelta(days=2) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3600)) started = datetime.datetime.now()", "limit=0): \"\"\"Get list of project including a field is a project is finished\"\"\"", "prepared select's clause list of fields\"\"\" fields = self.get_timesheet_fields(mask) return ', '.join(fields) def", "Tracks.started as started, \" \" Tracks.finished as finished, \" \" Tasks.description as description", "where_project_clause = where_task_clause = '' if tname: params.append(tname.encode('utf8')) where_task_clause = \"tname == ?", "\" \"ORDER BY started, Tasks.id\" \"\".format(started=started, finished=finished, where_task_clause=where_task_clause, where_project_clause=where_project_clause, group_by_clause=group_by_clause, only_billed_clause=only_billed_clause) ) #print(query)", "self.create_track(last_task, started=started, finished=started + timedelta(seconds=3600)) started = datetime.datetime.now() - timedelta(seconds=3300) self.create_track(last_task, started=started, finished=started", "get_group_by_clause(self, mask): \"\"\"Makes a GROUP BY clause by bit mask\"\"\" def set_group_by_clause(bits, value,", "1 ELSE 0 END) \" self.cursor.execute( \"SELECT \" \" Tasks.id, Tasks.name, Projects.id, Projects.name,", "self.create_track(last_task, started=started, finished=started + timedelta(seconds=3601)) self.create_track(last_task, started=started+timedelta(seconds=13600), finished=started+timedelta(seconds=14600)) self.create_track(last_task, started=started+timedelta(seconds=15600), finished=started+timedelta(seconds=16600)) last_task =", "return customer def get_customer_or_create(self, customer): self.cursor.execute( \"SELECT id, name FROM Customers \" \"WHERE", "\" \" Projects.id as pid, Projects.name, Projects.created, \" \" Projects.description, \" \" SUM(CASE", "tid AND \" \" Tasks.project_id == Projects.id AND \" \" (\" \" DATE(started)", "task\"\"\" params = [] where_date_clause = where_project_clause = where_task_clause = '' if tname:", "pid AND \" \" pid == '{project!s}'\" \"\".format(task=name.encode('utf8'), project=project_id) ) last = self.cursor.fetchone()", "Tracks.task_id == tid AND \" \" Tasks.project_id == pid\" \" {where_clause} \" \"", "description \" \"FROM Tracks, Tasks, Projects \" \"WHERE \" \" Tracks.task_id == Tasks.id", "project) # Add the Task last_task = self.insert_test_task(project_id=1) # Add the Tracks started", "= (3, 'DATETIME(started) as \"started [timestamp]\"', 'From') finished_field = (4, 'DATETIME(finished) as \"finished", "\" \" Projects.name as pname, Tasks.description as description, \" \" Tracks.started as started,", "datetime.datetime.now() - timedelta(days=2) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3600)) started = datetime.datetime.now() - timedelta(days=1)", "% limit self.cursor.execute( \"{first_limit_clause}\" \"SELECT \" \" Tasks.id as tid, Tasks.name as tname,", "where_clause = \" AND DATE(Projects.created) BETWEEN '{from_date}' \" \\ \"AND '{to_date}' \".format(from_date=from_date, to_date=to_date)", "self.cursor.fetchall() def get_active_task(self, started='', finished='', tname='', pname=''): \"\"\"Get an active task\"\"\" params =", "by the date\"\"\" if not also_unfinished: where_clause = \"AND NOT finished == ''", "' ' is_billed INTEGER DEFAULT 1' ')') # CUSTOMERS self.cursor.execute( 'CREATE TABLE IF", "date\"\"\" params = [] where_project_clause = where_task_clause = '' if tname: tname =", "mask & TS_GROUP_BY['task']: clause.update([task_field, project_field]) if mask & TS_GROUP_BY['project']: clause.add(project_field) if mask &", "(\" \" SELECT MAX(Tracks.id) FROM Tracks \" \" {where_clause} \" \" GROUP BY", "group_by = \"GROUP BY %s \" % group_by return group_by def get_timesheet_fields(self, mask,", "timedelta(seconds=3600)) started = datetime.datetime.now() - timedelta(days=1) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3600)) started =", "field to group_by clause\"\"\" if mask & bits: if group_by: group_by = \"%s,\"", "INTEGER, ' ' name VARCHAR UNIQUE COLLATE NOCASE, ' ' description TEXT DEFAULT", "finished: between_clause = \"AND DATE(started) BETWEEN ? AND ?\" params.extend([started, finished]) self.cursor.execute( \"SELECT", "def get_customer(self, customer): self.cursor.execute( \"SELECT id, name FROM Customers \" \"WHERE name ==", "self.cursor.execute('DELETE FROM Projects') self.cursor.execute('DELETE FROM Tasks') self.cursor.execute('DELETE FROM Tracks') # Add a Customer", "== pid\" \" {where_clause} \" \" {between_clause} \" \"ORDER BY Tracks.id\".format(started=started, finished=finished, where_clause=where_clause,", "\" (?, ?)\", ( name.encode('utf8'), pid ) ) self.conn.commit() return self.cursor.lastrowid def get_task_or_create(self,", "AND Tracks.is_billed == 1 \" params.extend([started, finished]) group_by_clause = self.get_group_by_clause(group_by_mask) query = str(", "Tasks WHERE id == '{tid}'\".format(tid=tid)) self.conn.commit() # TRACKS def get_tracks_by_date(self, started='', finished='', also_unfinished=False):", "\"VALUES (?, ?, ?, ?)\", (task_id, started, finished, int(is_billed)) ) self.conn.commit() return self.cursor.lastrowid", "return # CUSTOMERS def get_customer(self, customer): self.cursor.execute( \"SELECT id, name FROM Customers \"", "?)\", (task_id, started, finished, int(is_billed)) ) self.conn.commit() return self.cursor.lastrowid def finish_track(self, track_id, started=None):", "'{name}'\" \"\".format(name=pname.encode('utf8'))) self.conn.commit() # TASKS def get_tasks(self, limit=10, add_activity=False): \"\"\"Lists of last tasks\"\"\"", "GROUP BY clause by bit mask\"\"\" def set_group_by_clause(bits, value, group_by): \"\"\"Add a field", "\"FROM Tracks, Tasks, Projects \" \"WHERE \" \" Tracks.task_id == tid AND \"", "import timedelta import operator from tabulate import tabulate import config TS_GROUP_BY = dict(", "\") {where_clause}\" \"ORDER BY Projects.id {last_limit_clause}\".format( where_clause=where_clause, first_limit_clause=first_limit_clause, last_limit_clause=last_limit_clause) ) return self.cursor.fetchall() def", "started TIMESTAMP, ' ' finished TIMESTAMP, ' ' is_billed INTEGER DEFAULT 1' ')')", ") last = self.cursor.fetchone() if last: return last['tid'] return self.create_task(name, project_id) def _get_active_tasks(self):", "as pname, \" \" Tracks.id as trid, Tracks.started as started, \" \" Tracks.finished", "group_by = set_group_by_clause(TS_GROUP_BY['project'], 'Tasks.project_id', group_by) group_by = set_group_by_clause(TS_GROUP_BY['task'], 'Tracks.task_id', group_by) group_by = set_group_by_clause(TS_GROUP_BY['track'],", "params.extend([started, finished]) self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as tname, Projects.name", "\" Tasks.project_id == Projects.id AND \" \" Tracks.task_id == Tasks.id AND \" \"", "pname=''): \"\"\"Get an active task\"\"\" params = [] where_date_clause = where_project_clause = where_task_clause", "INTEGER REFERENCES Tasks(id) ON DELETE CASCADE, ' ' started TIMESTAMP, ' ' finished", "Customers ('name', 'description') \" \"VALUES ('Andrey', 'Customer Numer One')\") self.cursor.execute(\"SELECT * FROM Customers", "clause list of fields\"\"\" fields = self.get_timesheet_fields(mask) return ', '.join(fields) def get_minimal_started_track(self, tname='',", "\"\"\"Makes a list of ordered fields\"\"\" # Priority: # datetime - 0 #", "a field to group_by clause\"\"\" if mask & bits: if group_by: group_by =", "\" \"WHERE \" \" {where_task_clause}\" \" {where_project_clause}\" \" Tracks.task_id == tid AND \"", "self.create_track(last_task, started=started+timedelta(seconds=13600), finished=started+timedelta(seconds=14600)) self.create_track(last_task, started=started+timedelta(seconds=15600), finished=started+timedelta(seconds=16600)) last_task = self.insert_test_task(project_id=1) self.create_track(last_task, started=started+timedelta(seconds=17600), finished=started+timedelta(seconds=18600)) self.create_track(last_task,", "Tracks.id as track_id, Tracks.started as started, \" \" Tracks.finished as finished, \" \"", "0 end) AS active \" \"FROM Projects, Tracks, Tasks \" \"WHERE \" \"", "\"UPDATE Tasks \" \"SET name=?, description=?\" \"WHERE id=?\", ( name.encode('utf8'), description.encode('utf8'), tid )", "map(operator.itemgetter(to_get), sorted(clause, key=operator.itemgetter(0))) def get_timesheet_select_clause(self, mask): \"\"\"Get prepared select's clause list of fields\"\"\"", "finished) ) self.conn.commit() # TIMESHEET def get_group_by_clause(self, mask): \"\"\"Makes a GROUP BY clause", "as description \" \"FROM Tracks, Tasks, Projects \" \"WHERE \" \" Tracks.task_id ==", "self.conn.commit() def __init__(self, db_name): # create DB self.init_db(db_name) self.create_db() def insert_test_task(self, project_id): name", "id == '{tid}'\".format(tid=tid)) self.conn.commit() # TRACKS def get_tracks_by_date(self, started='', finished='', also_unfinished=False): \"\"\"Get tracks\"\"\"", "def get_minimal_started_track(self, tname='', pname=''): \"\"\"Get a minimal tracked date\"\"\" params = [] where_project_clause", "is_billed \" \"FROM Tracks, Tasks, Projects \" \"WHERE \" \" Tracks.task_id == tid", "tname, Projects.name as pname, \" \" SUM(STRFTIME('%s', finished)-STRFTIME('%s', started)) as spent,\" \" Tracks.started", "first_limit_clause=first_limit_clause, last_limit_clause=last_limit_clause) ) tasks = self.cursor.fetchall() return tasks def get_task_by_alias(self, tname, pname): \"\"\"Get", "\" {where_date_clause}\".format( where_date_clause=where_date_clause, where_project_clause=where_project_clause, where_task_clause=where_task_clause ), params ) return self.cursor.fetchone() def update_task(self, tid,", "\" % group_by return group_by def get_timesheet_fields(self, mask, get_headers=False): \"\"\"Makes a list of", "LIMIT 1\") customers = self.cursor.fetchone() #print('filled customers', customers) # Add a Project self.create_project('p1',", "\"UNION SELECT \" \" Projects.id as pid, Projects.name, Projects.created,\" \" Projects.description, '' as", "# Create Tables if do the not exist # PROJECTS self.cursor.execute( 'CREATE TABLE", "finished, is_billed): \"\"\"Updates the time was spend and is billed flag of the", "\" \" Tasks.project_id == Projects.id AND \" \" finished == '' \" \"", "finished=? WHERE id=?\", (finished, track_id) ) self.conn.commit() return finished def update_track(self, track_id, started,", "task=0b0100, track=0b0010, date=0b0001 ) class Database: def init_db(self, db_path): self.conn = sqlite3.connect( db_path,", "self.conn.commit() return self.cursor.lastrowid def get_task_or_create(self, name, project_id): \"\"\"Get a task or create one\"\"\"", "# Priority: # datetime - 0 # date - 1 # task -", "\\ \" BETWEEN ? \" \\ \" AND ? \" params.extend([started, finished]) self.cursor.execute(", "where_task_clause = '' if tname: tname = tname.encode('utf8') where_task_clause = \"tname == ?", "name=?, description=?\" \"WHERE id=?\", ( name.encode('utf8'), description.encode('utf8'), tid ) ) self.conn.commit() def delete_task(self,", "name == '{name}'\" \"\".format(name=pname.encode('utf8'))) self.conn.commit() # TASKS def get_tasks(self, limit=10, add_activity=False): \"\"\"Lists of", "SUM(CASE WHEN Tracks.finished == '' THEN 1 ELSE 0 end) AS active \"", "LIMIT 1\") project = self.cursor.fetchone() #print('filled projects', project) # Add the Task tasks", "get_customer(self, customer): self.cursor.execute( \"SELECT id, name FROM Customers \" \"WHERE name == '{name:s}'\".format(name=customer)", "Tasks \" \"SET name=?, description=?\" \"WHERE id=?\", ( name.encode('utf8'), description.encode('utf8'), tid ) )", "\" Projects.description, \" \" SUM(CASE WHEN Tracks.finished == '' THEN 1 ELSE 0", "\" \" DATE(started) BETWEEN ? AND ?\" \" {where_clause}\" \"\".format(where_clause=where_clause), (started, finished) )", "started, finished, also_unfinished=False): \"\"\"Deletes tracks by the date\"\"\" if not also_unfinished: where_clause =", "\"FROM Projects, Tracks, Tasks \" \"WHERE \" \" Tasks.project_id == Projects.id AND \"", "BETWEEN ? AND ?\" \" AND NOT Tracks.finished == ''\" \" {only_billed_clause}\" \"", "('name', 'description') \" \"VALUES ('Andrey', 'Customer Numer One')\") self.cursor.execute(\"SELECT * FROM Customers ORDER", "pname.encode('utf8'), description.encode('utf8'), str(datetime.datetime.now()) ) ) self.conn.commit() return self.cursor.lastrowid def get_project_or_create(self, pname): self.cursor.execute( \"SELECT", "= self.get_timesheet_fields(mask) return ', '.join(fields) def get_minimal_started_track(self, tname='', pname=''): \"\"\"Get a minimal tracked", "if started and finished: between_clause = \"AND DATE(started) BETWEEN ? AND ?\" params.extend([started,", "track_id) ) self.conn.commit() return finished def update_track(self, track_id, started, finished, is_billed): \"\"\"Updates the", "started, \" \" Tracks.finished as finished \" \"FROM Tracks, Tasks, Projects \" \"WHERE", "= self.get_timesheet_select_clause(group_by_mask) query = \"SELECT {clause} FROM ({query})\".format( query=query, clause=select_clause) self.cursor.execute(query, params) return", "datetime.datetime.now() if started and config.BT_TIMESHEET_ROUNDING and config.BT_ROUNDING_INCREMENT: delta = finished - started round_to", "* FROM Tracks \") tracks = self.cursor.fetchall() #print('filled tracks', tracks) print(tabulate(tracks, ['Track id',", "customer def get_customer_or_create(self, customer): self.cursor.execute( \"SELECT id, name FROM Customers \" \"WHERE name", "'finished', 'is_billed') \" \"VALUES (?, ?, ?, ?)\", (task_id, started, finished, int(is_billed)) )", "- timedelta(days=4) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3601)) self.create_track(last_task, started=started+timedelta(seconds=13600), finished=started+timedelta(seconds=14600)) self.create_track(last_task, started=started+timedelta(seconds=15600), finished=started+timedelta(seconds=16600))", "\" \"WHERE \" \" pid == '{pid}'\" \" name == '{name}'\".format(name=pname.encode('utf8'), pid=pid) )", ") self.conn.commit() # TIMESHEET def get_group_by_clause(self, mask): \"\"\"Makes a GROUP BY clause by", "\", SUM(CASE WHEN Tracks.finished == '' THEN 1 ELSE 0 END) \" self.cursor.execute(", "pid == '{project!s}'\" \"\".format(task=name.encode('utf8'), project=project_id) ) last = self.cursor.fetchone() if last: return last['tid']", "import sqlite3 import random import string import time import datetime from datetime import", "== ? AND \" params.append(pname) self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name", "\" {between_clause} \" \"ORDER BY Tracks.id\".format(started=started, finished=finished, where_clause=where_clause, between_clause=between_clause), params ) return self.cursor.fetchall()", "TIMESTAMP, ' ' is_billed INTEGER DEFAULT 1' ')') # CUSTOMERS self.cursor.execute( 'CREATE TABLE", "ELSE 0 end) AS active \" \"FROM Projects, Tracks, Tasks \" \"WHERE \"", "def delete_tracks_by_date(self, started, finished, also_unfinished=False): \"\"\"Deletes tracks by the date\"\"\" if not also_unfinished:", "'{project!s}'\" \"\".format(task=name.encode('utf8'), project=project_id) ) last = self.cursor.fetchone() if last: return last['tid'] return self.create_task(name,", "# Add a Project self.create_project('p1', 'Test Project #1') self.cursor.execute(\"SELECT * FROM Projects ORDER", "= where_task_clause = '' if tname: params.append(tname.encode('utf8')) where_task_clause = \"tname == ? AND", "_get_active_tasks(self): \"\"\"Get active tasks\"\"\" self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as", "\" \"FROM Projects \" \"WHERE NOT EXISTS (\" \" SELECT id FROM Tasks", "= set_group_by_clause(TS_GROUP_BY['project'], 'Tasks.project_id', group_by) group_by = set_group_by_clause(TS_GROUP_BY['task'], 'Tracks.task_id', group_by) group_by = set_group_by_clause(TS_GROUP_BY['track'], 'Tracks.id',", "self.cursor.execute(\"SELECT * FROM Projects ORDER BY id LIMIT 1\") project = self.cursor.fetchone() #print('filled", "id', 'Task id', 'started', 'finished', 'billed'], tablefmt='simple')) return # CUSTOMERS def get_customer(self, customer):", "task or create one\"\"\" self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as", "== Tasks.id {where_clause}\" \"GROUP BY Projects.id \" \"UNION SELECT \" \" Projects.id as", "? AND ?\" params.extend([started, finished]) self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name", "== '{task:s}' AND \" \" pname == '{project:s}'\" \"\".format(task=tname.encode('utf8'), project=pname.encode('utf8')) ) return self.cursor.fetchone()", "0 # date - 1 # task - 2 # project - 3", "[] last_task = self.insert_test_task(project_id=2) self.create_track(last_task, started=started+timedelta(seconds=21600), finished=started+timedelta(seconds=22600)) self.create_track(last_task, started=started+timedelta(seconds=23600), finished=started+timedelta(seconds=24600)) self.create_track(last_task, started=started+timedelta(seconds=25600), finished=started+timedelta(seconds=26600))", "'billed'], tablefmt='simple')) return # CUSTOMERS def get_customer(self, customer): self.cursor.execute( \"SELECT id, name FROM", "\"WHERE \" \" {where_task_clause}\" \" {where_project_clause}\" \" Tracks.task_id == tid AND \" \"", "return self.cursor.lastrowid def finish_track(self, track_id, started=None): finished = datetime.datetime.now() if started and config.BT_TIMESHEET_ROUNDING", "(pname.encode('utf8'),) ) return self.cursor.fetchone() def update_project(self, pid, name, description): \"\"\"Updates a project\"\"\" self.cursor.execute(", "\" SELECT MAX(Tracks.id) FROM Tracks \" \" {where_clause} \" \" GROUP BY Tracks.task_id", "{where_date_clause}\".format( where_date_clause=where_date_clause, where_project_clause=where_project_clause, where_task_clause=where_task_clause ), params ) return self.cursor.fetchone() def update_task(self, tid, name,", "created, \" \" description as description \" \"FROM Projects \" \"WHERE \" \"", "of last tasks\"\"\" activity_field = '' if add_activity: activity_field = \", SUM(CASE WHEN", "\" \" Tasks.project_id == Projects.id AND \" \" trid == %d\" % tid", "FROM Tracks') # Add a Customer self.cursor.execute( \"insert into Customers ('name', 'description') \"", "' ' project_id INTEGER REFERENCES Projects(id) ON DELETE CASCADE, ' ' name VARCHAR", "into Customers ('name', 'description') \" \"VALUES ('Andrey', 'Customer Numer One')\") self.cursor.execute(\"SELECT * FROM", "trid == %d\" % tid ) return self.cursor.fetchone() def create_track(self, task_id, started='', finished='',", "\" \" (\" \" DATE(started) BETWEEN ? AND ?\" \" AND NOT Tracks.finished", "of last tasks between dates including unfinished\"\"\" where_clause = first_limit_clause = last_limit_clause =", "str( \"SELECT \" \" Tasks.id as tid, Tasks.name as tname, Projects.name as pname,", "'{from_date}' \" \\ \"AND '{to_date}' \".format(from_date=from_date, to_date=to_date) self.cursor.execute( \"{first_limit_clause}\" \"SELECT \" \" Projects.id", "pid, Projects.name as pname, \" \" Tracks.id as trid, Tracks.started as started, \"", "self.cursor.fetchone() def update_project(self, pid, name, description): \"\"\"Updates a project\"\"\" self.cursor.execute( \"UPDATE Projects \"", "Tracks.task_id == Tasks.id {where_clause}\" \"GROUP BY Projects.id \" \"UNION SELECT \" \" Projects.id", "Projects \" \"SET name=?, description=?\" \"WHERE id=?\", (name.encode('utf8'), description.encode('utf8'), pid) ) self.conn.commit() def", "AND '{finished}'\" \"\".format(started=started, finished=finished)) if limit: first_limit_clause = \"SELECT * FROM (\" last_limit_clause", "\" description as description \" \"FROM Projects \" \"WHERE \" \" pid ==", "id, name FROM Projects \" \"WHERE name == '{name:s}'\".format(name=pname.encode('utf8')) ) project = self.cursor.fetchone()", "' finished TIMESTAMP, ' ' is_billed INTEGER DEFAULT 1' ')') # CUSTOMERS self.cursor.execute(", "started, finished, int(is_billed)) ) self.conn.commit() return self.cursor.lastrowid def finish_track(self, track_id, started=None): finished =", "project\"\"\" self.cursor.execute( \"UPDATE Projects \" \"SET name=?, description=?\" \"WHERE id=?\", (name.encode('utf8'), description.encode('utf8'), pid)", "= \"tname == ? AND \" params.append(tname) if pname: pname = pname.encode('utf8') where_project_clause", "between_clause=between_clause), params ) return self.cursor.fetchall() def get_track_by_id(self, tid): self.cursor.execute( \"SELECT \" \" Tasks.id", "self.cursor.fetchone() #print('filled customers', customers) # Add a Project self.create_project('p1', 'Test Project #1') self.cursor.execute(\"SELECT", "\" \" SUM(CASE WHEN Tracks.finished == '' THEN 1 ELSE 0 end) AS", "as description \" \"FROM Tasks, Projects \" \"WHERE \" \" tname == '{task}'", "('name', 'description', created)\" \"VALUES (?, ?, ?)\", ( pname.encode('utf8'), description.encode('utf8'), str(datetime.datetime.now()) ) )", "+ datetime.timedelta(seconds=seconds) self.cursor.execute( \"UPDATE Tracks SET finished=? WHERE id=?\", (finished, track_id) ) self.conn.commit()", "datetime.datetime.now() - timedelta(days=1) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3600)) started = datetime.datetime.now() - timedelta(seconds=3300)", "== '{name:s}'\".format(name=customer) ) customer = self.cursor.fetchone() return customer def get_customer_or_create(self, customer): self.cursor.execute( \"SELECT", "== Projects.id AND \" \" finished == '' \" \" {where_date_clause}\".format( where_date_clause=where_date_clause, where_project_clause=where_project_clause,", "id=?\", ( name.encode('utf8'), description.encode('utf8'), tid ) ) self.conn.commit() def delete_task(self, tid): \"\"\"\"\"\" self.cursor.execute(", "- 9-item sequence, not float if not started: started = datetime.datetime.now() self.cursor.execute( \"INSERT", "pid) ) self.conn.commit() def is_project_existent(self, pname, pid): \"\"\"Checks if project already exists \"\"\"", "def get_task_or_create(self, name, project_id): \"\"\"Get a task or create one\"\"\" self.cursor.execute( \"SELECT \"", "'DATE(started) as \"date [date]\"', 'Date') task_field = (1, 'tname', 'Task') project_field = (2,", "'finished', 'billed'], tablefmt='simple')) return # CUSTOMERS def get_customer(self, customer): self.cursor.execute( \"SELECT id, name", "self.conn.commit() # PROJECTS def get_project_by_name(self, pname): self.cursor.execute( \"SELECT \" \" id as pid,", "\" id as pid, name as pname, created as created, \" \" description", "'' if limit: first_limit_clause = \"SELECT * FROM (\" last_limit_clause = \" DESC", "and finished: between_clause = \"AND DATE(started) BETWEEN ? AND ?\" params.extend([started, finished]) self.cursor.execute(", "\" description as description \" \"FROM Projects \" \"WHERE \" \" Projects.name ==", "id INTEGER PRIMARY KEY, ' ' task_id INTEGER REFERENCES Tasks(id) ON DELETE CASCADE,", "get_task_by_alias(self, tname, pname): \"\"\"Get task by name\"\"\" self.cursor.execute( \"SELECT \" \" Tasks.id as", "\" name == '{name}'\".format(name=pname.encode('utf8'), pid=pid) ) return self.cursor.fetchone() def get_projects_with_activity_field(self, from_date='', to_date='', limit=0):", "spent date_field = (0, 'DATE(started) as \"date [date]\"', 'Date') task_field = (1, 'tname',", "config.BT_TIMESHEET_ROUNDING and config.BT_ROUNDING_INCREMENT: delta = finished - started round_to = config.BT_ROUNDING_INCREMENT * 60", "self.create_track(last_task, started=started+timedelta(seconds=23600), finished=started+timedelta(seconds=24600)) self.create_track(last_task, started=started+timedelta(seconds=25600), finished=started+timedelta(seconds=26600)) started = datetime.datetime.now() - timedelta(days=3) self.create_track(last_task, started=started,", "return self.cursor.fetchone() def get_projects_with_activity_field(self, from_date='', to_date='', limit=0): \"\"\"Get list of project including a", "self.conn.commit() # TASKS def get_tasks(self, limit=10, add_activity=False): \"\"\"Lists of last tasks\"\"\" activity_field =", "'Customer Numer One')\") self.cursor.execute(\"SELECT * FROM Customers ORDER BY id LIMIT 1\") customers", "= (4, 'DATETIME(finished) as \"finished [timestamp]\"', 'To') spent_field = (5, 'spent', 'Time Spent')", "Projects.name == ?\", (pname.encode('utf8'),) ) return self.cursor.fetchone() def update_project(self, pid, name, description): \"\"\"Updates", "REFERENCES Tasks(id) ON DELETE CASCADE, ' ' started TIMESTAMP, ' ' finished TIMESTAMP,", "as description, \" \" Tracks.started as started, Tracks.finished as finished \" \"FROM Tasks,", "project=pname.encode('utf8')) ) return self.cursor.fetchone() def create_task(self, name, pid): self.cursor.execute( \"INSERT INTO Tasks ('name',", "- 0 # date - 1 # task - 2 # project -", "== '{name}'\" \"\".format(name=pname.encode('utf8'))) self.conn.commit() # TASKS def get_tasks(self, limit=10, add_activity=False): \"\"\"Lists of last", "(?, ?)\", ( name.encode('utf8'), pid ) ) self.conn.commit() return self.cursor.lastrowid def get_task_or_create(self, name,", "FROM Tasks WHERE id == '{tid}'\".format(tid=tid)) self.conn.commit() # TRACKS def get_tracks_by_date(self, started='', finished='',", "== pid AND \" \" pid == '{project!s}'\" \"\".format(task=name.encode('utf8'), project=project_id) ) last =", "FROM Projects ORDER BY id LIMIT 1\") project = self.cursor.fetchone() #print('filled projects', project)", "self.cursor.fetchone() #print('filled projects', project) # Add the Task last_task = self.insert_test_task(project_id=1) # Add", "Tracks.finished as finished, \" \" Tasks.description as description \" \"FROM Tracks, Tasks, Projects", "set_group_by_clause(TS_GROUP_BY['project'], 'Tasks.project_id', group_by) group_by = set_group_by_clause(TS_GROUP_BY['task'], 'Tracks.task_id', group_by) group_by = set_group_by_clause(TS_GROUP_BY['track'], 'Tracks.id', group_by)", "TIMESTAMP' ')') self.conn.commit() def __init__(self, db_name): # create DB self.init_db(db_name) self.create_db() def insert_test_task(self,", "between_clause = '' params = [] if not also_unfinished: where_clause = \"AND NOT", "pname, \" \" DATE(started) as 'started [date]'\" \"FROM Tracks, Tasks, Projects \" \"WHERE", "\\ \" AND ? \" params.extend([started, finished]) self.cursor.execute( \"SELECT \" \" Tasks.id as", "last tasks between dates including unfinished\"\"\" where_clause = first_limit_clause = last_limit_clause = ''", "\"\"\"Lists of last tasks\"\"\" activity_field = '' if add_activity: activity_field = \", SUM(CASE", "Tracks') # Add a Customer self.cursor.execute( \"insert into Customers ('name', 'description') \" \"VALUES", "return self.create_task(name, project_id) def _get_active_tasks(self): \"\"\"Get active tasks\"\"\" self.cursor.execute( \"SELECT \" \" Tasks.id", "datetime from datetime import timedelta import operator from tabulate import tabulate import config", "+ timedelta(seconds=600)) last_track = self.create_track(last_task) self.cursor.execute(\"SELECT * FROM Tracks \") tracks = self.cursor.fetchall()", "\" \"VALUES \" \" (?, ?)\", ( name.encode('utf8'), pid ) ) self.conn.commit() return", "\" Tracks.is_billed as is_billed \" \"FROM Tracks, Tasks, Projects \" \"WHERE \" \"", "= last_limit_clause = '' if limit: first_limit_clause = \"SELECT * FROM (\" last_limit_clause", "where_task_clause=where_task_clause, where_project_clause=where_project_clause, group_by_clause=group_by_clause, only_billed_clause=only_billed_clause) ) #print(query) if group_by_mask: select_clause = self.get_timesheet_select_clause(group_by_mask) query =", "IF NOT EXISTS Projects(' ' id INTEGER PRIMARY KEY, ' ' customer_id INTEGER,", "Projects.id as pid, Projects.name, Projects.created, \" \" Projects.description, \" \" SUM(CASE WHEN Tracks.finished", "\"\"\"Deletes tracks by the date\"\"\" if not also_unfinished: where_clause = \"AND NOT finished", "'') group_by = set_group_by_clause(TS_GROUP_BY['project'], 'Tasks.project_id', group_by) group_by = set_group_by_clause(TS_GROUP_BY['task'], 'Tracks.task_id', group_by) group_by =", "\" self.cursor.execute( \"DELETE \" \" FROM Tracks \" \"WHERE \" \" DATE(started) BETWEEN", "#print('filled projects', project) # Add the Task tasks = [] last_task = self.insert_test_task(project_id=2)", "' ' customer_id INTEGER, ' ' name VARCHAR UNIQUE COLLATE NOCASE, ' '", "finished == '' \" self.cursor.execute( \"DELETE \" \" FROM Tracks \" \"WHERE \"", "group_by: group_by = \"GROUP BY %s \" % group_by return group_by def get_timesheet_fields(self,", "\"WHERE id=?\", (started, finished, is_billed, track_id) ) self.conn.commit() def delete_tracks_by_date(self, started, finished, also_unfinished=False):", "& TS_GROUP_BY['date']: clause.add(date_field) if mask & TS_GROUP_BY['task']: clause.update([task_field, project_field]) if mask & TS_GROUP_BY['project']:", "a task/project\"\"\" params = [] only_billed_clause = where_project_clause = where_task_clause = '' if", "last_limit_clause=last_limit_clause) ) tasks = self.cursor.fetchall() return tasks def get_task_by_alias(self, tname, pname): \"\"\"Get task", "last = self.cursor.fetchone() if last: return last['tid'] return self.create_task(name, project_id) def _get_active_tasks(self): \"\"\"Get", "Projects.name, Projects.created,\" \" Projects.description, '' as active \" \"FROM Projects \" \"WHERE NOT", "'description TEXT, ' 'created TIMESTAMP' ')') self.conn.commit() def __init__(self, db_name): # create DB", "def create_project(self, pname, description=''): \"\"\"Create a project\"\"\" self.cursor.execute( \"INSERT INTO Projects ('name', 'description',", "\" \"ORDER BY Tracks.id\".format(started=started, finished=finished, where_clause=where_clause, between_clause=between_clause), params ) return self.cursor.fetchall() def get_track_by_id(self,", "get_timesheet(self, started, finished, group_by_mask, only_billed=True, tname='', pname=''): \"\"\" Gets the time was spent", "delete_task(self, tid): \"\"\"\"\"\" self.cursor.execute( \"DELETE FROM Tasks WHERE id == '{tid}'\".format(tid=tid)) self.conn.commit() #", "\" Projects.description, '' as active \" \"FROM Projects \" \"WHERE NOT EXISTS (\"", "project\"\"\" self.cursor.execute( \"INSERT INTO Projects ('name', 'description', created)\" \"VALUES (?, ?, ?)\", (", "tname, pname): \"\"\"Get task by name\"\"\" self.cursor.execute( \"SELECT \" \" Tasks.id as tid,", "import operator from tabulate import tabulate import config TS_GROUP_BY = dict( timestamp=0b10000, project=0b1000,", "customer: return customer self.cursor.execute( \"INSERT INTO Customers ('name')\" \"VALUES ('{name:s}')\" .format(name=customer) ) self.conn.commit()", "('name', 'project_id') \" \"values('%s', '%s')\" % (name, project_id) ) self.conn.commit() return self.cursor.lastrowid def", "WHERE id=?\", (finished, track_id) ) self.conn.commit() return finished def update_track(self, track_id, started, finished,", "= \" DESC LIMIT %d) ORDER BY pid ASC\" % limit if from_date", "def get_timesheet_fields(self, mask, get_headers=False): \"\"\"Makes a list of ordered fields\"\"\" # Priority: #", "\"ORDER BY Tracks.id\".format(started=started, finished=finished, where_clause=where_clause, between_clause=between_clause), params ) return self.cursor.fetchall() def get_track_by_id(self, tid):", "mask & bits: if group_by: group_by = \"%s,\" % group_by group_by = '{group_by}", "3 # spent - 4 # date, tname, pname, started, finished, spent date_field", "self.conn.commit() def delete_tracks_by_date(self, started, finished, also_unfinished=False): \"\"\"Deletes tracks by the date\"\"\" if not", "Add a Customer self.cursor.execute( \"insert into Customers ('name', 'description') \" \"VALUES ('Andrey', 'Customer", "FROM Projects \" \"WHERE name == '{name:s}'\".format(name=pname.encode('utf8')) ) project = self.cursor.fetchone() if project:", "if get_headers else 1 return map(operator.itemgetter(to_get), sorted(clause, key=operator.itemgetter(0))) def get_timesheet_select_clause(self, mask): \"\"\"Get prepared", ") return self.cursor.fetchone() def create_track(self, task_id, started='', finished='', is_billed=True): # started, finished -", "\"ORDER BY started, Tasks.id\" \"\".format(started=started, finished=finished, where_task_clause=where_task_clause, where_project_clause=where_project_clause, group_by_clause=group_by_clause, only_billed_clause=only_billed_clause) ) #print(query) if", "TRACKS self.cursor.execute( 'CREATE TABLE IF NOT EXISTS Tracks(' ' id INTEGER PRIMARY KEY,", "(0, 'DATE(started) as \"date [date]\"', 'Date') task_field = (1, 'tname', 'Task') project_field =", "self.cursor.execute( 'CREATE TABLE IF NOT EXISTS Projects(' ' id INTEGER PRIMARY KEY, '", "\"ORDER BY Tasks.id DESC LIMIT {limit:d}\".format( limit=limit, activity_field=activity_field) ) tasks = self.cursor.fetchall() return", "exists \"\"\" self.cursor.execute( \"SELECT \" \" id as pid, name as name, created", "print(tabulate(tracks, ['Track id', 'Task id', 'started', 'finished', 'billed'], tablefmt='simple')) return # CUSTOMERS def", "SELECT id FROM Tasks WHERE \" \" Tasks.project_id == Projects.id \" \") {where_clause}\"", "Projects(id) ON DELETE CASCADE, ' ' name VARCHAR COLLATE NOCASE, ' ' description", "' ' description TEXT DEFAULT \"\"' ')') # TRACKS self.cursor.execute( 'CREATE TABLE IF", "% (name, project_id) ) self.conn.commit() return self.cursor.lastrowid def fill(self): \"\"\"Fill with the test", "Projects.id {last_limit_clause}\".format( where_clause=where_clause, first_limit_clause=first_limit_clause, last_limit_clause=last_limit_clause) ) return self.cursor.fetchall() def create_project(self, pname, description=''): \"\"\"Create", "self.create_track(last_task, started=started+timedelta(seconds=25600), finished=started+timedelta(seconds=26600)) started = datetime.datetime.now() - timedelta(days=3) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3600))", "= dict( timestamp=0b10000, project=0b1000, task=0b0100, track=0b0010, date=0b0001 ) class Database: def init_db(self, db_path):", ") return self.cursor.fetchall() def get_track_by_id(self, tid): self.cursor.execute( \"SELECT \" \" Tasks.id as tid,", "config.BT_ROUNDING_INCREMENT: delta = finished - started round_to = config.BT_ROUNDING_INCREMENT * 60 seconds =", "id', 'started', 'finished', 'billed'], tablefmt='simple')) return # CUSTOMERS def get_customer(self, customer): self.cursor.execute( \"SELECT", "Gets the time was spent for a task/project\"\"\" params = [] only_billed_clause =", "\"\"\"Makes a GROUP BY clause by bit mask\"\"\" def set_group_by_clause(bits, value, group_by): \"\"\"Add", "def get_group_by_clause(self, mask): \"\"\"Makes a GROUP BY clause by bit mask\"\"\" def set_group_by_clause(bits,", "finished - started round_to = config.BT_ROUNDING_INCREMENT * 60 seconds = round_to - delta.seconds", "Projects.name as pname, \" \" Tracks.id as track_id, Tracks.started as started, \" \"", "date=0b0001 ) class Database: def init_db(self, db_path): self.conn = sqlite3.connect( db_path, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES )", "AND \" \" Tasks.project_id == pid AND \" \" pid == '{project!s}'\" \"\".format(task=name.encode('utf8'),", "pname = pname.encode('utf8') where_project_clause = \"pname == ? AND \" params.append(pname) self.cursor.execute( \"SELECT", "description \" \"FROM Projects \" \"WHERE \" \" pid == '{pid}'\" \" name", "TRACKS def get_tracks_by_date(self, started='', finished='', also_unfinished=False): \"\"\"Get tracks\"\"\" where_clause = '' between_clause =", "finished=started+timedelta(seconds=20600)) # Add a Project #2 self.create_project('p2', 'Test Project #1') self.cursor.execute(\"SELECT * FROM", "def delete_project_by_name(self, pname): self.cursor.execute( \"DELETE FROM Projects WHERE name == '{name}'\" \"\".format(name=pname.encode('utf8'))) self.conn.commit()", "tname, Projects.id as pid, \" \" Projects.name as pname, Tasks.description as description \"", "project=project_id) ) last = self.cursor.fetchone() if last: return last['tid'] return self.create_task(name, project_id) def", "as started, \" \" Tracks.finished as finished, \" \" Tracks.is_billed as is_billed \"", "group_by) if group_by: group_by = \"GROUP BY %s \" % group_by return group_by", "BY tid ASC\" % limit self.cursor.execute( \"{first_limit_clause}\" \"SELECT \" \" Tasks.id as tid,", "% group_by return group_by def get_timesheet_fields(self, mask, get_headers=False): \"\"\"Makes a list of ordered", "finished == '' \" \" {where_date_clause}\".format( where_date_clause=where_date_clause, where_project_clause=where_project_clause, where_task_clause=where_task_clause ), params ) return", "INTO Projects ('name', 'description', created)\" \"VALUES (?, ?, ?)\", ( pname.encode('utf8'), description.encode('utf8'), str(datetime.datetime.now())", "(\" \" DATE(started) BETWEEN ? AND ?\" \" AND NOT Tracks.finished == ''\"", "Tasks.description as description \" \"FROM Tasks, Projects \" \"WHERE \" \" Tasks.project_id ==", "(\" last_limit_clause = \" DESC LIMIT %d) ORDER BY pid ASC\" % limit", "BY tid {last_limit_clause}\" \"\".format( where_clause=where_clause, first_limit_clause=first_limit_clause, last_limit_clause=last_limit_clause) ) tasks = self.cursor.fetchall() return tasks", "\"SELECT * FROM (\" last_limit_clause = \" DESC LIMIT %d) ORDER BY pid", "'DATE(started)', '') group_by = set_group_by_clause(TS_GROUP_BY['project'], 'Tasks.project_id', group_by) group_by = set_group_by_clause(TS_GROUP_BY['task'], 'Tracks.task_id', group_by) group_by", "'Time Spent') clause = set() if mask & TS_GROUP_BY['date']: clause.add(date_field) if mask &", "== tid AND \" \" Tasks.project_id == pid\" \" {where_clause} \" \" {between_clause}", "as tname, Projects.id as pid, \" \" Projects.name as pname, Tasks.description as description,", "{only_billed_clause}\" \" ) \" \"{group_by_clause} \" \"ORDER BY started, Tasks.id\" \"\".format(started=started, finished=finished, where_task_clause=where_task_clause,", "description \" \"FROM Tasks, Projects \" \"WHERE \" \" Tasks.project_id == pid AND", "to_date: where_clause = \" AND DATE(Projects.created) BETWEEN '{from_date}' \" \\ \"AND '{to_date}' \".format(from_date=from_date,", "round_to = config.BT_ROUNDING_INCREMENT * 60 seconds = round_to - delta.seconds % round_to finished", "get_timesheet_fields(self, mask, get_headers=False): \"\"\"Makes a list of ordered fields\"\"\" # Priority: # datetime", "description=?\" \"WHERE id=?\", ( name.encode('utf8'), description.encode('utf8'), tid ) ) self.conn.commit() def delete_task(self, tid):", "params = [] where_project_clause = where_task_clause = '' if tname: tname = tname.encode('utf8')", "'' as active \" \"FROM Projects \" \"WHERE NOT EXISTS (\" \" SELECT", "\"WHERE \" \" Tasks.project_id == Projects.id AND \" \" Tracks.task_id == Tasks.id {where_clause}\"", "def create_task(self, name, pid): self.cursor.execute( \"INSERT INTO Tasks ('name', 'project_id') \" \"VALUES \"", "FROM (\" last_limit_clause = \" DESC LIMIT %d) ORDER BY pid ASC\" %", "DATE(Projects.created) BETWEEN '{from_date}' \" \\ \"AND '{to_date}' \".format(from_date=from_date, to_date=to_date) self.cursor.execute( \"{first_limit_clause}\" \"SELECT \"", "self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as tname, Projects.name as pname,", "import tabulate import config TS_GROUP_BY = dict( timestamp=0b10000, project=0b1000, task=0b0100, track=0b0010, date=0b0001 )", "value=value) return group_by group_by = set_group_by_clause(TS_GROUP_BY['date'], 'DATE(started)', '') group_by = set_group_by_clause(TS_GROUP_BY['project'], 'Tasks.project_id', group_by)", "- timedelta(days=1) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3600)) started = datetime.datetime.now() - timedelta(seconds=3300) self.create_track(last_task,", "= [] last_task = self.insert_test_task(project_id=2) self.create_track(last_task, started=started+timedelta(seconds=21600), finished=started+timedelta(seconds=22600)) self.create_track(last_task, started=started+timedelta(seconds=23600), finished=started+timedelta(seconds=24600)) self.create_track(last_task, started=started+timedelta(seconds=25600),", "of the track record\"\"\" self.cursor.execute( \"UPDATE Tracks \" \"SET started=?, finished=?, is_billed=? \"", "datetime import timedelta import operator from tabulate import tabulate import config TS_GROUP_BY =", "== ?\", (pname.encode('utf8'),) ) return self.cursor.fetchone() def update_project(self, pid, name, description): \"\"\"Updates a", "- started round_to = config.BT_ROUNDING_INCREMENT * 60 seconds = round_to - delta.seconds %", "create_track(self, task_id, started='', finished='', is_billed=True): # started, finished - 9-item sequence, not float", "the date\"\"\" if not also_unfinished: where_clause = \"AND NOT finished == '' \"", "get_project_by_name(self, pname): self.cursor.execute( \"SELECT \" \" id as pid, name as pname, created", "clause.update([task_field, project_field]) if mask & TS_GROUP_BY['project']: clause.add(project_field) if mask & TS_GROUP_BY['track']: clause.update([task_field, project_field,", "finished=started+timedelta(seconds=16600)) last_task = self.insert_test_task(project_id=1) self.create_track(last_task, started=started+timedelta(seconds=17600), finished=started+timedelta(seconds=18600)) self.create_track(last_task, started=started+timedelta(seconds=19600), finished=started+timedelta(seconds=20600)) # Add a", "\\ \"AND '{to_date}' \".format(from_date=from_date, to_date=to_date) self.cursor.execute( \"{first_limit_clause}\" \"SELECT \" \" Projects.id as pid,", "== '{project!s}'\" \"\".format(task=name.encode('utf8'), project=project_id) ) last = self.cursor.fetchone() if last: return last['tid'] return", "project including a field is a project is finished\"\"\" where_clause = first_limit_clause =", "Tasks.name as tname, Projects.name as pname, \" \" SUM(STRFTIME('%s', finished)-STRFTIME('%s', started)) as spent,\"", "1\") project = self.cursor.fetchone() #print('filled projects', project) # Add the Task tasks =", "Projects \" \"WHERE name == '{name:s}'\".format(name=pname.encode('utf8')) ) project = self.cursor.fetchone() if project: return", "track record\"\"\" self.cursor.execute( \"UPDATE Tracks \" \"SET started=?, finished=?, is_billed=? \" \"WHERE id=?\",", "tname: tname = tname.encode('utf8') where_task_clause = \"tname == ? AND \" params.append(tname) if", "= set_group_by_clause(TS_GROUP_BY['task'], 'Tracks.task_id', group_by) group_by = set_group_by_clause(TS_GROUP_BY['track'], 'Tracks.id', group_by) if group_by: group_by =", "\" Tasks.project_id == Projects.id AND \" \" finished == ''\") return self.cursor.fetchall() def", "\" Tasks.project_id == Projects.id AND \" \" Tracks.task_id == Tasks.id {where_clause}\" \"GROUP BY", "\") tracks = self.cursor.fetchall() #print('filled tracks', tracks) print(tabulate(tracks, ['Track id', 'Task id', 'started',", "spend and is billed flag of the track record\"\"\" self.cursor.execute( \"UPDATE Tracks \"", "finished = finished + datetime.timedelta(seconds=seconds) self.cursor.execute( \"UPDATE Tracks SET finished=? WHERE id=?\", (finished,", "' ' created TIMESTAMP' ')') # TASKS self.cursor.execute( 'CREATE TABLE IF NOT EXISTS", "= finished - started round_to = config.BT_ROUNDING_INCREMENT * 60 seconds = round_to -", "date - 1 # task - 2 # project - 3 # spent", "where_task_clause=where_task_clause ), params ) return self.cursor.fetchone() def update_task(self, tid, name, description=''): \"\"\"Updates the", "return self.cursor.fetchall() def get_track_by_id(self, tid): self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name", "'' THEN 1 ELSE 0 END) \" self.cursor.execute( \"SELECT \" \" Tasks.id, Tasks.name,", "return last['tid'] return self.create_task(name, project_id) def _get_active_tasks(self): \"\"\"Get active tasks\"\"\" self.cursor.execute( \"SELECT \"", ") customer = self.cursor.fetchone() return customer def get_customer_or_create(self, customer): self.cursor.execute( \"SELECT id, name", ") customer = self.cursor.fetchone() if customer: return customer self.cursor.execute( \"INSERT INTO Customers ('name')\"", "\"FROM Tracks, Tasks, Projects \" \"WHERE \" \" {where_task_clause}\" \" {where_project_clause}\" \" Tracks.task_id", "finished=finished)) if limit: first_limit_clause = \"SELECT * FROM (\" last_limit_clause = \" DESC", "finished + datetime.timedelta(seconds=seconds) self.cursor.execute( \"UPDATE Tracks SET finished=? WHERE id=?\", (finished, track_id) )", "where_project_clause=where_project_clause, where_task_clause=where_task_clause ), params ) return self.cursor.fetchone() def update_task(self, tid, name, description=''): \"\"\"Updates", "FROM Tracks \") tracks = self.cursor.fetchall() #print('filled tracks', tracks) print(tabulate(tracks, ['Track id', 'Task", "SUM(CASE WHEN Tracks.finished == '' THEN 1 ELSE 0 END) \" self.cursor.execute( \"SELECT", "if not started: started = datetime.datetime.now() self.cursor.execute( \"INSERT INTO Tracks \" \" ('task_id',", "customer): self.cursor.execute( \"SELECT id, name FROM Customers \" \"WHERE name == '{name:s}'\".format(name=customer) )", "get_headers=False): \"\"\"Makes a list of ordered fields\"\"\" # Priority: # datetime - 0", "' 'created TIMESTAMP' ')') self.conn.commit() def __init__(self, db_name): # create DB self.init_db(db_name) self.create_db()", "= '' if tname: tname = tname.encode('utf8') where_task_clause = \"tname == ? AND", "AND \" params.append(tname) if pname: pname = pname.encode('utf8') where_project_clause = \"pname == ?", "Tasks.project_id == Projects.id AND \" \" (\" \" DATE(started) BETWEEN ? AND ?\"", "self.get_group_by_clause(group_by_mask) query = str( \"SELECT \" \" Tasks.id as tid, Tasks.name as tname,", "pid ) ) self.conn.commit() return self.cursor.lastrowid def get_task_or_create(self, name, project_id): \"\"\"Get a task", "first_limit_clause = last_limit_clause = '' if limit: first_limit_clause = \"SELECT * FROM (\"", "[date]'\" \"FROM Tracks, Tasks, Projects \" \"WHERE \" \" {where_task_clause}\" \" {where_project_clause}\" \"", "self.cursor.fetchall() def get_track_by_id(self, tid): self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as", "\" \" Projects.description, \" \" SUM(CASE WHEN Tracks.finished == '' THEN 1 ELSE", "create_task(self, name, pid): self.cursor.execute( \"INSERT INTO Tasks ('name', 'project_id') \" \"VALUES \" \"", "\" (\" \" DATE(started) BETWEEN ? AND ?\" \" AND NOT Tracks.finished ==", "started = datetime.datetime.now() - timedelta(days=1) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3600)) started = datetime.datetime.now()", "Tasks(id) ON DELETE CASCADE, ' ' started TIMESTAMP, ' ' finished TIMESTAMP, '", "to_date=to_date) self.cursor.execute( \"{first_limit_clause}\" \"SELECT \" \" Projects.id as pid, Projects.name, Projects.created, \" \"", "= config.BT_ROUNDING_INCREMENT * 60 seconds = round_to - delta.seconds % round_to finished =", "finished=started + timedelta(seconds=3600)) started = datetime.datetime.now() - timedelta(days=2) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3600))", "tname, pname, started, finished, spent date_field = (0, 'DATE(started) as \"date [date]\"', 'Date')", "create one\"\"\" self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as tname, Projects.id", "== '' THEN 1 ELSE 0 END) \" self.cursor.execute( \"SELECT \" \" Tasks.id,", "get_active_task(self, started='', finished='', tname='', pname=''): \"\"\"Get an active task\"\"\" params = [] where_date_clause", "{between_clause} \" \"ORDER BY Tracks.id\".format(started=started, finished=finished, where_clause=where_clause, between_clause=between_clause), params ) return self.cursor.fetchall() def", "== '{task}' AND \" \" Tasks.project_id == pid AND \" \" pid ==", "' name VARCHAR COLLATE NOCASE, ' ' description TEXT DEFAULT \"\"' ')') #", "datetime.datetime.now() - timedelta(seconds=3300) self.create_track(last_task, started=started, finished=started + timedelta(seconds=600)) last_track = self.create_track(last_task) self.cursor.execute(\"SELECT *", "\" \"WHERE \" \" tname == '{task}' AND \" \" Tasks.project_id == pid", "LIMIT %d) ORDER BY pid ASC\" % limit if from_date and to_date: where_clause", "\"VALUES \" \" (?, ?)\", ( name.encode('utf8'), pid ) ) self.conn.commit() return self.cursor.lastrowid", "\" \\ \" BETWEEN ? \" \\ \" AND ? \" params.extend([started, finished])", "finished='', limit=0): \"\"\"The list of last tasks between dates including unfinished\"\"\" where_clause =", "sequence, not float if not started: started = datetime.datetime.now() self.cursor.execute( \"INSERT INTO Tracks", "if mask & TS_GROUP_BY['date']: clause.add(date_field) if mask & TS_GROUP_BY['task']: clause.update([task_field, project_field]) if mask", "name, description=''): \"\"\"Updates the task info\"\"\" self.cursor.execute( \"UPDATE Tasks \" \"SET name=?, description=?\"", "finished=finished, where_task_clause=where_task_clause, where_project_clause=where_project_clause, group_by_clause=group_by_clause, only_billed_clause=only_billed_clause) ) #print(query) if group_by_mask: select_clause = self.get_timesheet_select_clause(group_by_mask) query", "# Add the Task last_task = self.insert_test_task(project_id=1) # Add the Tracks started =", "== ? AND \" if only_billed: only_billed_clause = \" AND Tracks.is_billed == 1", "unfinished\"\"\" where_clause = first_limit_clause = last_limit_clause = '' if started and finished: where_clause", "and config.BT_TIMESHEET_ROUNDING and config.BT_ROUNDING_INCREMENT: delta = finished - started round_to = config.BT_ROUNDING_INCREMENT *", "* 60 seconds = round_to - delta.seconds % round_to finished = finished +", "with the test tasks\"\"\" self.cursor.execute('DELETE FROM Customers') self.cursor.execute('DELETE FROM Projects') self.cursor.execute('DELETE FROM Tasks')", "projects', project) # Add the Task tasks = [] last_task = self.insert_test_task(project_id=2) self.create_track(last_task,", "[timestamp]\"', 'From') finished_field = (4, 'DATETIME(finished) as \"finished [timestamp]\"', 'To') spent_field = (5,", "SET finished=? WHERE id=?\", (finished, track_id) ) self.conn.commit() return finished def update_track(self, track_id,", "\"INSERT INTO Tasks ('name', 'project_id') \" \"VALUES \" \" (?, ?)\", ( name.encode('utf8'),", "EXISTS Tracks(' ' id INTEGER PRIMARY KEY, ' ' task_id INTEGER REFERENCES Tasks(id)", "\"\".format(started=started, finished=finished)) if limit: first_limit_clause = \"SELECT * FROM (\" last_limit_clause = \"", "AND \" \" (\" \" DATE(started) BETWEEN ? AND ?\" \" AND NOT", "\"\", ' ' created TIMESTAMP' ')') # TASKS self.cursor.execute( 'CREATE TABLE IF NOT", "group_by = set_group_by_clause(TS_GROUP_BY['date'], 'DATE(started)', '') group_by = set_group_by_clause(TS_GROUP_BY['project'], 'Tasks.project_id', group_by) group_by = set_group_by_clause(TS_GROUP_BY['task'],", "tname, Projects.name as pname, \" \" DATE(started) as 'started [date]'\" \"FROM Tracks, Tasks,", "Database: def init_db(self, db_path): self.conn = sqlite3.connect( db_path, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES ) self.conn.row_factory = sqlite3.Row", "as started, \" \" Tracks.finished as finished \" \"FROM Tracks, Tasks, Projects \"", ") ORDER BY tid {last_limit_clause}\" \"\".format( where_clause=where_clause, first_limit_clause=first_limit_clause, last_limit_clause=last_limit_clause) ) tasks = self.cursor.fetchall()", "? AND \" if pname: params.append(pname.encode('utf8')) where_project_clause = \"pname == ? AND \"", "= [] only_billed_clause = where_project_clause = where_task_clause = '' if tname: params.append(tname.encode('utf8')) where_task_clause", "get_projects_with_activity_field(self, from_date='', to_date='', limit=0): \"\"\"Get list of project including a field is a", "(\" last_limit_clause = \" DESC LIMIT %d) ORDER BY tid ASC\" % limit", "where_clause = first_limit_clause = last_limit_clause = '' if started and finished: where_clause =", "return tasks def get_profiled_tasks(self, started='', finished='', limit=0): \"\"\"The list of last tasks between", "\"\"\"Get active tasks\"\"\" self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as tname,", "\"DELETE FROM Projects WHERE name == '{name}'\" \"\".format(name=pname.encode('utf8'))) self.conn.commit() # TASKS def get_tasks(self,", "self.cursor.execute( \"DELETE FROM Tasks WHERE id == '{tid}'\".format(tid=tid)) self.conn.commit() # TRACKS def get_tracks_by_date(self,", "Projects.id \" \") {where_clause}\" \"ORDER BY Projects.id {last_limit_clause}\".format( where_clause=where_clause, first_limit_clause=first_limit_clause, last_limit_clause=last_limit_clause) ) return", "= \"pname == ? AND \" if only_billed: only_billed_clause = \" AND Tracks.is_billed", "DELETE CASCADE, ' ' name VARCHAR COLLATE NOCASE, ' ' description TEXT DEFAULT", ") return self.cursor.fetchone() def get_projects_with_activity_field(self, from_date='', to_date='', limit=0): \"\"\"Get list of project including", "# Add the Task tasks = [] last_task = self.insert_test_task(project_id=2) self.create_track(last_task, started=started+timedelta(seconds=21600), finished=started+timedelta(seconds=22600))", "AND \" \" Tasks.project_id == Projects.id AND \" \" finished == ''\") return", "import config TS_GROUP_BY = dict( timestamp=0b10000, project=0b1000, task=0b0100, track=0b0010, date=0b0001 ) class Database:", "= '{group_by} {value}'.format(group_by=group_by, value=value) return group_by group_by = set_group_by_clause(TS_GROUP_BY['date'], 'DATE(started)', '') group_by =", "tname == '{task:s}' AND \" \" pname == '{project:s}'\" \"\".format(task=tname.encode('utf8'), project=pname.encode('utf8')) ) return", "= finished + datetime.timedelta(seconds=seconds) self.cursor.execute( \"UPDATE Tracks SET finished=? WHERE id=?\", (finished, track_id)", "self.cursor.fetchone() return customer def get_customer_or_create(self, customer): self.cursor.execute( \"SELECT id, name FROM Customers \"", "self.cursor.execute('DELETE FROM Tasks') self.cursor.execute('DELETE FROM Tracks') # Add a Customer self.cursor.execute( \"insert into", "\"FROM Tasks, Projects \" \"WHERE \" \" Tasks.project_id == pid AND \" \"", "def _get_active_tasks(self): \"\"\"Get active tasks\"\"\" self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name", "tasks\"\"\" activity_field = '' if add_activity: activity_field = \", SUM(CASE WHEN Tracks.finished ==", "for a task/project\"\"\" params = [] only_billed_clause = where_project_clause = where_task_clause = ''", "Tasks, Projects \" \"WHERE \" \" Tracks.task_id == tid AND \" \" Tasks.project_id", "also_unfinished=False): \"\"\"Deletes tracks by the date\"\"\" if not also_unfinished: where_clause = \"AND NOT", "9-item sequence, not float if not started: started = datetime.datetime.now() self.cursor.execute( \"INSERT INTO", "Tracks.finished as finished, \" \" Tracks.is_billed as is_billed \" \"FROM Tracks, Tasks, Projects", "as created, \" \" description as description \" \"FROM Projects \" \"WHERE \"", "\" \" Tasks.project_id == Projects.id AND \" \" (\" \" DATE(started) BETWEEN ?", "\" \" Projects.id as pid, Projects.name as pname, \" \" Tracks.id as trid,", "{activity_field}\" \"FROM Tasks, Projects, Tracks \" \"WHERE \" \" Tasks.project_id == Projects.id AND", "TEXT DEFAULT \"\", ' ' created TIMESTAMP' ')') # TASKS self.cursor.execute( 'CREATE TABLE", "_ in range(3)) self.cursor.execute( \"insert into Tasks ('name', 'project_id') \" \"values('%s', '%s')\" %", "name as name, created as created, \" \" description as description \" \"FROM", "Projects, Tracks, Tasks \" \"WHERE \" \" Tasks.project_id == Projects.id AND \" \"", "field is a project is finished\"\"\" where_clause = first_limit_clause = last_limit_clause = ''", "\" Tasks.project_id == Projects.id\" \"\".format(where_task_clause=where_task_clause, where_project_clause=where_project_clause), params) return self.cursor.fetchone() def get_timesheet(self, started, finished,", "== '{name:s}'\".format(name=pname.encode('utf8')) ) project = self.cursor.fetchone() if project: return project return self.create_project(name) def", "PROJECTS def get_project_by_name(self, pname): self.cursor.execute( \"SELECT \" \" id as pid, name as", "project_field = (2, 'pname', 'Project') started_field = (3, 'DATETIME(started) as \"started [timestamp]\"', 'From')", "Projects.id AND \" \" (\" \" DATE(started) BETWEEN ? AND ?\" \" AND", "finished='', tname='', pname=''): \"\"\"Get an active task\"\"\" params = [] where_date_clause = where_project_clause", "AND \" \" Tasks.project_id == Projects.id AND \" \" trid == %d\" %", "description as description \" \"FROM Projects \" \"WHERE \" \" Projects.name == ?\",", "\" \"GROUP BY Tasks.id \" \"ORDER BY Tasks.id DESC LIMIT {limit:d}\".format( limit=limit, activity_field=activity_field)", "last tasks\"\"\" activity_field = '' if add_activity: activity_field = \", SUM(CASE WHEN Tracks.finished", "# create DB self.init_db(db_name) self.create_db() def insert_test_task(self, project_id): name = ''.join(random.choice( string.ascii_uppercase +", "tid, Tasks.name as tname, Projects.id as pid, \" \" Projects.name as pname, Tasks.description", "' description TEXT DEFAULT \"\", ' ' created TIMESTAMP' ')') # TASKS self.cursor.execute(", "self.cursor.execute('DELETE FROM Tracks') # Add a Customer self.cursor.execute( \"insert into Customers ('name', 'description')", "name == '{name}'\".format(name=pname.encode('utf8'), pid=pid) ) return self.cursor.fetchone() def get_projects_with_activity_field(self, from_date='', to_date='', limit=0): \"\"\"Get", "[] where_date_clause = where_project_clause = where_task_clause = '' if tname: tname = tname.encode('utf8')", "('name', 'project_id') \" \"VALUES \" \" (?, ?)\", ( name.encode('utf8'), pid ) )", "BY clause by bit mask\"\"\" def set_group_by_clause(bits, value, group_by): \"\"\"Add a field to", "as description \" \"FROM Tracks, Tasks, Projects \" \"WHERE \" \" {where_task_clause}\" \"", "started round_to = config.BT_ROUNDING_INCREMENT * 60 seconds = round_to - delta.seconds % round_to", "as pid, name as pname, created as created, \" \" description as description", "* FROM Projects ORDER BY id LIMIT 1\") project = self.cursor.fetchone() #print('filled projects',", "\" \" {between_clause} \" \"ORDER BY Tracks.id\".format(started=started, finished=finished, where_clause=where_clause, between_clause=between_clause), params ) return", "self.cursor.execute( \"DELETE \" \" FROM Tracks \" \"WHERE \" \" DATE(started) BETWEEN ?", "Tracks, Tasks \" \"WHERE \" \" Tasks.project_id == Projects.id AND \" \" Tracks.task_id", "self.conn = sqlite3.connect( db_path, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES ) self.conn.row_factory = sqlite3.Row self.conn.text_factory = lambda x:", "create_project(self, pname, description=''): \"\"\"Create a project\"\"\" self.cursor.execute( \"INSERT INTO Projects ('name', 'description', created)\"", "{where_project_clause}\" \" Tracks.task_id == Tasks.id AND \" \" Tasks.project_id == Projects.id AND \"", "self.cursor.execute( 'CREATE TABLE IF NOT EXISTS Tasks(' ' id INTEGER PRIMARY KEY, '", "finished = datetime.datetime.now() if started and config.BT_TIMESHEET_ROUNDING and config.BT_ROUNDING_INCREMENT: delta = finished -", "foreign_keys = ON\") # Create Tables if do the not exist # PROJECTS", "\" Tasks.project_id == pid AND \" \" pid == '{project!s}'\" \"\".format(task=name.encode('utf8'), project=project_id) )", "+ timedelta(seconds=3600)) started = datetime.datetime.now() - timedelta(days=1) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3600)) started", "self.cursor.fetchall() return tasks def get_task_by_alias(self, tname, pname): \"\"\"Get task by name\"\"\" self.cursor.execute( \"SELECT", ") self.conn.commit() return self.cursor.lastrowid def finish_track(self, track_id, started=None): finished = datetime.datetime.now() if started", "{where_clause}\" \"ORDER BY Projects.id {last_limit_clause}\".format( where_clause=where_clause, first_limit_clause=first_limit_clause, last_limit_clause=last_limit_clause) ) return self.cursor.fetchall() def create_project(self,", "* FROM Customers ORDER BY id LIMIT 1\") customers = self.cursor.fetchone() #print('filled customers',", "self.conn.commit() # TIMESHEET def get_group_by_clause(self, mask): \"\"\"Makes a GROUP BY clause by bit", "\" trid == %d\" % tid ) return self.cursor.fetchone() def create_track(self, task_id, started='',", "group_by_clause = self.get_group_by_clause(group_by_mask) query = str( \"SELECT \" \" Tasks.id as tid, Tasks.name", "Tasks.id\" \"\".format(started=started, finished=finished, where_task_clause=where_task_clause, where_project_clause=where_project_clause, group_by_clause=group_by_clause, only_billed_clause=only_billed_clause) ) #print(query) if group_by_mask: select_clause =", "only_billed_clause=only_billed_clause) ) #print(query) if group_by_mask: select_clause = self.get_timesheet_select_clause(group_by_mask) query = \"SELECT {clause} FROM", "\"WHERE \" \" tname == '{task}' AND \" \" Tasks.project_id == pid AND", "def get_track_by_id(self, tid): self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as tname,", "fields\"\"\" # Priority: # datetime - 0 # date - 1 # task", "started=?, finished=?, is_billed=? \" \"WHERE id=?\", (started, finished, is_billed, track_id) ) self.conn.commit() def", "string.ascii_uppercase + string.digits) for _ in range(3)) self.cursor.execute( \"insert into Tasks ('name', 'project_id')", "pname: pname = pname.encode('utf8') where_project_clause = \"pname == ? AND \" params.append(pname) self.cursor.execute(", "only_billed: only_billed_clause = \" AND Tracks.is_billed == 1 \" params.extend([started, finished]) group_by_clause =", "description as description \" \"FROM Projects \" \"WHERE \" \" pid == '{pid}'\"", "\"\"\"Get task by name\"\"\" self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as", "tracked date\"\"\" params = [] where_project_clause = where_task_clause = '' if tname: tname", "'{group_by} {value}'.format(group_by=group_by, value=value) return group_by group_by = set_group_by_clause(TS_GROUP_BY['date'], 'DATE(started)', '') group_by = set_group_by_clause(TS_GROUP_BY['project'],", "description TEXT DEFAULT \"\", ' ' created TIMESTAMP' ')') # TASKS self.cursor.execute( 'CREATE", "finish_track(self, track_id, started=None): finished = datetime.datetime.now() if started and config.BT_TIMESHEET_ROUNDING and config.BT_ROUNDING_INCREMENT: delta", "list of ordered fields\"\"\" # Priority: # datetime - 0 # date -", "')') self.conn.commit() def __init__(self, db_name): # create DB self.init_db(db_name) self.create_db() def insert_test_task(self, project_id):", "a Project #2 self.create_project('p2', 'Test Project #1') self.cursor.execute(\"SELECT * FROM Projects ORDER BY", "sqlite3.Row self.conn.text_factory = lambda x: x.decode('utf8') #try: #except sqlite3.OperationalError: self.cursor = self.conn.cursor() def", "Tracks started = datetime.datetime.now() - timedelta(days=4) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3601)) self.create_track(last_task, started=started+timedelta(seconds=13600),", "\" \" {where_date_clause}\".format( where_date_clause=where_date_clause, where_project_clause=where_project_clause, where_task_clause=where_task_clause ), params ) return self.cursor.fetchone() def update_task(self,", "db_path, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES ) self.conn.row_factory = sqlite3.Row self.conn.text_factory = lambda x: x.decode('utf8') #try: #except", "= self.insert_test_task(project_id=2) self.create_track(last_task, started=started+timedelta(seconds=21600), finished=started+timedelta(seconds=22600)) self.create_track(last_task, started=started+timedelta(seconds=23600), finished=started+timedelta(seconds=24600)) self.create_track(last_task, started=started+timedelta(seconds=25600), finished=started+timedelta(seconds=26600)) started =", "BETWEEN ? \" \\ \" AND ? \" params.extend([started, finished]) self.cursor.execute( \"SELECT \"", "params.extend([started, finished]) self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as tname, \"", "of project including a field is a project is finished\"\"\" where_clause = first_limit_clause", "\" Tasks.project_id == Projects.id AND \" \" finished == '' \" \" {where_date_clause}\".format(", "[] only_billed_clause = where_project_clause = where_task_clause = '' if tname: params.append(tname.encode('utf8')) where_task_clause =", "\"\"\"Updates a project\"\"\" self.cursor.execute( \"UPDATE Projects \" \"SET name=?, description=?\" \"WHERE id=?\", (name.encode('utf8'),", "\"UPDATE Tracks \" \"SET started=?, finished=?, is_billed=? \" \"WHERE id=?\", (started, finished, is_billed,", "started=started, finished=started + timedelta(seconds=600)) last_track = self.create_track(last_task) self.cursor.execute(\"SELECT * FROM Tracks \") tracks", "group_by_clause=group_by_clause, only_billed_clause=only_billed_clause) ) #print(query) if group_by_mask: select_clause = self.get_timesheet_select_clause(group_by_mask) query = \"SELECT {clause}", "\" Tasks.id as tid, Tasks.name as tname, Projects.id as pid, \" \" Projects.name", "task/project\"\"\" params = [] only_billed_clause = where_project_clause = where_task_clause = '' if tname:", "\"insert into Customers ('name', 'description') \" \"VALUES ('Andrey', 'Customer Numer One')\") self.cursor.execute(\"SELECT *", "tablefmt='simple')) return # CUSTOMERS def get_customer(self, customer): self.cursor.execute( \"SELECT id, name FROM Customers", "id FROM Tasks WHERE \" \" Tasks.project_id == Projects.id \" \") {where_clause}\" \"ORDER", "Tasks.id \" \"ORDER BY Tasks.id DESC LIMIT {limit:d}\".format( limit=limit, activity_field=activity_field) ) tasks =", "Tracks.task_id \" \" ) ORDER BY tid {last_limit_clause}\" \"\".format( where_clause=where_clause, first_limit_clause=first_limit_clause, last_limit_clause=last_limit_clause) )", "INTO Tasks ('name', 'project_id') \" \"VALUES \" \" (?, ?)\", ( name.encode('utf8'), pid", "NOT EXISTS (\" \" SELECT id FROM Tasks WHERE \" \" Tasks.project_id ==", "\"WHERE \" \" Tasks.project_id == Projects.id AND \" \" Tracks.task_id == Tasks.id AND", "\" \" Tasks.description {activity_field}\" \"FROM Tasks, Projects, Tracks \" \"WHERE \" \" Tasks.project_id", "# TIMESHEET def get_group_by_clause(self, mask): \"\"\"Makes a GROUP BY clause by bit mask\"\"\"", "# CUSTOMERS def get_customer(self, customer): self.cursor.execute( \"SELECT id, name FROM Customers \" \"WHERE", "started=started, finished=started + timedelta(seconds=3600)) started = datetime.datetime.now() - timedelta(seconds=3300) self.create_track(last_task, started=started, finished=started +", "= \"tname == ? AND \" if pname: params.append(pname.encode('utf8')) where_project_clause = \"pname ==", "Customers \" \"WHERE name == '{name:s}'\".format(name=customer) ) customer = self.cursor.fetchone() if customer: return", "if tname: params.append(tname.encode('utf8')) where_task_clause = \"tname == ? AND \" if pname: params.append(pname.encode('utf8'))", "self.cursor.execute( \"{first_limit_clause}\" \"SELECT \" \" Projects.id as pid, Projects.name, Projects.created, \" \" Projects.description,", "created TIMESTAMP' ')') # TASKS self.cursor.execute( 'CREATE TABLE IF NOT EXISTS Tasks(' '", "== Tasks.id \" \"GROUP BY Tasks.id \" \"ORDER BY Tasks.id DESC LIMIT {limit:d}\".format(", "last_task = self.insert_test_task(project_id=1) self.create_track(last_task, started=started+timedelta(seconds=17600), finished=started+timedelta(seconds=18600)) self.create_track(last_task, started=started+timedelta(seconds=19600), finished=started+timedelta(seconds=20600)) # Add a Project", "group_by_mask: select_clause = self.get_timesheet_select_clause(group_by_mask) query = \"SELECT {clause} FROM ({query})\".format( query=query, clause=select_clause) self.cursor.execute(query,", "self.insert_test_task(project_id=1) # Add the Tracks started = datetime.datetime.now() - timedelta(days=4) self.create_track(last_task, started=started, finished=started", "CUSTOMERS def get_customer(self, customer): self.cursor.execute( \"SELECT id, name FROM Customers \" \"WHERE name", "\" \"FROM Tasks, Projects \" \"WHERE \" \" Tasks.project_id == pid AND \"", "init_db(self, db_path): self.conn = sqlite3.connect( db_path, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES ) self.conn.row_factory = sqlite3.Row self.conn.text_factory =", "datetime.datetime.now() - timedelta(days=3) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3600)) started = datetime.datetime.now() - timedelta(days=2)", "group_by = '{group_by} {value}'.format(group_by=group_by, value=value) return group_by group_by = set_group_by_clause(TS_GROUP_BY['date'], 'DATE(started)', '') group_by", "Tasks.description as description \" \"FROM Tasks, Projects \" \"WHERE \" \" tname ==", "== Projects.id AND \" \" Tracks.task_id == Tasks.id {where_clause}\" \"GROUP BY Projects.id \"", "& TS_GROUP_BY['project']: clause.add(project_field) if mask & TS_GROUP_BY['track']: clause.update([task_field, project_field, started_field, finished_field]) clause.add(spent_field) to_get", "finished=started+timedelta(seconds=24600)) self.create_track(last_task, started=started+timedelta(seconds=25600), finished=started+timedelta(seconds=26600)) started = datetime.datetime.now() - timedelta(days=3) self.create_track(last_task, started=started, finished=started +", "self.cursor.fetchone() if project: return project return self.create_project(name) def delete_project_by_name(self, pname): self.cursor.execute( \"DELETE FROM", "\" \" Tasks.id as tid, Tasks.name as tname, Projects.name as pname, \" \"", "\"\"\"Get an active task\"\"\" params = [] where_date_clause = where_project_clause = where_task_clause =", "self.cursor.lastrowid def get_task_or_create(self, name, project_id): \"\"\"Get a task or create one\"\"\" self.cursor.execute( \"SELECT", "and config.BT_ROUNDING_INCREMENT: delta = finished - started round_to = config.BT_ROUNDING_INCREMENT * 60 seconds", "% round_to finished = finished + datetime.timedelta(seconds=seconds) self.cursor.execute( \"UPDATE Tracks SET finished=? WHERE", "\" finished == '' \" \" {where_date_clause}\".format( where_date_clause=where_date_clause, where_project_clause=where_project_clause, where_task_clause=where_task_clause ), params )", "fields = self.get_timesheet_fields(mask) return ', '.join(fields) def get_minimal_started_track(self, tname='', pname=''): \"\"\"Get a minimal", "spent,\" \" Tracks.started as started, \" \" Tracks.finished as finished \" \"FROM Tracks,", "CASCADE, ' ' name VARCHAR COLLATE NOCASE, ' ' description TEXT DEFAULT \"\"'", "pname, created as created, \" \" description as description \" \"FROM Projects \"", "\" \" Tracks.task_id == Tasks.id AND \" \" Tasks.project_id == Projects.id AND \"", "INTO Tracks \" \" ('task_id', 'started', 'finished', 'is_billed') \" \"VALUES (?, ?, ?,", "the Tracks started = datetime.datetime.now() - timedelta(days=4) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3601)) self.create_track(last_task,", "finished: where_clause = str( \"WHERE DATE(Tracks.started) BETWEEN '{started}' AND '{finished}'\" \"\".format(started=started, finished=finished)) if", "as pname, Tasks.description as description \" \"FROM Tasks, Projects \" \"WHERE \" \"", "\" if only_billed: only_billed_clause = \" AND Tracks.is_billed == 1 \" params.extend([started, finished])", "BY Projects.id \" \"UNION SELECT \" \" Projects.id as pid, Projects.name, Projects.created,\" \"", "= '' params = [] if not also_unfinished: where_clause = \"AND NOT finished", "'CREATE TABLE IF NOT EXISTS Tasks(' ' id INTEGER PRIMARY KEY, ' '", "if pname: pname = pname.encode('utf8') where_project_clause = \"pname == ? AND \" params.append(pname)", "NOCASE, ' 'description TEXT, ' 'created TIMESTAMP' ')') self.conn.commit() def __init__(self, db_name): #", "NOCASE, ' ' description TEXT DEFAULT \"\"' ')') # TRACKS self.cursor.execute( 'CREATE TABLE", "AND DATE(Projects.created) BETWEEN '{from_date}' \" \\ \"AND '{to_date}' \".format(from_date=from_date, to_date=to_date) self.cursor.execute( \"{first_limit_clause}\" \"SELECT", "first_limit_clause = \"SELECT * FROM (\" last_limit_clause = \" DESC LIMIT %d) ORDER", "\"\"\"Get a minimal tracked date\"\"\" params = [] where_project_clause = where_task_clause = ''", "\" Tasks.id as tid, Tasks.name as tname, \" \" Projects.id as pid, Projects.name", "id INTEGER PRIMARY KEY, ' ' customer_id INTEGER, ' ' name VARCHAR UNIQUE", "LIMIT {limit:d}\".format( limit=limit, activity_field=activity_field) ) tasks = self.cursor.fetchall() return tasks def get_profiled_tasks(self, started='',", "# PROJECTS self.cursor.execute( 'CREATE TABLE IF NOT EXISTS Projects(' ' id INTEGER PRIMARY", "\" \" Tasks.project_id == pid\" \" {where_clause} \" \" {between_clause} \" \"ORDER BY", "Tasks ('name', 'project_id') \" \"values('%s', '%s')\" % (name, project_id) ) self.conn.commit() return self.cursor.lastrowid", "pid, Projects.name, Projects.created, \" \" Projects.description, \" \" SUM(CASE WHEN Tracks.finished == ''", "limit=limit, activity_field=activity_field) ) tasks = self.cursor.fetchall() return tasks def get_profiled_tasks(self, started='', finished='', limit=0):", "\" {where_task_clause}\" \" {where_project_clause}\" \" Tracks.task_id == tid AND \" \" Tasks.project_id ==", "\" Tasks.id as tid, Tasks.name as tname, Projects.name as pname, \" \" SUM(STRFTIME('%s',", "timedelta(seconds=3300) self.create_track(last_task, started=started, finished=started + timedelta(seconds=600)) last_track = self.create_track(last_task) self.cursor.execute(\"SELECT * FROM Tracks", "pname, \" \" SUM(STRFTIME('%s', finished)-STRFTIME('%s', started)) as spent,\" \" Tracks.started as started, \"", "?)\", ( pname.encode('utf8'), description.encode('utf8'), str(datetime.datetime.now()) ) ) self.conn.commit() return self.cursor.lastrowid def get_project_or_create(self, pname):", "WHEN Tracks.finished == '' THEN 1 ELSE 0 end) AS active \" \"FROM", "config TS_GROUP_BY = dict( timestamp=0b10000, project=0b1000, task=0b0100, track=0b0010, date=0b0001 ) class Database: def", "Tasks.description as description, \" \" Tracks.started as started, Tracks.finished as finished \" \"FROM", "where_task_clause = '' if tname: params.append(tname.encode('utf8')) where_task_clause = \"tname == ? AND \"", "Tracks.task_id == tid AND \" \" Tasks.project_id == Projects.id AND \" \" (\"", ".format(name=customer) ) self.conn.commit() # PROJECTS def get_project_by_name(self, pname): self.cursor.execute( \"SELECT \" \" id", "PRIMARY KEY, ' ' customer_id INTEGER, ' ' name VARCHAR UNIQUE COLLATE NOCASE,", "FROM Customers \" \"WHERE name == '{name:s}'\".format(name=customer) ) customer = self.cursor.fetchone() return customer", "tid AND \" \" Tasks.project_id == pid\" \" {where_clause} \" \" {between_clause} \"", "timedelta import operator from tabulate import tabulate import config TS_GROUP_BY = dict( timestamp=0b10000,", "self.conn.close() def create_db(self): self.cursor.execute(\"PRAGMA foreign_keys = ON\") # Create Tables if do the", "= '' if add_activity: activity_field = \", SUM(CASE WHEN Tracks.finished == '' THEN", "as tid, Tasks.name as tname, Projects.id as pid, \" \" Projects.name as pname,", "Tasks.project_id == Projects.id \" \") {where_clause}\" \"ORDER BY Projects.id {last_limit_clause}\".format( where_clause=where_clause, first_limit_clause=first_limit_clause, last_limit_clause=last_limit_clause)", "'Tasks.project_id', group_by) group_by = set_group_by_clause(TS_GROUP_BY['task'], 'Tracks.task_id', group_by) group_by = set_group_by_clause(TS_GROUP_BY['track'], 'Tracks.id', group_by) if", "tname.encode('utf8') where_task_clause = \"tname == ? AND \" params.append(tname) if pname: pname =", "as pname, \" \" SUM(STRFTIME('%s', finished)-STRFTIME('%s', started)) as spent,\" \" Tracks.started as started,", "\"WHERE id=?\", ( name.encode('utf8'), description.encode('utf8'), tid ) ) self.conn.commit() def delete_task(self, tid): \"\"\"\"\"\"", "project_id): name = ''.join(random.choice( string.ascii_uppercase + string.digits) for _ in range(3)) self.cursor.execute( \"insert", "DEFAULT \"\", ' ' created TIMESTAMP' ')') # TASKS self.cursor.execute( 'CREATE TABLE IF", "\" Tracks.task_id == Tasks.id \" \"GROUP BY Tasks.id \" \"ORDER BY Tasks.id DESC", "started, \" \" Tracks.finished as finished, \" \" Tasks.description as description \" \"FROM", "self.conn.text_factory = lambda x: x.decode('utf8') #try: #except sqlite3.OperationalError: self.cursor = self.conn.cursor() def close_db(self):", "random import string import time import datetime from datetime import timedelta import operator", "return self.cursor.lastrowid def get_project_or_create(self, pname): self.cursor.execute( \"SELECT id, name FROM Projects \" \"WHERE", "Projects.id as pid, \" \" Projects.name as pname, Tasks.description as description \" \"FROM", "\" id as pid, name as name, created as created, \" \" description", "track=0b0010, date=0b0001 ) class Database: def init_db(self, db_path): self.conn = sqlite3.connect( db_path, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES", "an active task\"\"\" params = [] where_date_clause = where_project_clause = where_task_clause = ''", "where_date_clause=where_date_clause, where_project_clause=where_project_clause, where_task_clause=where_task_clause ), params ) return self.cursor.fetchone() def update_task(self, tid, name, description=''):", "Tasks.project_id == Projects.id AND \" \" Tracks.task_id == Tasks.id \" \"GROUP BY Tasks.id", "'' between_clause = '' params = [] if not also_unfinished: where_clause = \"AND", "TS_GROUP_BY = dict( timestamp=0b10000, project=0b1000, task=0b0100, track=0b0010, date=0b0001 ) class Database: def init_db(self,", "pid\" \" {where_clause} \" \" {between_clause} \" \"ORDER BY Tracks.id\".format(started=started, finished=finished, where_clause=where_clause, between_clause=between_clause),", "Projects \" \"WHERE \" \" Tracks.task_id == tid AND \" \" Tasks.project_id ==", "\" \"SET name=?, description=?\" \"WHERE id=?\", ( name.encode('utf8'), description.encode('utf8'), tid ) ) self.conn.commit()", "\" \" Projects.name as pname, Tasks.description as description \" \"FROM Tasks, Projects \"", "def get_projects_with_activity_field(self, from_date='', to_date='', limit=0): \"\"\"Get list of project including a field is", "Tasks.name as tname, Projects.name as pname, \" \" DATE(started) as 'started [date]'\" \"FROM", "== '{name:s}'\".format(name=customer) ) customer = self.cursor.fetchone() if customer: return customer self.cursor.execute( \"INSERT INTO", "Task last_task = self.insert_test_task(project_id=1) # Add the Tracks started = datetime.datetime.now() - timedelta(days=4)", "project) # Add the Task tasks = [] last_task = self.insert_test_task(project_id=2) self.create_track(last_task, started=started+timedelta(seconds=21600),", "AND NOT Tracks.finished == ''\" \" {only_billed_clause}\" \" ) \" \"{group_by_clause} \" \"ORDER", "\"WHERE \" \" Tasks.project_id == Projects.id AND \" \" Tracks.task_id == Tasks.id \"", "''\") return self.cursor.fetchall() def get_active_task(self, started='', finished='', tname='', pname=''): \"\"\"Get an active task\"\"\"", "= sqlite3.Row self.conn.text_factory = lambda x: x.decode('utf8') #try: #except sqlite3.OperationalError: self.cursor = self.conn.cursor()", "TS_GROUP_BY['date']: clause.add(date_field) if mask & TS_GROUP_BY['task']: clause.update([task_field, project_field]) if mask & TS_GROUP_BY['project']: clause.add(project_field)", "get_project_or_create(self, pname): self.cursor.execute( \"SELECT id, name FROM Projects \" \"WHERE name == '{name:s}'\".format(name=pname.encode('utf8'))", "finished=started + timedelta(seconds=3601)) self.create_track(last_task, started=started+timedelta(seconds=13600), finished=started+timedelta(seconds=14600)) self.create_track(last_task, started=started+timedelta(seconds=15600), finished=started+timedelta(seconds=16600)) last_task = self.insert_test_task(project_id=1) self.create_track(last_task,", "the time was spend and is billed flag of the track record\"\"\" self.cursor.execute(", "finished]) self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as tname, \" \"", "'{finished}'\" \"\".format(started=started, finished=finished)) if limit: first_limit_clause = \"SELECT * FROM (\" last_limit_clause =", "\" Tasks.project_id == Projects.id \" \") {where_clause}\" \"ORDER BY Projects.id {last_limit_clause}\".format( where_clause=where_clause, first_limit_clause=first_limit_clause,", "name, project_id): \"\"\"Get a task or create one\"\"\" self.cursor.execute( \"SELECT \" \" Tasks.id", "\"\".format(where_task_clause=where_task_clause, where_project_clause=where_project_clause), params) return self.cursor.fetchone() def get_timesheet(self, started, finished, group_by_mask, only_billed=True, tname='', pname=''):", "(3, 'DATETIME(started) as \"started [timestamp]\"', 'From') finished_field = (4, 'DATETIME(finished) as \"finished [timestamp]\"',", "\" BETWEEN ? \" \\ \" AND ? \" params.extend([started, finished]) self.cursor.execute( \"SELECT", "\" Tasks.project_id == pid\" \" {where_clause} \" \" {between_clause} \" \"ORDER BY Tracks.id\".format(started=started,", "INTO Customers ('name')\" \"VALUES ('{name:s}')\" .format(name=customer) ) self.conn.commit() # PROJECTS def get_project_by_name(self, pname):", "= '' if started and finished: where_clause = str( \"WHERE DATE(Tracks.started) BETWEEN '{started}'", "mask): \"\"\"Makes a GROUP BY clause by bit mask\"\"\" def set_group_by_clause(bits, value, group_by):", "Tasks.id as tid, Tasks.name as tname, Projects.id as pid, \" \" Projects.name as", "datetime.datetime.now() self.cursor.execute( \"INSERT INTO Tracks \" \" ('task_id', 'started', 'finished', 'is_billed') \" \"VALUES", "Tasks.project_id == Projects.id AND \" \" Tracks.task_id == Tasks.id AND \" \" Tracks.id", "\" \" id as pid, name as name, created as created, \" \"", "AND \" \" trid == %d\" % tid ) return self.cursor.fetchone() def create_track(self,", "- 4 # date, tname, pname, started, finished, spent date_field = (0, 'DATE(started)", "== '{pid}'\" \" name == '{name}'\".format(name=pname.encode('utf8'), pid=pid) ) return self.cursor.fetchone() def get_projects_with_activity_field(self, from_date='',", "select_clause = self.get_timesheet_select_clause(group_by_mask) query = \"SELECT {clause} FROM ({query})\".format( query=query, clause=select_clause) self.cursor.execute(query, params)", "started=started, finished=started + timedelta(seconds=3600)) started = datetime.datetime.now() - timedelta(days=1) self.create_track(last_task, started=started, finished=started +", "== '' THEN 1 ELSE 0 end) AS active \" \"FROM Projects, Tracks,", "started = datetime.datetime.now() - timedelta(days=3) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3600)) started = datetime.datetime.now()", "NOT EXISTS Tracks(' ' id INTEGER PRIMARY KEY, ' ' task_id INTEGER REFERENCES", "track_id, Tracks.started as started, \" \" Tracks.finished as finished, \" \" Tasks.description as", "\"\"\"Create a project\"\"\" self.cursor.execute( \"INSERT INTO Projects ('name', 'description', created)\" \"VALUES (?, ?,", "\"GROUP BY Tasks.id \" \"ORDER BY Tasks.id DESC LIMIT {limit:d}\".format( limit=limit, activity_field=activity_field) )", "and finished: where_clause = str( \"WHERE DATE(Tracks.started) BETWEEN '{started}' AND '{finished}'\" \"\".format(started=started, finished=finished))", "#print(query) if group_by_mask: select_clause = self.get_timesheet_select_clause(group_by_mask) query = \"SELECT {clause} FROM ({query})\".format( query=query,", "' id INTEGER PRIMARY KEY, ' ' customer_id INTEGER, ' ' name VARCHAR", "from_date and to_date: where_clause = \" AND DATE(Projects.created) BETWEEN '{from_date}' \" \\ \"AND", "(finished, track_id) ) self.conn.commit() return finished def update_track(self, track_id, started, finished, is_billed): \"\"\"Updates", "\" SUM(CASE WHEN Tracks.finished == '' THEN 1 ELSE 0 end) AS active", "\" pid == '{project!s}'\" \"\".format(task=name.encode('utf8'), project=project_id) ) last = self.cursor.fetchone() if last: return", "id as pid, name as name, created as created, \" \" description as", "- timedelta(days=3) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3600)) started = datetime.datetime.now() - timedelta(days=2) self.create_track(last_task,", "Tasks.id AND \" \" Tasks.project_id == Projects.id AND \" \" finished == ''\")", "= self.cursor.fetchall() return tasks def get_profiled_tasks(self, started='', finished='', limit=0): \"\"\"The list of last", "is_project_existent(self, pname, pid): \"\"\"Checks if project already exists \"\"\" self.cursor.execute( \"SELECT \" \"", "get_tracks_by_date(self, started='', finished='', also_unfinished=False): \"\"\"Get tracks\"\"\" where_clause = '' between_clause = '' params", "DATE(started) BETWEEN ? AND ?\" params.extend([started, finished]) self.cursor.execute( \"SELECT \" \" Tasks.id as", "Tasks(' ' id INTEGER PRIMARY KEY, ' ' project_id INTEGER REFERENCES Projects(id) ON", "active \" \"FROM Projects, Tracks, Tasks \" \"WHERE \" \" Tasks.project_id == Projects.id", "self.cursor.fetchone() def update_task(self, tid, name, description=''): \"\"\"Updates the task info\"\"\" self.cursor.execute( \"UPDATE Tasks", "= self.cursor.fetchone() #print('filled customers', customers) # Add a Project self.create_project('p1', 'Test Project #1')", "get_tasks(self, limit=10, add_activity=False): \"\"\"Lists of last tasks\"\"\" activity_field = '' if add_activity: activity_field", "name, pid): self.cursor.execute( \"INSERT INTO Tasks ('name', 'project_id') \" \"VALUES \" \" (?,", "= self.insert_test_task(project_id=1) self.create_track(last_task, started=started+timedelta(seconds=17600), finished=started+timedelta(seconds=18600)) self.create_track(last_task, started=started+timedelta(seconds=19600), finished=started+timedelta(seconds=20600)) # Add a Project #2", "# task - 2 # project - 3 # spent - 4 #", "\"WHERE \" \" pid == '{pid}'\" \" name == '{name}'\".format(name=pname.encode('utf8'), pid=pid) ) return", "\" params.append(tname) if pname: pname = pname.encode('utf8') where_project_clause = \"pname == ? AND", "Tasks.name as tname, Projects.id as pid, \" \" Projects.name as pname, Tasks.description as", "active \" \"FROM Projects \" \"WHERE NOT EXISTS (\" \" SELECT id FROM", "if tname: tname = tname.encode('utf8') where_task_clause = \"tname == ? AND \" params.append(tname)", "def get_tracks_by_date(self, started='', finished='', also_unfinished=False): \"\"\"Get tracks\"\"\" where_clause = '' between_clause = ''", "def insert_test_task(self, project_id): name = ''.join(random.choice( string.ascii_uppercase + string.digits) for _ in range(3))", "BY started, Tasks.id\" \"\".format(started=started, finished=finished, where_task_clause=where_task_clause, where_project_clause=where_project_clause, group_by_clause=group_by_clause, only_billed_clause=only_billed_clause) ) #print(query) if group_by_mask:", "= datetime.datetime.now() - timedelta(days=3) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3600)) started = datetime.datetime.now() -", "a field is a project is finished\"\"\" where_clause = first_limit_clause = last_limit_clause =", "\"SELECT id, name FROM Projects \" \"WHERE name == '{name:s}'\".format(name=pname.encode('utf8')) ) project =", "#try: #except sqlite3.OperationalError: self.cursor = self.conn.cursor() def close_db(self): self.conn.close() def create_db(self): self.cursor.execute(\"PRAGMA foreign_keys", "def get_project_by_name(self, pname): self.cursor.execute( \"SELECT \" \" id as pid, name as pname,", "\" Tracks.id as trid, Tracks.started as started, \" \" Tracks.finished as finished, \"", "Projects \" \"WHERE \" \" {where_task_clause}\" \" {where_project_clause}\" \" Tracks.task_id == Tasks.id AND", "AND ? \" params.extend([started, finished]) self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name", "self.conn.cursor() def close_db(self): self.conn.close() def create_db(self): self.cursor.execute(\"PRAGMA foreign_keys = ON\") # Create Tables", "tid ) return self.cursor.fetchone() def create_track(self, task_id, started='', finished='', is_billed=True): # started, finished", "\" Tracks.task_id == Tasks.id AND \" \" Tracks.id IN (\" \" SELECT MAX(Tracks.id)", "description.encode('utf8'), tid ) ) self.conn.commit() def delete_task(self, tid): \"\"\"\"\"\" self.cursor.execute( \"DELETE FROM Tasks", "as \"date [date]\"', 'Date') task_field = (1, 'tname', 'Task') project_field = (2, 'pname',", "self.cursor.execute( 'CREATE TABLE IF NOT EXISTS Customers(' 'id INTEGER PRIMARY KEY, ' 'name", "Tracks \" \"SET started=?, finished=?, is_billed=? \" \"WHERE id=?\", (started, finished, is_billed, track_id)", "& TS_GROUP_BY['task']: clause.update([task_field, project_field]) if mask & TS_GROUP_BY['project']: clause.add(project_field) if mask & TS_GROUP_BY['track']:", "flag of the track record\"\"\" self.cursor.execute( \"UPDATE Tracks \" \"SET started=?, finished=?, is_billed=?", "return self.cursor.lastrowid def fill(self): \"\"\"Fill with the test tasks\"\"\" self.cursor.execute('DELETE FROM Customers') self.cursor.execute('DELETE", "a Project self.create_project('p1', 'Test Project #1') self.cursor.execute(\"SELECT * FROM Projects ORDER BY id", "== '' \" if started and finished: between_clause = \"AND DATE(started) BETWEEN ?", "description \" \"FROM Tasks, Projects \" \"WHERE \" \" tname == '{task}' AND", "Projects.id \" \"UNION SELECT \" \" Projects.id as pid, Projects.name, Projects.created,\" \" Projects.description,", "if from_date and to_date: where_clause = \" AND DATE(Projects.created) BETWEEN '{from_date}' \" \\", "'' THEN 1 ELSE 0 end) AS active \" \"FROM Projects, Tracks, Tasks", "pid, name, description): \"\"\"Updates a project\"\"\" self.cursor.execute( \"UPDATE Projects \" \"SET name=?, description=?\"", "where_project_clause = \"pname == ? AND \" params.append(pname) self.cursor.execute( \"SELECT \" \" Tasks.id", "Projects.id AND \" \" finished == '' \" \" {where_date_clause}\".format( where_date_clause=where_date_clause, where_project_clause=where_project_clause, where_task_clause=where_task_clause", "where_task_clause = \"tname == ? AND \" if pname: params.append(pname.encode('utf8')) where_project_clause = \"pname", "name, created as created, \" \" description as description \" \"FROM Projects \"", "import string import time import datetime from datetime import timedelta import operator from", "the Task tasks = [] last_task = self.insert_test_task(project_id=2) self.create_track(last_task, started=started+timedelta(seconds=21600), finished=started+timedelta(seconds=22600)) self.create_track(last_task, started=started+timedelta(seconds=23600),", "tracks) print(tabulate(tracks, ['Track id', 'Task id', 'started', 'finished', 'billed'], tablefmt='simple')) return # CUSTOMERS", "DATE(Tracks.started) \" \\ \" BETWEEN ? \" \\ \" AND ? \" params.extend([started,", "{last_limit_clause}\" \"\".format( where_clause=where_clause, first_limit_clause=first_limit_clause, last_limit_clause=last_limit_clause) ) tasks = self.cursor.fetchall() return tasks def get_task_by_alias(self,", "Tasks.id DESC LIMIT {limit:d}\".format( limit=limit, activity_field=activity_field) ) tasks = self.cursor.fetchall() return tasks def", "as 'started [date]'\" \"FROM Tracks, Tasks, Projects \" \"WHERE \" \" {where_task_clause}\" \"", "AND ?\" \" AND NOT Tracks.finished == ''\" \" {only_billed_clause}\" \" ) \"", "TABLE IF NOT EXISTS Tracks(' ' id INTEGER PRIMARY KEY, ' ' task_id", "finished, spent date_field = (0, 'DATE(started) as \"date [date]\"', 'Date') task_field = (1,", "= \"AND DATE(Tracks.started) \" \\ \" BETWEEN ? \" \\ \" AND ?", "BY pid ASC\" % limit if from_date and to_date: where_clause = \" AND", "only_billed_clause = \" AND Tracks.is_billed == 1 \" params.extend([started, finished]) group_by_clause = self.get_group_by_clause(group_by_mask)", "round_to - delta.seconds % round_to finished = finished + datetime.timedelta(seconds=seconds) self.cursor.execute( \"UPDATE Tracks", "\" \") {where_clause}\" \"ORDER BY Projects.id {last_limit_clause}\".format( where_clause=where_clause, first_limit_clause=first_limit_clause, last_limit_clause=last_limit_clause) ) return self.cursor.fetchall()", "NOCASE, ' ' description TEXT DEFAULT \"\", ' ' created TIMESTAMP' ')') #", "Projects.id AND \" \" Tracks.task_id == Tasks.id AND \" \" Tracks.id IN (\"", "as tname, Projects.name as pname, \" \" DATE(started) as 'started [date]'\" \"FROM Tracks,", "\"WHERE \" \" Projects.name == ?\", (pname.encode('utf8'),) ) return self.cursor.fetchone() def update_project(self, pid,", "self.cursor.execute( \"insert into Customers ('name', 'description') \" \"VALUES ('Andrey', 'Customer Numer One')\") self.cursor.execute(\"SELECT", "self.init_db(db_name) self.create_db() def insert_test_task(self, project_id): name = ''.join(random.choice( string.ascii_uppercase + string.digits) for _", "tasks between dates including unfinished\"\"\" where_clause = first_limit_clause = last_limit_clause = '' if", "id as pid, name as pname, created as created, \" \" description as", "Tasks.id, Tasks.name, Projects.id, Projects.name, \" \" Tasks.description {activity_field}\" \"FROM Tasks, Projects, Tracks \"", "\" pname == '{project:s}'\" \"\".format(task=tname.encode('utf8'), project=pname.encode('utf8')) ) return self.cursor.fetchone() def create_task(self, name, pid):", "= \"SELECT * FROM (\" last_limit_clause = \" DESC LIMIT %d) ORDER BY", "query = str( \"SELECT \" \" Tasks.id as tid, Tasks.name as tname, Projects.name", "= \"pname == ? AND \" params.append(pname) if started and finished: where_date_clause =", "\"INSERT INTO Projects ('name', 'description', created)\" \"VALUES (?, ?, ?)\", ( pname.encode('utf8'), description.encode('utf8'),", "name, description): \"\"\"Updates a project\"\"\" self.cursor.execute( \"UPDATE Projects \" \"SET name=?, description=?\" \"WHERE", "one\"\"\" self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as tname, Projects.id as", "\" \" Tasks.id as tid, Tasks.name as tname, \" \" Projects.id as pid,", "limit if from_date and to_date: where_clause = \" AND DATE(Projects.created) BETWEEN '{from_date}' \"", "\" ('task_id', 'started', 'finished', 'is_billed') \" \"VALUES (?, ?, ?, ?)\", (task_id, started,", "\" \"WHERE \" \" Tracks.task_id == tid AND \" \" Tasks.project_id == pid\"", "Tasks, Projects \" \"WHERE \" \" {where_task_clause}\" \" {where_project_clause}\" \" Tracks.task_id == Tasks.id", "' project_id INTEGER REFERENCES Projects(id) ON DELETE CASCADE, ' ' name VARCHAR COLLATE", "pname: pname = pname.encode('utf8') where_project_clause = \"pname == ? AND \" params.append(pname) if", "if project: return project return self.create_project(name) def delete_project_by_name(self, pname): self.cursor.execute( \"DELETE FROM Projects", "Projects \" \"WHERE \" \" tname == '{task}' AND \" \" Tasks.project_id ==", "\"\"\"Get tracks\"\"\" where_clause = '' between_clause = '' params = [] if not", "\" pid == '{pid}'\" \" name == '{name}'\".format(name=pname.encode('utf8'), pid=pid) ) return self.cursor.fetchone() def", "group_by = set_group_by_clause(TS_GROUP_BY['track'], 'Tracks.id', group_by) if group_by: group_by = \"GROUP BY %s \"", "%d) ORDER BY pid ASC\" % limit if from_date and to_date: where_clause =", "\" DATE(started) as 'started [date]'\" \"FROM Tracks, Tasks, Projects \" \"WHERE \" \"", "the not exist # PROJECTS self.cursor.execute( 'CREATE TABLE IF NOT EXISTS Projects(' '", "a minimal tracked date\"\"\" params = [] where_project_clause = where_task_clause = '' if", "name == '{name:s}'\".format(name=customer) ) customer = self.cursor.fetchone() return customer def get_customer_or_create(self, customer): self.cursor.execute(", "( name.encode('utf8'), pid ) ) self.conn.commit() return self.cursor.lastrowid def get_task_or_create(self, name, project_id): \"\"\"Get", ") ) self.conn.commit() return self.cursor.lastrowid def get_project_or_create(self, pname): self.cursor.execute( \"SELECT id, name FROM", "only_billed=True, tname='', pname=''): \"\"\" Gets the time was spent for a task/project\"\"\" params", "(1, 'tname', 'Task') project_field = (2, 'pname', 'Project') started_field = (3, 'DATETIME(started) as", "Projects.id as pid, Projects.name, Projects.created,\" \" Projects.description, '' as active \" \"FROM Projects", "\"WHERE \" \" Tracks.task_id == Tasks.id AND \" \" Tasks.project_id == Projects.id AND", "TIMESHEET def get_group_by_clause(self, mask): \"\"\"Makes a GROUP BY clause by bit mask\"\"\" def", "\" \"FROM Tracks, Tasks, Projects \" \"WHERE \" \" Tracks.task_id == Tasks.id AND", "BY Projects.id {last_limit_clause}\".format( where_clause=where_clause, first_limit_clause=first_limit_clause, last_limit_clause=last_limit_clause) ) return self.cursor.fetchall() def create_project(self, pname, description=''):", "return self.cursor.fetchone() def update_project(self, pid, name, description): \"\"\"Updates a project\"\"\" self.cursor.execute( \"UPDATE Projects", "started=started+timedelta(seconds=21600), finished=started+timedelta(seconds=22600)) self.create_track(last_task, started=started+timedelta(seconds=23600), finished=started+timedelta(seconds=24600)) self.create_track(last_task, started=started+timedelta(seconds=25600), finished=started+timedelta(seconds=26600)) started = datetime.datetime.now() - timedelta(days=3)", "\"WHERE name == '{name:s}'\".format(name=pname.encode('utf8')) ) project = self.cursor.fetchone() if project: return project return", "\" \" Tracks.task_id == tid AND \" \" Tasks.project_id == Projects.id AND \"", "into Tasks ('name', 'project_id') \" \"values('%s', '%s')\" % (name, project_id) ) self.conn.commit() return", "\" \" Tracks.id as trid, Tracks.started as started, \" \" Tracks.finished as finished,", "\"WHERE name == '{name:s}'\".format(name=customer) ) customer = self.cursor.fetchone() if customer: return customer self.cursor.execute(", "group_by): \"\"\"Add a field to group_by clause\"\"\" if mask & bits: if group_by:", "as finished \" \"FROM Tasks, Projects, Tracks \" \"WHERE \" \" Tasks.project_id ==", "TEXT DEFAULT \"\"' ')') # TRACKS self.cursor.execute( 'CREATE TABLE IF NOT EXISTS Tracks('", "SUM(STRFTIME('%s', finished)-STRFTIME('%s', started)) as spent,\" \" Tracks.started as started, \" \" Tracks.finished as", "\" \" Tasks.project_id == Projects.id \" \") {where_clause}\" \"ORDER BY Projects.id {last_limit_clause}\".format( where_clause=where_clause,", "% limit if from_date and to_date: where_clause = \" AND DATE(Projects.created) BETWEEN '{from_date}'", "\" \" GROUP BY Tracks.task_id \" \" ) ORDER BY tid {last_limit_clause}\" \"\".format(", "'' if tname: tname = tname.encode('utf8') where_task_clause = \"tname == ? AND \"", "\"%s,\" % group_by group_by = '{group_by} {value}'.format(group_by=group_by, value=value) return group_by group_by = set_group_by_clause(TS_GROUP_BY['date'],", "where_project_clause=where_project_clause, group_by_clause=group_by_clause, only_billed_clause=only_billed_clause) ) #print(query) if group_by_mask: select_clause = self.get_timesheet_select_clause(group_by_mask) query = \"SELECT", "\"\".format(name=pname.encode('utf8'))) self.conn.commit() # TASKS def get_tasks(self, limit=10, add_activity=False): \"\"\"Lists of last tasks\"\"\" activity_field", "close_db(self): self.conn.close() def create_db(self): self.cursor.execute(\"PRAGMA foreign_keys = ON\") # Create Tables if do", "project = self.cursor.fetchone() if project: return project return self.create_project(name) def delete_project_by_name(self, pname): self.cursor.execute(", "get_track_by_id(self, tid): self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as tname, Projects.name", "tid AND \" \" Tasks.project_id == Projects.id\" \"\".format(where_task_clause=where_task_clause, where_project_clause=where_project_clause), params) return self.cursor.fetchone() def", "= \"AND NOT finished == '' \" if started and finished: between_clause =", "pid, \" \" Projects.name as pname, Tasks.description as description, \" \" Tracks.started as", "Customer self.cursor.execute( \"insert into Customers ('name', 'description') \" \"VALUES ('Andrey', 'Customer Numer One')\")", "project_id): \"\"\"Get a task or create one\"\"\" self.cursor.execute( \"SELECT \" \" Tasks.id as", "\"values('%s', '%s')\" % (name, project_id) ) self.conn.commit() return self.cursor.lastrowid def fill(self): \"\"\"Fill with", "self.cursor.execute( \"INSERT INTO Customers ('name')\" \"VALUES ('{name:s}')\" .format(name=customer) ) self.conn.commit() # PROJECTS def", "\" Tasks.description {activity_field}\" \"FROM Tasks, Projects, Tracks \" \"WHERE \" \" Tasks.project_id ==", "string import time import datetime from datetime import timedelta import operator from tabulate", "= (0, 'DATE(started) as \"date [date]\"', 'Date') task_field = (1, 'tname', 'Task') project_field", "\" SELECT id FROM Tasks WHERE \" \" Tasks.project_id == Projects.id \" \")", "as pid, Projects.name, Projects.created,\" \" Projects.description, '' as active \" \"FROM Projects \"", "Customers(' 'id INTEGER PRIMARY KEY, ' 'name VARCHAR UNIQUE COLLATE NOCASE, ' 'description", "\"pname == ? AND \" params.append(pname) if started and finished: where_date_clause = \"AND", "range(3)) self.cursor.execute( \"insert into Tasks ('name', 'project_id') \" \"values('%s', '%s')\" % (name, project_id)", "{where_clause}\" \"\".format(where_clause=where_clause), (started, finished) ) self.conn.commit() # TIMESHEET def get_group_by_clause(self, mask): \"\"\"Makes a", "a Customer self.cursor.execute( \"insert into Customers ('name', 'description') \" \"VALUES ('Andrey', 'Customer Numer", "\".format(from_date=from_date, to_date=to_date) self.cursor.execute( \"{first_limit_clause}\" \"SELECT \" \" Projects.id as pid, Projects.name, Projects.created, \"", "?)\", ( name.encode('utf8'), pid ) ) self.conn.commit() return self.cursor.lastrowid def get_task_or_create(self, name, project_id):", "finished \" \"FROM Tasks, Projects, Tracks \" \"WHERE \" \" Tasks.project_id == Projects.id", "\"WHERE \" \" Tasks.project_id == pid AND \" \" tname == '{task:s}' AND", "ASC\" % limit if from_date and to_date: where_clause = \" AND DATE(Projects.created) BETWEEN", "ELSE 0 END) \" self.cursor.execute( \"SELECT \" \" Tasks.id, Tasks.name, Projects.id, Projects.name, \"", "'tname', 'Task') project_field = (2, 'pname', 'Project') started_field = (3, 'DATETIME(started) as \"started", "id LIMIT 1\") project = self.cursor.fetchone() #print('filled projects', project) # Add the Task", "AND \" \" Tracks.id IN (\" \" SELECT MAX(Tracks.id) FROM Tracks \" \"", "== Projects.id \" \") {where_clause}\" \"ORDER BY Projects.id {last_limit_clause}\".format( where_clause=where_clause, first_limit_clause=first_limit_clause, last_limit_clause=last_limit_clause) )", "get_headers else 1 return map(operator.itemgetter(to_get), sorted(clause, key=operator.itemgetter(0))) def get_timesheet_select_clause(self, mask): \"\"\"Get prepared select's", "\"\"\"Get a task or create one\"\"\" self.cursor.execute( \"SELECT \" \" Tasks.id as tid,", "' customer_id INTEGER, ' ' name VARCHAR UNIQUE COLLATE NOCASE, ' ' description", "? AND \" params.append(pname) if started and finished: where_date_clause = \"AND DATE(Tracks.started) \"", "'CREATE TABLE IF NOT EXISTS Customers(' 'id INTEGER PRIMARY KEY, ' 'name VARCHAR", "Projects(' ' id INTEGER PRIMARY KEY, ' ' customer_id INTEGER, ' ' name", "pname, Tasks.description as description \" \"FROM Tasks, Projects \" \"WHERE \" \" Tasks.project_id", ") return self.cursor.fetchone() def create_task(self, name, pid): self.cursor.execute( \"INSERT INTO Tasks ('name', 'project_id')", "Tasks.description as description \" \"FROM Tracks, Tasks, Projects \" \"WHERE \" \" {where_task_clause}\"", "')') # TASKS self.cursor.execute( 'CREATE TABLE IF NOT EXISTS Tasks(' ' id INTEGER", "Add the Task tasks = [] last_task = self.insert_test_task(project_id=2) self.create_track(last_task, started=started+timedelta(seconds=21600), finished=started+timedelta(seconds=22600)) self.create_track(last_task,", "self.insert_test_task(project_id=1) self.create_track(last_task, started=started+timedelta(seconds=17600), finished=started+timedelta(seconds=18600)) self.create_track(last_task, started=started+timedelta(seconds=19600), finished=started+timedelta(seconds=20600)) # Add a Project #2 self.create_project('p2',", "')') # CUSTOMERS self.cursor.execute( 'CREATE TABLE IF NOT EXISTS Customers(' 'id INTEGER PRIMARY", "self.cursor = self.conn.cursor() def close_db(self): self.conn.close() def create_db(self): self.cursor.execute(\"PRAGMA foreign_keys = ON\") #", "\" params.extend([started, finished]) self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as tname,", "\" \"WHERE \" \" {where_task_clause}\" \" {where_project_clause}\" \" Tracks.task_id == Tasks.id AND \"", ") project = self.cursor.fetchone() if project: return project return self.create_project(name) def delete_project_by_name(self, pname):", "def create_db(self): self.cursor.execute(\"PRAGMA foreign_keys = ON\") # Create Tables if do the not", "name\"\"\" self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as tname, Projects.id as", "= self.insert_test_task(project_id=1) # Add the Tracks started = datetime.datetime.now() - timedelta(days=4) self.create_track(last_task, started=started,", "Projects.created, \" \" Projects.description, \" \" SUM(CASE WHEN Tracks.finished == '' THEN 1", "INTEGER PRIMARY KEY, ' ' task_id INTEGER REFERENCES Tasks(id) ON DELETE CASCADE, '", "as description \" \"FROM Projects \" \"WHERE \" \" pid == '{pid}'\" \"", "of fields\"\"\" fields = self.get_timesheet_fields(mask) return ', '.join(fields) def get_minimal_started_track(self, tname='', pname=''): \"\"\"Get", "to_date='', limit=0): \"\"\"Get list of project including a field is a project is", "+ string.digits) for _ in range(3)) self.cursor.execute( \"insert into Tasks ('name', 'project_id') \"", "\"WHERE \" \" {where_task_clause}\" \" {where_project_clause}\" \" Tracks.task_id == Tasks.id AND \" \"", "& bits: if group_by: group_by = \"%s,\" % group_by group_by = '{group_by} {value}'.format(group_by=group_by,", "'' params = [] if not also_unfinished: where_clause = \"AND NOT finished ==", "'{name:s}'\".format(name=pname.encode('utf8')) ) project = self.cursor.fetchone() if project: return project return self.create_project(name) def delete_project_by_name(self,", "'name VARCHAR UNIQUE COLLATE NOCASE, ' 'description TEXT, ' 'created TIMESTAMP' ')') self.conn.commit()", "pname.encode('utf8') where_project_clause = \"pname == ? AND \" params.append(pname) self.cursor.execute( \"SELECT \" \"", "DATE(started) BETWEEN ? AND ?\" \" AND NOT Tracks.finished == ''\" \" {only_billed_clause}\"", "# Add a Customer self.cursor.execute( \"insert into Customers ('name', 'description') \" \"VALUES ('Andrey',", "as tid, Tasks.name as tname, Projects.name as pname, \" \" SUM(STRFTIME('%s', finished)-STRFTIME('%s', started))", "is_billed): \"\"\"Updates the time was spend and is billed flag of the track", "'' if started and finished: where_clause = str( \"WHERE DATE(Tracks.started) BETWEEN '{started}' AND", "(4, 'DATETIME(finished) as \"finished [timestamp]\"', 'To') spent_field = (5, 'spent', 'Time Spent') clause", "def init_db(self, db_path): self.conn = sqlite3.connect( db_path, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES ) self.conn.row_factory = sqlite3.Row self.conn.text_factory", "where_date_clause = where_project_clause = where_task_clause = '' if tname: tname = tname.encode('utf8') where_task_clause", "\" \"FROM Tracks, Tasks, Projects \" \"WHERE \" \" {where_task_clause}\" \" {where_project_clause}\" \"", "pname=''): \"\"\" Gets the time was spent for a task/project\"\"\" params = []", "for _ in range(3)) self.cursor.execute( \"insert into Tasks ('name', 'project_id') \" \"values('%s', '%s')\"", "Tasks.description {activity_field}\" \"FROM Tasks, Projects, Tracks \" \"WHERE \" \" Tasks.project_id == Projects.id", "last_limit_clause = \" DESC LIMIT %d) ORDER BY pid ASC\" % limit if", "pname): self.cursor.execute( \"SELECT id, name FROM Projects \" \"WHERE name == '{name:s}'\".format(name=pname.encode('utf8')) )", "clause.add(project_field) if mask & TS_GROUP_BY['track']: clause.update([task_field, project_field, started_field, finished_field]) clause.add(spent_field) to_get = 2", "params = [] where_date_clause = where_project_clause = where_task_clause = '' if tname: tname", "as tid, Tasks.name as tname, Projects.name as pname, \" \" Tracks.id as track_id,", "(\" \" SELECT id FROM Tasks WHERE \" \" Tasks.project_id == Projects.id \"", "as pid, \" \" Projects.name as pname, Tasks.description as description \" \"FROM Tasks,", "name FROM Customers \" \"WHERE name == '{name:s}'\".format(name=customer) ) customer = self.cursor.fetchone() return", "Customers ORDER BY id LIMIT 1\") customers = self.cursor.fetchone() #print('filled customers', customers) #", "config.BT_ROUNDING_INCREMENT * 60 seconds = round_to - delta.seconds % round_to finished = finished", "def finish_track(self, track_id, started=None): finished = datetime.datetime.now() if started and config.BT_TIMESHEET_ROUNDING and config.BT_ROUNDING_INCREMENT:", "'created TIMESTAMP' ')') self.conn.commit() def __init__(self, db_name): # create DB self.init_db(db_name) self.create_db() def", "fill(self): \"\"\"Fill with the test tasks\"\"\" self.cursor.execute('DELETE FROM Customers') self.cursor.execute('DELETE FROM Projects') self.cursor.execute('DELETE", "exist # PROJECTS self.cursor.execute( 'CREATE TABLE IF NOT EXISTS Projects(' ' id INTEGER", "2 # project - 3 # spent - 4 # date, tname, pname,", "\" \\ \"AND '{to_date}' \".format(from_date=from_date, to_date=to_date) self.cursor.execute( \"{first_limit_clause}\" \"SELECT \" \" Projects.id as", "pname, description=''): \"\"\"Create a project\"\"\" self.cursor.execute( \"INSERT INTO Projects ('name', 'description', created)\" \"VALUES", "tasks\"\"\" self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as tname, Projects.name as", "date\"\"\" if not also_unfinished: where_clause = \"AND NOT finished == '' \" self.cursor.execute(", "== Projects.id AND \" \" finished == ''\") return self.cursor.fetchall() def get_active_task(self, started='',", "AND \" \" pname == '{project:s}'\" \"\".format(task=tname.encode('utf8'), project=pname.encode('utf8')) ) return self.cursor.fetchone() def create_task(self,", "and to_date: where_clause = \" AND DATE(Projects.created) BETWEEN '{from_date}' \" \\ \"AND '{to_date}'", "= self.cursor.fetchone() #print('filled projects', project) # Add the Task last_task = self.insert_test_task(project_id=1) #", "group_by = set_group_by_clause(TS_GROUP_BY['task'], 'Tracks.task_id', group_by) group_by = set_group_by_clause(TS_GROUP_BY['track'], 'Tracks.id', group_by) if group_by: group_by", "params.append(pname) self.cursor.execute( \"SELECT \" \" Tasks.id as tid, Tasks.name as tname, Projects.name as", "PRIMARY KEY, ' 'name VARCHAR UNIQUE COLLATE NOCASE, ' 'description TEXT, ' 'created", "\"insert into Tasks ('name', 'project_id') \" \"values('%s', '%s')\" % (name, project_id) ) self.conn.commit()", "= self.cursor.fetchall() return tasks def get_task_by_alias(self, tname, pname): \"\"\"Get task by name\"\"\" self.cursor.execute(", "finished == '' \" if started and finished: between_clause = \"AND DATE(started) BETWEEN", "name FROM Projects \" \"WHERE name == '{name:s}'\".format(name=pname.encode('utf8')) ) project = self.cursor.fetchone() if", "NOT EXISTS Tasks(' ' id INTEGER PRIMARY KEY, ' ' project_id INTEGER REFERENCES", "FROM Tracks \" \"WHERE \" \" DATE(started) BETWEEN ? AND ?\" \" {where_clause}\"", "= set_group_by_clause(TS_GROUP_BY['track'], 'Tracks.id', group_by) if group_by: group_by = \"GROUP BY %s \" %", "- timedelta(days=2) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3600)) started = datetime.datetime.now() - timedelta(days=1) self.create_track(last_task,", "FROM Projects WHERE name == '{name}'\" \"\".format(name=pname.encode('utf8'))) self.conn.commit() # TASKS def get_tasks(self, limit=10,", "'To') spent_field = (5, 'spent', 'Time Spent') clause = set() if mask &", "Tasks.id AND \" \" Tasks.project_id == Projects.id AND \" \" finished == ''", "last: return last['tid'] return self.create_task(name, project_id) def _get_active_tasks(self): \"\"\"Get active tasks\"\"\" self.cursor.execute( \"SELECT", "\" AND DATE(Projects.created) BETWEEN '{from_date}' \" \\ \"AND '{to_date}' \".format(from_date=from_date, to_date=to_date) self.cursor.execute( \"{first_limit_clause}\"", "AND \" \" Tasks.project_id == Projects.id\" \"\".format(where_task_clause=where_task_clause, where_project_clause=where_project_clause), params) return self.cursor.fetchone() def get_timesheet(self,", "where_project_clause = where_task_clause = '' if tname: tname = tname.encode('utf8') where_task_clause = \"tname", "TIMESTAMP' ')') # TASKS self.cursor.execute( 'CREATE TABLE IF NOT EXISTS Tasks(' ' id", "Projects') self.cursor.execute('DELETE FROM Tasks') self.cursor.execute('DELETE FROM Tracks') # Add a Customer self.cursor.execute( \"insert", "\" \" Tracks.started as started, Tracks.finished as finished \" \"FROM Tasks, Projects, Tracks", "= 2 if get_headers else 1 return map(operator.itemgetter(to_get), sorted(clause, key=operator.itemgetter(0))) def get_timesheet_select_clause(self, mask):", "last_limit_clause = '' if started and finished: where_clause = str( \"WHERE DATE(Tracks.started) BETWEEN", "\"FROM Projects \" \"WHERE NOT EXISTS (\" \" SELECT id FROM Tasks WHERE", "return project return self.create_project(name) def delete_project_by_name(self, pname): self.cursor.execute( \"DELETE FROM Projects WHERE name", "\"\"\"Updates the task info\"\"\" self.cursor.execute( \"UPDATE Tasks \" \"SET name=?, description=?\" \"WHERE id=?\",", "\" DESC LIMIT %d) ORDER BY pid ASC\" % limit if from_date and", ") #print(query) if group_by_mask: select_clause = self.get_timesheet_select_clause(group_by_mask) query = \"SELECT {clause} FROM ({query})\".format(", "1 # task - 2 # project - 3 # spent - 4", "as started, \" \" Tracks.finished as finished, \" \" Tasks.description as description \"", "'Tracks.id', group_by) if group_by: group_by = \"GROUP BY %s \" % group_by return", "\" \" SUM(STRFTIME('%s', finished)-STRFTIME('%s', started)) as spent,\" \" Tracks.started as started, \" \"", "Projects WHERE name == '{name}'\" \"\".format(name=pname.encode('utf8'))) self.conn.commit() # TASKS def get_tasks(self, limit=10, add_activity=False):", "\"FROM Tasks, Projects \" \"WHERE \" \" tname == '{task}' AND \" \"", "description \" \"FROM Tracks, Tasks, Projects \" \"WHERE \" \" {where_task_clause}\" \" {where_project_clause}\"", "- delta.seconds % round_to finished = finished + datetime.timedelta(seconds=seconds) self.cursor.execute( \"UPDATE Tracks SET", "return ', '.join(fields) def get_minimal_started_track(self, tname='', pname=''): \"\"\"Get a minimal tracked date\"\"\" params", "timedelta(seconds=3600)) started = datetime.datetime.now() - timedelta(days=2) self.create_track(last_task, started=started, finished=started + timedelta(seconds=3600)) started =", "\" if started and finished: between_clause = \"AND DATE(started) BETWEEN ? AND ?\"", "\"\"\"\"\"\" self.cursor.execute( \"DELETE FROM Tasks WHERE id == '{tid}'\".format(tid=tid)) self.conn.commit() # TRACKS def", "= [] where_date_clause = where_project_clause = where_task_clause = '' if tname: tname =", "? \" \\ \" AND ? \" params.extend([started, finished]) self.cursor.execute( \"SELECT \" \"", "self.create_track(last_task, started=started, finished=started + timedelta(seconds=600)) last_track = self.create_track(last_task) self.cursor.execute(\"SELECT * FROM Tracks \")", "tasks = self.cursor.fetchall() return tasks def get_task_by_alias(self, tname, pname): \"\"\"Get task by name\"\"\"", "Tracks.is_billed as is_billed \" \"FROM Tracks, Tasks, Projects \" \"WHERE \" \" Tracks.task_id", "Projects.id, Projects.name, \" \" Tasks.description {activity_field}\" \"FROM Tasks, Projects, Tracks \" \"WHERE \"", "clause.add(date_field) if mask & TS_GROUP_BY['task']: clause.update([task_field, project_field]) if mask & TS_GROUP_BY['project']: clause.add(project_field) if", "self.cursor.execute( \"SELECT id, name FROM Projects \" \"WHERE name == '{name:s}'\".format(name=pname.encode('utf8')) ) project", "activity_field=activity_field) ) tasks = self.cursor.fetchall() return tasks def get_profiled_tasks(self, started='', finished='', limit=0): \"\"\"The", "\" AND NOT Tracks.finished == ''\" \" {only_billed_clause}\" \" ) \" \"{group_by_clause} \"", "\" {only_billed_clause}\" \" ) \" \"{group_by_clause} \" \"ORDER BY started, Tasks.id\" \"\".format(started=started, finished=finished,", "description.encode('utf8'), pid) ) self.conn.commit() def is_project_existent(self, pname, pid): \"\"\"Checks if project already exists", "active task\"\"\" params = [] where_date_clause = where_project_clause = where_task_clause = '' if", "\" {where_clause} \" \" {between_clause} \" \"ORDER BY Tracks.id\".format(started=started, finished=finished, where_clause=where_clause, between_clause=between_clause), params", "info\"\"\" self.cursor.execute( \"UPDATE Tasks \" \"SET name=?, description=?\" \"WHERE id=?\", ( name.encode('utf8'), description.encode('utf8'),", "self.cursor.execute( \"UPDATE Tracks SET finished=? WHERE id=?\", (finished, track_id) ) self.conn.commit() return finished", "date_field = (0, 'DATE(started) as \"date [date]\"', 'Date') task_field = (1, 'tname', 'Task')", "description, \" \" Tracks.started as started, Tracks.finished as finished \" \"FROM Tasks, Projects,", "def delete_task(self, tid): \"\"\"\"\"\" self.cursor.execute( \"DELETE FROM Tasks WHERE id == '{tid}'\".format(tid=tid)) self.conn.commit()", "Tracks.finished == '' THEN 1 ELSE 0 END) \" self.cursor.execute( \"SELECT \" \"", "started='', finished='', also_unfinished=False): \"\"\"Get tracks\"\"\" where_clause = '' between_clause = '' params =", "finished=started+timedelta(seconds=14600)) self.create_track(last_task, started=started+timedelta(seconds=15600), finished=started+timedelta(seconds=16600)) last_task = self.insert_test_task(project_id=1) self.create_track(last_task, started=started+timedelta(seconds=17600), finished=started+timedelta(seconds=18600)) self.create_track(last_task, started=started+timedelta(seconds=19600), finished=started+timedelta(seconds=20600))", "sqlite3.connect( db_path, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES ) self.conn.row_factory = sqlite3.Row self.conn.text_factory = lambda x: x.decode('utf8') #try:", "self.cursor.execute( 'CREATE TABLE IF NOT EXISTS Tracks(' ' id INTEGER PRIMARY KEY, '", "self.create_track(last_task, started=started+timedelta(seconds=21600), finished=started+timedelta(seconds=22600)) self.create_track(last_task, started=started+timedelta(seconds=23600), finished=started+timedelta(seconds=24600)) self.create_track(last_task, started=started+timedelta(seconds=25600), finished=started+timedelta(seconds=26600)) started = datetime.datetime.now() -", "project already exists \"\"\" self.cursor.execute( \"SELECT \" \" id as pid, name as", "tname, Projects.name as pname, \" \" Tracks.id as track_id, Tracks.started as started, \"", "bit mask\"\"\" def set_group_by_clause(bits, value, group_by): \"\"\"Add a field to group_by clause\"\"\" if", "as track_id, Tracks.started as started, \" \" Tracks.finished as finished, \" \" Tasks.description", "= self.create_track(last_task) self.cursor.execute(\"SELECT * FROM Tracks \") tracks = self.cursor.fetchall() #print('filled tracks', tracks)", "'' if tname: params.append(tname.encode('utf8')) where_task_clause = \"tname == ? AND \" if pname:" ]
[ "YourId('1') # need stringify in such a way that they do not colide", "but the characters in a word cannot be sorted prior to comparison if", "maximal domain # for assuming similarity, though in some documents every instance of", "operations are as simple as string= or numberical equality. These must employ a", "the world tend to frown upon shoving subjects through hash functions. \"\"\" import", "all identifiers mapped to idlib should have a string representation # or be", "There is a tradeoff between robustness of reference and usefulness for human communication.", "That is, identifiers are distinguished from other pieces of data in the sense", "of identifiers to correctly imply the equality of what they dereference to. There", "of best guess maximal domain # for assuming similarity, though in some documents", "worse the IRBs and IACUCs of the world tend to frown upon shoving", "with an allowance for conversion to a canonical form which may include reordering", "Base class for all Identifiers \"\"\" # all identifiers mapped to idlib should", "elements of the identifier that follow set equality rather than string equality for", "identifiers are distinguished from other pieces of data in the sense that the", "sorted prior to comparison if we are interested in the equality of two", "yourid:1 # within the expected context of their expansion # local:?:myid:1 local:?:yourid:1 could", "data in the sense that the family of functions that implement 'sameness' requires", "some documents every instance of a local:?:id # should probably be assumed to", "there is a question of the robustness of that identity function to a", "identity function to a change in context, specifically defined as the failures of", "a record of all local conventions # seems likely to be a giant", "pain, so local:?: ids would be ephemoral and would # probably have to", "similarity, though in some documents every instance of a local:?:id # should probably", "expansion # as a result of this, it is still not entirely clear", "or numberical equality. These must employ a true identity function that does not", "to be marked with a source as a kind of best guess maximal", "of local identifiers # with unknown local conventions, maintaining a record of all", "the ONLY requirement for an identifier is that it come equipped with an", "guess maximal domain # for assuming similarity, though in some documents every instance", "have a string representation # or be representable as strings in as unambiguous", "record of all local conventions # seems likely to be a giant pain,", "means that whole computer programs can be identifiers as long as the comparison", "to. There is a tradeoff between robustness of reference and usefulness for human", "NotImplementedError def data(self): raise NotImplementedError def asLocal(self, conventions=None): if conventions is None: conventions", "with local:?:1, local:?:2, local:?:3, local:?:4 _id_class = str local_regex = None # an", "*args, **kwargs): return super().__init__(*args, **kwargs) #def exists(self): # bad identifiers are not allowed", "on types e.g. MyId('1') and YourId('1') # need stringify in such a way", "of the world tend to frown upon shoving subjects through hash functions. \"\"\"", "since normalization can # occur before stringification, it is probably ok ... #", "possible # this means that distinctions based on types e.g. MyId('1') and YourId('1')", "this means that distinctions based on types e.g. MyId('1') and YourId('1') # need", "be ephemoral and would # probably have to be marked with a source", "comparison if we are interested in the equality of two ordered strings of", "that distinctions based on types e.g. MyId('1') and YourId('1') # need stringify in", "of this, it is still not entirely clear whether # str is quite", "as the failures of the equiality of identifiers to correctly imply the equality", "equality for example composite primary keys in a database may be rearranged into", "two ordered strings of chars. Note that under the defintion provided above the", "be different under expansion # as a result of this, it is still", "in such a way that they do not colide e.g. myid:1 yourid:1 #", "every byte of two streams with an allowance for conversion to a canonical", "property is that they come equipped with an equality operation. Not all equality", "byte of two streams with an allowance for conversion to a canonical form", "identifier that follow set equality rather than string equality for example composite primary", "the smallest possible unit of a stream. Their fundamental property is that they", "would be ephemoral and would # probably have to be marked with a", "# str is quite the right option, but since normalization can # occur", "# should probably be assumed to be different under expansion # as a", "functions. \"\"\" import idlib class Identifier(idlib.Stream): # TODO decide if str should be", "the equiality of identifiers to correctly imply the equality of what they dereference", "# a local identifier is used without conventions # same with local:?:1, local:?:2,", "of every byte of two streams with an allowance for conversion to a", "identifier def __new__(cls, *args, **kwargs): return super().__new__(cls, *args, **kwargs) def __init__(self, *args, **kwargs):", "the characters in a word cannot be sorted prior to comparison if we", "usefulness for human communication. And for better or for worse the IRBs and", "are distinguished from other pieces of data in the sense that the family", "cannot be sorted prior to comparison if we are interested in the equality", "function. This means that whole computer programs can be identifiers as long as", "such a way that they do not colide e.g. myid:1 yourid:1 # within", "be marked with a source as a kind of best guess maximal domain", "right option, but since normalization can # occur before stringification, it is probably", "# same with local:?:1, local:?:2, local:?:3, local:?:4 _id_class = str local_regex = None", "str local_regex = None # an unqualified, likely non-unique regex for the system", "assuming similarity, though in some documents every instance of a local:?:id # should", "of data that is compared. That is, identifiers are distinguished from other pieces", "include reordering and deduplication of elements of the identifier that follow set equality", "in the equality of two ordered strings of chars. Note that under the", "computer programs can be identifiers as long as the comparison function is defined.", "bad identifiers are not allowed to finish __init__ #raise NotImplementedError def metadata(self): raise", "local:?:id # should probably be assumed to be different under expansion # as", "are interested in the equality of two ordered strings of chars. Note that", "return super().__new__(cls, *args, **kwargs) def __init__(self, *args, **kwargs): return super().__init__(*args, **kwargs) #def exists(self):", "NotImplementedError def asLocal(self, conventions=None): if conventions is None: conventions = self._local_conventions return conventions.asLocal(self)", "that does not reduce the amount of data that is compared. That is,", "allowance for conversion to a canonical form which may include reordering and deduplication", "really '.+' #@staticmethod #def normalize(identifier): #raise NotImplementedError #return identifier def __new__(cls, *args, **kwargs):", "# local:?:myid:1 local:?:yourid:1 could represent the space of local identifiers # with unknown", "NotImplementedError #return identifier def __new__(cls, *args, **kwargs): return super().__new__(cls, *args, **kwargs) def __init__(self,", "where # a local identifier is used without conventions # same with local:?:1,", "# probably have to be marked with a source as a kind of", "is a question of the robustness of that identity function to a change", "e.g. hello:world -> local:?:hello:world in cases where # a local identifier is used", "unqualified, likely non-unique regex for the system local identifier canonical_regex = None #", "this, it is still not entirely clear whether # str is quite the", "is, identifiers are distinguished from other pieces of data in the sense that", "may be rearranged into a preferred order for further byte to byte comparison", "\"\"\" Base class for all Identifiers \"\"\" # all identifiers mapped to idlib", "a stream. Their fundamental property is that they come equipped with an equality", "# with unknown local conventions, maintaining a record of all local conventions #", "class for all Identifiers \"\"\" # all identifiers mapped to idlib should have", "that the family of functions that implement 'sameness' requires direct comparison of every", "requirement for an identifier is that it come equipped with an identity function.", "other pieces of data in the sense that the family of functions that", "expansion # local:?:myid:1 local:?:yourid:1 could represent the space of local identifiers # with", "same with local:?:1, local:?:2, local:?:3, local:?:4 _id_class = str local_regex = None #", "and usefulness for human communication. And for better or for worse the IRBs", "comparison of every byte of two streams with an allowance for conversion to", "are as simple as string= or numberical equality. These must employ a true", "streams with an allowance for conversion to a canonical form which may include", "chars. Note that under the defintion provided above the ONLY requirement for an", "regex for the system local identifier canonical_regex = None # but really '.+'", "expected context of their expansion # local:?:myid:1 local:?:yourid:1 could represent the space of", "with an equality operation. Not all equality operations are as simple as string=", "in as unambiguous a way as possible # this means that distinctions based", "source as a kind of best guess maximal domain # for assuming similarity,", "metadata(self): raise NotImplementedError def data(self): raise NotImplementedError def asLocal(self, conventions=None): if conventions is", "#raise NotImplementedError def metadata(self): raise NotImplementedError def data(self): raise NotImplementedError def asLocal(self, conventions=None):", "what they dereference to. There is a tradeoff between robustness of reference and", "or for worse the IRBs and IACUCs of the world tend to frown", "idlib should have a string representation # or be representable as strings in", "mapped to idlib should have a string representation # or be representable as", "ok ... # e.g. hello:world -> local:?:hello:world in cases where # a local", "to comparison if we are interested in the equality of two ordered strings", "_id_class = str local_regex = None # an unqualified, likely non-unique regex for", "Then there is a question of the robustness of that identity function to", "# within the expected context of their expansion # local:?:myid:1 local:?:yourid:1 could represent", "be rearranged into a preferred order for further byte to byte comparison between", "dereference to. There is a tradeoff between robustness of reference and usefulness for", "is that they come equipped with an equality operation. Not all equality operations", "come equipped with an identity function. This means that whole computer programs can", "byte to byte comparison between rows, but the characters in a word cannot", "the identifier that follow set equality rather than string equality for example composite", "composite primary keys in a database may be rearranged into a preferred order", "come equipped with an equality operation. Not all equality operations are as simple", "local conventions # seems likely to be a giant pain, so local:?: ids", "in cases where # a local identifier is used without conventions # same", "... # e.g. hello:world -> local:?:hello:world in cases where # a local identifier", "a tradeoff between robustness of reference and usefulness for human communication. And for", "direct comparison of every byte of two streams with an allowance for conversion", "for example composite primary keys in a database may be rearranged into a", "hash functions. \"\"\" import idlib class Identifier(idlib.Stream): # TODO decide if str should", "for worse the IRBs and IACUCs of the world tend to frown upon", "super().__new__(cls, *args, **kwargs) def __init__(self, *args, **kwargs): return super().__init__(*args, **kwargs) #def exists(self): #", "to finish __init__ #raise NotImplementedError def metadata(self): raise NotImplementedError def data(self): raise NotImplementedError", "all local conventions # seems likely to be a giant pain, so local:?:", "local:?:2, local:?:3, local:?:4 _id_class = str local_regex = None # an unqualified, likely", "occur before stringification, it is probably ok ... # e.g. hello:world -> local:?:hello:world", "And for better or for worse the IRBs and IACUCs of the world", "unknown local conventions, maintaining a record of all local conventions # seems likely", "primary keys in a database may be rearranged into a preferred order for", "as strings in as unambiguous a way as possible # this means that", "characters in a word cannot be sorted prior to comparison if we are", "of elements of the identifier that follow set equality rather than string equality", "that whole computer programs can be identifiers as long as the comparison function", "upon shoving subjects through hash functions. \"\"\" import idlib class Identifier(idlib.Stream): # TODO", "# this means that distinctions based on types e.g. MyId('1') and YourId('1') #", "local conventions, maintaining a record of all local conventions # seems likely to", "Identifiers \"\"\" # all identifiers mapped to idlib should have a string representation", "with unknown local conventions, maintaining a record of all local conventions # seems", "does not reduce the amount of data that is compared. That is, identifiers", "__new__(cls, *args, **kwargs): return super().__new__(cls, *args, **kwargs) def __init__(self, *args, **kwargs): return super().__init__(*args,", "must employ a true identity function that does not reduce the amount of", "for better or for worse the IRBs and IACUCs of the world tend", "preferred order for further byte to byte comparison between rows, but the characters", "rather than string equality for example composite primary keys in a database may", "be a giant pain, so local:?: ids would be ephemoral and would #", "the defintion provided above the ONLY requirement for an identifier is that it", "between rows, but the characters in a word cannot be sorted prior to", "but since normalization can # occur before stringification, it is probably ok ...", "long as the comparison function is defined. Then there is a question of", "a string representation # or be representable as strings in as unambiguous a", "simple as string= or numberical equality. These must employ a true identity function", "exists(self): # bad identifiers are not allowed to finish __init__ #raise NotImplementedError def", "the system local identifier canonical_regex = None # but really '.+' #@staticmethod #def", "reference and usefulness for human communication. And for better or for worse the", "local:?:3, local:?:4 _id_class = str local_regex = None # an unqualified, likely non-unique", "are not allowed to finish __init__ #raise NotImplementedError def metadata(self): raise NotImplementedError def", "would # probably have to be marked with a source as a kind", "**kwargs) def __init__(self, *args, **kwargs): return super().__init__(*args, **kwargs) #def exists(self): # bad identifiers", "canonical form which may include reordering and deduplication of elements of the identifier", "the right option, but since normalization can # occur before stringification, it is", "better or for worse the IRBs and IACUCs of the world tend to", "# need stringify in such a way that they do not colide e.g.", "operation. Not all equality operations are as simple as string= or numberical equality.", "a result of this, it is still not entirely clear whether # str", "import idlib class Identifier(idlib.Stream): # TODO decide if str should be base ...", "string representation # or be representable as strings in as unambiguous a way", "system local identifier canonical_regex = None # but really '.+' #@staticmethod #def normalize(identifier):", "that is compared. That is, identifiers are distinguished from other pieces of data", "colide e.g. myid:1 yourid:1 # within the expected context of their expansion #", "for conversion to a canonical form which may include reordering and deduplication of", "they do not colide e.g. myid:1 yourid:1 # within the expected context of", "e.g. myid:1 yourid:1 # within the expected context of their expansion # local:?:myid:1", "# all identifiers mapped to idlib should have a string representation # or", "conversion to a canonical form which may include reordering and deduplication of elements", "to a canonical form which may include reordering and deduplication of elements of", "unambiguous a way as possible # this means that distinctions based on types", "a canonical form which may include reordering and deduplication of elements of the", "failures of the equiality of identifiers to correctly imply the equality of what", "to byte comparison between rows, but the characters in a word cannot be", "which may include reordering and deduplication of elements of the identifier that follow", "raise NotImplementedError def asLocal(self, conventions=None): if conventions is None: conventions = self._local_conventions return", "and would # probably have to be marked with a source as a", "None # but really '.+' #@staticmethod #def normalize(identifier): #raise NotImplementedError #return identifier def", "compared. That is, identifiers are distinguished from other pieces of data in the", "myid:1 yourid:1 # within the expected context of their expansion # local:?:myid:1 local:?:yourid:1", "marked with a source as a kind of best guess maximal domain #", "as simple as string= or numberical equality. These must employ a true identity", "the sense that the family of functions that implement 'sameness' requires direct comparison", "of what they dereference to. There is a tradeoff between robustness of reference", "programs can be identifiers as long as the comparison function is defined. Then", "local:?:yourid:1 could represent the space of local identifiers # with unknown local conventions,", "rows, but the characters in a word cannot be sorted prior to comparison", "for the system local identifier canonical_regex = None # but really '.+' #@staticmethod", "Note that under the defintion provided above the ONLY requirement for an identifier", "though in some documents every instance of a local:?:id # should probably be", "is that it come equipped with an identity function. This means that whole", "stringification, it is probably ok ... # e.g. hello:world -> local:?:hello:world in cases", "represent the space of local identifiers # with unknown local conventions, maintaining a", "interested in the equality of two ordered strings of chars. Note that under", "These must employ a true identity function that does not reduce the amount", "of chars. Note that under the defintion provided above the ONLY requirement for", "#def exists(self): # bad identifiers are not allowed to finish __init__ #raise NotImplementedError", "pieces of data in the sense that the family of functions that implement", "is a tradeoff between robustness of reference and usefulness for human communication. And", "set equality rather than string equality for example composite primary keys in a", "have to be marked with a source as a kind of best guess", "that identity function to a change in context, specifically defined as the failures", "could represent the space of local identifiers # with unknown local conventions, maintaining", "is defined. Then there is a question of the robustness of that identity", "not colide e.g. myid:1 yourid:1 # within the expected context of their expansion", "a local identifier is used without conventions # same with local:?:1, local:?:2, local:?:3,", "kind of best guess maximal domain # for assuming similarity, though in some", "is still not entirely clear whether # str is quite the right option,", "the expected context of their expansion # local:?:myid:1 local:?:yourid:1 could represent the space", "an identifier is that it come equipped with an identity function. This means", "amount of data that is compared. That is, identifiers are distinguished from other", "an unqualified, likely non-unique regex for the system local identifier canonical_regex = None", "stringify in such a way that they do not colide e.g. myid:1 yourid:1", "it is still not entirely clear whether # str is quite the right", "can # occur before stringification, it is probably ok ... # e.g. hello:world", "conventions # same with local:?:1, local:?:2, local:?:3, local:?:4 _id_class = str local_regex =", "#@staticmethod #def normalize(identifier): #raise NotImplementedError #return identifier def __new__(cls, *args, **kwargs): return super().__new__(cls,", "#raise NotImplementedError #return identifier def __new__(cls, *args, **kwargs): return super().__new__(cls, *args, **kwargs) def", "an identity function. This means that whole computer programs can be identifiers as", "identifiers are not allowed to finish __init__ #raise NotImplementedError def metadata(self): raise NotImplementedError", "quite the right option, but since normalization can # occur before stringification, it", "likely non-unique regex for the system local identifier canonical_regex = None # but", "true identity function that does not reduce the amount of data that is", "human communication. And for better or for worse the IRBs and IACUCs of", "\"\"\" # all identifiers mapped to idlib should have a string representation #", "the equality of what they dereference to. There is a tradeoff between robustness", "e.g. MyId('1') and YourId('1') # need stringify in such a way that they", "are the smallest possible unit of a stream. Their fundamental property is that", "# but really '.+' #@staticmethod #def normalize(identifier): #raise NotImplementedError #return identifier def __new__(cls,", "than string equality for example composite primary keys in a database may be", "do not colide e.g. myid:1 yourid:1 # within the expected context of their", "to frown upon shoving subjects through hash functions. \"\"\" import idlib class Identifier(idlib.Stream):", "*args, **kwargs): return super().__new__(cls, *args, **kwargs) def __init__(self, *args, **kwargs): return super().__init__(*args, **kwargs)", "allowed to finish __init__ #raise NotImplementedError def metadata(self): raise NotImplementedError def data(self): raise", "of functions that implement 'sameness' requires direct comparison of every byte of two", "equality of two ordered strings of chars. Note that under the defintion provided", "local:?:myid:1 local:?:yourid:1 could represent the space of local identifiers # with unknown local", "ids would be ephemoral and would # probably have to be marked with", "of data in the sense that the family of functions that implement 'sameness'", "normalize(identifier): #raise NotImplementedError #return identifier def __new__(cls, *args, **kwargs): return super().__new__(cls, *args, **kwargs)", "for further byte to byte comparison between rows, but the characters in a", "conventions, maintaining a record of all local conventions # seems likely to be", "*args, **kwargs) def __init__(self, *args, **kwargs): return super().__init__(*args, **kwargs) #def exists(self): # bad", "example composite primary keys in a database may be rearranged into a preferred", "class Identifier(idlib.Stream): # TODO decide if str should be base ... \"\"\" Base", "to be a giant pain, so local:?: ids would be ephemoral and would", "for assuming similarity, though in some documents every instance of a local:?:id #", "equipped with an identity function. This means that whole computer programs can be", "is probably ok ... # e.g. hello:world -> local:?:hello:world in cases where #", "not reduce the amount of data that is compared. That is, identifiers are", "without conventions # same with local:?:1, local:?:2, local:?:3, local:?:4 _id_class = str local_regex", "be sorted prior to comparison if we are interested in the equality of", "Their fundamental property is that they come equipped with an equality operation. Not", "into a preferred order for further byte to byte comparison between rows, but", "two streams with an allowance for conversion to a canonical form which may", "with an identity function. This means that whole computer programs can be identifiers", "ONLY requirement for an identifier is that it come equipped with an identity", "question of the robustness of that identity function to a change in context,", "local_regex = None # an unqualified, likely non-unique regex for the system local", "a change in context, specifically defined as the failures of the equiality of", "comparison between rows, but the characters in a word cannot be sorted prior", "representation # or be representable as strings in as unambiguous a way as", "hello:world -> local:?:hello:world in cases where # a local identifier is used without", "all Identifiers \"\"\" # all identifiers mapped to idlib should have a string", "function is defined. Then there is a question of the robustness of that", "# or be representable as strings in as unambiguous a way as possible", "raise NotImplementedError def data(self): raise NotImplementedError def asLocal(self, conventions=None): if conventions is None:", "byte comparison between rows, but the characters in a word cannot be sorted", "# for assuming similarity, though in some documents every instance of a local:?:id", "return super().__init__(*args, **kwargs) #def exists(self): # bad identifiers are not allowed to finish", "assumed to be different under expansion # as a result of this, it", "defintion provided above the ONLY requirement for an identifier is that it come", "This means that whole computer programs can be identifiers as long as the", "of the equiality of identifiers to correctly imply the equality of what they", "for all Identifiers \"\"\" # all identifiers mapped to idlib should have a", "identifiers mapped to idlib should have a string representation # or be representable", "different under expansion # as a result of this, it is still not", "reduce the amount of data that is compared. That is, identifiers are distinguished", "IACUCs of the world tend to frown upon shoving subjects through hash functions.", "under expansion # as a result of this, it is still not entirely", "def __init__(self, *args, **kwargs): return super().__init__(*args, **kwargs) #def exists(self): # bad identifiers are", "-> local:?:hello:world in cases where # a local identifier is used without conventions", "types e.g. MyId('1') and YourId('1') # need stringify in such a way that", "as the comparison function is defined. Then there is a question of the", "# bad identifiers are not allowed to finish __init__ #raise NotImplementedError def metadata(self):", "should have a string representation # or be representable as strings in as", "the failures of the equiality of identifiers to correctly imply the equality of", "requires direct comparison of every byte of two streams with an allowance for", "an equality operation. Not all equality operations are as simple as string= or", "the amount of data that is compared. That is, identifiers are distinguished from", "identifiers to correctly imply the equality of what they dereference to. There is", "within the expected context of their expansion # local:?:myid:1 local:?:yourid:1 could represent the", "giant pain, so local:?: ids would be ephemoral and would # probably have", "imply the equality of what they dereference to. There is a tradeoff between", "form which may include reordering and deduplication of elements of the identifier that", "# occur before stringification, it is probably ok ... # e.g. hello:world ->", "#return identifier def __new__(cls, *args, **kwargs): return super().__new__(cls, *args, **kwargs) def __init__(self, *args,", "equality rather than string equality for example composite primary keys in a database", "canonical_regex = None # but really '.+' #@staticmethod #def normalize(identifier): #raise NotImplementedError #return", "as long as the comparison function is defined. Then there is a question", "functions that implement 'sameness' requires direct comparison of every byte of two streams", "to correctly imply the equality of what they dereference to. There is a", "to be different under expansion # as a result of this, it is", "be representable as strings in as unambiguous a way as possible # this", "**kwargs): return super().__init__(*args, **kwargs) #def exists(self): # bad identifiers are not allowed to", "and deduplication of elements of the identifier that follow set equality rather than", "function that does not reduce the amount of data that is compared. That", "the space of local identifiers # with unknown local conventions, maintaining a record", "equality operation. Not all equality operations are as simple as string= or numberical", "should be base ... \"\"\" Base class for all Identifiers \"\"\" # all", "that under the defintion provided above the ONLY requirement for an identifier is", "likely to be a giant pain, so local:?: ids would be ephemoral and", "in the sense that the family of functions that implement 'sameness' requires direct", "identity function that does not reduce the amount of data that is compared.", "be assumed to be different under expansion # as a result of this,", "tend to frown upon shoving subjects through hash functions. \"\"\" import idlib class", "robustness of that identity function to a change in context, specifically defined as", "TODO decide if str should be base ... \"\"\" Base class for all", "local identifier is used without conventions # same with local:?:1, local:?:2, local:?:3, local:?:4", "that it come equipped with an identity function. This means that whole computer", "as a kind of best guess maximal domain # for assuming similarity, though", "None # an unqualified, likely non-unique regex for the system local identifier canonical_regex", "numberical equality. These must employ a true identity function that does not reduce", "way as possible # this means that distinctions based on types e.g. MyId('1')", "#def normalize(identifier): #raise NotImplementedError #return identifier def __new__(cls, *args, **kwargs): return super().__new__(cls, *args,", "space of local identifiers # with unknown local conventions, maintaining a record of", "'sameness' requires direct comparison of every byte of two streams with an allowance", "in a database may be rearranged into a preferred order for further byte", "to idlib should have a string representation # or be representable as strings", "identifiers # with unknown local conventions, maintaining a record of all local conventions", "a question of the robustness of that identity function to a change in", "local:?:4 _id_class = str local_regex = None # an unqualified, likely non-unique regex", "equality of what they dereference to. There is a tradeoff between robustness of", "super().__init__(*args, **kwargs) #def exists(self): # bad identifiers are not allowed to finish __init__", "of their expansion # local:?:myid:1 local:?:yourid:1 could represent the space of local identifiers", "instance of a local:?:id # should probably be assumed to be different under", "context, specifically defined as the failures of the equiality of identifiers to correctly", "they come equipped with an equality operation. Not all equality operations are as", "'.+' #@staticmethod #def normalize(identifier): #raise NotImplementedError #return identifier def __new__(cls, *args, **kwargs): return", "may include reordering and deduplication of elements of the identifier that follow set", "clear whether # str is quite the right option, but since normalization can", "is compared. That is, identifiers are distinguished from other pieces of data in", "we are interested in the equality of two ordered strings of chars. Note", "... \"\"\" Base class for all Identifiers \"\"\" # all identifiers mapped to", "conventions # seems likely to be a giant pain, so local:?: ids would", "str should be base ... \"\"\" Base class for all Identifiers \"\"\" #", "\"\"\" import idlib class Identifier(idlib.Stream): # TODO decide if str should be base", "local identifiers # with unknown local conventions, maintaining a record of all local", "and IACUCs of the world tend to frown upon shoving subjects through hash", "= None # but really '.+' #@staticmethod #def normalize(identifier): #raise NotImplementedError #return identifier", "implement 'sameness' requires direct comparison of every byte of two streams with an", "means that distinctions based on types e.g. MyId('1') and YourId('1') # need stringify", "probably be assumed to be different under expansion # as a result of", "defined. Then there is a question of the robustness of that identity function", "database may be rearranged into a preferred order for further byte to byte", "the family of functions that implement 'sameness' requires direct comparison of every byte", "used without conventions # same with local:?:1, local:?:2, local:?:3, local:?:4 _id_class = str", "employ a true identity function that does not reduce the amount of data", "whether # str is quite the right option, but since normalization can #", "probably ok ... # e.g. hello:world -> local:?:hello:world in cases where # a", "base ... \"\"\" Base class for all Identifiers \"\"\" # all identifiers mapped", "smallest possible unit of a stream. Their fundamental property is that they come", "string equality for example composite primary keys in a database may be rearranged", "# as a result of this, it is still not entirely clear whether", "between robustness of reference and usefulness for human communication. And for better or", "defined as the failures of the equiality of identifiers to correctly imply the", "decide if str should be base ... \"\"\" Base class for all Identifiers", "not entirely clear whether # str is quite the right option, but since", "as possible # this means that distinctions based on types e.g. MyId('1') and", "the robustness of that identity function to a change in context, specifically defined", "**kwargs) #def exists(self): # bad identifiers are not allowed to finish __init__ #raise", "of the identifier that follow set equality rather than string equality for example", "probably have to be marked with a source as a kind of best", "above the ONLY requirement for an identifier is that it come equipped with", "equipped with an equality operation. Not all equality operations are as simple as", "def __new__(cls, *args, **kwargs): return super().__new__(cls, *args, **kwargs) def __init__(self, *args, **kwargs): return", "\"\"\"Identifiers are the smallest possible unit of a stream. Their fundamental property is", "if str should be base ... \"\"\" Base class for all Identifiers \"\"\"", "it come equipped with an identity function. This means that whole computer programs", "an allowance for conversion to a canonical form which may include reordering and", "or be representable as strings in as unambiguous a way as possible #", "that they do not colide e.g. myid:1 yourid:1 # within the expected context", "ephemoral and would # probably have to be marked with a source as", "documents every instance of a local:?:id # should probably be assumed to be", "distinctions based on types e.g. MyId('1') and YourId('1') # need stringify in such", "for an identifier is that it come equipped with an identity function. This", "representable as strings in as unambiguous a way as possible # this means", "communication. And for better or for worse the IRBs and IACUCs of the", "reordering and deduplication of elements of the identifier that follow set equality rather", "__init__(self, *args, **kwargs): return super().__init__(*args, **kwargs) #def exists(self): # bad identifiers are not", "follow set equality rather than string equality for example composite primary keys in", "based on types e.g. MyId('1') and YourId('1') # need stringify in such a", "be base ... \"\"\" Base class for all Identifiers \"\"\" # all identifiers", "identifiers as long as the comparison function is defined. Then there is a", "still not entirely clear whether # str is quite the right option, but", "a word cannot be sorted prior to comparison if we are interested in", "with a source as a kind of best guess maximal domain # for", "the equality of two ordered strings of chars. Note that under the defintion", "subjects through hash functions. \"\"\" import idlib class Identifier(idlib.Stream): # TODO decide if", "a giant pain, so local:?: ids would be ephemoral and would # probably", "data that is compared. That is, identifiers are distinguished from other pieces of", "local:?:hello:world in cases where # a local identifier is used without conventions #", "provided above the ONLY requirement for an identifier is that it come equipped", "the IRBs and IACUCs of the world tend to frown upon shoving subjects", "strings in as unambiguous a way as possible # this means that distinctions", "of reference and usefulness for human communication. And for better or for worse", "under the defintion provided above the ONLY requirement for an identifier is that", "family of functions that implement 'sameness' requires direct comparison of every byte of", "of a stream. Their fundamental property is that they come equipped with an", "distinguished from other pieces of data in the sense that the family of", "word cannot be sorted prior to comparison if we are interested in the", "__init__ #raise NotImplementedError def metadata(self): raise NotImplementedError def data(self): raise NotImplementedError def asLocal(self,", "all equality operations are as simple as string= or numberical equality. These must", "prior to comparison if we are interested in the equality of two ordered", "a kind of best guess maximal domain # for assuming similarity, though in", "rearranged into a preferred order for further byte to byte comparison between rows,", "local:?: ids would be ephemoral and would # probably have to be marked", "but really '.+' #@staticmethod #def normalize(identifier): #raise NotImplementedError #return identifier def __new__(cls, *args,", "to a change in context, specifically defined as the failures of the equiality", "tradeoff between robustness of reference and usefulness for human communication. And for better", "can be identifiers as long as the comparison function is defined. Then there", "entirely clear whether # str is quite the right option, but since normalization", "identifier canonical_regex = None # but really '.+' #@staticmethod #def normalize(identifier): #raise NotImplementedError", "NotImplementedError def metadata(self): raise NotImplementedError def data(self): raise NotImplementedError def asLocal(self, conventions=None): if", "the comparison function is defined. Then there is a question of the robustness", "def metadata(self): raise NotImplementedError def data(self): raise NotImplementedError def asLocal(self, conventions=None): if conventions", "Identifier(idlib.Stream): # TODO decide if str should be base ... \"\"\" Base class", "that follow set equality rather than string equality for example composite primary keys", "in some documents every instance of a local:?:id # should probably be assumed", "a source as a kind of best guess maximal domain # for assuming", "their expansion # local:?:myid:1 local:?:yourid:1 could represent the space of local identifiers #", "local:?:1, local:?:2, local:?:3, local:?:4 _id_class = str local_regex = None # an unqualified,", "= str local_regex = None # an unqualified, likely non-unique regex for the", "change in context, specifically defined as the failures of the equiality of identifiers", "# an unqualified, likely non-unique regex for the system local identifier canonical_regex =", "of all local conventions # seems likely to be a giant pain, so", "they dereference to. There is a tradeoff between robustness of reference and usefulness", "context of their expansion # local:?:myid:1 local:?:yourid:1 could represent the space of local", "equiality of identifiers to correctly imply the equality of what they dereference to.", "for human communication. And for better or for worse the IRBs and IACUCs", "Not all equality operations are as simple as string= or numberical equality. These", "is quite the right option, but since normalization can # occur before stringification,", "order for further byte to byte comparison between rows, but the characters in", "result of this, it is still not entirely clear whether # str is", "seems likely to be a giant pain, so local:?: ids would be ephemoral", "if we are interested in the equality of two ordered strings of chars.", "further byte to byte comparison between rows, but the characters in a word", "identity function. This means that whole computer programs can be identifiers as long", "a way that they do not colide e.g. myid:1 yourid:1 # within the", "str is quite the right option, but since normalization can # occur before", "domain # for assuming similarity, though in some documents every instance of a", "strings of chars. Note that under the defintion provided above the ONLY requirement", "equality operations are as simple as string= or numberical equality. These must employ", "a way as possible # this means that distinctions based on types e.g.", "data(self): raise NotImplementedError def asLocal(self, conventions=None): if conventions is None: conventions = self._local_conventions", "that implement 'sameness' requires direct comparison of every byte of two streams with", "normalization can # occur before stringification, it is probably ok ... # e.g.", "from other pieces of data in the sense that the family of functions", "as unambiguous a way as possible # this means that distinctions based on", "way that they do not colide e.g. myid:1 yourid:1 # within the expected", "of that identity function to a change in context, specifically defined as the", "not allowed to finish __init__ #raise NotImplementedError def metadata(self): raise NotImplementedError def data(self):", "frown upon shoving subjects through hash functions. \"\"\" import idlib class Identifier(idlib.Stream): #", "finish __init__ #raise NotImplementedError def metadata(self): raise NotImplementedError def data(self): raise NotImplementedError def", "should probably be assumed to be different under expansion # as a result", "MyId('1') and YourId('1') # need stringify in such a way that they do", "non-unique regex for the system local identifier canonical_regex = None # but really", "need stringify in such a way that they do not colide e.g. myid:1", "correctly imply the equality of what they dereference to. There is a tradeoff", "# TODO decide if str should be base ... \"\"\" Base class for", "deduplication of elements of the identifier that follow set equality rather than string", "ordered strings of chars. Note that under the defintion provided above the ONLY", "# seems likely to be a giant pain, so local:?: ids would be", "before stringification, it is probably ok ... # e.g. hello:world -> local:?:hello:world in", "def data(self): raise NotImplementedError def asLocal(self, conventions=None): if conventions is None: conventions =", "identifier is used without conventions # same with local:?:1, local:?:2, local:?:3, local:?:4 _id_class", "stream. Their fundamental property is that they come equipped with an equality operation.", "so local:?: ids would be ephemoral and would # probably have to be", "a local:?:id # should probably be assumed to be different under expansion #", "= None # an unqualified, likely non-unique regex for the system local identifier", "as a result of this, it is still not entirely clear whether #", "a preferred order for further byte to byte comparison between rows, but the", "IRBs and IACUCs of the world tend to frown upon shoving subjects through", "every instance of a local:?:id # should probably be assumed to be different", "comparison function is defined. Then there is a question of the robustness of", "of two ordered strings of chars. Note that under the defintion provided above", "through hash functions. \"\"\" import idlib class Identifier(idlib.Stream): # TODO decide if str", "keys in a database may be rearranged into a preferred order for further", "whole computer programs can be identifiers as long as the comparison function is", "local identifier canonical_regex = None # but really '.+' #@staticmethod #def normalize(identifier): #raise", "identifier is that it come equipped with an identity function. This means that", "and YourId('1') # need stringify in such a way that they do not", "maintaining a record of all local conventions # seems likely to be a", "option, but since normalization can # occur before stringification, it is probably ok", "robustness of reference and usefulness for human communication. And for better or for", "in a word cannot be sorted prior to comparison if we are interested", "best guess maximal domain # for assuming similarity, though in some documents every", "is used without conventions # same with local:?:1, local:?:2, local:?:3, local:?:4 _id_class =", "shoving subjects through hash functions. \"\"\" import idlib class Identifier(idlib.Stream): # TODO decide", "unit of a stream. Their fundamental property is that they come equipped with", "of the robustness of that identity function to a change in context, specifically", "equality. These must employ a true identity function that does not reduce the", "of two streams with an allowance for conversion to a canonical form which", "world tend to frown upon shoving subjects through hash functions. \"\"\" import idlib", "# e.g. hello:world -> local:?:hello:world in cases where # a local identifier is", "as string= or numberical equality. These must employ a true identity function that", "in context, specifically defined as the failures of the equiality of identifiers to", "idlib class Identifier(idlib.Stream): # TODO decide if str should be base ... \"\"\"", "that they come equipped with an equality operation. Not all equality operations are", "string= or numberical equality. These must employ a true identity function that does", "a true identity function that does not reduce the amount of data that", "a database may be rearranged into a preferred order for further byte to", "fundamental property is that they come equipped with an equality operation. Not all", "it is probably ok ... # e.g. hello:world -> local:?:hello:world in cases where", "of a local:?:id # should probably be assumed to be different under expansion", "specifically defined as the failures of the equiality of identifiers to correctly imply", "sense that the family of functions that implement 'sameness' requires direct comparison of", "**kwargs): return super().__new__(cls, *args, **kwargs) def __init__(self, *args, **kwargs): return super().__init__(*args, **kwargs) #def", "possible unit of a stream. Their fundamental property is that they come equipped", "be identifiers as long as the comparison function is defined. Then there is", "cases where # a local identifier is used without conventions # same with", "function to a change in context, specifically defined as the failures of the" ]
[ "try: project_dir = f\"{dump_dir}/dump_{project.name.replace('/', '_')}\" if not os.path.exists(project_dir): os.makedirs(project_dir) print(f\"Dumping {project.name}\") labels =", "SEQUENCE_LABELING from api.serializers import LabelSerializer from api.utils import JSONPainter def extract_document_classification(label, labels): return", "= LabelSerializer(labels, many=True) documents = project.documents.all() data = JSONPainter().paint(documents) data = map( lambda", "= map(lambda x: x + \"\\n\", data) with open(f\"{project_dir}/labels.json\", \"wb\") as f: f.write(JSONRenderer().render(label_serializer.data))", "json import os from rest_framework.renderers import JSONRenderer from api.models import Project, DOCUMENT_CLASSIFICATION, SEQUENCE_LABELING", "LabelSerializer(labels, many=True) documents = project.documents.all() data = JSONPainter().paint(documents) data = map( lambda x:", "= f\"{dump_dir}/dump_{project.name.replace('/', '_')}\" if not os.path.exists(project_dir): os.makedirs(project_dir) print(f\"Dumping {project.name}\") labels = project.labels.all() label_serializer", "import JSONPainter def extract_document_classification(label, labels): return labels.get(pk=label[\"label\"]).text def extract_label_seq_labeling(label, labels): return [ label[\"start_offset\"],", "rest_framework.renderers import JSONRenderer from api.models import Project, DOCUMENT_CLASSIFICATION, SEQUENCE_LABELING from api.serializers import LabelSerializer", "import JSONRenderer from api.models import Project, DOCUMENT_CLASSIFICATION, SEQUENCE_LABELING from api.serializers import LabelSerializer from", "project.documents.all() data = JSONPainter().paint(documents) data = map( lambda x: { **x, \"labels\": list(", "\"labels\": list( map( lambda y: get_extract_label(project)(y, labels), x[\"annotations\"], ) ), }, data, )", "os.makedirs(project_dir) print(f\"Dumping {project.name}\") labels = project.labels.all() label_serializer = LabelSerializer(labels, many=True) documents = project.documents.all()", "get_extract_label(project)(y, labels), x[\"annotations\"], ) ), }, data, ) data = map(json.dumps, data) data", "JSONRenderer from api.models import Project, DOCUMENT_CLASSIFICATION, SEQUENCE_LABELING from api.serializers import LabelSerializer from api.utils", "**x, \"labels\": list( map( lambda y: get_extract_label(project)(y, labels), x[\"annotations\"], ) ), }, data,", "def extract_label_seq_labeling(label, labels): return [ label[\"start_offset\"], label[\"end_offset\"], labels.get(pk=label[\"label\"]).text, ] def get_extract_label(project): return {", "\"projects_dump\" if not os.path.exists(dump_dir): os.makedirs(dump_dir) for project in Project.objects.all(): try: project_dir = f\"{dump_dir}/dump_{project.name.replace('/',", "Project, DOCUMENT_CLASSIFICATION, SEQUENCE_LABELING from api.serializers import LabelSerializer from api.utils import JSONPainter def extract_document_classification(label,", "= project.labels.all() label_serializer = LabelSerializer(labels, many=True) documents = project.documents.all() data = JSONPainter().paint(documents) data", "extract_document_classification, SEQUENCE_LABELING: extract_label_seq_labeling, }[project.project_type] def get_all_projects_json(): dump_dir = \"projects_dump\" if not os.path.exists(dump_dir): os.makedirs(dump_dir)", "in Project.objects.all(): try: project_dir = f\"{dump_dir}/dump_{project.name.replace('/', '_')}\" if not os.path.exists(project_dir): os.makedirs(project_dir) print(f\"Dumping {project.name}\")", "return labels.get(pk=label[\"label\"]).text def extract_label_seq_labeling(label, labels): return [ label[\"start_offset\"], label[\"end_offset\"], labels.get(pk=label[\"label\"]).text, ] def get_extract_label(project):", "map(json.dumps, data) data = map(lambda x: x + \"\\n\", data) with open(f\"{project_dir}/labels.json\", \"wb\")", "labels = project.labels.all() label_serializer = LabelSerializer(labels, many=True) documents = project.documents.all() data = JSONPainter().paint(documents)", "os.makedirs(dump_dir) for project in Project.objects.all(): try: project_dir = f\"{dump_dir}/dump_{project.name.replace('/', '_')}\" if not os.path.exists(project_dir):", "project_dir = f\"{dump_dir}/dump_{project.name.replace('/', '_')}\" if not os.path.exists(project_dir): os.makedirs(project_dir) print(f\"Dumping {project.name}\") labels = project.labels.all()", "import LabelSerializer from api.utils import JSONPainter def extract_document_classification(label, labels): return labels.get(pk=label[\"label\"]).text def extract_label_seq_labeling(label,", "= map(json.dumps, data) data = map(lambda x: x + \"\\n\", data) with open(f\"{project_dir}/labels.json\",", "{project.name}\") labels = project.labels.all() label_serializer = LabelSerializer(labels, many=True) documents = project.documents.all() data =", "x: { **x, \"labels\": list( map( lambda y: get_extract_label(project)(y, labels), x[\"annotations\"], ) ),", "label_serializer = LabelSerializer(labels, many=True) documents = project.documents.all() data = JSONPainter().paint(documents) data = map(", "extract_label_seq_labeling(label, labels): return [ label[\"start_offset\"], label[\"end_offset\"], labels.get(pk=label[\"label\"]).text, ] def get_extract_label(project): return { DOCUMENT_CLASSIFICATION:", "= project.documents.all() data = JSONPainter().paint(documents) data = map( lambda x: { **x, \"labels\":", "many=True) documents = project.documents.all() data = JSONPainter().paint(documents) data = map( lambda x: {", "data) with open(f\"{project_dir}/labels.json\", \"wb\") as f: f.write(JSONRenderer().render(label_serializer.data)) with open(f\"{project_dir}/data.jsonl\", \"w\") as f: f.writelines(data)", "label[\"end_offset\"], labels.get(pk=label[\"label\"]).text, ] def get_extract_label(project): return { DOCUMENT_CLASSIFICATION: extract_document_classification, SEQUENCE_LABELING: extract_label_seq_labeling, }[project.project_type] def", "dump_dir = \"projects_dump\" if not os.path.exists(dump_dir): os.makedirs(dump_dir) for project in Project.objects.all(): try: project_dir", "{ **x, \"labels\": list( map( lambda y: get_extract_label(project)(y, labels), x[\"annotations\"], ) ), },", "] def get_extract_label(project): return { DOCUMENT_CLASSIFICATION: extract_document_classification, SEQUENCE_LABELING: extract_label_seq_labeling, }[project.project_type] def get_all_projects_json(): dump_dir", "map( lambda y: get_extract_label(project)(y, labels), x[\"annotations\"], ) ), }, data, ) data =", "api.utils import JSONPainter def extract_document_classification(label, labels): return labels.get(pk=label[\"label\"]).text def extract_label_seq_labeling(label, labels): return [", "= JSONPainter().paint(documents) data = map( lambda x: { **x, \"labels\": list( map( lambda", "from api.models import Project, DOCUMENT_CLASSIFICATION, SEQUENCE_LABELING from api.serializers import LabelSerializer from api.utils import", "print(f\"Dumping {project.name}\") labels = project.labels.all() label_serializer = LabelSerializer(labels, many=True) documents = project.documents.all() data", "x: x + \"\\n\", data) with open(f\"{project_dir}/labels.json\", \"wb\") as f: f.write(JSONRenderer().render(label_serializer.data)) with open(f\"{project_dir}/data.jsonl\",", "data = map( lambda x: { **x, \"labels\": list( map( lambda y: get_extract_label(project)(y,", "\"wb\") as f: f.write(JSONRenderer().render(label_serializer.data)) with open(f\"{project_dir}/data.jsonl\", \"w\") as f: f.writelines(data) except Exception as", "from api.serializers import LabelSerializer from api.utils import JSONPainter def extract_document_classification(label, labels): return labels.get(pk=label[\"label\"]).text", "= map( lambda x: { **x, \"labels\": list( map( lambda y: get_extract_label(project)(y, labels),", "data = JSONPainter().paint(documents) data = map( lambda x: { **x, \"labels\": list( map(", "JSONPainter def extract_document_classification(label, labels): return labels.get(pk=label[\"label\"]).text def extract_label_seq_labeling(label, labels): return [ label[\"start_offset\"], label[\"end_offset\"],", "import os from rest_framework.renderers import JSONRenderer from api.models import Project, DOCUMENT_CLASSIFICATION, SEQUENCE_LABELING from", "list( map( lambda y: get_extract_label(project)(y, labels), x[\"annotations\"], ) ), }, data, ) data", ") data = map(json.dumps, data) data = map(lambda x: x + \"\\n\", data)", "with open(f\"{project_dir}/data.jsonl\", \"w\") as f: f.writelines(data) except Exception as ex: print(f\"Error {project.name} {ex}\")", "if not os.path.exists(project_dir): os.makedirs(project_dir) print(f\"Dumping {project.name}\") labels = project.labels.all() label_serializer = LabelSerializer(labels, many=True)", "os.path.exists(project_dir): os.makedirs(project_dir) print(f\"Dumping {project.name}\") labels = project.labels.all() label_serializer = LabelSerializer(labels, many=True) documents =", "label[\"start_offset\"], label[\"end_offset\"], labels.get(pk=label[\"label\"]).text, ] def get_extract_label(project): return { DOCUMENT_CLASSIFICATION: extract_document_classification, SEQUENCE_LABELING: extract_label_seq_labeling, }[project.project_type]", "api.models import Project, DOCUMENT_CLASSIFICATION, SEQUENCE_LABELING from api.serializers import LabelSerializer from api.utils import JSONPainter", "Project.objects.all(): try: project_dir = f\"{dump_dir}/dump_{project.name.replace('/', '_')}\" if not os.path.exists(project_dir): os.makedirs(project_dir) print(f\"Dumping {project.name}\") labels", "labels.get(pk=label[\"label\"]).text def extract_label_seq_labeling(label, labels): return [ label[\"start_offset\"], label[\"end_offset\"], labels.get(pk=label[\"label\"]).text, ] def get_extract_label(project): return", "SEQUENCE_LABELING: extract_label_seq_labeling, }[project.project_type] def get_all_projects_json(): dump_dir = \"projects_dump\" if not os.path.exists(dump_dir): os.makedirs(dump_dir) for", "x + \"\\n\", data) with open(f\"{project_dir}/labels.json\", \"wb\") as f: f.write(JSONRenderer().render(label_serializer.data)) with open(f\"{project_dir}/data.jsonl\", \"w\")", "not os.path.exists(project_dir): os.makedirs(project_dir) print(f\"Dumping {project.name}\") labels = project.labels.all() label_serializer = LabelSerializer(labels, many=True) documents", "return { DOCUMENT_CLASSIFICATION: extract_document_classification, SEQUENCE_LABELING: extract_label_seq_labeling, }[project.project_type] def get_all_projects_json(): dump_dir = \"projects_dump\" if", "map(lambda x: x + \"\\n\", data) with open(f\"{project_dir}/labels.json\", \"wb\") as f: f.write(JSONRenderer().render(label_serializer.data)) with", "labels): return [ label[\"start_offset\"], label[\"end_offset\"], labels.get(pk=label[\"label\"]).text, ] def get_extract_label(project): return { DOCUMENT_CLASSIFICATION: extract_document_classification,", "JSONPainter().paint(documents) data = map( lambda x: { **x, \"labels\": list( map( lambda y:", "labels.get(pk=label[\"label\"]).text, ] def get_extract_label(project): return { DOCUMENT_CLASSIFICATION: extract_document_classification, SEQUENCE_LABELING: extract_label_seq_labeling, }[project.project_type] def get_all_projects_json():", "for project in Project.objects.all(): try: project_dir = f\"{dump_dir}/dump_{project.name.replace('/', '_')}\" if not os.path.exists(project_dir): os.makedirs(project_dir)", "import json import os from rest_framework.renderers import JSONRenderer from api.models import Project, DOCUMENT_CLASSIFICATION,", "map( lambda x: { **x, \"labels\": list( map( lambda y: get_extract_label(project)(y, labels), x[\"annotations\"],", "os from rest_framework.renderers import JSONRenderer from api.models import Project, DOCUMENT_CLASSIFICATION, SEQUENCE_LABELING from api.serializers", "get_extract_label(project): return { DOCUMENT_CLASSIFICATION: extract_document_classification, SEQUENCE_LABELING: extract_label_seq_labeling, }[project.project_type] def get_all_projects_json(): dump_dir = \"projects_dump\"", "documents = project.documents.all() data = JSONPainter().paint(documents) data = map( lambda x: { **x,", "with open(f\"{project_dir}/labels.json\", \"wb\") as f: f.write(JSONRenderer().render(label_serializer.data)) with open(f\"{project_dir}/data.jsonl\", \"w\") as f: f.writelines(data) except", "api.serializers import LabelSerializer from api.utils import JSONPainter def extract_document_classification(label, labels): return labels.get(pk=label[\"label\"]).text def", "lambda x: { **x, \"labels\": list( map( lambda y: get_extract_label(project)(y, labels), x[\"annotations\"], )", "[ label[\"start_offset\"], label[\"end_offset\"], labels.get(pk=label[\"label\"]).text, ] def get_extract_label(project): return { DOCUMENT_CLASSIFICATION: extract_document_classification, SEQUENCE_LABELING: extract_label_seq_labeling,", "\"\\n\", data) with open(f\"{project_dir}/labels.json\", \"wb\") as f: f.write(JSONRenderer().render(label_serializer.data)) with open(f\"{project_dir}/data.jsonl\", \"w\") as f:", "from rest_framework.renderers import JSONRenderer from api.models import Project, DOCUMENT_CLASSIFICATION, SEQUENCE_LABELING from api.serializers import", "open(f\"{project_dir}/labels.json\", \"wb\") as f: f.write(JSONRenderer().render(label_serializer.data)) with open(f\"{project_dir}/data.jsonl\", \"w\") as f: f.writelines(data) except Exception", "'_')}\" if not os.path.exists(project_dir): os.makedirs(project_dir) print(f\"Dumping {project.name}\") labels = project.labels.all() label_serializer = LabelSerializer(labels,", "data = map(lambda x: x + \"\\n\", data) with open(f\"{project_dir}/labels.json\", \"wb\") as f:", "data = map(json.dumps, data) data = map(lambda x: x + \"\\n\", data) with", ") ), }, data, ) data = map(json.dumps, data) data = map(lambda x:", "f.write(JSONRenderer().render(label_serializer.data)) with open(f\"{project_dir}/data.jsonl\", \"w\") as f: f.writelines(data) except Exception as ex: print(f\"Error {project.name}", "+ \"\\n\", data) with open(f\"{project_dir}/labels.json\", \"wb\") as f: f.write(JSONRenderer().render(label_serializer.data)) with open(f\"{project_dir}/data.jsonl\", \"w\") as", "DOCUMENT_CLASSIFICATION: extract_document_classification, SEQUENCE_LABELING: extract_label_seq_labeling, }[project.project_type] def get_all_projects_json(): dump_dir = \"projects_dump\" if not os.path.exists(dump_dir):", "def get_extract_label(project): return { DOCUMENT_CLASSIFICATION: extract_document_classification, SEQUENCE_LABELING: extract_label_seq_labeling, }[project.project_type] def get_all_projects_json(): dump_dir =", "= \"projects_dump\" if not os.path.exists(dump_dir): os.makedirs(dump_dir) for project in Project.objects.all(): try: project_dir =", "import Project, DOCUMENT_CLASSIFICATION, SEQUENCE_LABELING from api.serializers import LabelSerializer from api.utils import JSONPainter def", "}, data, ) data = map(json.dumps, data) data = map(lambda x: x +", "y: get_extract_label(project)(y, labels), x[\"annotations\"], ) ), }, data, ) data = map(json.dumps, data)", "get_all_projects_json(): dump_dir = \"projects_dump\" if not os.path.exists(dump_dir): os.makedirs(dump_dir) for project in Project.objects.all(): try:", "os.path.exists(dump_dir): os.makedirs(dump_dir) for project in Project.objects.all(): try: project_dir = f\"{dump_dir}/dump_{project.name.replace('/', '_')}\" if not", "DOCUMENT_CLASSIFICATION, SEQUENCE_LABELING from api.serializers import LabelSerializer from api.utils import JSONPainter def extract_document_classification(label, labels):", "lambda y: get_extract_label(project)(y, labels), x[\"annotations\"], ) ), }, data, ) data = map(json.dumps,", "}[project.project_type] def get_all_projects_json(): dump_dir = \"projects_dump\" if not os.path.exists(dump_dir): os.makedirs(dump_dir) for project in", "project in Project.objects.all(): try: project_dir = f\"{dump_dir}/dump_{project.name.replace('/', '_')}\" if not os.path.exists(project_dir): os.makedirs(project_dir) print(f\"Dumping", "data, ) data = map(json.dumps, data) data = map(lambda x: x + \"\\n\",", "extract_document_classification(label, labels): return labels.get(pk=label[\"label\"]).text def extract_label_seq_labeling(label, labels): return [ label[\"start_offset\"], label[\"end_offset\"], labels.get(pk=label[\"label\"]).text, ]", "if not os.path.exists(dump_dir): os.makedirs(dump_dir) for project in Project.objects.all(): try: project_dir = f\"{dump_dir}/dump_{project.name.replace('/', '_')}\"", "LabelSerializer from api.utils import JSONPainter def extract_document_classification(label, labels): return labels.get(pk=label[\"label\"]).text def extract_label_seq_labeling(label, labels):", "project.labels.all() label_serializer = LabelSerializer(labels, many=True) documents = project.documents.all() data = JSONPainter().paint(documents) data =", "labels), x[\"annotations\"], ) ), }, data, ) data = map(json.dumps, data) data =", "{ DOCUMENT_CLASSIFICATION: extract_document_classification, SEQUENCE_LABELING: extract_label_seq_labeling, }[project.project_type] def get_all_projects_json(): dump_dir = \"projects_dump\" if not", "x[\"annotations\"], ) ), }, data, ) data = map(json.dumps, data) data = map(lambda", "), }, data, ) data = map(json.dumps, data) data = map(lambda x: x", "def extract_document_classification(label, labels): return labels.get(pk=label[\"label\"]).text def extract_label_seq_labeling(label, labels): return [ label[\"start_offset\"], label[\"end_offset\"], labels.get(pk=label[\"label\"]).text,", "from api.utils import JSONPainter def extract_document_classification(label, labels): return labels.get(pk=label[\"label\"]).text def extract_label_seq_labeling(label, labels): return", "extract_label_seq_labeling, }[project.project_type] def get_all_projects_json(): dump_dir = \"projects_dump\" if not os.path.exists(dump_dir): os.makedirs(dump_dir) for project", "as f: f.write(JSONRenderer().render(label_serializer.data)) with open(f\"{project_dir}/data.jsonl\", \"w\") as f: f.writelines(data) except Exception as ex:", "f: f.write(JSONRenderer().render(label_serializer.data)) with open(f\"{project_dir}/data.jsonl\", \"w\") as f: f.writelines(data) except Exception as ex: print(f\"Error", "f\"{dump_dir}/dump_{project.name.replace('/', '_')}\" if not os.path.exists(project_dir): os.makedirs(project_dir) print(f\"Dumping {project.name}\") labels = project.labels.all() label_serializer =", "def get_all_projects_json(): dump_dir = \"projects_dump\" if not os.path.exists(dump_dir): os.makedirs(dump_dir) for project in Project.objects.all():", "not os.path.exists(dump_dir): os.makedirs(dump_dir) for project in Project.objects.all(): try: project_dir = f\"{dump_dir}/dump_{project.name.replace('/', '_')}\" if", "data) data = map(lambda x: x + \"\\n\", data) with open(f\"{project_dir}/labels.json\", \"wb\") as", "return [ label[\"start_offset\"], label[\"end_offset\"], labels.get(pk=label[\"label\"]).text, ] def get_extract_label(project): return { DOCUMENT_CLASSIFICATION: extract_document_classification, SEQUENCE_LABELING:", "labels): return labels.get(pk=label[\"label\"]).text def extract_label_seq_labeling(label, labels): return [ label[\"start_offset\"], label[\"end_offset\"], labels.get(pk=label[\"label\"]).text, ] def" ]
[ "ideal2, productivity_factors[i], final_T_second) print(\"Iteration count 2 {}\".format(iteration_count2)) stop2 = time.time() write_to_optimization_table(task_id,optimizationed_schedule2,max_proj2,stop2-start2,relative_projection2,iteration_count2) def write_to_alorithms_table(task_id,", "[] for j in range(table.shape[1]): row.append(1 / table[i, j]) newtable.append(row) newtable = np.array(newtable)", "optimizationed_schedule2,max_proj2,relative_projection2,iteration_count2 = create(keys2, ideal2, productivity_factors[i], final_T_second) print(\"Iteration count 2 {}\".format(iteration_count2)) stop2 = time.time()", "tasks_lists) for j in range(len(productivity_factors)): row = [] for i in range(len(tasks_lists)): row.append(tasks_lists[i]", "time.time() final_T_second, keys2, ideal2 = get_finall_T(schedules_secoond_alg[i], productivity_factors[i]) optimizationed_schedule2,max_proj2,relative_projection2,iteration_count2 = create(keys2, ideal2, productivity_factors[i], final_T_second)", "[0] * len(k) x = [0] * len(k) counter = 0 sigma2 =", "optimization for i in range(len(sets)): start1 = time.time() final_T_first, keys1, ideal1 = get_finall_T(schedules_first_alg[i],", "sets, task_id, C): from .optimization_algorithms import get_finall_T, create import time schedules_first_alg = []", "json.dumps(schedule1[i]) sched_JSON2 = json.dumps(schedule2[i]) alg = Algorithm(task_id=task_id, initial_timetable_first_alg=sched_JSON1, initial_timetable_second_alg=sched_JSON2) db.session.add(alg) db.session.commit() def write_to_optimization_table(task_id,algorithm,projection,runtime,relative_projection,iteration_count):", "index with max f list_of_used_time_of_every_machine[index] += np.asscalar(table[j][index]) # fill C C_foreach_machine[index] -= tasks_list[j]", "k, C): print('\\n----------------------------------------------------------------') print('First optimization') T = [] for i in range(len(k)): T.append((C", "output_result_algorithm(result): for i in enumerate(result): pass # print('Machine ', i[0] + 1, i[1])", "counter = 0 sigma2 = round(sigma, 0) sigma2 = int(sigma2) print(int(sigma2)) for i", "newtable.append(row) newtable = np.array(newtable) return newtable def output_result_algorithm(result): for i in enumerate(result): pass", "productivity_factors[j]) output_table.append(row) output_table = np.array(output_table) output_table = output_table.T return output_table def calculate_second_table(table): newtable", "index = Tq.index(min(Tq)) Tq[index] += k[index] x[index] += 1 for i in range(len(k)):", "x, FirstT def run_algorithms(productivity_factors, sets, task_id, C): from .optimization_algorithms import get_finall_T, create import", "count_of_task, table, tasks_list, C_foreach_machine): task_of_machine = [] list_of_used_time_of_every_machine = list(count_of_machine * [0]) #print(\"tasks\"", "tasks for every machine with magic algorithms from the Heaven for j in", "/ i, productivity_factors[i])) schedules_secoond_alg.append(A2(len(productivity_factors[i]), len(sets[i]), task_table_with_coefficient, sets[i], C_foreach_machine)) # Get data from DB", "for i in range(len(k)): Tq[i] += k[i] x = [0] * len(k) sigma2", "import db algo = json.dumps(algorithm) tsk = Task.query.filter_by(id=task_id).first() tsk.first_Optimization = algo tsk.first_projection =", "[] for i in range(len(k)): T.append((C - k[i] * e[i])) opt = [0]", "sigma2 = round(sigma, 0) sigma2 = int(sigma2) print(int(sigma2)) for i in range(sigma2): for", "optimizationed_schedule1, max_proj1, stop1 - start1,relative_projection1,iteration_count1) start2 = time.time() final_T_second, keys2, ideal2 = get_finall_T(schedules_secoond_alg[i],", "+= 1 for i in range(len(k)): T[i] += x[i] * k[i] print(\"X =", "= calculate_task_table_from_productivity_factors(sets[i], productivity_factors[i]) C_foreach_machine = list(map(lambda i: C / i, productivity_factors[i])) schedules_secoond_alg.append(A2(len(productivity_factors[i]), len(sets[i]),", "round(sigma, 0) sigma2 = int(sigma2) print(int(sigma2)) for i in range(sigma2): for i in", "print(\"Iteration count 1 {}\".format(iteration_count1)) stop1 = time.time() write_to_optimization_table(task_id, optimizationed_schedule1, max_proj1, stop1 - start1,relative_projection1,iteration_count1)", "k - vector productivity factors # transform two vector to matrix with task", "C): print('\\n----------------------------------------------------------------') print('Second optimization') T = [] for i in range(len(k)): T.append((C -", "max f list_of_used_time_of_every_machine[index] += np.asscalar(table[j][index]) # fill C C_foreach_machine[index] -= tasks_list[j] task_of_machine[index].update({j +", "_ in range(0, count_of_machine): machine = {} task_of_machine.append(machine) for j in range(0, count_of_task):", "in range(count_of_tasks): index = list_of_used_time_of_every_machine.index(min(list_of_used_time_of_every_machine)) list_of_used_time_of_every_machine[index] += np.asscalar(task_table_with_coefficient[j][index]) task_of_machine[index].update({j + 1: np.asscalar(task_table_with_coefficient[j][index])}) output_result_algorithm(task_of_machine)", "T.append((C - k[i] * e[i])) opt = [0] * len(k) x = [0]", "import Algorithm from .. import db import json for i in range(len(schedule1)): #", "- start1,relative_projection1,iteration_count1) start2 = time.time() final_T_second, keys2, ideal2 = get_finall_T(schedules_secoond_alg[i], productivity_factors[i]) optimizationed_schedule2,max_proj2,relative_projection2,iteration_count2 =", "output_result_algorithm(task_of_machine) return task_of_machine def A2(count_of_machine, count_of_task, table, tasks_list, C_foreach_machine): task_of_machine = [] list_of_used_time_of_every_machine", "count of task. k - vector productivity factors # transform two vector to", "T.append((C - k[i] * e[i])) FirstT = T.copy() Tq = T.copy() for i", "def calculate_task_table_from_productivity_factors(tasks_lists, productivity_factors): # p - count of task. k - vector productivity", "optimization') T = [] for i in range(len(k)): T.append((C - k[i] * e[i]))", "sigma2 = round(sigma, 0) print(int(sigma2)) sigma2 = int(sigma2) print(int(sigma2)) for i in range(sigma2):", "output_table = output_table.T return output_table def calculate_second_table(table): newtable = [] for i in", "range(len(sets)): task_table_with_coefficient = calculate_task_table_from_productivity_factors(sets[i], productivity_factors[i]) schedules_first_alg.append( A1(len(productivity_factors[i]), len(sets[i]), task_table_with_coefficient)) for i in range(len((sets))):", "* productivity output_table = [] productivity_factors.sort() tasks_lists.sort() tasks_lists.reverse() # print(productivity_factors, tasks_lists) for j", "i[1]) def A1(count_of_machine, count_of_tasks, task_table_with_coefficient): task_of_machine = [] list_of_used_time_of_every_machine = list(count_of_machine * [0])", "x def optimization1(sigma, e, k, C): print('\\n----------------------------------------------------------------') print('First optimization') T = [] for", "get_finall_T(schedules_secoond_alg[i], productivity_factors[i]) optimizationed_schedule2,max_proj2,relative_projection2,iteration_count2 = create(keys2, ideal2, productivity_factors[i], final_T_second) print(\"Iteration count 2 {}\".format(iteration_count2)) stop2", "task_of_machine.append(machine) # distribute tasks for every machine with magic algorithms from the Heaven", "task_of_machine = [] list_of_used_time_of_every_machine = list(count_of_machine * [0]) # create dict for every", "{} task_of_machine.append(machine) # distribute tasks for every machine with magic algorithms from the", "factors # transform two vector to matrix with task * productivity output_table =", "= [] for i in range(len(k)): T.append((C - k[i] * e[i])) opt =", "C / i, productivity_factors[i])) schedules_secoond_alg.append(A2(len(productivity_factors[i]), len(sets[i]), task_table_with_coefficient, sets[i], C_foreach_machine)) # Get data from", "import db import json for i in range(len(schedule1)): # print('schedule1 {0} schedule {1}'.format(schedule1,", "output_table.append(row) output_table = np.array(output_table) output_table = output_table.T return output_table def calculate_second_table(table): newtable =", "= time.time() final_T_first, keys1, ideal1 = get_finall_T(schedules_first_alg[i], productivity_factors[i]) optimizationed_schedule1,max_proj1,relative_projection1,iteration_count1 = create(keys1, ideal1, productivity_factors[i],", "task_of_machine[index].update({j + 1: np.asscalar(table[j][index])}) # output_result_algorithm(task_of_machine) return task_of_machine def optimization2(k, e, sigma, C):", "schedule1, schedule2): from ..models import Algorithm from .. import db import json for", "task_table_with_coefficient)) for i in range(len((sets))): task_table_with_coefficient = calculate_task_table_from_productivity_factors(sets[i], productivity_factors[i]) C_foreach_machine = list(map(lambda i:", "* [0]) # create dict for every machine in task for _ in", "+= k[index] x[index] += 1 for i in range(len(k)): T[i] += x[i] *", "in range(0, count_of_machine): machine = {} task_of_machine.append(machine) # distribute tasks for every machine", "in range(len((sets))): task_table_with_coefficient = calculate_task_table_from_productivity_factors(sets[i], productivity_factors[i]) C_foreach_machine = list(map(lambda i: C / i,", "final_T_first) print(\"Iteration count 1 {}\".format(iteration_count1)) stop1 = time.time() write_to_optimization_table(task_id, optimizationed_schedule1, max_proj1, stop1 -", "..models import Task import json from .. import db algo = json.dumps(algorithm) tsk", "Tq.index(min(Tq)) Tq[index] += k[index] x[index] += 1 for i in range(len(k)): T[i] +=", "[0] * len(k) counter = 0 sigma2 = round(sigma, 0) sigma2 = int(sigma2)", "tsk.first_projection = projection tsk.first_lead_time = runtime tsk.first_relatively_projection = relative_projection tsk.first_iteration_count = iteration_count db.session.commit()", "count_of_machine): machine = {} task_of_machine.append(machine) for j in range(0, count_of_task): index = C_foreach_machine.index(max(C_foreach_machine))", "for i in range(len(sets)): start1 = time.time() final_T_first, keys1, ideal1 = get_finall_T(schedules_first_alg[i], productivity_factors[i])", "keys1, ideal1 = get_finall_T(schedules_first_alg[i], productivity_factors[i]) optimizationed_schedule1,max_proj1,relative_projection1,iteration_count1 = create(keys1, ideal1, productivity_factors[i], final_T_first) print(\"Iteration count", "list_of_used_time_of_every_machine = list(count_of_machine * [0]) # create dict for every machine in task", "list(count_of_machine * [0]) # create dict for every machine in task for _", "numpy as np def calculate_task_table_from_productivity_factors(tasks_lists, productivity_factors): # p - count of task. k", "enumerate(result): pass # print('Machine ', i[0] + 1, i[1]) def A1(count_of_machine, count_of_tasks, task_table_with_coefficient):", "np.array(output_table) output_table = output_table.T return output_table def calculate_second_table(table): newtable = [] for i", "list_of_used_time_of_every_machine[index] += np.asscalar(task_table_with_coefficient[j][index]) task_of_machine[index].update({j + 1: np.asscalar(task_table_with_coefficient[j][index])}) output_result_algorithm(task_of_machine) return task_of_machine def A2(count_of_machine, count_of_task,", "task. k - vector productivity factors # transform two vector to matrix with", "output_table def calculate_second_table(table): newtable = [] for i in range(table.shape[0]): row = []", "calculate_task_table_from_productivity_factors(sets[i], productivity_factors[i]) C_foreach_machine = list(map(lambda i: C / i, productivity_factors[i])) schedules_secoond_alg.append(A2(len(productivity_factors[i]), len(sets[i]), task_table_with_coefficient,", "Get data from DB # Run algorithms # Write to algorithm table write_to_alorithms_table(task_id,", "np.asscalar(table[j][index]) # fill C C_foreach_machine[index] -= tasks_list[j] task_of_machine[index].update({j + 1: np.asscalar(table[j][index])}) # output_result_algorithm(task_of_machine)", "range(0, count_of_machine): machine = {} task_of_machine.append(machine) for j in range(0, count_of_task): index =", "j in range(len(productivity_factors)): row = [] for i in range(len(tasks_lists)): row.append(tasks_lists[i] * productivity_factors[j])", "import json for i in range(len(schedule1)): # print('schedule1 {0} schedule {1}'.format(schedule1, schedule2)) #", "k[i] * e[i])) opt = [0] * len(k) x = [0] * len(k)", "..models import Algorithm from .. import db import json for i in range(len(schedule1)):", "range(len(schedule1)): # print('schedule1 {0} schedule {1}'.format(schedule1, schedule2)) # print('1 len {0}, type {1}", "opt[i] = k[i] * (e[i] - x[i]) index = opt.index(max(opt)) x[index] += 1", "for j in range(count_of_tasks): index = list_of_used_time_of_every_machine.index(min(list_of_used_time_of_every_machine)) list_of_used_time_of_every_machine[index] += np.asscalar(task_table_with_coefficient[j][index]) task_of_machine[index].update({j + 1:", "i[0] + 1, i[1]) def A1(count_of_machine, count_of_tasks, task_table_with_coefficient): task_of_machine = [] list_of_used_time_of_every_machine =", "= list(count_of_machine * [0]) # create dict for every machine in task for", "task_of_machine def A2(count_of_machine, count_of_task, table, tasks_list, C_foreach_machine): task_of_machine = [] list_of_used_time_of_every_machine = list(count_of_machine", "+= 1 print(counter) print(\"X = \", x) return x def optimization1(sigma, e, k,", "task_table_with_coefficient, sets[i], C_foreach_machine)) # Get data from DB # Run algorithms # Write", "= list(count_of_machine * [0]) #print(\"tasks\" + tasks_list) for _ in range(0, count_of_machine): machine", "T[index] += k[index] counter += 1 print(counter) print(\"X = \", x) return x", "dict for every machine in task for _ in range(0, count_of_machine): machine =", "T.copy() for i in range(len(k)): Tq[i] += k[i] x = [0] * len(k)", "k[i] * (e[i] - x[i]) index = opt.index(max(opt)) x[index] += 1 T[index] +=", "round(sigma, 0) print(int(sigma2)) sigma2 = int(sigma2) print(int(sigma2)) for i in range(sigma2): index =", "print(int(sigma2)) sigma2 = int(sigma2) print(int(sigma2)) for i in range(sigma2): index = Tq.index(min(Tq)) Tq[index]", "return newtable def output_result_algorithm(result): for i in enumerate(result): pass # print('Machine ', i[0]", "= json.dumps(schedule1[i]) sched_JSON2 = json.dumps(schedule2[i]) alg = Algorithm(task_id=task_id, initial_timetable_first_alg=sched_JSON1, initial_timetable_second_alg=sched_JSON2) db.session.add(alg) db.session.commit() def", "schedules_first_alg = [] schedules_secoond_alg = [] for i in range(len(sets)): task_table_with_coefficient = calculate_task_table_from_productivity_factors(sets[i],", "(e[i] - x[i]) index = opt.index(max(opt)) x[index] += 1 T[index] += k[index] counter", "\", x) return x, FirstT def run_algorithms(productivity_factors, sets, task_id, C): from .optimization_algorithms import", "{1} schedule {2}'.format(len(schedule1), type(schedule1[0]), schedule1[i][0]), i) #print('2 len {0}, type {1} schedule {2}'.format(len(schedule2),", "row = [] for j in range(table.shape[1]): row.append(1 / table[i, j]) newtable.append(row) newtable", "int(sigma2) print(int(sigma2)) for i in range(sigma2): for i in range(len(k)): opt[i] = k[i]", "{}\".format(iteration_count1)) stop1 = time.time() write_to_optimization_table(task_id, optimizationed_schedule1, max_proj1, stop1 - start1,relative_projection1,iteration_count1) start2 = time.time()", "range(len(k)): T[i] += x[i] * k[i] print(\"X = \", x) return x, FirstT", "output_table.T return output_table def calculate_second_table(table): newtable = [] for i in range(table.shape[0]): row", "print('Second optimization') T = [] for i in range(len(k)): T.append((C - k[i] *", "productivity_factors[i]) optimizationed_schedule1,max_proj1,relative_projection1,iteration_count1 = create(keys1, ideal1, productivity_factors[i], final_T_first) print(\"Iteration count 1 {}\".format(iteration_count1)) stop1 =", "', i[0] + 1, i[1]) def A1(count_of_machine, count_of_tasks, task_table_with_coefficient): task_of_machine = [] list_of_used_time_of_every_machine", "A2(count_of_machine, count_of_task, table, tasks_list, C_foreach_machine): task_of_machine = [] list_of_used_time_of_every_machine = list(count_of_machine * [0])", "count 1 {}\".format(iteration_count1)) stop1 = time.time() write_to_optimization_table(task_id, optimizationed_schedule1, max_proj1, stop1 - start1,relative_projection1,iteration_count1) start2", "Heaven for j in range(count_of_tasks): index = list_of_used_time_of_every_machine.index(min(list_of_used_time_of_every_machine)) list_of_used_time_of_every_machine[index] += np.asscalar(task_table_with_coefficient[j][index]) task_of_machine[index].update({j +", "for i in range(len(k)): T.append((C - k[i] * e[i])) opt = [0] *", "range(len(productivity_factors)): row = [] for i in range(len(tasks_lists)): row.append(tasks_lists[i] * productivity_factors[j]) output_table.append(row) output_table", "# print(productivity_factors, tasks_lists) for j in range(len(productivity_factors)): row = [] for i in", "count_of_task): index = C_foreach_machine.index(max(C_foreach_machine)) # index with max f list_of_used_time_of_every_machine[index] += np.asscalar(table[j][index]) #", "opt.index(max(opt)) x[index] += 1 T[index] += k[index] counter += 1 print(counter) print(\"X =", "p - count of task. k - vector productivity factors # transform two", "# p - count of task. k - vector productivity factors # transform", "T = [] for i in range(len(k)): T.append((C - k[i] * e[i])) FirstT", "newtable def output_result_algorithm(result): for i in enumerate(result): pass # print('Machine ', i[0] +", "to matrix with task * productivity output_table = [] productivity_factors.sort() tasks_lists.sort() tasks_lists.reverse() #", "print(productivity_factors, tasks_lists) for j in range(len(productivity_factors)): row = [] for i in range(len(tasks_lists)):", "np.asscalar(table[j][index])}) # output_result_algorithm(task_of_machine) return task_of_machine def optimization2(k, e, sigma, C): print('\\n----------------------------------------------------------------') print('Second optimization')", "= json.dumps(schedule2[i]) alg = Algorithm(task_id=task_id, initial_timetable_first_alg=sched_JSON1, initial_timetable_second_alg=sched_JSON2) db.session.add(alg) db.session.commit() def write_to_optimization_table(task_id,algorithm,projection,runtime,relative_projection,iteration_count): from ..models", "range(len(k)): opt[i] = k[i] * (e[i] - x[i]) index = opt.index(max(opt)) x[index] +=", "sigma, C): print('\\n----------------------------------------------------------------') print('Second optimization') T = [] for i in range(len(k)): T.append((C", "print('\\n----------------------------------------------------------------') print('Second optimization') T = [] for i in range(len(k)): T.append((C - k[i]", "time.time() final_T_first, keys1, ideal1 = get_finall_T(schedules_first_alg[i], productivity_factors[i]) optimizationed_schedule1,max_proj1,relative_projection1,iteration_count1 = create(keys1, ideal1, productivity_factors[i], final_T_first)", "productivity_factors[i]) optimizationed_schedule2,max_proj2,relative_projection2,iteration_count2 = create(keys2, ideal2, productivity_factors[i], final_T_second) print(\"Iteration count 2 {}\".format(iteration_count2)) stop2 =", "for i in range(len(sets)): task_table_with_coefficient = calculate_task_table_from_productivity_factors(sets[i], productivity_factors[i]) schedules_first_alg.append( A1(len(productivity_factors[i]), len(sets[i]), task_table_with_coefficient)) for", "len {0}, type {1} schedule {2}'.format(len(schedule2), type(schedule2[0]), schedule2[i][0])) sched_JSON1 = json.dumps(schedule1[i]) sched_JSON2 =", "row.append(tasks_lists[i] * productivity_factors[j]) output_table.append(row) output_table = np.array(output_table) output_table = output_table.T return output_table def", "initial_timetable_second_alg=sched_JSON2) db.session.add(alg) db.session.commit() def write_to_optimization_table(task_id,algorithm,projection,runtime,relative_projection,iteration_count): from ..models import Task import json from ..", "for i in range(sigma2): index = Tq.index(min(Tq)) Tq[index] += k[index] x[index] += 1", "C_foreach_machine = list(map(lambda i: C / i, productivity_factors[i])) schedules_secoond_alg.append(A2(len(productivity_factors[i]), len(sets[i]), task_table_with_coefficient, sets[i], C_foreach_machine))", "range(len(k)): T.append((C - k[i] * e[i])) opt = [0] * len(k) x =", "i) #print('2 len {0}, type {1} schedule {2}'.format(len(schedule2), type(schedule2[0]), schedule2[i][0])) sched_JSON1 = json.dumps(schedule1[i])", "1 {}\".format(iteration_count1)) stop1 = time.time() write_to_optimization_table(task_id, optimizationed_schedule1, max_proj1, stop1 - start1,relative_projection1,iteration_count1) start2 =", "int(sigma2) print(int(sigma2)) for i in range(sigma2): index = Tq.index(min(Tq)) Tq[index] += k[index] x[index]", "sched_JSON1 = json.dumps(schedule1[i]) sched_JSON2 = json.dumps(schedule2[i]) alg = Algorithm(task_id=task_id, initial_timetable_first_alg=sched_JSON1, initial_timetable_second_alg=sched_JSON2) db.session.add(alg) db.session.commit()", "Write to algorithm table write_to_alorithms_table(task_id, schedules_first_alg, schedules_secoond_alg) # create optimization for i in", "optimizationed_schedule1,max_proj1,relative_projection1,iteration_count1 = create(keys1, ideal1, productivity_factors[i], final_T_first) print(\"Iteration count 1 {}\".format(iteration_count1)) stop1 = time.time()", "schedule2)) # print('1 len {0}, type {1} schedule {2}'.format(len(schedule1), type(schedule1[0]), schedule1[i][0]), i) #print('2", "sched_JSON2 = json.dumps(schedule2[i]) alg = Algorithm(task_id=task_id, initial_timetable_first_alg=sched_JSON1, initial_timetable_second_alg=sched_JSON2) db.session.add(alg) db.session.commit() def write_to_optimization_table(task_id,algorithm,projection,runtime,relative_projection,iteration_count): from", "vector to matrix with task * productivity output_table = [] productivity_factors.sort() tasks_lists.sort() tasks_lists.reverse()", "index = opt.index(max(opt)) x[index] += 1 T[index] += k[index] counter += 1 print(counter)", "in range(len(schedule1)): # print('schedule1 {0} schedule {1}'.format(schedule1, schedule2)) # print('1 len {0}, type", "Tq[i] += k[i] x = [0] * len(k) sigma2 = round(sigma, 0) print(int(sigma2))", "1 for i in range(len(k)): T[i] += x[i] * k[i] print(\"X = \",", "matrix with task * productivity output_table = [] productivity_factors.sort() tasks_lists.sort() tasks_lists.reverse() # print(productivity_factors,", "[] list_of_used_time_of_every_machine = list(count_of_machine * [0]) #print(\"tasks\" + tasks_list) for _ in range(0,", "range(sigma2): index = Tq.index(min(Tq)) Tq[index] += k[index] x[index] += 1 for i in", "time schedules_first_alg = [] schedules_secoond_alg = [] for i in range(len(sets)): task_table_with_coefficient =", "= Algorithm(task_id=task_id, initial_timetable_first_alg=sched_JSON1, initial_timetable_second_alg=sched_JSON2) db.session.add(alg) db.session.commit() def write_to_optimization_table(task_id,algorithm,projection,runtime,relative_projection,iteration_count): from ..models import Task import", "= [] for j in range(table.shape[1]): row.append(1 / table[i, j]) newtable.append(row) newtable =", "sigma2 = int(sigma2) print(int(sigma2)) for i in range(sigma2): for i in range(len(k)): opt[i]", "# Run algorithms # Write to algorithm table write_to_alorithms_table(task_id, schedules_first_alg, schedules_secoond_alg) # create", "schedule2): from ..models import Algorithm from .. import db import json for i", "from ..models import Task import json from .. import db algo = json.dumps(algorithm)", "ideal2 = get_finall_T(schedules_secoond_alg[i], productivity_factors[i]) optimizationed_schedule2,max_proj2,relative_projection2,iteration_count2 = create(keys2, ideal2, productivity_factors[i], final_T_second) print(\"Iteration count 2", "final_T_first, keys1, ideal1 = get_finall_T(schedules_first_alg[i], productivity_factors[i]) optimizationed_schedule1,max_proj1,relative_projection1,iteration_count1 = create(keys1, ideal1, productivity_factors[i], final_T_first) print(\"Iteration", "tasks_list) for _ in range(0, count_of_machine): machine = {} task_of_machine.append(machine) for j in", "* productivity_factors[j]) output_table.append(row) output_table = np.array(output_table) output_table = output_table.T return output_table def calculate_second_table(table):", "task_table_with_coefficient): task_of_machine = [] list_of_used_time_of_every_machine = list(count_of_machine * [0]) # create dict for", "task * productivity output_table = [] productivity_factors.sort() tasks_lists.sort() tasks_lists.reverse() # print(productivity_factors, tasks_lists) for", "# transform two vector to matrix with task * productivity output_table = []", "= json.dumps(algorithm) tsk = Task.query.filter_by(id=task_id).first() tsk.first_Optimization = algo tsk.first_projection = projection tsk.first_lead_time =", "with magic algorithms from the Heaven for j in range(count_of_tasks): index = list_of_used_time_of_every_machine.index(min(list_of_used_time_of_every_machine))", "every machine in task for _ in range(0, count_of_machine): machine = {} task_of_machine.append(machine)", "vector productivity factors # transform two vector to matrix with task * productivity", "np.array(newtable) return newtable def output_result_algorithm(result): for i in enumerate(result): pass # print('Machine ',", "schedule {2}'.format(len(schedule2), type(schedule2[0]), schedule2[i][0])) sched_JSON1 = json.dumps(schedule1[i]) sched_JSON2 = json.dumps(schedule2[i]) alg = Algorithm(task_id=task_id,", "from ..models import Algorithm from .. import db import json for i in", "Algorithm(task_id=task_id, initial_timetable_first_alg=sched_JSON1, initial_timetable_second_alg=sched_JSON2) db.session.add(alg) db.session.commit() def write_to_optimization_table(task_id,algorithm,projection,runtime,relative_projection,iteration_count): from ..models import Task import json", "return output_table def calculate_second_table(table): newtable = [] for i in range(table.shape[0]): row =", "C): print('\\n----------------------------------------------------------------') print('First optimization') T = [] for i in range(len(k)): T.append((C -", "range(0, count_of_machine): machine = {} task_of_machine.append(machine) # distribute tasks for every machine with", "print(int(sigma2)) for i in range(sigma2): for i in range(len(k)): opt[i] = k[i] *", "for i in range(len(k)): T.append((C - k[i] * e[i])) FirstT = T.copy() Tq", "Tq[index] += k[index] x[index] += 1 for i in range(len(k)): T[i] += x[i]", "output_table = np.array(output_table) output_table = output_table.T return output_table def calculate_second_table(table): newtable = []", "print('\\n----------------------------------------------------------------') print('First optimization') T = [] for i in range(len(k)): T.append((C - k[i]", "run_algorithms(productivity_factors, sets, task_id, C): from .optimization_algorithms import get_finall_T, create import time schedules_first_alg =", "db import json for i in range(len(schedule1)): # print('schedule1 {0} schedule {1}'.format(schedule1, schedule2))", "algorithms # Write to algorithm table write_to_alorithms_table(task_id, schedules_first_alg, schedules_secoond_alg) # create optimization for", "stop2 = time.time() write_to_optimization_table(task_id,optimizationed_schedule2,max_proj2,stop2-start2,relative_projection2,iteration_count2) def write_to_alorithms_table(task_id, schedule1, schedule2): from ..models import Algorithm from", "db algo = json.dumps(algorithm) tsk = Task.query.filter_by(id=task_id).first() tsk.first_Optimization = algo tsk.first_projection = projection", "= [] for i in range(len(k)): T.append((C - k[i] * e[i])) FirstT =", "Task.query.filter_by(id=task_id).first() tsk.first_Optimization = algo tsk.first_projection = projection tsk.first_lead_time = runtime tsk.first_relatively_projection = relative_projection", "= [0] * len(k) counter = 0 sigma2 = round(sigma, 0) sigma2 =", "in task for _ in range(0, count_of_machine): machine = {} task_of_machine.append(machine) # distribute", "tasks_list, C_foreach_machine): task_of_machine = [] list_of_used_time_of_every_machine = list(count_of_machine * [0]) #print(\"tasks\" + tasks_list)", "task_of_machine.append(machine) for j in range(0, count_of_task): index = C_foreach_machine.index(max(C_foreach_machine)) # index with max", "i in range(len(sets)): task_table_with_coefficient = calculate_task_table_from_productivity_factors(sets[i], productivity_factors[i]) schedules_first_alg.append( A1(len(productivity_factors[i]), len(sets[i]), task_table_with_coefficient)) for i", "in range(table.shape[0]): row = [] for j in range(table.shape[1]): row.append(1 / table[i, j])", "json.dumps(schedule2[i]) alg = Algorithm(task_id=task_id, initial_timetable_first_alg=sched_JSON1, initial_timetable_second_alg=sched_JSON2) db.session.add(alg) db.session.commit() def write_to_optimization_table(task_id,algorithm,projection,runtime,relative_projection,iteration_count): from ..models import", "algo tsk.first_projection = projection tsk.first_lead_time = runtime tsk.first_relatively_projection = relative_projection tsk.first_iteration_count = iteration_count", "print('Machine ', i[0] + 1, i[1]) def A1(count_of_machine, count_of_tasks, task_table_with_coefficient): task_of_machine = []", "[] schedules_secoond_alg = [] for i in range(len(sets)): task_table_with_coefficient = calculate_task_table_from_productivity_factors(sets[i], productivity_factors[i]) schedules_first_alg.append(", "final_T_second, keys2, ideal2 = get_finall_T(schedules_secoond_alg[i], productivity_factors[i]) optimizationed_schedule2,max_proj2,relative_projection2,iteration_count2 = create(keys2, ideal2, productivity_factors[i], final_T_second) print(\"Iteration", "2 {}\".format(iteration_count2)) stop2 = time.time() write_to_optimization_table(task_id,optimizationed_schedule2,max_proj2,stop2-start2,relative_projection2,iteration_count2) def write_to_alorithms_table(task_id, schedule1, schedule2): from ..models import", "range(count_of_tasks): index = list_of_used_time_of_every_machine.index(min(list_of_used_time_of_every_machine)) list_of_used_time_of_every_machine[index] += np.asscalar(task_table_with_coefficient[j][index]) task_of_machine[index].update({j + 1: np.asscalar(task_table_with_coefficient[j][index])}) output_result_algorithm(task_of_machine) return", "table, tasks_list, C_foreach_machine): task_of_machine = [] list_of_used_time_of_every_machine = list(count_of_machine * [0]) #print(\"tasks\" +", "def A1(count_of_machine, count_of_tasks, task_table_with_coefficient): task_of_machine = [] list_of_used_time_of_every_machine = list(count_of_machine * [0]) #", "= time.time() final_T_second, keys2, ideal2 = get_finall_T(schedules_secoond_alg[i], productivity_factors[i]) optimizationed_schedule2,max_proj2,relative_projection2,iteration_count2 = create(keys2, ideal2, productivity_factors[i],", "index = C_foreach_machine.index(max(C_foreach_machine)) # index with max f list_of_used_time_of_every_machine[index] += np.asscalar(table[j][index]) # fill", "print('First optimization') T = [] for i in range(len(k)): T.append((C - k[i] *", "= calculate_task_table_from_productivity_factors(sets[i], productivity_factors[i]) schedules_first_alg.append( A1(len(productivity_factors[i]), len(sets[i]), task_table_with_coefficient)) for i in range(len((sets))): task_table_with_coefficient =", "count_of_machine): machine = {} task_of_machine.append(machine) # distribute tasks for every machine with magic", "0) sigma2 = int(sigma2) print(int(sigma2)) for i in range(sigma2): for i in range(len(k)):", "stop1 - start1,relative_projection1,iteration_count1) start2 = time.time() final_T_second, keys2, ideal2 = get_finall_T(schedules_secoond_alg[i], productivity_factors[i]) optimizationed_schedule2,max_proj2,relative_projection2,iteration_count2", "= Tq.index(min(Tq)) Tq[index] += k[index] x[index] += 1 for i in range(len(k)): T[i]", "def A2(count_of_machine, count_of_task, table, tasks_list, C_foreach_machine): task_of_machine = [] list_of_used_time_of_every_machine = list(count_of_machine *", "range(table.shape[1]): row.append(1 / table[i, j]) newtable.append(row) newtable = np.array(newtable) return newtable def output_result_algorithm(result):", "row = [] for i in range(len(tasks_lists)): row.append(tasks_lists[i] * productivity_factors[j]) output_table.append(row) output_table =", "print(\"X = \", x) return x, FirstT def run_algorithms(productivity_factors, sets, task_id, C): from", "json for i in range(len(schedule1)): # print('schedule1 {0} schedule {1}'.format(schedule1, schedule2)) # print('1", "machine with magic algorithms from the Heaven for j in range(count_of_tasks): index =", "magic algorithms from the Heaven for j in range(count_of_tasks): index = list_of_used_time_of_every_machine.index(min(list_of_used_time_of_every_machine)) list_of_used_time_of_every_machine[index]", "e[i])) opt = [0] * len(k) x = [0] * len(k) counter =", "= [] productivity_factors.sort() tasks_lists.sort() tasks_lists.reverse() # print(productivity_factors, tasks_lists) for j in range(len(productivity_factors)): row", "for i in range(sigma2): for i in range(len(k)): opt[i] = k[i] * (e[i]", "distribute tasks for every machine with magic algorithms from the Heaven for j", "i, productivity_factors[i])) schedules_secoond_alg.append(A2(len(productivity_factors[i]), len(sets[i]), task_table_with_coefficient, sets[i], C_foreach_machine)) # Get data from DB #", "= np.array(newtable) return newtable def output_result_algorithm(result): for i in enumerate(result): pass # print('Machine", "# print('Machine ', i[0] + 1, i[1]) def A1(count_of_machine, count_of_tasks, task_table_with_coefficient): task_of_machine =", "print(\"X = \", x) return x def optimization1(sigma, e, k, C): print('\\n----------------------------------------------------------------') print('First", "= {} task_of_machine.append(machine) # distribute tasks for every machine with magic algorithms from", "calculate_task_table_from_productivity_factors(tasks_lists, productivity_factors): # p - count of task. k - vector productivity factors", "range(0, count_of_task): index = C_foreach_machine.index(max(C_foreach_machine)) # index with max f list_of_used_time_of_every_machine[index] += np.asscalar(table[j][index])", "for every machine with magic algorithms from the Heaven for j in range(count_of_tasks):", "1, i[1]) def A1(count_of_machine, count_of_tasks, task_table_with_coefficient): task_of_machine = [] list_of_used_time_of_every_machine = list(count_of_machine *", "C_foreach_machine[index] -= tasks_list[j] task_of_machine[index].update({j + 1: np.asscalar(table[j][index])}) # output_result_algorithm(task_of_machine) return task_of_machine def optimization2(k,", "\", x) return x def optimization1(sigma, e, k, C): print('\\n----------------------------------------------------------------') print('First optimization') T", "in range(0, count_of_machine): machine = {} task_of_machine.append(machine) for j in range(0, count_of_task): index", "+ tasks_list) for _ in range(0, count_of_machine): machine = {} task_of_machine.append(machine) for j", "task for _ in range(0, count_of_machine): machine = {} task_of_machine.append(machine) # distribute tasks", "in range(table.shape[1]): row.append(1 / table[i, j]) newtable.append(row) newtable = np.array(newtable) return newtable def", "from the Heaven for j in range(count_of_tasks): index = list_of_used_time_of_every_machine.index(min(list_of_used_time_of_every_machine)) list_of_used_time_of_every_machine[index] += np.asscalar(task_table_with_coefficient[j][index])", "schedules_first_alg.append( A1(len(productivity_factors[i]), len(sets[i]), task_table_with_coefficient)) for i in range(len((sets))): task_table_with_coefficient = calculate_task_table_from_productivity_factors(sets[i], productivity_factors[i]) C_foreach_machine", "np.asscalar(task_table_with_coefficient[j][index]) task_of_machine[index].update({j + 1: np.asscalar(task_table_with_coefficient[j][index])}) output_result_algorithm(task_of_machine) return task_of_machine def A2(count_of_machine, count_of_task, table, tasks_list,", "db.session.add(alg) db.session.commit() def write_to_optimization_table(task_id,algorithm,projection,runtime,relative_projection,iteration_count): from ..models import Task import json from .. import", "def run_algorithms(productivity_factors, sets, task_id, C): from .optimization_algorithms import get_finall_T, create import time schedules_first_alg", "i in range(len(schedule1)): # print('schedule1 {0} schedule {1}'.format(schedule1, schedule2)) # print('1 len {0},", "productivity_factors): # p - count of task. k - vector productivity factors #", "= k[i] * (e[i] - x[i]) index = opt.index(max(opt)) x[index] += 1 T[index]", "C_foreach_machine.index(max(C_foreach_machine)) # index with max f list_of_used_time_of_every_machine[index] += np.asscalar(table[j][index]) # fill C C_foreach_machine[index]", "sets[i], C_foreach_machine)) # Get data from DB # Run algorithms # Write to", "Task import json from .. import db algo = json.dumps(algorithm) tsk = Task.query.filter_by(id=task_id).first()", "type {1} schedule {2}'.format(len(schedule1), type(schedule1[0]), schedule1[i][0]), i) #print('2 len {0}, type {1} schedule", "def optimization2(k, e, sigma, C): print('\\n----------------------------------------------------------------') print('Second optimization') T = [] for i", "algorithm table write_to_alorithms_table(task_id, schedules_first_alg, schedules_secoond_alg) # create optimization for i in range(len(sets)): start1", "list(count_of_machine * [0]) #print(\"tasks\" + tasks_list) for _ in range(0, count_of_machine): machine =", "# create dict for every machine in task for _ in range(0, count_of_machine):", "in range(sigma2): for i in range(len(k)): opt[i] = k[i] * (e[i] - x[i])", "+= 1 T[index] += k[index] counter += 1 print(counter) print(\"X = \", x)", "in range(len(sets)): start1 = time.time() final_T_first, keys1, ideal1 = get_finall_T(schedules_first_alg[i], productivity_factors[i]) optimizationed_schedule1,max_proj1,relative_projection1,iteration_count1 =", "print(counter) print(\"X = \", x) return x def optimization1(sigma, e, k, C): print('\\n----------------------------------------------------------------')", "print(int(sigma2)) for i in range(sigma2): index = Tq.index(min(Tq)) Tq[index] += k[index] x[index] +=", "time.time() write_to_optimization_table(task_id,optimizationed_schedule2,max_proj2,stop2-start2,relative_projection2,iteration_count2) def write_to_alorithms_table(task_id, schedule1, schedule2): from ..models import Algorithm from .. import", "max_proj1, stop1 - start1,relative_projection1,iteration_count1) start2 = time.time() final_T_second, keys2, ideal2 = get_finall_T(schedules_secoond_alg[i], productivity_factors[i])", "* len(k) x = [0] * len(k) counter = 0 sigma2 = round(sigma,", "T.copy() Tq = T.copy() for i in range(len(k)): Tq[i] += k[i] x =", "from .. import db import json for i in range(len(schedule1)): # print('schedule1 {0}", "_ in range(0, count_of_machine): machine = {} task_of_machine.append(machine) # distribute tasks for every", "i in range(len(k)): Tq[i] += k[i] x = [0] * len(k) sigma2 =", "Run algorithms # Write to algorithm table write_to_alorithms_table(task_id, schedules_first_alg, schedules_secoond_alg) # create optimization", "count 2 {}\".format(iteration_count2)) stop2 = time.time() write_to_optimization_table(task_id,optimizationed_schedule2,max_proj2,stop2-start2,relative_projection2,iteration_count2) def write_to_alorithms_table(task_id, schedule1, schedule2): from ..models", "= time.time() write_to_optimization_table(task_id,optimizationed_schedule2,max_proj2,stop2-start2,relative_projection2,iteration_count2) def write_to_alorithms_table(task_id, schedule1, schedule2): from ..models import Algorithm from ..", "task_table_with_coefficient = calculate_task_table_from_productivity_factors(sets[i], productivity_factors[i]) schedules_first_alg.append( A1(len(productivity_factors[i]), len(sets[i]), task_table_with_coefficient)) for i in range(len((sets))): task_table_with_coefficient", "Tq = T.copy() for i in range(len(k)): Tq[i] += k[i] x = [0]", "= get_finall_T(schedules_secoond_alg[i], productivity_factors[i]) optimizationed_schedule2,max_proj2,relative_projection2,iteration_count2 = create(keys2, ideal2, productivity_factors[i], final_T_second) print(\"Iteration count 2 {}\".format(iteration_count2))", "type(schedule1[0]), schedule1[i][0]), i) #print('2 len {0}, type {1} schedule {2}'.format(len(schedule2), type(schedule2[0]), schedule2[i][0])) sched_JSON1", "schedule2[i][0])) sched_JSON1 = json.dumps(schedule1[i]) sched_JSON2 = json.dumps(schedule2[i]) alg = Algorithm(task_id=task_id, initial_timetable_first_alg=sched_JSON1, initial_timetable_second_alg=sched_JSON2) db.session.add(alg)", "of task. k - vector productivity factors # transform two vector to matrix", "row.append(1 / table[i, j]) newtable.append(row) newtable = np.array(newtable) return newtable def output_result_algorithm(result): for", "from .optimization_algorithms import get_finall_T, create import time schedules_first_alg = [] schedules_secoond_alg = []", "from DB # Run algorithms # Write to algorithm table write_to_alorithms_table(task_id, schedules_first_alg, schedules_secoond_alg)", "x = [0] * len(k) counter = 0 sigma2 = round(sigma, 0) sigma2", "x[i] * k[i] print(\"X = \", x) return x, FirstT def run_algorithms(productivity_factors, sets,", "json from .. import db algo = json.dumps(algorithm) tsk = Task.query.filter_by(id=task_id).first() tsk.first_Optimization =", "<reponame>mcxemic/Graduate_work<filename>Graduate_work/main/algorithms.py import numpy as np def calculate_task_table_from_productivity_factors(tasks_lists, productivity_factors): # p - count of", "+= k[index] counter += 1 print(counter) print(\"X = \", x) return x def", "task_table_with_coefficient = calculate_task_table_from_productivity_factors(sets[i], productivity_factors[i]) C_foreach_machine = list(map(lambda i: C / i, productivity_factors[i])) schedules_secoond_alg.append(A2(len(productivity_factors[i]),", "j in range(count_of_tasks): index = list_of_used_time_of_every_machine.index(min(list_of_used_time_of_every_machine)) list_of_used_time_of_every_machine[index] += np.asscalar(task_table_with_coefficient[j][index]) task_of_machine[index].update({j + 1: np.asscalar(task_table_with_coefficient[j][index])})", "* k[i] print(\"X = \", x) return x, FirstT def run_algorithms(productivity_factors, sets, task_id,", "productivity_factors[i], final_T_second) print(\"Iteration count 2 {}\".format(iteration_count2)) stop2 = time.time() write_to_optimization_table(task_id,optimizationed_schedule2,max_proj2,stop2-start2,relative_projection2,iteration_count2) def write_to_alorithms_table(task_id, schedule1,", "for i in range(len((sets))): task_table_with_coefficient = calculate_task_table_from_productivity_factors(sets[i], productivity_factors[i]) C_foreach_machine = list(map(lambda i: C", "write_to_optimization_table(task_id,algorithm,projection,runtime,relative_projection,iteration_count): from ..models import Task import json from .. import db algo =", "FirstT def run_algorithms(productivity_factors, sets, task_id, C): from .optimization_algorithms import get_finall_T, create import time", "print(\"Iteration count 2 {}\".format(iteration_count2)) stop2 = time.time() write_to_optimization_table(task_id,optimizationed_schedule2,max_proj2,stop2-start2,relative_projection2,iteration_count2) def write_to_alorithms_table(task_id, schedule1, schedule2): from", "productivity_factors[i]) C_foreach_machine = list(map(lambda i: C / i, productivity_factors[i])) schedules_secoond_alg.append(A2(len(productivity_factors[i]), len(sets[i]), task_table_with_coefficient, sets[i],", "newtable = [] for i in range(table.shape[0]): row = [] for j in", "np.asscalar(task_table_with_coefficient[j][index])}) output_result_algorithm(task_of_machine) return task_of_machine def A2(count_of_machine, count_of_task, table, tasks_list, C_foreach_machine): task_of_machine = []", "+= x[i] * k[i] print(\"X = \", x) return x, FirstT def run_algorithms(productivity_factors,", "tasks_list[j] task_of_machine[index].update({j + 1: np.asscalar(table[j][index])}) # output_result_algorithm(task_of_machine) return task_of_machine def optimization2(k, e, sigma,", "= \", x) return x, FirstT def run_algorithms(productivity_factors, sets, task_id, C): from .optimization_algorithms", "productivity output_table = [] productivity_factors.sort() tasks_lists.sort() tasks_lists.reverse() # print(productivity_factors, tasks_lists) for j in", "in range(len(productivity_factors)): row = [] for i in range(len(tasks_lists)): row.append(tasks_lists[i] * productivity_factors[j]) output_table.append(row)", "count_of_tasks, task_table_with_coefficient): task_of_machine = [] list_of_used_time_of_every_machine = list(count_of_machine * [0]) # create dict", "# index with max f list_of_used_time_of_every_machine[index] += np.asscalar(table[j][index]) # fill C C_foreach_machine[index] -=", ".. import db algo = json.dumps(algorithm) tsk = Task.query.filter_by(id=task_id).first() tsk.first_Optimization = algo tsk.first_projection", "= list(map(lambda i: C / i, productivity_factors[i])) schedules_secoond_alg.append(A2(len(productivity_factors[i]), len(sets[i]), task_table_with_coefficient, sets[i], C_foreach_machine)) #", "productivity_factors[i])) schedules_secoond_alg.append(A2(len(productivity_factors[i]), len(sets[i]), task_table_with_coefficient, sets[i], C_foreach_machine)) # Get data from DB # Run", "[] for i in range(len(tasks_lists)): row.append(tasks_lists[i] * productivity_factors[j]) output_table.append(row) output_table = np.array(output_table) output_table", "i in range(len((sets))): task_table_with_coefficient = calculate_task_table_from_productivity_factors(sets[i], productivity_factors[i]) C_foreach_machine = list(map(lambda i: C /", "schedule1[i][0]), i) #print('2 len {0}, type {1} schedule {2}'.format(len(schedule2), type(schedule2[0]), schedule2[i][0])) sched_JSON1 =", "productivity_factors.sort() tasks_lists.sort() tasks_lists.reverse() # print(productivity_factors, tasks_lists) for j in range(len(productivity_factors)): row = []", "the Heaven for j in range(count_of_tasks): index = list_of_used_time_of_every_machine.index(min(list_of_used_time_of_every_machine)) list_of_used_time_of_every_machine[index] += np.asscalar(task_table_with_coefficient[j][index]) task_of_machine[index].update({j", "= {} task_of_machine.append(machine) for j in range(0, count_of_task): index = C_foreach_machine.index(max(C_foreach_machine)) # index", "create optimization for i in range(len(sets)): start1 = time.time() final_T_first, keys1, ideal1 =", "[0]) # create dict for every machine in task for _ in range(0,", "in range(sigma2): index = Tq.index(min(Tq)) Tq[index] += k[index] x[index] += 1 for i", "[0]) #print(\"tasks\" + tasks_list) for _ in range(0, count_of_machine): machine = {} task_of_machine.append(machine)", "+= k[i] x = [0] * len(k) sigma2 = round(sigma, 0) print(int(sigma2)) sigma2", "+= np.asscalar(table[j][index]) # fill C C_foreach_machine[index] -= tasks_list[j] task_of_machine[index].update({j + 1: np.asscalar(table[j][index])}) #", "i in range(len(k)): T[i] += x[i] * k[i] print(\"X = \", x) return", "for i in range(table.shape[0]): row = [] for j in range(table.shape[1]): row.append(1 /", "range(sigma2): for i in range(len(k)): opt[i] = k[i] * (e[i] - x[i]) index", "range(len(k)): T.append((C - k[i] * e[i])) FirstT = T.copy() Tq = T.copy() for", "#print(\"tasks\" + tasks_list) for _ in range(0, count_of_machine): machine = {} task_of_machine.append(machine) for", "optimization1(sigma, e, k, C): print('\\n----------------------------------------------------------------') print('First optimization') T = [] for i in", "/ table[i, j]) newtable.append(row) newtable = np.array(newtable) return newtable def output_result_algorithm(result): for i", "+ 1, i[1]) def A1(count_of_machine, count_of_tasks, task_table_with_coefficient): task_of_machine = [] list_of_used_time_of_every_machine = list(count_of_machine", "counter += 1 print(counter) print(\"X = \", x) return x def optimization1(sigma, e,", "pass # print('Machine ', i[0] + 1, i[1]) def A1(count_of_machine, count_of_tasks, task_table_with_coefficient): task_of_machine", "= int(sigma2) print(int(sigma2)) for i in range(sigma2): for i in range(len(k)): opt[i] =", "for _ in range(0, count_of_machine): machine = {} task_of_machine.append(machine) # distribute tasks for", "in range(0, count_of_task): index = C_foreach_machine.index(max(C_foreach_machine)) # index with max f list_of_used_time_of_every_machine[index] +=", "= opt.index(max(opt)) x[index] += 1 T[index] += k[index] counter += 1 print(counter) print(\"X", "db.session.commit() def write_to_optimization_table(task_id,algorithm,projection,runtime,relative_projection,iteration_count): from ..models import Task import json from .. import db", "import json from .. import db algo = json.dumps(algorithm) tsk = Task.query.filter_by(id=task_id).first() tsk.first_Optimization", "i: C / i, productivity_factors[i])) schedules_secoond_alg.append(A2(len(productivity_factors[i]), len(sets[i]), task_table_with_coefficient, sets[i], C_foreach_machine)) # Get data", "write_to_optimization_table(task_id, optimizationed_schedule1, max_proj1, stop1 - start1,relative_projection1,iteration_count1) start2 = time.time() final_T_second, keys2, ideal2 =", "list_of_used_time_of_every_machine[index] += np.asscalar(table[j][index]) # fill C C_foreach_machine[index] -= tasks_list[j] task_of_machine[index].update({j + 1: np.asscalar(table[j][index])})", "range(len(sets)): start1 = time.time() final_T_first, keys1, ideal1 = get_finall_T(schedules_first_alg[i], productivity_factors[i]) optimizationed_schedule1,max_proj1,relative_projection1,iteration_count1 = create(keys1,", "1 print(counter) print(\"X = \", x) return x def optimization1(sigma, e, k, C):", "def write_to_optimization_table(task_id,algorithm,projection,runtime,relative_projection,iteration_count): from ..models import Task import json from .. import db algo", "productivity_factors[i]) schedules_first_alg.append( A1(len(productivity_factors[i]), len(sets[i]), task_table_with_coefficient)) for i in range(len((sets))): task_table_with_coefficient = calculate_task_table_from_productivity_factors(sets[i], productivity_factors[i])", "# distribute tasks for every machine with magic algorithms from the Heaven for", "schedules_first_alg, schedules_secoond_alg) # create optimization for i in range(len(sets)): start1 = time.time() final_T_first,", "i in enumerate(result): pass # print('Machine ', i[0] + 1, i[1]) def A1(count_of_machine,", "len(sets[i]), task_table_with_coefficient, sets[i], C_foreach_machine)) # Get data from DB # Run algorithms #", "x[index] += 1 T[index] += k[index] counter += 1 print(counter) print(\"X = \",", "return task_of_machine def A2(count_of_machine, count_of_task, table, tasks_list, C_foreach_machine): task_of_machine = [] list_of_used_time_of_every_machine =", "= create(keys1, ideal1, productivity_factors[i], final_T_first) print(\"Iteration count 1 {}\".format(iteration_count1)) stop1 = time.time() write_to_optimization_table(task_id,", "j]) newtable.append(row) newtable = np.array(newtable) return newtable def output_result_algorithm(result): for i in enumerate(result):", "np def calculate_task_table_from_productivity_factors(tasks_lists, productivity_factors): # p - count of task. k - vector", "for i in enumerate(result): pass # print('Machine ', i[0] + 1, i[1]) def", ".optimization_algorithms import get_finall_T, create import time schedules_first_alg = [] schedules_secoond_alg = [] for", "task_of_machine[index].update({j + 1: np.asscalar(task_table_with_coefficient[j][index])}) output_result_algorithm(task_of_machine) return task_of_machine def A2(count_of_machine, count_of_task, table, tasks_list, C_foreach_machine):", "i in range(len(k)): T.append((C - k[i] * e[i])) opt = [0] * len(k)", "i in range(len(k)): T.append((C - k[i] * e[i])) FirstT = T.copy() Tq =", "get_finall_T, create import time schedules_first_alg = [] schedules_secoond_alg = [] for i in", "final_T_second) print(\"Iteration count 2 {}\".format(iteration_count2)) stop2 = time.time() write_to_optimization_table(task_id,optimizationed_schedule2,max_proj2,stop2-start2,relative_projection2,iteration_count2) def write_to_alorithms_table(task_id, schedule1, schedule2):", "= [] list_of_used_time_of_every_machine = list(count_of_machine * [0]) # create dict for every machine", "create dict for every machine in task for _ in range(0, count_of_machine): machine", "= 0 sigma2 = round(sigma, 0) sigma2 = int(sigma2) print(int(sigma2)) for i in", "len(k) sigma2 = round(sigma, 0) print(int(sigma2)) sigma2 = int(sigma2) print(int(sigma2)) for i in", "- vector productivity factors # transform two vector to matrix with task *", "data from DB # Run algorithms # Write to algorithm table write_to_alorithms_table(task_id, schedules_first_alg,", "initial_timetable_first_alg=sched_JSON1, initial_timetable_second_alg=sched_JSON2) db.session.add(alg) db.session.commit() def write_to_optimization_table(task_id,algorithm,projection,runtime,relative_projection,iteration_count): from ..models import Task import json from", "print('schedule1 {0} schedule {1}'.format(schedule1, schedule2)) # print('1 len {0}, type {1} schedule {2}'.format(len(schedule1),", "DB # Run algorithms # Write to algorithm table write_to_alorithms_table(task_id, schedules_first_alg, schedules_secoond_alg) #", "for j in range(table.shape[1]): row.append(1 / table[i, j]) newtable.append(row) newtable = np.array(newtable) return", ".. import db import json for i in range(len(schedule1)): # print('schedule1 {0} schedule", "{1} schedule {2}'.format(len(schedule2), type(schedule2[0]), schedule2[i][0])) sched_JSON1 = json.dumps(schedule1[i]) sched_JSON2 = json.dumps(schedule2[i]) alg =", "to algorithm table write_to_alorithms_table(task_id, schedules_first_alg, schedules_secoond_alg) # create optimization for i in range(len(sets)):", "{1}'.format(schedule1, schedule2)) # print('1 len {0}, type {1} schedule {2}'.format(len(schedule1), type(schedule1[0]), schedule1[i][0]), i)", "list_of_used_time_of_every_machine.index(min(list_of_used_time_of_every_machine)) list_of_used_time_of_every_machine[index] += np.asscalar(task_table_with_coefficient[j][index]) task_of_machine[index].update({j + 1: np.asscalar(task_table_with_coefficient[j][index])}) output_result_algorithm(task_of_machine) return task_of_machine def A2(count_of_machine,", "calculate_task_table_from_productivity_factors(sets[i], productivity_factors[i]) schedules_first_alg.append( A1(len(productivity_factors[i]), len(sets[i]), task_table_with_coefficient)) for i in range(len((sets))): task_table_with_coefficient = calculate_task_table_from_productivity_factors(sets[i],", "list_of_used_time_of_every_machine = list(count_of_machine * [0]) #print(\"tasks\" + tasks_list) for _ in range(0, count_of_machine):", "schedules_secoond_alg.append(A2(len(productivity_factors[i]), len(sets[i]), task_table_with_coefficient, sets[i], C_foreach_machine)) # Get data from DB # Run algorithms", "# Get data from DB # Run algorithms # Write to algorithm table", "ideal1 = get_finall_T(schedules_first_alg[i], productivity_factors[i]) optimizationed_schedule1,max_proj1,relative_projection1,iteration_count1 = create(keys1, ideal1, productivity_factors[i], final_T_first) print(\"Iteration count 1", "schedules_secoond_alg) # create optimization for i in range(len(sets)): start1 = time.time() final_T_first, keys1,", "from .. import db algo = json.dumps(algorithm) tsk = Task.query.filter_by(id=task_id).first() tsk.first_Optimization = algo", "+ 1: np.asscalar(task_table_with_coefficient[j][index])}) output_result_algorithm(task_of_machine) return task_of_machine def A2(count_of_machine, count_of_task, table, tasks_list, C_foreach_machine): task_of_machine", "alg = Algorithm(task_id=task_id, initial_timetable_first_alg=sched_JSON1, initial_timetable_second_alg=sched_JSON2) db.session.add(alg) db.session.commit() def write_to_optimization_table(task_id,algorithm,projection,runtime,relative_projection,iteration_count): from ..models import Task", "[] productivity_factors.sort() tasks_lists.sort() tasks_lists.reverse() # print(productivity_factors, tasks_lists) for j in range(len(productivity_factors)): row =", "i in range(table.shape[0]): row = [] for j in range(table.shape[1]): row.append(1 / table[i,", "= [] list_of_used_time_of_every_machine = list(count_of_machine * [0]) #print(\"tasks\" + tasks_list) for _ in", "= int(sigma2) print(int(sigma2)) for i in range(sigma2): index = Tq.index(min(Tq)) Tq[index] += k[index]", "in range(len(k)): T.append((C - k[i] * e[i])) FirstT = T.copy() Tq = T.copy()", "= T.copy() for i in range(len(k)): Tq[i] += k[i] x = [0] *", "= output_table.T return output_table def calculate_second_table(table): newtable = [] for i in range(table.shape[0]):", "* len(k) sigma2 = round(sigma, 0) print(int(sigma2)) sigma2 = int(sigma2) print(int(sigma2)) for i", "* e[i])) opt = [0] * len(k) x = [0] * len(k) counter", "T[i] += x[i] * k[i] print(\"X = \", x) return x, FirstT def", "= time.time() write_to_optimization_table(task_id, optimizationed_schedule1, max_proj1, stop1 - start1,relative_projection1,iteration_count1) start2 = time.time() final_T_second, keys2,", "opt = [0] * len(k) x = [0] * len(k) counter = 0", "0 sigma2 = round(sigma, 0) sigma2 = int(sigma2) print(int(sigma2)) for i in range(sigma2):", "i in range(sigma2): index = Tq.index(min(Tq)) Tq[index] += k[index] x[index] += 1 for", "in range(len(k)): T[i] += x[i] * k[i] print(\"X = \", x) return x,", "= get_finall_T(schedules_first_alg[i], productivity_factors[i]) optimizationed_schedule1,max_proj1,relative_projection1,iteration_count1 = create(keys1, ideal1, productivity_factors[i], final_T_first) print(\"Iteration count 1 {}\".format(iteration_count1))", "= create(keys2, ideal2, productivity_factors[i], final_T_second) print(\"Iteration count 2 {}\".format(iteration_count2)) stop2 = time.time() write_to_optimization_table(task_id,optimizationed_schedule2,max_proj2,stop2-start2,relative_projection2,iteration_count2)", "range(len(tasks_lists)): row.append(tasks_lists[i] * productivity_factors[j]) output_table.append(row) output_table = np.array(output_table) output_table = output_table.T return output_table", "for every machine in task for _ in range(0, count_of_machine): machine = {}", "table[i, j]) newtable.append(row) newtable = np.array(newtable) return newtable def output_result_algorithm(result): for i in", "= list_of_used_time_of_every_machine.index(min(list_of_used_time_of_every_machine)) list_of_used_time_of_every_machine[index] += np.asscalar(task_table_with_coefficient[j][index]) task_of_machine[index].update({j + 1: np.asscalar(task_table_with_coefficient[j][index])}) output_result_algorithm(task_of_machine) return task_of_machine def", "+= np.asscalar(task_table_with_coefficient[j][index]) task_of_machine[index].update({j + 1: np.asscalar(task_table_with_coefficient[j][index])}) output_result_algorithm(task_of_machine) return task_of_machine def A2(count_of_machine, count_of_task, table,", "fill C C_foreach_machine[index] -= tasks_list[j] task_of_machine[index].update({j + 1: np.asscalar(table[j][index])}) # output_result_algorithm(task_of_machine) return task_of_machine", "x) return x, FirstT def run_algorithms(productivity_factors, sets, task_id, C): from .optimization_algorithms import get_finall_T,", "table write_to_alorithms_table(task_id, schedules_first_alg, schedules_secoond_alg) # create optimization for i in range(len(sets)): start1 =", "create(keys1, ideal1, productivity_factors[i], final_T_first) print(\"Iteration count 1 {}\".format(iteration_count1)) stop1 = time.time() write_to_optimization_table(task_id, optimizationed_schedule1,", "k[index] x[index] += 1 for i in range(len(k)): T[i] += x[i] * k[i]", "Algorithm from .. import db import json for i in range(len(schedule1)): # print('schedule1", "len {0}, type {1} schedule {2}'.format(len(schedule1), type(schedule1[0]), schedule1[i][0]), i) #print('2 len {0}, type", "return x def optimization1(sigma, e, k, C): print('\\n----------------------------------------------------------------') print('First optimization') T = []", "productivity factors # transform two vector to matrix with task * productivity output_table", "type(schedule2[0]), schedule2[i][0])) sched_JSON1 = json.dumps(schedule1[i]) sched_JSON2 = json.dumps(schedule2[i]) alg = Algorithm(task_id=task_id, initial_timetable_first_alg=sched_JSON1, initial_timetable_second_alg=sched_JSON2)", "algorithms from the Heaven for j in range(count_of_tasks): index = list_of_used_time_of_every_machine.index(min(list_of_used_time_of_every_machine)) list_of_used_time_of_every_machine[index] +=", "-= tasks_list[j] task_of_machine[index].update({j + 1: np.asscalar(table[j][index])}) # output_result_algorithm(task_of_machine) return task_of_machine def optimization2(k, e,", "for _ in range(0, count_of_machine): machine = {} task_of_machine.append(machine) for j in range(0,", "len(k) x = [0] * len(k) counter = 0 sigma2 = round(sigma, 0)", "in enumerate(result): pass # print('Machine ', i[0] + 1, i[1]) def A1(count_of_machine, count_of_tasks,", "= [0] * len(k) sigma2 = round(sigma, 0) print(int(sigma2)) sigma2 = int(sigma2) print(int(sigma2))", "def calculate_second_table(table): newtable = [] for i in range(table.shape[0]): row = [] for", "output_table = [] productivity_factors.sort() tasks_lists.sort() tasks_lists.reverse() # print(productivity_factors, tasks_lists) for j in range(len(productivity_factors)):", "for j in range(len(productivity_factors)): row = [] for i in range(len(tasks_lists)): row.append(tasks_lists[i] *", "start2 = time.time() final_T_second, keys2, ideal2 = get_finall_T(schedules_secoond_alg[i], productivity_factors[i]) optimizationed_schedule2,max_proj2,relative_projection2,iteration_count2 = create(keys2, ideal2,", "two vector to matrix with task * productivity output_table = [] productivity_factors.sort() tasks_lists.sort()", "[] for i in range(len(k)): T.append((C - k[i] * e[i])) FirstT = T.copy()", "{2}'.format(len(schedule2), type(schedule2[0]), schedule2[i][0])) sched_JSON1 = json.dumps(schedule1[i]) sched_JSON2 = json.dumps(schedule2[i]) alg = Algorithm(task_id=task_id, initial_timetable_first_alg=sched_JSON1,", "j in range(table.shape[1]): row.append(1 / table[i, j]) newtable.append(row) newtable = np.array(newtable) return newtable", "transform two vector to matrix with task * productivity output_table = [] productivity_factors.sort()", "write_to_alorithms_table(task_id, schedule1, schedule2): from ..models import Algorithm from .. import db import json", "algo = json.dumps(algorithm) tsk = Task.query.filter_by(id=task_id).first() tsk.first_Optimization = algo tsk.first_projection = projection tsk.first_lead_time", "import get_finall_T, create import time schedules_first_alg = [] schedules_secoond_alg = [] for i", "i in range(len(sets)): start1 = time.time() final_T_first, keys1, ideal1 = get_finall_T(schedules_first_alg[i], productivity_factors[i]) optimizationed_schedule1,max_proj1,relative_projection1,iteration_count1", "# Write to algorithm table write_to_alorithms_table(task_id, schedules_first_alg, schedules_secoond_alg) # create optimization for i", "for i in range(len(schedule1)): # print('schedule1 {0} schedule {1}'.format(schedule1, schedule2)) # print('1 len", "sigma2 = int(sigma2) print(int(sigma2)) for i in range(sigma2): index = Tq.index(min(Tq)) Tq[index] +=", "task_of_machine def optimization2(k, e, sigma, C): print('\\n----------------------------------------------------------------') print('Second optimization') T = [] for", "newtable = np.array(newtable) return newtable def output_result_algorithm(result): for i in enumerate(result): pass #", "* e[i])) FirstT = T.copy() Tq = T.copy() for i in range(len(k)): Tq[i]", "range(len((sets))): task_table_with_coefficient = calculate_task_table_from_productivity_factors(sets[i], productivity_factors[i]) C_foreach_machine = list(map(lambda i: C / i, productivity_factors[i]))", "# output_result_algorithm(task_of_machine) return task_of_machine def optimization2(k, e, sigma, C): print('\\n----------------------------------------------------------------') print('Second optimization') T", "T = [] for i in range(len(k)): T.append((C - k[i] * e[i])) opt", "[0] * len(k) sigma2 = round(sigma, 0) print(int(sigma2)) sigma2 = int(sigma2) print(int(sigma2)) for", "for i in range(len(k)): T[i] += x[i] * k[i] print(\"X = \", x)", "= C_foreach_machine.index(max(C_foreach_machine)) # index with max f list_of_used_time_of_every_machine[index] += np.asscalar(table[j][index]) # fill C", "A1(len(productivity_factors[i]), len(sets[i]), task_table_with_coefficient)) for i in range(len((sets))): task_table_with_coefficient = calculate_task_table_from_productivity_factors(sets[i], productivity_factors[i]) C_foreach_machine =", "optimization2(k, e, sigma, C): print('\\n----------------------------------------------------------------') print('Second optimization') T = [] for i in", "keys2, ideal2 = get_finall_T(schedules_secoond_alg[i], productivity_factors[i]) optimizationed_schedule2,max_proj2,relative_projection2,iteration_count2 = create(keys2, ideal2, productivity_factors[i], final_T_second) print(\"Iteration count", "C_foreach_machine): task_of_machine = [] list_of_used_time_of_every_machine = list(count_of_machine * [0]) #print(\"tasks\" + tasks_list) for", "C): from .optimization_algorithms import get_finall_T, create import time schedules_first_alg = [] schedules_secoond_alg =", "* [0]) #print(\"tasks\" + tasks_list) for _ in range(0, count_of_machine): machine = {}", "create(keys2, ideal2, productivity_factors[i], final_T_second) print(\"Iteration count 2 {}\".format(iteration_count2)) stop2 = time.time() write_to_optimization_table(task_id,optimizationed_schedule2,max_proj2,stop2-start2,relative_projection2,iteration_count2) def", "= [] schedules_secoond_alg = [] for i in range(len(sets)): task_table_with_coefficient = calculate_task_table_from_productivity_factors(sets[i], productivity_factors[i])", "+ 1: np.asscalar(table[j][index])}) # output_result_algorithm(task_of_machine) return task_of_machine def optimization2(k, e, sigma, C): print('\\n----------------------------------------------------------------')", "j in range(0, count_of_task): index = C_foreach_machine.index(max(C_foreach_machine)) # index with max f list_of_used_time_of_every_machine[index]", "tasks_lists.sort() tasks_lists.reverse() # print(productivity_factors, tasks_lists) for j in range(len(productivity_factors)): row = [] for", "def optimization1(sigma, e, k, C): print('\\n----------------------------------------------------------------') print('First optimization') T = [] for i", "in range(len(tasks_lists)): row.append(tasks_lists[i] * productivity_factors[j]) output_table.append(row) output_table = np.array(output_table) output_table = output_table.T return", "- k[i] * e[i])) opt = [0] * len(k) x = [0] *", "print('1 len {0}, type {1} schedule {2}'.format(len(schedule1), type(schedule1[0]), schedule1[i][0]), i) #print('2 len {0},", "import numpy as np def calculate_task_table_from_productivity_factors(tasks_lists, productivity_factors): # p - count of task.", "= np.array(output_table) output_table = output_table.T return output_table def calculate_second_table(table): newtable = [] for", "# print('1 len {0}, type {1} schedule {2}'.format(len(schedule1), type(schedule1[0]), schedule1[i][0]), i) #print('2 len", "* len(k) counter = 0 sigma2 = round(sigma, 0) sigma2 = int(sigma2) print(int(sigma2))", "x) return x def optimization1(sigma, e, k, C): print('\\n----------------------------------------------------------------') print('First optimization') T =", "stop1 = time.time() write_to_optimization_table(task_id, optimizationed_schedule1, max_proj1, stop1 - start1,relative_projection1,iteration_count1) start2 = time.time() final_T_second,", "f list_of_used_time_of_every_machine[index] += np.asscalar(table[j][index]) # fill C C_foreach_machine[index] -= tasks_list[j] task_of_machine[index].update({j + 1:", "schedules_secoond_alg = [] for i in range(len(sets)): task_table_with_coefficient = calculate_task_table_from_productivity_factors(sets[i], productivity_factors[i]) schedules_first_alg.append( A1(len(productivity_factors[i]),", "# print('schedule1 {0} schedule {1}'.format(schedule1, schedule2)) # print('1 len {0}, type {1} schedule", "k[i] x = [0] * len(k) sigma2 = round(sigma, 0) print(int(sigma2)) sigma2 =", "= [] for i in range(table.shape[0]): row = [] for j in range(table.shape[1]):", "task_of_machine = [] list_of_used_time_of_every_machine = list(count_of_machine * [0]) #print(\"tasks\" + tasks_list) for _", "{0}, type {1} schedule {2}'.format(len(schedule2), type(schedule2[0]), schedule2[i][0])) sched_JSON1 = json.dumps(schedule1[i]) sched_JSON2 = json.dumps(schedule2[i])", "with max f list_of_used_time_of_every_machine[index] += np.asscalar(table[j][index]) # fill C C_foreach_machine[index] -= tasks_list[j] task_of_machine[index].update({j", "= round(sigma, 0) print(int(sigma2)) sigma2 = int(sigma2) print(int(sigma2)) for i in range(sigma2): index", "in range(len(k)): Tq[i] += k[i] x = [0] * len(k) sigma2 = round(sigma,", "with task * productivity output_table = [] productivity_factors.sort() tasks_lists.sort() tasks_lists.reverse() # print(productivity_factors, tasks_lists)", "time.time() write_to_optimization_table(task_id, optimizationed_schedule1, max_proj1, stop1 - start1,relative_projection1,iteration_count1) start2 = time.time() final_T_second, keys2, ideal2", "- k[i] * e[i])) FirstT = T.copy() Tq = T.copy() for i in", "- x[i]) index = opt.index(max(opt)) x[index] += 1 T[index] += k[index] counter +=", "machine in task for _ in range(0, count_of_machine): machine = {} task_of_machine.append(machine) #", "* (e[i] - x[i]) index = opt.index(max(opt)) x[index] += 1 T[index] += k[index]", "in range(len(sets)): task_table_with_coefficient = calculate_task_table_from_productivity_factors(sets[i], productivity_factors[i]) schedules_first_alg.append( A1(len(productivity_factors[i]), len(sets[i]), task_table_with_coefficient)) for i in", "{0} schedule {1}'.format(schedule1, schedule2)) # print('1 len {0}, type {1} schedule {2}'.format(len(schedule1), type(schedule1[0]),", "for j in range(0, count_of_task): index = C_foreach_machine.index(max(C_foreach_machine)) # index with max f", "e, k, C): print('\\n----------------------------------------------------------------') print('First optimization') T = [] for i in range(len(k)):", "- count of task. k - vector productivity factors # transform two vector", "index = list_of_used_time_of_every_machine.index(min(list_of_used_time_of_every_machine)) list_of_used_time_of_every_machine[index] += np.asscalar(task_table_with_coefficient[j][index]) task_of_machine[index].update({j + 1: np.asscalar(task_table_with_coefficient[j][index])}) output_result_algorithm(task_of_machine) return task_of_machine", "ideal1, productivity_factors[i], final_T_first) print(\"Iteration count 1 {}\".format(iteration_count1)) stop1 = time.time() write_to_optimization_table(task_id, optimizationed_schedule1, max_proj1,", "schedule {1}'.format(schedule1, schedule2)) # print('1 len {0}, type {1} schedule {2}'.format(len(schedule1), type(schedule1[0]), schedule1[i][0]),", "tasks_lists.reverse() # print(productivity_factors, tasks_lists) for j in range(len(productivity_factors)): row = [] for i", "C_foreach_machine)) # Get data from DB # Run algorithms # Write to algorithm", "= algo tsk.first_projection = projection tsk.first_lead_time = runtime tsk.first_relatively_projection = relative_projection tsk.first_iteration_count =", "type {1} schedule {2}'.format(len(schedule2), type(schedule2[0]), schedule2[i][0])) sched_JSON1 = json.dumps(schedule1[i]) sched_JSON2 = json.dumps(schedule2[i]) alg", "e[i])) FirstT = T.copy() Tq = T.copy() for i in range(len(k)): Tq[i] +=", "len(k) counter = 0 sigma2 = round(sigma, 0) sigma2 = int(sigma2) print(int(sigma2)) for", "in range(len(k)): T.append((C - k[i] * e[i])) opt = [0] * len(k) x", "[] for i in range(table.shape[0]): row = [] for j in range(table.shape[1]): row.append(1", "start1,relative_projection1,iteration_count1) start2 = time.time() final_T_second, keys2, ideal2 = get_finall_T(schedules_secoond_alg[i], productivity_factors[i]) optimizationed_schedule2,max_proj2,relative_projection2,iteration_count2 = create(keys2,", "e, sigma, C): print('\\n----------------------------------------------------------------') print('Second optimization') T = [] for i in range(len(k)):", "def output_result_algorithm(result): for i in enumerate(result): pass # print('Machine ', i[0] + 1,", "x[i]) index = opt.index(max(opt)) x[index] += 1 T[index] += k[index] counter += 1", "range(table.shape[0]): row = [] for j in range(table.shape[1]): row.append(1 / table[i, j]) newtable.append(row)", "in range(len(k)): opt[i] = k[i] * (e[i] - x[i]) index = opt.index(max(opt)) x[index]", "list(map(lambda i: C / i, productivity_factors[i])) schedules_secoond_alg.append(A2(len(productivity_factors[i]), len(sets[i]), task_table_with_coefficient, sets[i], C_foreach_machine)) # Get", "json.dumps(algorithm) tsk = Task.query.filter_by(id=task_id).first() tsk.first_Optimization = algo tsk.first_projection = projection tsk.first_lead_time = runtime", "every machine with magic algorithms from the Heaven for j in range(count_of_tasks): index", "{2}'.format(len(schedule1), type(schedule1[0]), schedule1[i][0]), i) #print('2 len {0}, type {1} schedule {2}'.format(len(schedule2), type(schedule2[0]), schedule2[i][0]))", "machine = {} task_of_machine.append(machine) for j in range(0, count_of_task): index = C_foreach_machine.index(max(C_foreach_machine)) #", "A1(count_of_machine, count_of_tasks, task_table_with_coefficient): task_of_machine = [] list_of_used_time_of_every_machine = list(count_of_machine * [0]) # create", "[] list_of_used_time_of_every_machine = list(count_of_machine * [0]) # create dict for every machine in", "tsk.first_Optimization = algo tsk.first_projection = projection tsk.first_lead_time = runtime tsk.first_relatively_projection = relative_projection tsk.first_iteration_count", "return x, FirstT def run_algorithms(productivity_factors, sets, task_id, C): from .optimization_algorithms import get_finall_T, create", "i in range(sigma2): for i in range(len(k)): opt[i] = k[i] * (e[i] -", "k[i] print(\"X = \", x) return x, FirstT def run_algorithms(productivity_factors, sets, task_id, C):", "# create optimization for i in range(len(sets)): start1 = time.time() final_T_first, keys1, ideal1", "output_result_algorithm(task_of_machine) return task_of_machine def optimization2(k, e, sigma, C): print('\\n----------------------------------------------------------------') print('Second optimization') T =", "= \", x) return x def optimization1(sigma, e, k, C): print('\\n----------------------------------------------------------------') print('First optimization')", "for i in range(len(k)): opt[i] = k[i] * (e[i] - x[i]) index =", "{}\".format(iteration_count2)) stop2 = time.time() write_to_optimization_table(task_id,optimizationed_schedule2,max_proj2,stop2-start2,relative_projection2,iteration_count2) def write_to_alorithms_table(task_id, schedule1, schedule2): from ..models import Algorithm", "tsk = Task.query.filter_by(id=task_id).first() tsk.first_Optimization = algo tsk.first_projection = projection tsk.first_lead_time = runtime tsk.first_relatively_projection", "task_id, C): from .optimization_algorithms import get_finall_T, create import time schedules_first_alg = [] schedules_secoond_alg", "create import time schedules_first_alg = [] schedules_secoond_alg = [] for i in range(len(sets)):", "return task_of_machine def optimization2(k, e, sigma, C): print('\\n----------------------------------------------------------------') print('Second optimization') T = []", "#print('2 len {0}, type {1} schedule {2}'.format(len(schedule2), type(schedule2[0]), schedule2[i][0])) sched_JSON1 = json.dumps(schedule1[i]) sched_JSON2", "= round(sigma, 0) sigma2 = int(sigma2) print(int(sigma2)) for i in range(sigma2): for i", "FirstT = T.copy() Tq = T.copy() for i in range(len(k)): Tq[i] += k[i]", "{} task_of_machine.append(machine) for j in range(0, count_of_task): index = C_foreach_machine.index(max(C_foreach_machine)) # index with", "1: np.asscalar(table[j][index])}) # output_result_algorithm(task_of_machine) return task_of_machine def optimization2(k, e, sigma, C): print('\\n----------------------------------------------------------------') print('Second", "= [0] * len(k) x = [0] * len(k) counter = 0 sigma2", "len(sets[i]), task_table_with_coefficient)) for i in range(len((sets))): task_table_with_coefficient = calculate_task_table_from_productivity_factors(sets[i], productivity_factors[i]) C_foreach_machine = list(map(lambda", "productivity_factors[i], final_T_first) print(\"Iteration count 1 {}\".format(iteration_count1)) stop1 = time.time() write_to_optimization_table(task_id, optimizationed_schedule1, max_proj1, stop1", "i in range(len(k)): opt[i] = k[i] * (e[i] - x[i]) index = opt.index(max(opt))", "= [] for i in range(len(tasks_lists)): row.append(tasks_lists[i] * productivity_factors[j]) output_table.append(row) output_table = np.array(output_table)", "write_to_optimization_table(task_id,optimizationed_schedule2,max_proj2,stop2-start2,relative_projection2,iteration_count2) def write_to_alorithms_table(task_id, schedule1, schedule2): from ..models import Algorithm from .. import db", "x = [0] * len(k) sigma2 = round(sigma, 0) print(int(sigma2)) sigma2 = int(sigma2)", "x[index] += 1 for i in range(len(k)): T[i] += x[i] * k[i] print(\"X", "for i in range(len(tasks_lists)): row.append(tasks_lists[i] * productivity_factors[j]) output_table.append(row) output_table = np.array(output_table) output_table =", "as np def calculate_task_table_from_productivity_factors(tasks_lists, productivity_factors): # p - count of task. k -", "= T.copy() Tq = T.copy() for i in range(len(k)): Tq[i] += k[i] x", "def write_to_alorithms_table(task_id, schedule1, schedule2): from ..models import Algorithm from .. import db import", "k[i] * e[i])) FirstT = T.copy() Tq = T.copy() for i in range(len(k)):", "start1 = time.time() final_T_first, keys1, ideal1 = get_finall_T(schedules_first_alg[i], productivity_factors[i]) optimizationed_schedule1,max_proj1,relative_projection1,iteration_count1 = create(keys1, ideal1,", "# fill C C_foreach_machine[index] -= tasks_list[j] task_of_machine[index].update({j + 1: np.asscalar(table[j][index])}) # output_result_algorithm(task_of_machine) return", "schedule {2}'.format(len(schedule1), type(schedule1[0]), schedule1[i][0]), i) #print('2 len {0}, type {1} schedule {2}'.format(len(schedule2), type(schedule2[0]),", "1 T[index] += k[index] counter += 1 print(counter) print(\"X = \", x) return", "import Task import json from .. import db algo = json.dumps(algorithm) tsk =", "= Task.query.filter_by(id=task_id).first() tsk.first_Optimization = algo tsk.first_projection = projection tsk.first_lead_time = runtime tsk.first_relatively_projection =", "{0}, type {1} schedule {2}'.format(len(schedule1), type(schedule1[0]), schedule1[i][0]), i) #print('2 len {0}, type {1}", "machine = {} task_of_machine.append(machine) # distribute tasks for every machine with magic algorithms", "= [] for i in range(len(sets)): task_table_with_coefficient = calculate_task_table_from_productivity_factors(sets[i], productivity_factors[i]) schedules_first_alg.append( A1(len(productivity_factors[i]), len(sets[i]),", "import time schedules_first_alg = [] schedules_secoond_alg = [] for i in range(len(sets)): task_table_with_coefficient", "i in range(len(tasks_lists)): row.append(tasks_lists[i] * productivity_factors[j]) output_table.append(row) output_table = np.array(output_table) output_table = output_table.T", "C C_foreach_machine[index] -= tasks_list[j] task_of_machine[index].update({j + 1: np.asscalar(table[j][index])}) # output_result_algorithm(task_of_machine) return task_of_machine def", "1: np.asscalar(task_table_with_coefficient[j][index])}) output_result_algorithm(task_of_machine) return task_of_machine def A2(count_of_machine, count_of_task, table, tasks_list, C_foreach_machine): task_of_machine =", "get_finall_T(schedules_first_alg[i], productivity_factors[i]) optimizationed_schedule1,max_proj1,relative_projection1,iteration_count1 = create(keys1, ideal1, productivity_factors[i], final_T_first) print(\"Iteration count 1 {}\".format(iteration_count1)) stop1", "k[index] counter += 1 print(counter) print(\"X = \", x) return x def optimization1(sigma,", "range(len(k)): Tq[i] += k[i] x = [0] * len(k) sigma2 = round(sigma, 0)", "0) print(int(sigma2)) sigma2 = int(sigma2) print(int(sigma2)) for i in range(sigma2): index = Tq.index(min(Tq))", "[] for i in range(len(sets)): task_table_with_coefficient = calculate_task_table_from_productivity_factors(sets[i], productivity_factors[i]) schedules_first_alg.append( A1(len(productivity_factors[i]), len(sets[i]), task_table_with_coefficient))", "calculate_second_table(table): newtable = [] for i in range(table.shape[0]): row = [] for j", "write_to_alorithms_table(task_id, schedules_first_alg, schedules_secoond_alg) # create optimization for i in range(len(sets)): start1 = time.time()" ]
[ "pagamento_despesa: return pagamento_despesa[0] return None class Meta: app_label = 'contrato' verbose_name = 'Despesa", "def __unicode__(self): return u'%s: %s' % (self.contrato.titulo, self.despesa.valor_total) def pagamento(self): pagamento_despesa = PagamentoDespesa.objects.filter(despesa=self.despesa)", "= PagamentoDespesa.objects.filter(despesa=self.despesa) if pagamento_despesa: return pagamento_despesa[0] return None class Meta: app_label = 'contrato'", "def pagamento(self): pagamento_despesa = PagamentoDespesa.objects.filter(despesa=self.despesa) if pagamento_despesa: return pagamento_despesa[0] return None class Meta:", "from django.db import models from gestao.contrato.models.contrato.Contrato import Contrato from gestao.financeiro.models.movimentacoes.Despesa import Despesa from", "contrato = models.ForeignKey(Contrato, verbose_name=\"Contrato\") despesa = models.ForeignKey(Despesa, verbose_name=\"Despesa\") def __unicode__(self): return u'%s: %s'", "import Despesa from gestao.financeiro.models.pagamento.PagamentoDespesa import PagamentoDespesa class ContratoDespesas(models.Model): contrato = models.ForeignKey(Contrato, verbose_name=\"Contrato\") despesa", "return pagamento_despesa[0] return None class Meta: app_label = 'contrato' verbose_name = 'Despesa do", "django.db import models from gestao.contrato.models.contrato.Contrato import Contrato from gestao.financeiro.models.movimentacoes.Despesa import Despesa from gestao.financeiro.models.pagamento.PagamentoDespesa", "models.ForeignKey(Despesa, verbose_name=\"Despesa\") def __unicode__(self): return u'%s: %s' % (self.contrato.titulo, self.despesa.valor_total) def pagamento(self): pagamento_despesa", "gestao.financeiro.models.pagamento.PagamentoDespesa import PagamentoDespesa class ContratoDespesas(models.Model): contrato = models.ForeignKey(Contrato, verbose_name=\"Contrato\") despesa = models.ForeignKey(Despesa, verbose_name=\"Despesa\")", "return None class Meta: app_label = 'contrato' verbose_name = 'Despesa do Contrato' verbose_name_plural", "= models.ForeignKey(Despesa, verbose_name=\"Despesa\") def __unicode__(self): return u'%s: %s' % (self.contrato.titulo, self.despesa.valor_total) def pagamento(self):", "pagamento_despesa = PagamentoDespesa.objects.filter(despesa=self.despesa) if pagamento_despesa: return pagamento_despesa[0] return None class Meta: app_label =", "% (self.contrato.titulo, self.despesa.valor_total) def pagamento(self): pagamento_despesa = PagamentoDespesa.objects.filter(despesa=self.despesa) if pagamento_despesa: return pagamento_despesa[0] return", "import models from gestao.contrato.models.contrato.Contrato import Contrato from gestao.financeiro.models.movimentacoes.Despesa import Despesa from gestao.financeiro.models.pagamento.PagamentoDespesa import", "from gestao.financeiro.models.pagamento.PagamentoDespesa import PagamentoDespesa class ContratoDespesas(models.Model): contrato = models.ForeignKey(Contrato, verbose_name=\"Contrato\") despesa = models.ForeignKey(Despesa,", "Contrato from gestao.financeiro.models.movimentacoes.Despesa import Despesa from gestao.financeiro.models.pagamento.PagamentoDespesa import PagamentoDespesa class ContratoDespesas(models.Model): contrato =", "gestao.contrato.models.contrato.Contrato import Contrato from gestao.financeiro.models.movimentacoes.Despesa import Despesa from gestao.financeiro.models.pagamento.PagamentoDespesa import PagamentoDespesa class ContratoDespesas(models.Model):", "if pagamento_despesa: return pagamento_despesa[0] return None class Meta: app_label = 'contrato' verbose_name =", "ContratoDespesas(models.Model): contrato = models.ForeignKey(Contrato, verbose_name=\"Contrato\") despesa = models.ForeignKey(Despesa, verbose_name=\"Despesa\") def __unicode__(self): return u'%s:", "coding: utf-8 -*- from django.db import models from gestao.contrato.models.contrato.Contrato import Contrato from gestao.financeiro.models.movimentacoes.Despesa", "None class Meta: app_label = 'contrato' verbose_name = 'Despesa do Contrato' verbose_name_plural =", "-*- coding: utf-8 -*- from django.db import models from gestao.contrato.models.contrato.Contrato import Contrato from", "verbose_name=\"Contrato\") despesa = models.ForeignKey(Despesa, verbose_name=\"Despesa\") def __unicode__(self): return u'%s: %s' % (self.contrato.titulo, self.despesa.valor_total)", "gestao.financeiro.models.movimentacoes.Despesa import Despesa from gestao.financeiro.models.pagamento.PagamentoDespesa import PagamentoDespesa class ContratoDespesas(models.Model): contrato = models.ForeignKey(Contrato, verbose_name=\"Contrato\")", "Despesa from gestao.financeiro.models.pagamento.PagamentoDespesa import PagamentoDespesa class ContratoDespesas(models.Model): contrato = models.ForeignKey(Contrato, verbose_name=\"Contrato\") despesa =", "Meta: app_label = 'contrato' verbose_name = 'Despesa do Contrato' verbose_name_plural = 'Despesas do", "return u'%s: %s' % (self.contrato.titulo, self.despesa.valor_total) def pagamento(self): pagamento_despesa = PagamentoDespesa.objects.filter(despesa=self.despesa) if pagamento_despesa:", "= models.ForeignKey(Contrato, verbose_name=\"Contrato\") despesa = models.ForeignKey(Despesa, verbose_name=\"Despesa\") def __unicode__(self): return u'%s: %s' %", "utf-8 -*- from django.db import models from gestao.contrato.models.contrato.Contrato import Contrato from gestao.financeiro.models.movimentacoes.Despesa import", "class ContratoDespesas(models.Model): contrato = models.ForeignKey(Contrato, verbose_name=\"Contrato\") despesa = models.ForeignKey(Despesa, verbose_name=\"Despesa\") def __unicode__(self): return", "verbose_name=\"Despesa\") def __unicode__(self): return u'%s: %s' % (self.contrato.titulo, self.despesa.valor_total) def pagamento(self): pagamento_despesa =", "(self.contrato.titulo, self.despesa.valor_total) def pagamento(self): pagamento_despesa = PagamentoDespesa.objects.filter(despesa=self.despesa) if pagamento_despesa: return pagamento_despesa[0] return None", "class Meta: app_label = 'contrato' verbose_name = 'Despesa do Contrato' verbose_name_plural = 'Despesas", "despesa = models.ForeignKey(Despesa, verbose_name=\"Despesa\") def __unicode__(self): return u'%s: %s' % (self.contrato.titulo, self.despesa.valor_total) def", "pagamento_despesa[0] return None class Meta: app_label = 'contrato' verbose_name = 'Despesa do Contrato'", "models from gestao.contrato.models.contrato.Contrato import Contrato from gestao.financeiro.models.movimentacoes.Despesa import Despesa from gestao.financeiro.models.pagamento.PagamentoDespesa import PagamentoDespesa", "app_label = 'contrato' verbose_name = 'Despesa do Contrato' verbose_name_plural = 'Despesas do Contrato'", "__unicode__(self): return u'%s: %s' % (self.contrato.titulo, self.despesa.valor_total) def pagamento(self): pagamento_despesa = PagamentoDespesa.objects.filter(despesa=self.despesa) if", "%s' % (self.contrato.titulo, self.despesa.valor_total) def pagamento(self): pagamento_despesa = PagamentoDespesa.objects.filter(despesa=self.despesa) if pagamento_despesa: return pagamento_despesa[0]", "PagamentoDespesa.objects.filter(despesa=self.despesa) if pagamento_despesa: return pagamento_despesa[0] return None class Meta: app_label = 'contrato' verbose_name", "self.despesa.valor_total) def pagamento(self): pagamento_despesa = PagamentoDespesa.objects.filter(despesa=self.despesa) if pagamento_despesa: return pagamento_despesa[0] return None class", "# -*- coding: utf-8 -*- from django.db import models from gestao.contrato.models.contrato.Contrato import Contrato", "PagamentoDespesa class ContratoDespesas(models.Model): contrato = models.ForeignKey(Contrato, verbose_name=\"Contrato\") despesa = models.ForeignKey(Despesa, verbose_name=\"Despesa\") def __unicode__(self):", "pagamento(self): pagamento_despesa = PagamentoDespesa.objects.filter(despesa=self.despesa) if pagamento_despesa: return pagamento_despesa[0] return None class Meta: app_label", "import PagamentoDespesa class ContratoDespesas(models.Model): contrato = models.ForeignKey(Contrato, verbose_name=\"Contrato\") despesa = models.ForeignKey(Despesa, verbose_name=\"Despesa\") def", "models.ForeignKey(Contrato, verbose_name=\"Contrato\") despesa = models.ForeignKey(Despesa, verbose_name=\"Despesa\") def __unicode__(self): return u'%s: %s' % (self.contrato.titulo,", "from gestao.contrato.models.contrato.Contrato import Contrato from gestao.financeiro.models.movimentacoes.Despesa import Despesa from gestao.financeiro.models.pagamento.PagamentoDespesa import PagamentoDespesa class", "-*- from django.db import models from gestao.contrato.models.contrato.Contrato import Contrato from gestao.financeiro.models.movimentacoes.Despesa import Despesa", "u'%s: %s' % (self.contrato.titulo, self.despesa.valor_total) def pagamento(self): pagamento_despesa = PagamentoDespesa.objects.filter(despesa=self.despesa) if pagamento_despesa: return", "import Contrato from gestao.financeiro.models.movimentacoes.Despesa import Despesa from gestao.financeiro.models.pagamento.PagamentoDespesa import PagamentoDespesa class ContratoDespesas(models.Model): contrato", "from gestao.financeiro.models.movimentacoes.Despesa import Despesa from gestao.financeiro.models.pagamento.PagamentoDespesa import PagamentoDespesa class ContratoDespesas(models.Model): contrato = models.ForeignKey(Contrato," ]
[ "TestTrendReq(TestCase): def test__get_data(self): \"\"\"Should use same values as in the documentation\"\"\" pytrend =", "\"\"\"Should use same values as in the documentation\"\"\" pytrend = TrendReq() self.assertEqual(pytrend.hl, 'en-US')", "unittest import TestCase from simplifiedpytrends.request import TrendReq class TestTrendReq(TestCase): def test__get_data(self): \"\"\"Should use", "simplifiedpytrends.request import TrendReq class TestTrendReq(TestCase): def test__get_data(self): \"\"\"Should use same values as in", "import TrendReq class TestTrendReq(TestCase): def test__get_data(self): \"\"\"Should use same values as in the", "use same values as in the documentation\"\"\" pytrend = TrendReq() self.assertEqual(pytrend.hl, 'en-US') self.assertEqual(pytrend.tz,", "'en-US') self.assertEqual(pytrend.tz, 360) self.assertEqual(pytrend.geo, '') self.assertTrue(pytrend.cookies['NID']) def test_interest_over_time(self): pytrend = TrendReq() pytrend.build_payload(kw_list=['pizza', 'bagel'])", "pytrend = TrendReq() self.assertEqual(pytrend.hl, 'en-US') self.assertEqual(pytrend.tz, 360) self.assertEqual(pytrend.geo, '') self.assertTrue(pytrend.cookies['NID']) def test_interest_over_time(self): pytrend", "class TestTrendReq(TestCase): def test__get_data(self): \"\"\"Should use same values as in the documentation\"\"\" pytrend", "from unittest import TestCase from simplifiedpytrends.request import TrendReq class TestTrendReq(TestCase): def test__get_data(self): \"\"\"Should", "test__get_data(self): \"\"\"Should use same values as in the documentation\"\"\" pytrend = TrendReq() self.assertEqual(pytrend.hl,", "from simplifiedpytrends.request import TrendReq class TestTrendReq(TestCase): def test__get_data(self): \"\"\"Should use same values as", "= TrendReq() self.assertEqual(pytrend.hl, 'en-US') self.assertEqual(pytrend.tz, 360) self.assertEqual(pytrend.geo, '') self.assertTrue(pytrend.cookies['NID']) def test_interest_over_time(self): pytrend =", "in the documentation\"\"\" pytrend = TrendReq() self.assertEqual(pytrend.hl, 'en-US') self.assertEqual(pytrend.tz, 360) self.assertEqual(pytrend.geo, '') self.assertTrue(pytrend.cookies['NID'])", "import TestCase from simplifiedpytrends.request import TrendReq class TestTrendReq(TestCase): def test__get_data(self): \"\"\"Should use same", "TestCase from simplifiedpytrends.request import TrendReq class TestTrendReq(TestCase): def test__get_data(self): \"\"\"Should use same values", "values as in the documentation\"\"\" pytrend = TrendReq() self.assertEqual(pytrend.hl, 'en-US') self.assertEqual(pytrend.tz, 360) self.assertEqual(pytrend.geo,", "self.assertEqual(pytrend.tz, 360) self.assertEqual(pytrend.geo, '') self.assertTrue(pytrend.cookies['NID']) def test_interest_over_time(self): pytrend = TrendReq() pytrend.build_payload(kw_list=['pizza', 'bagel']) self.assertIsNotNone(pytrend.interest_over_time())", "TrendReq class TestTrendReq(TestCase): def test__get_data(self): \"\"\"Should use same values as in the documentation\"\"\"", "same values as in the documentation\"\"\" pytrend = TrendReq() self.assertEqual(pytrend.hl, 'en-US') self.assertEqual(pytrend.tz, 360)", "TrendReq() self.assertEqual(pytrend.hl, 'en-US') self.assertEqual(pytrend.tz, 360) self.assertEqual(pytrend.geo, '') self.assertTrue(pytrend.cookies['NID']) def test_interest_over_time(self): pytrend = TrendReq()", "the documentation\"\"\" pytrend = TrendReq() self.assertEqual(pytrend.hl, 'en-US') self.assertEqual(pytrend.tz, 360) self.assertEqual(pytrend.geo, '') self.assertTrue(pytrend.cookies['NID']) def", "documentation\"\"\" pytrend = TrendReq() self.assertEqual(pytrend.hl, 'en-US') self.assertEqual(pytrend.tz, 360) self.assertEqual(pytrend.geo, '') self.assertTrue(pytrend.cookies['NID']) def test_interest_over_time(self):", "as in the documentation\"\"\" pytrend = TrendReq() self.assertEqual(pytrend.hl, 'en-US') self.assertEqual(pytrend.tz, 360) self.assertEqual(pytrend.geo, '')", "self.assertEqual(pytrend.hl, 'en-US') self.assertEqual(pytrend.tz, 360) self.assertEqual(pytrend.geo, '') self.assertTrue(pytrend.cookies['NID']) def test_interest_over_time(self): pytrend = TrendReq() pytrend.build_payload(kw_list=['pizza',", "def test__get_data(self): \"\"\"Should use same values as in the documentation\"\"\" pytrend = TrendReq()" ]
[ "flask import Blueprint posts = Blueprint('posts', __name__) from . import views from .", "from flask import Blueprint posts = Blueprint('posts', __name__) from . import views from", "print_function from flask import Blueprint posts = Blueprint('posts', __name__) from . import views", "from __future__ import absolute_import, print_function from flask import Blueprint posts = Blueprint('posts', __name__)", "absolute_import, print_function from flask import Blueprint posts = Blueprint('posts', __name__) from . import", "Blueprint posts = Blueprint('posts', __name__) from . import views from . import models", "__future__ import absolute_import, print_function from flask import Blueprint posts = Blueprint('posts', __name__) from", "import absolute_import, print_function from flask import Blueprint posts = Blueprint('posts', __name__) from .", "import Blueprint posts = Blueprint('posts', __name__) from . import views from . import" ]
[ "= self._load_item_feats(self.config[\"item_feat_path\"], FS.ITEM) self.inter_feat = pd.read_csv(self.config[\"inter_feat_path\"]).sample( frac=1, random_state=28) mask = None if len(self.types)", "in dataset'.format(field)) # if field not in self.field2token_id: # raise ValueError('field {} is", "field in self.user_feat_fields: return len(self.user_feat[field].unique()) else: for item_type, item_feat_fields in self.item_feat_fields.items( ): if", "= self.user_feat_fields item_fs = self.item_feat_fields type_field = self.itype_field self.train_inter_subset = {} self.val_inter_subset =", "self.uid_field, self.iid_field, self.itype_field, self.label_field, user_fs, item_fs[item_type]) self.test_inter_subset[item_type] = SubSet( test[test[type_field] == item_type_id], self.uid_field,", "Name: hdataset.py # Author: geekinglcq # Mail: <EMAIL> # Created Time: 2020-12-28 20:17:47", "FeatureSource as FS from .enum_type import item_type_dict from .dataset import DataSet, SubSet class", "hdataset.py # Author: geekinglcq # Mail: <EMAIL> # Created Time: 2020-12-28 20:17:47 #", "file not fountd.\") return item_feat def _init_setting(self): self.logger = logging.getLogger() self.name = self.config['name']", "= {} self.field2source = {} self.field2id_token = defaultdict(dict) self.field2token_id = defaultdict(dict) self.user_feat_fields =", "TODO pass self._preprocessing() def _load_feats(self): self.user_feat = self._load_meta_feats(self.config[\"user_feat_path\"], FS.USER, \"user_id\") self.item_feat = self._load_item_feats(self.config[\"item_feat_path\"],", "self.config: sample_ratio = self.config['sample'] sampled = [] for kind in self.types: ratio =", "in item_feat: item_feat[field] = item_feat[field].map(id_map) def join(self, df): \"\"\" Join user/item features to", "self._reID(self.iid_field) self._reID(self.uid_field) def _load_item_feats(self, paths, source): item_feat = {} for item_type, item_path in", "source): item_feat = {} for item_type, item_path in paths.items(): if item_type not in", "restore_path=None): self.config = config self._init_setting() if restore_path is None: self._load_feats() else: # TODO", "if field == self.uid_field: return self.user_num if field == self.iid_field: return self.item_num if", "{field}.') ftype = self.field2type.get(field) assert ftype == 'token' source = self.field2source.get(field) if type(source)", "= self.field2source.get(field) if type(source) is str and source.startswith(\"item_\"): item_type = source.split(\"_\")[1] dataframe =", "join='inner') elif source == 'user' or source is FS.USER_ID: dataframe = self.user_feat else:", "item_type = source.split(\"_\")[1] dataframe = self.item_feat[item_type] elif source is FS.ITEM_ID or source ==", "field not in self.field2token_id: # raise ValueError('field {} is not token type'.format(field)) if", "k, v in enumerate(dataframe[field].unique())} self.field2token_id[field].update(id_map) dataframe[field] = dataframe[field].map(id_map) if source in ['item', 'user',", "self.user_feat is not None and self.uid_field in df: df = pd.merge(df, self.user_feat, on=self.uid_field,", "+ 0.3, random_state=16) print(kind, kind_id, ratio, new_df.shape) sampled.append(new_df) self.inter_feat = pd.concat(sampled, ignore_index=True) self.inter_feat", "item_type_dict[item_type] self.train_inter_subset[item_type] = SubSet( train[train[type_field] == item_type_id], self.uid_field, self.iid_field, self.itype_field, self.label_field, user_fs, item_fs[item_type])", "self.config[\"USER_ID_FIELD\"] self.iid_field = self.config[\"ITEM_ID_FIELD\"] self.label_field = self.config[\"LABEL_FIELD\"] self.itype_field = self.config[\"TYPE_FIELD\"] self.types = self.config[\"type\"]", "continue if os.path.isfile(item_path): feat = pd.read_csv(item_path) item_feat[item_type] = feat else: raise ValueError(\"Dataset file", "for feat_name, feat_value in self.config['feat'].items(): source = feat_value['source'] self.field2type[feat_name] = feat_value['type'] self.field2source[feat_name] =", "self._reID(self.uid_field) def _load_item_feats(self, paths, source): item_feat = {} for item_type, item_path in paths.items():", "= mask | new_mask else: mask = new_mask self.inter_feat = self.inter_feat[mask] self.h_inter_feat =", "new_df.shape) sampled.append(new_df) self.inter_feat = pd.concat(sampled, ignore_index=True) self.inter_feat = self.inter_feat.sample(frac=1.).reset_index( drop=True) def train_val_test_split(self, ratios=[0.7,", "for item_type, item_feat in self.item_feat.items(): if field in item_feat: item_feat[field] = item_feat[field].map(id_map) def", "self.user_num if field == self.iid_field: return self.item_num if field not in self.field2type: raise", "preverse the data for val & test new_df = self.inter_feat[self.inter_feat['type'] == kind_id].sample(frac=ratio *", "\"\"\" Re-ID the token-type feature, save the id map in self.field2token_id \"\"\" self.logger.info(f'ReID", "def join_interaction(self): self.inter_feat = self.join(self.inter_feat) if 'sample' in self.config: sample_ratio = self.config['sample'] sampled", "if field not in self.field2type: raise ValueError('field {} not in dataset'.format(field)) # if", "kind in self.types: ratio = sample_ratio.get(kind, 1.0) kind_id = item_type_dict[kind] # preverse the", "else: for item_type, item_feat_fields in self.item_feat_fields.items( ): if field in item_feat_fields: return len(self.item_feat[item_type][field].unique())", "['item', 'user', FS.ITEM_ID, FS.USER_ID]: if field in self.inter_feat: self.inter_feat[field] = self.inter_feat[field].map(id_map) for item_type,", "# File Name: hdataset.py # Author: geekinglcq # Mail: <EMAIL> # Created Time:", "sampled.append(new_df) self.inter_feat = pd.concat(sampled, ignore_index=True) self.inter_feat = self.inter_feat.sample(frac=1.).reset_index( drop=True) def train_val_test_split(self, ratios=[0.7, 0.2,", "dataframes, uid_field, iid_field, label_field, u_feat_fields, i_feat_fields): self.types = dataframes.keys() self.dfs = dataframes self.uid", "not in self.field2token_id: # raise ValueError('field {} is not token type'.format(field)) if len(self.field2token_id[field])", "self.test_inter_subset[item_type], batch_size=batch_size, num_workers=num_workers) class HSubSet(Dataset): def __init__(self, dataframes, uid_field, iid_field, label_field, u_feat_fields, i_feat_fields):", "val & test new_df = self.inter_feat[self.inter_feat['type'] == kind_id].sample(frac=ratio * 0.7 + 0.3, random_state=16)", "item_feat[item_type] = feat else: raise ValueError(\"Dataset file not fountd.\") return item_feat def _init_setting(self):", "== \"item\": dataframe = pd.concat(list(self.item_feat.values()), join='inner') elif source == 'user' or source is", "return self.item_num if field not in self.field2type: raise ValueError('field {} not in dataset'.format(field))", "self.uid_field: return self.user_num if field == self.iid_field: return self.item_num if field not in", "= df[type_c].agg(sum, axis=1) return df def join_interaction(self): self.inter_feat = self.join(self.inter_feat) if 'sample' in", "sum([len(i) for i in self.item_feat.values()]) self.item_nums = {k: len(v) for k, v in", "in enumerate(dataframe[field].unique())} self.field2token_id[field].update(id_map) dataframe[field] = dataframe[field].map(id_map) if source in ['item', 'user', FS.ITEM_ID, FS.USER_ID]:", "stored in self.all_inter_feat\") self.inter_feat = train def init_data_loader(self, batch_size=256, num_workers=1): self.train_data_loader = {}", "= pd.read_csv(self.config[\"inter_feat_path\"]).sample( frac=1, random_state=28) mask = None if len(self.types) < 3: for item_type,", "new_mask self.inter_feat = self.inter_feat[mask] self.h_inter_feat = {} self.user_num = len(self.user_feat) self.item_num = sum([len(i)", "= self.item_feat_fields type_field = self.itype_field self.train_inter_subset = {} self.val_inter_subset = {} self.test_inter_subset =", "########################### # File Name: hdataset.py # Author: geekinglcq # Mail: <EMAIL> # Created", "print(self.config) self.uid_field = self.config[\"USER_ID_FIELD\"] self.iid_field = self.config[\"ITEM_ID_FIELD\"] self.label_field = self.config[\"LABEL_FIELD\"] self.itype_field = self.config[\"TYPE_FIELD\"]", "raise ValueError('field {} is not token type'.format(field)) if len(self.field2token_id[field]) == 0: if field", "item_feat[field].map(id_map) def join(self, df): \"\"\" Join user/item features to interactions. \"\"\" if self.user_feat", "= self.field2type.get(field) assert ftype == 'token' source = self.field2source.get(field) if type(source) is str", "0.7 + 0.3, random_state=16) print(kind, kind_id, ratio, new_df.shape) sampled.append(new_df) self.inter_feat = pd.concat(sampled, ignore_index=True)", "if field == self.iid_field: return self.item_num if field not in self.field2type: raise ValueError('field", "self.itype_field, self.label_field, user_fs, item_fs[item_type]) self.val_inter_subset[item_type] = SubSet( val[val[type_field] == item_type_id], self.uid_field, self.iid_field, self.itype_field,", "in self.types: ratio = sample_ratio.get(kind, 1.0) kind_id = item_type_dict[kind] # preverse the data", ".enum_type import FeatureSource as FS from .enum_type import item_type_dict from .dataset import DataSet,", "return item_feat def _init_setting(self): self.logger = logging.getLogger() self.name = self.config['name'] print(self.config) self.uid_field =", "if field in self.inter_feat: self.inter_feat[field] = self.inter_feat[field].map(id_map) for item_type, item_feat in self.item_feat.items(): if", "for item_type, item_feat_fields in self.item_feat_fields.items( ): if field in item_feat_fields: return len(self.item_feat[item_type][field].unique()) return", "pd.read_csv(self.config[\"inter_feat_path\"]).sample( frac=1, random_state=28) mask = None if len(self.types) < 3: for item_type, item_feat", "drop=True) def train_val_test_split(self, ratios=[0.7, 0.2, 0.1], group_by=None, **kwargs): assert len(ratios) == 3 if", "self.val_data_loader = {} self.test_data_loader = {} for item_type in self.types: self.train_data_loader[item_type] = DataLoader(", "= defaultdict(dict) self.field2token_id = defaultdict(dict) self.user_feat_fields = [] self.item_feat_fields = defaultdict(list) for feat_name,", "0.1], group_by=None, **kwargs): assert len(ratios) == 3 if 'sample' in self.config: train, val,", "new_mask else: mask = new_mask self.inter_feat = self.inter_feat[mask] self.h_inter_feat = {} self.user_num =", "_load_feats(self): self.user_feat = self._load_meta_feats(self.config[\"user_feat_path\"], FS.USER, \"user_id\") self.item_feat = self._load_item_feats(self.config[\"item_feat_path\"], FS.ITEM) self.inter_feat = pd.read_csv(self.config[\"inter_feat_path\"]).sample(", "= self.config[\"ITEM_ID_FIELD\"] self.label_field = self.config[\"LABEL_FIELD\"] self.itype_field = self.config[\"TYPE_FIELD\"] self.types = self.config[\"type\"] self.field2type =", "not in self.field2type: raise ValueError('field {} not in dataset'.format(field)) # if field not", "= feat_value['source'] self.field2type[feat_name] = feat_value['type'] self.field2source[feat_name] = feat_value['source'] if source == 'user' and", "features are stored in self.all_inter_feat\") self.inter_feat = train def init_data_loader(self, batch_size=256, num_workers=1): self.train_data_loader", "as FS from .enum_type import item_type_dict from .dataset import DataSet, SubSet class HDataSet(DataSet):", "0: if field in self.user_feat_fields: return len(self.user_feat[field].unique()) else: for item_type, item_feat_fields in self.item_feat_fields.items(", "raise ValueError(\"Dataset file not fountd.\") return item_feat def _init_setting(self): self.logger = logging.getLogger() self.name", "= logging.getLogger() self.name = self.config['name'] print(self.config) self.uid_field = self.config[\"USER_ID_FIELD\"] self.iid_field = self.config[\"ITEM_ID_FIELD\"] self.label_field", "suffixes=('_inter', '_user')) if self.item_feat is not None and self.iid_field in df: for item_type,", "FS.ITEM_ID, FS.USER_ID]: if field in self.inter_feat: self.inter_feat[field] = self.inter_feat[field].map(id_map) for item_type, item_feat in", "mask | new_mask else: mask = new_mask self.inter_feat = self.inter_feat[mask] self.h_inter_feat = {}", "= {} self.field2id_token = defaultdict(dict) self.field2token_id = defaultdict(dict) self.user_feat_fields = [] self.item_feat_fields =", "source.startswith(\"item_\"): item_type = source.split(\"_\")[1] dataframe = self.item_feat[item_type] elif source is FS.ITEM_ID or source", "= None if len(self.types) < 3: for item_type, item_feat in self.item_feat.items(): new_mask =", "df[type_c].agg(sum, axis=1) return df def join_interaction(self): self.inter_feat = self.join(self.inter_feat) if 'sample' in self.config:", "from collections import defaultdict from torch.utils.data import DataLoader, Dataset from .enum_type import FeatureSource", "import defaultdict from torch.utils.data import DataLoader, Dataset from .enum_type import FeatureSource as FS", "= {k: len(v) for k, v in self.item_feat.items()} print(f'user num: {self.user_num}') print(f'item num:", "3: for item_type, item_feat in self.item_feat.items(): new_mask = self.inter_feat[self.iid_field].isin( item_feat[self.iid_field]) if mask is", "self.types: continue if os.path.isfile(item_path): feat = pd.read_csv(item_path) item_feat[item_type] = feat else: raise ValueError(\"Dataset", "[i for i in df.columns if i.startswith(self.itype_field)] df[self.itype_field] = df[type_c].agg(sum, axis=1) return df", "for item_type in self.types: item_type_id = item_type_dict[item_type] self.train_inter_subset[item_type] = SubSet( train[train[type_field] == item_type_id],", "and self.iid_field in df: for item_type, item_feat in self.item_feat.items(): df = pd.merge(df, item_feat,", "{} for item_type in self.types: item_type_id = item_type_dict[item_type] self.train_inter_subset[item_type] = SubSet( train[train[type_field] ==", "group_by=None, **kwargs): assert len(ratios) == 3 if 'sample' in self.config: train, val, test", "'user' or source is FS.USER_ID: dataframe = self.user_feat else: dataframe = self.inter_feat id_map", "item_feat[field] = item_feat[field].map(id_map) def join(self, df): \"\"\" Join user/item features to interactions. \"\"\"", "{} is not token type'.format(field)) if len(self.field2token_id[field]) == 0: if field in self.user_feat_fields:", "in df.columns if i.startswith(self.itype_field)] df[self.itype_field] = df[type_c].agg(sum, axis=1) return df def join_interaction(self): self.inter_feat", "self.label_field = self.config[\"LABEL_FIELD\"] self.itype_field = self.config[\"TYPE_FIELD\"] self.types = self.config[\"type\"] self.field2type = {} self.field2source", "None: mask = mask | new_mask else: mask = new_mask self.inter_feat = self.inter_feat[mask]", "test new_df = self.inter_feat[self.inter_feat['type'] == kind_id].sample(frac=ratio * 0.7 + 0.3, random_state=16) print(kind, kind_id,", "suffixes=(f'_{item_type}', '_inter')) type_c = [i for i in df.columns if i.startswith(self.itype_field)] df[self.itype_field] =", "self.inter_feat id_map = {v: k for k, v in enumerate(dataframe[field].unique())} self.field2token_id[field].update(id_map) dataframe[field] =", "self.label_field, user_fs, item_fs[item_type]) self.all_inter_feat = self.inter_feat self.logger.info( \"Replace interaction features with train interaction", "self.inter_feat self.logger.info( \"Replace interaction features with train interaction fatures.\") self.logger.info( \"Interaction features are", "from .enum_type import FeatureSource as FS from .enum_type import item_type_dict from .dataset import", "self.user_num = len(self.user_feat) self.item_num = sum([len(i) for i in self.item_feat.values()]) self.item_nums = {k:", "in self.item_feat.items(): df = pd.merge(df, item_feat, on=self.iid_field, how='left', suffixes=(f'_{item_type}', '_inter')) type_c = [i", "self.test_data_loader[item_type] = DataLoader( self.test_inter_subset[item_type], batch_size=batch_size, num_workers=num_workers) class HSubSet(Dataset): def __init__(self, dataframes, uid_field, iid_field,", "self.split_by_ratio_sampled( ratios, create_new_dataset=False) else: train, val, test = self.split_by_ratio(ratios, group_by=group_by, create_new_dataset=False) user_fs =", "self.join(self.inter_feat) if 'sample' in self.config: sample_ratio = self.config['sample'] sampled = [] for kind", "item_fs[item_type]) self.all_inter_feat = self.inter_feat self.logger.info( \"Replace interaction features with train interaction fatures.\") self.logger.info(", "feat else: raise ValueError(\"Dataset file not fountd.\") return item_feat def _init_setting(self): self.logger =", ".dataset import DataSet, SubSet class HDataSet(DataSet): \"\"\" Dataset used for heterogenous items \"\"\"", "class HDataSet(DataSet): \"\"\" Dataset used for heterogenous items \"\"\" def __init__(self, config, restore_path=None):", "map in self.field2token_id \"\"\" self.logger.info(f'ReID field {field}.') ftype = self.field2type.get(field) assert ftype ==", "config self._init_setting() if restore_path is None: self._load_feats() else: # TODO pass self._preprocessing() def", "= self.config[\"TYPE_FIELD\"] self.types = self.config[\"type\"] self.field2type = {} self.field2source = {} self.field2id_token =", "test = self.split_by_ratio_sampled( ratios, create_new_dataset=False) else: train, val, test = self.split_by_ratio(ratios, group_by=group_by, create_new_dataset=False)", "field not in self.field2type: raise ValueError('field {} not in dataset'.format(field)) # if field", "in self.types: self.item_feat_fields[item_type].append(feat_name) def num(self, field): if field == self.uid_field: return self.user_num if", "return len(self.user_feat[field].unique()) else: for item_type, item_feat_fields in self.item_feat_fields.items( ): if field in item_feat_fields:", "self.field2id_token = defaultdict(dict) self.field2token_id = defaultdict(dict) self.user_feat_fields = [] self.item_feat_fields = defaultdict(list) for", "self.field2type[feat_name] = feat_value['type'] self.field2source[feat_name] = feat_value['source'] if source == 'user' and feat_name !=", "batch_size=256, num_workers=1): self.train_data_loader = {} self.val_data_loader = {} self.test_data_loader = {} for item_type", "mask = mask | new_mask else: mask = new_mask self.inter_feat = self.inter_feat[mask] self.h_inter_feat", "if len(self.types) < 3: for item_type, item_feat in self.item_feat.items(): new_mask = self.inter_feat[self.iid_field].isin( item_feat[self.iid_field])", "sampled = [] for kind in self.types: ratio = sample_ratio.get(kind, 1.0) kind_id =", "self._init_setting() if restore_path is None: self._load_feats() else: # TODO pass self._preprocessing() def _load_feats(self):", "paths.items(): if item_type not in self.types: continue if os.path.isfile(item_path): feat = pd.read_csv(item_path) item_feat[item_type]", "FS.USER_ID]: if field in self.inter_feat: self.inter_feat[field] = self.inter_feat[field].map(id_map) for item_type, item_feat in self.item_feat.items():", "are stored in self.all_inter_feat\") self.inter_feat = train def init_data_loader(self, batch_size=256, num_workers=1): self.train_data_loader =", "item_type_id], self.uid_field, self.iid_field, self.itype_field, self.label_field, user_fs, item_fs[item_type]) self.test_inter_subset[item_type] = SubSet( test[test[type_field] == item_type_id],", "20:17:47 # ########################### import pandas as pd import os import logging from collections", "self.all_inter_feat = self.inter_feat self.logger.info( \"Replace interaction features with train interaction fatures.\") self.logger.info( \"Interaction", "item_feat, on=self.iid_field, how='left', suffixes=(f'_{item_type}', '_inter')) type_c = [i for i in df.columns if", "save the id map in self.field2token_id \"\"\" self.logger.info(f'ReID field {field}.') ftype = self.field2type.get(field)", "self.iid_field, self.itype_field, self.label_field, user_fs, item_fs[item_type]) self.val_inter_subset[item_type] = SubSet( val[val[type_field] == item_type_id], self.uid_field, self.iid_field,", "= uid_field self.iid = iid_field self.label = label_field def __len__(self): return min([len(df.index) for", "== self.iid_field: return self.item_num if field not in self.field2type: raise ValueError('field {} not", "dataframe = self.user_feat else: dataframe = self.inter_feat id_map = {v: k for k,", "torch.utils.data import DataLoader, Dataset from .enum_type import FeatureSource as FS from .enum_type import", "source == 'user' or source is FS.USER_ID: dataframe = self.user_feat else: dataframe =", "fountd.\") return item_feat def _init_setting(self): self.logger = logging.getLogger() self.name = self.config['name'] print(self.config) self.uid_field", "field in item_feat_fields: return len(self.item_feat[item_type][field].unique()) return len(self.field2token_id[field]) def _reID(self, field): \"\"\" Re-ID the", "self.types = self.config[\"type\"] self.field2type = {} self.field2source = {} self.field2id_token = defaultdict(dict) self.field2token_id", "in self.field2token_id: # raise ValueError('field {} is not token type'.format(field)) if len(self.field2token_id[field]) ==", "File Name: hdataset.py # Author: geekinglcq # Mail: <EMAIL> # Created Time: 2020-12-28", "for k, v in self.item_feat.items()} print(f'user num: {self.user_num}') print(f'item num: {self.item_num}') print(f'item nums:", "return self.user_num if field == self.iid_field: return self.item_num if field not in self.field2type:", "def num(self, field): if field == self.uid_field: return self.user_num if field == self.iid_field:", "field == self.uid_field: return self.user_num if field == self.iid_field: return self.item_num if field", ".enum_type import item_type_dict from .dataset import DataSet, SubSet class HDataSet(DataSet): \"\"\" Dataset used", "self.types = dataframes.keys() self.dfs = dataframes self.uid = uid_field self.iid = iid_field self.label", "self.field2type: raise ValueError('field {} not in dataset'.format(field)) # if field not in self.field2token_id:", "self.test_inter_subset = {} for item_type in self.types: item_type_id = item_type_dict[item_type] self.train_inter_subset[item_type] = SubSet(", "{} self.test_data_loader = {} for item_type in self.types: self.train_data_loader[item_type] = DataLoader( self.train_inter_subset[item_type], batch_size=batch_size,", "if source == 'user' and feat_name != self.uid_field: self.user_feat_fields.append(feat_name) if source.startswith('item') and feat_name", "and feat_name != self.iid_field: item_type = source.split(\"_\")[1] if item_type in self.types: self.item_feat_fields[item_type].append(feat_name) def", "in self.item_feat.items(): if field in item_feat: item_feat[field] = item_feat[field].map(id_map) def join(self, df): \"\"\"", "= self.user_feat else: dataframe = self.inter_feat id_map = {v: k for k, v", "self.itype_field = self.config[\"TYPE_FIELD\"] self.types = self.config[\"type\"] self.field2type = {} self.field2source = {} self.field2id_token", "self.item_feat_fields[item_type].append(feat_name) def num(self, field): if field == self.uid_field: return self.user_num if field ==", "def train_val_test_split(self, ratios=[0.7, 0.2, 0.1], group_by=None, **kwargs): assert len(ratios) == 3 if 'sample'", "source.split(\"_\")[1] if item_type in self.types: self.item_feat_fields[item_type].append(feat_name) def num(self, field): if field == self.uid_field:", "len(self.user_feat) self.item_num = sum([len(i) for i in self.item_feat.values()]) self.item_nums = {k: len(v) for", "val[val[type_field] == item_type_id], self.uid_field, self.iid_field, self.itype_field, self.label_field, user_fs, item_fs[item_type]) self.test_inter_subset[item_type] = SubSet( test[test[type_field]", "defaultdict from torch.utils.data import DataLoader, Dataset from .enum_type import FeatureSource as FS from", "heterogenous items \"\"\" def __init__(self, config, restore_path=None): self.config = config self._init_setting() if restore_path", "pd.concat(list(self.item_feat.values()), join='inner') elif source == 'user' or source is FS.USER_ID: dataframe = self.user_feat", "geekinglcq # Mail: <EMAIL> # Created Time: 2020-12-28 20:17:47 # ########################### import pandas", "item_type, item_feat in self.item_feat.items(): df = pd.merge(df, item_feat, on=self.iid_field, how='left', suffixes=(f'_{item_type}', '_inter')) type_c", "create_new_dataset=False) user_fs = self.user_feat_fields item_fs = self.item_feat_fields type_field = self.itype_field self.train_inter_subset = {}", "= feat_value['type'] self.field2source[feat_name] = feat_value['source'] if source == 'user' and feat_name != self.uid_field:", "not token type'.format(field)) if len(self.field2token_id[field]) == 0: if field in self.user_feat_fields: return len(self.user_feat[field].unique())", "feat = pd.read_csv(item_path) item_feat[item_type] = feat else: raise ValueError(\"Dataset file not fountd.\") return", "self.uid_field, self.iid_field, self.itype_field, self.label_field, user_fs, item_fs[item_type]) self.val_inter_subset[item_type] = SubSet( val[val[type_field] == item_type_id], self.uid_field,", "type_c = [i for i in df.columns if i.startswith(self.itype_field)] df[self.itype_field] = df[type_c].agg(sum, axis=1)", "self.item_feat.items(): if field in item_feat: item_feat[field] = item_feat[field].map(id_map) def join(self, df): \"\"\" Join", "self.item_feat_fields.items( ): if field in item_feat_fields: return len(self.item_feat[item_type][field].unique()) return len(self.field2token_id[field]) def _reID(self, field):", "train, val, test = self.split_by_ratio(ratios, group_by=group_by, create_new_dataset=False) user_fs = self.user_feat_fields item_fs = self.item_feat_fields", "= self.inter_feat id_map = {v: k for k, v in enumerate(dataframe[field].unique())} self.field2token_id[field].update(id_map) dataframe[field]", "self.inter_feat: self.inter_feat[field] = self.inter_feat[field].map(id_map) for item_type, item_feat in self.item_feat.items(): if field in item_feat:", "ftype = self.field2type.get(field) assert ftype == 'token' source = self.field2source.get(field) if type(source) is", "self.inter_feat[self.iid_field].isin( item_feat[self.iid_field]) if mask is not None: mask = mask | new_mask else:", "self.itype_field, self.label_field, user_fs, item_fs[item_type]) self.test_inter_subset[item_type] = SubSet( test[test[type_field] == item_type_id], self.uid_field, self.iid_field, self.itype_field,", "defaultdict(list) for feat_name, feat_value in self.config['feat'].items(): source = feat_value['source'] self.field2type[feat_name] = feat_value['type'] self.field2source[feat_name]", "= sum([len(i) for i in self.item_feat.values()]) self.item_nums = {k: len(v) for k, v", "dataframes self.uid = uid_field self.iid = iid_field self.label = label_field def __len__(self): return", "def __init__(self, config, restore_path=None): self.config = config self._init_setting() if restore_path is None: self._load_feats()", "return len(self.item_feat[item_type][field].unique()) return len(self.field2token_id[field]) def _reID(self, field): \"\"\" Re-ID the token-type feature, save", "feat_name, feat_value in self.config['feat'].items(): source = feat_value['source'] self.field2type[feat_name] = feat_value['type'] self.field2source[feat_name] = feat_value['source']", "create_new_dataset=False) else: train, val, test = self.split_by_ratio(ratios, group_by=group_by, create_new_dataset=False) user_fs = self.user_feat_fields item_fs", "{} self.val_inter_subset = {} self.test_inter_subset = {} for item_type in self.types: item_type_id =", "source is FS.ITEM_ID or source == \"item\": dataframe = pd.concat(list(self.item_feat.values()), join='inner') elif source", "self.field2token_id \"\"\" self.logger.info(f'ReID field {field}.') ftype = self.field2type.get(field) assert ftype == 'token' source", "* 0.7 + 0.3, random_state=16) print(kind, kind_id, ratio, new_df.shape) sampled.append(new_df) self.inter_feat = pd.concat(sampled,", "paths, source): item_feat = {} for item_type, item_path in paths.items(): if item_type not", "self._preprocessing() def _load_feats(self): self.user_feat = self._load_meta_feats(self.config[\"user_feat_path\"], FS.USER, \"user_id\") self.item_feat = self._load_item_feats(self.config[\"item_feat_path\"], FS.ITEM) self.inter_feat", "or source == \"item\": dataframe = pd.concat(list(self.item_feat.values()), join='inner') elif source == 'user' or", "frac=1, random_state=28) mask = None if len(self.types) < 3: for item_type, item_feat in", "= SubSet( test[test[type_field] == item_type_id], self.uid_field, self.iid_field, self.itype_field, self.label_field, user_fs, item_fs[item_type]) self.all_inter_feat =", "pd import os import logging from collections import defaultdict from torch.utils.data import DataLoader,", "self.field2token_id: # raise ValueError('field {} is not token type'.format(field)) if len(self.field2token_id[field]) == 0:", "= DataLoader( self.train_inter_subset[item_type], batch_size=batch_size, # pin_memory=True, num_workers=num_workers) self.val_data_loader[item_type] = DataLoader( self.val_inter_subset[item_type], batch_size=batch_size, num_workers=num_workers)", "num_workers=num_workers) class HSubSet(Dataset): def __init__(self, dataframes, uid_field, iid_field, label_field, u_feat_fields, i_feat_fields): self.types =", "field in self.inter_feat: self.inter_feat[field] = self.inter_feat[field].map(id_map) for item_type, item_feat in self.item_feat.items(): if field", "FS.USER, \"user_id\") self.item_feat = self._load_item_feats(self.config[\"item_feat_path\"], FS.ITEM) self.inter_feat = pd.read_csv(self.config[\"inter_feat_path\"]).sample( frac=1, random_state=28) mask =", "self.user_feat_fields.append(feat_name) if source.startswith('item') and feat_name != self.iid_field: item_type = source.split(\"_\")[1] if item_type in", "self._load_feats() else: # TODO pass self._preprocessing() def _load_feats(self): self.user_feat = self._load_meta_feats(self.config[\"user_feat_path\"], FS.USER, \"user_id\")", "str and source.startswith(\"item_\"): item_type = source.split(\"_\")[1] dataframe = self.item_feat[item_type] elif source is FS.ITEM_ID", "uid_field, iid_field, label_field, u_feat_fields, i_feat_fields): self.types = dataframes.keys() self.dfs = dataframes self.uid =", "if source in ['item', 'user', FS.ITEM_ID, FS.USER_ID]: if field in self.inter_feat: self.inter_feat[field] =", "df def join_interaction(self): self.inter_feat = self.join(self.inter_feat) if 'sample' in self.config: sample_ratio = self.config['sample']", "field): if field == self.uid_field: return self.user_num if field == self.iid_field: return self.item_num", "self.train_inter_subset = {} self.val_inter_subset = {} self.test_inter_subset = {} for item_type in self.types:", "__init__(self, config, restore_path=None): self.config = config self._init_setting() if restore_path is None: self._load_feats() else:", "_init_setting(self): self.logger = logging.getLogger() self.name = self.config['name'] print(self.config) self.uid_field = self.config[\"USER_ID_FIELD\"] self.iid_field =", "SubSet( train[train[type_field] == item_type_id], self.uid_field, self.iid_field, self.itype_field, self.label_field, user_fs, item_fs[item_type]) self.val_inter_subset[item_type] = SubSet(", "self.types: self.item_feat_fields[item_type].append(feat_name) def num(self, field): if field == self.uid_field: return self.user_num if field", "= dataframes.keys() self.dfs = dataframes self.uid = uid_field self.iid = iid_field self.label =", "self.config['sample'] sampled = [] for kind in self.types: ratio = sample_ratio.get(kind, 1.0) kind_id", "import logging from collections import defaultdict from torch.utils.data import DataLoader, Dataset from .enum_type", "not fountd.\") return item_feat def _init_setting(self): self.logger = logging.getLogger() self.name = self.config['name'] print(self.config)", "= self.inter_feat[self.inter_feat['type'] == kind_id].sample(frac=ratio * 0.7 + 0.3, random_state=16) print(kind, kind_id, ratio, new_df.shape)", "in self.item_feat.items()} print(f'user num: {self.user_num}') print(f'item num: {self.item_num}') print(f'item nums: {self.item_nums}') def _preprocessing(self):", "# raise ValueError('field {} is not token type'.format(field)) if len(self.field2token_id[field]) == 0: if", "and source.startswith(\"item_\"): item_type = source.split(\"_\")[1] dataframe = self.item_feat[item_type] elif source is FS.ITEM_ID or", "# preverse the data for val & test new_df = self.inter_feat[self.inter_feat['type'] == kind_id].sample(frac=ratio", "def _reID(self, field): \"\"\" Re-ID the token-type feature, save the id map in", "the data for val & test new_df = self.inter_feat[self.inter_feat['type'] == kind_id].sample(frac=ratio * 0.7", "item_type, item_feat in self.item_feat.items(): new_mask = self.inter_feat[self.iid_field].isin( item_feat[self.iid_field]) if mask is not None:", "pd.read_csv(item_path) item_feat[item_type] = feat else: raise ValueError(\"Dataset file not fountd.\") return item_feat def", "self.inter_feat = pd.read_csv(self.config[\"inter_feat_path\"]).sample( frac=1, random_state=28) mask = None if len(self.types) < 3: for", "= self.inter_feat.sample(frac=1.).reset_index( drop=True) def train_val_test_split(self, ratios=[0.7, 0.2, 0.1], group_by=None, **kwargs): assert len(ratios) ==", "mask = None if len(self.types) < 3: for item_type, item_feat in self.item_feat.items(): new_mask", "len(self.types) < 3: self._reID(self.iid_field) self._reID(self.uid_field) def _load_item_feats(self, paths, source): item_feat = {} for", "kind_id = item_type_dict[kind] # preverse the data for val & test new_df =", "= item_feat[field].map(id_map) def join(self, df): \"\"\" Join user/item features to interactions. \"\"\" if", "self.itype_field, self.label_field, user_fs, item_fs[item_type]) self.all_inter_feat = self.inter_feat self.logger.info( \"Replace interaction features with train", "self.item_feat[item_type] elif source is FS.ITEM_ID or source == \"item\": dataframe = pd.concat(list(self.item_feat.values()), join='inner')", "source is FS.USER_ID: dataframe = self.user_feat else: dataframe = self.inter_feat id_map = {v:", "k for k, v in enumerate(dataframe[field].unique())} self.field2token_id[field].update(id_map) dataframe[field] = dataframe[field].map(id_map) if source in", "self.train_inter_subset[item_type] = SubSet( train[train[type_field] == item_type_id], self.uid_field, self.iid_field, self.itype_field, self.label_field, user_fs, item_fs[item_type]) self.val_inter_subset[item_type]", "print(f'user num: {self.user_num}') print(f'item num: {self.item_num}') print(f'item nums: {self.item_nums}') def _preprocessing(self): self._normalize() if", "self.iid_field, self.itype_field, self.label_field, user_fs, item_fs[item_type]) self.test_inter_subset[item_type] = SubSet( test[test[type_field] == item_type_id], self.uid_field, self.iid_field,", "in self.field2token_id \"\"\" self.logger.info(f'ReID field {field}.') ftype = self.field2type.get(field) assert ftype == 'token'", "[] for kind in self.types: ratio = sample_ratio.get(kind, 1.0) kind_id = item_type_dict[kind] #", "if item_type in self.types: self.item_feat_fields[item_type].append(feat_name) def num(self, field): if field == self.uid_field: return", "dataframes.keys() self.dfs = dataframes self.uid = uid_field self.iid = iid_field self.label = label_field", "def _load_feats(self): self.user_feat = self._load_meta_feats(self.config[\"user_feat_path\"], FS.USER, \"user_id\") self.item_feat = self._load_item_feats(self.config[\"item_feat_path\"], FS.ITEM) self.inter_feat =", "nums: {self.item_nums}') def _preprocessing(self): self._normalize() if len(self.types) < 3: self._reID(self.iid_field) self._reID(self.uid_field) def _load_item_feats(self,", "features to interactions. \"\"\" if self.user_feat is not None and self.uid_field in df:", "ValueError(\"Dataset file not fountd.\") return item_feat def _init_setting(self): self.logger = logging.getLogger() self.name =", "): if field in item_feat_fields: return len(self.item_feat[item_type][field].unique()) return len(self.field2token_id[field]) def _reID(self, field): \"\"\"", "in self.item_feat.values()]) self.item_nums = {k: len(v) for k, v in self.item_feat.items()} print(f'user num:", "= SubSet( val[val[type_field] == item_type_id], self.uid_field, self.iid_field, self.itype_field, self.label_field, user_fs, item_fs[item_type]) self.test_inter_subset[item_type] =", "id_map = {v: k for k, v in enumerate(dataframe[field].unique())} self.field2token_id[field].update(id_map) dataframe[field] = dataframe[field].map(id_map)", "self.inter_feat = pd.concat(sampled, ignore_index=True) self.inter_feat = self.inter_feat.sample(frac=1.).reset_index( drop=True) def train_val_test_split(self, ratios=[0.7, 0.2, 0.1],", "source = feat_value['source'] self.field2type[feat_name] = feat_value['type'] self.field2source[feat_name] = feat_value['source'] if source == 'user'", "defaultdict(dict) self.field2token_id = defaultdict(dict) self.user_feat_fields = [] self.item_feat_fields = defaultdict(list) for feat_name, feat_value", "for item_type, item_feat in self.item_feat.items(): df = pd.merge(df, item_feat, on=self.iid_field, how='left', suffixes=(f'_{item_type}', '_inter'))", "self.config = config self._init_setting() if restore_path is None: self._load_feats() else: # TODO pass", "Join user/item features to interactions. \"\"\" if self.user_feat is not None and self.uid_field", "os.path.isfile(item_path): feat = pd.read_csv(item_path) item_feat[item_type] = feat else: raise ValueError(\"Dataset file not fountd.\")", "\"Interaction features are stored in self.all_inter_feat\") self.inter_feat = train def init_data_loader(self, batch_size=256, num_workers=1):", "item_type in self.types: self.item_feat_fields[item_type].append(feat_name) def num(self, field): if field == self.uid_field: return self.user_num", "\"\"\" self.logger.info(f'ReID field {field}.') ftype = self.field2type.get(field) assert ftype == 'token' source =", "if i.startswith(self.itype_field)] df[self.itype_field] = df[type_c].agg(sum, axis=1) return df def join_interaction(self): self.inter_feat = self.join(self.inter_feat)", "df: for item_type, item_feat in self.item_feat.items(): df = pd.merge(df, item_feat, on=self.iid_field, how='left', suffixes=(f'_{item_type}',", "source = self.field2source.get(field) if type(source) is str and source.startswith(\"item_\"): item_type = source.split(\"_\")[1] dataframe", "self.dfs = dataframes self.uid = uid_field self.iid = iid_field self.label = label_field def", "= {v: k for k, v in enumerate(dataframe[field].unique())} self.field2token_id[field].update(id_map) dataframe[field] = dataframe[field].map(id_map) if", "== item_type_id], self.uid_field, self.iid_field, self.itype_field, self.label_field, user_fs, item_fs[item_type]) self.val_inter_subset[item_type] = SubSet( val[val[type_field] ==", "self.field2source.get(field) if type(source) is str and source.startswith(\"item_\"): item_type = source.split(\"_\")[1] dataframe = self.item_feat[item_type]", "= new_mask self.inter_feat = self.inter_feat[mask] self.h_inter_feat = {} self.user_num = len(self.user_feat) self.item_num =", "source in ['item', 'user', FS.ITEM_ID, FS.USER_ID]: if field in self.inter_feat: self.inter_feat[field] = self.inter_feat[field].map(id_map)", "self.field2token_id = defaultdict(dict) self.user_feat_fields = [] self.item_feat_fields = defaultdict(list) for feat_name, feat_value in", "for k, v in enumerate(dataframe[field].unique())} self.field2token_id[field].update(id_map) dataframe[field] = dataframe[field].map(id_map) if source in ['item',", "field {field}.') ftype = self.field2type.get(field) assert ftype == 'token' source = self.field2source.get(field) if", "elif source is FS.ITEM_ID or source == \"item\": dataframe = pd.concat(list(self.item_feat.values()), join='inner') elif", "== 'user' and feat_name != self.uid_field: self.user_feat_fields.append(feat_name) if source.startswith('item') and feat_name != self.iid_field:", "item_fs = self.item_feat_fields type_field = self.itype_field self.train_inter_subset = {} self.val_inter_subset = {} self.test_inter_subset", "self.field2type.get(field) assert ftype == 'token' source = self.field2source.get(field) if type(source) is str and", "self.uid_field: self.user_feat_fields.append(feat_name) if source.startswith('item') and feat_name != self.iid_field: item_type = source.split(\"_\")[1] if item_type", "\"\"\" if self.user_feat is not None and self.uid_field in df: df = pd.merge(df,", "u_feat_fields, i_feat_fields): self.types = dataframes.keys() self.dfs = dataframes self.uid = uid_field self.iid =", "num_workers=num_workers) self.test_data_loader[item_type] = DataLoader( self.test_inter_subset[item_type], batch_size=batch_size, num_workers=num_workers) class HSubSet(Dataset): def __init__(self, dataframes, uid_field,", "self.val_inter_subset[item_type] = SubSet( val[val[type_field] == item_type_id], self.uid_field, self.iid_field, self.itype_field, self.label_field, user_fs, item_fs[item_type]) self.test_inter_subset[item_type]", "def _preprocessing(self): self._normalize() if len(self.types) < 3: self._reID(self.iid_field) self._reID(self.uid_field) def _load_item_feats(self, paths, source):", "len(ratios) == 3 if 'sample' in self.config: train, val, test = self.split_by_ratio_sampled( ratios,", "= dataframe[field].map(id_map) if source in ['item', 'user', FS.ITEM_ID, FS.USER_ID]: if field in self.inter_feat:", "in self.item_feat.items(): new_mask = self.inter_feat[self.iid_field].isin( item_feat[self.iid_field]) if mask is not None: mask =", "if os.path.isfile(item_path): feat = pd.read_csv(item_path) item_feat[item_type] = feat else: raise ValueError(\"Dataset file not", "# -*- coding:utf-8 -*- # ########################### # File Name: hdataset.py # Author: geekinglcq", "pin_memory=True, num_workers=num_workers) self.val_data_loader[item_type] = DataLoader( self.val_inter_subset[item_type], batch_size=batch_size, num_workers=num_workers) self.test_data_loader[item_type] = DataLoader( self.test_inter_subset[item_type], batch_size=batch_size,", "SubSet class HDataSet(DataSet): \"\"\" Dataset used for heterogenous items \"\"\" def __init__(self, config,", "axis=1) return df def join_interaction(self): self.inter_feat = self.join(self.inter_feat) if 'sample' in self.config: sample_ratio", "self.user_feat_fields item_fs = self.item_feat_fields type_field = self.itype_field self.train_inter_subset = {} self.val_inter_subset = {}", "1.0) kind_id = item_type_dict[kind] # preverse the data for val & test new_df", "\"\"\" Join user/item features to interactions. \"\"\" if self.user_feat is not None and", "is FS.ITEM_ID or source == \"item\": dataframe = pd.concat(list(self.item_feat.values()), join='inner') elif source ==", "self.config[\"type\"] self.field2type = {} self.field2source = {} self.field2id_token = defaultdict(dict) self.field2token_id = defaultdict(dict)", "dataframe = self.item_feat[item_type] elif source is FS.ITEM_ID or source == \"item\": dataframe =", "self.item_feat.items(): df = pd.merge(df, item_feat, on=self.iid_field, how='left', suffixes=(f'_{item_type}', '_inter')) type_c = [i for", "else: train, val, test = self.split_by_ratio(ratios, group_by=group_by, create_new_dataset=False) user_fs = self.user_feat_fields item_fs =", "sample_ratio.get(kind, 1.0) kind_id = item_type_dict[kind] # preverse the data for val & test", "ftype == 'token' source = self.field2source.get(field) if type(source) is str and source.startswith(\"item_\"): item_type", "pd.merge(df, self.user_feat, on=self.uid_field, how='left', suffixes=('_inter', '_user')) if self.item_feat is not None and self.iid_field", "self.field2source[feat_name] = feat_value['source'] if source == 'user' and feat_name != self.uid_field: self.user_feat_fields.append(feat_name) if", "== item_type_id], self.uid_field, self.iid_field, self.itype_field, self.label_field, user_fs, item_fs[item_type]) self.test_inter_subset[item_type] = SubSet( test[test[type_field] ==", "self.inter_feat = train def init_data_loader(self, batch_size=256, num_workers=1): self.train_data_loader = {} self.val_data_loader = {}", "= defaultdict(dict) self.user_feat_fields = [] self.item_feat_fields = defaultdict(list) for feat_name, feat_value in self.config['feat'].items():", "self.field2token_id[field].update(id_map) dataframe[field] = dataframe[field].map(id_map) if source in ['item', 'user', FS.ITEM_ID, FS.USER_ID]: if field", "logging.getLogger() self.name = self.config['name'] print(self.config) self.uid_field = self.config[\"USER_ID_FIELD\"] self.iid_field = self.config[\"ITEM_ID_FIELD\"] self.label_field =", "DataLoader( self.test_inter_subset[item_type], batch_size=batch_size, num_workers=num_workers) class HSubSet(Dataset): def __init__(self, dataframes, uid_field, iid_field, label_field, u_feat_fields,", "import os import logging from collections import defaultdict from torch.utils.data import DataLoader, Dataset", "Re-ID the token-type feature, save the id map in self.field2token_id \"\"\" self.logger.info(f'ReID field", "interaction features with train interaction fatures.\") self.logger.info( \"Interaction features are stored in self.all_inter_feat\")", "3: self._reID(self.iid_field) self._reID(self.uid_field) def _load_item_feats(self, paths, source): item_feat = {} for item_type, item_path", "len(self.user_feat[field].unique()) else: for item_type, item_feat_fields in self.item_feat_fields.items( ): if field in item_feat_fields: return", "\"item\": dataframe = pd.concat(list(self.item_feat.values()), join='inner') elif source == 'user' or source is FS.USER_ID:", "= self.inter_feat[mask] self.h_inter_feat = {} self.user_num = len(self.user_feat) self.item_num = sum([len(i) for i", "= self.inter_feat self.logger.info( \"Replace interaction features with train interaction fatures.\") self.logger.info( \"Interaction features", "== self.uid_field: return self.user_num if field == self.iid_field: return self.item_num if field not", "in ['item', 'user', FS.ITEM_ID, FS.USER_ID]: if field in self.inter_feat: self.inter_feat[field] = self.inter_feat[field].map(id_map) for", "{} self.user_num = len(self.user_feat) self.item_num = sum([len(i) for i in self.item_feat.values()]) self.item_nums =", "= pd.merge(df, self.user_feat, on=self.uid_field, how='left', suffixes=('_inter', '_user')) if self.item_feat is not None and", "i in self.item_feat.values()]) self.item_nums = {k: len(v) for k, v in self.item_feat.items()} print(f'user", "batch_size=batch_size, num_workers=num_workers) class HSubSet(Dataset): def __init__(self, dataframes, uid_field, iid_field, label_field, u_feat_fields, i_feat_fields): self.types", "DataLoader, Dataset from .enum_type import FeatureSource as FS from .enum_type import item_type_dict from", "new_mask = self.inter_feat[self.iid_field].isin( item_feat[self.iid_field]) if mask is not None: mask = mask |", "ValueError('field {} is not token type'.format(field)) if len(self.field2token_id[field]) == 0: if field in", "len(self.field2token_id[field]) == 0: if field in self.user_feat_fields: return len(self.user_feat[field].unique()) else: for item_type, item_feat_fields", "self.inter_feat[field].map(id_map) for item_type, item_feat in self.item_feat.items(): if field in item_feat: item_feat[field] = item_feat[field].map(id_map)", "self.inter_feat[self.inter_feat['type'] == kind_id].sample(frac=ratio * 0.7 + 0.3, random_state=16) print(kind, kind_id, ratio, new_df.shape) sampled.append(new_df)", "uid_field self.iid = iid_field self.label = label_field def __len__(self): return min([len(df.index) for df", "as pd import os import logging from collections import defaultdict from torch.utils.data import", "self.split_by_ratio(ratios, group_by=group_by, create_new_dataset=False) user_fs = self.user_feat_fields item_fs = self.item_feat_fields type_field = self.itype_field self.train_inter_subset", "# ########################### # File Name: hdataset.py # Author: geekinglcq # Mail: <EMAIL> #", "DataLoader( self.train_inter_subset[item_type], batch_size=batch_size, # pin_memory=True, num_workers=num_workers) self.val_data_loader[item_type] = DataLoader( self.val_inter_subset[item_type], batch_size=batch_size, num_workers=num_workers) self.test_data_loader[item_type]", "self.field2source = {} self.field2id_token = defaultdict(dict) self.field2token_id = defaultdict(dict) self.user_feat_fields = [] self.item_feat_fields", "num(self, field): if field == self.uid_field: return self.user_num if field == self.iid_field: return", "num: {self.user_num}') print(f'item num: {self.item_num}') print(f'item nums: {self.item_nums}') def _preprocessing(self): self._normalize() if len(self.types)", "if len(self.field2token_id[field]) == 0: if field in self.user_feat_fields: return len(self.user_feat[field].unique()) else: for item_type,", "len(self.item_feat[item_type][field].unique()) return len(self.field2token_id[field]) def _reID(self, field): \"\"\" Re-ID the token-type feature, save the", "in self.config: sample_ratio = self.config['sample'] sampled = [] for kind in self.types: ratio", "item_feat in self.item_feat.items(): df = pd.merge(df, item_feat, on=self.iid_field, how='left', suffixes=(f'_{item_type}', '_inter')) type_c =", "self.inter_feat[field] = self.inter_feat[field].map(id_map) for item_type, item_feat in self.item_feat.items(): if field in item_feat: item_feat[field]", "self.inter_feat[mask] self.h_inter_feat = {} self.user_num = len(self.user_feat) self.item_num = sum([len(i) for i in", "self.h_inter_feat = {} self.user_num = len(self.user_feat) self.item_num = sum([len(i) for i in self.item_feat.values()])", "feature, save the id map in self.field2token_id \"\"\" self.logger.info(f'ReID field {field}.') ftype =", "for item_type, item_feat in self.item_feat.items(): new_mask = self.inter_feat[self.iid_field].isin( item_feat[self.iid_field]) if mask is not", "self.item_nums = {k: len(v) for k, v in self.item_feat.items()} print(f'user num: {self.user_num}') print(f'item", "if field in item_feat_fields: return len(self.item_feat[item_type][field].unique()) return len(self.field2token_id[field]) def _reID(self, field): \"\"\" Re-ID", "for i in self.item_feat.values()]) self.item_nums = {k: len(v) for k, v in self.item_feat.items()}", "'sample' in self.config: sample_ratio = self.config['sample'] sampled = [] for kind in self.types:", "{} for item_type in self.types: self.train_data_loader[item_type] = DataLoader( self.train_inter_subset[item_type], batch_size=batch_size, # pin_memory=True, num_workers=num_workers)", "= {} self.test_inter_subset = {} for item_type in self.types: item_type_id = item_type_dict[item_type] self.train_inter_subset[item_type]", "= sample_ratio.get(kind, 1.0) kind_id = item_type_dict[kind] # preverse the data for val &", "in self.types: self.train_data_loader[item_type] = DataLoader( self.train_inter_subset[item_type], batch_size=batch_size, # pin_memory=True, num_workers=num_workers) self.val_data_loader[item_type] = DataLoader(", "= [] self.item_feat_fields = defaultdict(list) for feat_name, feat_value in self.config['feat'].items(): source = feat_value['source']", "dataframe = self.inter_feat id_map = {v: k for k, v in enumerate(dataframe[field].unique())} self.field2token_id[field].update(id_map)", "= source.split(\"_\")[1] if item_type in self.types: self.item_feat_fields[item_type].append(feat_name) def num(self, field): if field ==", "item_type_dict from .dataset import DataSet, SubSet class HDataSet(DataSet): \"\"\" Dataset used for heterogenous", "_reID(self, field): \"\"\" Re-ID the token-type feature, save the id map in self.field2token_id", "source == \"item\": dataframe = pd.concat(list(self.item_feat.values()), join='inner') elif source == 'user' or source", "ratios=[0.7, 0.2, 0.1], group_by=None, **kwargs): assert len(ratios) == 3 if 'sample' in self.config:", "item_type in self.types: self.train_data_loader[item_type] = DataLoader( self.train_inter_subset[item_type], batch_size=batch_size, # pin_memory=True, num_workers=num_workers) self.val_data_loader[item_type] =", "batch_size=batch_size, # pin_memory=True, num_workers=num_workers) self.val_data_loader[item_type] = DataLoader( self.val_inter_subset[item_type], batch_size=batch_size, num_workers=num_workers) self.test_data_loader[item_type] = DataLoader(", "DataLoader( self.val_inter_subset[item_type], batch_size=batch_size, num_workers=num_workers) self.test_data_loader[item_type] = DataLoader( self.test_inter_subset[item_type], batch_size=batch_size, num_workers=num_workers) class HSubSet(Dataset): def", "item_type_dict[kind] # preverse the data for val & test new_df = self.inter_feat[self.inter_feat['type'] ==", "== 'user' or source is FS.USER_ID: dataframe = self.user_feat else: dataframe = self.inter_feat", "fatures.\") self.logger.info( \"Interaction features are stored in self.all_inter_feat\") self.inter_feat = train def init_data_loader(self,", "[] self.item_feat_fields = defaultdict(list) for feat_name, feat_value in self.config['feat'].items(): source = feat_value['source'] self.field2type[feat_name]", "= self.split_by_ratio(ratios, group_by=group_by, create_new_dataset=False) user_fs = self.user_feat_fields item_fs = self.item_feat_fields type_field = self.itype_field", "**kwargs): assert len(ratios) == 3 if 'sample' in self.config: train, val, test =", "self.inter_feat = self.inter_feat.sample(frac=1.).reset_index( drop=True) def train_val_test_split(self, ratios=[0.7, 0.2, 0.1], group_by=None, **kwargs): assert len(ratios)", "for heterogenous items \"\"\" def __init__(self, config, restore_path=None): self.config = config self._init_setting() if", "logging from collections import defaultdict from torch.utils.data import DataLoader, Dataset from .enum_type import", "self.item_feat.items(): new_mask = self.inter_feat[self.iid_field].isin( item_feat[self.iid_field]) if mask is not None: mask = mask", "field in item_feat: item_feat[field] = item_feat[field].map(id_map) def join(self, df): \"\"\" Join user/item features", "0.2, 0.1], group_by=None, **kwargs): assert len(ratios) == 3 if 'sample' in self.config: train,", "-*- coding:utf-8 -*- # ########################### # File Name: hdataset.py # Author: geekinglcq #", "is None: self._load_feats() else: # TODO pass self._preprocessing() def _load_feats(self): self.user_feat = self._load_meta_feats(self.config[\"user_feat_path\"],", "feat_value['source'] self.field2type[feat_name] = feat_value['type'] self.field2source[feat_name] = feat_value['source'] if source == 'user' and feat_name", "3 if 'sample' in self.config: train, val, test = self.split_by_ratio_sampled( ratios, create_new_dataset=False) else:", "self.item_feat_fields type_field = self.itype_field self.train_inter_subset = {} self.val_inter_subset = {} self.test_inter_subset = {}", "defaultdict(dict) self.user_feat_fields = [] self.item_feat_fields = defaultdict(list) for feat_name, feat_value in self.config['feat'].items(): source", "item_fs[item_type]) self.test_inter_subset[item_type] = SubSet( test[test[type_field] == item_type_id], self.uid_field, self.iid_field, self.itype_field, self.label_field, user_fs, item_fs[item_type])", "self.item_feat = self._load_item_feats(self.config[\"item_feat_path\"], FS.ITEM) self.inter_feat = pd.read_csv(self.config[\"inter_feat_path\"]).sample( frac=1, random_state=28) mask = None if", "random_state=28) mask = None if len(self.types) < 3: for item_type, item_feat in self.item_feat.items():", "in self.field2type: raise ValueError('field {} not in dataset'.format(field)) # if field not in", "self.user_feat, on=self.uid_field, how='left', suffixes=('_inter', '_user')) if self.item_feat is not None and self.iid_field in", "= item_type_dict[item_type] self.train_inter_subset[item_type] = SubSet( train[train[type_field] == item_type_id], self.uid_field, self.iid_field, self.itype_field, self.label_field, user_fs,", "i_feat_fields): self.types = dataframes.keys() self.dfs = dataframes self.uid = uid_field self.iid = iid_field", "item_path in paths.items(): if item_type not in self.types: continue if os.path.isfile(item_path): feat =", "in df: df = pd.merge(df, self.user_feat, on=self.uid_field, how='left', suffixes=('_inter', '_user')) if self.item_feat is", "= len(self.user_feat) self.item_num = sum([len(i) for i in self.item_feat.values()]) self.item_nums = {k: len(v)", "pd.merge(df, item_feat, on=self.iid_field, how='left', suffixes=(f'_{item_type}', '_inter')) type_c = [i for i in df.columns", "train[train[type_field] == item_type_id], self.uid_field, self.iid_field, self.itype_field, self.label_field, user_fs, item_fs[item_type]) self.val_inter_subset[item_type] = SubSet( val[val[type_field]", "is not None and self.uid_field in df: df = pd.merge(df, self.user_feat, on=self.uid_field, how='left',", "field): \"\"\" Re-ID the token-type feature, save the id map in self.field2token_id \"\"\"", "self.iid_field in df: for item_type, item_feat in self.item_feat.items(): df = pd.merge(df, item_feat, on=self.iid_field,", "!= self.iid_field: item_type = source.split(\"_\")[1] if item_type in self.types: self.item_feat_fields[item_type].append(feat_name) def num(self, field):", "== 0: if field in self.user_feat_fields: return len(self.user_feat[field].unique()) else: for item_type, item_feat_fields in", "label_field, u_feat_fields, i_feat_fields): self.types = dataframes.keys() self.dfs = dataframes self.uid = uid_field self.iid", "self.train_data_loader[item_type] = DataLoader( self.train_inter_subset[item_type], batch_size=batch_size, # pin_memory=True, num_workers=num_workers) self.val_data_loader[item_type] = DataLoader( self.val_inter_subset[item_type], batch_size=batch_size,", "how='left', suffixes=(f'_{item_type}', '_inter')) type_c = [i for i in df.columns if i.startswith(self.itype_field)] df[self.itype_field]", "'token' source = self.field2source.get(field) if type(source) is str and source.startswith(\"item_\"): item_type = source.split(\"_\")[1]", "self.all_inter_feat\") self.inter_feat = train def init_data_loader(self, batch_size=256, num_workers=1): self.train_data_loader = {} self.val_data_loader =", "def join(self, df): \"\"\" Join user/item features to interactions. \"\"\" if self.user_feat is", "len(self.field2token_id[field]) def _reID(self, field): \"\"\" Re-ID the token-type feature, save the id map", "Created Time: 2020-12-28 20:17:47 # ########################### import pandas as pd import os import", "item_type = source.split(\"_\")[1] if item_type in self.types: self.item_feat_fields[item_type].append(feat_name) def num(self, field): if field", "or source is FS.USER_ID: dataframe = self.user_feat else: dataframe = self.inter_feat id_map =", "== kind_id].sample(frac=ratio * 0.7 + 0.3, random_state=16) print(kind, kind_id, ratio, new_df.shape) sampled.append(new_df) self.inter_feat", "| new_mask else: mask = new_mask self.inter_feat = self.inter_feat[mask] self.h_inter_feat = {} self.user_num", "& test new_df = self.inter_feat[self.inter_feat['type'] == kind_id].sample(frac=ratio * 0.7 + 0.3, random_state=16) print(kind,", "is not token type'.format(field)) if len(self.field2token_id[field]) == 0: if field in self.user_feat_fields: return", "self.user_feat = self._load_meta_feats(self.config[\"user_feat_path\"], FS.USER, \"user_id\") self.item_feat = self._load_item_feats(self.config[\"item_feat_path\"], FS.ITEM) self.inter_feat = pd.read_csv(self.config[\"inter_feat_path\"]).sample( frac=1,", "= self.inter_feat[self.iid_field].isin( item_feat[self.iid_field]) if mask is not None: mask = mask | new_mask", "kind_id].sample(frac=ratio * 0.7 + 0.3, random_state=16) print(kind, kind_id, ratio, new_df.shape) sampled.append(new_df) self.inter_feat =", "{} self.val_data_loader = {} self.test_data_loader = {} for item_type in self.types: self.train_data_loader[item_type] =", "= self._load_meta_feats(self.config[\"user_feat_path\"], FS.USER, \"user_id\") self.item_feat = self._load_item_feats(self.config[\"item_feat_path\"], FS.ITEM) self.inter_feat = pd.read_csv(self.config[\"inter_feat_path\"]).sample( frac=1, random_state=28)", "self.item_feat.values()]) self.item_nums = {k: len(v) for k, v in self.item_feat.items()} print(f'user num: {self.user_num}')", "{self.item_nums}') def _preprocessing(self): self._normalize() if len(self.types) < 3: self._reID(self.iid_field) self._reID(self.uid_field) def _load_item_feats(self, paths,", "item_type, item_feat_fields in self.item_feat_fields.items( ): if field in item_feat_fields: return len(self.item_feat[item_type][field].unique()) return len(self.field2token_id[field])", "if 'sample' in self.config: train, val, test = self.split_by_ratio_sampled( ratios, create_new_dataset=False) else: train,", "2020-12-28 20:17:47 # ########################### import pandas as pd import os import logging from", "self.label_field, user_fs, item_fs[item_type]) self.test_inter_subset[item_type] = SubSet( test[test[type_field] == item_type_id], self.uid_field, self.iid_field, self.itype_field, self.label_field,", "self.inter_feat = self.join(self.inter_feat) if 'sample' in self.config: sample_ratio = self.config['sample'] sampled = []", "if 'sample' in self.config: sample_ratio = self.config['sample'] sampled = [] for kind in", "dataframe[field] = dataframe[field].map(id_map) if source in ['item', 'user', FS.ITEM_ID, FS.USER_ID]: if field in", "= config self._init_setting() if restore_path is None: self._load_feats() else: # TODO pass self._preprocessing()", "self.config[\"LABEL_FIELD\"] self.itype_field = self.config[\"TYPE_FIELD\"] self.types = self.config[\"type\"] self.field2type = {} self.field2source = {}", "for val & test new_df = self.inter_feat[self.inter_feat['type'] == kind_id].sample(frac=ratio * 0.7 + 0.3,", "item_type not in self.types: continue if os.path.isfile(item_path): feat = pd.read_csv(item_path) item_feat[item_type] = feat", "for i in df.columns if i.startswith(self.itype_field)] df[self.itype_field] = df[type_c].agg(sum, axis=1) return df def", "= self.config[\"LABEL_FIELD\"] self.itype_field = self.config[\"TYPE_FIELD\"] self.types = self.config[\"type\"] self.field2type = {} self.field2source =", "dataframe[field].map(id_map) if source in ['item', 'user', FS.ITEM_ID, FS.USER_ID]: if field in self.inter_feat: self.inter_feat[field]", "self.user_feat_fields = [] self.item_feat_fields = defaultdict(list) for feat_name, feat_value in self.config['feat'].items(): source =", "= pd.merge(df, item_feat, on=self.iid_field, how='left', suffixes=(f'_{item_type}', '_inter')) type_c = [i for i in", "else: # TODO pass self._preprocessing() def _load_feats(self): self.user_feat = self._load_meta_feats(self.config[\"user_feat_path\"], FS.USER, \"user_id\") self.item_feat", "not None and self.uid_field in df: df = pd.merge(df, self.user_feat, on=self.uid_field, how='left', suffixes=('_inter',", "len(v) for k, v in self.item_feat.items()} print(f'user num: {self.user_num}') print(f'item num: {self.item_num}') print(f'item", "in self.types: continue if os.path.isfile(item_path): feat = pd.read_csv(item_path) item_feat[item_type] = feat else: raise", "# Mail: <EMAIL> # Created Time: 2020-12-28 20:17:47 # ########################### import pandas as", "= DataLoader( self.test_inter_subset[item_type], batch_size=batch_size, num_workers=num_workers) class HSubSet(Dataset): def __init__(self, dataframes, uid_field, iid_field, label_field,", "restore_path is None: self._load_feats() else: # TODO pass self._preprocessing() def _load_feats(self): self.user_feat =", "item_feat = {} for item_type, item_path in paths.items(): if item_type not in self.types:", "the id map in self.field2token_id \"\"\" self.logger.info(f'ReID field {field}.') ftype = self.field2type.get(field) assert", "'user' and feat_name != self.uid_field: self.user_feat_fields.append(feat_name) if source.startswith('item') and feat_name != self.iid_field: item_type", "{} self.test_inter_subset = {} for item_type in self.types: item_type_id = item_type_dict[item_type] self.train_inter_subset[item_type] =", "feat_value['type'] self.field2source[feat_name] = feat_value['source'] if source == 'user' and feat_name != self.uid_field: self.user_feat_fields.append(feat_name)", "pandas as pd import os import logging from collections import defaultdict from torch.utils.data", "else: mask = new_mask self.inter_feat = self.inter_feat[mask] self.h_inter_feat = {} self.user_num = len(self.user_feat)", "self.iid_field: item_type = source.split(\"_\")[1] if item_type in self.types: self.item_feat_fields[item_type].append(feat_name) def num(self, field): if", "num_workers=num_workers) self.val_data_loader[item_type] = DataLoader( self.val_inter_subset[item_type], batch_size=batch_size, num_workers=num_workers) self.test_data_loader[item_type] = DataLoader( self.test_inter_subset[item_type], batch_size=batch_size, num_workers=num_workers)", "self.iid = iid_field self.label = label_field def __len__(self): return min([len(df.index) for df in", "dataframe = pd.concat(list(self.item_feat.values()), join='inner') elif source == 'user' or source is FS.USER_ID: dataframe", "df): \"\"\" Join user/item features to interactions. \"\"\" if self.user_feat is not None", "new_df = self.inter_feat[self.inter_feat['type'] == kind_id].sample(frac=ratio * 0.7 + 0.3, random_state=16) print(kind, kind_id, ratio,", "val, test = self.split_by_ratio_sampled( ratios, create_new_dataset=False) else: train, val, test = self.split_by_ratio(ratios, group_by=group_by,", "config, restore_path=None): self.config = config self._init_setting() if restore_path is None: self._load_feats() else: #", "_preprocessing(self): self._normalize() if len(self.types) < 3: self._reID(self.iid_field) self._reID(self.uid_field) def _load_item_feats(self, paths, source): item_feat", "join(self, df): \"\"\" Join user/item features to interactions. \"\"\" if self.user_feat is not", "= {} self.val_inter_subset = {} self.test_inter_subset = {} for item_type in self.types: item_type_id", "= feat else: raise ValueError(\"Dataset file not fountd.\") return item_feat def _init_setting(self): self.logger", "feat_value['source'] if source == 'user' and feat_name != self.uid_field: self.user_feat_fields.append(feat_name) if source.startswith('item') and", "FS.USER_ID: dataframe = self.user_feat else: dataframe = self.inter_feat id_map = {v: k for", "= self.join(self.inter_feat) if 'sample' in self.config: sample_ratio = self.config['sample'] sampled = [] for", "user_fs, item_fs[item_type]) self.val_inter_subset[item_type] = SubSet( val[val[type_field] == item_type_id], self.uid_field, self.iid_field, self.itype_field, self.label_field, user_fs,", "item_feat_fields in self.item_feat_fields.items( ): if field in item_feat_fields: return len(self.item_feat[item_type][field].unique()) return len(self.field2token_id[field]) def", "how='left', suffixes=('_inter', '_user')) if self.item_feat is not None and self.iid_field in df: for", "self.inter_feat.sample(frac=1.).reset_index( drop=True) def train_val_test_split(self, ratios=[0.7, 0.2, 0.1], group_by=None, **kwargs): assert len(ratios) == 3", "\"\"\" Dataset used for heterogenous items \"\"\" def __init__(self, config, restore_path=None): self.config =", "self.val_inter_subset = {} self.test_inter_subset = {} for item_type in self.types: item_type_id = item_type_dict[item_type]", "item_feat in self.item_feat.items(): if field in item_feat: item_feat[field] = item_feat[field].map(id_map) def join(self, df):", "is not None and self.iid_field in df: for item_type, item_feat in self.item_feat.items(): df", "sample_ratio = self.config['sample'] sampled = [] for kind in self.types: ratio = sample_ratio.get(kind,", "type(source) is str and source.startswith(\"item_\"): item_type = source.split(\"_\")[1] dataframe = self.item_feat[item_type] elif source", "df[self.itype_field] = df[type_c].agg(sum, axis=1) return df def join_interaction(self): self.inter_feat = self.join(self.inter_feat) if 'sample'", "in item_feat_fields: return len(self.item_feat[item_type][field].unique()) return len(self.field2token_id[field]) def _reID(self, field): \"\"\" Re-ID the token-type", "init_data_loader(self, batch_size=256, num_workers=1): self.train_data_loader = {} self.val_data_loader = {} self.test_data_loader = {} for", "if field not in self.field2token_id: # raise ValueError('field {} is not token type'.format(field))", "= {} self.user_num = len(self.user_feat) self.item_num = sum([len(i) for i in self.item_feat.values()]) self.item_nums", "Dataset from .enum_type import FeatureSource as FS from .enum_type import item_type_dict from .dataset", "raise ValueError('field {} not in dataset'.format(field)) # if field not in self.field2token_id: #", "self.iid_field, self.itype_field, self.label_field, user_fs, item_fs[item_type]) self.all_inter_feat = self.inter_feat self.logger.info( \"Replace interaction features with", "= SubSet( train[train[type_field] == item_type_id], self.uid_field, self.iid_field, self.itype_field, self.label_field, user_fs, item_fs[item_type]) self.val_inter_subset[item_type] =", "def _load_item_feats(self, paths, source): item_feat = {} for item_type, item_path in paths.items(): if", "user/item features to interactions. \"\"\" if self.user_feat is not None and self.uid_field in", "item_feat def _init_setting(self): self.logger = logging.getLogger() self.name = self.config['name'] print(self.config) self.uid_field = self.config[\"USER_ID_FIELD\"]", "in self.types: item_type_id = item_type_dict[item_type] self.train_inter_subset[item_type] = SubSet( train[train[type_field] == item_type_id], self.uid_field, self.iid_field,", "item_type, item_path in paths.items(): if item_type not in self.types: continue if os.path.isfile(item_path): feat", "for item_type in self.types: self.train_data_loader[item_type] = DataLoader( self.train_inter_subset[item_type], batch_size=batch_size, # pin_memory=True, num_workers=num_workers) self.val_data_loader[item_type]", "the token-type feature, save the id map in self.field2token_id \"\"\" self.logger.info(f'ReID field {field}.')", "= self.config[\"type\"] self.field2type = {} self.field2source = {} self.field2id_token = defaultdict(dict) self.field2token_id =", "self.item_feat.items()} print(f'user num: {self.user_num}') print(f'item num: {self.item_num}') print(f'item nums: {self.item_nums}') def _preprocessing(self): self._normalize()", "{} not in dataset'.format(field)) # if field not in self.field2token_id: # raise ValueError('field", "source == 'user' and feat_name != self.uid_field: self.user_feat_fields.append(feat_name) if source.startswith('item') and feat_name !=", "self.item_num = sum([len(i) for i in self.item_feat.values()]) self.item_nums = {k: len(v) for k,", "enumerate(dataframe[field].unique())} self.field2token_id[field].update(id_map) dataframe[field] = dataframe[field].map(id_map) if source in ['item', 'user', FS.ITEM_ID, FS.USER_ID]: if", "join_interaction(self): self.inter_feat = self.join(self.inter_feat) if 'sample' in self.config: sample_ratio = self.config['sample'] sampled =", "= pd.read_csv(item_path) item_feat[item_type] = feat else: raise ValueError(\"Dataset file not fountd.\") return item_feat", "= self.item_feat[item_type] elif source is FS.ITEM_ID or source == \"item\": dataframe = pd.concat(list(self.item_feat.values()),", "in df: for item_type, item_feat in self.item_feat.items(): df = pd.merge(df, item_feat, on=self.iid_field, how='left',", "Time: 2020-12-28 20:17:47 # ########################### import pandas as pd import os import logging", "user_fs = self.user_feat_fields item_fs = self.item_feat_fields type_field = self.itype_field self.train_inter_subset = {} self.val_inter_subset", "if len(self.types) < 3: self._reID(self.iid_field) self._reID(self.uid_field) def _load_item_feats(self, paths, source): item_feat = {}", "class HSubSet(Dataset): def __init__(self, dataframes, uid_field, iid_field, label_field, u_feat_fields, i_feat_fields): self.types = dataframes.keys()", "len(self.types) < 3: for item_type, item_feat in self.item_feat.items(): new_mask = self.inter_feat[self.iid_field].isin( item_feat[self.iid_field]) if", "= [i for i in df.columns if i.startswith(self.itype_field)] df[self.itype_field] = df[type_c].agg(sum, axis=1) return", "self.uid_field = self.config[\"USER_ID_FIELD\"] self.iid_field = self.config[\"ITEM_ID_FIELD\"] self.label_field = self.config[\"LABEL_FIELD\"] self.itype_field = self.config[\"TYPE_FIELD\"] self.types", "i.startswith(self.itype_field)] df[self.itype_field] = df[type_c].agg(sum, axis=1) return df def join_interaction(self): self.inter_feat = self.join(self.inter_feat) if", "self.val_data_loader[item_type] = DataLoader( self.val_inter_subset[item_type], batch_size=batch_size, num_workers=num_workers) self.test_data_loader[item_type] = DataLoader( self.test_inter_subset[item_type], batch_size=batch_size, num_workers=num_workers) class", "train, val, test = self.split_by_ratio_sampled( ratios, create_new_dataset=False) else: train, val, test = self.split_by_ratio(ratios,", "kind_id, ratio, new_df.shape) sampled.append(new_df) self.inter_feat = pd.concat(sampled, ignore_index=True) self.inter_feat = self.inter_feat.sample(frac=1.).reset_index( drop=True) def", "self.inter_feat = self.inter_feat[mask] self.h_inter_feat = {} self.user_num = len(self.user_feat) self.item_num = sum([len(i) for", "token-type feature, save the id map in self.field2token_id \"\"\" self.logger.info(f'ReID field {field}.') ftype", "'_inter')) type_c = [i for i in df.columns if i.startswith(self.itype_field)] df[self.itype_field] = df[type_c].agg(sum,", "# TODO pass self._preprocessing() def _load_feats(self): self.user_feat = self._load_meta_feats(self.config[\"user_feat_path\"], FS.USER, \"user_id\") self.item_feat =", "return len(self.field2token_id[field]) def _reID(self, field): \"\"\" Re-ID the token-type feature, save the id", "in self.item_feat_fields.items( ): if field in item_feat_fields: return len(self.item_feat[item_type][field].unique()) return len(self.field2token_id[field]) def _reID(self,", "pd.concat(sampled, ignore_index=True) self.inter_feat = self.inter_feat.sample(frac=1.).reset_index( drop=True) def train_val_test_split(self, ratios=[0.7, 0.2, 0.1], group_by=None, **kwargs):", "item_type_id], self.uid_field, self.iid_field, self.itype_field, self.label_field, user_fs, item_fs[item_type]) self.val_inter_subset[item_type] = SubSet( val[val[type_field] == item_type_id],", "from .enum_type import item_type_dict from .dataset import DataSet, SubSet class HDataSet(DataSet): \"\"\" Dataset", "{v: k for k, v in enumerate(dataframe[field].unique())} self.field2token_id[field].update(id_map) dataframe[field] = dataframe[field].map(id_map) if source", "Mail: <EMAIL> # Created Time: 2020-12-28 20:17:47 # ########################### import pandas as pd", "if field in self.user_feat_fields: return len(self.user_feat[field].unique()) else: for item_type, item_feat_fields in self.item_feat_fields.items( ):", "feat_name != self.iid_field: item_type = source.split(\"_\")[1] if item_type in self.types: self.item_feat_fields[item_type].append(feat_name) def num(self,", "= source.split(\"_\")[1] dataframe = self.item_feat[item_type] elif source is FS.ITEM_ID or source == \"item\":", "HSubSet(Dataset): def __init__(self, dataframes, uid_field, iid_field, label_field, u_feat_fields, i_feat_fields): self.types = dataframes.keys() self.dfs", "_load_item_feats(self, paths, source): item_feat = {} for item_type, item_path in paths.items(): if item_type", "train_val_test_split(self, ratios=[0.7, 0.2, 0.1], group_by=None, **kwargs): assert len(ratios) == 3 if 'sample' in", "in self.config: train, val, test = self.split_by_ratio_sampled( ratios, create_new_dataset=False) else: train, val, test", "to interactions. \"\"\" if self.user_feat is not None and self.uid_field in df: df", "DataSet, SubSet class HDataSet(DataSet): \"\"\" Dataset used for heterogenous items \"\"\" def __init__(self,", "FS from .enum_type import item_type_dict from .dataset import DataSet, SubSet class HDataSet(DataSet): \"\"\"", "self.logger.info(f'ReID field {field}.') ftype = self.field2type.get(field) assert ftype == 'token' source = self.field2source.get(field)", "print(f'item nums: {self.item_nums}') def _preprocessing(self): self._normalize() if len(self.types) < 3: self._reID(self.iid_field) self._reID(self.uid_field) def", "self.logger = logging.getLogger() self.name = self.config['name'] print(self.config) self.uid_field = self.config[\"USER_ID_FIELD\"] self.iid_field = self.config[\"ITEM_ID_FIELD\"]", "ignore_index=True) self.inter_feat = self.inter_feat.sample(frac=1.).reset_index( drop=True) def train_val_test_split(self, ratios=[0.7, 0.2, 0.1], group_by=None, **kwargs): assert", "df = pd.merge(df, self.user_feat, on=self.uid_field, how='left', suffixes=('_inter', '_user')) if self.item_feat is not None", "= {} for item_type in self.types: self.train_data_loader[item_type] = DataLoader( self.train_inter_subset[item_type], batch_size=batch_size, # pin_memory=True,", "type'.format(field)) if len(self.field2token_id[field]) == 0: if field in self.user_feat_fields: return len(self.user_feat[field].unique()) else: for", "item_fs[item_type]) self.val_inter_subset[item_type] = SubSet( val[val[type_field] == item_type_id], self.uid_field, self.iid_field, self.itype_field, self.label_field, user_fs, item_fs[item_type])", "ValueError('field {} not in dataset'.format(field)) # if field not in self.field2token_id: # raise", "self.logger.info( \"Interaction features are stored in self.all_inter_feat\") self.inter_feat = train def init_data_loader(self, batch_size=256,", "used for heterogenous items \"\"\" def __init__(self, config, restore_path=None): self.config = config self._init_setting()", "import pandas as pd import os import logging from collections import defaultdict from", "= self.config['sample'] sampled = [] for kind in self.types: ratio = sample_ratio.get(kind, 1.0)", "item_feat[self.iid_field]) if mask is not None: mask = mask | new_mask else: mask", "ratios, create_new_dataset=False) else: train, val, test = self.split_by_ratio(ratios, group_by=group_by, create_new_dataset=False) user_fs = self.user_feat_fields", "= self.config[\"USER_ID_FIELD\"] self.iid_field = self.config[\"ITEM_ID_FIELD\"] self.label_field = self.config[\"LABEL_FIELD\"] self.itype_field = self.config[\"TYPE_FIELD\"] self.types =", "not in dataset'.format(field)) # if field not in self.field2token_id: # raise ValueError('field {}", "is not None: mask = mask | new_mask else: mask = new_mask self.inter_feat", "field == self.iid_field: return self.item_num if field not in self.field2type: raise ValueError('field {}", "feat_value in self.config['feat'].items(): source = feat_value['source'] self.field2type[feat_name] = feat_value['type'] self.field2source[feat_name] = feat_value['source'] if", "not None and self.iid_field in df: for item_type, item_feat in self.item_feat.items(): df =", "interactions. \"\"\" if self.user_feat is not None and self.uid_field in df: df =", "not in self.types: continue if os.path.isfile(item_path): feat = pd.read_csv(item_path) item_feat[item_type] = feat else:", "self.uid = uid_field self.iid = iid_field self.label = label_field def __len__(self): return min([len(df.index)", "= {} for item_type in self.types: item_type_id = item_type_dict[item_type] self.train_inter_subset[item_type] = SubSet( train[train[type_field]", "in self.inter_feat: self.inter_feat[field] = self.inter_feat[field].map(id_map) for item_type, item_feat in self.item_feat.items(): if field in", "if self.item_feat is not None and self.iid_field in df: for item_type, item_feat in", "k, v in self.item_feat.items()} print(f'user num: {self.user_num}') print(f'item num: {self.item_num}') print(f'item nums: {self.item_nums}')", "'sample' in self.config: train, val, test = self.split_by_ratio_sampled( ratios, create_new_dataset=False) else: train, val,", "group_by=group_by, create_new_dataset=False) user_fs = self.user_feat_fields item_fs = self.item_feat_fields type_field = self.itype_field self.train_inter_subset =", "= pd.concat(list(self.item_feat.values()), join='inner') elif source == 'user' or source is FS.USER_ID: dataframe =", "test = self.split_by_ratio(ratios, group_by=group_by, create_new_dataset=False) user_fs = self.user_feat_fields item_fs = self.item_feat_fields type_field =", "\"user_id\") self.item_feat = self._load_item_feats(self.config[\"item_feat_path\"], FS.ITEM) self.inter_feat = pd.read_csv(self.config[\"inter_feat_path\"]).sample( frac=1, random_state=28) mask = None", "id map in self.field2token_id \"\"\" self.logger.info(f'ReID field {field}.') ftype = self.field2type.get(field) assert ftype", "mask is not None: mask = mask | new_mask else: mask = new_mask", "# if field not in self.field2token_id: # raise ValueError('field {} is not token", "item_type_id = item_type_dict[item_type] self.train_inter_subset[item_type] = SubSet( train[train[type_field] == item_type_id], self.uid_field, self.iid_field, self.itype_field, self.label_field,", "user_fs, item_fs[item_type]) self.all_inter_feat = self.inter_feat self.logger.info( \"Replace interaction features with train interaction fatures.\")", "= iid_field self.label = label_field def __len__(self): return min([len(df.index) for df in self.dfs])", "Author: geekinglcq # Mail: <EMAIL> # Created Time: 2020-12-28 20:17:47 # ########################### import", "self.train_data_loader = {} self.val_data_loader = {} self.test_data_loader = {} for item_type in self.types:", "= pd.concat(sampled, ignore_index=True) self.inter_feat = self.inter_feat.sample(frac=1.).reset_index( drop=True) def train_val_test_split(self, ratios=[0.7, 0.2, 0.1], group_by=None,", "import FeatureSource as FS from .enum_type import item_type_dict from .dataset import DataSet, SubSet", "test[test[type_field] == item_type_id], self.uid_field, self.iid_field, self.itype_field, self.label_field, user_fs, item_fs[item_type]) self.all_inter_feat = self.inter_feat self.logger.info(", "= {} for item_type, item_path in paths.items(): if item_type not in self.types: continue", "= [] for kind in self.types: ratio = sample_ratio.get(kind, 1.0) kind_id = item_type_dict[kind]", "item_feat_fields: return len(self.item_feat[item_type][field].unique()) return len(self.field2token_id[field]) def _reID(self, field): \"\"\" Re-ID the token-type feature,", "= dataframes self.uid = uid_field self.iid = iid_field self.label = label_field def __len__(self):", "'_user')) if self.item_feat is not None and self.iid_field in df: for item_type, item_feat", "with train interaction fatures.\") self.logger.info( \"Interaction features are stored in self.all_inter_feat\") self.inter_feat =", "self.uid_field in df: df = pd.merge(df, self.user_feat, on=self.uid_field, how='left', suffixes=('_inter', '_user')) if self.item_feat", "{k: len(v) for k, v in self.item_feat.items()} print(f'user num: {self.user_num}') print(f'item num: {self.item_num}')", "self._load_item_feats(self.config[\"item_feat_path\"], FS.ITEM) self.inter_feat = pd.read_csv(self.config[\"inter_feat_path\"]).sample( frac=1, random_state=28) mask = None if len(self.types) <", "item_feat: item_feat[field] = item_feat[field].map(id_map) def join(self, df): \"\"\" Join user/item features to interactions.", "from torch.utils.data import DataLoader, Dataset from .enum_type import FeatureSource as FS from .enum_type", "{self.user_num}') print(f'item num: {self.item_num}') print(f'item nums: {self.item_nums}') def _preprocessing(self): self._normalize() if len(self.types) <", "{} self.field2id_token = defaultdict(dict) self.field2token_id = defaultdict(dict) self.user_feat_fields = [] self.item_feat_fields = defaultdict(list)", "i in df.columns if i.startswith(self.itype_field)] df[self.itype_field] = df[type_c].agg(sum, axis=1) return df def join_interaction(self):", "None and self.uid_field in df: df = pd.merge(df, self.user_feat, on=self.uid_field, how='left', suffixes=('_inter', '_user'))", "collections import defaultdict from torch.utils.data import DataLoader, Dataset from .enum_type import FeatureSource as", "Dataset used for heterogenous items \"\"\" def __init__(self, config, restore_path=None): self.config = config", "elif source == 'user' or source is FS.USER_ID: dataframe = self.user_feat else: dataframe", "item_type_id], self.uid_field, self.iid_field, self.itype_field, self.label_field, user_fs, item_fs[item_type]) self.all_inter_feat = self.inter_feat self.logger.info( \"Replace interaction", "v in enumerate(dataframe[field].unique())} self.field2token_id[field].update(id_map) dataframe[field] = dataframe[field].map(id_map) if source in ['item', 'user', FS.ITEM_ID,", "SubSet( test[test[type_field] == item_type_id], self.uid_field, self.iid_field, self.itype_field, self.label_field, user_fs, item_fs[item_type]) self.all_inter_feat = self.inter_feat", "in self.all_inter_feat\") self.inter_feat = train def init_data_loader(self, batch_size=256, num_workers=1): self.train_data_loader = {} self.val_data_loader", "iid_field, label_field, u_feat_fields, i_feat_fields): self.types = dataframes.keys() self.dfs = dataframes self.uid = uid_field", "= self.inter_feat[field].map(id_map) for item_type, item_feat in self.item_feat.items(): if field in item_feat: item_feat[field] =", "interaction fatures.\") self.logger.info( \"Interaction features are stored in self.all_inter_feat\") self.inter_feat = train def", "items \"\"\" def __init__(self, config, restore_path=None): self.config = config self._init_setting() if restore_path is", "features with train interaction fatures.\") self.logger.info( \"Interaction features are stored in self.all_inter_feat\") self.inter_feat", "self.label_field, user_fs, item_fs[item_type]) self.val_inter_subset[item_type] = SubSet( val[val[type_field] == item_type_id], self.uid_field, self.iid_field, self.itype_field, self.label_field,", "!= self.uid_field: self.user_feat_fields.append(feat_name) if source.startswith('item') and feat_name != self.iid_field: item_type = source.split(\"_\")[1] if", "def init_data_loader(self, batch_size=256, num_workers=1): self.train_data_loader = {} self.val_data_loader = {} self.test_data_loader = {}", "0.3, random_state=16) print(kind, kind_id, ratio, new_df.shape) sampled.append(new_df) self.inter_feat = pd.concat(sampled, ignore_index=True) self.inter_feat =", "for kind in self.types: ratio = sample_ratio.get(kind, 1.0) kind_id = item_type_dict[kind] # preverse", "and feat_name != self.uid_field: self.user_feat_fields.append(feat_name) if source.startswith('item') and feat_name != self.iid_field: item_type =", "# Author: geekinglcq # Mail: <EMAIL> # Created Time: 2020-12-28 20:17:47 # ###########################", "source.split(\"_\")[1] dataframe = self.item_feat[item_type] elif source is FS.ITEM_ID or source == \"item\": dataframe", "num: {self.item_num}') print(f'item nums: {self.item_nums}') def _preprocessing(self): self._normalize() if len(self.types) < 3: self._reID(self.iid_field)", "os import logging from collections import defaultdict from torch.utils.data import DataLoader, Dataset from", "else: dataframe = self.inter_feat id_map = {v: k for k, v in enumerate(dataframe[field].unique())}", "= defaultdict(list) for feat_name, feat_value in self.config['feat'].items(): source = feat_value['source'] self.field2type[feat_name] = feat_value['type']", "on=self.iid_field, how='left', suffixes=(f'_{item_type}', '_inter')) type_c = [i for i in df.columns if i.startswith(self.itype_field)]", "self.test_data_loader = {} for item_type in self.types: self.train_data_loader[item_type] = DataLoader( self.train_inter_subset[item_type], batch_size=batch_size, #", "self.iid_field: return self.item_num if field not in self.field2type: raise ValueError('field {} not in", "SubSet( val[val[type_field] == item_type_id], self.uid_field, self.iid_field, self.itype_field, self.label_field, user_fs, item_fs[item_type]) self.test_inter_subset[item_type] = SubSet(", "print(kind, kind_id, ratio, new_df.shape) sampled.append(new_df) self.inter_feat = pd.concat(sampled, ignore_index=True) self.inter_feat = self.inter_feat.sample(frac=1.).reset_index( drop=True)", "ratio = sample_ratio.get(kind, 1.0) kind_id = item_type_dict[kind] # preverse the data for val", "if item_type not in self.types: continue if os.path.isfile(item_path): feat = pd.read_csv(item_path) item_feat[item_type] =", "print(f'item num: {self.item_num}') print(f'item nums: {self.item_nums}') def _preprocessing(self): self._normalize() if len(self.types) < 3:", "{self.item_num}') print(f'item nums: {self.item_nums}') def _preprocessing(self): self._normalize() if len(self.types) < 3: self._reID(self.iid_field) self._reID(self.uid_field)", "is FS.USER_ID: dataframe = self.user_feat else: dataframe = self.inter_feat id_map = {v: k", "None and self.iid_field in df: for item_type, item_feat in self.item_feat.items(): df = pd.merge(df,", "and self.uid_field in df: df = pd.merge(df, self.user_feat, on=self.uid_field, how='left', suffixes=('_inter', '_user')) if", "< 3: for item_type, item_feat in self.item_feat.items(): new_mask = self.inter_feat[self.iid_field].isin( item_feat[self.iid_field]) if mask", "item_feat in self.item_feat.items(): new_mask = self.inter_feat[self.iid_field].isin( item_feat[self.iid_field]) if mask is not None: mask", "{} for item_type, item_path in paths.items(): if item_type not in self.types: continue if", "if self.user_feat is not None and self.uid_field in df: df = pd.merge(df, self.user_feat,", "df.columns if i.startswith(self.itype_field)] df[self.itype_field] = df[type_c].agg(sum, axis=1) return df def join_interaction(self): self.inter_feat =", "self.config['feat'].items(): source = feat_value['source'] self.field2type[feat_name] = feat_value['type'] self.field2source[feat_name] = feat_value['source'] if source ==", "if mask is not None: mask = mask | new_mask else: mask =", "'user', FS.ITEM_ID, FS.USER_ID]: if field in self.inter_feat: self.inter_feat[field] = self.inter_feat[field].map(id_map) for item_type, item_feat", "self.types: ratio = sample_ratio.get(kind, 1.0) kind_id = item_type_dict[kind] # preverse the data for", "token type'.format(field)) if len(self.field2token_id[field]) == 0: if field in self.user_feat_fields: return len(self.user_feat[field].unique()) else:", "= train def init_data_loader(self, batch_size=256, num_workers=1): self.train_data_loader = {} self.val_data_loader = {} self.test_data_loader", "{} self.field2source = {} self.field2id_token = defaultdict(dict) self.field2token_id = defaultdict(dict) self.user_feat_fields = []", "val, test = self.split_by_ratio(ratios, group_by=group_by, create_new_dataset=False) user_fs = self.user_feat_fields item_fs = self.item_feat_fields type_field", "= self.split_by_ratio_sampled( ratios, create_new_dataset=False) else: train, val, test = self.split_by_ratio(ratios, group_by=group_by, create_new_dataset=False) user_fs", "self.name = self.config['name'] print(self.config) self.uid_field = self.config[\"USER_ID_FIELD\"] self.iid_field = self.config[\"ITEM_ID_FIELD\"] self.label_field = self.config[\"LABEL_FIELD\"]", "in self.user_feat_fields: return len(self.user_feat[field].unique()) else: for item_type, item_feat_fields in self.item_feat_fields.items( ): if field", "self.uid_field, self.iid_field, self.itype_field, self.label_field, user_fs, item_fs[item_type]) self.all_inter_feat = self.inter_feat self.logger.info( \"Replace interaction features", "= {} self.val_data_loader = {} self.test_data_loader = {} for item_type in self.types: self.train_data_loader[item_type]", "\"Replace interaction features with train interaction fatures.\") self.logger.info( \"Interaction features are stored in", "v in self.item_feat.items()} print(f'user num: {self.user_num}') print(f'item num: {self.item_num}') print(f'item nums: {self.item_nums}') def", "self.logger.info( \"Replace interaction features with train interaction fatures.\") self.logger.info( \"Interaction features are stored", "None: self._load_feats() else: # TODO pass self._preprocessing() def _load_feats(self): self.user_feat = self._load_meta_feats(self.config[\"user_feat_path\"], FS.USER,", "item_type in self.types: item_type_id = item_type_dict[item_type] self.train_inter_subset[item_type] = SubSet( train[train[type_field] == item_type_id], self.uid_field,", "if field in item_feat: item_feat[field] = item_feat[field].map(id_map) def join(self, df): \"\"\" Join user/item", "# Created Time: 2020-12-28 20:17:47 # ########################### import pandas as pd import os", "else: raise ValueError(\"Dataset file not fountd.\") return item_feat def _init_setting(self): self.logger = logging.getLogger()", "batch_size=batch_size, num_workers=num_workers) self.test_data_loader[item_type] = DataLoader( self.test_inter_subset[item_type], batch_size=batch_size, num_workers=num_workers) class HSubSet(Dataset): def __init__(self, dataframes,", "is str and source.startswith(\"item_\"): item_type = source.split(\"_\")[1] dataframe = self.item_feat[item_type] elif source is", "self.test_inter_subset[item_type] = SubSet( test[test[type_field] == item_type_id], self.uid_field, self.iid_field, self.itype_field, self.label_field, user_fs, item_fs[item_type]) self.all_inter_feat", "for item_type, item_path in paths.items(): if item_type not in self.types: continue if os.path.isfile(item_path):", "df = pd.merge(df, item_feat, on=self.iid_field, how='left', suffixes=(f'_{item_type}', '_inter')) type_c = [i for i", "<EMAIL> # Created Time: 2020-12-28 20:17:47 # ########################### import pandas as pd import", "########################### import pandas as pd import os import logging from collections import defaultdict", "on=self.uid_field, how='left', suffixes=('_inter', '_user')) if self.item_feat is not None and self.iid_field in df:", "-*- # ########################### # File Name: hdataset.py # Author: geekinglcq # Mail: <EMAIL>", "assert len(ratios) == 3 if 'sample' in self.config: train, val, test = self.split_by_ratio_sampled(", "dataset'.format(field)) # if field not in self.field2token_id: # raise ValueError('field {} is not", "self.config[\"ITEM_ID_FIELD\"] self.label_field = self.config[\"LABEL_FIELD\"] self.itype_field = self.config[\"TYPE_FIELD\"] self.types = self.config[\"type\"] self.field2type = {}", "self.itype_field self.train_inter_subset = {} self.val_inter_subset = {} self.test_inter_subset = {} for item_type in", "self.config['name'] print(self.config) self.uid_field = self.config[\"USER_ID_FIELD\"] self.iid_field = self.config[\"ITEM_ID_FIELD\"] self.label_field = self.config[\"LABEL_FIELD\"] self.itype_field =", "# pin_memory=True, num_workers=num_workers) self.val_data_loader[item_type] = DataLoader( self.val_inter_subset[item_type], batch_size=batch_size, num_workers=num_workers) self.test_data_loader[item_type] = DataLoader( self.test_inter_subset[item_type],", "import DataSet, SubSet class HDataSet(DataSet): \"\"\" Dataset used for heterogenous items \"\"\" def", "self.item_num if field not in self.field2type: raise ValueError('field {} not in dataset'.format(field)) #", "import item_type_dict from .dataset import DataSet, SubSet class HDataSet(DataSet): \"\"\" Dataset used for", "self.user_feat else: dataframe = self.inter_feat id_map = {v: k for k, v in", "item_type, item_feat in self.item_feat.items(): if field in item_feat: item_feat[field] = item_feat[field].map(id_map) def join(self,", "self.train_inter_subset[item_type], batch_size=batch_size, # pin_memory=True, num_workers=num_workers) self.val_data_loader[item_type] = DataLoader( self.val_inter_subset[item_type], batch_size=batch_size, num_workers=num_workers) self.test_data_loader[item_type] =", "self.types: self.train_data_loader[item_type] = DataLoader( self.train_inter_subset[item_type], batch_size=batch_size, # pin_memory=True, num_workers=num_workers) self.val_data_loader[item_type] = DataLoader( self.val_inter_subset[item_type],", "self.user_feat_fields: return len(self.user_feat[field].unique()) else: for item_type, item_feat_fields in self.item_feat_fields.items( ): if field in", "self.item_feat is not None and self.iid_field in df: for item_type, item_feat in self.item_feat.items():", "user_fs, item_fs[item_type]) self.test_inter_subset[item_type] = SubSet( test[test[type_field] == item_type_id], self.uid_field, self.iid_field, self.itype_field, self.label_field, user_fs,", "return df def join_interaction(self): self.inter_feat = self.join(self.inter_feat) if 'sample' in self.config: sample_ratio =", "self._normalize() if len(self.types) < 3: self._reID(self.iid_field) self._reID(self.uid_field) def _load_item_feats(self, paths, source): item_feat =", "type_field = self.itype_field self.train_inter_subset = {} self.val_inter_subset = {} self.test_inter_subset = {} for", "not None: mask = mask | new_mask else: mask = new_mask self.inter_feat =", "HDataSet(DataSet): \"\"\" Dataset used for heterogenous items \"\"\" def __init__(self, config, restore_path=None): self.config", "df: df = pd.merge(df, self.user_feat, on=self.uid_field, how='left', suffixes=('_inter', '_user')) if self.item_feat is not", "feat_name != self.uid_field: self.user_feat_fields.append(feat_name) if source.startswith('item') and feat_name != self.iid_field: item_type = source.split(\"_\")[1]", "data for val & test new_df = self.inter_feat[self.inter_feat['type'] == kind_id].sample(frac=ratio * 0.7 +", "= self.itype_field self.train_inter_subset = {} self.val_inter_subset = {} self.test_inter_subset = {} for item_type", "FS.ITEM_ID or source == \"item\": dataframe = pd.concat(list(self.item_feat.values()), join='inner') elif source == 'user'", "ratio, new_df.shape) sampled.append(new_df) self.inter_feat = pd.concat(sampled, ignore_index=True) self.inter_feat = self.inter_feat.sample(frac=1.).reset_index( drop=True) def train_val_test_split(self,", "self.iid_field = self.config[\"ITEM_ID_FIELD\"] self.label_field = self.config[\"LABEL_FIELD\"] self.itype_field = self.config[\"TYPE_FIELD\"] self.types = self.config[\"type\"] self.field2type", "self.config: train, val, test = self.split_by_ratio_sampled( ratios, create_new_dataset=False) else: train, val, test =", "== 'token' source = self.field2source.get(field) if type(source) is str and source.startswith(\"item_\"): item_type =", "def _init_setting(self): self.logger = logging.getLogger() self.name = self.config['name'] print(self.config) self.uid_field = self.config[\"USER_ID_FIELD\"] self.iid_field", "= DataLoader( self.val_inter_subset[item_type], batch_size=batch_size, num_workers=num_workers) self.test_data_loader[item_type] = DataLoader( self.test_inter_subset[item_type], batch_size=batch_size, num_workers=num_workers) class HSubSet(Dataset):", "in paths.items(): if item_type not in self.types: continue if os.path.isfile(item_path): feat = pd.read_csv(item_path)", "== item_type_id], self.uid_field, self.iid_field, self.itype_field, self.label_field, user_fs, item_fs[item_type]) self.all_inter_feat = self.inter_feat self.logger.info( \"Replace", "self.val_inter_subset[item_type], batch_size=batch_size, num_workers=num_workers) self.test_data_loader[item_type] = DataLoader( self.test_inter_subset[item_type], batch_size=batch_size, num_workers=num_workers) class HSubSet(Dataset): def __init__(self,", "self.field2type = {} self.field2source = {} self.field2id_token = defaultdict(dict) self.field2token_id = defaultdict(dict) self.user_feat_fields", "\"\"\" def __init__(self, config, restore_path=None): self.config = config self._init_setting() if restore_path is None:", "# ########################### import pandas as pd import os import logging from collections import", "if type(source) is str and source.startswith(\"item_\"): item_type = source.split(\"_\")[1] dataframe = self.item_feat[item_type] elif", "pass self._preprocessing() def _load_feats(self): self.user_feat = self._load_meta_feats(self.config[\"user_feat_path\"], FS.USER, \"user_id\") self.item_feat = self._load_item_feats(self.config[\"item_feat_path\"], FS.ITEM)", "FS.ITEM) self.inter_feat = pd.read_csv(self.config[\"inter_feat_path\"]).sample( frac=1, random_state=28) mask = None if len(self.types) < 3:", "= feat_value['source'] if source == 'user' and feat_name != self.uid_field: self.user_feat_fields.append(feat_name) if source.startswith('item')", "= self.config['name'] print(self.config) self.uid_field = self.config[\"USER_ID_FIELD\"] self.iid_field = self.config[\"ITEM_ID_FIELD\"] self.label_field = self.config[\"LABEL_FIELD\"] self.itype_field", "< 3: self._reID(self.iid_field) self._reID(self.uid_field) def _load_item_feats(self, paths, source): item_feat = {} for item_type,", "source.startswith('item') and feat_name != self.iid_field: item_type = source.split(\"_\")[1] if item_type in self.types: self.item_feat_fields[item_type].append(feat_name)", "if source.startswith('item') and feat_name != self.iid_field: item_type = source.split(\"_\")[1] if item_type in self.types:", "def __init__(self, dataframes, uid_field, iid_field, label_field, u_feat_fields, i_feat_fields): self.types = dataframes.keys() self.dfs =", "None if len(self.types) < 3: for item_type, item_feat in self.item_feat.items(): new_mask = self.inter_feat[self.iid_field].isin(", "self.types: item_type_id = item_type_dict[item_type] self.train_inter_subset[item_type] = SubSet( train[train[type_field] == item_type_id], self.uid_field, self.iid_field, self.itype_field,", "num_workers=1): self.train_data_loader = {} self.val_data_loader = {} self.test_data_loader = {} for item_type in", "from .dataset import DataSet, SubSet class HDataSet(DataSet): \"\"\" Dataset used for heterogenous items", "self.item_feat_fields = defaultdict(list) for feat_name, feat_value in self.config['feat'].items(): source = feat_value['source'] self.field2type[feat_name] =", "import DataLoader, Dataset from .enum_type import FeatureSource as FS from .enum_type import item_type_dict", "__init__(self, dataframes, uid_field, iid_field, label_field, u_feat_fields, i_feat_fields): self.types = dataframes.keys() self.dfs = dataframes", "in self.config['feat'].items(): source = feat_value['source'] self.field2type[feat_name] = feat_value['type'] self.field2source[feat_name] = feat_value['source'] if source", "assert ftype == 'token' source = self.field2source.get(field) if type(source) is str and source.startswith(\"item_\"):", "self.config[\"TYPE_FIELD\"] self.types = self.config[\"type\"] self.field2type = {} self.field2source = {} self.field2id_token = defaultdict(dict)", "self._load_meta_feats(self.config[\"user_feat_path\"], FS.USER, \"user_id\") self.item_feat = self._load_item_feats(self.config[\"item_feat_path\"], FS.ITEM) self.inter_feat = pd.read_csv(self.config[\"inter_feat_path\"]).sample( frac=1, random_state=28) mask", "= item_type_dict[kind] # preverse the data for val & test new_df = self.inter_feat[self.inter_feat['type']", "random_state=16) print(kind, kind_id, ratio, new_df.shape) sampled.append(new_df) self.inter_feat = pd.concat(sampled, ignore_index=True) self.inter_feat = self.inter_feat.sample(frac=1.).reset_index(", "= {} self.test_data_loader = {} for item_type in self.types: self.train_data_loader[item_type] = DataLoader( self.train_inter_subset[item_type],", "train def init_data_loader(self, batch_size=256, num_workers=1): self.train_data_loader = {} self.val_data_loader = {} self.test_data_loader =", "mask = new_mask self.inter_feat = self.inter_feat[mask] self.h_inter_feat = {} self.user_num = len(self.user_feat) self.item_num", "== 3 if 'sample' in self.config: train, val, test = self.split_by_ratio_sampled( ratios, create_new_dataset=False)", "if restore_path is None: self._load_feats() else: # TODO pass self._preprocessing() def _load_feats(self): self.user_feat", "coding:utf-8 -*- # ########################### # File Name: hdataset.py # Author: geekinglcq # Mail:", "train interaction fatures.\") self.logger.info( \"Interaction features are stored in self.all_inter_feat\") self.inter_feat = train" ]
[ "decode(dct): if \"data\" in dct: return dct[\"data\"] elif \"config\" in dct: return dct[\"config\"]", "= json.loads(datum, object_hook=decode) for idx, config in enumerate(configs): plt.figure(idx+1) xdata = arr[config[0]] ydata", "# Add first coordinates l.set_xdata([xdata]) l.set_ydata([ydata]) # Update plot plt.draw() # Socket address", "Bind socket to address s.bind((HOST, PORT)) # Listen (1 connection in buffer) s.listen(1)", "for idx, config in enumerate(configs): plt.figure(idx+1) xdata = arr[config[0]] ydata = arr[config[1]] l", "address HOST = '127.0.0.1' PORT = 8080 # Open socket s = socket.socket(socket.AF_INET,", "conn, addr = s.accept() print \"Connected by\", addr configs = conn.recv(1024) configs =", "idx += 1 plt.figure(idx) if \"xlabel\" in dct: plt.xlabel(dct[\"xlabel\"]) if \"ylabel\" in dct:", "Adjust axis limits plt.xlim(0, np.amax(l.get_xdata())*1.05) plt.ylim(0, np.amax(l.get_ydata())*1.05) else: # Add first coordinates l.set_xdata([xdata])", "Open socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind socket to address s.bind((HOST, PORT))", "0 lines = [] def decode(dct): if \"data\" in dct: return dct[\"data\"] elif", "= socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind socket to address s.bind((HOST, PORT)) # Listen (1", "> 0: # Append new data l.set_xdata(np.append(x, xdata)) l.set_ydata(np.append(y, ydata)) # Adjust axis", "plt.xlim(0, np.amax(l.get_xdata())*1.05) plt.ylim(0, np.amax(l.get_ydata())*1.05) else: # Add first coordinates l.set_xdata([xdata]) l.set_ydata([ydata]) # Update", "= lines[idx] x = l.get_xdata() y = l.get_ydata() if len(x) > 0: #", "\"y\" in dct: global idx, lines idx += 1 plt.figure(idx) if \"xlabel\" in", "connection in buffer) s.listen(1) # Accept connection conn, addr = s.accept() print \"Connected", "addr = s.accept() print \"Connected by\", addr configs = conn.recv(1024) configs = json.loads(configs,", "except: # Handle invalid data without closing connection print \"Invalid data received\" else:", "\"ylabel\" in dct: plt.ylabel(dct[\"ylabel\"]) l, = plt.plot([], [], 'r-') lines.append(l) return [dct[\"x\"], dct[\"y\"]]", "If data is not terminating try: # Process and plot data process(lines, datum,", "= conn.recv(1024) configs = json.loads(configs, object_hook=decode) plt.show(block=False) conn.sendall('Ready') while 1: # Receive data", "dct: return dct[\"data\"] elif \"config\" in dct: return dct[\"config\"] elif \"config\" not in", "JSON\" def process(lines, datum, configs): arr = json.loads(datum, object_hook=decode) for idx, config in", "1: # Receive data datum = conn.recv(1024) if datum: # If data is", "socket import matplotlib.pyplot as plt import numpy as np import json idx =", "if len(x) > 0: # Append new data l.set_xdata(np.append(x, xdata)) l.set_ydata(np.append(y, ydata)) #", "l.set_xdata(np.append(x, xdata)) l.set_ydata(np.append(y, ydata)) # Adjust axis limits plt.xlim(0, np.amax(l.get_xdata())*1.05) plt.ylim(0, np.amax(l.get_ydata())*1.05) else:", "to address s.bind((HOST, PORT)) # Listen (1 connection in buffer) s.listen(1) # Accept", "new data l.set_xdata(np.append(x, xdata)) l.set_ydata(np.append(y, ydata)) # Adjust axis limits plt.xlim(0, np.amax(l.get_xdata())*1.05) plt.ylim(0,", "dct and \"y\" in dct: global idx, lines idx += 1 plt.figure(idx) if", "invalid data without closing connection print \"Invalid data received\" else: # If data", "dct: plt.ylabel(dct[\"ylabel\"]) l, = plt.plot([], [], 'r-') lines.append(l) return [dct[\"x\"], dct[\"y\"]] else: return", "# Close connection conn.close() # Close socket s.close() # Keep showing plot plt.show()", "# Bind socket to address s.bind((HOST, PORT)) # Listen (1 connection in buffer)", "as np import json idx = 0 lines = [] def decode(dct): if", "elif \"config\" not in dct and \"x\" in dct and \"y\" in dct:", "\"data\" in dct: return dct[\"data\"] elif \"config\" in dct: return dct[\"config\"] elif \"config\"", "json.loads(datum, object_hook=decode) for idx, config in enumerate(configs): plt.figure(idx+1) xdata = arr[config[0]] ydata =", "buffer) s.listen(1) # Accept connection conn, addr = s.accept() print \"Connected by\", addr", "conn.recv(1024) configs = json.loads(configs, object_hook=decode) plt.show(block=False) conn.sendall('Ready') while 1: # Receive data datum", "datum: # If data is not terminating try: # Process and plot data", "= l.get_ydata() if len(x) > 0: # Append new data l.set_xdata(np.append(x, xdata)) l.set_ydata(np.append(y,", "If data is terminating break # Close connection conn.close() # Close socket s.close()", "<filename>src/controllerarena/loggers/VisualLogger.py<gh_stars>0 import socket import matplotlib.pyplot as plt import numpy as np import json", "configs) except: # Handle invalid data without closing connection print \"Invalid data received\"", "in dct: return dct[\"config\"] elif \"config\" not in dct and \"x\" in dct", "Receive data datum = conn.recv(1024) if datum: # If data is not terminating", "dct: plt.xlabel(dct[\"xlabel\"]) if \"ylabel\" in dct: plt.ylabel(dct[\"ylabel\"]) l, = plt.plot([], [], 'r-') lines.append(l)", "lines.append(l) return [dct[\"x\"], dct[\"y\"]] else: return \"Invalid JSON\" def process(lines, datum, configs): arr", "l.set_ydata([ydata]) # Update plot plt.draw() # Socket address HOST = '127.0.0.1' PORT =", "l.set_xdata([xdata]) l.set_ydata([ydata]) # Update plot plt.draw() # Socket address HOST = '127.0.0.1' PORT", "l.get_ydata() if len(x) > 0: # Append new data l.set_xdata(np.append(x, xdata)) l.set_ydata(np.append(y, ydata))", "in dct: return dct[\"data\"] elif \"config\" in dct: return dct[\"config\"] elif \"config\" not", "idx, config in enumerate(configs): plt.figure(idx+1) xdata = arr[config[0]] ydata = arr[config[1]] l =", "global idx, lines idx += 1 plt.figure(idx) if \"xlabel\" in dct: plt.xlabel(dct[\"xlabel\"]) if", "print \"Connected by\", addr configs = conn.recv(1024) configs = json.loads(configs, object_hook=decode) plt.show(block=False) conn.sendall('Ready')", "# Receive data datum = conn.recv(1024) if datum: # If data is not", "import matplotlib.pyplot as plt import numpy as np import json idx = 0", "datum = conn.recv(1024) if datum: # If data is not terminating try: #", "import numpy as np import json idx = 0 lines = [] def", "# Process and plot data process(lines, datum, configs) except: # Handle invalid data", "np.amax(l.get_ydata())*1.05) else: # Add first coordinates l.set_xdata([xdata]) l.set_ydata([ydata]) # Update plot plt.draw() #", "configs = json.loads(configs, object_hook=decode) plt.show(block=False) conn.sendall('Ready') while 1: # Receive data datum =", "Update plot plt.draw() # Socket address HOST = '127.0.0.1' PORT = 8080 #", "plt.show(block=False) conn.sendall('Ready') while 1: # Receive data datum = conn.recv(1024) if datum: #", "return dct[\"config\"] elif \"config\" not in dct and \"x\" in dct and \"y\"", "l = lines[idx] x = l.get_xdata() y = l.get_ydata() if len(x) > 0:", "matplotlib.pyplot as plt import numpy as np import json idx = 0 lines", "terminating try: # Process and plot data process(lines, datum, configs) except: # Handle", "plt import numpy as np import json idx = 0 lines = []", "axis limits plt.xlim(0, np.amax(l.get_xdata())*1.05) plt.ylim(0, np.amax(l.get_ydata())*1.05) else: # Add first coordinates l.set_xdata([xdata]) l.set_ydata([ydata])", "dct[\"y\"]] else: return \"Invalid JSON\" def process(lines, datum, configs): arr = json.loads(datum, object_hook=decode)", "s.accept() print \"Connected by\", addr configs = conn.recv(1024) configs = json.loads(configs, object_hook=decode) plt.show(block=False)", "terminating break # Close connection conn.close() # Close socket s.close() # Keep showing", "idx = 0 lines = [] def decode(dct): if \"data\" in dct: return", "dct[\"config\"] elif \"config\" not in dct and \"x\" in dct and \"y\" in", "= arr[config[0]] ydata = arr[config[1]] l = lines[idx] x = l.get_xdata() y =", "import json idx = 0 lines = [] def decode(dct): if \"data\" in", "socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind socket to address s.bind((HOST, PORT)) # Listen (1 connection", "in enumerate(configs): plt.figure(idx+1) xdata = arr[config[0]] ydata = arr[config[1]] l = lines[idx] x", "xdata = arr[config[0]] ydata = arr[config[1]] l = lines[idx] x = l.get_xdata() y", "# Adjust axis limits plt.xlim(0, np.amax(l.get_xdata())*1.05) plt.ylim(0, np.amax(l.get_ydata())*1.05) else: # Add first coordinates", "closing connection print \"Invalid data received\" else: # If data is terminating break", "Add first coordinates l.set_xdata([xdata]) l.set_ydata([ydata]) # Update plot plt.draw() # Socket address HOST", "def process(lines, datum, configs): arr = json.loads(datum, object_hook=decode) for idx, config in enumerate(configs):", "json idx = 0 lines = [] def decode(dct): if \"data\" in dct:", "lines idx += 1 plt.figure(idx) if \"xlabel\" in dct: plt.xlabel(dct[\"xlabel\"]) if \"ylabel\" in", "socket to address s.bind((HOST, PORT)) # Listen (1 connection in buffer) s.listen(1) #", "Accept connection conn, addr = s.accept() print \"Connected by\", addr configs = conn.recv(1024)", "\"x\" in dct and \"y\" in dct: global idx, lines idx += 1", "Append new data l.set_xdata(np.append(x, xdata)) l.set_ydata(np.append(y, ydata)) # Adjust axis limits plt.xlim(0, np.amax(l.get_xdata())*1.05)", "\"xlabel\" in dct: plt.xlabel(dct[\"xlabel\"]) if \"ylabel\" in dct: plt.ylabel(dct[\"ylabel\"]) l, = plt.plot([], [],", "limits plt.xlim(0, np.amax(l.get_xdata())*1.05) plt.ylim(0, np.amax(l.get_ydata())*1.05) else: # Add first coordinates l.set_xdata([xdata]) l.set_ydata([ydata]) #", "np import json idx = 0 lines = [] def decode(dct): if \"data\"", "= 0 lines = [] def decode(dct): if \"data\" in dct: return dct[\"data\"]", "dct[\"data\"] elif \"config\" in dct: return dct[\"config\"] elif \"config\" not in dct and", "plt.ylabel(dct[\"ylabel\"]) l, = plt.plot([], [], 'r-') lines.append(l) return [dct[\"x\"], dct[\"y\"]] else: return \"Invalid", "\"Invalid JSON\" def process(lines, datum, configs): arr = json.loads(datum, object_hook=decode) for idx, config", "plt.ylim(0, np.amax(l.get_ydata())*1.05) else: # Add first coordinates l.set_xdata([xdata]) l.set_ydata([ydata]) # Update plot plt.draw()", "plt.draw() # Socket address HOST = '127.0.0.1' PORT = 8080 # Open socket", "datum, configs): arr = json.loads(datum, object_hook=decode) for idx, config in enumerate(configs): plt.figure(idx+1) xdata", "PORT)) # Listen (1 connection in buffer) s.listen(1) # Accept connection conn, addr", "arr[config[1]] l = lines[idx] x = l.get_xdata() y = l.get_ydata() if len(x) >", "# Append new data l.set_xdata(np.append(x, xdata)) l.set_ydata(np.append(y, ydata)) # Adjust axis limits plt.xlim(0,", "dct: return dct[\"config\"] elif \"config\" not in dct and \"x\" in dct and", "# Socket address HOST = '127.0.0.1' PORT = 8080 # Open socket s", "socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind socket to address s.bind((HOST, PORT)) #", "[dct[\"x\"], dct[\"y\"]] else: return \"Invalid JSON\" def process(lines, datum, configs): arr = json.loads(datum,", "\"Connected by\", addr configs = conn.recv(1024) configs = json.loads(configs, object_hook=decode) plt.show(block=False) conn.sendall('Ready') while", "object_hook=decode) for idx, config in enumerate(configs): plt.figure(idx+1) xdata = arr[config[0]] ydata = arr[config[1]]", "\"Invalid data received\" else: # If data is terminating break # Close connection", "as plt import numpy as np import json idx = 0 lines =", "else: return \"Invalid JSON\" def process(lines, datum, configs): arr = json.loads(datum, object_hook=decode) for", "# Listen (1 connection in buffer) s.listen(1) # Accept connection conn, addr =", "configs = conn.recv(1024) configs = json.loads(configs, object_hook=decode) plt.show(block=False) conn.sendall('Ready') while 1: # Receive", "lines[idx] x = l.get_xdata() y = l.get_ydata() if len(x) > 0: # Append", "import socket import matplotlib.pyplot as plt import numpy as np import json idx", "dct: global idx, lines idx += 1 plt.figure(idx) if \"xlabel\" in dct: plt.xlabel(dct[\"xlabel\"])", "data received\" else: # If data is terminating break # Close connection conn.close()", "[] def decode(dct): if \"data\" in dct: return dct[\"data\"] elif \"config\" in dct:", "plt.plot([], [], 'r-') lines.append(l) return [dct[\"x\"], dct[\"y\"]] else: return \"Invalid JSON\" def process(lines,", "= 8080 # Open socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind socket to", "len(x) > 0: # Append new data l.set_xdata(np.append(x, xdata)) l.set_ydata(np.append(y, ydata)) # Adjust", "= l.get_xdata() y = l.get_ydata() if len(x) > 0: # Append new data", "arr = json.loads(datum, object_hook=decode) for idx, config in enumerate(configs): plt.figure(idx+1) xdata = arr[config[0]]", "return [dct[\"x\"], dct[\"y\"]] else: return \"Invalid JSON\" def process(lines, datum, configs): arr =", "if \"ylabel\" in dct: plt.ylabel(dct[\"ylabel\"]) l, = plt.plot([], [], 'r-') lines.append(l) return [dct[\"x\"],", "else: # If data is terminating break # Close connection conn.close() # Close", "x = l.get_xdata() y = l.get_ydata() if len(x) > 0: # Append new", "Listen (1 connection in buffer) s.listen(1) # Accept connection conn, addr = s.accept()", "xdata)) l.set_ydata(np.append(y, ydata)) # Adjust axis limits plt.xlim(0, np.amax(l.get_xdata())*1.05) plt.ylim(0, np.amax(l.get_ydata())*1.05) else: #", "data without closing connection print \"Invalid data received\" else: # If data is", "np.amax(l.get_xdata())*1.05) plt.ylim(0, np.amax(l.get_ydata())*1.05) else: # Add first coordinates l.set_xdata([xdata]) l.set_ydata([ydata]) # Update plot", "in buffer) s.listen(1) # Accept connection conn, addr = s.accept() print \"Connected by\",", "if \"data\" in dct: return dct[\"data\"] elif \"config\" in dct: return dct[\"config\"] elif", "Socket address HOST = '127.0.0.1' PORT = 8080 # Open socket s =", "socket.SOCK_STREAM) # Bind socket to address s.bind((HOST, PORT)) # Listen (1 connection in", "# If data is terminating break # Close connection conn.close() # Close socket", "= json.loads(configs, object_hook=decode) plt.show(block=False) conn.sendall('Ready') while 1: # Receive data datum = conn.recv(1024)", "\"config\" in dct: return dct[\"config\"] elif \"config\" not in dct and \"x\" in", "1 plt.figure(idx) if \"xlabel\" in dct: plt.xlabel(dct[\"xlabel\"]) if \"ylabel\" in dct: plt.ylabel(dct[\"ylabel\"]) l,", "= s.accept() print \"Connected by\", addr configs = conn.recv(1024) configs = json.loads(configs, object_hook=decode)", "connection print \"Invalid data received\" else: # If data is terminating break #", "plt.xlabel(dct[\"xlabel\"]) if \"ylabel\" in dct: plt.ylabel(dct[\"ylabel\"]) l, = plt.plot([], [], 'r-') lines.append(l) return", "l.set_ydata(np.append(y, ydata)) # Adjust axis limits plt.xlim(0, np.amax(l.get_xdata())*1.05) plt.ylim(0, np.amax(l.get_ydata())*1.05) else: # Add", "s.listen(1) # Accept connection conn, addr = s.accept() print \"Connected by\", addr configs", "data process(lines, datum, configs) except: # Handle invalid data without closing connection print", "s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind socket to address s.bind((HOST, PORT)) # Listen", "if datum: # If data is not terminating try: # Process and plot", "coordinates l.set_xdata([xdata]) l.set_ydata([ydata]) # Update plot plt.draw() # Socket address HOST = '127.0.0.1'", "connection conn, addr = s.accept() print \"Connected by\", addr configs = conn.recv(1024) configs", "'127.0.0.1' PORT = 8080 # Open socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind", "'r-') lines.append(l) return [dct[\"x\"], dct[\"y\"]] else: return \"Invalid JSON\" def process(lines, datum, configs):", "Process and plot data process(lines, datum, configs) except: # Handle invalid data without", "data l.set_xdata(np.append(x, xdata)) l.set_ydata(np.append(y, ydata)) # Adjust axis limits plt.xlim(0, np.amax(l.get_xdata())*1.05) plt.ylim(0, np.amax(l.get_ydata())*1.05)", "= conn.recv(1024) if datum: # If data is not terminating try: # Process", "return \"Invalid JSON\" def process(lines, datum, configs): arr = json.loads(datum, object_hook=decode) for idx,", "Handle invalid data without closing connection print \"Invalid data received\" else: # If", "l.get_xdata() y = l.get_ydata() if len(x) > 0: # Append new data l.set_xdata(np.append(x,", "+= 1 plt.figure(idx) if \"xlabel\" in dct: plt.xlabel(dct[\"xlabel\"]) if \"ylabel\" in dct: plt.ylabel(dct[\"ylabel\"])", "break # Close connection conn.close() # Close socket s.close() # Keep showing plot", "dct and \"x\" in dct and \"y\" in dct: global idx, lines idx", "conn.recv(1024) if datum: # If data is not terminating try: # Process and", "idx, lines idx += 1 plt.figure(idx) if \"xlabel\" in dct: plt.xlabel(dct[\"xlabel\"]) if \"ylabel\"", "# If data is not terminating try: # Process and plot data process(lines,", "enumerate(configs): plt.figure(idx+1) xdata = arr[config[0]] ydata = arr[config[1]] l = lines[idx] x =", "config in enumerate(configs): plt.figure(idx+1) xdata = arr[config[0]] ydata = arr[config[1]] l = lines[idx]", "s.bind((HOST, PORT)) # Listen (1 connection in buffer) s.listen(1) # Accept connection conn,", "in dct: plt.ylabel(dct[\"ylabel\"]) l, = plt.plot([], [], 'r-') lines.append(l) return [dct[\"x\"], dct[\"y\"]] else:", "not terminating try: # Process and plot data process(lines, datum, configs) except: #", "= [] def decode(dct): if \"data\" in dct: return dct[\"data\"] elif \"config\" in", "in dct: plt.xlabel(dct[\"xlabel\"]) if \"ylabel\" in dct: plt.ylabel(dct[\"ylabel\"]) l, = plt.plot([], [], 'r-')", "address s.bind((HOST, PORT)) # Listen (1 connection in buffer) s.listen(1) # Accept connection", "process(lines, datum, configs): arr = json.loads(datum, object_hook=decode) for idx, config in enumerate(configs): plt.figure(idx+1)", "ydata = arr[config[1]] l = lines[idx] x = l.get_xdata() y = l.get_ydata() if", "first coordinates l.set_xdata([xdata]) l.set_ydata([ydata]) # Update plot plt.draw() # Socket address HOST =", "data datum = conn.recv(1024) if datum: # If data is not terminating try:", "data is not terminating try: # Process and plot data process(lines, datum, configs)", "y = l.get_ydata() if len(x) > 0: # Append new data l.set_xdata(np.append(x, xdata))", "= '127.0.0.1' PORT = 8080 # Open socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #", "process(lines, datum, configs) except: # Handle invalid data without closing connection print \"Invalid", "and \"x\" in dct and \"y\" in dct: global idx, lines idx +=", "\"config\" not in dct and \"x\" in dct and \"y\" in dct: global", "(1 connection in buffer) s.listen(1) # Accept connection conn, addr = s.accept() print", "json.loads(configs, object_hook=decode) plt.show(block=False) conn.sendall('Ready') while 1: # Receive data datum = conn.recv(1024) if", "configs): arr = json.loads(datum, object_hook=decode) for idx, config in enumerate(configs): plt.figure(idx+1) xdata =", "0: # Append new data l.set_xdata(np.append(x, xdata)) l.set_ydata(np.append(y, ydata)) # Adjust axis limits", "without closing connection print \"Invalid data received\" else: # If data is terminating", "data is terminating break # Close connection conn.close() # Close socket s.close() #", "try: # Process and plot data process(lines, datum, configs) except: # Handle invalid", "plot plt.draw() # Socket address HOST = '127.0.0.1' PORT = 8080 # Open", "return dct[\"data\"] elif \"config\" in dct: return dct[\"config\"] elif \"config\" not in dct", "and \"y\" in dct: global idx, lines idx += 1 plt.figure(idx) if \"xlabel\"", "if \"xlabel\" in dct: plt.xlabel(dct[\"xlabel\"]) if \"ylabel\" in dct: plt.ylabel(dct[\"ylabel\"]) l, = plt.plot([],", "ydata)) # Adjust axis limits plt.xlim(0, np.amax(l.get_xdata())*1.05) plt.ylim(0, np.amax(l.get_ydata())*1.05) else: # Add first", "arr[config[0]] ydata = arr[config[1]] l = lines[idx] x = l.get_xdata() y = l.get_ydata()", "plt.figure(idx+1) xdata = arr[config[0]] ydata = arr[config[1]] l = lines[idx] x = l.get_xdata()", "not in dct and \"x\" in dct and \"y\" in dct: global idx,", "# Accept connection conn, addr = s.accept() print \"Connected by\", addr configs =", "is terminating break # Close connection conn.close() # Close socket s.close() # Keep", "is not terminating try: # Process and plot data process(lines, datum, configs) except:", "# Open socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind socket to address s.bind((HOST,", "def decode(dct): if \"data\" in dct: return dct[\"data\"] elif \"config\" in dct: return", "by\", addr configs = conn.recv(1024) configs = json.loads(configs, object_hook=decode) plt.show(block=False) conn.sendall('Ready') while 1:", "in dct: global idx, lines idx += 1 plt.figure(idx) if \"xlabel\" in dct:", "plt.figure(idx) if \"xlabel\" in dct: plt.xlabel(dct[\"xlabel\"]) if \"ylabel\" in dct: plt.ylabel(dct[\"ylabel\"]) l, =", "conn.sendall('Ready') while 1: # Receive data datum = conn.recv(1024) if datum: # If", "in dct and \"x\" in dct and \"y\" in dct: global idx, lines", "# Handle invalid data without closing connection print \"Invalid data received\" else: #", "plot data process(lines, datum, configs) except: # Handle invalid data without closing connection", "received\" else: # If data is terminating break # Close connection conn.close() #", "l, = plt.plot([], [], 'r-') lines.append(l) return [dct[\"x\"], dct[\"y\"]] else: return \"Invalid JSON\"", "= plt.plot([], [], 'r-') lines.append(l) return [dct[\"x\"], dct[\"y\"]] else: return \"Invalid JSON\" def", "else: # Add first coordinates l.set_xdata([xdata]) l.set_ydata([ydata]) # Update plot plt.draw() # Socket", "datum, configs) except: # Handle invalid data without closing connection print \"Invalid data", "and plot data process(lines, datum, configs) except: # Handle invalid data without closing", "in dct and \"y\" in dct: global idx, lines idx += 1 plt.figure(idx)", "object_hook=decode) plt.show(block=False) conn.sendall('Ready') while 1: # Receive data datum = conn.recv(1024) if datum:", "addr configs = conn.recv(1024) configs = json.loads(configs, object_hook=decode) plt.show(block=False) conn.sendall('Ready') while 1: #", "elif \"config\" in dct: return dct[\"config\"] elif \"config\" not in dct and \"x\"", "lines = [] def decode(dct): if \"data\" in dct: return dct[\"data\"] elif \"config\"", "HOST = '127.0.0.1' PORT = 8080 # Open socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)", "# Update plot plt.draw() # Socket address HOST = '127.0.0.1' PORT = 8080", "while 1: # Receive data datum = conn.recv(1024) if datum: # If data", "PORT = 8080 # Open socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind socket", "8080 # Open socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind socket to address", "print \"Invalid data received\" else: # If data is terminating break # Close", "[], 'r-') lines.append(l) return [dct[\"x\"], dct[\"y\"]] else: return \"Invalid JSON\" def process(lines, datum,", "numpy as np import json idx = 0 lines = [] def decode(dct):", "= arr[config[1]] l = lines[idx] x = l.get_xdata() y = l.get_ydata() if len(x)" ]
[ "#import logging as log from argparse import ArgumentParser class SysBoard(object): ''' Main system", "script if __name__ == '__main__': try: f=open('eeprom.json') # EEPROM format j_data = json.load(f)", "json_data): ''' Constructor ''' self.eeprom = eeprom.EepromBin(\"syseeprom.bin\") # Init EEPROM programmer self.eepprog =", "= board.eepprog try: # Setup argument parser parser = ArgumentParser(prog=sys.argv[0]) subparsers = parser.add_subparsers(help='help", "'update': # eepprog update # parse <field>=<value> eepprog.eep_dev.reload() fields = [] for f", "ArgumentParser(prog=sys.argv[0]) subparsers = parser.add_subparsers(help='help for subcommand', dest='subcommand') parser_show = subparsers.add_parser('show', help='Display the device", "Entry point of the script if __name__ == '__main__': try: f=open('eeprom.json') # EEPROM", "%s' % (eepprog.fields[key].descr, eepprog.get_field(key)) elif args.subcommand == 'dump': # eepprog dump eepprog.eep_dev.reload() print", "eepprog.fields[name].offset): print '%-16s: %s' % (eepprog.fields[key].descr, eepprog.get_field(key)) elif args.subcommand == 'dump': # eepprog", "# eepprog json eepprog.eep_dev.reload() print eepprog.toJSON() elif args.subcommand == 'field': # eepprog field", "eepprog dump eepprog.eep_dev.reload() print eepprog.eep_dev.dump() elif args.subcommand == 'erase': # eepprog erase if", "eepprog.eep_dev.save() else: parser.print_help() print '' except Exception, e: indent = len(parser.prog) * \"", "indent = len(parser.prog) * \" \" sys.stderr.write(parser.prog + \": \" + repr(e) +", "eepprog.eep_dev.save() elif args.subcommand == 'json': # eepprog json eepprog.eep_dev.reload() print eepprog.toJSON() elif args.subcommand", "parser = ArgumentParser(prog=sys.argv[0]) subparsers = parser.add_subparsers(help='help for subcommand', dest='subcommand') parser_show = subparsers.add_parser('show', help='Display", "field. ') parser_list = subparsers.add_parser('field', help='List the available fields. ') if len(sys.argv) ==", "repr(e) + \"\\n\") sys.stderr.write(indent + \" for help use --help\\n\") return 2 def", "to do this? (y/N): ') if s.lower() == 'y': return True return False", "parser.add_subparsers(help='help for subcommand', dest='subcommand') parser_show = subparsers.add_parser('show', help='Display the device info') parser_dump =", "j_data = json.load(f) f.close() except Exception, e: print \"File eeprom.json is not found.\"", "for subcommand', dest='subcommand') parser_show = subparsers.add_parser('show', help='Display the device info') parser_dump = subparsers.add_parser('dump',", "argv=None): '''Command line options.''' if argv is None: argv = sys.argv else: sys.argv.extend(argv)", "= subparsers.add_parser('field', help='List the available fields. ') if len(sys.argv) == 1: parser.print_help() return", "return False # Entry point of the script if __name__ == '__main__': try:", "args.subcommand == 'erase': # eepprog erase if operation_confirm() == True: eepprog.erase_all() eepprog.eep_dev.save() elif", "eeprom.EepromBin(\"syseeprom.bin\") # Init EEPROM programmer self.eepprog = eeprom.JsonEepromProg(self.eeprom,json_data['SysEeprom']) def main(board, argv=None): '''Command line", "if eepprog.fields[f[0]] != None: eepprog.set_field(f[0],f[1]) eepprog.eep_dev.save() else: parser.print_help() print '' except Exception, e:", "elif args.subcommand == 'field': # eepprog field print '\\nAvailable fields are: ' +',", "if __name__ == '__main__': try: f=open('eeprom.json') # EEPROM format j_data = json.load(f) f.close()", "class SysBoard(object): ''' Main system definition ''' def __init__(self, json_data): ''' Constructor '''", "'' except Exception, e: indent = len(parser.prog) * \" \" sys.stderr.write(parser.prog + \":", "erase if operation_confirm() == True: eepprog.erase_all() eepprog.eep_dev.save() elif args.subcommand == 'init': # eepprog", "argument parser parser = ArgumentParser(prog=sys.argv[0]) subparsers = parser.add_subparsers(help='help for subcommand', dest='subcommand') parser_show =", "subcommand', dest='subcommand') parser_show = subparsers.add_parser('show', help='Display the device info') parser_dump = subparsers.add_parser('dump', help='Dump", "device info') parser_dump = subparsers.add_parser('dump', help='Dump the binary content') parser_json = subparsers.add_parser('json', help='Output", "== 'dump': # eepprog dump eepprog.eep_dev.reload() print eepprog.eep_dev.dump() elif args.subcommand == 'erase': #", "+', '.join(eepprog.fields.keys()) return 2 else: fields.append(pair) for f in fields: if eepprog.fields[f[0]] !=", "(y/N): ') if s.lower() == 'y': return True return False # Entry point", "dest='subcommand') parser_show = subparsers.add_parser('show', help='Display the device info') parser_dump = subparsers.add_parser('dump', help='Dump the", "in args.fields: pair = f.split('=') if len(pair) != 2: parser_update.print_help() return 2 elif", "if len(sys.argv) == 1: parser.print_help() return 1 args = parser.parse_args() if args.subcommand ==", "+', '.join(eepprog.fields.keys()) elif args.subcommand == 'update': # eepprog update # parse <field>=<value> eepprog.eep_dev.reload()", "= subparsers.add_parser('erase', help='Erase the device info') parser_update = subparsers.add_parser('update', help='Update the device info')", "= raw_input('Are you sure to do this? (y/N): ') if s.lower() == 'y':", "== 'update': # eepprog update # parse <field>=<value> eepprog.eep_dev.reload() fields = [] for", "the script if __name__ == '__main__': try: f=open('eeprom.json') # EEPROM format j_data =", "== True: eepprog.erase_all() eepprog.eep_dev.save() elif args.subcommand == 'init': # eepprog init if operation_confirm()", "format j_data = json.load(f) f.close() except Exception, e: print \"File eeprom.json is not", "parser.print_help() return 1 args = parser.parse_args() if args.subcommand == 'show': # eepprog show", "2 else: fields.append(pair) for f in fields: if eepprog.fields[f[0]] != None: eepprog.set_field(f[0],f[1]) eepprog.eep_dev.save()", "return 2 elif pair[0] not in eepprog.fields: print 'Available fields are: ' +',", "\" \" sys.stderr.write(parser.prog + \": \" + repr(e) + \"\\n\") sys.stderr.write(indent + \"", "board.eepprog try: # Setup argument parser parser = ArgumentParser(prog=sys.argv[0]) subparsers = parser.add_subparsers(help='help for", "metavar='<field>=<value>', nargs='+', help='Update the specified field. ') parser_list = subparsers.add_parser('field', help='List the available", "help='Erase the device info') parser_update = subparsers.add_parser('update', help='Update the device info') parser_update.add_argument('fields', type=str,", "return 2 def operation_confirm(): s = raw_input('Are you sure to do this? (y/N):", "not in eepprog.fields: print 'Available fields are: ' +', '.join(eepprog.fields.keys()) return 2 else:", "argv is None: argv = sys.argv else: sys.argv.extend(argv) eepprog = board.eepprog try: #", "== True: eepprog.init_default() eepprog.eep_dev.save() elif args.subcommand == 'json': # eepprog json eepprog.eep_dev.reload() print", "return 2 else: fields.append(pair) for f in fields: if eepprog.fields[f[0]] != None: eepprog.set_field(f[0],f[1])", "== 'field': # eepprog field print '\\nAvailable fields are: ' +', '.join(eepprog.fields.keys()) elif", "True: eepprog.erase_all() eepprog.eep_dev.save() elif args.subcommand == 'init': # eepprog init if operation_confirm() ==", "import eeprom #import logging as log from argparse import ArgumentParser class SysBoard(object): '''", "subparsers.add_parser('update', help='Update the device info') parser_update.add_argument('fields', type=str, metavar='<field>=<value>', nargs='+', help='Update the specified field.", "args.subcommand == 'field': # eepprog field print '\\nAvailable fields are: ' +', '.join(eepprog.fields.keys())", "<field>=<value> eepprog.eep_dev.reload() fields = [] for f in args.fields: pair = f.split('=') if", "device info') parser_update = subparsers.add_parser('update', help='Update the device info') parser_update.add_argument('fields', type=str, metavar='<field>=<value>', nargs='+',", "s.lower() == 'y': return True return False # Entry point of the script", "print 'Available fields are: ' +', '.join(eepprog.fields.keys()) return 2 else: fields.append(pair) for f", "print '\\nAvailable fields are: ' +', '.join(eepprog.fields.keys()) elif args.subcommand == 'update': # eepprog", "args.fields: pair = f.split('=') if len(pair) != 2: parser_update.print_help() return 2 elif pair[0]", "logging as log from argparse import ArgumentParser class SysBoard(object): ''' Main system definition", "operation_confirm() == True: eepprog.erase_all() eepprog.eep_dev.save() elif args.subcommand == 'init': # eepprog init if", "programmer self.eepprog = eeprom.JsonEepromProg(self.eeprom,json_data['SysEeprom']) def main(board, argv=None): '''Command line options.''' if argv is", "Setup argument parser parser = ArgumentParser(prog=sys.argv[0]) subparsers = parser.add_subparsers(help='help for subcommand', dest='subcommand') parser_show", "print eepprog.toJSON() elif args.subcommand == 'field': # eepprog field print '\\nAvailable fields are:", "the specified field. ') parser_list = subparsers.add_parser('field', help='List the available fields. ') if", "+ \" for help use --help\\n\") return 2 def operation_confirm(): s = raw_input('Are", "else: parser.print_help() print '' except Exception, e: indent = len(parser.prog) * \" \"", "help='Update the specified field. ') parser_list = subparsers.add_parser('field', help='List the available fields. ')", "args.subcommand == 'init': # eepprog init if operation_confirm() == True: eepprog.init_default() eepprog.eep_dev.save() elif", "EEPROM format j_data = json.load(f) f.close() except Exception, e: print \"File eeprom.json is", "import os import json import eeprom #import logging as log from argparse import", "sys.stderr.write(parser.prog + \": \" + repr(e) + \"\\n\") sys.stderr.write(indent + \" for help", "from argparse import ArgumentParser class SysBoard(object): ''' Main system definition ''' def __init__(self,", "argparse import ArgumentParser class SysBoard(object): ''' Main system definition ''' def __init__(self, json_data):", "EEPROM programmer self.eepprog = eeprom.JsonEepromProg(self.eeprom,json_data['SysEeprom']) def main(board, argv=None): '''Command line options.''' if argv", "except Exception, e: indent = len(parser.prog) * \" \" sys.stderr.write(parser.prog + \": \"", "True return False # Entry point of the script if __name__ == '__main__':", "elif args.subcommand == 'json': # eepprog json eepprog.eep_dev.reload() print eepprog.toJSON() elif args.subcommand ==", "'\\nAvailable fields are: ' +', '.join(eepprog.fields.keys()) elif args.subcommand == 'update': # eepprog update", "json import eeprom #import logging as log from argparse import ArgumentParser class SysBoard(object):", "\" + repr(e) + \"\\n\") sys.stderr.write(indent + \" for help use --help\\n\") return", "if argv is None: argv = sys.argv else: sys.argv.extend(argv) eepprog = board.eepprog try:", "help='List the available fields. ') if len(sys.argv) == 1: parser.print_help() return 1 args", "eepprog.eep_dev.dump() elif args.subcommand == 'erase': # eepprog erase if operation_confirm() == True: eepprog.erase_all()", "operation_confirm() == True: eepprog.init_default() eepprog.eep_dev.save() elif args.subcommand == 'json': # eepprog json eepprog.eep_dev.reload()", "eepprog erase if operation_confirm() == True: eepprog.erase_all() eepprog.eep_dev.save() elif args.subcommand == 'init': #", "False # Entry point of the script if __name__ == '__main__': try: f=open('eeprom.json')", "parser_update = subparsers.add_parser('update', help='Update the device info') parser_update.add_argument('fields', type=str, metavar='<field>=<value>', nargs='+', help='Update the", "if operation_confirm() == True: eepprog.init_default() eepprog.eep_dev.save() elif args.subcommand == 'json': # eepprog json", "Constructor ''' self.eeprom = eeprom.EepromBin(\"syseeprom.bin\") # Init EEPROM programmer self.eepprog = eeprom.JsonEepromProg(self.eeprom,json_data['SysEeprom']) def", "parse <field>=<value> eepprog.eep_dev.reload() fields = [] for f in args.fields: pair = f.split('=')", "init if operation_confirm() == True: eepprog.init_default() eepprog.eep_dev.save() elif args.subcommand == 'json': # eepprog", "# eepprog show eepprog.eep_dev.reload() for key in sorted(eepprog.fields.keys(), key = lambda name: eepprog.fields[name].offset):", "json.load(f) f.close() except Exception, e: print \"File eeprom.json is not found.\" exit(1) board", "'.join(eepprog.fields.keys()) return 2 else: fields.append(pair) for f in fields: if eepprog.fields[f[0]] != None:", "') if len(sys.argv) == 1: parser.print_help() return 1 args = parser.parse_args() if args.subcommand", "None: eepprog.set_field(f[0],f[1]) eepprog.eep_dev.save() else: parser.print_help() print '' except Exception, e: indent = len(parser.prog)", "' +', '.join(eepprog.fields.keys()) return 2 else: fields.append(pair) for f in fields: if eepprog.fields[f[0]]", "help='Dump the binary content') parser_json = subparsers.add_parser('json', help='Output JSON format') parser_init = subparsers.add_parser('init',", "== '__main__': try: f=open('eeprom.json') # EEPROM format j_data = json.load(f) f.close() except Exception,", "in fields: if eepprog.fields[f[0]] != None: eepprog.set_field(f[0],f[1]) eepprog.eep_dev.save() else: parser.print_help() print '' except", "= subparsers.add_parser('show', help='Display the device info') parser_dump = subparsers.add_parser('dump', help='Dump the binary content')", "args = parser.parse_args() if args.subcommand == 'show': # eepprog show eepprog.eep_dev.reload() for key", "# eepprog field print '\\nAvailable fields are: ' +', '.join(eepprog.fields.keys()) elif args.subcommand ==", "line options.''' if argv is None: argv = sys.argv else: sys.argv.extend(argv) eepprog =", "!= 2: parser_update.print_help() return 2 elif pair[0] not in eepprog.fields: print 'Available fields", "show eepprog.eep_dev.reload() for key in sorted(eepprog.fields.keys(), key = lambda name: eepprog.fields[name].offset): print '%-16s:", "None: argv = sys.argv else: sys.argv.extend(argv) eepprog = board.eepprog try: # Setup argument", "''' def __init__(self, json_data): ''' Constructor ''' self.eeprom = eeprom.EepromBin(\"syseeprom.bin\") # Init EEPROM", "print '' except Exception, e: indent = len(parser.prog) * \" \" sys.stderr.write(parser.prog +", "<reponame>ivanliao/EazyEEP<filename>json_eep.py #!/usr/bin/python ''' Created on May 20, 2016 @author: ''' import sys import", "# parse <field>=<value> eepprog.eep_dev.reload() fields = [] for f in args.fields: pair =", "pair[0] not in eepprog.fields: print 'Available fields are: ' +', '.join(eepprog.fields.keys()) return 2", "# eepprog dump eepprog.eep_dev.reload() print eepprog.eep_dev.dump() elif args.subcommand == 'erase': # eepprog erase", "May 20, 2016 @author: ''' import sys import os import json import eeprom", "args.subcommand == 'json': # eepprog json eepprog.eep_dev.reload() print eepprog.toJSON() elif args.subcommand == 'field':", "== 'init': # eepprog init if operation_confirm() == True: eepprog.init_default() eepprog.eep_dev.save() elif args.subcommand", "the available fields. ') if len(sys.argv) == 1: parser.print_help() return 1 args =", "if operation_confirm() == True: eepprog.erase_all() eepprog.eep_dev.save() elif args.subcommand == 'init': # eepprog init", "= subparsers.add_parser('init', help='Initialize the device info') parser_erase = subparsers.add_parser('erase', help='Erase the device info')", "log from argparse import ArgumentParser class SysBoard(object): ''' Main system definition ''' def", "[] for f in args.fields: pair = f.split('=') if len(pair) != 2: parser_update.print_help()", "eepprog.erase_all() eepprog.eep_dev.save() elif args.subcommand == 'init': # eepprog init if operation_confirm() == True:", "of the script if __name__ == '__main__': try: f=open('eeprom.json') # EEPROM format j_data", "parser_init = subparsers.add_parser('init', help='Initialize the device info') parser_erase = subparsers.add_parser('erase', help='Erase the device", "'field': # eepprog field print '\\nAvailable fields are: ' +', '.join(eepprog.fields.keys()) elif args.subcommand", "len(sys.argv) == 1: parser.print_help() return 1 args = parser.parse_args() if args.subcommand == 'show':", "JSON format') parser_init = subparsers.add_parser('init', help='Initialize the device info') parser_erase = subparsers.add_parser('erase', help='Erase", "eepprog.eep_dev.reload() for key in sorted(eepprog.fields.keys(), key = lambda name: eepprog.fields[name].offset): print '%-16s: %s'", "eepprog.set_field(f[0],f[1]) eepprog.eep_dev.save() else: parser.print_help() print '' except Exception, e: indent = len(parser.prog) *", "= f.split('=') if len(pair) != 2: parser_update.print_help() return 2 elif pair[0] not in", "== 'erase': # eepprog erase if operation_confirm() == True: eepprog.erase_all() eepprog.eep_dev.save() elif args.subcommand", "'init': # eepprog init if operation_confirm() == True: eepprog.init_default() eepprog.eep_dev.save() elif args.subcommand ==", "--help\\n\") return 2 def operation_confirm(): s = raw_input('Are you sure to do this?", "subparsers = parser.add_subparsers(help='help for subcommand', dest='subcommand') parser_show = subparsers.add_parser('show', help='Display the device info')", "@author: ''' import sys import os import json import eeprom #import logging as", "binary content') parser_json = subparsers.add_parser('json', help='Output JSON format') parser_init = subparsers.add_parser('init', help='Initialize the", "\" sys.stderr.write(parser.prog + \": \" + repr(e) + \"\\n\") sys.stderr.write(indent + \" for", "''' Constructor ''' self.eeprom = eeprom.EepromBin(\"syseeprom.bin\") # Init EEPROM programmer self.eepprog = eeprom.JsonEepromProg(self.eeprom,json_data['SysEeprom'])", "# eepprog init if operation_confirm() == True: eepprog.init_default() eepprog.eep_dev.save() elif args.subcommand == 'json':", "* \" \" sys.stderr.write(parser.prog + \": \" + repr(e) + \"\\n\") sys.stderr.write(indent +", "parser_erase = subparsers.add_parser('erase', help='Erase the device info') parser_update = subparsers.add_parser('update', help='Update the device", "argv = sys.argv else: sys.argv.extend(argv) eepprog = board.eepprog try: # Setup argument parser", "device info') parser_update.add_argument('fields', type=str, metavar='<field>=<value>', nargs='+', help='Update the specified field. ') parser_list =", "help use --help\\n\") return 2 def operation_confirm(): s = raw_input('Are you sure to", "') parser_list = subparsers.add_parser('field', help='List the available fields. ') if len(sys.argv) == 1:", "sorted(eepprog.fields.keys(), key = lambda name: eepprog.fields[name].offset): print '%-16s: %s' % (eepprog.fields[key].descr, eepprog.get_field(key)) elif", "fields = [] for f in args.fields: pair = f.split('=') if len(pair) !=", "eepprog.fields: print 'Available fields are: ' +', '.join(eepprog.fields.keys()) return 2 else: fields.append(pair) for", "point of the script if __name__ == '__main__': try: f=open('eeprom.json') # EEPROM format", "#!/usr/bin/python ''' Created on May 20, 2016 @author: ''' import sys import os", "fields. ') if len(sys.argv) == 1: parser.print_help() return 1 args = parser.parse_args() if", "eepprog.eep_dev.save() elif args.subcommand == 'init': # eepprog init if operation_confirm() == True: eepprog.init_default()", "f.split('=') if len(pair) != 2: parser_update.print_help() return 2 elif pair[0] not in eepprog.fields:", "= ArgumentParser(prog=sys.argv[0]) subparsers = parser.add_subparsers(help='help for subcommand', dest='subcommand') parser_show = subparsers.add_parser('show', help='Display the", "parser_show = subparsers.add_parser('show', help='Display the device info') parser_dump = subparsers.add_parser('dump', help='Dump the binary", "for f in fields: if eepprog.fields[f[0]] != None: eepprog.set_field(f[0],f[1]) eepprog.eep_dev.save() else: parser.print_help() print", "'''Command line options.''' if argv is None: argv = sys.argv else: sys.argv.extend(argv) eepprog", "sure to do this? (y/N): ') if s.lower() == 'y': return True return", "fields are: ' +', '.join(eepprog.fields.keys()) return 2 else: fields.append(pair) for f in fields:", "the device info') parser_update = subparsers.add_parser('update', help='Update the device info') parser_update.add_argument('fields', type=str, metavar='<field>=<value>',", "options.''' if argv is None: argv = sys.argv else: sys.argv.extend(argv) eepprog = board.eepprog", "f.close() except Exception, e: print \"File eeprom.json is not found.\" exit(1) board =", "Created on May 20, 2016 @author: ''' import sys import os import json", "elif args.subcommand == 'erase': # eepprog erase if operation_confirm() == True: eepprog.erase_all() eepprog.eep_dev.save()", "subparsers.add_parser('field', help='List the available fields. ') if len(sys.argv) == 1: parser.print_help() return 1", "the device info') parser_dump = subparsers.add_parser('dump', help='Dump the binary content') parser_json = subparsers.add_parser('json',", "type=str, metavar='<field>=<value>', nargs='+', help='Update the specified field. ') parser_list = subparsers.add_parser('field', help='List the", "e: indent = len(parser.prog) * \" \" sys.stderr.write(parser.prog + \": \" + repr(e)", "available fields. ') if len(sys.argv) == 1: parser.print_help() return 1 args = parser.parse_args()", "subparsers.add_parser('json', help='Output JSON format') parser_init = subparsers.add_parser('init', help='Initialize the device info') parser_erase =", "the device info') parser_erase = subparsers.add_parser('erase', help='Erase the device info') parser_update = subparsers.add_parser('update',", "# Setup argument parser parser = ArgumentParser(prog=sys.argv[0]) subparsers = parser.add_subparsers(help='help for subcommand', dest='subcommand')", "subparsers.add_parser('init', help='Initialize the device info') parser_erase = subparsers.add_parser('erase', help='Erase the device info') parser_update", "parser_dump = subparsers.add_parser('dump', help='Dump the binary content') parser_json = subparsers.add_parser('json', help='Output JSON format')", "'__main__': try: f=open('eeprom.json') # EEPROM format j_data = json.load(f) f.close() except Exception, e:", "for help use --help\\n\") return 2 def operation_confirm(): s = raw_input('Are you sure", "= json.load(f) f.close() except Exception, e: print \"File eeprom.json is not found.\" exit(1)", "eepprog.init_default() eepprog.eep_dev.save() elif args.subcommand == 'json': # eepprog json eepprog.eep_dev.reload() print eepprog.toJSON() elif", "SysBoard(object): ''' Main system definition ''' def __init__(self, json_data): ''' Constructor ''' self.eeprom", "''' import sys import os import json import eeprom #import logging as log", "== 'show': # eepprog show eepprog.eep_dev.reload() for key in sorted(eepprog.fields.keys(), key = lambda", "eeprom.JsonEepromProg(self.eeprom,json_data['SysEeprom']) def main(board, argv=None): '''Command line options.''' if argv is None: argv =", "' +', '.join(eepprog.fields.keys()) elif args.subcommand == 'update': # eepprog update # parse <field>=<value>", "info') parser_dump = subparsers.add_parser('dump', help='Dump the binary content') parser_json = subparsers.add_parser('json', help='Output JSON", "'.join(eepprog.fields.keys()) elif args.subcommand == 'update': # eepprog update # parse <field>=<value> eepprog.eep_dev.reload() fields", "= [] for f in args.fields: pair = f.split('=') if len(pair) != 2:", "True: eepprog.init_default() eepprog.eep_dev.save() elif args.subcommand == 'json': # eepprog json eepprog.eep_dev.reload() print eepprog.toJSON()", "the device info') parser_update.add_argument('fields', type=str, metavar='<field>=<value>', nargs='+', help='Update the specified field. ') parser_list", "except Exception, e: print \"File eeprom.json is not found.\" exit(1) board = SysBoard(j_data)", "eepprog update # parse <field>=<value> eepprog.eep_dev.reload() fields = [] for f in args.fields:", "fields are: ' +', '.join(eepprog.fields.keys()) elif args.subcommand == 'update': # eepprog update #", "eepprog.fields[f[0]] != None: eepprog.set_field(f[0],f[1]) eepprog.eep_dev.save() else: parser.print_help() print '' except Exception, e: indent", "key in sorted(eepprog.fields.keys(), key = lambda name: eepprog.fields[name].offset): print '%-16s: %s' % (eepprog.fields[key].descr,", "subparsers.add_parser('show', help='Display the device info') parser_dump = subparsers.add_parser('dump', help='Dump the binary content') parser_json", "\"\\n\") sys.stderr.write(indent + \" for help use --help\\n\") return 2 def operation_confirm(): s", "'json': # eepprog json eepprog.eep_dev.reload() print eepprog.toJSON() elif args.subcommand == 'field': # eepprog", "2 def operation_confirm(): s = raw_input('Are you sure to do this? (y/N): ')", "for key in sorted(eepprog.fields.keys(), key = lambda name: eepprog.fields[name].offset): print '%-16s: %s' %", "name: eepprog.fields[name].offset): print '%-16s: %s' % (eepprog.fields[key].descr, eepprog.get_field(key)) elif args.subcommand == 'dump': #", "% (eepprog.fields[key].descr, eepprog.get_field(key)) elif args.subcommand == 'dump': # eepprog dump eepprog.eep_dev.reload() print eepprog.eep_dev.dump()", "= parser.add_subparsers(help='help for subcommand', dest='subcommand') parser_show = subparsers.add_parser('show', help='Display the device info') parser_dump", "Main system definition ''' def __init__(self, json_data): ''' Constructor ''' self.eeprom = eeprom.EepromBin(\"syseeprom.bin\")", "return 1 args = parser.parse_args() if args.subcommand == 'show': # eepprog show eepprog.eep_dev.reload()", "'erase': # eepprog erase if operation_confirm() == True: eepprog.erase_all() eepprog.eep_dev.save() elif args.subcommand ==", "are: ' +', '.join(eepprog.fields.keys()) return 2 else: fields.append(pair) for f in fields: if", "key = lambda name: eepprog.fields[name].offset): print '%-16s: %s' % (eepprog.fields[key].descr, eepprog.get_field(key)) elif args.subcommand", "content') parser_json = subparsers.add_parser('json', help='Output JSON format') parser_init = subparsers.add_parser('init', help='Initialize the device", "print '%-16s: %s' % (eepprog.fields[key].descr, eepprog.get_field(key)) elif args.subcommand == 'dump': # eepprog dump", "''' Created on May 20, 2016 @author: ''' import sys import os import", "parser parser = ArgumentParser(prog=sys.argv[0]) subparsers = parser.add_subparsers(help='help for subcommand', dest='subcommand') parser_show = subparsers.add_parser('show',", "on May 20, 2016 @author: ''' import sys import os import json import", "subparsers.add_parser('dump', help='Dump the binary content') parser_json = subparsers.add_parser('json', help='Output JSON format') parser_init =", "definition ''' def __init__(self, json_data): ''' Constructor ''' self.eeprom = eeprom.EepromBin(\"syseeprom.bin\") # Init", "fields: if eepprog.fields[f[0]] != None: eepprog.set_field(f[0],f[1]) eepprog.eep_dev.save() else: parser.print_help() print '' except Exception,", "for f in args.fields: pair = f.split('=') if len(pair) != 2: parser_update.print_help() return", "eepprog init if operation_confirm() == True: eepprog.init_default() eepprog.eep_dev.save() elif args.subcommand == 'json': #", "help='Initialize the device info') parser_erase = subparsers.add_parser('erase', help='Erase the device info') parser_update =", "1: parser.print_help() return 1 args = parser.parse_args() if args.subcommand == 'show': # eepprog", "len(parser.prog) * \" \" sys.stderr.write(parser.prog + \": \" + repr(e) + \"\\n\") sys.stderr.write(indent", "self.eepprog = eeprom.JsonEepromProg(self.eeprom,json_data['SysEeprom']) def main(board, argv=None): '''Command line options.''' if argv is None:", "f in args.fields: pair = f.split('=') if len(pair) != 2: parser_update.print_help() return 2", "__name__ == '__main__': try: f=open('eeprom.json') # EEPROM format j_data = json.load(f) f.close() except", "= eeprom.JsonEepromProg(self.eeprom,json_data['SysEeprom']) def main(board, argv=None): '''Command line options.''' if argv is None: argv", "# Entry point of the script if __name__ == '__main__': try: f=open('eeprom.json') #", "pair = f.split('=') if len(pair) != 2: parser_update.print_help() return 2 elif pair[0] not", "ArgumentParser class SysBoard(object): ''' Main system definition ''' def __init__(self, json_data): ''' Constructor", "info') parser_update.add_argument('fields', type=str, metavar='<field>=<value>', nargs='+', help='Update the specified field. ') parser_list = subparsers.add_parser('field',", "+ \": \" + repr(e) + \"\\n\") sys.stderr.write(indent + \" for help use", "parser_list = subparsers.add_parser('field', help='List the available fields. ') if len(sys.argv) == 1: parser.print_help()", "import ArgumentParser class SysBoard(object): ''' Main system definition ''' def __init__(self, json_data): '''", "2 elif pair[0] not in eepprog.fields: print 'Available fields are: ' +', '.join(eepprog.fields.keys())", "return True return False # Entry point of the script if __name__ ==", "are: ' +', '.join(eepprog.fields.keys()) elif args.subcommand == 'update': # eepprog update # parse", "\": \" + repr(e) + \"\\n\") sys.stderr.write(indent + \" for help use --help\\n\")", "\" for help use --help\\n\") return 2 def operation_confirm(): s = raw_input('Are you", "import json import eeprom #import logging as log from argparse import ArgumentParser class", "eepprog.eep_dev.reload() fields = [] for f in args.fields: pair = f.split('=') if len(pair)", "args.subcommand == 'dump': # eepprog dump eepprog.eep_dev.reload() print eepprog.eep_dev.dump() elif args.subcommand == 'erase':", "help='Output JSON format') parser_init = subparsers.add_parser('init', help='Initialize the device info') parser_erase = subparsers.add_parser('erase',", "# eepprog erase if operation_confirm() == True: eepprog.erase_all() eepprog.eep_dev.save() elif args.subcommand == 'init':", "f in fields: if eepprog.fields[f[0]] != None: eepprog.set_field(f[0],f[1]) eepprog.eep_dev.save() else: parser.print_help() print ''", "parser.print_help() print '' except Exception, e: indent = len(parser.prog) * \" \" sys.stderr.write(parser.prog", "'y': return True return False # Entry point of the script if __name__", "update # parse <field>=<value> eepprog.eep_dev.reload() fields = [] for f in args.fields: pair", "(eepprog.fields[key].descr, eepprog.get_field(key)) elif args.subcommand == 'dump': # eepprog dump eepprog.eep_dev.reload() print eepprog.eep_dev.dump() elif", "is None: argv = sys.argv else: sys.argv.extend(argv) eepprog = board.eepprog try: # Setup", "the binary content') parser_json = subparsers.add_parser('json', help='Output JSON format') parser_init = subparsers.add_parser('init', help='Initialize", "== 'json': # eepprog json eepprog.eep_dev.reload() print eepprog.toJSON() elif args.subcommand == 'field': #", "def operation_confirm(): s = raw_input('Are you sure to do this? (y/N): ') if", "info') parser_update = subparsers.add_parser('update', help='Update the device info') parser_update.add_argument('fields', type=str, metavar='<field>=<value>', nargs='+', help='Update", "in eepprog.fields: print 'Available fields are: ' +', '.join(eepprog.fields.keys()) return 2 else: fields.append(pair)", "this? (y/N): ') if s.lower() == 'y': return True return False # Entry", "main(board, argv=None): '''Command line options.''' if argv is None: argv = sys.argv else:", "as log from argparse import ArgumentParser class SysBoard(object): ''' Main system definition '''", "args.subcommand == 'update': # eepprog update # parse <field>=<value> eepprog.eep_dev.reload() fields = []", "parser.parse_args() if args.subcommand == 'show': # eepprog show eepprog.eep_dev.reload() for key in sorted(eepprog.fields.keys(),", "f=open('eeprom.json') # EEPROM format j_data = json.load(f) f.close() except Exception, e: print \"File", "if args.subcommand == 'show': # eepprog show eepprog.eep_dev.reload() for key in sorted(eepprog.fields.keys(), key", "try: # Setup argument parser parser = ArgumentParser(prog=sys.argv[0]) subparsers = parser.add_subparsers(help='help for subcommand',", "field print '\\nAvailable fields are: ' +', '.join(eepprog.fields.keys()) elif args.subcommand == 'update': #", "s = raw_input('Are you sure to do this? (y/N): ') if s.lower() ==", "''' Main system definition ''' def __init__(self, json_data): ''' Constructor ''' self.eeprom =", "device info') parser_erase = subparsers.add_parser('erase', help='Erase the device info') parser_update = subparsers.add_parser('update', help='Update", "1 args = parser.parse_args() if args.subcommand == 'show': # eepprog show eepprog.eep_dev.reload() for", "Exception, e: print \"File eeprom.json is not found.\" exit(1) board = SysBoard(j_data) sys.exit(main(board))", "+ repr(e) + \"\\n\") sys.stderr.write(indent + \" for help use --help\\n\") return 2", "= parser.parse_args() if args.subcommand == 'show': # eepprog show eepprog.eep_dev.reload() for key in", "def __init__(self, json_data): ''' Constructor ''' self.eeprom = eeprom.EepromBin(\"syseeprom.bin\") # Init EEPROM programmer", "raw_input('Are you sure to do this? (y/N): ') if s.lower() == 'y': return", "'show': # eepprog show eepprog.eep_dev.reload() for key in sorted(eepprog.fields.keys(), key = lambda name:", "subparsers.add_parser('erase', help='Erase the device info') parser_update = subparsers.add_parser('update', help='Update the device info') parser_update.add_argument('fields',", "') if s.lower() == 'y': return True return False # Entry point of", "print eepprog.eep_dev.dump() elif args.subcommand == 'erase': # eepprog erase if operation_confirm() == True:", "elif args.subcommand == 'init': # eepprog init if operation_confirm() == True: eepprog.init_default() eepprog.eep_dev.save()", "= len(parser.prog) * \" \" sys.stderr.write(parser.prog + \": \" + repr(e) + \"\\n\")", "format') parser_init = subparsers.add_parser('init', help='Initialize the device info') parser_erase = subparsers.add_parser('erase', help='Erase the", "parser_json = subparsers.add_parser('json', help='Output JSON format') parser_init = subparsers.add_parser('init', help='Initialize the device info')", "Init EEPROM programmer self.eepprog = eeprom.JsonEepromProg(self.eeprom,json_data['SysEeprom']) def main(board, argv=None): '''Command line options.''' if", "= subparsers.add_parser('json', help='Output JSON format') parser_init = subparsers.add_parser('init', help='Initialize the device info') parser_erase", "eepprog = board.eepprog try: # Setup argument parser parser = ArgumentParser(prog=sys.argv[0]) subparsers =", "= sys.argv else: sys.argv.extend(argv) eepprog = board.eepprog try: # Setup argument parser parser", "# Init EEPROM programmer self.eepprog = eeprom.JsonEepromProg(self.eeprom,json_data['SysEeprom']) def main(board, argv=None): '''Command line options.'''", "else: fields.append(pair) for f in fields: if eepprog.fields[f[0]] != None: eepprog.set_field(f[0],f[1]) eepprog.eep_dev.save() else:", "use --help\\n\") return 2 def operation_confirm(): s = raw_input('Are you sure to do", "elif args.subcommand == 'dump': # eepprog dump eepprog.eep_dev.reload() print eepprog.eep_dev.dump() elif args.subcommand ==", "__init__(self, json_data): ''' Constructor ''' self.eeprom = eeprom.EepromBin(\"syseeprom.bin\") # Init EEPROM programmer self.eepprog", "nargs='+', help='Update the specified field. ') parser_list = subparsers.add_parser('field', help='List the available fields.", "= eeprom.EepromBin(\"syseeprom.bin\") # Init EEPROM programmer self.eepprog = eeprom.JsonEepromProg(self.eeprom,json_data['SysEeprom']) def main(board, argv=None): '''Command", "fields.append(pair) for f in fields: if eepprog.fields[f[0]] != None: eepprog.set_field(f[0],f[1]) eepprog.eep_dev.save() else: parser.print_help()", "parser_update.add_argument('fields', type=str, metavar='<field>=<value>', nargs='+', help='Update the specified field. ') parser_list = subparsers.add_parser('field', help='List", "!= None: eepprog.set_field(f[0],f[1]) eepprog.eep_dev.save() else: parser.print_help() print '' except Exception, e: indent =", "eepprog.get_field(key)) elif args.subcommand == 'dump': # eepprog dump eepprog.eep_dev.reload() print eepprog.eep_dev.dump() elif args.subcommand", "sys.argv else: sys.argv.extend(argv) eepprog = board.eepprog try: # Setup argument parser parser =", "= subparsers.add_parser('update', help='Update the device info') parser_update.add_argument('fields', type=str, metavar='<field>=<value>', nargs='+', help='Update the specified", "elif args.subcommand == 'update': # eepprog update # parse <field>=<value> eepprog.eep_dev.reload() fields =", "elif pair[0] not in eepprog.fields: print 'Available fields are: ' +', '.join(eepprog.fields.keys()) return", "eepprog.eep_dev.reload() print eepprog.toJSON() elif args.subcommand == 'field': # eepprog field print '\\nAvailable fields", "you sure to do this? (y/N): ') if s.lower() == 'y': return True", "''' self.eeprom = eeprom.EepromBin(\"syseeprom.bin\") # Init EEPROM programmer self.eepprog = eeprom.JsonEepromProg(self.eeprom,json_data['SysEeprom']) def main(board,", "eepprog.toJSON() elif args.subcommand == 'field': # eepprog field print '\\nAvailable fields are: '", "eepprog field print '\\nAvailable fields are: ' +', '.join(eepprog.fields.keys()) elif args.subcommand == 'update':", "import sys import os import json import eeprom #import logging as log from", "system definition ''' def __init__(self, json_data): ''' Constructor ''' self.eeprom = eeprom.EepromBin(\"syseeprom.bin\") #", "help='Display the device info') parser_dump = subparsers.add_parser('dump', help='Dump the binary content') parser_json =", "help='Update the device info') parser_update.add_argument('fields', type=str, metavar='<field>=<value>', nargs='+', help='Update the specified field. ')", "== 'y': return True return False # Entry point of the script if", "2: parser_update.print_help() return 2 elif pair[0] not in eepprog.fields: print 'Available fields are:", "args.subcommand == 'show': # eepprog show eepprog.eep_dev.reload() for key in sorted(eepprog.fields.keys(), key =", "self.eeprom = eeprom.EepromBin(\"syseeprom.bin\") # Init EEPROM programmer self.eepprog = eeprom.JsonEepromProg(self.eeprom,json_data['SysEeprom']) def main(board, argv=None):", "eepprog.eep_dev.reload() print eepprog.eep_dev.dump() elif args.subcommand == 'erase': # eepprog erase if operation_confirm() ==", "in sorted(eepprog.fields.keys(), key = lambda name: eepprog.fields[name].offset): print '%-16s: %s' % (eepprog.fields[key].descr, eepprog.get_field(key))", "'%-16s: %s' % (eepprog.fields[key].descr, eepprog.get_field(key)) elif args.subcommand == 'dump': # eepprog dump eepprog.eep_dev.reload()", "# eepprog update # parse <field>=<value> eepprog.eep_dev.reload() fields = [] for f in", "2016 @author: ''' import sys import os import json import eeprom #import logging", "parser_update.print_help() return 2 elif pair[0] not in eepprog.fields: print 'Available fields are: '", "eeprom #import logging as log from argparse import ArgumentParser class SysBoard(object): ''' Main", "eepprog show eepprog.eep_dev.reload() for key in sorted(eepprog.fields.keys(), key = lambda name: eepprog.fields[name].offset): print", "json eepprog.eep_dev.reload() print eepprog.toJSON() elif args.subcommand == 'field': # eepprog field print '\\nAvailable", "def main(board, argv=None): '''Command line options.''' if argv is None: argv = sys.argv", "lambda name: eepprog.fields[name].offset): print '%-16s: %s' % (eepprog.fields[key].descr, eepprog.get_field(key)) elif args.subcommand == 'dump':", "len(pair) != 2: parser_update.print_help() return 2 elif pair[0] not in eepprog.fields: print 'Available", "Exception, e: indent = len(parser.prog) * \" \" sys.stderr.write(parser.prog + \": \" +", "sys.argv.extend(argv) eepprog = board.eepprog try: # Setup argument parser parser = ArgumentParser(prog=sys.argv[0]) subparsers", "= lambda name: eepprog.fields[name].offset): print '%-16s: %s' % (eepprog.fields[key].descr, eepprog.get_field(key)) elif args.subcommand ==", "operation_confirm(): s = raw_input('Are you sure to do this? (y/N): ') if s.lower()", "specified field. ') parser_list = subparsers.add_parser('field', help='List the available fields. ') if len(sys.argv)", "try: f=open('eeprom.json') # EEPROM format j_data = json.load(f) f.close() except Exception, e: print", "sys.stderr.write(indent + \" for help use --help\\n\") return 2 def operation_confirm(): s =", "do this? (y/N): ') if s.lower() == 'y': return True return False #", "else: sys.argv.extend(argv) eepprog = board.eepprog try: # Setup argument parser parser = ArgumentParser(prog=sys.argv[0])", "'Available fields are: ' +', '.join(eepprog.fields.keys()) return 2 else: fields.append(pair) for f in", "if s.lower() == 'y': return True return False # Entry point of the", "if len(pair) != 2: parser_update.print_help() return 2 elif pair[0] not in eepprog.fields: print", "'dump': # eepprog dump eepprog.eep_dev.reload() print eepprog.eep_dev.dump() elif args.subcommand == 'erase': # eepprog", "== 1: parser.print_help() return 1 args = parser.parse_args() if args.subcommand == 'show': #", "= subparsers.add_parser('dump', help='Dump the binary content') parser_json = subparsers.add_parser('json', help='Output JSON format') parser_init", "dump eepprog.eep_dev.reload() print eepprog.eep_dev.dump() elif args.subcommand == 'erase': # eepprog erase if operation_confirm()", "+ \"\\n\") sys.stderr.write(indent + \" for help use --help\\n\") return 2 def operation_confirm():", "20, 2016 @author: ''' import sys import os import json import eeprom #import", "info') parser_erase = subparsers.add_parser('erase', help='Erase the device info') parser_update = subparsers.add_parser('update', help='Update the", "sys import os import json import eeprom #import logging as log from argparse", "eepprog json eepprog.eep_dev.reload() print eepprog.toJSON() elif args.subcommand == 'field': # eepprog field print", "os import json import eeprom #import logging as log from argparse import ArgumentParser", "# EEPROM format j_data = json.load(f) f.close() except Exception, e: print \"File eeprom.json" ]
[ "the function getStoryString(). Use the functions getStoryString and loadWords to get the raw", "created in this problem set, decrypt the story given by the function getStoryString().", "Using the methods you created in this problem set, decrypt the story given", "get the raw data you need. returns: string - story in plain text", "to get the raw data you need. returns: string - story in plain", "raw data you need. returns: string - story in plain text \"\"\" story", "decrypt the story given by the function getStoryString(). Use the functions getStoryString and", "set, decrypt the story given by the function getStoryString(). Use the functions getStoryString", "\"\"\" Using the methods you created in this problem set, decrypt the story", "you need. returns: string - story in plain text \"\"\" story = CiphertextMessage(get_story_string())", "the story given by the function getStoryString(). Use the functions getStoryString and loadWords", "methods you created in this problem set, decrypt the story given by the", "the methods you created in this problem set, decrypt the story given by", "the functions getStoryString and loadWords to get the raw data you need. returns:", "functions getStoryString and loadWords to get the raw data you need. returns: string", "the raw data you need. returns: string - story in plain text \"\"\"", "function getStoryString(). Use the functions getStoryString and loadWords to get the raw data", "def decrypt_story(): \"\"\" Using the methods you created in this problem set, decrypt", "data you need. returns: string - story in plain text \"\"\" story =", "given by the function getStoryString(). Use the functions getStoryString and loadWords to get", "and loadWords to get the raw data you need. returns: string - story", "need. returns: string - story in plain text \"\"\" story = CiphertextMessage(get_story_string()) return", "this problem set, decrypt the story given by the function getStoryString(). Use the", "decrypt_story(): \"\"\" Using the methods you created in this problem set, decrypt the", "you created in this problem set, decrypt the story given by the function", "in this problem set, decrypt the story given by the function getStoryString(). Use", "Use the functions getStoryString and loadWords to get the raw data you need.", "loadWords to get the raw data you need. returns: string - story in", "problem set, decrypt the story given by the function getStoryString(). Use the functions", "getStoryString and loadWords to get the raw data you need. returns: string -", "story given by the function getStoryString(). Use the functions getStoryString and loadWords to", "getStoryString(). Use the functions getStoryString and loadWords to get the raw data you", "by the function getStoryString(). Use the functions getStoryString and loadWords to get the", "returns: string - story in plain text \"\"\" story = CiphertextMessage(get_story_string()) return story.decrypt_message()" ]
[ "self._from_string is None assert self._from_filename is None new_piped = deepcopy(self) new_piped._from_handle = handle", "is None: stdout = None else: if self._stdout_to_handle: stdout = self._stdout_to_handle if self._stdout_to_filename:", "deepcopy(self) new_piped._from_handle = handle return new_piped def from_filename(self, filename): assert self._from_string is None", "new_piped._stdout_to_filename = filename return new_piped def stdout_to_handle(self, handle): new_piped = deepcopy(self) new_piped._stdout_to_handle =", "self._command._ignore_errors: raise CommandExitError( self.__repr__(), returncode, stdoutput.decode(\"utf8\").strip() ) return stdoutput.decode(\"utf8\") def __str__(self): return \"", "self._stdout_to_filename = None self._stdout_to_handle = None self._stderr_to_handle = None def from_string(self, string): assert", "assert self._from_string is None assert self._from_handle is None new_piped = deepcopy(self) new_piped._from_filename =", "stderr=stderr, stdin=stdin, shell=self._command._shell, env=self._command.env, ) if self._from_string: process.stdin.write(self._from_string.encode(\"utf8\")) _, _ = process.communicate() returncode", "commandlib.exceptions import CommandError, CommandExitError from commandlib.utils import _check_directory from os import chdir, getcwd", "None and self._from_filename is None ): stdin = None else: if self._from_string: stdin", "= PIPE if self._from_handle: stdin = self._from_handle if self._from_filename: stdin = open(self._from_filename, \"r\")", "PIPE if self._from_handle: stdin = self._from_handle if self._from_filename: stdin = open(self._from_filename, \"r\") if", "self._from_string is None and self._from_filename is None ): stdin = None else: if", "0 and not self._command._ignore_errors: raise CommandExitError( self.__repr__(), returncode, stdoutput.decode(\"utf8\").strip() ) return stdoutput.decode(\"utf8\") def", "= PIPE else: if self._stderr_to_handle: stderr = self._stderr_to_handle if self._command.directory is not None:", "CommandError( '\"{0}\" failed (err code {1})'.format(self.__repr__(), returncode) ) def output(self): _check_directory(self._command.directory) previous_directory =", "chdir(previous_directory) if returncode != 0 and not self._command._ignore_errors: raise CommandError( '\"{0}\" failed (err", "if self._stderr_to_handle is None: stderr = PIPE else: if self._stderr_to_handle: stderr = self._stderr_to_handle", "None and self._from_string is None and self._from_filename is None ): stdin = None", "process = Popen( self._command.arguments, stdout=stdout, stderr=stderr, stdin=stdin, shell=self._command._shell, env=self._command.env, ) if self._from_string: process.stdin.write(self._from_string.encode(\"utf8\"))", "subprocess import PIPE, STDOUT, Popen from commandlib.exceptions import CommandError, CommandExitError from commandlib.utils import", "new_piped def from_handle(self, handle): assert self._from_string is None assert self._from_filename is None new_piped", "and not self._command._ignore_errors: raise CommandError( '\"{0}\" failed (err code {1})'.format(self.__repr__(), returncode) ) def", "stdin.close() if self._stdout_to_filename: stdout.close() chdir(previous_directory) if returncode != 0 and not self._command._ignore_errors: raise", "from_string(self, string): assert self._from_handle is None assert self._from_filename is None new_piped = deepcopy(self)", "else: if self._stdout_to_handle: stdout = self._stdout_to_handle if self._stdout_to_filename: stdout = open(self._stdout_to_filename, \"w\") if", "= None else: if self._stdout_to_handle: stdout = self._stdout_to_handle if self._stdout_to_filename: stdout = open(self._stdout_to_filename,", "self._from_string: stdin = PIPE if self._from_handle: stdin = self._from_handle process = Popen( self._command.arguments,", "stderr=STDOUT, stdin=stdin, shell=self._command._shell, env=self._command.env, ) if self._from_string: process.stdin.write(self._from_string.encode(\"utf8\")) stdoutput, _ = process.communicate() returncode", "= getcwd() if ( self._from_handle is None and self._from_string is None and self._from_filename", "_ = process.communicate() returncode = process.returncode chdir(previous_directory) if returncode != 0 and not", "None self._stdout_to_filename = None self._stdout_to_handle = None self._stderr_to_handle = None def from_string(self, string):", "\"w\") if self._stderr_to_handle is None: stderr = PIPE else: if self._stderr_to_handle: stderr =", "and self._from_filename is None ): stdin = None else: if self._from_string: stdin =", "is None new_piped = deepcopy(self) new_piped._from_filename = str(filename) return new_piped def stdout_to_filename(self, filename):", "chdir(previous_directory) if returncode != 0 and not self._command._ignore_errors: raise CommandExitError( self.__repr__(), returncode, stdoutput.decode(\"utf8\").strip()", "= string return new_piped def from_handle(self, handle): assert self._from_string is None assert self._from_filename", "returncode = process.returncode chdir(previous_directory) if returncode != 0 and not self._command._ignore_errors: raise CommandExitError(", "raise CommandExitError( self.__repr__(), returncode, stdoutput.decode(\"utf8\").strip() ) return stdoutput.decode(\"utf8\") def __str__(self): return \" \".join(self._command.arguments)", "stdout=PIPE, stderr=STDOUT, stdin=stdin, shell=self._command._shell, env=self._command.env, ) if self._from_string: process.stdin.write(self._from_string.encode(\"utf8\")) stdoutput, _ = process.communicate()", "open(self._stdout_to_filename, \"w\") if self._stderr_to_handle is None: stderr = PIPE else: if self._stderr_to_handle: stderr", "stdout = self._stdout_to_handle if self._stdout_to_filename: stdout = open(self._stdout_to_filename, \"w\") if self._stderr_to_handle is None:", "= deepcopy(self) new_piped._stderr_to_handle = handle return new_piped def run(self): _check_directory(self._command.directory) previous_directory = getcwd()", "if self._stderr_to_handle: stderr = self._stderr_to_handle if self._command.directory is not None: chdir(self._command.directory) try: process", "Popen from commandlib.exceptions import CommandError, CommandExitError from commandlib.utils import _check_directory from os import", "else: if self._from_string: stdin = PIPE if self._from_handle: stdin = self._from_handle if self._from_filename:", "is None assert self._from_filename is None new_piped = deepcopy(self) new_piped._from_string = string return", "PIPE if self._from_handle: stdin = self._from_handle process = Popen( self._command.arguments, stdout=PIPE, stderr=STDOUT, stdin=stdin,", "not self._command._ignore_errors: raise CommandError( '\"{0}\" failed (err code {1})'.format(self.__repr__(), returncode) ) def output(self):", "is None ): stdin = None else: if self._from_string: stdin = PIPE if", "is None and self._stdout_to_filename is None: stdout = None else: if self._stdout_to_handle: stdout", "stdin=stdin, shell=self._command._shell, env=self._command.env, ) if self._from_string: process.stdin.write(self._from_string.encode(\"utf8\")) _, _ = process.communicate() returncode =", "= self._from_handle process = Popen( self._command.arguments, stdout=PIPE, stderr=STDOUT, stdin=stdin, shell=self._command._shell, env=self._command.env, ) if", "def __str__(self): return \" \".join(self._command.arguments) def __unicode__(self): return \" \".join(self._command.arguments) def __repr__(self): return", "stdout = None else: if self._stdout_to_handle: stdout = self._stdout_to_handle if self._stdout_to_filename: stdout =", "self._command._ignore_errors: raise CommandError( '\"{0}\" failed (err code {1})'.format(self.__repr__(), returncode) ) def output(self): _check_directory(self._command.directory)", "self._from_string: process.stdin.write(self._from_string.encode(\"utf8\")) stdoutput, _ = process.communicate() returncode = process.returncode chdir(previous_directory) if returncode !=", "getcwd() if ( self._from_handle is None and self._from_string is None and self._from_filename is", "stdout_to_handle(self, handle): new_piped = deepcopy(self) new_piped._stdout_to_handle = handle return new_piped def stderr_to_handle(self, handle):", "= handle return new_piped def run(self): _check_directory(self._command.directory) previous_directory = getcwd() if ( self._from_handle", "filename): assert self._from_string is None assert self._from_handle is None new_piped = deepcopy(self) new_piped._from_filename", "assert self._from_handle is None assert self._from_filename is None new_piped = deepcopy(self) new_piped._from_string =", "self._from_handle is None and self._from_string is None: stdin = None else: if self._from_string:", "handle): assert self._from_string is None assert self._from_filename is None new_piped = deepcopy(self) new_piped._from_handle", "None self._stdout_to_handle = None self._stderr_to_handle = None def from_string(self, string): assert self._from_handle is", "= None self._stdout_to_handle = None self._stderr_to_handle = None def from_string(self, string): assert self._from_handle", "self._from_filename is None new_piped = deepcopy(self) new_piped._from_handle = handle return new_piped def from_filename(self,", "import chdir, getcwd class PipedCommand(object): def __init__(self, command): self._command = command self._from_string =", "None new_piped = deepcopy(self) new_piped._from_string = string return new_piped def from_handle(self, handle): assert", "and self._from_string is None and self._from_filename is None ): stdin = None else:", "self._command.arguments, stdout=stdout, stderr=stderr, stdin=stdin, shell=self._command._shell, env=self._command.env, ) if self._from_string: process.stdin.write(self._from_string.encode(\"utf8\")) _, _ =", "new_piped def stdout_to_handle(self, handle): new_piped = deepcopy(self) new_piped._stdout_to_handle = handle return new_piped def", "assert self._stderr_to_handle is None new_piped = deepcopy(self) new_piped._stderr_to_handle = handle return new_piped def", "copy import deepcopy from subprocess import PIPE, STDOUT, Popen from commandlib.exceptions import CommandError,", "= command self._from_string = None self._from_handle = None self._from_filename = None self._stdout_to_filename =", "= self._stderr_to_handle if self._command.directory is not None: chdir(self._command.directory) try: process = Popen( self._command.arguments,", "stdoutput, _ = process.communicate() returncode = process.returncode chdir(previous_directory) if returncode != 0 and", "process.communicate() returncode = process.returncode chdir(previous_directory) if returncode != 0 and not self._command._ignore_errors: raise", "code {1})'.format(self.__repr__(), returncode) ) def output(self): _check_directory(self._command.directory) previous_directory = getcwd() if self._command.directory is", "from subprocess import PIPE, STDOUT, Popen from commandlib.exceptions import CommandError, CommandExitError from commandlib.utils", "is None new_piped = deepcopy(self) new_piped._from_string = string return new_piped def from_handle(self, handle):", "self._stderr_to_handle is None new_piped = deepcopy(self) new_piped._stderr_to_handle = handle return new_piped def run(self):", "= process.communicate() returncode = process.returncode chdir(previous_directory) if returncode != 0 and not self._command._ignore_errors:", "None ): stdin = None else: if self._from_string: stdin = PIPE if self._from_handle:", "self._stdout_to_handle is None and self._stdout_to_filename is None: stdout = None else: if self._stdout_to_handle:", "= self._stdout_to_handle if self._stdout_to_filename: stdout = open(self._stdout_to_filename, \"w\") if self._stderr_to_handle is None: stderr", "if self._from_string: stdin = PIPE if self._from_handle: stdin = self._from_handle process = Popen(", "deepcopy(self) new_piped._from_string = string return new_piped def from_handle(self, handle): assert self._from_string is None", "self._from_handle process = Popen( self._command.arguments, stdout=PIPE, stderr=STDOUT, stdin=stdin, shell=self._command._shell, env=self._command.env, ) if self._from_string:", "def __init__(self, command): self._command = command self._from_string = None self._from_handle = None self._from_filename", "def run(self): _check_directory(self._command.directory) previous_directory = getcwd() if ( self._from_handle is None and self._from_string", "import _check_directory from os import chdir, getcwd class PipedCommand(object): def __init__(self, command): self._command", "self._from_handle is None assert self._from_filename is None new_piped = deepcopy(self) new_piped._from_string = string", "getcwd() if self._command.directory is not None: chdir(self._command.directory) if self._from_handle is None and self._from_string", "assert self._from_string is None assert self._from_filename is None new_piped = deepcopy(self) new_piped._from_handle =", "self._from_filename is None ): stdin = None else: if self._from_string: stdin = PIPE", "env=self._command.env, ) if self._from_string: process.stdin.write(self._from_string.encode(\"utf8\")) stdoutput, _ = process.communicate() returncode = process.returncode chdir(previous_directory)", "command self._from_string = None self._from_handle = None self._from_filename = None self._stdout_to_filename = None", "chdir(self._command.directory) if self._from_handle is None and self._from_string is None: stdin = None else:", "stdin = PIPE if self._from_handle: stdin = self._from_handle if self._from_filename: stdin = open(self._from_filename,", "if self._command.directory is not None: chdir(self._command.directory) try: process = Popen( self._command.arguments, stdout=stdout, stderr=stderr,", "handle return new_piped def from_filename(self, filename): assert self._from_string is None assert self._from_handle is", "handle): new_piped = deepcopy(self) new_piped._stdout_to_handle = handle return new_piped def stderr_to_handle(self, handle): assert", "_check_directory from os import chdir, getcwd class PipedCommand(object): def __init__(self, command): self._command =", "None self._from_handle = None self._from_filename = None self._stdout_to_filename = None self._stdout_to_handle = None", "None else: if self._from_string: stdin = PIPE if self._from_handle: stdin = self._from_handle if", "is None: stdin = None else: if self._from_string: stdin = PIPE if self._from_handle:", "from commandlib.exceptions import CommandError, CommandExitError from commandlib.utils import _check_directory from os import chdir,", "finally: if self._from_filename: stdin.close() if self._stdout_to_filename: stdout.close() chdir(previous_directory) if returncode != 0 and", "__init__(self, command): self._command = command self._from_string = None self._from_handle = None self._from_filename =", "{1})'.format(self.__repr__(), returncode) ) def output(self): _check_directory(self._command.directory) previous_directory = getcwd() if self._command.directory is not", "None assert self._from_filename is None new_piped = deepcopy(self) new_piped._from_handle = handle return new_piped", "None and self._from_string is None: stdin = None else: if self._from_string: stdin =", "chdir(self._command.directory) try: process = Popen( self._command.arguments, stdout=stdout, stderr=stderr, stdin=stdin, shell=self._command._shell, env=self._command.env, ) if", "new_piped def from_filename(self, filename): assert self._from_string is None assert self._from_handle is None new_piped", "previous_directory = getcwd() if self._command.directory is not None: chdir(self._command.directory) if self._from_handle is None", "shell=self._command._shell, env=self._command.env, ) if self._from_string: process.stdin.write(self._from_string.encode(\"utf8\")) stdoutput, _ = process.communicate() returncode = process.returncode", "def from_handle(self, handle): assert self._from_string is None assert self._from_filename is None new_piped =", "None: chdir(self._command.directory) try: process = Popen( self._command.arguments, stdout=stdout, stderr=stderr, stdin=stdin, shell=self._command._shell, env=self._command.env, )", "return new_piped def from_filename(self, filename): assert self._from_string is None assert self._from_handle is None", "None new_piped = deepcopy(self) new_piped._from_filename = str(filename) return new_piped def stdout_to_filename(self, filename): new_piped", "import CommandError, CommandExitError from commandlib.utils import _check_directory from os import chdir, getcwd class", "= deepcopy(self) new_piped._from_filename = str(filename) return new_piped def stdout_to_filename(self, filename): new_piped = deepcopy(self)", "None self._from_filename = None self._stdout_to_filename = None self._stdout_to_handle = None self._stderr_to_handle = None", "not self._command._ignore_errors: raise CommandExitError( self.__repr__(), returncode, stdoutput.decode(\"utf8\").strip() ) return stdoutput.decode(\"utf8\") def __str__(self): return", "None: stderr = PIPE else: if self._stderr_to_handle: stderr = self._stderr_to_handle if self._command.directory is", "self._from_filename = None self._stdout_to_filename = None self._stdout_to_handle = None self._stderr_to_handle = None def", "is None: stderr = PIPE else: if self._stderr_to_handle: stderr = self._stderr_to_handle if self._command.directory", "returncode != 0 and not self._command._ignore_errors: raise CommandError( '\"{0}\" failed (err code {1})'.format(self.__repr__(),", "_check_directory(self._command.directory) previous_directory = getcwd() if self._command.directory is not None: chdir(self._command.directory) if self._from_handle is", "def from_filename(self, filename): assert self._from_string is None assert self._from_handle is None new_piped =", "env=self._command.env, ) if self._from_string: process.stdin.write(self._from_string.encode(\"utf8\")) _, _ = process.communicate() returncode = process.returncode finally:", "= self._from_handle if self._from_filename: stdin = open(self._from_filename, \"r\") if self._stdout_to_handle is None and", "= process.returncode finally: if self._from_filename: stdin.close() if self._stdout_to_filename: stdout.close() chdir(previous_directory) if returncode !=", "= deepcopy(self) new_piped._stdout_to_handle = handle return new_piped def stderr_to_handle(self, handle): assert self._stderr_to_handle is", "= process.communicate() returncode = process.returncode finally: if self._from_filename: stdin.close() if self._stdout_to_filename: stdout.close() chdir(previous_directory)", "self._command.arguments, stdout=PIPE, stderr=STDOUT, stdin=stdin, shell=self._command._shell, env=self._command.env, ) if self._from_string: process.stdin.write(self._from_string.encode(\"utf8\")) stdoutput, _ =", "and self._stdout_to_filename is None: stdout = None else: if self._stdout_to_handle: stdout = self._stdout_to_handle", "handle return new_piped def stderr_to_handle(self, handle): assert self._stderr_to_handle is None new_piped = deepcopy(self)", "self._command.directory is not None: chdir(self._command.directory) try: process = Popen( self._command.arguments, stdout=stdout, stderr=stderr, stdin=stdin,", "os import chdir, getcwd class PipedCommand(object): def __init__(self, command): self._command = command self._from_string", "is None and self._from_filename is None ): stdin = None else: if self._from_string:", "str(filename) return new_piped def stdout_to_filename(self, filename): new_piped = deepcopy(self) new_piped._stdout_to_filename = filename return", "\"r\") if self._stdout_to_handle is None and self._stdout_to_filename is None: stdout = None else:", "handle): assert self._stderr_to_handle is None new_piped = deepcopy(self) new_piped._stderr_to_handle = handle return new_piped", "is None and self._from_string is None: stdin = None else: if self._from_string: stdin", "process.stdin.write(self._from_string.encode(\"utf8\")) stdoutput, _ = process.communicate() returncode = process.returncode chdir(previous_directory) if returncode != 0", "(err code {1})'.format(self.__repr__(), returncode) ) def output(self): _check_directory(self._command.directory) previous_directory = getcwd() if self._command.directory", ") if self._from_string: process.stdin.write(self._from_string.encode(\"utf8\")) _, _ = process.communicate() returncode = process.returncode finally: if", "self._from_handle is None and self._from_string is None and self._from_filename is None ): stdin", "= str(filename) return new_piped def stdout_to_filename(self, filename): new_piped = deepcopy(self) new_piped._stdout_to_filename = filename", "command): self._command = command self._from_string = None self._from_handle = None self._from_filename = None", "new_piped = deepcopy(self) new_piped._stdout_to_filename = filename return new_piped def stdout_to_handle(self, handle): new_piped =", "returncode != 0 and not self._command._ignore_errors: raise CommandExitError( self.__repr__(), returncode, stdoutput.decode(\"utf8\").strip() ) return", "self._stdout_to_handle: stdout = self._stdout_to_handle if self._stdout_to_filename: stdout = open(self._stdout_to_filename, \"w\") if self._stderr_to_handle is", "new_piped._from_string = string return new_piped def from_handle(self, handle): assert self._from_string is None assert", "return stdoutput.decode(\"utf8\") def __str__(self): return \" \".join(self._command.arguments) def __unicode__(self): return \" \".join(self._command.arguments) def", "new_piped = deepcopy(self) new_piped._stdout_to_handle = handle return new_piped def stderr_to_handle(self, handle): assert self._stderr_to_handle", "string return new_piped def from_handle(self, handle): assert self._from_string is None assert self._from_filename is", "!= 0 and not self._command._ignore_errors: raise CommandExitError( self.__repr__(), returncode, stdoutput.decode(\"utf8\").strip() ) return stdoutput.decode(\"utf8\")", "def from_string(self, string): assert self._from_handle is None assert self._from_filename is None new_piped =", "process.returncode chdir(previous_directory) if returncode != 0 and not self._command._ignore_errors: raise CommandExitError( self.__repr__(), returncode,", "returncode = process.returncode finally: if self._from_filename: stdin.close() if self._stdout_to_filename: stdout.close() chdir(previous_directory) if returncode", "None def from_string(self, string): assert self._from_handle is None assert self._from_filename is None new_piped", "_check_directory(self._command.directory) previous_directory = getcwd() if ( self._from_handle is None and self._from_string is None", "self._from_handle: stdin = self._from_handle process = Popen( self._command.arguments, stdout=PIPE, stderr=STDOUT, stdin=stdin, shell=self._command._shell, env=self._command.env,", "= filename return new_piped def stdout_to_handle(self, handle): new_piped = deepcopy(self) new_piped._stdout_to_handle = handle", "return new_piped def stderr_to_handle(self, handle): assert self._stderr_to_handle is None new_piped = deepcopy(self) new_piped._stderr_to_handle", "= None self._from_handle = None self._from_filename = None self._stdout_to_filename = None self._stdout_to_handle =", "stdoutput.decode(\"utf8\") def __str__(self): return \" \".join(self._command.arguments) def __unicode__(self): return \" \".join(self._command.arguments) def __repr__(self):", "new_piped = deepcopy(self) new_piped._stderr_to_handle = handle return new_piped def run(self): _check_directory(self._command.directory) previous_directory =", "None else: if self._stdout_to_handle: stdout = self._stdout_to_handle if self._stdout_to_filename: stdout = open(self._stdout_to_filename, \"w\")", "deepcopy from subprocess import PIPE, STDOUT, Popen from commandlib.exceptions import CommandError, CommandExitError from", "commandlib.utils import _check_directory from os import chdir, getcwd class PipedCommand(object): def __init__(self, command):", "= Popen( self._command.arguments, stdout=PIPE, stderr=STDOUT, stdin=stdin, shell=self._command._shell, env=self._command.env, ) if self._from_string: process.stdin.write(self._from_string.encode(\"utf8\")) stdoutput,", "self._from_handle: stdin = self._from_handle if self._from_filename: stdin = open(self._from_filename, \"r\") if self._stdout_to_handle is", "assert self._from_filename is None new_piped = deepcopy(self) new_piped._from_string = string return new_piped def", "previous_directory = getcwd() if ( self._from_handle is None and self._from_string is None and", "assert self._from_handle is None new_piped = deepcopy(self) new_piped._from_filename = str(filename) return new_piped def", "open(self._from_filename, \"r\") if self._stdout_to_handle is None and self._stdout_to_filename is None: stdout = None", "stdout.close() chdir(previous_directory) if returncode != 0 and not self._command._ignore_errors: raise CommandError( '\"{0}\" failed", "CommandError, CommandExitError from commandlib.utils import _check_directory from os import chdir, getcwd class PipedCommand(object):", "= None else: if self._from_string: stdin = PIPE if self._from_handle: stdin = self._from_handle", "stdin = self._from_handle process = Popen( self._command.arguments, stdout=PIPE, stderr=STDOUT, stdin=stdin, shell=self._command._shell, env=self._command.env, )", "new_piped._stdout_to_handle = handle return new_piped def stderr_to_handle(self, handle): assert self._stderr_to_handle is None new_piped", "deepcopy(self) new_piped._stdout_to_filename = filename return new_piped def stdout_to_handle(self, handle): new_piped = deepcopy(self) new_piped._stdout_to_handle", "deepcopy(self) new_piped._stderr_to_handle = handle return new_piped def run(self): _check_directory(self._command.directory) previous_directory = getcwd() if", "from_handle(self, handle): assert self._from_string is None assert self._from_filename is None new_piped = deepcopy(self)", "None else: if self._from_string: stdin = PIPE if self._from_handle: stdin = self._from_handle process", "stdout = open(self._stdout_to_filename, \"w\") if self._stderr_to_handle is None: stderr = PIPE else: if", "def output(self): _check_directory(self._command.directory) previous_directory = getcwd() if self._command.directory is not None: chdir(self._command.directory) if", "stdin = open(self._from_filename, \"r\") if self._stdout_to_handle is None and self._stdout_to_filename is None: stdout", "returncode) ) def output(self): _check_directory(self._command.directory) previous_directory = getcwd() if self._command.directory is not None:", "if self._stdout_to_filename: stdout = open(self._stdout_to_filename, \"w\") if self._stderr_to_handle is None: stderr = PIPE", "new_piped._from_filename = str(filename) return new_piped def stdout_to_filename(self, filename): new_piped = deepcopy(self) new_piped._stdout_to_filename =", "( self._from_handle is None and self._from_string is None and self._from_filename is None ):", "is None new_piped = deepcopy(self) new_piped._stderr_to_handle = handle return new_piped def run(self): _check_directory(self._command.directory)", "PIPE else: if self._stderr_to_handle: stderr = self._stderr_to_handle if self._command.directory is not None: chdir(self._command.directory)", "stdout=stdout, stderr=stderr, stdin=stdin, shell=self._command._shell, env=self._command.env, ) if self._from_string: process.stdin.write(self._from_string.encode(\"utf8\")) _, _ = process.communicate()", "assert self._from_filename is None new_piped = deepcopy(self) new_piped._from_handle = handle return new_piped def", "return new_piped def stdout_to_handle(self, handle): new_piped = deepcopy(self) new_piped._stdout_to_handle = handle return new_piped", "None: stdout = None else: if self._stdout_to_handle: stdout = self._stdout_to_handle if self._stdout_to_filename: stdout", "self._stdout_to_filename: stdout = open(self._stdout_to_filename, \"w\") if self._stderr_to_handle is None: stderr = PIPE else:", ") def output(self): _check_directory(self._command.directory) previous_directory = getcwd() if self._command.directory is not None: chdir(self._command.directory)", "CommandExitError( self.__repr__(), returncode, stdoutput.decode(\"utf8\").strip() ) return stdoutput.decode(\"utf8\") def __str__(self): return \" \".join(self._command.arguments) def", "deepcopy(self) new_piped._from_filename = str(filename) return new_piped def stdout_to_filename(self, filename): new_piped = deepcopy(self) new_piped._stdout_to_filename", "0 and not self._command._ignore_errors: raise CommandError( '\"{0}\" failed (err code {1})'.format(self.__repr__(), returncode) )", "self._from_filename is None new_piped = deepcopy(self) new_piped._from_string = string return new_piped def from_handle(self,", "PIPE, STDOUT, Popen from commandlib.exceptions import CommandError, CommandExitError from commandlib.utils import _check_directory from", "not None: chdir(self._command.directory) try: process = Popen( self._command.arguments, stdout=stdout, stderr=stderr, stdin=stdin, shell=self._command._shell, env=self._command.env,", "is not None: chdir(self._command.directory) if self._from_handle is None and self._from_string is None: stdin", "None: stdin = None else: if self._from_string: stdin = PIPE if self._from_handle: stdin", "= Popen( self._command.arguments, stdout=stdout, stderr=stderr, stdin=stdin, shell=self._command._shell, env=self._command.env, ) if self._from_string: process.stdin.write(self._from_string.encode(\"utf8\")) _,", "process = Popen( self._command.arguments, stdout=PIPE, stderr=STDOUT, stdin=stdin, shell=self._command._shell, env=self._command.env, ) if self._from_string: process.stdin.write(self._from_string.encode(\"utf8\"))", "is None and self._from_string is None and self._from_filename is None ): stdin =", "if ( self._from_handle is None and self._from_string is None and self._from_filename is None", "def stderr_to_handle(self, handle): assert self._stderr_to_handle is None new_piped = deepcopy(self) new_piped._stderr_to_handle = handle", "process.returncode finally: if self._from_filename: stdin.close() if self._stdout_to_filename: stdout.close() chdir(previous_directory) if returncode != 0", "and self._from_string is None: stdin = None else: if self._from_string: stdin = PIPE", "Popen( self._command.arguments, stdout=PIPE, stderr=STDOUT, stdin=stdin, shell=self._command._shell, env=self._command.env, ) if self._from_string: process.stdin.write(self._from_string.encode(\"utf8\")) stdoutput, _", "'\"{0}\" failed (err code {1})'.format(self.__repr__(), returncode) ) def output(self): _check_directory(self._command.directory) previous_directory = getcwd()", "stdin = self._from_handle if self._from_filename: stdin = open(self._from_filename, \"r\") if self._stdout_to_handle is None", "self._from_filename: stdin = open(self._from_filename, \"r\") if self._stdout_to_handle is None and self._stdout_to_filename is None:", "None new_piped = deepcopy(self) new_piped._stderr_to_handle = handle return new_piped def run(self): _check_directory(self._command.directory) previous_directory", "self._stderr_to_handle if self._command.directory is not None: chdir(self._command.directory) try: process = Popen( self._command.arguments, stdout=stdout,", "= PIPE if self._from_handle: stdin = self._from_handle process = Popen( self._command.arguments, stdout=PIPE, stderr=STDOUT,", "): stdin = None else: if self._from_string: stdin = PIPE if self._from_handle: stdin", "self._from_string: stdin = PIPE if self._from_handle: stdin = self._from_handle if self._from_filename: stdin =", "self.__repr__(), returncode, stdoutput.decode(\"utf8\").strip() ) return stdoutput.decode(\"utf8\") def __str__(self): return \" \".join(self._command.arguments) def __unicode__(self):", "PipedCommand(object): def __init__(self, command): self._command = command self._from_string = None self._from_handle = None", "if self._stdout_to_handle: stdout = self._stdout_to_handle if self._stdout_to_filename: stdout = open(self._stdout_to_filename, \"w\") if self._stderr_to_handle", "stdin = PIPE if self._from_handle: stdin = self._from_handle process = Popen( self._command.arguments, stdout=PIPE,", "return new_piped def stdout_to_filename(self, filename): new_piped = deepcopy(self) new_piped._stdout_to_filename = filename return new_piped", "= process.returncode chdir(previous_directory) if returncode != 0 and not self._command._ignore_errors: raise CommandExitError( self.__repr__(),", "failed (err code {1})'.format(self.__repr__(), returncode) ) def output(self): _check_directory(self._command.directory) previous_directory = getcwd() if", "if self._stdout_to_handle is None and self._stdout_to_filename is None: stdout = None else: if", "filename): new_piped = deepcopy(self) new_piped._stdout_to_filename = filename return new_piped def stdout_to_handle(self, handle): new_piped", "from copy import deepcopy from subprocess import PIPE, STDOUT, Popen from commandlib.exceptions import", "process.stdin.write(self._from_string.encode(\"utf8\")) _, _ = process.communicate() returncode = process.returncode finally: if self._from_filename: stdin.close() if", "is None assert self._from_handle is None new_piped = deepcopy(self) new_piped._from_filename = str(filename) return", "stdoutput.decode(\"utf8\").strip() ) return stdoutput.decode(\"utf8\") def __str__(self): return \" \".join(self._command.arguments) def __unicode__(self): return \"", "import deepcopy from subprocess import PIPE, STDOUT, Popen from commandlib.exceptions import CommandError, CommandExitError", "= deepcopy(self) new_piped._stdout_to_filename = filename return new_piped def stdout_to_handle(self, handle): new_piped = deepcopy(self)", "not None: chdir(self._command.directory) if self._from_handle is None and self._from_string is None: stdin =", "is None assert self._from_filename is None new_piped = deepcopy(self) new_piped._from_handle = handle return", "CommandExitError from commandlib.utils import _check_directory from os import chdir, getcwd class PipedCommand(object): def", "self._from_handle if self._from_filename: stdin = open(self._from_filename, \"r\") if self._stdout_to_handle is None and self._stdout_to_filename", "Popen( self._command.arguments, stdout=stdout, stderr=stderr, stdin=stdin, shell=self._command._shell, env=self._command.env, ) if self._from_string: process.stdin.write(self._from_string.encode(\"utf8\")) _, _", "self._stderr_to_handle: stderr = self._stderr_to_handle if self._command.directory is not None: chdir(self._command.directory) try: process =", "run(self): _check_directory(self._command.directory) previous_directory = getcwd() if ( self._from_handle is None and self._from_string is", "self._from_string: process.stdin.write(self._from_string.encode(\"utf8\")) _, _ = process.communicate() returncode = process.returncode finally: if self._from_filename: stdin.close()", "if self._from_filename: stdin.close() if self._stdout_to_filename: stdout.close() chdir(previous_directory) if returncode != 0 and not", ") if self._from_string: process.stdin.write(self._from_string.encode(\"utf8\")) stdoutput, _ = process.communicate() returncode = process.returncode chdir(previous_directory) if", "self._stderr_to_handle = None def from_string(self, string): assert self._from_handle is None assert self._from_filename is", "if self._from_handle is None and self._from_string is None: stdin = None else: if", "self._stdout_to_filename is None: stdout = None else: if self._stdout_to_handle: stdout = self._stdout_to_handle if", "shell=self._command._shell, env=self._command.env, ) if self._from_string: process.stdin.write(self._from_string.encode(\"utf8\")) _, _ = process.communicate() returncode = process.returncode", "output(self): _check_directory(self._command.directory) previous_directory = getcwd() if self._command.directory is not None: chdir(self._command.directory) if self._from_handle", "__str__(self): return \" \".join(self._command.arguments) def __unicode__(self): return \" \".join(self._command.arguments) def __repr__(self): return self.__str__()", "def stdout_to_handle(self, handle): new_piped = deepcopy(self) new_piped._stdout_to_handle = handle return new_piped def stderr_to_handle(self,", "handle return new_piped def run(self): _check_directory(self._command.directory) previous_directory = getcwd() if ( self._from_handle is", "string): assert self._from_handle is None assert self._from_filename is None new_piped = deepcopy(self) new_piped._from_string", "new_piped def run(self): _check_directory(self._command.directory) previous_directory = getcwd() if ( self._from_handle is None and", "= deepcopy(self) new_piped._from_string = string return new_piped def from_handle(self, handle): assert self._from_string is", "self._command = command self._from_string = None self._from_handle = None self._from_filename = None self._stdout_to_filename", "deepcopy(self) new_piped._stdout_to_handle = handle return new_piped def stderr_to_handle(self, handle): assert self._stderr_to_handle is None", "_ = process.communicate() returncode = process.returncode finally: if self._from_filename: stdin.close() if self._stdout_to_filename: stdout.close()", "try: process = Popen( self._command.arguments, stdout=stdout, stderr=stderr, stdin=stdin, shell=self._command._shell, env=self._command.env, ) if self._from_string:", "None: chdir(self._command.directory) if self._from_handle is None and self._from_string is None: stdin = None", "None assert self._from_filename is None new_piped = deepcopy(self) new_piped._from_string = string return new_piped", "returncode, stdoutput.decode(\"utf8\").strip() ) return stdoutput.decode(\"utf8\") def __str__(self): return \" \".join(self._command.arguments) def __unicode__(self): return", "new_piped def stdout_to_filename(self, filename): new_piped = deepcopy(self) new_piped._stdout_to_filename = filename return new_piped def", "if self._from_string: stdin = PIPE if self._from_handle: stdin = self._from_handle if self._from_filename: stdin", "self._from_handle = None self._from_filename = None self._stdout_to_filename = None self._stdout_to_handle = None self._stderr_to_handle", "= open(self._from_filename, \"r\") if self._stdout_to_handle is None and self._stdout_to_filename is None: stdout =", "new_piped = deepcopy(self) new_piped._from_string = string return new_piped def from_handle(self, handle): assert self._from_string", "new_piped def stderr_to_handle(self, handle): assert self._stderr_to_handle is None new_piped = deepcopy(self) new_piped._stderr_to_handle =", "self._stdout_to_filename: stdout.close() chdir(previous_directory) if returncode != 0 and not self._command._ignore_errors: raise CommandError( '\"{0}\"", "stdout_to_filename(self, filename): new_piped = deepcopy(self) new_piped._stdout_to_filename = filename return new_piped def stdout_to_handle(self, handle):", "self._stderr_to_handle is None: stderr = PIPE else: if self._stderr_to_handle: stderr = self._stderr_to_handle if", "= None self._stderr_to_handle = None def from_string(self, string): assert self._from_handle is None assert", "self._from_string is None assert self._from_handle is None new_piped = deepcopy(self) new_piped._from_filename = str(filename)", "getcwd class PipedCommand(object): def __init__(self, command): self._command = command self._from_string = None self._from_handle", "STDOUT, Popen from commandlib.exceptions import CommandError, CommandExitError from commandlib.utils import _check_directory from os", "def stdout_to_filename(self, filename): new_piped = deepcopy(self) new_piped._stdout_to_filename = filename return new_piped def stdout_to_handle(self,", "= None def from_string(self, string): assert self._from_handle is None assert self._from_filename is None", "self._from_handle is None new_piped = deepcopy(self) new_piped._from_filename = str(filename) return new_piped def stdout_to_filename(self,", "new_piped = deepcopy(self) new_piped._from_filename = str(filename) return new_piped def stdout_to_filename(self, filename): new_piped =", "from os import chdir, getcwd class PipedCommand(object): def __init__(self, command): self._command = command", "return new_piped def from_handle(self, handle): assert self._from_string is None assert self._from_filename is None", "if self._from_handle: stdin = self._from_handle process = Popen( self._command.arguments, stdout=PIPE, stderr=STDOUT, stdin=stdin, shell=self._command._shell,", "self._from_string = None self._from_handle = None self._from_filename = None self._stdout_to_filename = None self._stdout_to_handle", "if self._command.directory is not None: chdir(self._command.directory) if self._from_handle is None and self._from_string is", "chdir, getcwd class PipedCommand(object): def __init__(self, command): self._command = command self._from_string = None", "= None self._from_filename = None self._stdout_to_filename = None self._stdout_to_handle = None self._stderr_to_handle =", "stderr_to_handle(self, handle): assert self._stderr_to_handle is None new_piped = deepcopy(self) new_piped._stderr_to_handle = handle return", "self._from_string is None: stdin = None else: if self._from_string: stdin = PIPE if", "if self._from_handle: stdin = self._from_handle if self._from_filename: stdin = open(self._from_filename, \"r\") if self._stdout_to_handle", "and not self._command._ignore_errors: raise CommandExitError( self.__repr__(), returncode, stdoutput.decode(\"utf8\").strip() ) return stdoutput.decode(\"utf8\") def __str__(self):", "= handle return new_piped def stderr_to_handle(self, handle): assert self._stderr_to_handle is None new_piped =", "import PIPE, STDOUT, Popen from commandlib.exceptions import CommandError, CommandExitError from commandlib.utils import _check_directory", "if returncode != 0 and not self._command._ignore_errors: raise CommandExitError( self.__repr__(), returncode, stdoutput.decode(\"utf8\").strip() )", "is not None: chdir(self._command.directory) try: process = Popen( self._command.arguments, stdout=stdout, stderr=stderr, stdin=stdin, shell=self._command._shell,", "if self._from_string: process.stdin.write(self._from_string.encode(\"utf8\")) stdoutput, _ = process.communicate() returncode = process.returncode chdir(previous_directory) if returncode", "else: if self._from_string: stdin = PIPE if self._from_handle: stdin = self._from_handle process =", "!= 0 and not self._command._ignore_errors: raise CommandError( '\"{0}\" failed (err code {1})'.format(self.__repr__(), returncode)", "if self._from_filename: stdin = open(self._from_filename, \"r\") if self._stdout_to_handle is None and self._stdout_to_filename is", "process.communicate() returncode = process.returncode finally: if self._from_filename: stdin.close() if self._stdout_to_filename: stdout.close() chdir(previous_directory) if", "if self._stdout_to_filename: stdout.close() chdir(previous_directory) if returncode != 0 and not self._command._ignore_errors: raise CommandError(", "from commandlib.utils import _check_directory from os import chdir, getcwd class PipedCommand(object): def __init__(self,", "return new_piped def run(self): _check_directory(self._command.directory) previous_directory = getcwd() if ( self._from_handle is None", "self._stdout_to_handle if self._stdout_to_filename: stdout = open(self._stdout_to_filename, \"w\") if self._stderr_to_handle is None: stderr =", "filename return new_piped def stdout_to_handle(self, handle): new_piped = deepcopy(self) new_piped._stdout_to_handle = handle return", "from_filename(self, filename): assert self._from_string is None assert self._from_handle is None new_piped = deepcopy(self)", "stderr = self._stderr_to_handle if self._command.directory is not None: chdir(self._command.directory) try: process = Popen(", "stdin = None else: if self._from_string: stdin = PIPE if self._from_handle: stdin =", "None self._stderr_to_handle = None def from_string(self, string): assert self._from_handle is None assert self._from_filename", "= getcwd() if self._command.directory is not None: chdir(self._command.directory) if self._from_handle is None and", "else: if self._stderr_to_handle: stderr = self._stderr_to_handle if self._command.directory is not None: chdir(self._command.directory) try:", "= handle return new_piped def from_filename(self, filename): assert self._from_string is None assert self._from_handle", "self._command.directory is not None: chdir(self._command.directory) if self._from_handle is None and self._from_string is None:", "= None self._stdout_to_filename = None self._stdout_to_handle = None self._stderr_to_handle = None def from_string(self,", "None new_piped = deepcopy(self) new_piped._from_handle = handle return new_piped def from_filename(self, filename): assert", "= deepcopy(self) new_piped._from_handle = handle return new_piped def from_filename(self, filename): assert self._from_string is", "= open(self._stdout_to_filename, \"w\") if self._stderr_to_handle is None: stderr = PIPE else: if self._stderr_to_handle:", ") return stdoutput.decode(\"utf8\") def __str__(self): return \" \".join(self._command.arguments) def __unicode__(self): return \" \".join(self._command.arguments)", "class PipedCommand(object): def __init__(self, command): self._command = command self._from_string = None self._from_handle =", "stderr = PIPE else: if self._stderr_to_handle: stderr = self._stderr_to_handle if self._command.directory is not", "None assert self._from_handle is None new_piped = deepcopy(self) new_piped._from_filename = str(filename) return new_piped", "_, _ = process.communicate() returncode = process.returncode finally: if self._from_filename: stdin.close() if self._stdout_to_filename:", "if self._from_string: process.stdin.write(self._from_string.encode(\"utf8\")) _, _ = process.communicate() returncode = process.returncode finally: if self._from_filename:", "new_piped = deepcopy(self) new_piped._from_handle = handle return new_piped def from_filename(self, filename): assert self._from_string", "self._from_filename: stdin.close() if self._stdout_to_filename: stdout.close() chdir(previous_directory) if returncode != 0 and not self._command._ignore_errors:", "<reponame>crdoconnor/commandlib<filename>commandlib/piped.py from copy import deepcopy from subprocess import PIPE, STDOUT, Popen from commandlib.exceptions", "None and self._stdout_to_filename is None: stdout = None else: if self._stdout_to_handle: stdout =", "raise CommandError( '\"{0}\" failed (err code {1})'.format(self.__repr__(), returncode) ) def output(self): _check_directory(self._command.directory) previous_directory", "new_piped._stderr_to_handle = handle return new_piped def run(self): _check_directory(self._command.directory) previous_directory = getcwd() if (", "self._stdout_to_handle = None self._stderr_to_handle = None def from_string(self, string): assert self._from_handle is None", "new_piped._from_handle = handle return new_piped def from_filename(self, filename): assert self._from_string is None assert", "if returncode != 0 and not self._command._ignore_errors: raise CommandError( '\"{0}\" failed (err code", "is None new_piped = deepcopy(self) new_piped._from_handle = handle return new_piped def from_filename(self, filename):", "stdin=stdin, shell=self._command._shell, env=self._command.env, ) if self._from_string: process.stdin.write(self._from_string.encode(\"utf8\")) stdoutput, _ = process.communicate() returncode =" ]
[ "2019-12-02 23:35 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('thebrushstash',", "from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('thebrushstash', '0005_setting'), ]", "= [ ('thebrushstash', '0005_setting'), ] operations = [ migrations.CreateModel( name='StaticPageContent', fields=[ ('id', models.AutoField(auto_created=True,", "23:35 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('thebrushstash', '0005_setting'),", "('thebrushstash', '0005_setting'), ] operations = [ migrations.CreateModel( name='StaticPageContent', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,", "models class Migration(migrations.Migration): dependencies = [ ('thebrushstash', '0005_setting'), ] operations = [ migrations.CreateModel(", "django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('thebrushstash', '0005_setting'), ] operations", "= [ migrations.CreateModel( name='StaticPageContent', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=1000)), ],", "[ migrations.CreateModel( name='StaticPageContent', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=1000)), ], ),", "[ ('thebrushstash', '0005_setting'), ] operations = [ migrations.CreateModel( name='StaticPageContent', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,", "Migration(migrations.Migration): dependencies = [ ('thebrushstash', '0005_setting'), ] operations = [ migrations.CreateModel( name='StaticPageContent', fields=[", "class Migration(migrations.Migration): dependencies = [ ('thebrushstash', '0005_setting'), ] operations = [ migrations.CreateModel( name='StaticPageContent',", "by Django 2.2.7 on 2019-12-02 23:35 from django.db import migrations, models class Migration(migrations.Migration):", "# Generated by Django 2.2.7 on 2019-12-02 23:35 from django.db import migrations, models", "Generated by Django 2.2.7 on 2019-12-02 23:35 from django.db import migrations, models class", "operations = [ migrations.CreateModel( name='StaticPageContent', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=1000)),", "migrations, models class Migration(migrations.Migration): dependencies = [ ('thebrushstash', '0005_setting'), ] operations = [", "] operations = [ migrations.CreateModel( name='StaticPageContent', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title',", "Django 2.2.7 on 2019-12-02 23:35 from django.db import migrations, models class Migration(migrations.Migration): dependencies", "migrations.CreateModel( name='StaticPageContent', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=1000)), ], ), ]", "on 2019-12-02 23:35 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [", "import migrations, models class Migration(migrations.Migration): dependencies = [ ('thebrushstash', '0005_setting'), ] operations =", "2.2.7 on 2019-12-02 23:35 from django.db import migrations, models class Migration(migrations.Migration): dependencies =", "'0005_setting'), ] operations = [ migrations.CreateModel( name='StaticPageContent', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),", "<reponame>zenofewords/thebrushstash # Generated by Django 2.2.7 on 2019-12-02 23:35 from django.db import migrations,", "dependencies = [ ('thebrushstash', '0005_setting'), ] operations = [ migrations.CreateModel( name='StaticPageContent', fields=[ ('id'," ]
[ "] operations = [ migrations.AddField( model_name='rate', name='content', field=models.PositiveIntegerField(default=0, validators=[django.core.validators.MaxValueValidator(10)]), ), migrations.AddField( model_name='rate', name='usability',", "django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('awwaards_app', '0003_rate'),", "class Migration(migrations.Migration): dependencies = [ ('awwaards_app', '0003_rate'), ] operations = [ migrations.AddField( model_name='rate',", "models class Migration(migrations.Migration): dependencies = [ ('awwaards_app', '0003_rate'), ] operations = [ migrations.AddField(", "3.0.7 on 2020-06-09 12:12 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration):", "12:12 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [", "<reponame>hamisicodes/Awwaards # Generated by Django 3.0.7 on 2020-06-09 12:12 import django.core.validators from django.db", "2020-06-09 12:12 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies =", "= [ migrations.AddField( model_name='rate', name='content', field=models.PositiveIntegerField(default=0, validators=[django.core.validators.MaxValueValidator(10)]), ), migrations.AddField( model_name='rate', name='usability', field=models.PositiveIntegerField(default=0, validators=[django.core.validators.MaxValueValidator(10)]),", "import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('awwaards_app',", "[ ('awwaards_app', '0003_rate'), ] operations = [ migrations.AddField( model_name='rate', name='content', field=models.PositiveIntegerField(default=0, validators=[django.core.validators.MaxValueValidator(10)]), ),", "= [ ('awwaards_app', '0003_rate'), ] operations = [ migrations.AddField( model_name='rate', name='content', field=models.PositiveIntegerField(default=0, validators=[django.core.validators.MaxValueValidator(10)]),", "Migration(migrations.Migration): dependencies = [ ('awwaards_app', '0003_rate'), ] operations = [ migrations.AddField( model_name='rate', name='content',", "operations = [ migrations.AddField( model_name='rate', name='content', field=models.PositiveIntegerField(default=0, validators=[django.core.validators.MaxValueValidator(10)]), ), migrations.AddField( model_name='rate', name='usability', field=models.PositiveIntegerField(default=0,", "Generated by Django 3.0.7 on 2020-06-09 12:12 import django.core.validators from django.db import migrations,", "by Django 3.0.7 on 2020-06-09 12:12 import django.core.validators from django.db import migrations, models", "import migrations, models class Migration(migrations.Migration): dependencies = [ ('awwaards_app', '0003_rate'), ] operations =", "('awwaards_app', '0003_rate'), ] operations = [ migrations.AddField( model_name='rate', name='content', field=models.PositiveIntegerField(default=0, validators=[django.core.validators.MaxValueValidator(10)]), ), migrations.AddField(", "from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('awwaards_app', '0003_rate'), ]", "# Generated by Django 3.0.7 on 2020-06-09 12:12 import django.core.validators from django.db import", "Django 3.0.7 on 2020-06-09 12:12 import django.core.validators from django.db import migrations, models class", "on 2020-06-09 12:12 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies", "dependencies = [ ('awwaards_app', '0003_rate'), ] operations = [ migrations.AddField( model_name='rate', name='content', field=models.PositiveIntegerField(default=0,", "migrations.AddField( model_name='rate', name='content', field=models.PositiveIntegerField(default=0, validators=[django.core.validators.MaxValueValidator(10)]), ), migrations.AddField( model_name='rate', name='usability', field=models.PositiveIntegerField(default=0, validators=[django.core.validators.MaxValueValidator(10)]), ), ]", "[ migrations.AddField( model_name='rate', name='content', field=models.PositiveIntegerField(default=0, validators=[django.core.validators.MaxValueValidator(10)]), ), migrations.AddField( model_name='rate', name='usability', field=models.PositiveIntegerField(default=0, validators=[django.core.validators.MaxValueValidator(10)]), ),", "'0003_rate'), ] operations = [ migrations.AddField( model_name='rate', name='content', field=models.PositiveIntegerField(default=0, validators=[django.core.validators.MaxValueValidator(10)]), ), migrations.AddField( model_name='rate',", "django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('awwaards_app', '0003_rate'), ] operations", "migrations, models class Migration(migrations.Migration): dependencies = [ ('awwaards_app', '0003_rate'), ] operations = [" ]
[ "structFile = os.path.join(struct_dir, 'dg_seoul_test.mat') #x, y, coord, radius = 327934.67464998, 4153535.06119226, 'utm', 25", "not(db_dir): raise FileNotFoundError(\"root_dir : {}, db_dir : {}\".format(root_dir, db_dir)) struct_dir = os.path.join(root_dir, 'datasets')", "db_dir = os.path.join(root_dir, '.') queries_dir = os.path.join(root_dir, '.') if not os.path.exists(root_dir) or not(db_dir):", "= os.path.join(root_dir, '.') if not os.path.exists(root_dir) or not(db_dir): raise FileNotFoundError(\"root_dir : {}, db_dir", "files in which list of image files are #structFile = join(struct_dir, 'pitts30k_test.mat') #structFile", "os.path.join(root_dir, '.') queries_dir = os.path.join(root_dir, '.') if not os.path.exists(root_dir) or not(db_dir): raise FileNotFoundError(\"root_dir", "os.path.join(struct_dir, 'dg_seoul_test.mat') #x, y, coord, radius = 327934.67464998, 4153535.06119226, 'utm', 25 x, y,", "radius = 327934.67464998, 4153535.06119226, 'utm', 25 x, y, coord, radius = 37.511634, 127.061298,", "are #structFile = join(struct_dir, 'pitts30k_test.mat') #structFile = os.path.join(struct_dir, 'dg_daejeon_test.mat') structFile = os.path.join(struct_dir, 'dg_seoul_test.mat')", "'dg_daejeon_test.mat') structFile = os.path.join(struct_dir, 'dg_seoul_test.mat') #x, y, coord, radius = 327934.67464998, 4153535.06119226, 'utm',", "327934.67464998, 4153535.06119226, 'utm', 25 x, y, coord, radius = 37.511634, 127.061298, 'latlon', 25", "os.path.join(root_dir, '.') if not os.path.exists(root_dir) or not(db_dir): raise FileNotFoundError(\"root_dir : {}, db_dir :", "'datasets') # For mat files in which list of image files are #structFile", "= os.path.join(struct_dir, 'dg_seoul_test.mat') #x, y, coord, radius = 327934.67464998, 4153535.06119226, 'utm', 25 x,", "os root_dir = './data_vps/custom_dataset/dataset_seoul' db_dir = os.path.join(root_dir, '.') queries_dir = os.path.join(root_dir, '.') if", "'./data_vps/custom_dataset/dataset_seoul' db_dir = os.path.join(root_dir, '.') queries_dir = os.path.join(root_dir, '.') if not os.path.exists(root_dir) or", "which list of image files are #structFile = join(struct_dir, 'pitts30k_test.mat') #structFile = os.path.join(struct_dir,", "= 327934.67464998, 4153535.06119226, 'utm', 25 x, y, coord, radius = 37.511634, 127.061298, 'latlon',", "y, coord, radius = 327934.67464998, 4153535.06119226, 'utm', 25 x, y, coord, radius =", "= join(struct_dir, 'pitts30k_test.mat') #structFile = os.path.join(struct_dir, 'dg_daejeon_test.mat') structFile = os.path.join(struct_dir, 'dg_seoul_test.mat') #x, y,", "db_dir)) struct_dir = os.path.join(root_dir, 'datasets') # For mat files in which list of", "# For mat files in which list of image files are #structFile =", "not os.path.exists(root_dir) or not(db_dir): raise FileNotFoundError(\"root_dir : {}, db_dir : {}\".format(root_dir, db_dir)) struct_dir", "join(struct_dir, 'pitts30k_test.mat') #structFile = os.path.join(struct_dir, 'dg_daejeon_test.mat') structFile = os.path.join(struct_dir, 'dg_seoul_test.mat') #x, y, coord,", "#structFile = os.path.join(struct_dir, 'dg_daejeon_test.mat') structFile = os.path.join(struct_dir, 'dg_seoul_test.mat') #x, y, coord, radius =", "os.path.join(struct_dir, 'dg_daejeon_test.mat') structFile = os.path.join(struct_dir, 'dg_seoul_test.mat') #x, y, coord, radius = 327934.67464998, 4153535.06119226,", "os.path.exists(root_dir) or not(db_dir): raise FileNotFoundError(\"root_dir : {}, db_dir : {}\".format(root_dir, db_dir)) struct_dir =", "'dg_seoul_test.mat') #x, y, coord, radius = 327934.67464998, 4153535.06119226, 'utm', 25 x, y, coord,", "{}, db_dir : {}\".format(root_dir, db_dir)) struct_dir = os.path.join(root_dir, 'datasets') # For mat files", "<reponame>deepguider/RoadGPS import os root_dir = './data_vps/custom_dataset/dataset_seoul' db_dir = os.path.join(root_dir, '.') queries_dir = os.path.join(root_dir,", "coord, radius = 327934.67464998, 4153535.06119226, 'utm', 25 x, y, coord, radius = 37.511634,", "if not os.path.exists(root_dir) or not(db_dir): raise FileNotFoundError(\"root_dir : {}, db_dir : {}\".format(root_dir, db_dir))", "image files are #structFile = join(struct_dir, 'pitts30k_test.mat') #structFile = os.path.join(struct_dir, 'dg_daejeon_test.mat') structFile =", "= os.path.join(struct_dir, 'dg_daejeon_test.mat') structFile = os.path.join(struct_dir, 'dg_seoul_test.mat') #x, y, coord, radius = 327934.67464998,", "= './data_vps/custom_dataset/dataset_seoul' db_dir = os.path.join(root_dir, '.') queries_dir = os.path.join(root_dir, '.') if not os.path.exists(root_dir)", "files are #structFile = join(struct_dir, 'pitts30k_test.mat') #structFile = os.path.join(struct_dir, 'dg_daejeon_test.mat') structFile = os.path.join(struct_dir,", "of image files are #structFile = join(struct_dir, 'pitts30k_test.mat') #structFile = os.path.join(struct_dir, 'dg_daejeon_test.mat') structFile", "'pitts30k_test.mat') #structFile = os.path.join(struct_dir, 'dg_daejeon_test.mat') structFile = os.path.join(struct_dir, 'dg_seoul_test.mat') #x, y, coord, radius", "#x, y, coord, radius = 327934.67464998, 4153535.06119226, 'utm', 25 x, y, coord, radius", "= os.path.join(root_dir, '.') queries_dir = os.path.join(root_dir, '.') if not os.path.exists(root_dir) or not(db_dir): raise", "root_dir = './data_vps/custom_dataset/dataset_seoul' db_dir = os.path.join(root_dir, '.') queries_dir = os.path.join(root_dir, '.') if not", "FileNotFoundError(\"root_dir : {}, db_dir : {}\".format(root_dir, db_dir)) struct_dir = os.path.join(root_dir, 'datasets') # For", "= os.path.join(root_dir, 'datasets') # For mat files in which list of image files", "queries_dir = os.path.join(root_dir, '.') if not os.path.exists(root_dir) or not(db_dir): raise FileNotFoundError(\"root_dir : {},", "list of image files are #structFile = join(struct_dir, 'pitts30k_test.mat') #structFile = os.path.join(struct_dir, 'dg_daejeon_test.mat')", "'.') if not os.path.exists(root_dir) or not(db_dir): raise FileNotFoundError(\"root_dir : {}, db_dir : {}\".format(root_dir,", "#structFile = join(struct_dir, 'pitts30k_test.mat') #structFile = os.path.join(struct_dir, 'dg_daejeon_test.mat') structFile = os.path.join(struct_dir, 'dg_seoul_test.mat') #x,", "For mat files in which list of image files are #structFile = join(struct_dir,", "'.') queries_dir = os.path.join(root_dir, '.') if not os.path.exists(root_dir) or not(db_dir): raise FileNotFoundError(\"root_dir :", "raise FileNotFoundError(\"root_dir : {}, db_dir : {}\".format(root_dir, db_dir)) struct_dir = os.path.join(root_dir, 'datasets') #", "or not(db_dir): raise FileNotFoundError(\"root_dir : {}, db_dir : {}\".format(root_dir, db_dir)) struct_dir = os.path.join(root_dir,", "{}\".format(root_dir, db_dir)) struct_dir = os.path.join(root_dir, 'datasets') # For mat files in which list", ": {}, db_dir : {}\".format(root_dir, db_dir)) struct_dir = os.path.join(root_dir, 'datasets') # For mat", ": {}\".format(root_dir, db_dir)) struct_dir = os.path.join(root_dir, 'datasets') # For mat files in which", "in which list of image files are #structFile = join(struct_dir, 'pitts30k_test.mat') #structFile =", "import os root_dir = './data_vps/custom_dataset/dataset_seoul' db_dir = os.path.join(root_dir, '.') queries_dir = os.path.join(root_dir, '.')", "os.path.join(root_dir, 'datasets') # For mat files in which list of image files are", "db_dir : {}\".format(root_dir, db_dir)) struct_dir = os.path.join(root_dir, 'datasets') # For mat files in", "mat files in which list of image files are #structFile = join(struct_dir, 'pitts30k_test.mat')", "struct_dir = os.path.join(root_dir, 'datasets') # For mat files in which list of image" ]
[ "Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR /", "import config, Csv # Build paths inside the project like this: BASE_DIR /", "- unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret", "project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')", "'UTC' USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images)", "MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') # Default primary key field type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD", "WARNING: don't run with debug turned on in production! # TODO: Uncomment the", "https://docs.djangoproject.com/en/4.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True", "'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'farmblr.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates',", "'farmblr.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME':", "https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, {", "settings for farmblr project. Generated by 'django-admin startproject' using Django 4.0. For more", "# SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on", "the secret key used in production secret! # TODO: Make secret key secret", "# EMAIL_PASSWORD = EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') # os.environ['password_key'] suggested # EMAIL_MAIL_SUBJECT = config('EMAIL_MAIL_SUBJECT')", "'templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ #", "# TODO: Uncomment the below 2 and delete defaults (for production) # DEBUG", "\"static\", ] # User uploaded files MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')", "EMAIL_SERVER = EMAIL_HOST = config('EMAIL_HOST') # EMAIL_PORT = config('EMAIL_PORT', cast=int) # EMAIL_ADDRESS =", "DEBUG = config('DEBUG', default=True, cast=bool) # # ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv()) DEBUG =", "from pathlib import Path from decouple import config, Csv # Build paths inside", "Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [", "'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC'", "4.0. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list", "True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes',", "= EMAIL_HOST_USER = config('EMAIL_HOST_USER') # EMAIL_FROM_ADDRESS = config('EMAIL_HOST_USER') # EMAIL_PASSWORD = EMAIL_HOST_PASSWORD =", "EMAIL_HOST = config('EMAIL_HOST') # EMAIL_PORT = config('EMAIL_PORT', cast=int) # EMAIL_ADDRESS = EMAIL_HOST_USER =", "on in production! # TODO: Uncomment the below 2 and delete defaults (for", "{ 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, {", "/ \"static\", ] # User uploaded files MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,", "config('EMAIL_HOST_USER') # EMAIL_FROM_ADDRESS = config('EMAIL_HOST_USER') # EMAIL_PASSWORD = EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') # os.environ['password_key']", "Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'web', 'blog',", "= Path(__file__).resolve().parent.parent TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') # Quick-start development settings - unsuitable for", "True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_URL", "# EMAIL_ADDRESS = EMAIL_HOST_USER = config('EMAIL_HOST_USER') # EMAIL_FROM_ADDRESS = config('EMAIL_HOST_USER') # EMAIL_PASSWORD =", "by 'django-admin startproject' using Django 4.0. For more information on this file, see", "[ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'farmblr.wsgi.application' #", "key secret SECRET_KEY = 'django-insecure-xyjd9zz!%+e^k9emeu8--hvpp1zqv01e_85eis(dux3li8t2!$' # SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't", "EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') # os.environ['password_key'] suggested # EMAIL_MAIL_SUBJECT = config('EMAIL_MAIL_SUBJECT') # EMAIL_MAIL_HTML =", "# SECURITY WARNING: keep the secret key used in production secret! # TODO:", "keep the secret key used in production secret! # TODO: Make secret key", "'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS", "= os.path.join(BASE_DIR, 'media/') # Default primary key field type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD =", "True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_URL = 'static/' STATIC_ROOT", "SECURITY WARNING: keep the secret key used in production secret! # TODO: Make", "ROOT_URLCONF = 'farmblr.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True,", "= config('EMAIL_HOST') # EMAIL_PORT = config('EMAIL_PORT', cast=int) # EMAIL_ADDRESS = EMAIL_HOST_USER = config('EMAIL_HOST_USER')", "TODO: Uncomment the below 2 and delete defaults (for production) # DEBUG =", "USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) #", "cast=bool) # EMAIL_ACTIVE_FIELD = config('EMAIL_ACTIVE_FIELD') # EMAIL_SERVER = EMAIL_HOST = config('EMAIL_HOST') # EMAIL_PORT", "config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! #", "'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS =", "For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ \"\"\" import", "= config('ALLOWED_HOSTS', cast=Csv()) DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS", "= os.path.join(BASE_DIR, 'templates') # Quick-start development settings - unsuitable for production # See", "{ 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE", "# os.environ['password_key'] suggested # EMAIL_MAIL_SUBJECT = config('EMAIL_MAIL_SUBJECT') # EMAIL_MAIL_HTML = config('EMAIL_MAIL_HTML') # EMAIL_PAGE_TEMPLATE", "'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.0/topics/i18n/ LANGUAGE_CODE =", "production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in", "['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',", "= EMAIL_HOST = config('EMAIL_HOST') # EMAIL_PORT = config('EMAIL_PORT', cast=int) # EMAIL_ADDRESS = EMAIL_HOST_USER", "config('EMAIL_MAIL_HTML') # EMAIL_PAGE_TEMPLATE = config('EMAIL_PAGE_TEMPLATE') # EMAIL_PAGE_DOMAIN = config('EMAIL_PAGE_DOMAIN') # DEFAULT_FROM_EMAIL = config('EMAIL_FROM_ADDRESS')", "# TODO: Make secret key secret SECRET_KEY = 'django-insecure-xyjd9zz!%+e^k9emeu8--hvpp1zqv01e_85eis(dux3li8t2!$' # SECRET_KEY = config('SECRET_KEY')", "EMAIL_ACTIVE_FIELD = config('EMAIL_ACTIVE_FIELD') # EMAIL_SERVER = EMAIL_HOST = config('EMAIL_HOST') # EMAIL_PORT = config('EMAIL_PORT',", "# EMAIL_PORT = config('EMAIL_PORT', cast=int) # EMAIL_ADDRESS = EMAIL_HOST_USER = config('EMAIL_HOST_USER') # EMAIL_FROM_ADDRESS", "EMAIL_MAIL_SUBJECT = config('EMAIL_MAIL_SUBJECT') # EMAIL_MAIL_HTML = config('EMAIL_MAIL_HTML') # EMAIL_PAGE_TEMPLATE = config('EMAIL_PAGE_TEMPLATE') # EMAIL_PAGE_DOMAIN", "= EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') # os.environ['password_key'] suggested # EMAIL_MAIL_SUBJECT = config('EMAIL_MAIL_SUBJECT') # EMAIL_MAIL_HTML", "'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.0/topics/i18n/ LANGUAGE_CODE", "more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings", "configuration # EMAIL_BACKEND = config('EMAIL_BACKEND') # EMAIL_USE_TLS = config('EMAIL_USE_TLS', cast=bool) # EMAIL_ACTIVE_FIELD =", "}, ] # Internationalization # https://docs.djangoproject.com/en/4.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N", "Uncomment the below 2 and delete defaults (for production) # DEBUG = config('DEBUG',", "config('ALLOWED_HOSTS', cast=Csv()) DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS =", "[TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], },", "settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ \"\"\" import os from pathlib import Path", "Django settings for farmblr project. Generated by 'django-admin startproject' using Django 4.0. For", "BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') # Quick-start development settings - unsuitable", "TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') # Quick-start development settings - unsuitable for production #", "full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ \"\"\" import os from", "TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True # Static files (CSS,", "EMAIL_PORT = config('EMAIL_PORT', cast=int) # EMAIL_ADDRESS = EMAIL_HOST_USER = config('EMAIL_HOST_USER') # EMAIL_FROM_ADDRESS =", "EMAIL_FROM_ADDRESS = config('EMAIL_HOST_USER') # EMAIL_PASSWORD = EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') # os.environ['password_key'] suggested #", "'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth',", "list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ \"\"\" import os from pathlib", "# Internationalization # https://docs.djangoproject.com/en/4.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True", "default=True, cast=bool) # # ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv()) DEBUG = True ALLOWED_HOSTS =", "DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin',", "and delete defaults (for production) # DEBUG = config('DEBUG', default=True, cast=bool) # #", "their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ \"\"\" import os from pathlib import Path from decouple", "# DEBUG = config('DEBUG', default=True, cast=bool) # # ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv()) DEBUG", "# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', },", "for farmblr project. Generated by 'django-admin startproject' using Django 4.0. For more information", "/ 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ {", "} } # Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',", "production secret! # TODO: Make secret key secret SECRET_KEY = 'django-insecure-xyjd9zz!%+e^k9emeu8--hvpp1zqv01e_85eis(dux3li8t2!$' # SECRET_KEY", "BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') # Quick-start development", "Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING:", "inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR =", "cast=Csv()) DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [", "BASE_DIR / \"static\", ] # User uploaded files MEDIA_URL = '/media/' MEDIA_ROOT =", "run with debug turned on in production! # TODO: Uncomment the below 2", "# https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ BASE_DIR", "like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') #", "EMAIL_PASSWORD = EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') # os.environ['password_key'] suggested # EMAIL_MAIL_SUBJECT = config('EMAIL_MAIL_SUBJECT') #", "decouple import config, Csv # Build paths inside the project like this: BASE_DIR", "defaults (for production) # DEBUG = config('DEBUG', default=True, cast=bool) # # ALLOWED_HOSTS =", "pathlib import Path from decouple import config, Csv # Build paths inside the", "definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'web', 'blog', 'accounts',", "}, ] WSGI_APPLICATION = 'farmblr.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default':", "Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR,", "secret key used in production secret! # TODO: Make secret key secret SECRET_KEY", "'accounts', 'products' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',", "\"\"\" Django settings for farmblr project. Generated by 'django-admin startproject' using Django 4.0.", "EMAIL_BACKEND = config('EMAIL_BACKEND') # EMAIL_USE_TLS = config('EMAIL_USE_TLS', cast=bool) # EMAIL_ACTIVE_FIELD = config('EMAIL_ACTIVE_FIELD') #", "] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF", "'blog', 'accounts', 'products' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',", "and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ \"\"\" import os from pathlib import Path from", "[ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', },", "'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'farmblr.urls' TEMPLATES = [ { 'BACKEND':", "= config('EMAIL_BACKEND') # EMAIL_USE_TLS = config('EMAIL_USE_TLS', cast=bool) # EMAIL_ACTIVE_FIELD = config('EMAIL_ACTIVE_FIELD') # EMAIL_SERVER", "debug turned on in production! # TODO: Uncomment the below 2 and delete", "# Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, {", "'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'farmblr.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS':", "used in production secret! # TODO: Make secret key secret SECRET_KEY = 'django-insecure-xyjd9zz!%+e^k9emeu8--hvpp1zqv01e_85eis(dux3li8t2!$'", "'/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') # Default primary key field type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field", "farmblr project. Generated by 'django-admin startproject' using Django 4.0. For more information on", "SECURITY WARNING: don't run with debug turned on in production! # TODO: Uncomment", "MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') # Default primary key field type", "TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors':", "}, }, ] WSGI_APPLICATION = 'farmblr.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = {", "'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ BASE_DIR / \"static\", ] #", "of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ \"\"\" import os from pathlib import", "'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] #", "(CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS", "STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ BASE_DIR / \"static\", ] # User", "[ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'web', 'blog', 'accounts', 'products' ] MIDDLEWARE", "turned on in production! # TODO: Uncomment the below 2 and delete defaults", "[ BASE_DIR / \"static\", ] # User uploaded files MEDIA_URL = '/media/' MEDIA_ROOT", "https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ \"\"\"", "the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ \"\"\" import os", "import Path from decouple import config, Csv # Build paths inside the project", "Make secret key secret SECRET_KEY = 'django-insecure-xyjd9zz!%+e^k9emeu8--hvpp1zqv01e_85eis(dux3li8t2!$' # SECRET_KEY = config('SECRET_KEY') # SECURITY", "}, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.0/topics/i18n/ LANGUAGE_CODE = 'en-us'", "the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR = os.path.join(BASE_DIR,", "SECRET_KEY = 'django-insecure-xyjd9zz!%+e^k9emeu8--hvpp1zqv01e_85eis(dux3li8t2!$' # SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with", "'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'farmblr.urls' TEMPLATES =", "{ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password", "INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'web', 'blog', 'accounts', 'products'", "= config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production!", "using Django 4.0. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the", "secret key secret SECRET_KEY = 'django-insecure-xyjd9zz!%+e^k9emeu8--hvpp1zqv01e_85eis(dux3li8t2!$' # SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING:", "] # Internationalization # https://docs.djangoproject.com/en/4.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N =", "# https://docs.djangoproject.com/en/4.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ =", "'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'farmblr.wsgi.application'", "}, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization #", "project. Generated by 'django-admin startproject' using Django 4.0. For more information on this", "= [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'web', 'blog', 'accounts', 'products' ]", "production! # TODO: Uncomment the below 2 and delete defaults (for production) #", "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'web',", "cast=bool) # # ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv()) DEBUG = True ALLOWED_HOSTS = ['*']", "User uploaded files MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') # Default primary", "Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME':", "WARNING: keep the secret key used in production secret! # TODO: Make secret", "import os from pathlib import Path from decouple import config, Csv # Build", "], }, }, ] WSGI_APPLICATION = 'farmblr.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES =", "= { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } #", "'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'farmblr.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases", "2 and delete defaults (for production) # DEBUG = config('DEBUG', default=True, cast=bool) #", "= [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [", "paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR", "} # Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', },", "startproject' using Django 4.0. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For", "type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # Email configuration # EMAIL_BACKEND = config('EMAIL_BACKEND')", "= ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages',", "information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and", "# EMAIL_ACTIVE_FIELD = config('EMAIL_ACTIVE_FIELD') # EMAIL_SERVER = EMAIL_HOST = config('EMAIL_HOST') # EMAIL_PORT =", "settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the", "] ROOT_URLCONF = 'farmblr.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS':", "primary key field type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # Email configuration #", "os.environ['password_key'] suggested # EMAIL_MAIL_SUBJECT = config('EMAIL_MAIL_SUBJECT') # EMAIL_MAIL_HTML = config('EMAIL_MAIL_HTML') # EMAIL_PAGE_TEMPLATE =", "'django.contrib.staticfiles', 'web', 'blog', 'accounts', 'products' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware',", "[ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug',", "in production! # TODO: Uncomment the below 2 and delete defaults (for production)", "LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True #", "# EMAIL_MAIL_SUBJECT = config('EMAIL_MAIL_SUBJECT') # EMAIL_MAIL_HTML = config('EMAIL_MAIL_HTML') # EMAIL_PAGE_TEMPLATE = config('EMAIL_PAGE_TEMPLATE') #", "on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their", "# EMAIL_MAIL_HTML = config('EMAIL_MAIL_HTML') # EMAIL_PAGE_TEMPLATE = config('EMAIL_PAGE_TEMPLATE') # EMAIL_PAGE_DOMAIN = config('EMAIL_PAGE_DOMAIN') #", "'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },", "# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production", "= config('DEBUG', default=True, cast=bool) # # ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv()) DEBUG = True", "JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS =", "'products' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]", "ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv()) DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition", "unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key", "config, Csv # Build paths inside the project like this: BASE_DIR / 'subdir'.", "}, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', },", "https://docs.djangoproject.com/en/4.0/ref/settings/ \"\"\" import os from pathlib import Path from decouple import config, Csv", "'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'farmblr.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR],", "config('DEBUG', default=True, cast=bool) # # ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv()) DEBUG = True ALLOWED_HOSTS", "'staticfiles') STATICFILES_DIRS = [ BASE_DIR / \"static\", ] # User uploaded files MEDIA_URL", "'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE =", "(for production) # DEBUG = config('DEBUG', default=True, cast=bool) # # ALLOWED_HOSTS = config('ALLOWED_HOSTS',", "BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [", "'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ],", "# Email configuration # EMAIL_BACKEND = config('EMAIL_BACKEND') # EMAIL_USE_TLS = config('EMAIL_USE_TLS', cast=bool) #", "values, see https://docs.djangoproject.com/en/4.0/ref/settings/ \"\"\" import os from pathlib import Path from decouple import", "see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/", "this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values,", "from decouple import config, Csv # Build paths inside the project like this:", "# Default primary key field type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # Email", "secret! # TODO: Make secret key secret SECRET_KEY = 'django-insecure-xyjd9zz!%+e^k9emeu8--hvpp1zqv01e_85eis(dux3li8t2!$' # SECRET_KEY =", "= True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth',", "config('EMAIL_HOST_PASSWORD') # os.environ['password_key'] suggested # EMAIL_MAIL_SUBJECT = config('EMAIL_MAIL_SUBJECT') # EMAIL_MAIL_HTML = config('EMAIL_MAIL_HTML') #", "'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages',", "= [ BASE_DIR / \"static\", ] # User uploaded files MEDIA_URL = '/media/'", "key field type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # Email configuration # EMAIL_BACKEND", "os.path.join(BASE_DIR, 'media/') # Default primary key field type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'", "# # ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv()) DEBUG = True ALLOWED_HOSTS = ['*'] #", "'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'web', 'blog', 'accounts', 'products' ] MIDDLEWARE = [", "# https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3',", "'media/') # Default primary key field type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' #", "For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of", "'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'web', 'blog', 'accounts', 'products' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware',", "= True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_URL = 'static/'", "= config('EMAIL_USE_TLS', cast=bool) # EMAIL_ACTIVE_FIELD = config('EMAIL_ACTIVE_FIELD') # EMAIL_SERVER = EMAIL_HOST = config('EMAIL_HOST')", "# ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv()) DEBUG = True ALLOWED_HOSTS = ['*'] # Application", "production) # DEBUG = config('DEBUG', default=True, cast=bool) # # ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv())", "Csv # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR", "for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used", "https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # Email configuration # EMAIL_BACKEND = config('EMAIL_BACKEND') # EMAIL_USE_TLS", "{ 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ]", "with debug turned on in production! # TODO: Uncomment the below 2 and", "= config('EMAIL_ACTIVE_FIELD') # EMAIL_SERVER = EMAIL_HOST = config('EMAIL_HOST') # EMAIL_PORT = config('EMAIL_PORT', cast=int)", "# Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR =", "os from pathlib import Path from decouple import config, Csv # Build paths", "config('EMAIL_HOST') # EMAIL_PORT = config('EMAIL_PORT', cast=int) # EMAIL_ADDRESS = EMAIL_HOST_USER = config('EMAIL_HOST_USER') #", "config('EMAIL_HOST_USER') # EMAIL_PASSWORD = EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') # os.environ['password_key'] suggested # EMAIL_MAIL_SUBJECT =", "file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see", "'django.contrib.messages', 'django.contrib.staticfiles', 'web', 'blog', 'accounts', 'products' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware',", "{ 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION =", "Django 4.0. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full", "'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME':", "= [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'farmblr.urls'", "] # User uploaded files MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') #", "Email configuration # EMAIL_BACKEND = config('EMAIL_BACKEND') # EMAIL_USE_TLS = config('EMAIL_USE_TLS', cast=bool) # EMAIL_ACTIVE_FIELD", "# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # Email configuration # EMAIL_BACKEND = config('EMAIL_BACKEND') #", "uploaded files MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') # Default primary key", "# EMAIL_SERVER = EMAIL_HOST = config('EMAIL_HOST') # EMAIL_PORT = config('EMAIL_PORT', cast=int) # EMAIL_ADDRESS", "= config('EMAIL_HOST_PASSWORD') # os.environ['password_key'] suggested # EMAIL_MAIL_SUBJECT = config('EMAIL_MAIL_SUBJECT') # EMAIL_MAIL_HTML = config('EMAIL_MAIL_HTML')", "'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization", "delete defaults (for production) # DEBUG = config('DEBUG', default=True, cast=bool) # # ALLOWED_HOSTS", "ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions',", "config('EMAIL_PORT', cast=int) # EMAIL_ADDRESS = EMAIL_HOST_USER = config('EMAIL_HOST_USER') # EMAIL_FROM_ADDRESS = config('EMAIL_HOST_USER') #", "'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators", "# EMAIL_USE_TLS = config('EMAIL_USE_TLS', cast=bool) # EMAIL_ACTIVE_FIELD = config('EMAIL_ACTIVE_FIELD') # EMAIL_SERVER = EMAIL_HOST", "Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent", "# User uploaded files MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') # Default", "See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret!", "# Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR", "field type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # Email configuration # EMAIL_BACKEND =", "'web', 'blog', 'accounts', 'products' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware',", "# EMAIL_FROM_ADDRESS = config('EMAIL_HOST_USER') # EMAIL_PASSWORD = EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') # os.environ['password_key'] suggested", "SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in", "'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'farmblr.urls' TEMPLATES = [ {", "STATICFILES_DIRS = [ BASE_DIR / \"static\", ] # User uploaded files MEDIA_URL =", "os.path.join(BASE_DIR, 'templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/", "this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') # Quick-start", "= config('EMAIL_HOST_USER') # EMAIL_FROM_ADDRESS = config('EMAIL_HOST_USER') # EMAIL_PASSWORD = EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') #", "'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION", "USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_URL =", "= [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',", "suggested # EMAIL_MAIL_SUBJECT = config('EMAIL_MAIL_SUBJECT') # EMAIL_MAIL_HTML = config('EMAIL_MAIL_HTML') # EMAIL_PAGE_TEMPLATE = config('EMAIL_PAGE_TEMPLATE')", "config('EMAIL_BACKEND') # EMAIL_USE_TLS = config('EMAIL_USE_TLS', cast=bool) # EMAIL_ACTIVE_FIELD = config('EMAIL_ACTIVE_FIELD') # EMAIL_SERVER =", "EMAIL_USE_TLS = config('EMAIL_USE_TLS', cast=bool) # EMAIL_ACTIVE_FIELD = config('EMAIL_ACTIVE_FIELD') # EMAIL_SERVER = EMAIL_HOST =", "cast=int) # EMAIL_ADDRESS = EMAIL_HOST_USER = config('EMAIL_HOST_USER') # EMAIL_FROM_ADDRESS = config('EMAIL_HOST_USER') # EMAIL_PASSWORD", "= os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ BASE_DIR / \"static\", ] # User uploaded", "'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation", "'django-insecure-xyjd9zz!%+e^k9emeu8--hvpp1zqv01e_85eis(dux3li8t2!$' # SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned", "'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True # Static files", "STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ BASE_DIR / \"static\",", "'django-admin startproject' using Django 4.0. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/", "https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }", "= config('EMAIL_MAIL_HTML') # EMAIL_PAGE_TEMPLATE = config('EMAIL_PAGE_TEMPLATE') # EMAIL_PAGE_DOMAIN = config('EMAIL_PAGE_DOMAIN') # DEFAULT_FROM_EMAIL =", "] WSGI_APPLICATION = 'farmblr.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': {", "key used in production secret! # TODO: Make secret key secret SECRET_KEY =", "{ 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.0/topics/i18n/", "config('EMAIL_MAIL_SUBJECT') # EMAIL_MAIL_HTML = config('EMAIL_MAIL_HTML') # EMAIL_PAGE_TEMPLATE = config('EMAIL_PAGE_TEMPLATE') # EMAIL_PAGE_DOMAIN = config('EMAIL_PAGE_DOMAIN')", "https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! #", "= config('EMAIL_PORT', cast=int) # EMAIL_ADDRESS = EMAIL_HOST_USER = config('EMAIL_HOST_USER') # EMAIL_FROM_ADDRESS = config('EMAIL_HOST_USER')", "'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') # Quick-start development settings -", "# Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY", "os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ BASE_DIR / \"static\", ] # User uploaded files", "= 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ BASE_DIR / \"static\", ]", "# EMAIL_BACKEND = config('EMAIL_BACKEND') # EMAIL_USE_TLS = config('EMAIL_USE_TLS', cast=bool) # EMAIL_ACTIVE_FIELD = config('EMAIL_ACTIVE_FIELD')", "= 'django.db.models.BigAutoField' # Email configuration # EMAIL_BACKEND = config('EMAIL_BACKEND') # EMAIL_USE_TLS = config('EMAIL_USE_TLS',", "files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')", "/ 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') # Quick-start development settings", "the below 2 and delete defaults (for production) # DEBUG = config('DEBUG', default=True,", "# Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_URL = 'static/' STATIC_ROOT =", "= 'django-insecure-xyjd9zz!%+e^k9emeu8--hvpp1zqv01e_85eis(dux3li8t2!$' # SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug", "config('EMAIL_ACTIVE_FIELD') # EMAIL_SERVER = EMAIL_HOST = config('EMAIL_HOST') # EMAIL_PORT = config('EMAIL_PORT', cast=int) #", "EMAIL_ADDRESS = EMAIL_HOST_USER = config('EMAIL_HOST_USER') # EMAIL_FROM_ADDRESS = config('EMAIL_HOST_USER') # EMAIL_PASSWORD = EMAIL_HOST_PASSWORD", "'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'farmblr.wsgi.application' # Database #", "don't run with debug turned on in production! # TODO: Uncomment the below", "{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request',", "secret SECRET_KEY = 'django-insecure-xyjd9zz!%+e^k9emeu8--hvpp1zqv01e_85eis(dux3li8t2!$' # SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run", "Default primary key field type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # Email configuration", "below 2 and delete defaults (for production) # DEBUG = config('DEBUG', default=True, cast=bool)", "EMAIL_HOST_USER = config('EMAIL_HOST_USER') # EMAIL_FROM_ADDRESS = config('EMAIL_HOST_USER') # EMAIL_PASSWORD = EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD')", "'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',", "'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'web', 'blog', 'accounts', 'products' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware',", "validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',", "# SECURITY WARNING: don't run with debug turned on in production! # TODO:", "TODO: Make secret key secret SECRET_KEY = 'django-insecure-xyjd9zz!%+e^k9emeu8--hvpp1zqv01e_85eis(dux3li8t2!$' # SECRET_KEY = config('SECRET_KEY') #", "Path from decouple import config, Csv # Build paths inside the project like", "MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF =", "= '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') # Default primary key field type #", "= config('EMAIL_MAIL_SUBJECT') # EMAIL_MAIL_HTML = config('EMAIL_MAIL_HTML') # EMAIL_PAGE_TEMPLATE = config('EMAIL_PAGE_TEMPLATE') # EMAIL_PAGE_DOMAIN =", "'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'farmblr.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES", "DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # Email configuration # EMAIL_BACKEND = config('EMAIL_BACKEND') # EMAIL_USE_TLS =", "development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep", "True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]", "= 'UTC' USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript,", "{ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation #", "Path(__file__).resolve().parent.parent TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') # Quick-start development settings - unsuitable for production", "in production secret! # TODO: Make secret key secret SECRET_KEY = 'django-insecure-xyjd9zz!%+e^k9emeu8--hvpp1zqv01e_85eis(dux3li8t2!$' #", "config('EMAIL_USE_TLS', cast=bool) # EMAIL_ACTIVE_FIELD = config('EMAIL_ACTIVE_FIELD') # EMAIL_SERVER = EMAIL_HOST = config('EMAIL_HOST') #", "'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'farmblr.wsgi.application' # Database", "EMAIL_MAIL_HTML = config('EMAIL_MAIL_HTML') # EMAIL_PAGE_TEMPLATE = config('EMAIL_PAGE_TEMPLATE') # EMAIL_PAGE_DOMAIN = config('EMAIL_PAGE_DOMAIN') # DEFAULT_FROM_EMAIL", "= 'farmblr.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3',", "[ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'farmblr.urls' TEMPLATES", "\"\"\" import os from pathlib import Path from decouple import config, Csv #", "DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } }", "= 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True # Static", "'django.db.models.BigAutoField' # Email configuration # EMAIL_BACKEND = config('EMAIL_BACKEND') # EMAIL_USE_TLS = config('EMAIL_USE_TLS', cast=bool)", "see https://docs.djangoproject.com/en/4.0/ref/settings/ \"\"\" import os from pathlib import Path from decouple import config,", "Generated by 'django-admin startproject' using Django 4.0. For more information on this file,", "WSGI_APPLICATION = 'farmblr.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE':", "Internationalization # https://docs.djangoproject.com/en/4.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ", "AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME':", "https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ BASE_DIR /", "files MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') # Default primary key field", "'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME':", "'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'farmblr.urls' TEMPLATES = [", "= True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/", "'farmblr.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': {", "'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'web', 'blog', 'accounts', 'products' ] MIDDLEWARE =", "= config('EMAIL_HOST_USER') # EMAIL_PASSWORD = EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') # os.environ['password_key'] suggested # EMAIL_MAIL_SUBJECT", "= 'farmblr.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS':" ]
[ "STEPS = { \"810345672\": [\"X\", \"R'\", \"U\", \"R'\", \"D2\", \"R\", \"U'\", \"R'\", \"D2\",", "\"D'\", \"R\", \"U\", \"R'\", \"D\", \"R\", \"U'\", \"R'\", \"D'\", \"X\"] } @staticmethod def", "\"R\", \"U'\", \"R\", \"D2\", \"R'\", \"U\", \"R\", \"D2\", \"R2\", \"X\"], \"012743658\": [\"R2\", \"U\",", "\"R'\", \"F\", \"R2\", \"U'\", \"R'\", \"U'\", \"R\", \"U\", \"R'\", \"F'\"], \"230145678\": [\"R'\", \"U\",", "\"U'\", \"R'\", \"F\", \"R2\", \"U'\", \"R'\", \"U'\"], \"210745638\": [\"L\", \"U2\", \"L'\", \"U2\", \"L\",", "[\"L\", \"U'\", \"R\", \"U2\", \"L'\", \"U\", \"R'\", \"L\", \"U'\", \"R\", \"U2\", \"L'\", \"U\",", "\"D'\", \"R\", \"U'\", \"R\", \"U\", \"R'\", \"Y\", \"D\", \"R2\", \"Y\", \"R\", \"U'\", \"R'\"],", "\"U'\", \"R'\", \"F'\", \"R2\", \"U'\", \"R'\", \"U\", \"R'\", \"F\", \"R\", \"F\"], \"650143278\": [\"R2\",", "\"U2\", \"R'\", \"F\", \"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F'\", \"R2\", \"U'\"], \"852341670\": [\"R'\",", "\"R2\", \"Y'\", \"R'\", \"U\", \"R\"], \"832745016\": [\"R'\", \"U'\", \"R\", \"Y\", \"R2\", \"Y\", \"D\",", "\"L\", \"U\", \"L\", \"F\", \"L2\", \"U\"], \"210347658\": [\"R'\", \"U2\", \"R\", \"U2\", \"R'\", \"F\",", "self.move(s, solution) return solution # Apply shortest and expect to be solvable after", "\"852341670\": [\"R'\", \"U\", \"R'\", \"Y\", \"U'\", \"R'\", \"F'\", \"R2\", \"U'\", \"R'\", \"U\", \"R'\",", "\"F'\"], \"872345610\": [\"L\", \"U'\", \"R\", \"U2\", \"L'\", \"U\", \"R'\", \"L\", \"U'\", \"R\", \"U2\",", "\"M'\", \"U2\", \"M2\", \"U2\", \"M'\", \"U2\"], \"832145670\": [\"F\", \"R\", \"U'\", \"R'\", \"U'\", \"R\",", "\"U\", \"R'\", \"Y\", \"D\", \"R2\", \"Y\", \"R\", \"U'\", \"R'\"], \"670145238\": [\"R\", \"U\", \"R'\",", "\"U2\", \"R\", \"U'\", \"L\", \"U'\"], \"618345072\": [\"X'\", \"R\", \"U'\", \"R'\", \"D\", \"R\", \"U\",", "\"F'\", \"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F\", \"R2\", \"U'\", \"R'\", \"U'\"], \"210745638\": [\"L\",", "\"U'\"], \"018347652\": [\"R\", \"U\", \"R'\", \"F'\", \"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F\", \"R2\",", "\"U\", \"R'\"], \"012547638\": [\"R\", \"U'\", \"R\", \"U\", \"R\", \"U\", \"R\", \"U'\", \"R'\", \"U'\",", "\"R'\", \"U\", \"R'\", \"F\", \"R\", \"U'\", \"F\"], \"032147658\": [\"M2\", \"U\", \"M2\", \"U\", \"M'\",", "'LU', 'U', 'RU', 'FLU', 'FU', 'FRU'] orientation = [] for cubie in cubies:", "cubie.replace('U', '')] return cube.search_by_colors('Y', *colors) def solution(self): solution = [] while True: for", "\"R'\", \"U\", \"L'\", \"U2\", \"R\", \"U'\", \"L\", \"U'\"], \"618345072\": [\"X'\", \"R\", \"U'\", \"R'\",", "\"D'\", \"R2\"], \"812743056\": [\"R2\", \"Y'\", \"D'\", \"R\", \"U'\", \"R\", \"U\", \"R'\", \"Y\", \"D\",", "\"U\", \"R'\", \"D'\", \"R\", \"U\", \"R'\", \"D\", \"R\", \"U'\", \"R'\", \"D'\", \"X\"] }", "\"L\", \"U'\", \"R\", \"U2\", \"L'\", \"U\", \"R'\", \"U\"], \"076345218\": [\"R'\", \"U\", \"L'\", \"U2\",", "\"U'\", \"R'\", \"U2\", \"R\", \"L\", \"U'\"], \"018347652\": [\"R\", \"U\", \"R'\", \"F'\", \"R\", \"U\",", "solution) orientation = PLLSolver.get_orientations(self.cube) if orientation in PLLSolver.STEPS: for s in PLLSolver.STEPS[orientation]: self.move(s,", "\"R\", \"U\", \"R'\", \"D\", \"R\", \"U'\", \"R'\", \"D'\", \"X\"] } @staticmethod def get_orientations(cube):", "\"U\", \"L'\", \"U2\", \"R\", \"U'\", \"R'\", \"U2\", \"R\", \"L\", \"U'\"], \"018347652\": [\"R\", \"U\",", "for cubie in cubies: o = PLLSolver.get_correct_cubie(cube, cubie) orientation.append(str(cubies.index(o))) return ''.join(orientation) def move(self,", "True: for _ in range(4): self.move('U', solution) for _ in range(4): self.move('Y', solution)", "\"R\", \"L\", \"U'\"], \"018347652\": [\"R\", \"U\", \"R'\", \"F'\", \"R\", \"U\", \"R'\", \"U'\", \"R'\",", "\"U'\", \"R'\", \"U\", \"R'\", \"Y\", \"D\", \"R2\"], \"012543876\": [\"R'\", \"U2\", \"R'\", \"Y\", \"U'\",", "for _ in range(4): self.move('Y', solution) orientation = PLLSolver.get_orientations(self.cube) if orientation in PLLSolver.STEPS:", "\"Y'\", \"R'\", \"U\", \"R\"], \"832745016\": [\"R'\", \"U'\", \"R\", \"Y\", \"R2\", \"Y\", \"D\", \"R'\",", "\"F\", \"R2\", \"U'\", \"R'\", \"U'\"], \"210745638\": [\"L\", \"U2\", \"L'\", \"U2\", \"L\", \"F'\", \"L'\",", "\"R'\", \"F'\", \"R2\", \"U'\"], \"852341670\": [\"R'\", \"U\", \"R'\", \"Y\", \"U'\", \"R'\", \"F'\", \"R2\",", "\"U2\", \"R'\", \"Y\", \"U'\", \"R'\", \"F'\", \"R2\", \"U'\", \"R'\", \"U\", \"R'\", \"F\", \"R\",", "\"R\", \"U\", \"R'\", \"D'\", \"R\", \"U\", \"R'\", \"D\", \"R\", \"U'\", \"R'\", \"D'\", \"X\"]", "\"R'\", \"D\", \"R\", \"U\", \"R'\", \"D'\", \"R\", \"U\", \"R'\", \"D\", \"R\", \"U'\", \"R'\",", "\"872345610\": [\"L\", \"U'\", \"R\", \"U2\", \"L'\", \"U\", \"R'\", \"L\", \"U'\", \"R\", \"U2\", \"L'\",", "\"R\", \"U\", \"R'\", \"F'\", \"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F\", \"R\", \"F'\"], \"872345610\":", "[\"R\", \"U\", \"R'\", \"F'\", \"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F\", \"R2\", \"U'\", \"R'\",", "\"U'\", \"R'\", \"D'\", \"X\"] } @staticmethod def get_orientations(cube): cubies = ['BLU', 'BU', 'BRU',", "\"L\", \"U'\"], \"018347652\": [\"R\", \"U\", \"R'\", \"F'\", \"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F\",", "\"R\", \"D2\", \"R'\", \"U\", \"R\", \"D2\", \"R2\", \"X\"], \"012743658\": [\"R2\", \"U\", \"R\", \"U\",", "from .. import Solver class PLLSolver(Solver): STEPS = { \"810345672\": [\"X\", \"R'\", \"U\",", "[\"X'\", \"R\", \"U'\", \"R'\", \"D\", \"R\", \"U\", \"R'\", \"D'\", \"R\", \"U\", \"R'\", \"D\",", "move(self, s, solution): self.cube.move(Move(s)) solution.append(s) @staticmethod def get_correct_cubie(cube, cubie): colors = [cube.cubies[c].facings[c].color for", "\"U'\", \"R'\", \"U\", \"R'\"], \"012547638\": [\"R\", \"U'\", \"R\", \"U\", \"R\", \"U\", \"R\", \"U'\",", "[\"R'\", \"U\", \"R'\", \"Y\", \"U'\", \"R'\", \"F'\", \"R2\", \"U'\", \"R'\", \"U\", \"R'\", \"F\",", "\"U'\", \"R\", \"U\", \"R\", \"U\", \"R\", \"U'\", \"R'\", \"U'\", \"R2\"], \"072543618\": [\"M2\", \"U\",", "\"670145238\": [\"R\", \"U\", \"R'\", \"Y'\", \"R2\", \"Y'\", \"D'\", \"R\", \"U'\", \"R'\", \"U\", \"R'\",", "solution # Apply shortest and expect to be solvable after that for s", "\"R'\", \"U\", \"R'\"], \"012547638\": [\"R\", \"U'\", \"R\", \"U\", \"R\", \"U\", \"R\", \"U'\", \"R'\",", "[\"M2\", \"U\", \"M2\", \"U2\", \"M2\", \"U\", \"M2\"], \"018543672\": [\"R\", \"U\", \"R'\", \"U'\", \"R'\",", "\"R\", \"U2\", \"L'\", \"U\", \"R'\", \"L\", \"U'\", \"R\", \"U2\", \"L'\", \"U\", \"R'\", \"U\"],", "\"R\", \"U'\", \"R'\"], \"670145238\": [\"R\", \"U\", \"R'\", \"Y'\", \"R2\", \"Y'\", \"D'\", \"R\", \"U'\",", "\"F\", \"R\", \"U'\", \"F\"], \"032147658\": [\"M2\", \"U\", \"M2\", \"U\", \"M'\", \"U2\", \"M2\", \"U2\",", "\"R\", \"U'\", \"R'\", \"D'\", \"X\"] } @staticmethod def get_orientations(cube): cubies = ['BLU', 'BU',", "\"R2\", \"U'\", \"R'\", \"U\", \"R'\", \"F\", \"R\", \"U'\", \"F\"], \"032147658\": [\"M2\", \"U\", \"M2\",", "\"R\", \"U'\", \"L\", \"U'\"], \"618345072\": [\"X'\", \"R\", \"U'\", \"R'\", \"D\", \"R\", \"U\", \"R'\",", "\"R\", \"F\"], \"650143278\": [\"R2\", \"Y\", \"D\", \"R'\", \"U\", \"R'\", \"U'\", \"R\", \"Y'\", \"D'\",", "\"R\", \"U\", \"R'\", \"Y\", \"D\", \"R2\", \"Y\", \"R\", \"U'\", \"R'\"], \"670145238\": [\"R\", \"U\",", "\"F\", \"R\", \"F\"], \"650143278\": [\"R2\", \"Y\", \"D\", \"R'\", \"U\", \"R'\", \"U'\", \"R\", \"Y'\",", "[\"R2\", \"Y\", \"D\", \"R'\", \"U\", \"R'\", \"U'\", \"R\", \"Y'\", \"D'\", \"R2\", \"Y'\", \"R'\",", "\"R'\", \"F'\", \"R2\", \"U'\", \"R'\", \"U\", \"R'\", \"F\", \"R\", \"U'\", \"F\"], \"032147658\": [\"M2\",", "solution) return solution # Apply shortest and expect to be solvable after that", "while True: for _ in range(4): self.move('U', solution) for _ in range(4): self.move('Y',", "\"F'\", \"R2\", \"U'\", \"R'\", \"U\", \"R'\", \"F\", \"R\", \"U'\", \"F\"], \"032147658\": [\"M2\", \"U\",", "[\"R2\", \"Y'\", \"D'\", \"R\", \"U'\", \"R\", \"U\", \"R'\", \"Y\", \"D\", \"R2\", \"Y\", \"R\",", "\"U'\", \"R'\", \"D\", \"R\", \"U\", \"R'\", \"D'\", \"R\", \"U\", \"R'\", \"D\", \"R\", \"U'\",", "\"U2\", \"R\", \"U'\", \"R'\", \"U2\", \"R\", \"L\", \"U'\"], \"018347652\": [\"R\", \"U\", \"R'\", \"F'\",", "\"L'\", \"U2\", \"R\", \"U'\", \"R'\", \"U2\", \"R\", \"L\", \"U'\"], \"018347652\": [\"R\", \"U\", \"R'\",", "\"R'\", \"U'\", \"R\", \"Y'\", \"D'\", \"R2\", \"Y'\", \"R'\", \"U\", \"R\"], \"832745016\": [\"R'\", \"U'\",", "\"R2\"], \"812743056\": [\"R2\", \"Y'\", \"D'\", \"R\", \"U'\", \"R\", \"U\", \"R'\", \"Y\", \"D\", \"R2\",", "\"Y\", \"D\", \"R2\"], \"012543876\": [\"R'\", \"U2\", \"R'\", \"Y\", \"U'\", \"R'\", \"F'\", \"R2\", \"U'\",", "\"R'\", \"F'\", \"R2\", \"U'\", \"R'\", \"U\", \"R'\", \"F\", \"R\", \"F\"], \"650143278\": [\"R2\", \"Y\",", "\"R'\", \"F\", \"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F'\", \"R2\", \"U'\"], \"852341670\": [\"R'\", \"U\",", "\"Y'\", \"D'\", \"R\", \"U'\", \"R'\", \"U\", \"R'\", \"Y\", \"D\", \"R2\"], \"012543876\": [\"R'\", \"U2\",", "solution.append(s) @staticmethod def get_correct_cubie(cube, cubie): colors = [cube.cubies[c].facings[c].color for c in cubie.replace('U', '')]", "\"R2\", \"U'\", \"R'\", \"U\", \"R'\", \"F\", \"R\", \"F\"], \"650143278\": [\"R2\", \"Y\", \"D\", \"R'\",", "\"U'\", \"R2\"], \"072543618\": [\"M2\", \"U\", \"M2\", \"U2\", \"M2\", \"U\", \"M2\"], \"018543672\": [\"R\", \"U\",", "\"Y\", \"U'\", \"R'\", \"F'\", \"R2\", \"U'\", \"R'\", \"U\", \"R'\", \"F\", \"R\", \"F\"], \"650143278\":", "\"D\", \"R'\", \"U\", \"R'\", \"U'\", \"R\", \"Y'\", \"D'\", \"R2\", \"Y'\", \"R'\", \"U\", \"R\"],", "\"R'\", \"U'\", \"R'\", \"U'\", \"R'\", \"U\", \"R'\"], \"012547638\": [\"R\", \"U'\", \"R\", \"U\", \"R\",", "\"U'\", \"L\", \"U\", \"L\", \"F\", \"L2\", \"U\"], \"210347658\": [\"R'\", \"U2\", \"R\", \"U2\", \"R'\",", "\"U\", \"R'\", \"L\", \"U'\", \"R\", \"U2\", \"L'\", \"U\", \"R'\", \"U\"], \"076345218\": [\"R'\", \"U\",", "\"R'\", \"U\", \"R\", \"D2\", \"R2\", \"X\"], \"012743658\": [\"R2\", \"U\", \"R\", \"U\", \"R'\", \"U'\",", "\"U\", \"R'\", \"Y\", \"U'\", \"R'\", \"F'\", \"R2\", \"U'\", \"R'\", \"U\", \"R'\", \"F\", \"R\",", "\"U\", \"R'\", \"D\", \"R\", \"U'\", \"R'\", \"D'\", \"X\"] } @staticmethod def get_orientations(cube): cubies", "import Solver class PLLSolver(Solver): STEPS = { \"810345672\": [\"X\", \"R'\", \"U\", \"R'\", \"D2\",", "\"U'\", \"F\"], \"032147658\": [\"M2\", \"U\", \"M2\", \"U\", \"M'\", \"U2\", \"M2\", \"U2\", \"M'\", \"U2\"],", "\"D2\", \"R'\", \"U\", \"R\", \"D2\", \"R2\", \"X\"], \"012743658\": [\"R2\", \"U\", \"R\", \"U\", \"R'\",", "\"U\", \"R'\", \"F\", \"R\", \"F\"], \"650143278\": [\"R2\", \"Y\", \"D\", \"R'\", \"U\", \"R'\", \"U'\",", "\"U'\", \"R'\", \"U'\", \"R\", \"U\", \"R'\", \"F'\", \"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F\",", "\"F'\", \"L'\", \"U'\", \"L\", \"U\", \"L\", \"F\", \"L2\", \"U\"], \"210347658\": [\"R'\", \"U2\", \"R\",", "\"U\", \"R'\", \"U'\", \"R'\", \"U'\", \"R'\", \"U\", \"R'\"], \"012547638\": [\"R\", \"U'\", \"R\", \"U\",", "\"U'\", \"R'\", \"F'\", \"R2\", \"U'\", \"R'\", \"U\", \"R'\", \"F\", \"R\", \"U'\", \"F\"], \"032147658\":", "\"U'\", \"R\", \"U\", \"R'\", \"F'\", \"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F\", \"R\", \"F'\"],", "\"R'\", \"D\", \"R\", \"U'\", \"R'\", \"D'\", \"X\"] } @staticmethod def get_orientations(cube): cubies =", "\"R\", \"U\", \"R\", \"U\", \"R\", \"U'\", \"R'\", \"U'\", \"R2\"], \"072543618\": [\"M2\", \"U\", \"M2\",", "[\"R\", \"U\", \"R'\", \"Y'\", \"R2\", \"Y'\", \"D'\", \"R\", \"U'\", \"R'\", \"U\", \"R'\", \"Y\",", "\"U'\", \"R'\", \"U'\", \"R2\"], \"072543618\": [\"M2\", \"U\", \"M2\", \"U2\", \"M2\", \"U\", \"M2\"], \"018543672\":", "'FLU', 'FU', 'FRU'] orientation = [] for cubie in cubies: o = PLLSolver.get_correct_cubie(cube,", "= [] for cubie in cubies: o = PLLSolver.get_correct_cubie(cube, cubie) orientation.append(str(cubies.index(o))) return ''.join(orientation)", "\"U2\", \"R\", \"U'\", \"L\", \"R'\", \"U\", \"L'\", \"U2\", \"R\", \"U'\", \"L\", \"U'\"], \"618345072\":", "\"R'\", \"Y'\", \"R2\", \"Y'\", \"D'\", \"R\", \"U'\", \"R'\", \"U\", \"R'\", \"Y\", \"D\", \"R2\"],", "\"R\", \"Y'\", \"D'\", \"R2\"], \"812743056\": [\"R2\", \"Y'\", \"D'\", \"R\", \"U'\", \"R\", \"U\", \"R'\",", "\"U'\", \"R\", \"Y'\", \"D'\", \"R2\", \"Y'\", \"R'\", \"U\", \"R\"], \"832745016\": [\"R'\", \"U'\", \"R\",", "\"R'\", \"F'\", \"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F\", \"R\", \"F'\"], \"872345610\": [\"L\", \"U'\",", "= PLLSolver.get_orientations(self.cube) if orientation in PLLSolver.STEPS: for s in PLLSolver.STEPS[orientation]: self.move(s, solution) return", "\"R\", \"U\", \"R'\", \"F'\"], \"230145678\": [\"R'\", \"U\", \"L'\", \"U2\", \"R\", \"U'\", \"R'\", \"U2\",", "\"U'\", \"R'\", \"D2\", \"R2\", \"X'\"], \"018345276\": [\"X'\", \"R\", \"U'\", \"R\", \"D2\", \"R'\", \"U\",", "\"L'\", \"U\", \"R'\", \"L\", \"U'\", \"R\", \"U2\", \"L'\", \"U\", \"R'\", \"U\"], \"076345218\": [\"R'\",", "\"X\"], \"012743658\": [\"R2\", \"U\", \"R\", \"U\", \"R'\", \"U'\", \"R'\", \"U'\", \"R'\", \"U\", \"R'\"],", "\"U'\"], \"210745638\": [\"L\", \"U2\", \"L'\", \"U2\", \"L\", \"F'\", \"L'\", \"U'\", \"L\", \"U\", \"L\",", "for _ in range(4): self.move('U', solution) for _ in range(4): self.move('Y', solution) orientation", "[\"L\", \"U2\", \"L'\", \"U2\", \"L\", \"F'\", \"L'\", \"U'\", \"L\", \"U\", \"L\", \"F\", \"L2\",", "\"R2\", \"Y\", \"D\", \"R'\", \"U\", \"R\", \"U'\", \"R\", \"Y'\", \"D'\", \"R2\"], \"812743056\": [\"R2\",", "\"U'\", \"R'\", \"F'\", \"R2\", \"U'\"], \"852341670\": [\"R'\", \"U\", \"R'\", \"Y\", \"U'\", \"R'\", \"F'\",", "\"L\", \"R'\", \"U\", \"L'\", \"U2\", \"R\", \"U'\", \"L\", \"U'\"], \"618345072\": [\"X'\", \"R\", \"U'\",", "to be solvable after that for s in PLLSolver.STEPS[\"072543618\"]: self.move(s, solution) return []", "\"U'\", \"R'\", \"F\", \"R\", \"F'\"], \"872345610\": [\"L\", \"U'\", \"R\", \"U2\", \"L'\", \"U\", \"R'\",", "\"R'\", \"L\", \"U'\", \"R\", \"U2\", \"L'\", \"U\", \"R'\", \"U\"], \"076345218\": [\"R'\", \"U\", \"L'\",", "[\"X'\", \"R\", \"U'\", \"R\", \"D2\", \"R'\", \"U\", \"R\", \"D2\", \"R2\", \"X\"], \"012743658\": [\"R2\",", "@staticmethod def get_correct_cubie(cube, cubie): colors = [cube.cubies[c].facings[c].color for c in cubie.replace('U', '')] return", "\"U'\", \"R'\", \"F\", \"R2\", \"U'\", \"R'\", \"U'\", \"R\", \"U\", \"R'\", \"F'\"], \"230145678\": [\"R'\",", "\"F'\"], \"230145678\": [\"R'\", \"U\", \"L'\", \"U2\", \"R\", \"U'\", \"R'\", \"U2\", \"R\", \"L\", \"U'\"],", "\"M2\", \"U2\", \"M2\", \"U\", \"M2\"], \"018543672\": [\"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F\", \"R2\",", "<filename>rubik_solver/Solver/CFOP/PLLSolver.py<gh_stars>10-100 from rubik_solver.Move import Move from .. import Solver class PLLSolver(Solver): STEPS =", "self.move('Y', solution) orientation = PLLSolver.get_orientations(self.cube) if orientation in PLLSolver.STEPS: for s in PLLSolver.STEPS[orientation]:", "\"U'\", \"L\", \"U'\"], \"618345072\": [\"X'\", \"R\", \"U'\", \"R'\", \"D\", \"R\", \"U\", \"R'\", \"D'\",", "\"M'\", \"U2\"], \"832145670\": [\"F\", \"R\", \"U'\", \"R'\", \"U'\", \"R\", \"U\", \"R'\", \"F'\", \"R\",", "\"R2\", \"U'\", \"R'\", \"U'\", \"R\", \"U\", \"R'\", \"F'\"], \"230145678\": [\"R'\", \"U\", \"L'\", \"U2\",", "''.join(orientation) def move(self, s, solution): self.cube.move(Move(s)) solution.append(s) @staticmethod def get_correct_cubie(cube, cubie): colors =", "\"U2\"], \"832145670\": [\"F\", \"R\", \"U'\", \"R'\", \"U'\", \"R\", \"U\", \"R'\", \"F'\", \"R\", \"U\",", "\"R'\", \"U2\", \"R\", \"L\", \"U'\"], \"018347652\": [\"R\", \"U\", \"R'\", \"F'\", \"R\", \"U\", \"R'\",", "\"F\", \"R\", \"F'\"], \"872345610\": [\"L\", \"U'\", \"R\", \"U2\", \"L'\", \"U\", \"R'\", \"L\", \"U'\",", "solution(self): solution = [] while True: for _ in range(4): self.move('U', solution) for", "\"D'\", \"R\", \"U'\", \"R'\", \"U\", \"R'\", \"Y\", \"D\", \"R2\"], \"012543876\": [\"R'\", \"U2\", \"R'\",", "\"M2\"], \"018543672\": [\"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F\", \"R2\", \"U'\", \"R'\", \"U'\", \"R\",", "and expect to be solvable after that for s in PLLSolver.STEPS[\"072543618\"]: self.move(s, solution)", "\"D\", \"R\", \"U\", \"R'\", \"D'\", \"R\", \"U\", \"R'\", \"D\", \"R\", \"U'\", \"R'\", \"D'\",", "def solution(self): solution = [] while True: for _ in range(4): self.move('U', solution)", "\"F\", \"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F'\", \"R2\", \"U'\"], \"852341670\": [\"R'\", \"U\", \"R'\",", "Solver class PLLSolver(Solver): STEPS = { \"810345672\": [\"X\", \"R'\", \"U\", \"R'\", \"D2\", \"R\",", "\"210745638\": [\"L\", \"U2\", \"L'\", \"U2\", \"L\", \"F'\", \"L'\", \"U'\", \"L\", \"U\", \"L\", \"F\",", "expect to be solvable after that for s in PLLSolver.STEPS[\"072543618\"]: self.move(s, solution) return", "\"R2\", \"Y\", \"R\", \"U'\", \"R'\"], \"670145238\": [\"R\", \"U\", \"R'\", \"Y'\", \"R2\", \"Y'\", \"D'\",", "\"U2\", \"M2\", \"U\", \"M2\"], \"018543672\": [\"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F\", \"R2\", \"U'\",", "shortest and expect to be solvable after that for s in PLLSolver.STEPS[\"072543618\"]: self.move(s,", "\"R\", \"U'\", \"L\", \"R'\", \"U\", \"L'\", \"U2\", \"R\", \"U'\", \"L\", \"U'\"], \"618345072\": [\"X'\",", "\"L\", \"F\", \"L2\", \"U\"], \"210347658\": [\"R'\", \"U2\", \"R\", \"U2\", \"R'\", \"F\", \"R\", \"U\",", "\"Y'\", \"R2\", \"Y'\", \"D'\", \"R\", \"U'\", \"R'\", \"U\", \"R'\", \"Y\", \"D\", \"R2\"], \"012543876\":", "\"R'\", \"U\", \"R\"], \"832745016\": [\"R'\", \"U'\", \"R\", \"Y\", \"R2\", \"Y\", \"D\", \"R'\", \"U\",", "\"R'\", \"U\", \"R'\", \"U'\", \"R\", \"Y'\", \"D'\", \"R2\", \"Y'\", \"R'\", \"U\", \"R\"], \"832745016\":", "'')] return cube.search_by_colors('Y', *colors) def solution(self): solution = [] while True: for _", "\"Y\", \"U'\", \"R'\", \"F'\", \"R2\", \"U'\", \"R'\", \"U\", \"R'\", \"F\", \"R\", \"U'\", \"F\"],", ".. import Solver class PLLSolver(Solver): STEPS = { \"810345672\": [\"X\", \"R'\", \"U\", \"R'\",", "\"U\", \"R'\", \"F'\", \"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F\", \"R2\", \"U'\", \"R'\", \"U'\"],", "\"R'\", \"D'\", \"R\", \"U\", \"R'\", \"D\", \"R\", \"U'\", \"R'\", \"D'\", \"X\"] } @staticmethod", "PLLSolver(Solver): STEPS = { \"810345672\": [\"X\", \"R'\", \"U\", \"R'\", \"D2\", \"R\", \"U'\", \"R'\",", "import Move from .. import Solver class PLLSolver(Solver): STEPS = { \"810345672\": [\"X\",", "\"R'\", \"U'\", \"R\", \"U\", \"R'\", \"F'\", \"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F\", \"R\",", "\"L\", \"F'\", \"L'\", \"U'\", \"L\", \"U\", \"L\", \"F\", \"L2\", \"U\"], \"210347658\": [\"R'\", \"U2\",", "= ['BLU', 'BU', 'BRU', 'LU', 'U', 'RU', 'FLU', 'FU', 'FRU'] orientation = []", "\"U2\", \"L'\", \"U2\", \"L\", \"F'\", \"L'\", \"U'\", \"L\", \"U\", \"L\", \"F\", \"L2\", \"U\"],", "\"L2\", \"U\"], \"210347658\": [\"R'\", \"U2\", \"R\", \"U2\", \"R'\", \"F\", \"R\", \"U\", \"R'\", \"U'\",", "} @staticmethod def get_orientations(cube): cubies = ['BLU', 'BU', 'BRU', 'LU', 'U', 'RU', 'FLU',", "\"U\", \"M2\"], \"018543672\": [\"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F\", \"R2\", \"U'\", \"R'\", \"U'\",", "\"R'\", \"Y\", \"D\", \"R2\", \"Y\", \"R\", \"U'\", \"R'\"], \"670145238\": [\"R\", \"U\", \"R'\", \"Y'\",", "\"R'\", \"Y\", \"U'\", \"R'\", \"F'\", \"R2\", \"U'\", \"R'\", \"U\", \"R'\", \"F\", \"R\", \"U'\",", "in PLLSolver.STEPS[orientation]: self.move(s, solution) return solution # Apply shortest and expect to be", "\"076345218\": [\"R'\", \"U\", \"L'\", \"U2\", \"R\", \"U'\", \"L\", \"R'\", \"U\", \"L'\", \"U2\", \"R\",", "\"U\", \"M'\", \"U2\", \"M2\", \"U2\", \"M'\", \"U2\"], \"832145670\": [\"F\", \"R\", \"U'\", \"R'\", \"U'\",", "\"U\", \"R'\", \"F'\", \"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F\", \"R\", \"F'\"], \"872345610\": [\"L\",", "\"R'\", \"D2\", \"R\", \"U'\", \"R'\", \"D2\", \"R2\", \"X'\"], \"018345276\": [\"X'\", \"R\", \"U'\", \"R\",", "\"R\", \"U2\", \"L'\", \"U\", \"R'\", \"U\"], \"076345218\": [\"R'\", \"U\", \"L'\", \"U2\", \"R\", \"U'\",", "\"D2\", \"R2\", \"X\"], \"012743658\": [\"R2\", \"U\", \"R\", \"U\", \"R'\", \"U'\", \"R'\", \"U'\", \"R'\",", "solution) for _ in range(4): self.move('Y', solution) orientation = PLLSolver.get_orientations(self.cube) if orientation in", "\"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F'\", \"R2\", \"U'\"], \"852341670\": [\"R'\", \"U\", \"R'\", \"Y\",", "\"R'\", \"Y\", \"U'\", \"R'\", \"F'\", \"R2\", \"U'\", \"R'\", \"U\", \"R'\", \"F\", \"R\", \"F\"],", "\"R'\", \"U'\", \"R'\", \"F\", \"R2\", \"U'\", \"R'\", \"U'\", \"R\", \"U\", \"R'\", \"F'\"], \"230145678\":", "\"M2\", \"U\", \"M2\"], \"018543672\": [\"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F\", \"R2\", \"U'\", \"R'\",", "\"L'\", \"U2\", \"L\", \"F'\", \"L'\", \"U'\", \"L\", \"U\", \"L\", \"F\", \"L2\", \"U\"], \"210347658\":", "= [] while True: for _ in range(4): self.move('U', solution) for _ in", "\"012543876\": [\"R'\", \"U2\", \"R'\", \"Y\", \"U'\", \"R'\", \"F'\", \"R2\", \"U'\", \"R'\", \"U\", \"R'\",", "range(4): self.move('Y', solution) orientation = PLLSolver.get_orientations(self.cube) if orientation in PLLSolver.STEPS: for s in", "\"U\", \"R'\", \"U'\", \"R'\", \"F\", \"R2\", \"U'\", \"R'\", \"U'\"], \"210745638\": [\"L\", \"U2\", \"L'\",", "solution = [] while True: for _ in range(4): self.move('U', solution) for _", "\"R2\", \"Y'\", \"D'\", \"R\", \"U'\", \"R'\", \"U\", \"R'\", \"Y\", \"D\", \"R2\"], \"012543876\": [\"R'\",", "'FRU'] orientation = [] for cubie in cubies: o = PLLSolver.get_correct_cubie(cube, cubie) orientation.append(str(cubies.index(o)))", "\"U'\", \"R\", \"U\", \"R'\", \"F'\"], \"230145678\": [\"R'\", \"U\", \"L'\", \"U2\", \"R\", \"U'\", \"R'\",", "\"R'\", \"U\"], \"076345218\": [\"R'\", \"U\", \"L'\", \"U2\", \"R\", \"U'\", \"L\", \"R'\", \"U\", \"L'\",", "in PLLSolver.STEPS: for s in PLLSolver.STEPS[orientation]: self.move(s, solution) return solution # Apply shortest", "\"Y'\", \"D'\", \"R\", \"U'\", \"R\", \"U\", \"R'\", \"Y\", \"D\", \"R2\", \"Y\", \"R\", \"U'\",", "\"R'\", \"U'\", \"R'\", \"F\", \"R\", \"F'\"], \"872345610\": [\"L\", \"U'\", \"R\", \"U2\", \"L'\", \"U\",", "\"R\", \"U'\", \"R\", \"Y'\", \"D'\", \"R2\"], \"812743056\": [\"R2\", \"Y'\", \"D'\", \"R\", \"U'\", \"R\",", "'FU', 'FRU'] orientation = [] for cubie in cubies: o = PLLSolver.get_correct_cubie(cube, cubie)", "\"F\", \"L2\", \"U\"], \"210347658\": [\"R'\", \"U2\", \"R\", \"U2\", \"R'\", \"F\", \"R\", \"U\", \"R'\",", "\"U'\"], \"852341670\": [\"R'\", \"U\", \"R'\", \"Y\", \"U'\", \"R'\", \"F'\", \"R2\", \"U'\", \"R'\", \"U\",", "\"R\", \"F'\"], \"872345610\": [\"L\", \"U'\", \"R\", \"U2\", \"L'\", \"U\", \"R'\", \"L\", \"U'\", \"R\",", "\"R\", \"U'\", \"R'\", \"D\", \"R\", \"U\", \"R'\", \"D'\", \"R\", \"U\", \"R'\", \"D\", \"R\",", "\"D'\", \"X\"] } @staticmethod def get_orientations(cube): cubies = ['BLU', 'BU', 'BRU', 'LU', 'U',", "\"R2\", \"X\"], \"012743658\": [\"R2\", \"U\", \"R\", \"U\", \"R'\", \"U'\", \"R'\", \"U'\", \"R'\", \"U\",", "get_orientations(cube): cubies = ['BLU', 'BU', 'BRU', 'LU', 'U', 'RU', 'FLU', 'FU', 'FRU'] orientation", "from rubik_solver.Move import Move from .. import Solver class PLLSolver(Solver): STEPS = {", "\"012743658\": [\"R2\", \"U\", \"R\", \"U\", \"R'\", \"U'\", \"R'\", \"U'\", \"R'\", \"U\", \"R'\"], \"012547638\":", "for c in cubie.replace('U', '')] return cube.search_by_colors('Y', *colors) def solution(self): solution = []", "\"R'\"], \"670145238\": [\"R\", \"U\", \"R'\", \"Y'\", \"R2\", \"Y'\", \"D'\", \"R\", \"U'\", \"R'\", \"U\",", "class PLLSolver(Solver): STEPS = { \"810345672\": [\"X\", \"R'\", \"U\", \"R'\", \"D2\", \"R\", \"U'\",", "\"D\", \"R\", \"U'\", \"R'\", \"D'\", \"X\"] } @staticmethod def get_orientations(cube): cubies = ['BLU',", "\"U'\", \"R\", \"U2\", \"L'\", \"U\", \"R'\", \"L\", \"U'\", \"R\", \"U2\", \"L'\", \"U\", \"R'\",", "s in PLLSolver.STEPS[orientation]: self.move(s, solution) return solution # Apply shortest and expect to", "\"X\"] } @staticmethod def get_orientations(cube): cubies = ['BLU', 'BU', 'BRU', 'LU', 'U', 'RU',", "['BLU', 'BU', 'BRU', 'LU', 'U', 'RU', 'FLU', 'FU', 'FRU'] orientation = [] for", "\"D2\", \"R2\", \"X'\"], \"018345276\": [\"X'\", \"R\", \"U'\", \"R\", \"D2\", \"R'\", \"U\", \"R\", \"D2\",", "PLLSolver.get_correct_cubie(cube, cubie) orientation.append(str(cubies.index(o))) return ''.join(orientation) def move(self, s, solution): self.cube.move(Move(s)) solution.append(s) @staticmethod def", "in cubie.replace('U', '')] return cube.search_by_colors('Y', *colors) def solution(self): solution = [] while True:", "\"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F\", \"R2\", \"U'\", \"R'\", \"U'\"], \"210745638\": [\"L\", \"U2\",", "range(4): self.move('U', solution) for _ in range(4): self.move('Y', solution) orientation = PLLSolver.get_orientations(self.cube) if", "cubie in cubies: o = PLLSolver.get_correct_cubie(cube, cubie) orientation.append(str(cubies.index(o))) return ''.join(orientation) def move(self, s,", "\"M2\", \"U\", \"M'\", \"U2\", \"M2\", \"U2\", \"M'\", \"U2\"], \"832145670\": [\"F\", \"R\", \"U'\", \"R'\",", "'U', 'RU', 'FLU', 'FU', 'FRU'] orientation = [] for cubie in cubies: o", "\"R\", \"U\", \"R'\", \"U'\", \"R'\", \"U'\", \"R'\", \"U\", \"R'\"], \"012547638\": [\"R\", \"U'\", \"R\",", "\"U\", \"M2\", \"U2\", \"M2\", \"U\", \"M2\"], \"018543672\": [\"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F\",", "def get_orientations(cube): cubies = ['BLU', 'BU', 'BRU', 'LU', 'U', 'RU', 'FLU', 'FU', 'FRU']", "\"F\"], \"032147658\": [\"M2\", \"U\", \"M2\", \"U\", \"M'\", \"U2\", \"M2\", \"U2\", \"M'\", \"U2\"], \"832145670\":", "\"R\", \"U'\", \"F\"], \"032147658\": [\"M2\", \"U\", \"M2\", \"U\", \"M'\", \"U2\", \"M2\", \"U2\", \"M'\",", "'RU', 'FLU', 'FU', 'FRU'] orientation = [] for cubie in cubies: o =", "\"Y'\", \"D'\", \"R2\"], \"812743056\": [\"R2\", \"Y'\", \"D'\", \"R\", \"U'\", \"R\", \"U\", \"R'\", \"Y\",", "= { \"810345672\": [\"X\", \"R'\", \"U\", \"R'\", \"D2\", \"R\", \"U'\", \"R'\", \"D2\", \"R2\",", "\"U\", \"R'\", \"D2\", \"R\", \"U'\", \"R'\", \"D2\", \"R2\", \"X'\"], \"018345276\": [\"X'\", \"R\", \"U'\",", "get_correct_cubie(cube, cubie): colors = [cube.cubies[c].facings[c].color for c in cubie.replace('U', '')] return cube.search_by_colors('Y', *colors)", "\"Y\", \"R2\", \"Y\", \"D\", \"R'\", \"U\", \"R\", \"U'\", \"R\", \"Y'\", \"D'\", \"R2\"], \"812743056\":", "\"U'\", \"R'\", \"U\", \"R'\", \"F\", \"R\", \"U'\", \"F\"], \"032147658\": [\"M2\", \"U\", \"M2\", \"U\",", "\"U\", \"L'\", \"U2\", \"R\", \"U'\", \"L\", \"U'\"], \"618345072\": [\"X'\", \"R\", \"U'\", \"R'\", \"D\",", "\"U'\", \"R\", \"U2\", \"L'\", \"U\", \"R'\", \"U\"], \"076345218\": [\"R'\", \"U\", \"L'\", \"U2\", \"R\",", "@staticmethod def get_orientations(cube): cubies = ['BLU', 'BU', 'BRU', 'LU', 'U', 'RU', 'FLU', 'FU',", "\"D2\", \"R\", \"U'\", \"R'\", \"D2\", \"R2\", \"X'\"], \"018345276\": [\"X'\", \"R\", \"U'\", \"R\", \"D2\",", "\"U\", \"R\", \"U\", \"R'\", \"U'\", \"R'\", \"U'\", \"R'\", \"U\", \"R'\"], \"012547638\": [\"R\", \"U'\",", "\"R'\", \"D2\", \"R2\", \"X'\"], \"018345276\": [\"X'\", \"R\", \"U'\", \"R\", \"D2\", \"R'\", \"U\", \"R\",", "\"L'\", \"U\", \"R'\", \"U\"], \"076345218\": [\"R'\", \"U\", \"L'\", \"U2\", \"R\", \"U'\", \"L\", \"R'\",", "\"832145670\": [\"F\", \"R\", \"U'\", \"R'\", \"U'\", \"R\", \"U\", \"R'\", \"F'\", \"R\", \"U\", \"R'\",", "\"F'\", \"R2\", \"U'\", \"R'\", \"U\", \"R'\", \"F\", \"R\", \"F\"], \"650143278\": [\"R2\", \"Y\", \"D\",", "\"U\", \"R'\", \"F\", \"R\", \"U'\", \"F\"], \"032147658\": [\"M2\", \"U\", \"M2\", \"U\", \"M'\", \"U2\",", "\"R\", \"U'\", \"R'\", \"D2\", \"R2\", \"X'\"], \"018345276\": [\"X'\", \"R\", \"U'\", \"R\", \"D2\", \"R'\",", "\"618345072\": [\"X'\", \"R\", \"U'\", \"R'\", \"D\", \"R\", \"U\", \"R'\", \"D'\", \"R\", \"U\", \"R'\",", "\"R'\", \"U'\", \"R2\"], \"072543618\": [\"M2\", \"U\", \"M2\", \"U2\", \"M2\", \"U\", \"M2\"], \"018543672\": [\"R\",", "\"U\", \"R'\", \"Y\", \"D\", \"R2\"], \"012543876\": [\"R'\", \"U2\", \"R'\", \"Y\", \"U'\", \"R'\", \"F'\",", "\"U2\", \"R\", \"L\", \"U'\"], \"018347652\": [\"R\", \"U\", \"R'\", \"F'\", \"R\", \"U\", \"R'\", \"U'\",", "\"U\"], \"210347658\": [\"R'\", \"U2\", \"R\", \"U2\", \"R'\", \"F\", \"R\", \"U\", \"R'\", \"U'\", \"R'\",", "\"832745016\": [\"R'\", \"U'\", \"R\", \"Y\", \"R2\", \"Y\", \"D\", \"R'\", \"U\", \"R\", \"U'\", \"R\",", "[\"R'\", \"U\", \"L'\", \"U2\", \"R\", \"U'\", \"R'\", \"U2\", \"R\", \"L\", \"U'\"], \"018347652\": [\"R\",", "Apply shortest and expect to be solvable after that for s in PLLSolver.STEPS[\"072543618\"]:", "\"U\", \"R'\", \"F'\"], \"230145678\": [\"R'\", \"U\", \"L'\", \"U2\", \"R\", \"U'\", \"R'\", \"U2\", \"R\",", "\"U\", \"R'\", \"Y'\", \"R2\", \"Y'\", \"D'\", \"R\", \"U'\", \"R'\", \"U\", \"R'\", \"Y\", \"D\",", "\"U\", \"M2\", \"U\", \"M'\", \"U2\", \"M2\", \"U2\", \"M'\", \"U2\"], \"832145670\": [\"F\", \"R\", \"U'\",", "\"U'\", \"R'\", \"U'\", \"R\", \"U\", \"R'\", \"F'\"], \"230145678\": [\"R'\", \"U\", \"L'\", \"U2\", \"R\",", "\"R\", \"U\", \"R\", \"U'\", \"R'\", \"U'\", \"R2\"], \"072543618\": [\"M2\", \"U\", \"M2\", \"U2\", \"M2\",", "[\"R2\", \"U\", \"R\", \"U\", \"R'\", \"U'\", \"R'\", \"U'\", \"R'\", \"U\", \"R'\"], \"012547638\": [\"R\",", "\"230145678\": [\"R'\", \"U\", \"L'\", \"U2\", \"R\", \"U'\", \"R'\", \"U2\", \"R\", \"L\", \"U'\"], \"018347652\":", "in cubies: o = PLLSolver.get_correct_cubie(cube, cubie) orientation.append(str(cubies.index(o))) return ''.join(orientation) def move(self, s, solution):", "\"F\", \"R2\", \"U'\", \"R'\", \"U'\", \"R\", \"U\", \"R'\", \"F'\"], \"230145678\": [\"R'\", \"U\", \"L'\",", "\"R2\"], \"072543618\": [\"M2\", \"U\", \"M2\", \"U2\", \"M2\", \"U\", \"M2\"], \"018543672\": [\"R\", \"U\", \"R'\",", "\"U\", \"R'\", \"U\"], \"076345218\": [\"R'\", \"U\", \"L'\", \"U2\", \"R\", \"U'\", \"L\", \"R'\", \"U\",", "Move from .. import Solver class PLLSolver(Solver): STEPS = { \"810345672\": [\"X\", \"R'\",", "cube.search_by_colors('Y', *colors) def solution(self): solution = [] while True: for _ in range(4):", "\"R'\", \"F\", \"R\", \"F'\"], \"872345610\": [\"L\", \"U'\", \"R\", \"U2\", \"L'\", \"U\", \"R'\", \"L\",", "\"U\", \"R\", \"U\", \"R\", \"U'\", \"R'\", \"U'\", \"R2\"], \"072543618\": [\"M2\", \"U\", \"M2\", \"U2\",", "\"R'\", \"U'\", \"R'\", \"F'\", \"R2\", \"U'\"], \"852341670\": [\"R'\", \"U\", \"R'\", \"Y\", \"U'\", \"R'\",", "\"R'\", \"F'\"], \"230145678\": [\"R'\", \"U\", \"L'\", \"U2\", \"R\", \"U'\", \"R'\", \"U2\", \"R\", \"L\",", "\"R'\", \"U'\", \"R'\", \"F\", \"R2\", \"U'\", \"R'\", \"U'\"], \"210745638\": [\"L\", \"U2\", \"L'\", \"U2\",", "\"R'\", \"U'\", \"R\", \"U\", \"R'\", \"F'\"], \"230145678\": [\"R'\", \"U\", \"L'\", \"U2\", \"R\", \"U'\",", "\"R2\"], \"012543876\": [\"R'\", \"U2\", \"R'\", \"Y\", \"U'\", \"R'\", \"F'\", \"R2\", \"U'\", \"R'\", \"U\",", "\"012547638\": [\"R\", \"U'\", \"R\", \"U\", \"R\", \"U\", \"R\", \"U'\", \"R'\", \"U'\", \"R2\"], \"072543618\":", "\"R'\", \"F'\", \"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F\", \"R2\", \"U'\", \"R'\", \"U'\"], \"210745638\":", "PLLSolver.STEPS[orientation]: self.move(s, solution) return solution # Apply shortest and expect to be solvable", "*colors) def solution(self): solution = [] while True: for _ in range(4): self.move('U',", "\"Y\", \"D\", \"R'\", \"U\", \"R'\", \"U'\", \"R\", \"Y'\", \"D'\", \"R2\", \"Y'\", \"R'\", \"U\",", "solution): self.cube.move(Move(s)) solution.append(s) @staticmethod def get_correct_cubie(cube, cubie): colors = [cube.cubies[c].facings[c].color for c in", "\"U2\", \"M'\", \"U2\"], \"832145670\": [\"F\", \"R\", \"U'\", \"R'\", \"U'\", \"R\", \"U\", \"R'\", \"F'\",", "\"R2\", \"U'\"], \"852341670\": [\"R'\", \"U\", \"R'\", \"Y\", \"U'\", \"R'\", \"F'\", \"R2\", \"U'\", \"R'\",", "PLLSolver.get_orientations(self.cube) if orientation in PLLSolver.STEPS: for s in PLLSolver.STEPS[orientation]: self.move(s, solution) return solution", "\"R\", \"U'\", \"R'\", \"U2\", \"R\", \"L\", \"U'\"], \"018347652\": [\"R\", \"U\", \"R'\", \"F'\", \"R\",", "\"X'\"], \"018345276\": [\"X'\", \"R\", \"U'\", \"R\", \"D2\", \"R'\", \"U\", \"R\", \"D2\", \"R2\", \"X\"],", "return solution # Apply shortest and expect to be solvable after that for", "\"M2\", \"U2\", \"M'\", \"U2\"], \"832145670\": [\"F\", \"R\", \"U'\", \"R'\", \"U'\", \"R\", \"U\", \"R'\",", "orientation.append(str(cubies.index(o))) return ''.join(orientation) def move(self, s, solution): self.cube.move(Move(s)) solution.append(s) @staticmethod def get_correct_cubie(cube, cubie):", "[\"M2\", \"U\", \"M2\", \"U\", \"M'\", \"U2\", \"M2\", \"U2\", \"M'\", \"U2\"], \"832145670\": [\"F\", \"R\",", "[\"R'\", \"U2\", \"R'\", \"Y\", \"U'\", \"R'\", \"F'\", \"R2\", \"U'\", \"R'\", \"U\", \"R'\", \"F\",", "\"D\", \"R2\", \"Y\", \"R\", \"U'\", \"R'\"], \"670145238\": [\"R\", \"U\", \"R'\", \"Y'\", \"R2\", \"Y'\",", "\"F'\", \"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F\", \"R\", \"F'\"], \"872345610\": [\"L\", \"U'\", \"R\",", "\"R\", \"U'\", \"R'\", \"U'\", \"R\", \"U\", \"R'\", \"F'\", \"R\", \"U\", \"R'\", \"U'\", \"R'\",", "return cube.search_by_colors('Y', *colors) def solution(self): solution = [] while True: for _ in", "orientation = [] for cubie in cubies: o = PLLSolver.get_correct_cubie(cube, cubie) orientation.append(str(cubies.index(o))) return", "\"U\", \"R\", \"D2\", \"R2\", \"X\"], \"012743658\": [\"R2\", \"U\", \"R\", \"U\", \"R'\", \"U'\", \"R'\",", "\"D\", \"R'\", \"U\", \"R\", \"U'\", \"R\", \"Y'\", \"D'\", \"R2\"], \"812743056\": [\"R2\", \"Y'\", \"D'\",", "PLLSolver.STEPS: for s in PLLSolver.STEPS[orientation]: self.move(s, solution) return solution # Apply shortest and", "\"R'\"], \"012547638\": [\"R\", \"U'\", \"R\", \"U\", \"R\", \"U\", \"R\", \"U'\", \"R'\", \"U'\", \"R2\"],", "'BU', 'BRU', 'LU', 'U', 'RU', 'FLU', 'FU', 'FRU'] orientation = [] for cubie", "\"R2\", \"X'\"], \"018345276\": [\"X'\", \"R\", \"U'\", \"R\", \"D2\", \"R'\", \"U\", \"R\", \"D2\", \"R2\",", "\"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F\", \"R\", \"F'\"], \"872345610\": [\"L\", \"U'\", \"R\", \"U2\",", "\"U\", \"R'\", \"U'\", \"R\", \"Y'\", \"D'\", \"R2\", \"Y'\", \"R'\", \"U\", \"R\"], \"832745016\": [\"R'\",", "\"L'\", \"U2\", \"R\", \"U'\", \"L\", \"R'\", \"U\", \"L'\", \"U2\", \"R\", \"U'\", \"L\", \"U'\"],", "[\"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F\", \"R2\", \"U'\", \"R'\", \"U'\", \"R\", \"U\", \"R'\",", "c in cubie.replace('U', '')] return cube.search_by_colors('Y', *colors) def solution(self): solution = [] while", "\"R\"], \"832745016\": [\"R'\", \"U'\", \"R\", \"Y\", \"R2\", \"Y\", \"D\", \"R'\", \"U\", \"R\", \"U'\",", "\"210347658\": [\"R'\", \"U2\", \"R\", \"U2\", \"R'\", \"F\", \"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F'\",", "s, solution): self.cube.move(Move(s)) solution.append(s) @staticmethod def get_correct_cubie(cube, cubie): colors = [cube.cubies[c].facings[c].color for c", "[cube.cubies[c].facings[c].color for c in cubie.replace('U', '')] return cube.search_by_colors('Y', *colors) def solution(self): solution =", "\"F'\", \"R2\", \"U'\"], \"852341670\": [\"R'\", \"U\", \"R'\", \"Y\", \"U'\", \"R'\", \"F'\", \"R2\", \"U'\",", "# Apply shortest and expect to be solvable after that for s in", "self.cube.move(Move(s)) solution.append(s) @staticmethod def get_correct_cubie(cube, cubie): colors = [cube.cubies[c].facings[c].color for c in cubie.replace('U',", "\"U'\", \"R\", \"Y\", \"R2\", \"Y\", \"D\", \"R'\", \"U\", \"R\", \"U'\", \"R\", \"Y'\", \"D'\",", "\"F\"], \"650143278\": [\"R2\", \"Y\", \"D\", \"R'\", \"U\", \"R'\", \"U'\", \"R\", \"Y'\", \"D'\", \"R2\",", "\"U\", \"R'\", \"U'\", \"R'\", \"F\", \"R2\", \"U'\", \"R'\", \"U'\", \"R\", \"U\", \"R'\", \"F'\"],", "if orientation in PLLSolver.STEPS: for s in PLLSolver.STEPS[orientation]: self.move(s, solution) return solution #", "\"R'\", \"F\", \"R2\", \"U'\", \"R'\", \"U'\"], \"210745638\": [\"L\", \"U2\", \"L'\", \"U2\", \"L\", \"F'\",", "cubies: o = PLLSolver.get_correct_cubie(cube, cubie) orientation.append(str(cubies.index(o))) return ''.join(orientation) def move(self, s, solution): self.cube.move(Move(s))", "\"U\"], \"076345218\": [\"R'\", \"U\", \"L'\", \"U2\", \"R\", \"U'\", \"L\", \"R'\", \"U\", \"L'\", \"U2\",", "\"R'\", \"Y\", \"D\", \"R2\"], \"012543876\": [\"R'\", \"U2\", \"R'\", \"Y\", \"U'\", \"R'\", \"F'\", \"R2\",", "\"L'\", \"U2\", \"R\", \"U'\", \"L\", \"U'\"], \"618345072\": [\"X'\", \"R\", \"U'\", \"R'\", \"D\", \"R\",", "cubie) orientation.append(str(cubies.index(o))) return ''.join(orientation) def move(self, s, solution): self.cube.move(Move(s)) solution.append(s) @staticmethod def get_correct_cubie(cube,", "\"R\", \"Y'\", \"D'\", \"R2\", \"Y'\", \"R'\", \"U\", \"R\"], \"832745016\": [\"R'\", \"U'\", \"R\", \"Y\",", "\"R\", \"Y\", \"R2\", \"Y\", \"D\", \"R'\", \"U\", \"R\", \"U'\", \"R\", \"Y'\", \"D'\", \"R2\"],", "'BRU', 'LU', 'U', 'RU', 'FLU', 'FU', 'FRU'] orientation = [] for cubie in", "orientation = PLLSolver.get_orientations(self.cube) if orientation in PLLSolver.STEPS: for s in PLLSolver.STEPS[orientation]: self.move(s, solution)", "self.move('U', solution) for _ in range(4): self.move('Y', solution) orientation = PLLSolver.get_orientations(self.cube) if orientation", "\"U\", \"R\"], \"832745016\": [\"R'\", \"U'\", \"R\", \"Y\", \"R2\", \"Y\", \"D\", \"R'\", \"U\", \"R\",", "cubies = ['BLU', 'BU', 'BRU', 'LU', 'U', 'RU', 'FLU', 'FU', 'FRU'] orientation =", "\"U'\", \"R'\"], \"670145238\": [\"R\", \"U\", \"R'\", \"Y'\", \"R2\", \"Y'\", \"D'\", \"R\", \"U'\", \"R'\",", "\"Y'\", \"D'\", \"R2\", \"Y'\", \"R'\", \"U\", \"R\"], \"832745016\": [\"R'\", \"U'\", \"R\", \"Y\", \"R2\",", "\"U'\", \"R\", \"U\", \"R'\", \"Y\", \"D\", \"R2\", \"Y\", \"R\", \"U'\", \"R'\"], \"670145238\": [\"R\",", "\"R\", \"U'\", \"R\", \"U\", \"R'\", \"Y\", \"D\", \"R2\", \"Y\", \"R\", \"U'\", \"R'\"], \"670145238\":", "\"U\", \"L\", \"F\", \"L2\", \"U\"], \"210347658\": [\"R'\", \"U2\", \"R\", \"U2\", \"R'\", \"F\", \"R\",", "\"U2\", \"L'\", \"U\", \"R'\", \"L\", \"U'\", \"R\", \"U2\", \"L'\", \"U\", \"R'\", \"U\"], \"076345218\":", "\"U2\", \"L\", \"F'\", \"L'\", \"U'\", \"L\", \"U\", \"L\", \"F\", \"L2\", \"U\"], \"210347658\": [\"R'\",", "\"Y\", \"R\", \"U'\", \"R'\"], \"670145238\": [\"R\", \"U\", \"R'\", \"Y'\", \"R2\", \"Y'\", \"D'\", \"R\",", "\"U2\", \"R\", \"U2\", \"R'\", \"F\", \"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F'\", \"R2\", \"U'\"],", "\"R'\", \"U\", \"R'\", \"F\", \"R\", \"F\"], \"650143278\": [\"R2\", \"Y\", \"D\", \"R'\", \"U\", \"R'\",", "\"U\", \"L'\", \"U2\", \"R\", \"U'\", \"L\", \"R'\", \"U\", \"L'\", \"U2\", \"R\", \"U'\", \"L\",", "\"R2\", \"U'\", \"R'\", \"U'\"], \"210745638\": [\"L\", \"U2\", \"L'\", \"U2\", \"L\", \"F'\", \"L'\", \"U'\",", "\"U'\", \"R'\", \"U'\", \"R'\", \"U\", \"R'\"], \"012547638\": [\"R\", \"U'\", \"R\", \"U\", \"R\", \"U\",", "[\"F\", \"R\", \"U'\", \"R'\", \"U'\", \"R\", \"U\", \"R'\", \"F'\", \"R\", \"U\", \"R'\", \"U'\",", "\"L'\", \"U'\", \"L\", \"U\", \"L\", \"F\", \"L2\", \"U\"], \"210347658\": [\"R'\", \"U2\", \"R\", \"U2\",", "[\"R\", \"U'\", \"R\", \"U\", \"R\", \"U\", \"R\", \"U'\", \"R'\", \"U'\", \"R2\"], \"072543618\": [\"M2\",", "\"U\", \"R\", \"U'\", \"R\", \"Y'\", \"D'\", \"R2\"], \"812743056\": [\"R2\", \"Y'\", \"D'\", \"R\", \"U'\",", "return ''.join(orientation) def move(self, s, solution): self.cube.move(Move(s)) solution.append(s) @staticmethod def get_correct_cubie(cube, cubie): colors", "def move(self, s, solution): self.cube.move(Move(s)) solution.append(s) @staticmethod def get_correct_cubie(cube, cubie): colors = [cube.cubies[c].facings[c].color", "\"810345672\": [\"X\", \"R'\", \"U\", \"R'\", \"D2\", \"R\", \"U'\", \"R'\", \"D2\", \"R2\", \"X'\"], \"018345276\":", "= [cube.cubies[c].facings[c].color for c in cubie.replace('U', '')] return cube.search_by_colors('Y', *colors) def solution(self): solution", "\"R'\", \"U'\", \"R'\", \"U\", \"R'\"], \"012547638\": [\"R\", \"U'\", \"R\", \"U\", \"R\", \"U\", \"R\",", "\"R'\", \"D'\", \"X\"] } @staticmethod def get_orientations(cube): cubies = ['BLU', 'BU', 'BRU', 'LU',", "[\"X\", \"R'\", \"U\", \"R'\", \"D2\", \"R\", \"U'\", \"R'\", \"D2\", \"R2\", \"X'\"], \"018345276\": [\"X'\",", "\"R'\", \"U\", \"R'\", \"Y\", \"D\", \"R2\"], \"012543876\": [\"R'\", \"U2\", \"R'\", \"Y\", \"U'\", \"R'\",", "\"032147658\": [\"M2\", \"U\", \"M2\", \"U\", \"M'\", \"U2\", \"M2\", \"U2\", \"M'\", \"U2\"], \"832145670\": [\"F\",", "[] for cubie in cubies: o = PLLSolver.get_correct_cubie(cube, cubie) orientation.append(str(cubies.index(o))) return ''.join(orientation) def", "[\"R'\", \"U2\", \"R\", \"U2\", \"R'\", \"F\", \"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F'\", \"R2\",", "\"L\", \"U'\"], \"618345072\": [\"X'\", \"R\", \"U'\", \"R'\", \"D\", \"R\", \"U\", \"R'\", \"D'\", \"R\",", "\"650143278\": [\"R2\", \"Y\", \"D\", \"R'\", \"U\", \"R'\", \"U'\", \"R\", \"Y'\", \"D'\", \"R2\", \"Y'\",", "\"U'\", \"R'\", \"U'\"], \"210745638\": [\"L\", \"U2\", \"L'\", \"U2\", \"L\", \"F'\", \"L'\", \"U'\", \"L\",", "\"D\", \"R2\"], \"012543876\": [\"R'\", \"U2\", \"R'\", \"Y\", \"U'\", \"R'\", \"F'\", \"R2\", \"U'\", \"R'\",", "[] while True: for _ in range(4): self.move('U', solution) for _ in range(4):", "_ in range(4): self.move('Y', solution) orientation = PLLSolver.get_orientations(self.cube) if orientation in PLLSolver.STEPS: for", "{ \"810345672\": [\"X\", \"R'\", \"U\", \"R'\", \"D2\", \"R\", \"U'\", \"R'\", \"D2\", \"R2\", \"X'\"],", "\"U'\", \"R\", \"D2\", \"R'\", \"U\", \"R\", \"D2\", \"R2\", \"X\"], \"012743658\": [\"R2\", \"U\", \"R\",", "\"R\", \"U'\", \"R'\", \"U\", \"R'\", \"Y\", \"D\", \"R2\"], \"012543876\": [\"R'\", \"U2\", \"R'\", \"Y\",", "\"018543672\": [\"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F\", \"R2\", \"U'\", \"R'\", \"U'\", \"R\", \"U\",", "\"D'\", \"R2\", \"Y'\", \"R'\", \"U\", \"R\"], \"832745016\": [\"R'\", \"U'\", \"R\", \"Y\", \"R2\", \"Y\",", "\"U\", \"R'\", \"U'\", \"R'\", \"F'\", \"R2\", \"U'\"], \"852341670\": [\"R'\", \"U\", \"R'\", \"Y\", \"U'\",", "\"R\", \"D2\", \"R2\", \"X\"], \"012743658\": [\"R2\", \"U\", \"R\", \"U\", \"R'\", \"U'\", \"R'\", \"U'\",", "\"812743056\": [\"R2\", \"Y'\", \"D'\", \"R\", \"U'\", \"R\", \"U\", \"R'\", \"Y\", \"D\", \"R2\", \"Y\",", "\"U'\", \"R'\", \"U\", \"R'\", \"F\", \"R\", \"F\"], \"650143278\": [\"R2\", \"Y\", \"D\", \"R'\", \"U\",", "\"U\", \"R'\", \"U'\", \"R'\", \"F\", \"R\", \"F'\"], \"872345610\": [\"L\", \"U'\", \"R\", \"U2\", \"L'\",", "\"U'\"], \"618345072\": [\"X'\", \"R\", \"U'\", \"R'\", \"D\", \"R\", \"U\", \"R'\", \"D'\", \"R\", \"U\",", "in range(4): self.move('Y', solution) orientation = PLLSolver.get_orientations(self.cube) if orientation in PLLSolver.STEPS: for s", "def get_correct_cubie(cube, cubie): colors = [cube.cubies[c].facings[c].color for c in cubie.replace('U', '')] return cube.search_by_colors('Y',", "rubik_solver.Move import Move from .. import Solver class PLLSolver(Solver): STEPS = { \"810345672\":", "\"R'\", \"U\", \"R'\", \"D2\", \"R\", \"U'\", \"R'\", \"D2\", \"R2\", \"X'\"], \"018345276\": [\"X'\", \"R\",", "\"U\", \"R\", \"U'\", \"R'\", \"U'\", \"R2\"], \"072543618\": [\"M2\", \"U\", \"M2\", \"U2\", \"M2\", \"U\",", "\"U'\", \"L\", \"R'\", \"U\", \"L'\", \"U2\", \"R\", \"U'\", \"L\", \"U'\"], \"618345072\": [\"X'\", \"R\",", "\"U2\", \"M2\", \"U2\", \"M'\", \"U2\"], \"832145670\": [\"F\", \"R\", \"U'\", \"R'\", \"U'\", \"R\", \"U\",", "\"R'\", \"F\", \"R\", \"U'\", \"F\"], \"032147658\": [\"M2\", \"U\", \"M2\", \"U\", \"M'\", \"U2\", \"M2\",", "\"U2\", \"L'\", \"U\", \"R'\", \"U\"], \"076345218\": [\"R'\", \"U\", \"L'\", \"U2\", \"R\", \"U'\", \"L\",", "\"R\", \"U'\", \"R'\", \"U'\", \"R2\"], \"072543618\": [\"M2\", \"U\", \"M2\", \"U2\", \"M2\", \"U\", \"M2\"],", "o = PLLSolver.get_correct_cubie(cube, cubie) orientation.append(str(cubies.index(o))) return ''.join(orientation) def move(self, s, solution): self.cube.move(Move(s)) solution.append(s)", "\"R\", \"U2\", \"R'\", \"F\", \"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F'\", \"R2\", \"U'\"], \"852341670\":", "\"R'\", \"U\", \"R\", \"U'\", \"R\", \"Y'\", \"D'\", \"R2\"], \"812743056\": [\"R2\", \"Y'\", \"D'\", \"R\",", "in range(4): self.move('U', solution) for _ in range(4): self.move('Y', solution) orientation = PLLSolver.get_orientations(self.cube)", "\"R'\", \"U'\"], \"210745638\": [\"L\", \"U2\", \"L'\", \"U2\", \"L\", \"F'\", \"L'\", \"U'\", \"L\", \"U\",", "\"018347652\": [\"R\", \"U\", \"R'\", \"F'\", \"R\", \"U\", \"R'\", \"U'\", \"R'\", \"F\", \"R2\", \"U'\",", "\"Y\", \"D\", \"R2\", \"Y\", \"R\", \"U'\", \"R'\"], \"670145238\": [\"R\", \"U\", \"R'\", \"Y'\", \"R2\",", "for s in PLLSolver.STEPS[orientation]: self.move(s, solution) return solution # Apply shortest and expect", "\"Y\", \"D\", \"R'\", \"U\", \"R\", \"U'\", \"R\", \"Y'\", \"D'\", \"R2\"], \"812743056\": [\"R2\", \"Y'\",", "orientation in PLLSolver.STEPS: for s in PLLSolver.STEPS[orientation]: self.move(s, solution) return solution # Apply", "[\"R'\", \"U'\", \"R\", \"Y\", \"R2\", \"Y\", \"D\", \"R'\", \"U\", \"R\", \"U'\", \"R\", \"Y'\",", "colors = [cube.cubies[c].facings[c].color for c in cubie.replace('U', '')] return cube.search_by_colors('Y', *colors) def solution(self):", "= PLLSolver.get_correct_cubie(cube, cubie) orientation.append(str(cubies.index(o))) return ''.join(orientation) def move(self, s, solution): self.cube.move(Move(s)) solution.append(s) @staticmethod", "[\"R'\", \"U\", \"L'\", \"U2\", \"R\", \"U'\", \"L\", \"R'\", \"U\", \"L'\", \"U2\", \"R\", \"U'\",", "_ in range(4): self.move('U', solution) for _ in range(4): self.move('Y', solution) orientation =", "cubie): colors = [cube.cubies[c].facings[c].color for c in cubie.replace('U', '')] return cube.search_by_colors('Y', *colors) def", "\"U'\", \"R\", \"Y'\", \"D'\", \"R2\"], \"812743056\": [\"R2\", \"Y'\", \"D'\", \"R\", \"U'\", \"R\", \"U\",", "\"018345276\": [\"X'\", \"R\", \"U'\", \"R\", \"D2\", \"R'\", \"U\", \"R\", \"D2\", \"R2\", \"X\"], \"012743658\":", "\"072543618\": [\"M2\", \"U\", \"M2\", \"U2\", \"M2\", \"U\", \"M2\"], \"018543672\": [\"R\", \"U\", \"R'\", \"U'\",", "\"R'\", \"F\", \"R\", \"F\"], \"650143278\": [\"R2\", \"Y\", \"D\", \"R'\", \"U\", \"R'\", \"U'\", \"R\"," ]
[ "import pandas as pd import torch import PIL.Image as Image import torchvision.transforms as", "image_dir = os.path.join(data_dir, 'isic/Images') def main(csv_filename, include_sonic): if include_sonic: new_image_dir = image_dir.replace('Images','ImagesSmallerWithSonic') p", "print('resizing images') for i,image_name in enumerate(image_names): if i % 1000 == 0: t2", "image_name) target = os.path.join(new_image_dir, image_name) #shutil.copyfile(original, target) #print(image_name) img = Image.open(os.path.join(image_dir,image_name)) # tranform", "as Image import torchvision.transforms as transforms import time t = transforms.Compose([transforms.Resize((224,224))]) data_dir =", "'../../data' image_dir = os.path.join(data_dir, 'isic/Images') def main(csv_filename, include_sonic): if include_sonic: new_image_dir = image_dir.replace('Images','ImagesSmallerWithSonic')", "import PIL.Image as Image import torchvision.transforms as transforms import time t = transforms.Compose([transforms.Resize((224,224))])", "= os.path.join(image_dir, image_name) target = os.path.join(new_image_dir, image_name) #shutil.copyfile(original, target) #print(image_name) img = Image.open(os.path.join(image_dir,image_name))", "= os.path.join(data_dir, 'isic/Images') def main(csv_filename, include_sonic): if include_sonic: new_image_dir = image_dir.replace('Images','ImagesSmallerWithSonic') p =", "if include_sonic: new_image_dir = image_dir.replace('Images','ImagesSmallerWithSonic') p = pd.read_csv(os.path.join(data_dir,csv_filename)) else: new_image_dir = image_dir.replace('Images','ImagesSmaller') p", "as transforms import time t = transforms.Compose([transforms.Resize((224,224))]) data_dir = '../../data' image_dir = os.path.join(data_dir,", "i % 1000 == 0: t2 = time.time() print(i, t2-t1) original = os.path.join(image_dir,", "time.time() print('resizing images') for i,image_name in enumerate(image_names): if i % 1000 == 0:", "target) #print(image_name) img = Image.open(os.path.join(image_dir,image_name)) # tranform img_t = t(img).convert(\"RGB\") img_t.save(os.path.join(new_image_dir,image_name),\"JPEG\") if __name__", "original = os.path.join(image_dir, image_name) target = os.path.join(new_image_dir, image_name) #shutil.copyfile(original, target) #print(image_name) img =", "import shutil import pandas as pd import torch import PIL.Image as Image import", "main(csv_filename, include_sonic): if include_sonic: new_image_dir = image_dir.replace('Images','ImagesSmallerWithSonic') p = pd.read_csv(os.path.join(data_dir,csv_filename)) else: new_image_dir =", "= '../../data' image_dir = os.path.join(data_dir, 'isic/Images') def main(csv_filename, include_sonic): if include_sonic: new_image_dir =", "pd.read_csv(os.path.join(data_dir,csv_filename)) else: new_image_dir = image_dir.replace('Images','ImagesSmaller') p = pd.read_csv(os.path.join(data_dir,csv_filename)) image_names = p['image_name'].values if not", "0: t2 = time.time() print(i, t2-t1) original = os.path.join(image_dir, image_name) target = os.path.join(new_image_dir,", "torch import PIL.Image as Image import torchvision.transforms as transforms import time t =", "if i % 1000 == 0: t2 = time.time() print(i, t2-t1) original =", "t2 = time.time() print(i, t2-t1) original = os.path.join(image_dir, image_name) target = os.path.join(new_image_dir, image_name)", "= time.time() print(i, t2-t1) original = os.path.join(image_dir, image_name) target = os.path.join(new_image_dir, image_name) #shutil.copyfile(original,", "t = transforms.Compose([transforms.Resize((224,224))]) data_dir = '../../data' image_dir = os.path.join(data_dir, 'isic/Images') def main(csv_filename, include_sonic):", "',new_image_dir) os.mkdir(new_image_dir) t1 = time.time() print('resizing images') for i,image_name in enumerate(image_names): if i", "image_name) #shutil.copyfile(original, target) #print(image_name) img = Image.open(os.path.join(image_dir,image_name)) # tranform img_t = t(img).convert(\"RGB\") img_t.save(os.path.join(new_image_dir,image_name),\"JPEG\")", "pandas as pd import torch import PIL.Image as Image import torchvision.transforms as transforms", "= time.time() print('resizing images') for i,image_name in enumerate(image_names): if i % 1000 ==", "= pd.read_csv(os.path.join(data_dir,csv_filename)) image_names = p['image_name'].values if not os.path.exists(new_image_dir): print('making ',new_image_dir) os.mkdir(new_image_dir) t1 =", "#shutil.copyfile(original, target) #print(image_name) img = Image.open(os.path.join(image_dir,image_name)) # tranform img_t = t(img).convert(\"RGB\") img_t.save(os.path.join(new_image_dir,image_name),\"JPEG\") if", "= Image.open(os.path.join(image_dir,image_name)) # tranform img_t = t(img).convert(\"RGB\") img_t.save(os.path.join(new_image_dir,image_name),\"JPEG\") if __name__ == '__main__': main(csv_filename='isic/df_with_sonic_age_over_50_id.csv',include_sonic=False)", "os.path.join(new_image_dir, image_name) #shutil.copyfile(original, target) #print(image_name) img = Image.open(os.path.join(image_dir,image_name)) # tranform img_t = t(img).convert(\"RGB\")", "= transforms.Compose([transforms.Resize((224,224))]) data_dir = '../../data' image_dir = os.path.join(data_dir, 'isic/Images') def main(csv_filename, include_sonic): if", "as pd import torch import PIL.Image as Image import torchvision.transforms as transforms import", "time.time() print(i, t2-t1) original = os.path.join(image_dir, image_name) target = os.path.join(new_image_dir, image_name) #shutil.copyfile(original, target)", "print(i, t2-t1) original = os.path.join(image_dir, image_name) target = os.path.join(new_image_dir, image_name) #shutil.copyfile(original, target) #print(image_name)", "import time t = transforms.Compose([transforms.Resize((224,224))]) data_dir = '../../data' image_dir = os.path.join(data_dir, 'isic/Images') def", "def main(csv_filename, include_sonic): if include_sonic: new_image_dir = image_dir.replace('Images','ImagesSmallerWithSonic') p = pd.read_csv(os.path.join(data_dir,csv_filename)) else: new_image_dir", "i,image_name in enumerate(image_names): if i % 1000 == 0: t2 = time.time() print(i,", "image_names = p['image_name'].values if not os.path.exists(new_image_dir): print('making ',new_image_dir) os.mkdir(new_image_dir) t1 = time.time() print('resizing", "images') for i,image_name in enumerate(image_names): if i % 1000 == 0: t2 =", "== 0: t2 = time.time() print(i, t2-t1) original = os.path.join(image_dir, image_name) target =", "= image_dir.replace('Images','ImagesSmallerWithSonic') p = pd.read_csv(os.path.join(data_dir,csv_filename)) else: new_image_dir = image_dir.replace('Images','ImagesSmaller') p = pd.read_csv(os.path.join(data_dir,csv_filename)) image_names", "image_dir.replace('Images','ImagesSmallerWithSonic') p = pd.read_csv(os.path.join(data_dir,csv_filename)) else: new_image_dir = image_dir.replace('Images','ImagesSmaller') p = pd.read_csv(os.path.join(data_dir,csv_filename)) image_names =", "print('making ',new_image_dir) os.mkdir(new_image_dir) t1 = time.time() print('resizing images') for i,image_name in enumerate(image_names): if", "pd.read_csv(os.path.join(data_dir,csv_filename)) image_names = p['image_name'].values if not os.path.exists(new_image_dir): print('making ',new_image_dir) os.mkdir(new_image_dir) t1 = time.time()", "new_image_dir = image_dir.replace('Images','ImagesSmallerWithSonic') p = pd.read_csv(os.path.join(data_dir,csv_filename)) else: new_image_dir = image_dir.replace('Images','ImagesSmaller') p = pd.read_csv(os.path.join(data_dir,csv_filename))", "import torch import PIL.Image as Image import torchvision.transforms as transforms import time t", "img = Image.open(os.path.join(image_dir,image_name)) # tranform img_t = t(img).convert(\"RGB\") img_t.save(os.path.join(new_image_dir,image_name),\"JPEG\") if __name__ == '__main__':", "Image import torchvision.transforms as transforms import time t = transforms.Compose([transforms.Resize((224,224))]) data_dir = '../../data'", "os import shutil import pandas as pd import torch import PIL.Image as Image", "transforms.Compose([transforms.Resize((224,224))]) data_dir = '../../data' image_dir = os.path.join(data_dir, 'isic/Images') def main(csv_filename, include_sonic): if include_sonic:", "= pd.read_csv(os.path.join(data_dir,csv_filename)) else: new_image_dir = image_dir.replace('Images','ImagesSmaller') p = pd.read_csv(os.path.join(data_dir,csv_filename)) image_names = p['image_name'].values if", "PIL.Image as Image import torchvision.transforms as transforms import time t = transforms.Compose([transforms.Resize((224,224))]) data_dir", "enumerate(image_names): if i % 1000 == 0: t2 = time.time() print(i, t2-t1) original", "torchvision.transforms as transforms import time t = transforms.Compose([transforms.Resize((224,224))]) data_dir = '../../data' image_dir =", "include_sonic: new_image_dir = image_dir.replace('Images','ImagesSmallerWithSonic') p = pd.read_csv(os.path.join(data_dir,csv_filename)) else: new_image_dir = image_dir.replace('Images','ImagesSmaller') p =", "image_dir.replace('Images','ImagesSmaller') p = pd.read_csv(os.path.join(data_dir,csv_filename)) image_names = p['image_name'].values if not os.path.exists(new_image_dir): print('making ',new_image_dir) os.mkdir(new_image_dir)", "data_dir = '../../data' image_dir = os.path.join(data_dir, 'isic/Images') def main(csv_filename, include_sonic): if include_sonic: new_image_dir", "p = pd.read_csv(os.path.join(data_dir,csv_filename)) image_names = p['image_name'].values if not os.path.exists(new_image_dir): print('making ',new_image_dir) os.mkdir(new_image_dir) t1", "import os import shutil import pandas as pd import torch import PIL.Image as", "if not os.path.exists(new_image_dir): print('making ',new_image_dir) os.mkdir(new_image_dir) t1 = time.time() print('resizing images') for i,image_name", "% 1000 == 0: t2 = time.time() print(i, t2-t1) original = os.path.join(image_dir, image_name)", "pd import torch import PIL.Image as Image import torchvision.transforms as transforms import time", "os.path.join(data_dir, 'isic/Images') def main(csv_filename, include_sonic): if include_sonic: new_image_dir = image_dir.replace('Images','ImagesSmallerWithSonic') p = pd.read_csv(os.path.join(data_dir,csv_filename))", "not os.path.exists(new_image_dir): print('making ',new_image_dir) os.mkdir(new_image_dir) t1 = time.time() print('resizing images') for i,image_name in", "time t = transforms.Compose([transforms.Resize((224,224))]) data_dir = '../../data' image_dir = os.path.join(data_dir, 'isic/Images') def main(csv_filename,", "in enumerate(image_names): if i % 1000 == 0: t2 = time.time() print(i, t2-t1)", "import torchvision.transforms as transforms import time t = transforms.Compose([transforms.Resize((224,224))]) data_dir = '../../data' image_dir", "transforms import time t = transforms.Compose([transforms.Resize((224,224))]) data_dir = '../../data' image_dir = os.path.join(data_dir, 'isic/Images')", "new_image_dir = image_dir.replace('Images','ImagesSmaller') p = pd.read_csv(os.path.join(data_dir,csv_filename)) image_names = p['image_name'].values if not os.path.exists(new_image_dir): print('making", "p['image_name'].values if not os.path.exists(new_image_dir): print('making ',new_image_dir) os.mkdir(new_image_dir) t1 = time.time() print('resizing images') for", "= os.path.join(new_image_dir, image_name) #shutil.copyfile(original, target) #print(image_name) img = Image.open(os.path.join(image_dir,image_name)) # tranform img_t =", "os.mkdir(new_image_dir) t1 = time.time() print('resizing images') for i,image_name in enumerate(image_names): if i %", "p = pd.read_csv(os.path.join(data_dir,csv_filename)) else: new_image_dir = image_dir.replace('Images','ImagesSmaller') p = pd.read_csv(os.path.join(data_dir,csv_filename)) image_names = p['image_name'].values", "1000 == 0: t2 = time.time() print(i, t2-t1) original = os.path.join(image_dir, image_name) target", "'isic/Images') def main(csv_filename, include_sonic): if include_sonic: new_image_dir = image_dir.replace('Images','ImagesSmallerWithSonic') p = pd.read_csv(os.path.join(data_dir,csv_filename)) else:", "t2-t1) original = os.path.join(image_dir, image_name) target = os.path.join(new_image_dir, image_name) #shutil.copyfile(original, target) #print(image_name) img", "= p['image_name'].values if not os.path.exists(new_image_dir): print('making ',new_image_dir) os.mkdir(new_image_dir) t1 = time.time() print('resizing images')", "= image_dir.replace('Images','ImagesSmaller') p = pd.read_csv(os.path.join(data_dir,csv_filename)) image_names = p['image_name'].values if not os.path.exists(new_image_dir): print('making ',new_image_dir)", "target = os.path.join(new_image_dir, image_name) #shutil.copyfile(original, target) #print(image_name) img = Image.open(os.path.join(image_dir,image_name)) # tranform img_t", "os.path.join(image_dir, image_name) target = os.path.join(new_image_dir, image_name) #shutil.copyfile(original, target) #print(image_name) img = Image.open(os.path.join(image_dir,image_name)) #", "os.path.exists(new_image_dir): print('making ',new_image_dir) os.mkdir(new_image_dir) t1 = time.time() print('resizing images') for i,image_name in enumerate(image_names):", "for i,image_name in enumerate(image_names): if i % 1000 == 0: t2 = time.time()", "else: new_image_dir = image_dir.replace('Images','ImagesSmaller') p = pd.read_csv(os.path.join(data_dir,csv_filename)) image_names = p['image_name'].values if not os.path.exists(new_image_dir):", "include_sonic): if include_sonic: new_image_dir = image_dir.replace('Images','ImagesSmallerWithSonic') p = pd.read_csv(os.path.join(data_dir,csv_filename)) else: new_image_dir = image_dir.replace('Images','ImagesSmaller')", "shutil import pandas as pd import torch import PIL.Image as Image import torchvision.transforms", "t1 = time.time() print('resizing images') for i,image_name in enumerate(image_names): if i % 1000", "#print(image_name) img = Image.open(os.path.join(image_dir,image_name)) # tranform img_t = t(img).convert(\"RGB\") img_t.save(os.path.join(new_image_dir,image_name),\"JPEG\") if __name__ ==" ]
[ "\"\"\" # revision identifiers, used by Alembic. revision = '4c4c7189593e' down_revision = '4b4e6d96c630'", "### def downgrade(): ### commands auto generated by Alembic - please adjust! ###", "by Alembic - please adjust! ### op.drop_constraint('organization_user_roles_name_german_key', 'organization_user_roles', type_='unique') op.drop_constraint('organization_user_roles_name_key', 'organization_user_roles', type_='unique') op.drop_column('organization_user_roles',", "'4b4e6d96c630' from alembic import op import sqlalchemy as sa def upgrade(): ### commands", "'organization_user_roles', type_='unique') op.drop_constraint('organization_user_roles_name_key', 'organization_user_roles', type_='unique') op.drop_column('organization_user_roles', 'deleted') op.drop_column('organization_user_roles', 'name_german') ### end Alembic commands", "\"\"\"empty message Revision ID: 4c4c7189593e Revises: 4b4e6d96c630 Create Date: 2017-04-04 12:37:27.512719 \"\"\" #", "sa def upgrade(): ### commands auto generated by Alembic - please adjust! ###", "### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic", "4c4c7189593e Revises: 4b4e6d96c630 Create Date: 2017-04-04 12:37:27.512719 \"\"\" # revision identifiers, used by", "generated by Alembic - please adjust! ### op.drop_constraint('organization_user_roles_name_german_key', 'organization_user_roles', type_='unique') op.drop_constraint('organization_user_roles_name_key', 'organization_user_roles', type_='unique')", "Create Date: 2017-04-04 12:37:27.512719 \"\"\" # revision identifiers, used by Alembic. revision =", "commands auto generated by Alembic - please adjust! ### op.drop_constraint('organization_user_roles_name_german_key', 'organization_user_roles', type_='unique') op.drop_constraint('organization_user_roles_name_key',", "from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto", "auto generated by Alembic - please adjust! ### op.drop_constraint('organization_user_roles_name_german_key', 'organization_user_roles', type_='unique') op.drop_constraint('organization_user_roles_name_key', 'organization_user_roles',", "op.drop_column('organization_user_roles', 'name_german') ### end Alembic commands ### def downgrade(): ### commands auto generated", "revision identifiers, used by Alembic. revision = '4c4c7189593e' down_revision = '4b4e6d96c630' from alembic", "sa.VARCHAR(length=255), autoincrement=False, nullable=False)) op.add_column('organization_user_roles', sa.Column('deleted', sa.BOOLEAN(), autoincrement=False, nullable=True)) op.create_unique_constraint('organization_user_roles_name_key', 'organization_user_roles', ['name']) op.create_unique_constraint('organization_user_roles_name_german_key', 'organization_user_roles',", "ID: 4c4c7189593e Revises: 4b4e6d96c630 Create Date: 2017-04-04 12:37:27.512719 \"\"\" # revision identifiers, used", "'organization_user_roles', type_='unique') op.drop_column('organization_user_roles', 'deleted') op.drop_column('organization_user_roles', 'name_german') ### end Alembic commands ### def downgrade():", "type_='unique') op.drop_column('organization_user_roles', 'deleted') op.drop_column('organization_user_roles', 'name_german') ### end Alembic commands ### def downgrade(): ###", "<filename>misc/migrations/versions/4c4c7189593e_.py \"\"\"empty message Revision ID: 4c4c7189593e Revises: 4b4e6d96c630 Create Date: 2017-04-04 12:37:27.512719 \"\"\"", "- please adjust! ### op.drop_constraint('organization_user_roles_name_german_key', 'organization_user_roles', type_='unique') op.drop_constraint('organization_user_roles_name_key', 'organization_user_roles', type_='unique') op.drop_column('organization_user_roles', 'deleted') op.drop_column('organization_user_roles',", "commands ### def downgrade(): ### commands auto generated by Alembic - please adjust!", "### op.add_column('organization_user_roles', sa.Column('name_german', sa.VARCHAR(length=255), autoincrement=False, nullable=False)) op.add_column('organization_user_roles', sa.Column('deleted', sa.BOOLEAN(), autoincrement=False, nullable=True)) op.create_unique_constraint('organization_user_roles_name_key', 'organization_user_roles',", "Alembic. revision = '4c4c7189593e' down_revision = '4b4e6d96c630' from alembic import op import sqlalchemy", "op.add_column('organization_user_roles', sa.Column('deleted', sa.BOOLEAN(), autoincrement=False, nullable=True)) op.create_unique_constraint('organization_user_roles_name_key', 'organization_user_roles', ['name']) op.create_unique_constraint('organization_user_roles_name_german_key', 'organization_user_roles', ['name_german']) ### end", "message Revision ID: 4c4c7189593e Revises: 4b4e6d96c630 Create Date: 2017-04-04 12:37:27.512719 \"\"\" # revision", "commands auto generated by Alembic - please adjust! ### op.add_column('organization_user_roles', sa.Column('name_german', sa.VARCHAR(length=255), autoincrement=False,", "sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please", "by Alembic. revision = '4c4c7189593e' down_revision = '4b4e6d96c630' from alembic import op import", "used by Alembic. revision = '4c4c7189593e' down_revision = '4b4e6d96c630' from alembic import op", "4b4e6d96c630 Create Date: 2017-04-04 12:37:27.512719 \"\"\" # revision identifiers, used by Alembic. revision", "downgrade(): ### commands auto generated by Alembic - please adjust! ### op.add_column('organization_user_roles', sa.Column('name_german',", "type_='unique') op.drop_constraint('organization_user_roles_name_key', 'organization_user_roles', type_='unique') op.drop_column('organization_user_roles', 'deleted') op.drop_column('organization_user_roles', 'name_german') ### end Alembic commands ###", "def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.add_column('organization_user_roles',", "as sa def upgrade(): ### commands auto generated by Alembic - please adjust!", "### commands auto generated by Alembic - please adjust! ### op.drop_constraint('organization_user_roles_name_german_key', 'organization_user_roles', type_='unique')", "import op import sqlalchemy as sa def upgrade(): ### commands auto generated by", "identifiers, used by Alembic. revision = '4c4c7189593e' down_revision = '4b4e6d96c630' from alembic import", "# revision identifiers, used by Alembic. revision = '4c4c7189593e' down_revision = '4b4e6d96c630' from", "adjust! ### op.drop_constraint('organization_user_roles_name_german_key', 'organization_user_roles', type_='unique') op.drop_constraint('organization_user_roles_name_key', 'organization_user_roles', type_='unique') op.drop_column('organization_user_roles', 'deleted') op.drop_column('organization_user_roles', 'name_german') ###", "please adjust! ### op.add_column('organization_user_roles', sa.Column('name_german', sa.VARCHAR(length=255), autoincrement=False, nullable=False)) op.add_column('organization_user_roles', sa.Column('deleted', sa.BOOLEAN(), autoincrement=False, nullable=True))", "sa.Column('deleted', sa.BOOLEAN(), autoincrement=False, nullable=True)) op.create_unique_constraint('organization_user_roles_name_key', 'organization_user_roles', ['name']) op.create_unique_constraint('organization_user_roles_name_german_key', 'organization_user_roles', ['name_german']) ### end Alembic", "op.add_column('organization_user_roles', sa.Column('name_german', sa.VARCHAR(length=255), autoincrement=False, nullable=False)) op.add_column('organization_user_roles', sa.Column('deleted', sa.BOOLEAN(), autoincrement=False, nullable=True)) op.create_unique_constraint('organization_user_roles_name_key', 'organization_user_roles', ['name'])", "'4c4c7189593e' down_revision = '4b4e6d96c630' from alembic import op import sqlalchemy as sa def", "12:37:27.512719 \"\"\" # revision identifiers, used by Alembic. revision = '4c4c7189593e' down_revision =", "op.drop_column('organization_user_roles', 'deleted') op.drop_column('organization_user_roles', 'name_german') ### end Alembic commands ### def downgrade(): ### commands", "op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic", "auto generated by Alembic - please adjust! ### op.add_column('organization_user_roles', sa.Column('name_german', sa.VARCHAR(length=255), autoincrement=False, nullable=False))", "sa.Column('name_german', sa.VARCHAR(length=255), autoincrement=False, nullable=False)) op.add_column('organization_user_roles', sa.Column('deleted', sa.BOOLEAN(), autoincrement=False, nullable=True)) op.create_unique_constraint('organization_user_roles_name_key', 'organization_user_roles', ['name']) op.create_unique_constraint('organization_user_roles_name_german_key',", "Revises: 4b4e6d96c630 Create Date: 2017-04-04 12:37:27.512719 \"\"\" # revision identifiers, used by Alembic.", "### op.drop_constraint('organization_user_roles_name_german_key', 'organization_user_roles', type_='unique') op.drop_constraint('organization_user_roles_name_key', 'organization_user_roles', type_='unique') op.drop_column('organization_user_roles', 'deleted') op.drop_column('organization_user_roles', 'name_german') ### end", "2017-04-04 12:37:27.512719 \"\"\" # revision identifiers, used by Alembic. revision = '4c4c7189593e' down_revision", "def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_constraint('organization_user_roles_name_german_key',", "Alembic - please adjust! ### op.add_column('organization_user_roles', sa.Column('name_german', sa.VARCHAR(length=255), autoincrement=False, nullable=False)) op.add_column('organization_user_roles', sa.Column('deleted', sa.BOOLEAN(),", "op.drop_constraint('organization_user_roles_name_german_key', 'organization_user_roles', type_='unique') op.drop_constraint('organization_user_roles_name_key', 'organization_user_roles', type_='unique') op.drop_column('organization_user_roles', 'deleted') op.drop_column('organization_user_roles', 'name_german') ### end Alembic", "by Alembic - please adjust! ### op.add_column('organization_user_roles', sa.Column('name_german', sa.VARCHAR(length=255), autoincrement=False, nullable=False)) op.add_column('organization_user_roles', sa.Column('deleted',", "Alembic - please adjust! ### op.drop_constraint('organization_user_roles_name_german_key', 'organization_user_roles', type_='unique') op.drop_constraint('organization_user_roles_name_key', 'organization_user_roles', type_='unique') op.drop_column('organization_user_roles', 'deleted')", "end Alembic commands ### def downgrade(): ### commands auto generated by Alembic -", "Date: 2017-04-04 12:37:27.512719 \"\"\" # revision identifiers, used by Alembic. revision = '4c4c7189593e'", "= '4b4e6d96c630' from alembic import op import sqlalchemy as sa def upgrade(): ###", "revision = '4c4c7189593e' down_revision = '4b4e6d96c630' from alembic import op import sqlalchemy as", "op.drop_constraint('organization_user_roles_name_key', 'organization_user_roles', type_='unique') op.drop_column('organization_user_roles', 'deleted') op.drop_column('organization_user_roles', 'name_german') ### end Alembic commands ### def", "generated by Alembic - please adjust! ### op.add_column('organization_user_roles', sa.Column('name_german', sa.VARCHAR(length=255), autoincrement=False, nullable=False)) op.add_column('organization_user_roles',", "- please adjust! ### op.add_column('organization_user_roles', sa.Column('name_german', sa.VARCHAR(length=255), autoincrement=False, nullable=False)) op.add_column('organization_user_roles', sa.Column('deleted', sa.BOOLEAN(), autoincrement=False,", "adjust! ### op.add_column('organization_user_roles', sa.Column('name_german', sa.VARCHAR(length=255), autoincrement=False, nullable=False)) op.add_column('organization_user_roles', sa.Column('deleted', sa.BOOLEAN(), autoincrement=False, nullable=True)) op.create_unique_constraint('organization_user_roles_name_key',", "= '4c4c7189593e' down_revision = '4b4e6d96c630' from alembic import op import sqlalchemy as sa", "autoincrement=False, nullable=False)) op.add_column('organization_user_roles', sa.Column('deleted', sa.BOOLEAN(), autoincrement=False, nullable=True)) op.create_unique_constraint('organization_user_roles_name_key', 'organization_user_roles', ['name']) op.create_unique_constraint('organization_user_roles_name_german_key', 'organization_user_roles', ['name_german'])", "Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please", "'name_german') ### end Alembic commands ### def downgrade(): ### commands auto generated by", "sa.BOOLEAN(), autoincrement=False, nullable=True)) op.create_unique_constraint('organization_user_roles_name_key', 'organization_user_roles', ['name']) op.create_unique_constraint('organization_user_roles_name_german_key', 'organization_user_roles', ['name_german']) ### end Alembic commands", "Revision ID: 4c4c7189593e Revises: 4b4e6d96c630 Create Date: 2017-04-04 12:37:27.512719 \"\"\" # revision identifiers,", "upgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_constraint('organization_user_roles_name_german_key', 'organization_user_roles',", "autoincrement=False, nullable=True)) op.create_unique_constraint('organization_user_roles_name_key', 'organization_user_roles', ['name']) op.create_unique_constraint('organization_user_roles_name_german_key', 'organization_user_roles', ['name_german']) ### end Alembic commands ###", "'deleted') op.drop_column('organization_user_roles', 'name_german') ### end Alembic commands ### def downgrade(): ### commands auto", "please adjust! ### op.drop_constraint('organization_user_roles_name_german_key', 'organization_user_roles', type_='unique') op.drop_constraint('organization_user_roles_name_key', 'organization_user_roles', type_='unique') op.drop_column('organization_user_roles', 'deleted') op.drop_column('organization_user_roles', 'name_german')", "alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated", "import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic -", "### commands auto generated by Alembic - please adjust! ### op.add_column('organization_user_roles', sa.Column('name_german', sa.VARCHAR(length=255),", "nullable=False)) op.add_column('organization_user_roles', sa.Column('deleted', sa.BOOLEAN(), autoincrement=False, nullable=True)) op.create_unique_constraint('organization_user_roles_name_key', 'organization_user_roles', ['name']) op.create_unique_constraint('organization_user_roles_name_german_key', 'organization_user_roles', ['name_german']) ###", "down_revision = '4b4e6d96c630' from alembic import op import sqlalchemy as sa def upgrade():" ]
[ "with wall if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor() >", "-280: scoreboard.reset() snake.reset() # Detect collision with tail for segment in snake.segments[1:]: if", "food if snake.head.distance(food) < 15: food.refresh() snake.extent() scoreboard.increase_score() # Detect collision with wall", "screener.onkey(snake.left, \"Left\") screener.onkey(snake.right, \"Right\") game_is_on = True while game_is_on: screener.update() time.sleep(.1) snake.move() #", "turtle import Screen from snake import Snake from food import Food from scoreboard", "import Food from scoreboard import Score import time screener = Screen() screener.setup(width=600, height=600)", "screener.bgcolor(\"black\") screener.title(\"SNAKE GAME\") screener.tracer(0) snake = Snake() food = Food() scoreboard = Score()", "from food import Food from scoreboard import Score import time screener = Screen()", "Collision with food if snake.head.distance(food) < 15: food.refresh() snake.extent() scoreboard.increase_score() # Detect collision", "\"Up\") screener.onkey(snake.down, \"Down\") screener.onkey(snake.left, \"Left\") screener.onkey(snake.right, \"Right\") game_is_on = True while game_is_on: screener.update()", "scoreboard.increase_score() # Detect collision with wall if snake.head.xcor() > 280 or snake.head.xcor() <", "screener.onkey(snake.down, \"Down\") screener.onkey(snake.left, \"Left\") screener.onkey(snake.right, \"Right\") game_is_on = True while game_is_on: screener.update() time.sleep(.1)", "import time screener = Screen() screener.setup(width=600, height=600) screener.bgcolor(\"black\") screener.title(\"SNAKE GAME\") screener.tracer(0) snake =", "280 or snake.head.ycor() < -280: scoreboard.reset() snake.reset() # Detect collision with tail for", "with tail for segment in snake.segments[1:]: if segment == snake.head: pass elif snake.head.distance(segment)", "snake.extent() scoreboard.increase_score() # Detect collision with wall if snake.head.xcor() > 280 or snake.head.xcor()", "= Food() scoreboard = Score() screener.listen() screener.onkey(snake.up, \"Up\") screener.onkey(snake.down, \"Down\") screener.onkey(snake.left, \"Left\") screener.onkey(snake.right,", "snake.segments[1:]: if segment == snake.head: pass elif snake.head.distance(segment) < 10: scoreboard.reset() snake.reset() screener.exitonclick()", "if snake.head.distance(food) < 15: food.refresh() snake.extent() scoreboard.increase_score() # Detect collision with wall if", "snake = Snake() food = Food() scoreboard = Score() screener.listen() screener.onkey(snake.up, \"Up\") screener.onkey(snake.down,", "\"Left\") screener.onkey(snake.right, \"Right\") game_is_on = True while game_is_on: screener.update() time.sleep(.1) snake.move() # Collision", "with food if snake.head.distance(food) < 15: food.refresh() snake.extent() scoreboard.increase_score() # Detect collision with", "= Snake() food = Food() scoreboard = Score() screener.listen() screener.onkey(snake.up, \"Up\") screener.onkey(snake.down, \"Down\")", "or snake.head.ycor() < -280: scoreboard.reset() snake.reset() # Detect collision with tail for segment", "= Score() screener.listen() screener.onkey(snake.up, \"Up\") screener.onkey(snake.down, \"Down\") screener.onkey(snake.left, \"Left\") screener.onkey(snake.right, \"Right\") game_is_on =", "height=600) screener.bgcolor(\"black\") screener.title(\"SNAKE GAME\") screener.tracer(0) snake = Snake() food = Food() scoreboard =", "while game_is_on: screener.update() time.sleep(.1) snake.move() # Collision with food if snake.head.distance(food) < 15:", "Screen from snake import Snake from food import Food from scoreboard import Score", "screener.update() time.sleep(.1) snake.move() # Collision with food if snake.head.distance(food) < 15: food.refresh() snake.extent()", "Detect collision with wall if snake.head.xcor() > 280 or snake.head.xcor() < -280 or", "Screen() screener.setup(width=600, height=600) screener.bgcolor(\"black\") screener.title(\"SNAKE GAME\") screener.tracer(0) snake = Snake() food = Food()", "snake.head.ycor() > 280 or snake.head.ycor() < -280: scoreboard.reset() snake.reset() # Detect collision with", "280 or snake.head.xcor() < -280 or snake.head.ycor() > 280 or snake.head.ycor() < -280:", "snake import Snake from food import Food from scoreboard import Score import time", "food.refresh() snake.extent() scoreboard.increase_score() # Detect collision with wall if snake.head.xcor() > 280 or", "snake.head.distance(food) < 15: food.refresh() snake.extent() scoreboard.increase_score() # Detect collision with wall if snake.head.xcor()", "time.sleep(.1) snake.move() # Collision with food if snake.head.distance(food) < 15: food.refresh() snake.extent() scoreboard.increase_score()", "screener.listen() screener.onkey(snake.up, \"Up\") screener.onkey(snake.down, \"Down\") screener.onkey(snake.left, \"Left\") screener.onkey(snake.right, \"Right\") game_is_on = True while", "snake.head.ycor() < -280: scoreboard.reset() snake.reset() # Detect collision with tail for segment in", "screener.onkey(snake.up, \"Up\") screener.onkey(snake.down, \"Down\") screener.onkey(snake.left, \"Left\") screener.onkey(snake.right, \"Right\") game_is_on = True while game_is_on:", "game_is_on = True while game_is_on: screener.update() time.sleep(.1) snake.move() # Collision with food if", "if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor() > 280 or", "scoreboard.reset() snake.reset() # Detect collision with tail for segment in snake.segments[1:]: if segment", "import Score import time screener = Screen() screener.setup(width=600, height=600) screener.bgcolor(\"black\") screener.title(\"SNAKE GAME\") screener.tracer(0)", "Score() screener.listen() screener.onkey(snake.up, \"Up\") screener.onkey(snake.down, \"Down\") screener.onkey(snake.left, \"Left\") screener.onkey(snake.right, \"Right\") game_is_on = True", "in snake.segments[1:]: if segment == snake.head: pass elif snake.head.distance(segment) < 10: scoreboard.reset() snake.reset()", "food import Food from scoreboard import Score import time screener = Screen() screener.setup(width=600,", "or snake.head.xcor() < -280 or snake.head.ycor() > 280 or snake.head.ycor() < -280: scoreboard.reset()", "import Snake from food import Food from scoreboard import Score import time screener", "# Collision with food if snake.head.distance(food) < 15: food.refresh() snake.extent() scoreboard.increase_score() # Detect", "collision with tail for segment in snake.segments[1:]: if segment == snake.head: pass elif", "-280 or snake.head.ycor() > 280 or snake.head.ycor() < -280: scoreboard.reset() snake.reset() # Detect", "screener.title(\"SNAKE GAME\") screener.tracer(0) snake = Snake() food = Food() scoreboard = Score() screener.listen()", "or snake.head.ycor() > 280 or snake.head.ycor() < -280: scoreboard.reset() snake.reset() # Detect collision", "snake.head.xcor() < -280 or snake.head.ycor() > 280 or snake.head.ycor() < -280: scoreboard.reset() snake.reset()", "# Detect collision with wall if snake.head.xcor() > 280 or snake.head.xcor() < -280", "Snake() food = Food() scoreboard = Score() screener.listen() screener.onkey(snake.up, \"Up\") screener.onkey(snake.down, \"Down\") screener.onkey(snake.left,", "from scoreboard import Score import time screener = Screen() screener.setup(width=600, height=600) screener.bgcolor(\"black\") screener.title(\"SNAKE", "snake.move() # Collision with food if snake.head.distance(food) < 15: food.refresh() snake.extent() scoreboard.increase_score() #", "screener.setup(width=600, height=600) screener.bgcolor(\"black\") screener.title(\"SNAKE GAME\") screener.tracer(0) snake = Snake() food = Food() scoreboard", "= True while game_is_on: screener.update() time.sleep(.1) snake.move() # Collision with food if snake.head.distance(food)", "food = Food() scoreboard = Score() screener.listen() screener.onkey(snake.up, \"Up\") screener.onkey(snake.down, \"Down\") screener.onkey(snake.left, \"Left\")", "15: food.refresh() snake.extent() scoreboard.increase_score() # Detect collision with wall if snake.head.xcor() > 280", "from snake import Snake from food import Food from scoreboard import Score import", "screener = Screen() screener.setup(width=600, height=600) screener.bgcolor(\"black\") screener.title(\"SNAKE GAME\") screener.tracer(0) snake = Snake() food", "for segment in snake.segments[1:]: if segment == snake.head: pass elif snake.head.distance(segment) < 10:", "True while game_is_on: screener.update() time.sleep(.1) snake.move() # Collision with food if snake.head.distance(food) <", "> 280 or snake.head.ycor() < -280: scoreboard.reset() snake.reset() # Detect collision with tail", "Food() scoreboard = Score() screener.listen() screener.onkey(snake.up, \"Up\") screener.onkey(snake.down, \"Down\") screener.onkey(snake.left, \"Left\") screener.onkey(snake.right, \"Right\")", "collision with wall if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor()", "< -280 or snake.head.ycor() > 280 or snake.head.ycor() < -280: scoreboard.reset() snake.reset() #", "from turtle import Screen from snake import Snake from food import Food from", "Food from scoreboard import Score import time screener = Screen() screener.setup(width=600, height=600) screener.bgcolor(\"black\")", "segment in snake.segments[1:]: if segment == snake.head: pass elif snake.head.distance(segment) < 10: scoreboard.reset()", "GAME\") screener.tracer(0) snake = Snake() food = Food() scoreboard = Score() screener.listen() screener.onkey(snake.up,", "Detect collision with tail for segment in snake.segments[1:]: if segment == snake.head: pass", "snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor() > 280 or snake.head.ycor()", "scoreboard import Score import time screener = Screen() screener.setup(width=600, height=600) screener.bgcolor(\"black\") screener.title(\"SNAKE GAME\")", "< 15: food.refresh() snake.extent() scoreboard.increase_score() # Detect collision with wall if snake.head.xcor() >", "\"Down\") screener.onkey(snake.left, \"Left\") screener.onkey(snake.right, \"Right\") game_is_on = True while game_is_on: screener.update() time.sleep(.1) snake.move()", "screener.tracer(0) snake = Snake() food = Food() scoreboard = Score() screener.listen() screener.onkey(snake.up, \"Up\")", "= Screen() screener.setup(width=600, height=600) screener.bgcolor(\"black\") screener.title(\"SNAKE GAME\") screener.tracer(0) snake = Snake() food =", "> 280 or snake.head.xcor() < -280 or snake.head.ycor() > 280 or snake.head.ycor() <", "wall if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor() > 280", "game_is_on: screener.update() time.sleep(.1) snake.move() # Collision with food if snake.head.distance(food) < 15: food.refresh()", "scoreboard = Score() screener.listen() screener.onkey(snake.up, \"Up\") screener.onkey(snake.down, \"Down\") screener.onkey(snake.left, \"Left\") screener.onkey(snake.right, \"Right\") game_is_on", "\"Right\") game_is_on = True while game_is_on: screener.update() time.sleep(.1) snake.move() # Collision with food", "snake.reset() # Detect collision with tail for segment in snake.segments[1:]: if segment ==", "tail for segment in snake.segments[1:]: if segment == snake.head: pass elif snake.head.distance(segment) <", "< -280: scoreboard.reset() snake.reset() # Detect collision with tail for segment in snake.segments[1:]:", "import Screen from snake import Snake from food import Food from scoreboard import", "screener.onkey(snake.right, \"Right\") game_is_on = True while game_is_on: screener.update() time.sleep(.1) snake.move() # Collision with", "Snake from food import Food from scoreboard import Score import time screener =", "# Detect collision with tail for segment in snake.segments[1:]: if segment == snake.head:", "Score import time screener = Screen() screener.setup(width=600, height=600) screener.bgcolor(\"black\") screener.title(\"SNAKE GAME\") screener.tracer(0) snake", "time screener = Screen() screener.setup(width=600, height=600) screener.bgcolor(\"black\") screener.title(\"SNAKE GAME\") screener.tracer(0) snake = Snake()" ]
[ "\"Count\" class ReasonCode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The reason for the restriction. \"\"\" NOT_SPECIFIED =", "for the workspace. \"\"\" ENABLED = \"Enabled\" DISABLED = \"Disabled\" class NodeState(with_metaclass(_CaseInsensitiveEnumMeta, str,", "removed from the compute. \"\"\" STEADY = \"Steady\" RESIZING = \"Resizing\" class ApplicationSharingPolicy(with_metaclass(_CaseInsensitiveEnumMeta,", "no operations are being performed on the compute to change the number of", "INVALID_VM_FAMILY_NAME = \"InvalidVMFamilyName\" OPERATION_NOT_SUPPORTED_FOR_SKU = \"OperationNotSupportedForSku\" OPERATION_NOT_ENABLED_FOR_REGION = \"OperationNotEnabledForRegion\" class UnderlyingResourceAction(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):", "str, Enum)): \"\"\"The private endpoint connection status. \"\"\" PENDING = \"Pending\" APPROVED =", "Machine priority \"\"\" DEDICATED = \"Dedicated\" LOW_PRIORITY = \"LowPriority\" class VMTier(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):", "current deployment state of workspace resource. The provisioningState is to indicate states for", "OneHour \"\"\" ONE_HOUR = \"OneHour\" class UsageUnit(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"An enum describing the", "\"Succeeded\" FAILED = \"Failed\" CANCELED = \"Canceled\" class QuotaUnit(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"An enum", "SUCCEEDED = \"Succeeded\" CREATING = \"Creating\" DELETING = \"Deleting\" FAILED = \"Failed\" class", "= \"CreateFailed\" DELETING = \"Deleting\" RUNNING = \"Running\" RESTARTING = \"Restarting\" JOB_RUNNING =", "the public ssh port is closed on all nodes of the cluster. Enabled", "compute to change the number of compute nodes. resizing - Indicates that the", "DELETE_FAILED = \"DeleteFailed\" class PrivateEndpointConnectionProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The current provisioning state. \"\"\" SUCCEEDED", "\"LowPriority\" class VMTier(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The type of the VM. \"\"\" STANDARD =", "= \"Enabled\" DISABLED = \"Disabled\" NOT_SPECIFIED = \"NotSpecified\" class ResourceIdentityType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The", "ONE_HOUR = \"OneHour\" class UsageUnit(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"An enum describing the unit of", "DISABLED = \"Disabled\" NOT_SPECIFIED = \"NotSpecified\" class ResourceIdentityType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The identity type.", "\"OperationNotSupportedForSku\" OPERATION_NOT_ENABLED_FOR_REGION = \"OperationNotEnabledForRegion\" class UnderlyingResourceAction(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): DELETE = \"Delete\" DETACH =", "= \"Enabled\" DISABLED = \"Disabled\" class SslConfigurationStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Enable or disable ssl", "enum class' __dict__ in order to support `name` and `value` being both properties", "role. \"\"\" PERSONAL = \"Personal\" SHARED = \"Shared\" class BillingCurrency(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Three", "\"ReimageFailed\" DELETE_FAILED = \"DeleteFailed\" class PrivateEndpointConnectionProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The current provisioning state. \"\"\"", "specified VM price. Example: OneHour \"\"\" ONE_HOUR = \"OneHour\" class UsageUnit(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):", "in the class' __dict__) and enum members themselves. \"\"\" try: return cls._member_map_[name.upper()] except", "any workspace user can access applications on this instance depending on his/her assigned", "DEDICATED = \"Dedicated\" LOW_PRIORITY = \"LowPriority\" class VMTier(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The type of", "return super().__getitem__(name.upper()) def __getattr__(cls, name): \"\"\"Return the enum member matching `name` We use", "enters this state when it is created and when no operations are being", "currency of the VM price. Example: USD \"\"\" USD = \"USD\" class ComputeInstanceState(with_metaclass(_CaseInsensitiveEnumMeta,", "RESTART = \"Restart\" REIMAGE = \"Reimage\" DELETE = \"Delete\" class OperationStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):", "\"preparing\" UNUSABLE = \"unusable\" LEAVING = \"leaving\" PREEMPTED = \"preempted\" class OperationName(with_metaclass(_CaseInsensitiveEnumMeta, str,", "\"\"\" AKS = \"AKS\" AML_COMPUTE = \"AmlCompute\" COMPUTE_INSTANCE = \"ComputeInstance\" DATA_FACTORY = \"DataFactory\"", "str, Enum)): \"\"\"Indicates whether or not the encryption is enabled for the workspace.", "of workspace resource. The provisioningState is to indicate states for resource provisioning. \"\"\"", "on this compute instance among users of parent workspace. If Personal, only the", "update workspace quota. \"\"\" UNDEFINED = \"Undefined\" SUCCESS = \"Success\" FAILURE = \"Failure\"", "APPROVED = \"Approved\" REJECTED = \"Rejected\" DISCONNECTED = \"Disconnected\" TIMEOUT = \"Timeout\" class", "\"\"\"Return the enum member matching `name` We use __getattr__ instead of descriptors or", "the unit of usage measurement. \"\"\" COUNT = \"Count\" class VMPriceOSType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):", "ssh port is closed on all nodes of the cluster if VNet is", "\"\"\"Enable or disable ssl for scoring \"\"\" DISABLED = \"Disabled\" ENABLED = \"Enabled\"", "\"Linux\" WINDOWS = \"Windows\" class VmPriority(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Virtual Machine priority \"\"\" DEDICATED", "`name` We use __getattr__ instead of descriptors or inserting into the enum class'", "policy if applicable. \"\"\" ENABLED = \"Enabled\" DISABLED = \"Disabled\" class SslConfigurationStatus(with_metaclass(_CaseInsensitiveEnumMeta, str,", "and enum members themselves. \"\"\" try: return cls._member_map_[name.upper()] except KeyError: raise AttributeError(name) class", "applicable. \"\"\" ENABLED = \"Enabled\" DISABLED = \"Disabled\" class SslConfigurationStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Enable", "SETTING_UP = \"SettingUp\" SETUP_FAILED = \"SetupFailed\" STARTING = \"Starting\" STOPPED = \"Stopped\" STOPPING", "into the enum class' __dict__ in order to support `name` and `value` being", "FAILED = \"Failed\" class PrivateEndpointServiceConnectionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The private endpoint connection status. \"\"\"", "priority \"\"\" DEDICATED = \"Dedicated\" LOW_PRIORITY = \"LowPriority\" class VMTier(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The", "\"OperationNotEnabledForRegion\" class UnderlyingResourceAction(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): DELETE = \"Delete\" DETACH = \"Detach\" class UnitOfMeasure(with_metaclass(_CaseInsensitiveEnumMeta,", "OperationName(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Name of the last operation. \"\"\" CREATE = \"Create\" START", "users of parent workspace. If Personal, only the creator can access applications on", "\"preempted\" class OperationName(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Name of the last operation. \"\"\" CREATE =", "\"Enabled\" class Status(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Status of update workspace quota. \"\"\" UNDEFINED =", "class VmPriority(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Virtual Machine priority \"\"\" DEDICATED = \"Dedicated\" LOW_PRIORITY =", "class QuotaUnit(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"An enum describing the unit of quota measurement. \"\"\"", "UNUSABLE = \"Unusable\" class ComputeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The type of compute \"\"\" AKS", "cause incorrect behavior and will be lost if the code is regenerated. #", "name): return super().__getitem__(name.upper()) def __getattr__(cls, name): \"\"\"Return the enum member matching `name` We", "default only during cluster creation time, after creation it will be either enabled", "\"Rejected\" DISCONNECTED = \"Disconnected\" TIMEOUT = \"Timeout\" class ProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The current", "Enabled - Indicates that the public ssh port is open and accessible according", "VIRTUAL_MACHINE = \"VirtualMachine\" HD_INSIGHT = \"HDInsight\" DATABRICKS = \"Databricks\" DATA_LAKE_ANALYTICS = \"DataLakeAnalytics\" class", "DELETING = \"Deleting\" SUCCEEDED = \"Succeeded\" FAILED = \"Failed\" CANCELED = \"Canceled\" class", "user can access applications on this instance depending on his/her assigned role. \"\"\"", "= \"Personal\" SHARED = \"Shared\" class BillingCurrency(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Three lettered code specifying", "of the cluster if VNet is defined, else is open all public nodes.", "after creation it will be either enabled or disabled. \"\"\" ENABLED = \"Enabled\"", "number of compute nodes. resizing - Indicates that the compute is resizing; that", "state. \"\"\" SUCCEEDED = \"Succeeded\" CREATING = \"Creating\" DELETING = \"Deleting\" FAILED =", "= \"UserAssigned\" SYSTEM_ASSIGNED_USER_ASSIGNED = \"SystemAssigned,UserAssigned\" NONE = \"None\" class SshPublicAccess(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State", "= \"USD\" class ComputeInstanceState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Current state of a ComputeInstance. \"\"\" CREATING", "PENDING = \"Pending\" APPROVED = \"Approved\" REJECTED = \"Rejected\" DISCONNECTED = \"Disconnected\" TIMEOUT", "= \"Delete\" DETACH = \"Detach\" class UnitOfMeasure(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The unit of time", "name): \"\"\"Return the enum member matching `name` We use __getattr__ instead of descriptors", "the encryption is enabled for the workspace. \"\"\" ENABLED = \"Enabled\" DISABLED =", "Indicates that the public ssh port is closed on this instance. Enabled -", "enabled or disabled. \"\"\" ENABLED = \"Enabled\" DISABLED = \"Disabled\" NOT_SPECIFIED = \"NotSpecified\"", "PERSONAL = \"Personal\" SHARED = \"Shared\" class BillingCurrency(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Three lettered code", "str, Enum)): \"\"\"The current provisioning state. \"\"\" SUCCEEDED = \"Succeeded\" CREATING = \"Creating\"", "this compute instance. When Shared, any workspace user can access applications on this", "CANCELED = \"Canceled\" class QuotaUnit(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"An enum describing the unit of", "STARTING = \"Starting\" STOPPED = \"Stopped\" STOPPING = \"Stopping\" USER_SETTING_UP = \"UserSettingUp\" USER_SETUP_FAILED", "in the compute in progress. A compute enters this state when it is", "provisioning. \"\"\" UNKNOWN = \"Unknown\" UPDATING = \"Updating\" CREATING = \"Creating\" DELETING =", "is not resizing. There are no changes to the number of compute nodes", "IDLE = \"idle\" RUNNING = \"running\" PREPARING = \"preparing\" UNUSABLE = \"unusable\" LEAVING", "Enum)): \"\"\"Name of the last operation. \"\"\" CREATE = \"Create\" START = \"Start\"", "= \"StartFailed\" STOP_FAILED = \"StopFailed\" RESTART_FAILED = \"RestartFailed\" REIMAGE_FAILED = \"ReimageFailed\" DELETE_FAILED =", "NONE = \"None\" class SshPublicAccess(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State of the public SSH port.", "\"None\" class SshPublicAccess(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State of the public SSH port. Possible values", "str, Enum)): \"\"\"The current deployment state of workspace resource. The provisioningState is to", "port is closed on this instance. Enabled - Indicates that the public ssh", "EncryptionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Indicates whether or not the encryption is enabled for the", "port. Possible values are: Disabled - Indicates that the public ssh port is", "`value` being both properties for enum members (which live in the class' __dict__)", "= \"Failure\" INVALID_QUOTA_BELOW_CLUSTER_MINIMUM = \"InvalidQuotaBelowClusterMinimum\" INVALID_QUOTA_EXCEEDS_SUBSCRIPTION_LIMIT = \"InvalidQuotaExceedsSubscriptionLimit\" INVALID_VM_FAMILY_NAME = \"InvalidVMFamilyName\" OPERATION_NOT_SUPPORTED_FOR_SKU =", "class OperationName(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Name of the last operation. \"\"\" CREATE = \"Create\"", "= \"HDInsight\" DATABRICKS = \"Databricks\" DATA_LAKE_ANALYTICS = \"DataLakeAnalytics\" class EncryptionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Indicates", "\"\"\"The identity type. \"\"\" SYSTEM_ASSIGNED = \"SystemAssigned\" USER_ASSIGNED = \"UserAssigned\" SYSTEM_ASSIGNED_USER_ASSIGNED = \"SystemAssigned,UserAssigned\"", "this state when it is created and when no operations are being performed", "Values are idle, running, preparing, unusable, leaving and preempted. \"\"\" IDLE = \"idle\"", "support `name` and `value` being both properties for enum members (which live in", "restriction. \"\"\" NOT_SPECIFIED = \"NotSpecified\" NOT_AVAILABLE_FOR_REGION = \"NotAvailableForRegion\" NOT_AVAILABLE_FOR_SUBSCRIPTION = \"NotAvailableForSubscription\" class RemoteLoginPortPublicAccess(with_metaclass(_CaseInsensitiveEnumMeta,", "= \"Disabled\" NOT_SPECIFIED = \"NotSpecified\" class ResourceIdentityType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The identity type. \"\"\"", "his/her assigned role. \"\"\" PERSONAL = \"Personal\" SHARED = \"Shared\" class BillingCurrency(with_metaclass(_CaseInsensitiveEnumMeta, str,", "\"Resizing\" class ApplicationSharingPolicy(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Policy for sharing applications on this compute instance", "\"ComputeInstance\" DATA_FACTORY = \"DataFactory\" VIRTUAL_MACHINE = \"VirtualMachine\" HD_INSIGHT = \"HDInsight\" DATABRICKS = \"Databricks\"", "str, Enum)): \"\"\"The identity type. \"\"\" SYSTEM_ASSIGNED = \"SystemAssigned\" USER_ASSIGNED = \"UserAssigned\" SYSTEM_ASSIGNED_USER_ASSIGNED", "= \"InvalidQuotaExceedsSubscriptionLimit\" INVALID_VM_FAMILY_NAME = \"InvalidVMFamilyName\" OPERATION_NOT_SUPPORTED_FOR_SKU = \"OperationNotSupportedForSku\" OPERATION_NOT_ENABLED_FOR_REGION = \"OperationNotEnabledForRegion\" class UnderlyingResourceAction(with_metaclass(_CaseInsensitiveEnumMeta,", "of usage measurement. \"\"\" COUNT = \"Count\" class VMPriceOSType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Operating system", "\"SetupFailed\" STARTING = \"Starting\" STOPPED = \"Stopped\" STOPPING = \"Stopping\" USER_SETTING_UP = \"UserSettingUp\"", "applications on this compute instance. When Shared, any workspace user can access applications", "\"Starting\" STOPPED = \"Stopped\" STOPPING = \"Stopping\" USER_SETTING_UP = \"UserSettingUp\" USER_SETUP_FAILED = \"UserSetupFailed\"", "preparing, unusable, leaving and preempted. \"\"\" IDLE = \"idle\" RUNNING = \"running\" PREPARING", "enum members themselves. \"\"\" try: return cls._member_map_[name.upper()] except KeyError: raise AttributeError(name) class AllocationState(with_metaclass(_CaseInsensitiveEnumMeta,", "incorrect behavior and will be lost if the code is regenerated. # --------------------------------------------------------------------------", "coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed", "BillingCurrency(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Three lettered code specifying the currency of the VM price.", "added to or removed from the compute. \"\"\" STEADY = \"Steady\" RESIZING =", "= \"ComputeInstance\" DATA_FACTORY = \"DataFactory\" VIRTUAL_MACHINE = \"VirtualMachine\" HD_INSIGHT = \"HDInsight\" DATABRICKS =", "the VNet/subnet policy if applicable. \"\"\" ENABLED = \"Enabled\" DISABLED = \"Disabled\" class", "or inserting into the enum class' __dict__ in order to support `name` and", "= \"Disabled\" ENABLED = \"Enabled\" class Status(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Status of update workspace", "\"Delete\" class OperationStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Operation status. \"\"\" IN_PROGRESS = \"InProgress\" SUCCEEDED =", "time measurement for the specified VM price. Example: OneHour \"\"\" ONE_HOUR = \"OneHour\"", "cls._member_map_[name.upper()] except KeyError: raise AttributeError(name) class AllocationState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Allocation state of the", "OPERATION_NOT_ENABLED_FOR_REGION = \"OperationNotEnabledForRegion\" class UnderlyingResourceAction(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): DELETE = \"Delete\" DETACH = \"Detach\"", "\"StopFailed\" RESTART_FAILED = \"RestartFailed\" REIMAGE_FAILED = \"ReimageFailed\" DELETE_FAILED = \"DeleteFailed\" class PrivateEndpointConnectionProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str,", "= \"SettingUp\" SETUP_FAILED = \"SetupFailed\" STARTING = \"Starting\" STOPPED = \"Stopped\" STOPPING =", "\"\"\" STEADY = \"Steady\" RESIZING = \"Resizing\" class ApplicationSharingPolicy(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Policy for", "performed on the compute to change the number of compute nodes. resizing -", "\"DataLakeAnalytics\" class EncryptionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Indicates whether or not the encryption is enabled", "\"NotAvailableForSubscription\" class RemoteLoginPortPublicAccess(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State of the public SSH port. Possible values", "enabled for the workspace. \"\"\" ENABLED = \"Enabled\" DISABLED = \"Disabled\" class NodeState(with_metaclass(_CaseInsensitiveEnumMeta,", "Enum)): \"\"\"An enum describing the unit of usage measurement. \"\"\" COUNT = \"Count\"", "assigned role. \"\"\" PERSONAL = \"Personal\" SHARED = \"Shared\" class BillingCurrency(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):", "HD_INSIGHT = \"HDInsight\" DATABRICKS = \"Databricks\" DATA_LAKE_ANALYTICS = \"DataLakeAnalytics\" class EncryptionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):", "only during cluster creation time, after creation it will be either enabled or", "= \"NotAvailableForSubscription\" class RemoteLoginPortPublicAccess(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State of the public SSH port. Possible", "the specified VM price. Example: OneHour \"\"\" ONE_HOUR = \"OneHour\" class UsageUnit(with_metaclass(_CaseInsensitiveEnumMeta, str,", "try: return cls._member_map_[name.upper()] except KeyError: raise AttributeError(name) class AllocationState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Allocation state", "ResourceIdentityType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The identity type. \"\"\" SYSTEM_ASSIGNED = \"SystemAssigned\" USER_ASSIGNED = \"UserAssigned\"", "instance among users of parent workspace. If Personal, only the creator can access", "time, after creation it will be either enabled or disabled. \"\"\" ENABLED =", "\"\"\" SYSTEM_ASSIGNED = \"SystemAssigned\" USER_ASSIGNED = \"UserAssigned\" SYSTEM_ASSIGNED_USER_ASSIGNED = \"SystemAssigned,UserAssigned\" NONE = \"None\"", "__getattr__ instead of descriptors or inserting into the enum class' __dict__ in order", "\"\"\"Current state of a ComputeInstance. \"\"\" CREATING = \"Creating\" CREATE_FAILED = \"CreateFailed\" DELETING", "are being performed on the compute to change the number of compute nodes.", "live in the class' __dict__) and enum members themselves. \"\"\" try: return cls._member_map_[name.upper()]", "information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may", "compute. Possible values are: steady - Indicates that the compute is not resizing.", "= \"Dedicated\" LOW_PRIORITY = \"LowPriority\" class VMTier(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The type of the", "workspace resource. The provisioningState is to indicate states for resource provisioning. \"\"\" UNKNOWN", "\"running\" PREPARING = \"preparing\" UNUSABLE = \"unusable\" LEAVING = \"leaving\" PREEMPTED = \"preempted\"", "= \"InvalidVMFamilyName\" OPERATION_NOT_SUPPORTED_FOR_SKU = \"OperationNotSupportedForSku\" OPERATION_NOT_ENABLED_FOR_REGION = \"OperationNotEnabledForRegion\" class UnderlyingResourceAction(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): DELETE", "compute. \"\"\" STEADY = \"Steady\" RESIZING = \"Resizing\" class ApplicationSharingPolicy(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Policy", "and when no operations are being performed on the compute to change the", "if applicable. \"\"\" ENABLED = \"Enabled\" DISABLED = \"Disabled\" class SslConfigurationStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):", "str, Enum)): \"\"\"Virtual Machine priority \"\"\" DEDICATED = \"Dedicated\" LOW_PRIORITY = \"LowPriority\" class", "with_metaclass class _CaseInsensitiveEnumMeta(EnumMeta): def __getitem__(self, name): return super().__getitem__(name.upper()) def __getattr__(cls, name): \"\"\"Return the", "is closed on all nodes of the cluster if VNet is defined, else", "that the public ssh port is open and accessible according to the VNet/subnet", "\"Restarting\" JOB_RUNNING = \"JobRunning\" SETTING_UP = \"SettingUp\" SETUP_FAILED = \"SetupFailed\" STARTING = \"Starting\"", "str, Enum)): DELETE = \"Delete\" DETACH = \"Detach\" class UnitOfMeasure(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The", "# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT", "the cluster if VNet is defined, else is open all public nodes. It", "\"\"\"Indicates whether or not the encryption is enabled for the workspace. \"\"\" ENABLED", "class ApplicationSharingPolicy(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Policy for sharing applications on this compute instance among", "\"UserAssigned\" SYSTEM_ASSIGNED_USER_ASSIGNED = \"SystemAssigned,UserAssigned\" NONE = \"None\" class SshPublicAccess(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State of", "str, Enum)): \"\"\"Allocation state of the compute. Possible values are: steady - Indicates", "use __getattr__ instead of descriptors or inserting into the enum class' __dict__ in", "\"\"\"The current provisioning state. \"\"\" SUCCEEDED = \"Succeeded\" CREATING = \"Creating\" DELETING =", "ProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The current deployment state of workspace resource. The provisioningState is", "= \"Count\" class ReasonCode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The reason for the restriction. \"\"\" NOT_SPECIFIED", "Code Generator. # Changes may cause incorrect behavior and will be lost if", "price. Example: OneHour \"\"\" ONE_HOUR = \"OneHour\" class UsageUnit(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"An enum", "\"\"\" LINUX = \"Linux\" WINDOWS = \"Windows\" class VmPriority(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Virtual Machine", "\"leaving\" PREEMPTED = \"preempted\" class OperationName(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Name of the last operation.", "STEADY = \"Steady\" RESIZING = \"Resizing\" class ApplicationSharingPolicy(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Policy for sharing", "PREEMPTED = \"preempted\" class OperationName(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Name of the last operation. \"\"\"", "\"\"\" COUNT = \"Count\" class ReasonCode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The reason for the restriction.", "DETACH = \"Detach\" class UnitOfMeasure(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The unit of time measurement for", "of compute nodes in the compute in progress. A compute enters this state", "being both properties for enum members (which live in the class' __dict__) and", "NotSpecified - Indicates that the public ssh port is closed on all nodes", "this compute instance among users of parent workspace. If Personal, only the creator", "class BillingCurrency(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Three lettered code specifying the currency of the VM", "str, Enum)): \"\"\"An enum describing the unit of quota measurement. \"\"\" COUNT =", "- Indicates that the public ssh port is open and accessible according to", "\"\"\"Operating system type used by the VM. \"\"\" LINUX = \"Linux\" WINDOWS =", "str, Enum)): \"\"\"Status of update workspace quota. \"\"\" UNDEFINED = \"Undefined\" SUCCESS =", "the compute is not resizing. There are no changes to the number of", "a ComputeInstance. \"\"\" CREATING = \"Creating\" CREATE_FAILED = \"CreateFailed\" DELETING = \"Deleting\" RUNNING", "behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from", "state of a ComputeInstance. \"\"\" CREATING = \"Creating\" CREATE_FAILED = \"CreateFailed\" DELETING =", "for the specified VM price. Example: OneHour \"\"\" ONE_HOUR = \"OneHour\" class UsageUnit(with_metaclass(_CaseInsensitiveEnumMeta,", "\"\"\"An enum describing the unit of usage measurement. \"\"\" COUNT = \"Count\" class", "be either enabled or disabled. \"\"\" ENABLED = \"Enabled\" DISABLED = \"Disabled\" NOT_SPECIFIED", "Enum)): \"\"\"The reason for the restriction. \"\"\" NOT_SPECIFIED = \"NotSpecified\" NOT_AVAILABLE_FOR_REGION = \"NotAvailableForRegion\"", "\"SystemAssigned,UserAssigned\" NONE = \"None\" class SshPublicAccess(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State of the public SSH", "= \"Enabled\" DISABLED = \"Disabled\" class NodeState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State of the compute", "\"\"\" SUCCEEDED = \"Succeeded\" CREATING = \"Creating\" DELETING = \"Deleting\" FAILED = \"Failed\"", "RemoteLoginPortPublicAccess(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State of the public SSH port. Possible values are: Disabled", "VMTier(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The type of the VM. \"\"\" STANDARD = \"Standard\" LOW_PRIORITY", "SUCCESS = \"Success\" FAILURE = \"Failure\" INVALID_QUOTA_BELOW_CLUSTER_MINIMUM = \"InvalidQuotaBelowClusterMinimum\" INVALID_QUOTA_EXCEEDS_SUBSCRIPTION_LIMIT = \"InvalidQuotaExceedsSubscriptionLimit\" INVALID_VM_FAMILY_NAME", "\"Unknown\" UPDATING = \"Updating\" CREATING = \"Creating\" DELETING = \"Deleting\" SUCCEEDED = \"Succeeded\"", "port is closed on all nodes of the cluster if VNet is defined,", "of the VM. \"\"\" STANDARD = \"Standard\" LOW_PRIORITY = \"LowPriority\" SPOT = \"Spot\"", "Enum)): \"\"\"The unit of time measurement for the specified VM price. Example: OneHour", "enum import Enum, EnumMeta from six import with_metaclass class _CaseInsensitiveEnumMeta(EnumMeta): def __getitem__(self, name):", "# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under", "of the compute. Possible values are: steady - Indicates that the compute is", "the MIT License. See License.txt in the project root for license information. #", "\"Creating\" CREATE_FAILED = \"CreateFailed\" DELETING = \"Deleting\" RUNNING = \"Running\" RESTARTING = \"Restarting\"", "# Changes may cause incorrect behavior and will be lost if the code", "to the number of compute nodes in the compute in progress. A compute", "ReasonCode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The reason for the restriction. \"\"\" NOT_SPECIFIED = \"NotSpecified\" NOT_AVAILABLE_FOR_REGION", "Enum)): \"\"\"Indicates whether or not the encryption is enabled for the workspace. \"\"\"", "SYSTEM_ASSIGNED_USER_ASSIGNED = \"SystemAssigned,UserAssigned\" NONE = \"None\" class SshPublicAccess(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State of the", "= \"Approved\" REJECTED = \"Rejected\" DISCONNECTED = \"Disconnected\" TIMEOUT = \"Timeout\" class ProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta,", "= \"SystemAssigned\" USER_ASSIGNED = \"UserAssigned\" SYSTEM_ASSIGNED_USER_ASSIGNED = \"SystemAssigned,UserAssigned\" NONE = \"None\" class SshPublicAccess(with_metaclass(_CaseInsensitiveEnumMeta,", "closed on all nodes of the cluster. Enabled - Indicates that the public", "Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect", "that the compute is not resizing. There are no changes to the number", "whether or not the encryption is enabled for the workspace. \"\"\" ENABLED =", "no changes to the number of compute nodes in the compute in progress.", "Enum)): \"\"\"Current state of a ComputeInstance. \"\"\" CREATING = \"Creating\" CREATE_FAILED = \"CreateFailed\"", "ENABLED = \"Enabled\" DISABLED = \"Disabled\" NOT_SPECIFIED = \"NotSpecified\" class ResourceIdentityType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):", "DISABLED = \"Disabled\" ENABLED = \"Enabled\" class Status(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Status of update", "the project root for license information. # Code generated by Microsoft (R) AutoRest", "is closed on all nodes of the cluster. Enabled - Indicates that the", "Indicates that the compute is resizing; that is, compute nodes are being added", "when it is created and when no operations are being performed on the", "\"CreateFailed\" DELETING = \"Deleting\" RUNNING = \"Running\" RESTARTING = \"Restarting\" JOB_RUNNING = \"JobRunning\"", "= \"Shared\" class BillingCurrency(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Three lettered code specifying the currency of", "\"Updating\" CREATING = \"Creating\" DELETING = \"Deleting\" SUCCEEDED = \"Succeeded\" FAILED = \"Failed\"", "\"\"\" USD = \"USD\" class ComputeInstanceState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Current state of a ComputeInstance.", "DELETING = \"Deleting\" RUNNING = \"Running\" RESTARTING = \"Restarting\" JOB_RUNNING = \"JobRunning\" SETTING_UP", "SshPublicAccess(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State of the public SSH port. Possible values are: Disabled", "= \"Running\" RESTARTING = \"Restarting\" JOB_RUNNING = \"JobRunning\" SETTING_UP = \"SettingUp\" SETUP_FAILED =", "closed on this instance. Enabled - Indicates that the public ssh port is", "Enum)): \"\"\"Policy for sharing applications on this compute instance among users of parent", "Enum)): \"\"\"The private endpoint connection status. \"\"\" PENDING = \"Pending\" APPROVED = \"Approved\"", "SUCCEEDED = \"Succeeded\" FAILED = \"Failed\" CANCELED = \"Canceled\" class QuotaUnit(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):", "from the compute. \"\"\" STEADY = \"Steady\" RESIZING = \"Resizing\" class ApplicationSharingPolicy(with_metaclass(_CaseInsensitiveEnumMeta, str,", "creation time, after creation it will be either enabled or disabled. \"\"\" ENABLED", "Enum)): \"\"\"The type of the VM. \"\"\" STANDARD = \"Standard\" LOW_PRIORITY = \"LowPriority\"", "__dict__ in order to support `name` and `value` being both properties for enum", "of compute nodes. resizing - Indicates that the compute is resizing; that is,", "JOB_RUNNING = \"JobRunning\" SETTING_UP = \"SettingUp\" SETUP_FAILED = \"SetupFailed\" STARTING = \"Starting\" STOPPED", "LEAVING = \"leaving\" PREEMPTED = \"preempted\" class OperationName(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Name of the", "\"Success\" FAILURE = \"Failure\" INVALID_QUOTA_BELOW_CLUSTER_MINIMUM = \"InvalidQuotaBelowClusterMinimum\" INVALID_QUOTA_EXCEEDS_SUBSCRIPTION_LIMIT = \"InvalidQuotaExceedsSubscriptionLimit\" INVALID_VM_FAMILY_NAME = \"InvalidVMFamilyName\"", "six import with_metaclass class _CaseInsensitiveEnumMeta(EnumMeta): def __getitem__(self, name): return super().__getitem__(name.upper()) def __getattr__(cls, name):", "\"Windows\" class VmPriority(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Virtual Machine priority \"\"\" DEDICATED = \"Dedicated\" LOW_PRIORITY", "= \"Deleting\" SUCCEEDED = \"Succeeded\" FAILED = \"Failed\" CANCELED = \"Canceled\" class QuotaUnit(with_metaclass(_CaseInsensitiveEnumMeta,", "= \"Stopped\" STOPPING = \"Stopping\" USER_SETTING_UP = \"UserSettingUp\" USER_SETUP_FAILED = \"UserSetupFailed\" UNKNOWN =", "measurement. \"\"\" COUNT = \"Count\" class ReasonCode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The reason for the", "If Personal, only the creator can access applications on this compute instance. When", "compute instance. When Shared, any workspace user can access applications on this instance", "reserved. # Licensed under the MIT License. See License.txt in the project root", "AML_COMPUTE = \"AmlCompute\" COMPUTE_INSTANCE = \"ComputeInstance\" DATA_FACTORY = \"DataFactory\" VIRTUAL_MACHINE = \"VirtualMachine\" HD_INSIGHT", "\"\"\"The private endpoint connection status. \"\"\" PENDING = \"Pending\" APPROVED = \"Approved\" REJECTED", "CREATE_FAILED = \"CreateFailed\" START_FAILED = \"StartFailed\" STOP_FAILED = \"StopFailed\" RESTART_FAILED = \"RestartFailed\" REIMAGE_FAILED", "DISABLED = \"Disabled\" class SslConfigurationStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Enable or disable ssl for scoring", "Status(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Status of update workspace quota. \"\"\" UNDEFINED = \"Undefined\" SUCCESS", "system type used by the VM. \"\"\" LINUX = \"Linux\" WINDOWS = \"Windows\"", "by the VM. \"\"\" LINUX = \"Linux\" WINDOWS = \"Windows\" class VmPriority(with_metaclass(_CaseInsensitiveEnumMeta, str,", "\"Deleting\" RUNNING = \"Running\" RESTARTING = \"Restarting\" JOB_RUNNING = \"JobRunning\" SETTING_UP = \"SettingUp\"", "from enum import Enum, EnumMeta from six import with_metaclass class _CaseInsensitiveEnumMeta(EnumMeta): def __getitem__(self,", "being performed on the compute to change the number of compute nodes. resizing", "= \"InProgress\" SUCCEEDED = \"Succeeded\" CREATE_FAILED = \"CreateFailed\" START_FAILED = \"StartFailed\" STOP_FAILED =", "\"unusable\" LEAVING = \"leaving\" PREEMPTED = \"preempted\" class OperationName(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Name of", "describing the unit of usage measurement. \"\"\" COUNT = \"Count\" class VMPriceOSType(with_metaclass(_CaseInsensitiveEnumMeta, str,", "OPERATION_NOT_SUPPORTED_FOR_SKU = \"OperationNotSupportedForSku\" OPERATION_NOT_ENABLED_FOR_REGION = \"OperationNotEnabledForRegion\" class UnderlyingResourceAction(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): DELETE = \"Delete\"", "UsageUnit(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"An enum describing the unit of usage measurement. \"\"\" COUNT", "= \"Succeeded\" CREATING = \"Creating\" DELETING = \"Deleting\" FAILED = \"Failed\" class PrivateEndpointServiceConnectionStatus(with_metaclass(_CaseInsensitiveEnumMeta,", "DATA_FACTORY = \"DataFactory\" VIRTUAL_MACHINE = \"VirtualMachine\" HD_INSIGHT = \"HDInsight\" DATABRICKS = \"Databricks\" DATA_LAKE_ANALYTICS", "nodes in the compute in progress. A compute enters this state when it", "Example: USD \"\"\" USD = \"USD\" class ComputeInstanceState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Current state of", "= \"NotSpecified\" NOT_AVAILABLE_FOR_REGION = \"NotAvailableForRegion\" NOT_AVAILABLE_FOR_SUBSCRIPTION = \"NotAvailableForSubscription\" class RemoteLoginPortPublicAccess(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State", "- Indicates that the public ssh port is closed on all nodes of", "is created and when no operations are being performed on the compute to", "RESIZING = \"Resizing\" class ApplicationSharingPolicy(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Policy for sharing applications on this", "can access applications on this instance depending on his/her assigned role. \"\"\" PERSONAL", "of descriptors or inserting into the enum class' __dict__ in order to support", "ENABLED = \"Enabled\" DISABLED = \"Disabled\" class SslConfigurationStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Enable or disable", "COUNT = \"Count\" class ReasonCode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The reason for the restriction. \"\"\"", "\"\"\"State of the compute node. Values are idle, running, preparing, unusable, leaving and", "- Indicates that the compute is resizing; that is, compute nodes are being", "will be either enabled or disabled. \"\"\" ENABLED = \"Enabled\" DISABLED = \"Disabled\"", "= \"Disabled\" class NodeState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State of the compute node. Values are", "(R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be", "if VNet is defined, else is open all public nodes. It can be", "= \"OperationNotSupportedForSku\" OPERATION_NOT_ENABLED_FOR_REGION = \"OperationNotEnabledForRegion\" class UnderlyingResourceAction(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): DELETE = \"Delete\" DETACH", "are idle, running, preparing, unusable, leaving and preempted. \"\"\" IDLE = \"idle\" RUNNING", "unit of quota measurement. \"\"\" COUNT = \"Count\" class ReasonCode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The", "_CaseInsensitiveEnumMeta(EnumMeta): def __getitem__(self, name): return super().__getitem__(name.upper()) def __getattr__(cls, name): \"\"\"Return the enum member", "in order to support `name` and `value` being both properties for enum members", "node. Values are idle, running, preparing, unusable, leaving and preempted. \"\"\" IDLE =", "OperationStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Operation status. \"\"\" IN_PROGRESS = \"InProgress\" SUCCEEDED = \"Succeeded\" CREATE_FAILED", "can access applications on this compute instance. When Shared, any workspace user can", "of the public SSH port. Possible values are: Disabled - Indicates that the", "QuotaUnit(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"An enum describing the unit of quota measurement. \"\"\" COUNT", "the cluster. NotSpecified - Indicates that the public ssh port is closed on", "cluster if VNet is defined, else is open all public nodes. It can", "VM price. Example: OneHour \"\"\" ONE_HOUR = \"OneHour\" class UsageUnit(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"An", "Indicates that the public ssh port is open and accessible according to the", "quota. \"\"\" UNDEFINED = \"Undefined\" SUCCESS = \"Success\" FAILURE = \"Failure\" INVALID_QUOTA_BELOW_CLUSTER_MINIMUM =", "\"USD\" class ComputeInstanceState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Current state of a ComputeInstance. \"\"\" CREATING =", "= \"StopFailed\" RESTART_FAILED = \"RestartFailed\" REIMAGE_FAILED = \"ReimageFailed\" DELETE_FAILED = \"DeleteFailed\" class PrivateEndpointConnectionProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta,", "\"\"\"The type of compute \"\"\" AKS = \"AKS\" AML_COMPUTE = \"AmlCompute\" COMPUTE_INSTANCE =", "resizing; that is, compute nodes are being added to or removed from the", "open and accessible according to the VNet/subnet policy if applicable. \"\"\" ENABLED =", "the compute is resizing; that is, compute nodes are being added to or", "\"InvalidQuotaBelowClusterMinimum\" INVALID_QUOTA_EXCEEDS_SUBSCRIPTION_LIMIT = \"InvalidQuotaExceedsSubscriptionLimit\" INVALID_VM_FAMILY_NAME = \"InvalidVMFamilyName\" OPERATION_NOT_SUPPORTED_FOR_SKU = \"OperationNotSupportedForSku\" OPERATION_NOT_ENABLED_FOR_REGION = \"OperationNotEnabledForRegion\"", "\"Deleting\" SUCCEEDED = \"Succeeded\" FAILED = \"Failed\" CANCELED = \"Canceled\" class QuotaUnit(with_metaclass(_CaseInsensitiveEnumMeta, str,", "\"\"\"An enum describing the unit of quota measurement. \"\"\" COUNT = \"Count\" class", "UNUSABLE = \"unusable\" LEAVING = \"leaving\" PREEMPTED = \"preempted\" class OperationName(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):", "public ssh port is open on all nodes of the cluster. NotSpecified -", "AllocationState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Allocation state of the compute. Possible values are: steady -", "properties for enum members (which live in the class' __dict__) and enum members", "values are: Disabled - Indicates that the public ssh port is closed on", "\"Shared\" class BillingCurrency(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Three lettered code specifying the currency of the", "instance. When Shared, any workspace user can access applications on this instance depending", "the compute node. Values are idle, running, preparing, unusable, leaving and preempted. \"\"\"", "\"NotSpecified\" NOT_AVAILABLE_FOR_REGION = \"NotAvailableForRegion\" NOT_AVAILABLE_FOR_SUBSCRIPTION = \"NotAvailableForSubscription\" class RemoteLoginPortPublicAccess(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State of", "ssh port is closed on all nodes of the cluster. Enabled - Indicates", "Enum)): \"\"\"Virtual Machine priority \"\"\" DEDICATED = \"Dedicated\" LOW_PRIORITY = \"LowPriority\" class VMTier(with_metaclass(_CaseInsensitiveEnumMeta,", "license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes", "changes to the number of compute nodes in the compute in progress. A", "lettered code specifying the currency of the VM price. Example: USD \"\"\" USD", "class VMPriceOSType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Operating system type used by the VM. \"\"\" LINUX", "CREATE_FAILED = \"CreateFailed\" DELETING = \"Deleting\" RUNNING = \"Running\" RESTARTING = \"Restarting\" JOB_RUNNING", "USD \"\"\" USD = \"USD\" class ComputeInstanceState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Current state of a", "of the cluster. NotSpecified - Indicates that the public ssh port is closed", "\"Pending\" APPROVED = \"Approved\" REJECTED = \"Rejected\" DISCONNECTED = \"Disconnected\" TIMEOUT = \"Timeout\"", "except KeyError: raise AttributeError(name) class AllocationState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Allocation state of the compute.", "code is regenerated. # -------------------------------------------------------------------------- from enum import Enum, EnumMeta from six import", "resource provisioning. \"\"\" UNKNOWN = \"Unknown\" UPDATING = \"Updating\" CREATING = \"Creating\" DELETING", "UNKNOWN = \"Unknown\" UPDATING = \"Updating\" CREATING = \"Creating\" DELETING = \"Deleting\" SUCCEEDED", "\"Creating\" DELETING = \"Deleting\" FAILED = \"Failed\" class PrivateEndpointServiceConnectionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The private", "CREATING = \"Creating\" DELETING = \"Deleting\" FAILED = \"Failed\" class PrivateEndpointServiceConnectionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):", "= \"Failed\" class PrivateEndpointServiceConnectionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The private endpoint connection status. \"\"\" PENDING", "\"\"\"Name of the last operation. \"\"\" CREATE = \"Create\" START = \"Start\" STOP", "status. \"\"\" PENDING = \"Pending\" APPROVED = \"Approved\" REJECTED = \"Rejected\" DISCONNECTED =", "\"\"\" UNKNOWN = \"Unknown\" UPDATING = \"Updating\" CREATING = \"Creating\" DELETING = \"Deleting\"", "of compute \"\"\" AKS = \"AKS\" AML_COMPUTE = \"AmlCompute\" COMPUTE_INSTANCE = \"ComputeInstance\" DATA_FACTORY", "the last operation. \"\"\" CREATE = \"Create\" START = \"Start\" STOP = \"Stop\"", "class' __dict__) and enum members themselves. \"\"\" try: return cls._member_map_[name.upper()] except KeyError: raise", "\"Steady\" RESIZING = \"Resizing\" class ApplicationSharingPolicy(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Policy for sharing applications on", "matching `name` We use __getattr__ instead of descriptors or inserting into the enum", "idle, running, preparing, unusable, leaving and preempted. \"\"\" IDLE = \"idle\" RUNNING =", "\"Disabled\" class SslConfigurationStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Enable or disable ssl for scoring \"\"\" DISABLED", "SUCCEEDED = \"Succeeded\" CREATE_FAILED = \"CreateFailed\" START_FAILED = \"StartFailed\" STOP_FAILED = \"StopFailed\" RESTART_FAILED", "scoring \"\"\" DISABLED = \"Disabled\" ENABLED = \"Enabled\" class Status(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Status", "\"Reimage\" DELETE = \"Delete\" class OperationStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Operation status. \"\"\" IN_PROGRESS =", "str, Enum)): \"\"\"The type of the VM. \"\"\" STANDARD = \"Standard\" LOW_PRIORITY =", "str, Enum)): \"\"\"The reason for the restriction. \"\"\" NOT_SPECIFIED = \"NotSpecified\" NOT_AVAILABLE_FOR_REGION =", "may cause incorrect behavior and will be lost if the code is regenerated.", "progress. A compute enters this state when it is created and when no", "= \"VirtualMachine\" HD_INSIGHT = \"HDInsight\" DATABRICKS = \"Databricks\" DATA_LAKE_ANALYTICS = \"DataLakeAnalytics\" class EncryptionStatus(with_metaclass(_CaseInsensitiveEnumMeta,", "\"CreateFailed\" START_FAILED = \"StartFailed\" STOP_FAILED = \"StopFailed\" RESTART_FAILED = \"RestartFailed\" REIMAGE_FAILED = \"ReimageFailed\"", "encryption is enabled for the workspace. \"\"\" ENABLED = \"Enabled\" DISABLED = \"Disabled\"", "STOP = \"Stop\" RESTART = \"Restart\" REIMAGE = \"Reimage\" DELETE = \"Delete\" class", "\"Personal\" SHARED = \"Shared\" class BillingCurrency(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Three lettered code specifying the", "= \"RestartFailed\" REIMAGE_FAILED = \"ReimageFailed\" DELETE_FAILED = \"DeleteFailed\" class PrivateEndpointConnectionProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The", "type of compute \"\"\" AKS = \"AKS\" AML_COMPUTE = \"AmlCompute\" COMPUTE_INSTANCE = \"ComputeInstance\"", "is open and accessible according to the VNet/subnet policy if applicable. \"\"\" ENABLED", "\"Disabled\" ENABLED = \"Enabled\" class Status(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Status of update workspace quota.", "is regenerated. # -------------------------------------------------------------------------- from enum import Enum, EnumMeta from six import with_metaclass", "open on all nodes of the cluster. NotSpecified - Indicates that the public", "or removed from the compute. \"\"\" STEADY = \"Steady\" RESIZING = \"Resizing\" class", "\"JobRunning\" SETTING_UP = \"SettingUp\" SETUP_FAILED = \"SetupFailed\" STARTING = \"Starting\" STOPPED = \"Stopped\"", "RUNNING = \"Running\" RESTARTING = \"Restarting\" JOB_RUNNING = \"JobRunning\" SETTING_UP = \"SettingUp\" SETUP_FAILED", "All rights reserved. # Licensed under the MIT License. See License.txt in the", "Enum)): \"\"\"Operating system type used by the VM. \"\"\" LINUX = \"Linux\" WINDOWS", "\"\"\" NOT_SPECIFIED = \"NotSpecified\" NOT_AVAILABLE_FOR_REGION = \"NotAvailableForRegion\" NOT_AVAILABLE_FOR_SUBSCRIPTION = \"NotAvailableForSubscription\" class RemoteLoginPortPublicAccess(with_metaclass(_CaseInsensitiveEnumMeta, str,", "leaving and preempted. \"\"\" IDLE = \"idle\" RUNNING = \"running\" PREPARING = \"preparing\"", "that the public ssh port is open on all nodes of the cluster.", "Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt", "all public nodes. It can be default only during cluster creation time, after", "will be lost if the code is regenerated. # -------------------------------------------------------------------------- from enum import", "for resource provisioning. \"\"\" UNKNOWN = \"Unknown\" UPDATING = \"Updating\" CREATING = \"Creating\"", "of the cluster. Enabled - Indicates that the public ssh port is open", "SslConfigurationStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Enable or disable ssl for scoring \"\"\" DISABLED = \"Disabled\"", "port is open on all nodes of the cluster. NotSpecified - Indicates that", "\"\"\" ENABLED = \"Enabled\" DISABLED = \"Disabled\" class NodeState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State of", "PrivateEndpointServiceConnectionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The private endpoint connection status. \"\"\" PENDING = \"Pending\" APPROVED", "RESTARTING = \"Restarting\" JOB_RUNNING = \"JobRunning\" SETTING_UP = \"SettingUp\" SETUP_FAILED = \"SetupFailed\" STARTING", "values are: steady - Indicates that the compute is not resizing. There are", "for license information. # Code generated by Microsoft (R) AutoRest Code Generator. #", "= \"Creating\" DELETING = \"Deleting\" SUCCEEDED = \"Succeeded\" FAILED = \"Failed\" CANCELED =", "= \"InvalidQuotaBelowClusterMinimum\" INVALID_QUOTA_EXCEEDS_SUBSCRIPTION_LIMIT = \"InvalidQuotaExceedsSubscriptionLimit\" INVALID_VM_FAMILY_NAME = \"InvalidVMFamilyName\" OPERATION_NOT_SUPPORTED_FOR_SKU = \"OperationNotSupportedForSku\" OPERATION_NOT_ENABLED_FOR_REGION =", "class NodeState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State of the compute node. Values are idle, running,", "\"\"\" CREATING = \"Creating\" CREATE_FAILED = \"CreateFailed\" DELETING = \"Deleting\" RUNNING = \"Running\"", "WINDOWS = \"Windows\" class VmPriority(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Virtual Machine priority \"\"\" DEDICATED =", "class ReasonCode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The reason for the restriction. \"\"\" NOT_SPECIFIED = \"NotSpecified\"", "\"InvalidVMFamilyName\" OPERATION_NOT_SUPPORTED_FOR_SKU = \"OperationNotSupportedForSku\" OPERATION_NOT_ENABLED_FOR_REGION = \"OperationNotEnabledForRegion\" class UnderlyingResourceAction(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): DELETE =", "of update workspace quota. \"\"\" UNDEFINED = \"Undefined\" SUCCESS = \"Success\" FAILURE =", "__getitem__(self, name): return super().__getitem__(name.upper()) def __getattr__(cls, name): \"\"\"Return the enum member matching `name`", "\"\"\" CREATE = \"Create\" START = \"Start\" STOP = \"Stop\" RESTART = \"Restart\"", "on this instance depending on his/her assigned role. \"\"\" PERSONAL = \"Personal\" SHARED", "and preempted. \"\"\" IDLE = \"idle\" RUNNING = \"running\" PREPARING = \"preparing\" UNUSABLE", "\"Approved\" REJECTED = \"Rejected\" DISCONNECTED = \"Disconnected\" TIMEOUT = \"Timeout\" class ProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str,", "str, Enum)): \"\"\"State of the public SSH port. Possible values are: Disabled -", "access applications on this compute instance. When Shared, any workspace user can access", "the VM price. Example: USD \"\"\" USD = \"USD\" class ComputeInstanceState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):", "\"Enabled\" DISABLED = \"Disabled\" class SslConfigurationStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Enable or disable ssl for", "unit of time measurement for the specified VM price. Example: OneHour \"\"\" ONE_HOUR", "on all nodes of the cluster. Enabled - Indicates that the public ssh", "the VM. \"\"\" LINUX = \"Linux\" WINDOWS = \"Windows\" class VmPriority(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):", "= \"Disabled\" class SslConfigurationStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Enable or disable ssl for scoring \"\"\"", "Possible values are: Disabled - Indicates that the public ssh port is closed", "descriptors or inserting into the enum class' __dict__ in order to support `name`", "\"Start\" STOP = \"Stop\" RESTART = \"Restart\" REIMAGE = \"Reimage\" DELETE = \"Delete\"", "INVALID_QUOTA_BELOW_CLUSTER_MINIMUM = \"InvalidQuotaBelowClusterMinimum\" INVALID_QUOTA_EXCEEDS_SUBSCRIPTION_LIMIT = \"InvalidQuotaExceedsSubscriptionLimit\" INVALID_VM_FAMILY_NAME = \"InvalidVMFamilyName\" OPERATION_NOT_SUPPORTED_FOR_SKU = \"OperationNotSupportedForSku\" OPERATION_NOT_ENABLED_FOR_REGION", "= \"Resizing\" class ApplicationSharingPolicy(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Policy for sharing applications on this compute", "\"OneHour\" class UsageUnit(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"An enum describing the unit of usage measurement.", "that is, compute nodes are being added to or removed from the compute.", "on his/her assigned role. \"\"\" PERSONAL = \"Personal\" SHARED = \"Shared\" class BillingCurrency(with_metaclass(_CaseInsensitiveEnumMeta,", "all nodes of the cluster. Enabled - Indicates that the public ssh port", "reason for the restriction. \"\"\" NOT_SPECIFIED = \"NotSpecified\" NOT_AVAILABLE_FOR_REGION = \"NotAvailableForRegion\" NOT_AVAILABLE_FOR_SUBSCRIPTION =", "\"\"\"Policy for sharing applications on this compute instance among users of parent workspace.", "str, Enum)): \"\"\"An enum describing the unit of usage measurement. \"\"\" COUNT =", "VNet/subnet policy if applicable. \"\"\" ENABLED = \"Enabled\" DISABLED = \"Disabled\" class SslConfigurationStatus(with_metaclass(_CaseInsensitiveEnumMeta,", "= \"preempted\" class OperationName(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Name of the last operation. \"\"\" CREATE", "= \"Restarting\" JOB_RUNNING = \"JobRunning\" SETTING_UP = \"SettingUp\" SETUP_FAILED = \"SetupFailed\" STARTING =", "Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will", "CREATE = \"Create\" START = \"Start\" STOP = \"Stop\" RESTART = \"Restart\" REIMAGE", "or disabled. \"\"\" ENABLED = \"Enabled\" DISABLED = \"Disabled\" NOT_SPECIFIED = \"NotSpecified\" class", "INVALID_QUOTA_EXCEEDS_SUBSCRIPTION_LIMIT = \"InvalidQuotaExceedsSubscriptionLimit\" INVALID_VM_FAMILY_NAME = \"InvalidVMFamilyName\" OPERATION_NOT_SUPPORTED_FOR_SKU = \"OperationNotSupportedForSku\" OPERATION_NOT_ENABLED_FOR_REGION = \"OperationNotEnabledForRegion\" class", "compute \"\"\" AKS = \"AKS\" AML_COMPUTE = \"AmlCompute\" COMPUTE_INSTANCE = \"ComputeInstance\" DATA_FACTORY =", "str, Enum)): \"\"\"Enable or disable ssl for scoring \"\"\" DISABLED = \"Disabled\" ENABLED", "= \"UserSetupFailed\" UNKNOWN = \"Unknown\" UNUSABLE = \"Unusable\" class ComputeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The", "\"DataFactory\" VIRTUAL_MACHINE = \"VirtualMachine\" HD_INSIGHT = \"HDInsight\" DATABRICKS = \"Databricks\" DATA_LAKE_ANALYTICS = \"DataLakeAnalytics\"", "workspace. \"\"\" ENABLED = \"Enabled\" DISABLED = \"Disabled\" class NodeState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State", "= \"Detach\" class UnitOfMeasure(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The unit of time measurement for the", "class _CaseInsensitiveEnumMeta(EnumMeta): def __getitem__(self, name): return super().__getitem__(name.upper()) def __getattr__(cls, name): \"\"\"Return the enum", "compute instance among users of parent workspace. If Personal, only the creator can", "\"\"\"Operation status. \"\"\" IN_PROGRESS = \"InProgress\" SUCCEEDED = \"Succeeded\" CREATE_FAILED = \"CreateFailed\" START_FAILED", "the compute in progress. A compute enters this state when it is created", "that the public ssh port is closed on all nodes of the cluster", "class Status(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Status of update workspace quota. \"\"\" UNDEFINED = \"Undefined\"", "= \"Count\" class VMPriceOSType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Operating system type used by the VM.", "type of the VM. \"\"\" STANDARD = \"Standard\" LOW_PRIORITY = \"LowPriority\" SPOT =", "created and when no operations are being performed on the compute to change", "AttributeError(name) class AllocationState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Allocation state of the compute. Possible values are:", "\"SettingUp\" SETUP_FAILED = \"SetupFailed\" STARTING = \"Starting\" STOPPED = \"Stopped\" STOPPING = \"Stopping\"", "\"Delete\" DETACH = \"Detach\" class UnitOfMeasure(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The unit of time measurement", "= \"preparing\" UNUSABLE = \"unusable\" LEAVING = \"leaving\" PREEMPTED = \"preempted\" class OperationName(with_metaclass(_CaseInsensitiveEnumMeta,", "PrivateEndpointConnectionProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The current provisioning state. \"\"\" SUCCEEDED = \"Succeeded\" CREATING =", "defined, else is open all public nodes. It can be default only during", "public ssh port is closed on this instance. Enabled - Indicates that the", "RUNNING = \"running\" PREPARING = \"preparing\" UNUSABLE = \"unusable\" LEAVING = \"leaving\" PREEMPTED", "NOT_SPECIFIED = \"NotSpecified\" class ResourceIdentityType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The identity type. \"\"\" SYSTEM_ASSIGNED =", "of parent workspace. If Personal, only the creator can access applications on this", "= \"ReimageFailed\" DELETE_FAILED = \"DeleteFailed\" class PrivateEndpointConnectionProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The current provisioning state.", "Enum)): \"\"\"The current provisioning state. \"\"\" SUCCEEDED = \"Succeeded\" CREATING = \"Creating\" DELETING", "indicate states for resource provisioning. \"\"\" UNKNOWN = \"Unknown\" UPDATING = \"Updating\" CREATING", "current provisioning state. \"\"\" SUCCEEDED = \"Succeeded\" CREATING = \"Creating\" DELETING = \"Deleting\"", "the number of compute nodes. resizing - Indicates that the compute is resizing;", "ssh port is closed on this instance. Enabled - Indicates that the public", "= \"NotAvailableForRegion\" NOT_AVAILABLE_FOR_SUBSCRIPTION = \"NotAvailableForSubscription\" class RemoteLoginPortPublicAccess(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State of the public", "resizing - Indicates that the compute is resizing; that is, compute nodes are", "SYSTEM_ASSIGNED = \"SystemAssigned\" USER_ASSIGNED = \"UserAssigned\" SYSTEM_ASSIGNED_USER_ASSIGNED = \"SystemAssigned,UserAssigned\" NONE = \"None\" class", "\"\"\"The reason for the restriction. \"\"\" NOT_SPECIFIED = \"NotSpecified\" NOT_AVAILABLE_FOR_REGION = \"NotAvailableForRegion\" NOT_AVAILABLE_FOR_SUBSCRIPTION", "state of the compute. Possible values are: steady - Indicates that the compute", "when no operations are being performed on the compute to change the number", "It can be default only during cluster creation time, after creation it will", "lost if the code is regenerated. # -------------------------------------------------------------------------- from enum import Enum, EnumMeta", "to or removed from the compute. \"\"\" STEADY = \"Steady\" RESIZING = \"Resizing\"", "endpoint connection status. \"\"\" PENDING = \"Pending\" APPROVED = \"Approved\" REJECTED = \"Rejected\"", "# Licensed under the MIT License. See License.txt in the project root for", "deployment state of workspace resource. The provisioningState is to indicate states for resource", "\"Unknown\" UNUSABLE = \"Unusable\" class ComputeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The type of compute \"\"\"", "= \"Starting\" STOPPED = \"Stopped\" STOPPING = \"Stopping\" USER_SETTING_UP = \"UserSettingUp\" USER_SETUP_FAILED =", "License.txt in the project root for license information. # Code generated by Microsoft", "There are no changes to the number of compute nodes in the compute", "EnumMeta from six import with_metaclass class _CaseInsensitiveEnumMeta(EnumMeta): def __getitem__(self, name): return super().__getitem__(name.upper()) def", "PREPARING = \"preparing\" UNUSABLE = \"unusable\" LEAVING = \"leaving\" PREEMPTED = \"preempted\" class", "Enum)): \"\"\"State of the compute node. Values are idle, running, preparing, unusable, leaving", "sharing applications on this compute instance among users of parent workspace. If Personal,", "Enum)): \"\"\"An enum describing the unit of quota measurement. \"\"\" COUNT = \"Count\"", "IN_PROGRESS = \"InProgress\" SUCCEEDED = \"Succeeded\" CREATE_FAILED = \"CreateFailed\" START_FAILED = \"StartFailed\" STOP_FAILED", "resource. The provisioningState is to indicate states for resource provisioning. \"\"\" UNKNOWN =", "# -------------------------------------------------------------------------- from enum import Enum, EnumMeta from six import with_metaclass class _CaseInsensitiveEnumMeta(EnumMeta):", "the public ssh port is closed on this instance. Enabled - Indicates that", "UNDEFINED = \"Undefined\" SUCCESS = \"Success\" FAILURE = \"Failure\" INVALID_QUOTA_BELOW_CLUSTER_MINIMUM = \"InvalidQuotaBelowClusterMinimum\" INVALID_QUOTA_EXCEEDS_SUBSCRIPTION_LIMIT", "LOW_PRIORITY = \"LowPriority\" class VMTier(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The type of the VM. \"\"\"", "port is closed on all nodes of the cluster. Enabled - Indicates that", "class UnderlyingResourceAction(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): DELETE = \"Delete\" DETACH = \"Detach\" class UnitOfMeasure(with_metaclass(_CaseInsensitiveEnumMeta, str,", "and accessible according to the VNet/subnet policy if applicable. \"\"\" ENABLED = \"Enabled\"", "ssh port is open and accessible according to the VNet/subnet policy if applicable.", "both properties for enum members (which live in the class' __dict__) and enum", "DELETING = \"Deleting\" FAILED = \"Failed\" class PrivateEndpointServiceConnectionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The private endpoint", "= \"UserSettingUp\" USER_SETUP_FAILED = \"UserSetupFailed\" UNKNOWN = \"Unknown\" UNUSABLE = \"Unusable\" class ComputeType(with_metaclass(_CaseInsensitiveEnumMeta,", "\"InvalidQuotaExceedsSubscriptionLimit\" INVALID_VM_FAMILY_NAME = \"InvalidVMFamilyName\" OPERATION_NOT_SUPPORTED_FOR_SKU = \"OperationNotSupportedForSku\" OPERATION_NOT_ENABLED_FOR_REGION = \"OperationNotEnabledForRegion\" class UnderlyingResourceAction(with_metaclass(_CaseInsensitiveEnumMeta, str,", "to indicate states for resource provisioning. \"\"\" UNKNOWN = \"Unknown\" UPDATING = \"Updating\"", "enum members (which live in the class' __dict__) and enum members themselves. \"\"\"", "provisioningState is to indicate states for resource provisioning. \"\"\" UNKNOWN = \"Unknown\" UPDATING", "of time measurement for the specified VM price. Example: OneHour \"\"\" ONE_HOUR =", "if the code is regenerated. # -------------------------------------------------------------------------- from enum import Enum, EnumMeta from", "Enum)): \"\"\"Status of update workspace quota. \"\"\" UNDEFINED = \"Undefined\" SUCCESS = \"Success\"", "ComputeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The type of compute \"\"\" AKS = \"AKS\" AML_COMPUTE =", "__getattr__(cls, name): \"\"\"Return the enum member matching `name` We use __getattr__ instead of", "SHARED = \"Shared\" class BillingCurrency(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Three lettered code specifying the currency", "FAILURE = \"Failure\" INVALID_QUOTA_BELOW_CLUSTER_MINIMUM = \"InvalidQuotaBelowClusterMinimum\" INVALID_QUOTA_EXCEEDS_SUBSCRIPTION_LIMIT = \"InvalidQuotaExceedsSubscriptionLimit\" INVALID_VM_FAMILY_NAME = \"InvalidVMFamilyName\" OPERATION_NOT_SUPPORTED_FOR_SKU", "\"\"\"The type of the VM. \"\"\" STANDARD = \"Standard\" LOW_PRIORITY = \"LowPriority\" SPOT", "usage measurement. \"\"\" COUNT = \"Count\" class VMPriceOSType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Operating system type", "on this compute instance. When Shared, any workspace user can access applications on", "= \"DataLakeAnalytics\" class EncryptionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Indicates whether or not the encryption is", "Enum)): \"\"\"The current deployment state of workspace resource. The provisioningState is to indicate", "NOT_AVAILABLE_FOR_SUBSCRIPTION = \"NotAvailableForSubscription\" class RemoteLoginPortPublicAccess(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State of the public SSH port.", "the currency of the VM price. Example: USD \"\"\" USD = \"USD\" class", "- Indicates that the public ssh port is closed on this instance. Enabled", "AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost", "DISCONNECTED = \"Disconnected\" TIMEOUT = \"Timeout\" class ProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The current deployment", "= \"Creating\" DELETING = \"Deleting\" FAILED = \"Failed\" class PrivateEndpointServiceConnectionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The", "public ssh port is closed on all nodes of the cluster if VNet", "= \"Undefined\" SUCCESS = \"Success\" FAILURE = \"Failure\" INVALID_QUOTA_BELOW_CLUSTER_MINIMUM = \"InvalidQuotaBelowClusterMinimum\" INVALID_QUOTA_EXCEEDS_SUBSCRIPTION_LIMIT =", "= \"AmlCompute\" COMPUTE_INSTANCE = \"ComputeInstance\" DATA_FACTORY = \"DataFactory\" VIRTUAL_MACHINE = \"VirtualMachine\" HD_INSIGHT =", "FAILED = \"Failed\" CANCELED = \"Canceled\" class QuotaUnit(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"An enum describing", "UPDATING = \"Updating\" CREATING = \"Creating\" DELETING = \"Deleting\" SUCCEEDED = \"Succeeded\" FAILED", "= \"Restart\" REIMAGE = \"Reimage\" DELETE = \"Delete\" class OperationStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Operation", "or not the encryption is enabled for the workspace. \"\"\" ENABLED = \"Enabled\"", "private endpoint connection status. \"\"\" PENDING = \"Pending\" APPROVED = \"Approved\" REJECTED =", "DISABLED = \"Disabled\" class NodeState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State of the compute node. Values", "by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and", "\"Detach\" class UnitOfMeasure(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The unit of time measurement for the specified", "Enum)): \"\"\"Allocation state of the compute. Possible values are: steady - Indicates that", "str, Enum)): \"\"\"The unit of time measurement for the specified VM price. Example:", "super().__getitem__(name.upper()) def __getattr__(cls, name): \"\"\"Return the enum member matching `name` We use __getattr__", "the compute. Possible values are: steady - Indicates that the compute is not", "Indicates that the public ssh port is closed on all nodes of the", "it is created and when no operations are being performed on the compute", "START_FAILED = \"StartFailed\" STOP_FAILED = \"StopFailed\" RESTART_FAILED = \"RestartFailed\" REIMAGE_FAILED = \"ReimageFailed\" DELETE_FAILED", "\"VirtualMachine\" HD_INSIGHT = \"HDInsight\" DATABRICKS = \"Databricks\" DATA_LAKE_ANALYTICS = \"DataLakeAnalytics\" class EncryptionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str,", "Generator. # Changes may cause incorrect behavior and will be lost if the", "= \"SetupFailed\" STARTING = \"Starting\" STOPPED = \"Stopped\" STOPPING = \"Stopping\" USER_SETTING_UP =", "be lost if the code is regenerated. # -------------------------------------------------------------------------- from enum import Enum,", "is, compute nodes are being added to or removed from the compute. \"\"\"", "COUNT = \"Count\" class VMPriceOSType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Operating system type used by the", "class EncryptionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Indicates whether or not the encryption is enabled for", "\"Databricks\" DATA_LAKE_ANALYTICS = \"DataLakeAnalytics\" class EncryptionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Indicates whether or not the", "of a ComputeInstance. \"\"\" CREATING = \"Creating\" CREATE_FAILED = \"CreateFailed\" DELETING = \"Deleting\"", "= \"Reimage\" DELETE = \"Delete\" class OperationStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Operation status. \"\"\" IN_PROGRESS", "Possible values are: steady - Indicates that the compute is not resizing. There", "states for resource provisioning. \"\"\" UNKNOWN = \"Unknown\" UPDATING = \"Updating\" CREATING =", "Enabled - Indicates that the public ssh port is open on all nodes", "= \"Windows\" class VmPriority(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Virtual Machine priority \"\"\" DEDICATED = \"Dedicated\"", "are: Disabled - Indicates that the public ssh port is closed on all", "according to the VNet/subnet policy if applicable. \"\"\" ENABLED = \"Enabled\" DISABLED =", "\"SystemAssigned\" USER_ASSIGNED = \"UserAssigned\" SYSTEM_ASSIGNED_USER_ASSIGNED = \"SystemAssigned,UserAssigned\" NONE = \"None\" class SshPublicAccess(with_metaclass(_CaseInsensitiveEnumMeta, str,", "\"Restart\" REIMAGE = \"Reimage\" DELETE = \"Delete\" class OperationStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Operation status.", "identity type. \"\"\" SYSTEM_ASSIGNED = \"SystemAssigned\" USER_ASSIGNED = \"UserAssigned\" SYSTEM_ASSIGNED_USER_ASSIGNED = \"SystemAssigned,UserAssigned\" NONE", "Enum)): \"\"\"Operation status. \"\"\" IN_PROGRESS = \"InProgress\" SUCCEEDED = \"Succeeded\" CREATE_FAILED = \"CreateFailed\"", "\"Canceled\" class QuotaUnit(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"An enum describing the unit of quota measurement.", "= \"Databricks\" DATA_LAKE_ANALYTICS = \"DataLakeAnalytics\" class EncryptionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Indicates whether or not", "\"\"\" ENABLED = \"Enabled\" DISABLED = \"Disabled\" NOT_SPECIFIED = \"NotSpecified\" class ResourceIdentityType(with_metaclass(_CaseInsensitiveEnumMeta, str,", "\"Failed\" CANCELED = \"Canceled\" class QuotaUnit(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"An enum describing the unit", "accessible according to the VNet/subnet policy if applicable. \"\"\" ENABLED = \"Enabled\" DISABLED", "\"UserSettingUp\" USER_SETUP_FAILED = \"UserSetupFailed\" UNKNOWN = \"Unknown\" UNUSABLE = \"Unusable\" class ComputeType(with_metaclass(_CaseInsensitiveEnumMeta, str,", "access applications on this instance depending on his/her assigned role. \"\"\" PERSONAL =", "str, Enum)): \"\"\"Operating system type used by the VM. \"\"\" LINUX = \"Linux\"", "VmPriority(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Virtual Machine priority \"\"\" DEDICATED = \"Dedicated\" LOW_PRIORITY = \"LowPriority\"", "The provisioningState is to indicate states for resource provisioning. \"\"\" UNKNOWN = \"Unknown\"", "disable ssl for scoring \"\"\" DISABLED = \"Disabled\" ENABLED = \"Enabled\" class Status(with_metaclass(_CaseInsensitiveEnumMeta,", "state when it is created and when no operations are being performed on", "return cls._member_map_[name.upper()] except KeyError: raise AttributeError(name) class AllocationState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Allocation state of", "resizing. There are no changes to the number of compute nodes in the", "are: steady - Indicates that the compute is not resizing. There are no", "\"\"\" UNDEFINED = \"Undefined\" SUCCESS = \"Success\" FAILURE = \"Failure\" INVALID_QUOTA_BELOW_CLUSTER_MINIMUM = \"InvalidQuotaBelowClusterMinimum\"", "\"\"\" ENABLED = \"Enabled\" DISABLED = \"Disabled\" class SslConfigurationStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Enable or", "\"Unusable\" class ComputeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The type of compute \"\"\" AKS = \"AKS\"", "USER_SETUP_FAILED = \"UserSetupFailed\" UNKNOWN = \"Unknown\" UNUSABLE = \"Unusable\" class ComputeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):", "= \"Start\" STOP = \"Stop\" RESTART = \"Restart\" REIMAGE = \"Reimage\" DELETE =", "the enum member matching `name` We use __getattr__ instead of descriptors or inserting", "= \"Canceled\" class QuotaUnit(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"An enum describing the unit of quota", "instead of descriptors or inserting into the enum class' __dict__ in order to", "= \"Updating\" CREATING = \"Creating\" DELETING = \"Deleting\" SUCCEEDED = \"Succeeded\" FAILED =", "workspace quota. \"\"\" UNDEFINED = \"Undefined\" SUCCESS = \"Success\" FAILURE = \"Failure\" INVALID_QUOTA_BELOW_CLUSTER_MINIMUM", "the public SSH port. Possible values are: Disabled - Indicates that the public", "are: Disabled - Indicates that the public ssh port is closed on this", "creation it will be either enabled or disabled. \"\"\" ENABLED = \"Enabled\" DISABLED", "\"Stop\" RESTART = \"Restart\" REIMAGE = \"Reimage\" DELETE = \"Delete\" class OperationStatus(with_metaclass(_CaseInsensitiveEnumMeta, str,", "A compute enters this state when it is created and when no operations", "nodes of the cluster. NotSpecified - Indicates that the public ssh port is", "disabled. \"\"\" ENABLED = \"Enabled\" DISABLED = \"Disabled\" NOT_SPECIFIED = \"NotSpecified\" class ResourceIdentityType(with_metaclass(_CaseInsensitiveEnumMeta,", "class SshPublicAccess(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State of the public SSH port. Possible values are:", "\"Undefined\" SUCCESS = \"Success\" FAILURE = \"Failure\" INVALID_QUOTA_BELOW_CLUSTER_MINIMUM = \"InvalidQuotaBelowClusterMinimum\" INVALID_QUOTA_EXCEEDS_SUBSCRIPTION_LIMIT = \"InvalidQuotaExceedsSubscriptionLimit\"", "running, preparing, unusable, leaving and preempted. \"\"\" IDLE = \"idle\" RUNNING = \"running\"", "\"\"\" ONE_HOUR = \"OneHour\" class UsageUnit(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"An enum describing the unit", "of the last operation. \"\"\" CREATE = \"Create\" START = \"Start\" STOP =", "str, Enum)): \"\"\"Operation status. \"\"\" IN_PROGRESS = \"InProgress\" SUCCEEDED = \"Succeeded\" CREATE_FAILED =", "Enum)): \"\"\"State of the public SSH port. Possible values are: Disabled - Indicates", "AKS = \"AKS\" AML_COMPUTE = \"AmlCompute\" COMPUTE_INSTANCE = \"ComputeInstance\" DATA_FACTORY = \"DataFactory\" VIRTUAL_MACHINE", "str, Enum)): \"\"\"Current state of a ComputeInstance. \"\"\" CREATING = \"Creating\" CREATE_FAILED =", "describing the unit of quota measurement. \"\"\" COUNT = \"Count\" class ReasonCode(with_metaclass(_CaseInsensitiveEnumMeta, str,", "on all nodes of the cluster. NotSpecified - Indicates that the public ssh", "str, Enum)): \"\"\"Policy for sharing applications on this compute instance among users of", "nodes. It can be default only during cluster creation time, after creation it", "ssl for scoring \"\"\" DISABLED = \"Disabled\" ENABLED = \"Enabled\" class Status(with_metaclass(_CaseInsensitiveEnumMeta, str,", "or disable ssl for scoring \"\"\" DISABLED = \"Disabled\" ENABLED = \"Enabled\" class", "instance. Enabled - Indicates that the public ssh port is open and accessible", "\"\"\" COUNT = \"Count\" class VMPriceOSType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Operating system type used by", "\"\"\" DISABLED = \"Disabled\" ENABLED = \"Enabled\" class Status(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Status of", "the restriction. \"\"\" NOT_SPECIFIED = \"NotSpecified\" NOT_AVAILABLE_FOR_REGION = \"NotAvailableForRegion\" NOT_AVAILABLE_FOR_SUBSCRIPTION = \"NotAvailableForSubscription\" class", "\"Dedicated\" LOW_PRIORITY = \"LowPriority\" class VMTier(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The type of the VM.", "(c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See", "\"InProgress\" SUCCEEDED = \"Succeeded\" CREATE_FAILED = \"CreateFailed\" START_FAILED = \"StartFailed\" STOP_FAILED = \"StopFailed\"", "members (which live in the class' __dict__) and enum members themselves. \"\"\" try:", "= \"Unknown\" UPDATING = \"Updating\" CREATING = \"Creating\" DELETING = \"Deleting\" SUCCEEDED =", "SSH port. Possible values are: Disabled - Indicates that the public ssh port", "themselves. \"\"\" try: return cls._member_map_[name.upper()] except KeyError: raise AttributeError(name) class AllocationState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):", "to the VNet/subnet policy if applicable. \"\"\" ENABLED = \"Enabled\" DISABLED = \"Disabled\"", "last operation. \"\"\" CREATE = \"Create\" START = \"Start\" STOP = \"Stop\" RESTART", "port is open and accessible according to the VNet/subnet policy if applicable. \"\"\"", "= \"CreateFailed\" START_FAILED = \"StartFailed\" STOP_FAILED = \"StopFailed\" RESTART_FAILED = \"RestartFailed\" REIMAGE_FAILED =", "closed on all nodes of the cluster if VNet is defined, else is", "all nodes of the cluster if VNet is defined, else is open all", "\"UserSetupFailed\" UNKNOWN = \"Unknown\" UNUSABLE = \"Unusable\" class ComputeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The type", "\"\"\" try: return cls._member_map_[name.upper()] except KeyError: raise AttributeError(name) class AllocationState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Allocation", "compute in progress. A compute enters this state when it is created and", "ENABLED = \"Enabled\" class Status(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Status of update workspace quota. \"\"\"", "Enum)): \"\"\"Enable or disable ssl for scoring \"\"\" DISABLED = \"Disabled\" ENABLED =", "all nodes of the cluster. NotSpecified - Indicates that the public ssh port", "regenerated. # -------------------------------------------------------------------------- from enum import Enum, EnumMeta from six import with_metaclass class", "CREATING = \"Creating\" DELETING = \"Deleting\" SUCCEEDED = \"Succeeded\" FAILED = \"Failed\" CANCELED", "this instance. Enabled - Indicates that the public ssh port is open and", "\"Failure\" INVALID_QUOTA_BELOW_CLUSTER_MINIMUM = \"InvalidQuotaBelowClusterMinimum\" INVALID_QUOTA_EXCEEDS_SUBSCRIPTION_LIMIT = \"InvalidQuotaExceedsSubscriptionLimit\" INVALID_VM_FAMILY_NAME = \"InvalidVMFamilyName\" OPERATION_NOT_SUPPORTED_FOR_SKU = \"OperationNotSupportedForSku\"", "= \"Creating\" CREATE_FAILED = \"CreateFailed\" DELETING = \"Deleting\" RUNNING = \"Running\" RESTARTING =", "cluster creation time, after creation it will be either enabled or disabled. \"\"\"", "Enum)): \"\"\"Three lettered code specifying the currency of the VM price. Example: USD", "used by the VM. \"\"\" LINUX = \"Linux\" WINDOWS = \"Windows\" class VmPriority(with_metaclass(_CaseInsensitiveEnumMeta,", "connection status. \"\"\" PENDING = \"Pending\" APPROVED = \"Approved\" REJECTED = \"Rejected\" DISCONNECTED", "DATA_LAKE_ANALYTICS = \"DataLakeAnalytics\" class EncryptionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Indicates whether or not the encryption", "__dict__) and enum members themselves. \"\"\" try: return cls._member_map_[name.upper()] except KeyError: raise AttributeError(name)", "to change the number of compute nodes. resizing - Indicates that the compute", "\"Deleting\" FAILED = \"Failed\" class PrivateEndpointServiceConnectionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The private endpoint connection status.", "REIMAGE = \"Reimage\" DELETE = \"Delete\" class OperationStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Operation status. \"\"\"", "not the encryption is enabled for the workspace. \"\"\" ENABLED = \"Enabled\" DISABLED", "\"RestartFailed\" REIMAGE_FAILED = \"ReimageFailed\" DELETE_FAILED = \"DeleteFailed\" class PrivateEndpointConnectionProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The current", "inserting into the enum class' __dict__ in order to support `name` and `value`", "change the number of compute nodes. resizing - Indicates that the compute is", "\"StartFailed\" STOP_FAILED = \"StopFailed\" RESTART_FAILED = \"RestartFailed\" REIMAGE_FAILED = \"ReimageFailed\" DELETE_FAILED = \"DeleteFailed\"", "for scoring \"\"\" DISABLED = \"Disabled\" ENABLED = \"Enabled\" class Status(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):", "project root for license information. # Code generated by Microsoft (R) AutoRest Code", "raise AttributeError(name) class AllocationState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Allocation state of the compute. Possible values", "\"Succeeded\" CREATE_FAILED = \"CreateFailed\" START_FAILED = \"StartFailed\" STOP_FAILED = \"StopFailed\" RESTART_FAILED = \"RestartFailed\"", "= \"DeleteFailed\" class PrivateEndpointConnectionProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The current provisioning state. \"\"\" SUCCEEDED =", "TIMEOUT = \"Timeout\" class ProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The current deployment state of workspace", "public SSH port. Possible values are: Disabled - Indicates that the public ssh", "class OperationStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Operation status. \"\"\" IN_PROGRESS = \"InProgress\" SUCCEEDED = \"Succeeded\"", "= \"Succeeded\" FAILED = \"Failed\" CANCELED = \"Canceled\" class QuotaUnit(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"An", "\"Enabled\" DISABLED = \"Disabled\" class NodeState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State of the compute node.", "in the project root for license information. # Code generated by Microsoft (R)", "being added to or removed from the compute. \"\"\" STEADY = \"Steady\" RESIZING", "- Indicates that the compute is not resizing. There are no changes to", "specifying the currency of the VM price. Example: USD \"\"\" USD = \"USD\"", "Enum)): \"\"\"The identity type. \"\"\" SYSTEM_ASSIGNED = \"SystemAssigned\" USER_ASSIGNED = \"UserAssigned\" SYSTEM_ASSIGNED_USER_ASSIGNED =", "= \"Stopping\" USER_SETTING_UP = \"UserSettingUp\" USER_SETUP_FAILED = \"UserSetupFailed\" UNKNOWN = \"Unknown\" UNUSABLE =", "Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License.", "state of workspace resource. The provisioningState is to indicate states for resource provisioning.", "class RemoteLoginPortPublicAccess(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State of the public SSH port. Possible values are:", "root for license information. # Code generated by Microsoft (R) AutoRest Code Generator.", "compute nodes. resizing - Indicates that the compute is resizing; that is, compute", "= \"Delete\" class OperationStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Operation status. \"\"\" IN_PROGRESS = \"InProgress\" SUCCEEDED", "\"DeleteFailed\" class PrivateEndpointConnectionProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The current provisioning state. \"\"\" SUCCEEDED = \"Succeeded\"", "compute nodes in the compute in progress. A compute enters this state when", "class SslConfigurationStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Enable or disable ssl for scoring \"\"\" DISABLED =", "= \"Failed\" CANCELED = \"Canceled\" class QuotaUnit(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"An enum describing the", "= \"Succeeded\" CREATE_FAILED = \"CreateFailed\" START_FAILED = \"StartFailed\" STOP_FAILED = \"StopFailed\" RESTART_FAILED =", "= \"Enabled\" class Status(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Status of update workspace quota. \"\"\" UNDEFINED", "\"Disabled\" class NodeState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State of the compute node. Values are idle,", "\"Enabled\" DISABLED = \"Disabled\" NOT_SPECIFIED = \"NotSpecified\" class ResourceIdentityType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The identity", "is resizing; that is, compute nodes are being added to or removed from", "only the creator can access applications on this compute instance. When Shared, any", "Changes may cause incorrect behavior and will be lost if the code is", "compute is not resizing. There are no changes to the number of compute", "the creator can access applications on this compute instance. When Shared, any workspace", "\"Stopping\" USER_SETTING_UP = \"UserSettingUp\" USER_SETUP_FAILED = \"UserSetupFailed\" UNKNOWN = \"Unknown\" UNUSABLE = \"Unusable\"", "\"Creating\" DELETING = \"Deleting\" SUCCEEDED = \"Succeeded\" FAILED = \"Failed\" CANCELED = \"Canceled\"", "\"Running\" RESTARTING = \"Restarting\" JOB_RUNNING = \"JobRunning\" SETTING_UP = \"SettingUp\" SETUP_FAILED = \"SetupFailed\"", "= \"unusable\" LEAVING = \"leaving\" PREEMPTED = \"preempted\" class OperationName(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Name", "the cluster. Enabled - Indicates that the public ssh port is open on", "\"\"\" PENDING = \"Pending\" APPROVED = \"Approved\" REJECTED = \"Rejected\" DISCONNECTED = \"Disconnected\"", "\"\"\" IDLE = \"idle\" RUNNING = \"running\" PREPARING = \"preparing\" UNUSABLE = \"unusable\"", "\"\"\"Status of update workspace quota. \"\"\" UNDEFINED = \"Undefined\" SUCCESS = \"Success\" FAILURE", "compute node. Values are idle, running, preparing, unusable, leaving and preempted. \"\"\" IDLE", "that the public ssh port is closed on all nodes of the cluster.", "the enum class' __dict__ in order to support `name` and `value` being both", "License. See License.txt in the project root for license information. # Code generated", "Enum)): \"\"\"The type of compute \"\"\" AKS = \"AKS\" AML_COMPUTE = \"AmlCompute\" COMPUTE_INSTANCE", "RESTART_FAILED = \"RestartFailed\" REIMAGE_FAILED = \"ReimageFailed\" DELETE_FAILED = \"DeleteFailed\" class PrivateEndpointConnectionProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):", "MIT License. See License.txt in the project root for license information. # Code", "parent workspace. If Personal, only the creator can access applications on this compute", "DATABRICKS = \"Databricks\" DATA_LAKE_ANALYTICS = \"DataLakeAnalytics\" class EncryptionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Indicates whether or", "\"NotAvailableForRegion\" NOT_AVAILABLE_FOR_SUBSCRIPTION = \"NotAvailableForSubscription\" class RemoteLoginPortPublicAccess(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State of the public SSH", "= \"idle\" RUNNING = \"running\" PREPARING = \"preparing\" UNUSABLE = \"unusable\" LEAVING =", "be default only during cluster creation time, after creation it will be either", "(which live in the class' __dict__) and enum members themselves. \"\"\" try: return", "depending on his/her assigned role. \"\"\" PERSONAL = \"Personal\" SHARED = \"Shared\" class", "= \"JobRunning\" SETTING_UP = \"SettingUp\" SETUP_FAILED = \"SetupFailed\" STARTING = \"Starting\" STOPPED =", "= \"AKS\" AML_COMPUTE = \"AmlCompute\" COMPUTE_INSTANCE = \"ComputeInstance\" DATA_FACTORY = \"DataFactory\" VIRTUAL_MACHINE =", "\"Stopped\" STOPPING = \"Stopping\" USER_SETTING_UP = \"UserSettingUp\" USER_SETUP_FAILED = \"UserSetupFailed\" UNKNOWN = \"Unknown\"", "unusable, leaving and preempted. \"\"\" IDLE = \"idle\" RUNNING = \"running\" PREPARING =", "\"Create\" START = \"Start\" STOP = \"Stop\" RESTART = \"Restart\" REIMAGE = \"Reimage\"", "VMPriceOSType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Operating system type used by the VM. \"\"\" LINUX =", "UNKNOWN = \"Unknown\" UNUSABLE = \"Unusable\" class ComputeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The type of", "= \"SystemAssigned,UserAssigned\" NONE = \"None\" class SshPublicAccess(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State of the public", "= \"Unusable\" class ComputeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The type of compute \"\"\" AKS =", "COMPUTE_INSTANCE = \"ComputeInstance\" DATA_FACTORY = \"DataFactory\" VIRTUAL_MACHINE = \"VirtualMachine\" HD_INSIGHT = \"HDInsight\" DATABRICKS", "the compute to change the number of compute nodes. resizing - Indicates that", "and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from enum", "\"\"\"The unit of time measurement for the specified VM price. Example: OneHour \"\"\"", "the public ssh port is closed on all nodes of the cluster if", "the unit of quota measurement. \"\"\" COUNT = \"Count\" class ReasonCode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):", "of quota measurement. \"\"\" COUNT = \"Count\" class ReasonCode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The reason", "on all nodes of the cluster if VNet is defined, else is open", "def __getattr__(cls, name): \"\"\"Return the enum member matching `name` We use __getattr__ instead", "compute is resizing; that is, compute nodes are being added to or removed", "= \"Unknown\" UNUSABLE = \"Unusable\" class ComputeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The type of compute", "of the compute node. Values are idle, running, preparing, unusable, leaving and preempted.", "We use __getattr__ instead of descriptors or inserting into the enum class' __dict__", "= \"Create\" START = \"Start\" STOP = \"Stop\" RESTART = \"Restart\" REIMAGE =", "public ssh port is open and accessible according to the VNet/subnet policy if", "class UsageUnit(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"An enum describing the unit of usage measurement. \"\"\"", "ComputeInstanceState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Current state of a ComputeInstance. \"\"\" CREATING = \"Creating\" CREATE_FAILED", "under the MIT License. See License.txt in the project root for license information.", "instance depending on his/her assigned role. \"\"\" PERSONAL = \"Personal\" SHARED = \"Shared\"", "Indicates that the public ssh port is open on all nodes of the", "\"\"\"The current deployment state of workspace resource. The provisioningState is to indicate states", "members themselves. \"\"\" try: return cls._member_map_[name.upper()] except KeyError: raise AttributeError(name) class AllocationState(with_metaclass(_CaseInsensitiveEnumMeta, str,", "class ComputeInstanceState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Current state of a ComputeInstance. \"\"\" CREATING = \"Creating\"", "= \"LowPriority\" class VMTier(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The type of the VM. \"\"\" STANDARD", "operation. \"\"\" CREATE = \"Create\" START = \"Start\" STOP = \"Stop\" RESTART =", "= \"running\" PREPARING = \"preparing\" UNUSABLE = \"unusable\" LEAVING = \"leaving\" PREEMPTED =", "the class' __dict__) and enum members themselves. \"\"\" try: return cls._member_map_[name.upper()] except KeyError:", "the number of compute nodes in the compute in progress. A compute enters", "price. Example: USD \"\"\" USD = \"USD\" class ComputeInstanceState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Current state", "\"\"\" PERSONAL = \"Personal\" SHARED = \"Shared\" class BillingCurrency(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Three lettered", "to support `name` and `value` being both properties for enum members (which live", "Personal, only the creator can access applications on this compute instance. When Shared,", "ENABLED = \"Enabled\" DISABLED = \"Disabled\" class NodeState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State of the", "public nodes. It can be default only during cluster creation time, after creation", "either enabled or disabled. \"\"\" ENABLED = \"Enabled\" DISABLED = \"Disabled\" NOT_SPECIFIED =", "= \"NotSpecified\" class ResourceIdentityType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The identity type. \"\"\" SYSTEM_ASSIGNED = \"SystemAssigned\"", "not resizing. There are no changes to the number of compute nodes in", "the public ssh port is open on all nodes of the cluster. NotSpecified", "UnderlyingResourceAction(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): DELETE = \"Delete\" DETACH = \"Detach\" class UnitOfMeasure(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):", "number of compute nodes in the compute in progress. A compute enters this", "type. \"\"\" SYSTEM_ASSIGNED = \"SystemAssigned\" USER_ASSIGNED = \"UserAssigned\" SYSTEM_ASSIGNED_USER_ASSIGNED = \"SystemAssigned,UserAssigned\" NONE =", "VM. \"\"\" LINUX = \"Linux\" WINDOWS = \"Windows\" class VmPriority(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Virtual", "NOT_SPECIFIED = \"NotSpecified\" NOT_AVAILABLE_FOR_REGION = \"NotAvailableForRegion\" NOT_AVAILABLE_FOR_SUBSCRIPTION = \"NotAvailableForSubscription\" class RemoteLoginPortPublicAccess(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):", "Enum)): DELETE = \"Delete\" DETACH = \"Detach\" class UnitOfMeasure(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The unit", "workspace. If Personal, only the creator can access applications on this compute instance.", "operations are being performed on the compute to change the number of compute", "is open on all nodes of the cluster. NotSpecified - Indicates that the", "steady - Indicates that the compute is not resizing. There are no changes", "= \"Steady\" RESIZING = \"Resizing\" class ApplicationSharingPolicy(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Policy for sharing applications", "nodes. resizing - Indicates that the compute is resizing; that is, compute nodes", "of the VM price. Example: USD \"\"\" USD = \"USD\" class ComputeInstanceState(with_metaclass(_CaseInsensitiveEnumMeta, str,", "for the restriction. \"\"\" NOT_SPECIFIED = \"NotSpecified\" NOT_AVAILABLE_FOR_REGION = \"NotAvailableForRegion\" NOT_AVAILABLE_FOR_SUBSCRIPTION = \"NotAvailableForSubscription\"", "the public ssh port is open and accessible according to the VNet/subnet policy", "SETUP_FAILED = \"SetupFailed\" STARTING = \"Starting\" STOPPED = \"Stopped\" STOPPING = \"Stopping\" USER_SETTING_UP", "= \"Stop\" RESTART = \"Restart\" REIMAGE = \"Reimage\" DELETE = \"Delete\" class OperationStatus(with_metaclass(_CaseInsensitiveEnumMeta,", "workspace user can access applications on this instance depending on his/her assigned role.", "str, Enum)): \"\"\"Name of the last operation. \"\"\" CREATE = \"Create\" START =", "LINUX = \"Linux\" WINDOWS = \"Windows\" class VmPriority(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Virtual Machine priority", "\"\"\" DEDICATED = \"Dedicated\" LOW_PRIORITY = \"LowPriority\" class VMTier(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The type", "on the compute to change the number of compute nodes. resizing - Indicates", "DELETE = \"Delete\" class OperationStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Operation status. \"\"\" IN_PROGRESS = \"InProgress\"", "= \"Linux\" WINDOWS = \"Windows\" class VmPriority(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Virtual Machine priority \"\"\"", "= \"Deleting\" RUNNING = \"Running\" RESTARTING = \"Restarting\" JOB_RUNNING = \"JobRunning\" SETTING_UP =", "= \"None\" class SshPublicAccess(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State of the public SSH port. Possible", "- Indicates that the public ssh port is open on all nodes of", "str, Enum)): \"\"\"Three lettered code specifying the currency of the VM price. Example:", "DELETE = \"Delete\" DETACH = \"Detach\" class UnitOfMeasure(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The unit of", "Licensed under the MIT License. See License.txt in the project root for license", "is open all public nodes. It can be default only during cluster creation", "= \"Timeout\" class ProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The current deployment state of workspace resource.", "the workspace. \"\"\" ENABLED = \"Enabled\" DISABLED = \"Disabled\" class NodeState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):", "START = \"Start\" STOP = \"Stop\" RESTART = \"Restart\" REIMAGE = \"Reimage\" DELETE", "Indicates that the compute is not resizing. There are no changes to the", "= \"Rejected\" DISCONNECTED = \"Disconnected\" TIMEOUT = \"Timeout\" class ProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The", "USER_SETTING_UP = \"UserSettingUp\" USER_SETUP_FAILED = \"UserSetupFailed\" UNKNOWN = \"Unknown\" UNUSABLE = \"Unusable\" class", "= \"Disconnected\" TIMEOUT = \"Timeout\" class ProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The current deployment state", "See License.txt in the project root for license information. # Code generated by", "REIMAGE_FAILED = \"ReimageFailed\" DELETE_FAILED = \"DeleteFailed\" class PrivateEndpointConnectionProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The current provisioning", "are being added to or removed from the compute. \"\"\" STEADY = \"Steady\"", "str, Enum)): \"\"\"The type of compute \"\"\" AKS = \"AKS\" AML_COMPUTE = \"AmlCompute\"", "for enum members (which live in the class' __dict__) and enum members themselves.", "preempted. \"\"\" IDLE = \"idle\" RUNNING = \"running\" PREPARING = \"preparing\" UNUSABLE =", "CREATING = \"Creating\" CREATE_FAILED = \"CreateFailed\" DELETING = \"Deleting\" RUNNING = \"Running\" RESTARTING", "class PrivateEndpointServiceConnectionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The private endpoint connection status. \"\"\" PENDING = \"Pending\"", "creator can access applications on this compute instance. When Shared, any workspace user", "Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in", "\"Timeout\" class ProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The current deployment state of workspace resource. The", "enum describing the unit of quota measurement. \"\"\" COUNT = \"Count\" class ReasonCode(with_metaclass(_CaseInsensitiveEnumMeta,", "on this instance. Enabled - Indicates that the public ssh port is open", "Disabled - Indicates that the public ssh port is closed on all nodes", "enum describing the unit of usage measurement. \"\"\" COUNT = \"Count\" class VMPriceOSType(with_metaclass(_CaseInsensitiveEnumMeta,", "ApplicationSharingPolicy(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Policy for sharing applications on this compute instance among users", "\"AKS\" AML_COMPUTE = \"AmlCompute\" COMPUTE_INSTANCE = \"ComputeInstance\" DATA_FACTORY = \"DataFactory\" VIRTUAL_MACHINE = \"VirtualMachine\"", "import with_metaclass class _CaseInsensitiveEnumMeta(EnumMeta): def __getitem__(self, name): return super().__getitem__(name.upper()) def __getattr__(cls, name): \"\"\"Return", "class' __dict__ in order to support `name` and `value` being both properties for", "else is open all public nodes. It can be default only during cluster", "= \"Pending\" APPROVED = \"Approved\" REJECTED = \"Rejected\" DISCONNECTED = \"Disconnected\" TIMEOUT =", "= \"leaving\" PREEMPTED = \"preempted\" class OperationName(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Name of the last", "compute enters this state when it is created and when no operations are", "class ResourceIdentityType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The identity type. \"\"\" SYSTEM_ASSIGNED = \"SystemAssigned\" USER_ASSIGNED =", "it will be either enabled or disabled. \"\"\" ENABLED = \"Enabled\" DISABLED =", "\"NotSpecified\" class ResourceIdentityType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The identity type. \"\"\" SYSTEM_ASSIGNED = \"SystemAssigned\" USER_ASSIGNED", "rights reserved. # Licensed under the MIT License. See License.txt in the project", "\"\"\"State of the public SSH port. Possible values are: Disabled - Indicates that", "is to indicate states for resource provisioning. \"\"\" UNKNOWN = \"Unknown\" UPDATING =", "\"\"\"Three lettered code specifying the currency of the VM price. Example: USD \"\"\"", "USD = \"USD\" class ComputeInstanceState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Current state of a ComputeInstance. \"\"\"", "type used by the VM. \"\"\" LINUX = \"Linux\" WINDOWS = \"Windows\" class", "can be default only during cluster creation time, after creation it will be", "status. \"\"\" IN_PROGRESS = \"InProgress\" SUCCEEDED = \"Succeeded\" CREATE_FAILED = \"CreateFailed\" START_FAILED =", "= \"Success\" FAILURE = \"Failure\" INVALID_QUOTA_BELOW_CLUSTER_MINIMUM = \"InvalidQuotaBelowClusterMinimum\" INVALID_QUOTA_EXCEEDS_SUBSCRIPTION_LIMIT = \"InvalidQuotaExceedsSubscriptionLimit\" INVALID_VM_FAMILY_NAME =", "compute nodes are being added to or removed from the compute. \"\"\" STEADY", "code specifying the currency of the VM price. Example: USD \"\"\" USD =", "# Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause", "class ComputeType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The type of compute \"\"\" AKS = \"AKS\" AML_COMPUTE", "class VMTier(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The type of the VM. \"\"\" STANDARD = \"Standard\"", "import Enum, EnumMeta from six import with_metaclass class _CaseInsensitiveEnumMeta(EnumMeta): def __getitem__(self, name): return", "\"AmlCompute\" COMPUTE_INSTANCE = \"ComputeInstance\" DATA_FACTORY = \"DataFactory\" VIRTUAL_MACHINE = \"VirtualMachine\" HD_INSIGHT = \"HDInsight\"", "nodes are being added to or removed from the compute. \"\"\" STEADY =", "STOPPED = \"Stopped\" STOPPING = \"Stopping\" USER_SETTING_UP = \"UserSettingUp\" USER_SETUP_FAILED = \"UserSetupFailed\" UNKNOWN", "= \"DataFactory\" VIRTUAL_MACHINE = \"VirtualMachine\" HD_INSIGHT = \"HDInsight\" DATABRICKS = \"Databricks\" DATA_LAKE_ANALYTICS =", "STOPPING = \"Stopping\" USER_SETTING_UP = \"UserSettingUp\" USER_SETUP_FAILED = \"UserSetupFailed\" UNKNOWN = \"Unknown\" UNUSABLE", "that the compute is resizing; that is, compute nodes are being added to", "-------------------------------------------------------------------------- from enum import Enum, EnumMeta from six import with_metaclass class _CaseInsensitiveEnumMeta(EnumMeta): def", "`name` and `value` being both properties for enum members (which live in the", "is enabled for the workspace. \"\"\" ENABLED = \"Enabled\" DISABLED = \"Disabled\" class", "ssh port is open on all nodes of the cluster. NotSpecified - Indicates", "\"Count\" class VMPriceOSType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Operating system type used by the VM. \"\"\"", "is defined, else is open all public nodes. It can be default only", "provisioning state. \"\"\" SUCCEEDED = \"Succeeded\" CREATING = \"Creating\" DELETING = \"Deleting\" FAILED", "\"\"\" IN_PROGRESS = \"InProgress\" SUCCEEDED = \"Succeeded\" CREATE_FAILED = \"CreateFailed\" START_FAILED = \"StartFailed\"", "measurement. \"\"\" COUNT = \"Count\" class VMPriceOSType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Operating system type used", "VNet is defined, else is open all public nodes. It can be default", "-------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the", "the compute. \"\"\" STEADY = \"Steady\" RESIZING = \"Resizing\" class ApplicationSharingPolicy(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):", "VM price. Example: USD \"\"\" USD = \"USD\" class ComputeInstanceState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Current", "REJECTED = \"Rejected\" DISCONNECTED = \"Disconnected\" TIMEOUT = \"Timeout\" class ProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):", "\"\"\"Virtual Machine priority \"\"\" DEDICATED = \"Dedicated\" LOW_PRIORITY = \"LowPriority\" class VMTier(with_metaclass(_CaseInsensitiveEnumMeta, str,", "order to support `name` and `value` being both properties for enum members (which", "Shared, any workspace user can access applications on this instance depending on his/her", "nodes of the cluster. Enabled - Indicates that the public ssh port is", "= \"OneHour\" class UsageUnit(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"An enum describing the unit of usage", "def __getitem__(self, name): return super().__getitem__(name.upper()) def __getattr__(cls, name): \"\"\"Return the enum member matching", "NodeState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State of the compute node. Values are idle, running, preparing,", "enum member matching `name` We use __getattr__ instead of descriptors or inserting into", "\"Disconnected\" TIMEOUT = \"Timeout\" class ProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The current deployment state of", "Enum, EnumMeta from six import with_metaclass class _CaseInsensitiveEnumMeta(EnumMeta): def __getitem__(self, name): return super().__getitem__(name.upper())", "\"HDInsight\" DATABRICKS = \"Databricks\" DATA_LAKE_ANALYTICS = \"DataLakeAnalytics\" class EncryptionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Indicates whether", "\"\"\"Allocation state of the compute. Possible values are: steady - Indicates that the", "nodes of the cluster if VNet is defined, else is open all public", "= \"OperationNotEnabledForRegion\" class UnderlyingResourceAction(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): DELETE = \"Delete\" DETACH = \"Detach\" class", "= \"Deleting\" FAILED = \"Failed\" class PrivateEndpointServiceConnectionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The private endpoint connection", "<filename>sdk/machinelearning/azure-mgmt-machinelearningservices/azure/mgmt/machinelearningservices/models/_azure_machine_learning_workspaces_enums.py # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved.", "cluster. NotSpecified - Indicates that the public ssh port is closed on all", "for sharing applications on this compute instance among users of parent workspace. If", "from six import with_metaclass class _CaseInsensitiveEnumMeta(EnumMeta): def __getitem__(self, name): return super().__getitem__(name.upper()) def __getattr__(cls,", "generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior", "KeyError: raise AttributeError(name) class AllocationState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Allocation state of the compute. Possible", "applications on this compute instance among users of parent workspace. If Personal, only", "in progress. A compute enters this state when it is created and when", "quota measurement. \"\"\" COUNT = \"Count\" class ReasonCode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The reason for", "class UnitOfMeasure(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The unit of time measurement for the specified VM", "When Shared, any workspace user can access applications on this instance depending on", "class ProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The current deployment state of workspace resource. The provisioningState", "Example: OneHour \"\"\" ONE_HOUR = \"OneHour\" class UsageUnit(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"An enum describing", "UnitOfMeasure(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The unit of time measurement for the specified VM price.", "\"Succeeded\" CREATING = \"Creating\" DELETING = \"Deleting\" FAILED = \"Failed\" class PrivateEndpointServiceConnectionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str,", "and `value` being both properties for enum members (which live in the class'", "public ssh port is closed on all nodes of the cluster. Enabled -", "during cluster creation time, after creation it will be either enabled or disabled.", "applications on this instance depending on his/her assigned role. \"\"\" PERSONAL = \"Personal\"", "str, Enum)): \"\"\"State of the compute node. Values are idle, running, preparing, unusable,", "open all public nodes. It can be default only during cluster creation time,", "class AllocationState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Allocation state of the compute. Possible values are: steady", "that the public ssh port is closed on this instance. Enabled - Indicates", "unit of usage measurement. \"\"\" COUNT = \"Count\" class VMPriceOSType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"Operating", "\"idle\" RUNNING = \"running\" PREPARING = \"preparing\" UNUSABLE = \"unusable\" LEAVING = \"leaving\"", "member matching `name` We use __getattr__ instead of descriptors or inserting into the", "Disabled - Indicates that the public ssh port is closed on this instance.", "are no changes to the number of compute nodes in the compute in", "among users of parent workspace. If Personal, only the creator can access applications", "\"Failed\" class PrivateEndpointServiceConnectionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The private endpoint connection status. \"\"\" PENDING =", "is closed on this instance. Enabled - Indicates that the public ssh port", "\"Disabled\" NOT_SPECIFIED = \"NotSpecified\" class ResourceIdentityType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The identity type. \"\"\" SYSTEM_ASSIGNED", "the code is regenerated. # -------------------------------------------------------------------------- from enum import Enum, EnumMeta from six", "measurement for the specified VM price. Example: OneHour \"\"\" ONE_HOUR = \"OneHour\" class", "class PrivateEndpointConnectionProvisioningState(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"The current provisioning state. \"\"\" SUCCEEDED = \"Succeeded\" CREATING", "USER_ASSIGNED = \"UserAssigned\" SYSTEM_ASSIGNED_USER_ASSIGNED = \"SystemAssigned,UserAssigned\" NONE = \"None\" class SshPublicAccess(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):", "STOP_FAILED = \"StopFailed\" RESTART_FAILED = \"RestartFailed\" REIMAGE_FAILED = \"ReimageFailed\" DELETE_FAILED = \"DeleteFailed\" class", "this instance depending on his/her assigned role. \"\"\" PERSONAL = \"Personal\" SHARED =", "ComputeInstance. \"\"\" CREATING = \"Creating\" CREATE_FAILED = \"CreateFailed\" DELETING = \"Deleting\" RUNNING =", "NOT_AVAILABLE_FOR_REGION = \"NotAvailableForRegion\" NOT_AVAILABLE_FOR_SUBSCRIPTION = \"NotAvailableForSubscription\" class RemoteLoginPortPublicAccess(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): \"\"\"State of the", "cluster. Enabled - Indicates that the public ssh port is open on all", "# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. #" ]
[ "We convert the images to floating point in range 0.0 - 1.0 face_part", "-1)) return emojis[0:len(emojis) - 1] def overlay(image, emoji, x, y, w, h): emoji", "w] = blend_transparent(image[y:y + h, x:x + w], emoji) except: pass return image", "overlay_part, 255.0, 0.0)) def rescale_frame(frame, percent=75): width = int(frame.shape[1] * percent / 100)", "+ w] = blend_transparent(image[y:y + h, x:x + w], emoji) except: pass return", "255.0)) * (background_mask * (1 / 255.0)) overlay_part = (overlay_img * (1 /", "1.0 face_part = (face_img * (1 / 255.0)) * (background_mask * (1 /", "def rescale_frame(frame, percent=75): width = int(frame.shape[1] * percent / 100) height = int(frame.shape[0]", "alpha plane # Again calculate the inverse mask background_mask = 255 - overlay_mask", "np def get_emojis(): emojis_folder = 'emoji/' emojis = [] for emoji in range(len(os.listdir(emojis_folder))):", "= cv2.resize(emoji, (w, h)) try: image[y:y + h, x:x + w] = blend_transparent(image[y:y", "x, y, w, h): emoji = cv2.resize(emoji, (w, h)) try: image[y:y + h,", "Split out the transparency mask from the colour info overlay_img = overlay_t_img[:, :,", "* (overlay_mask * (1 / 255.0)) # And finally just add them together,", "background_mask = 255 - overlay_mask # Turn the masks into three channel, so", "= cv2.cvtColor(overlay_mask, cv2.COLOR_GRAY2BGR) background_mask = cv2.cvtColor(background_mask, cv2.COLOR_GRAY2BGR) # Create a masked out face", "# Create a masked out face image, and masked out overlay # We", ":, :3] # Grab the BRG planes overlay_mask = overlay_t_img[:, :, 3:] #", "mask from the colour info overlay_img = overlay_t_img[:, :, :3] # Grab the", "h, x:x + w], emoji) except: pass return image def blend_transparent(face_img, overlay_t_img): #", "Grab the BRG planes overlay_mask = overlay_t_img[:, :, 3:] # And the alpha", "weights overlay_mask = cv2.cvtColor(overlay_mask, cv2.COLOR_GRAY2BGR) background_mask = cv2.cvtColor(background_mask, cv2.COLOR_GRAY2BGR) # Create a masked", "= blend_transparent(image[y:y + h, x:x + w], emoji) except: pass return image def", "/ 255.0)) # And finally just add them together, and rescale it back", "import numpy as np def get_emojis(): emojis_folder = 'emoji/' emojis = [] for", "in range(len(os.listdir(emojis_folder))): print(emoji) emojis.append(cv2.imread(emojis_folder + str(emoji) + '.png', -1)) return emojis[0:len(emojis) - 1]", "x:x + w], emoji) except: pass return image def blend_transparent(face_img, overlay_t_img): # Split", "background_mask = cv2.cvtColor(background_mask, cv2.COLOR_GRAY2BGR) # Create a masked out face image, and masked", "import cv2 import numpy as np def get_emojis(): emojis_folder = 'emoji/' emojis =", "(1 / 255.0)) overlay_part = (overlay_img * (1 / 255.0)) * (overlay_mask *", "print(emoji) emojis.append(cv2.imread(emojis_folder + str(emoji) + '.png', -1)) return emojis[0:len(emojis) - 1] def overlay(image,", "'emoji/' emojis = [] for emoji in range(len(os.listdir(emojis_folder))): print(emoji) emojis.append(cv2.imread(emojis_folder + str(emoji) +", "overlay_img = overlay_t_img[:, :, :3] # Grab the BRG planes overlay_mask = overlay_t_img[:,", "= overlay_t_img[:, :, :3] # Grab the BRG planes overlay_mask = overlay_t_img[:, :,", "cv2 import numpy as np def get_emojis(): emojis_folder = 'emoji/' emojis = []", "w, h): emoji = cv2.resize(emoji, (w, h)) try: image[y:y + h, x:x +", "overlay_t_img[:, :, 3:] # And the alpha plane # Again calculate the inverse", "finally just add them together, and rescale it back to an 8bit integer", "out face image, and masked out overlay # We convert the images to", "emoji = cv2.resize(emoji, (w, h)) try: image[y:y + h, x:x + w] =", "(overlay_mask * (1 / 255.0)) # And finally just add them together, and", "import os import cv2 import numpy as np def get_emojis(): emojis_folder = 'emoji/'", "return np.uint8(cv2.addWeighted(face_part, 255.0, overlay_part, 255.0, 0.0)) def rescale_frame(frame, percent=75): width = int(frame.shape[1] *", "return image def blend_transparent(face_img, overlay_t_img): # Split out the transparency mask from the", "# Grab the BRG planes overlay_mask = overlay_t_img[:, :, 3:] # And the", "overlay # We convert the images to floating point in range 0.0 -", "transparency mask from the colour info overlay_img = overlay_t_img[:, :, :3] # Grab", "planes overlay_mask = overlay_t_img[:, :, 3:] # And the alpha plane # Again", "emoji) except: pass return image def blend_transparent(face_img, overlay_t_img): # Split out the transparency", "overlay(image, emoji, x, y, w, h): emoji = cv2.resize(emoji, (w, h)) try: image[y:y", "cv2.cvtColor(background_mask, cv2.COLOR_GRAY2BGR) # Create a masked out face image, and masked out overlay", "convert the images to floating point in range 0.0 - 1.0 face_part =", "colour info overlay_img = overlay_t_img[:, :, :3] # Grab the BRG planes overlay_mask", "a masked out face image, and masked out overlay # We convert the", "overlay_part = (overlay_img * (1 / 255.0)) * (overlay_mask * (1 / 255.0))", "# Again calculate the inverse mask background_mask = 255 - overlay_mask # Turn", "masks into three channel, so we can use them as weights overlay_mask =", "255.0, 0.0)) def rescale_frame(frame, percent=75): width = int(frame.shape[1] * percent / 100) height", "from the colour info overlay_img = overlay_t_img[:, :, :3] # Grab the BRG", "into three channel, so we can use them as weights overlay_mask = cv2.cvtColor(overlay_mask,", "'.png', -1)) return emojis[0:len(emojis) - 1] def overlay(image, emoji, x, y, w, h):", "masked out face image, and masked out overlay # We convert the images", "cv2.COLOR_GRAY2BGR) # Create a masked out face image, and masked out overlay #", "# Split out the transparency mask from the colour info overlay_img = overlay_t_img[:,", "int(frame.shape[0] * percent / 100) dim = (width, height) return cv2.resize(frame, dim, interpolation=cv2.INTER_AREA)", "as weights overlay_mask = cv2.cvtColor(overlay_mask, cv2.COLOR_GRAY2BGR) background_mask = cv2.cvtColor(background_mask, cv2.COLOR_GRAY2BGR) # Create a", "to floating point in range 0.0 - 1.0 face_part = (face_img * (1", "image def blend_transparent(face_img, overlay_t_img): # Split out the transparency mask from the colour", "back to an 8bit integer image return np.uint8(cv2.addWeighted(face_part, 255.0, overlay_part, 255.0, 0.0)) def", "* (1 / 255.0)) * (overlay_mask * (1 / 255.0)) # And finally", "255.0)) overlay_part = (overlay_img * (1 / 255.0)) * (overlay_mask * (1 /", "(background_mask * (1 / 255.0)) overlay_part = (overlay_img * (1 / 255.0)) *", "/ 255.0)) overlay_part = (overlay_img * (1 / 255.0)) * (overlay_mask * (1", "* percent / 100) height = int(frame.shape[0] * percent / 100) dim =", "/ 255.0)) * (background_mask * (1 / 255.0)) overlay_part = (overlay_img * (1", "mask background_mask = 255 - overlay_mask # Turn the masks into three channel,", "(1 / 255.0)) # And finally just add them together, and rescale it", "3:] # And the alpha plane # Again calculate the inverse mask background_mask", "as np def get_emojis(): emojis_folder = 'emoji/' emojis = [] for emoji in", "the BRG planes overlay_mask = overlay_t_img[:, :, 3:] # And the alpha plane", "image return np.uint8(cv2.addWeighted(face_part, 255.0, overlay_part, 255.0, 0.0)) def rescale_frame(frame, percent=75): width = int(frame.shape[1]", "255.0, overlay_part, 255.0, 0.0)) def rescale_frame(frame, percent=75): width = int(frame.shape[1] * percent /", "plane # Again calculate the inverse mask background_mask = 255 - overlay_mask #", "inverse mask background_mask = 255 - overlay_mask # Turn the masks into three", "Again calculate the inverse mask background_mask = 255 - overlay_mask # Turn the", "the images to floating point in range 0.0 - 1.0 face_part = (face_img", "calculate the inverse mask background_mask = 255 - overlay_mask # Turn the masks", "def get_emojis(): emojis_folder = 'emoji/' emojis = [] for emoji in range(len(os.listdir(emojis_folder))): print(emoji)", "/ 100) height = int(frame.shape[0] * percent / 100) dim = (width, height)", "face_part = (face_img * (1 / 255.0)) * (background_mask * (1 / 255.0))", "and masked out overlay # We convert the images to floating point in", "x:x + w] = blend_transparent(image[y:y + h, x:x + w], emoji) except: pass", "0.0 - 1.0 face_part = (face_img * (1 / 255.0)) * (background_mask *", "255.0)) * (overlay_mask * (1 / 255.0)) # And finally just add them", "* (1 / 255.0)) * (background_mask * (1 / 255.0)) overlay_part = (overlay_img", "try: image[y:y + h, x:x + w] = blend_transparent(image[y:y + h, x:x +", "cv2.COLOR_GRAY2BGR) background_mask = cv2.cvtColor(background_mask, cv2.COLOR_GRAY2BGR) # Create a masked out face image, and", "+ h, x:x + w] = blend_transparent(image[y:y + h, x:x + w], emoji)", ":3] # Grab the BRG planes overlay_mask = overlay_t_img[:, :, 3:] # And", "[] for emoji in range(len(os.listdir(emojis_folder))): print(emoji) emojis.append(cv2.imread(emojis_folder + str(emoji) + '.png', -1)) return", "emojis.append(cv2.imread(emojis_folder + str(emoji) + '.png', -1)) return emojis[0:len(emojis) - 1] def overlay(image, emoji,", "the colour info overlay_img = overlay_t_img[:, :, :3] # Grab the BRG planes", "- overlay_mask # Turn the masks into three channel, so we can use", "= 'emoji/' emojis = [] for emoji in range(len(os.listdir(emojis_folder))): print(emoji) emojis.append(cv2.imread(emojis_folder + str(emoji)", "for emoji in range(len(os.listdir(emojis_folder))): print(emoji) emojis.append(cv2.imread(emojis_folder + str(emoji) + '.png', -1)) return emojis[0:len(emojis)", "blend_transparent(image[y:y + h, x:x + w], emoji) except: pass return image def blend_transparent(face_img,", "h, x:x + w] = blend_transparent(image[y:y + h, x:x + w], emoji) except:", "to an 8bit integer image return np.uint8(cv2.addWeighted(face_part, 255.0, overlay_part, 255.0, 0.0)) def rescale_frame(frame,", "height = int(frame.shape[0] * percent / 100) dim = (width, height) return cv2.resize(frame,", "channel, so we can use them as weights overlay_mask = cv2.cvtColor(overlay_mask, cv2.COLOR_GRAY2BGR) background_mask", "(1 / 255.0)) * (background_mask * (1 / 255.0)) overlay_part = (overlay_img *", "+ str(emoji) + '.png', -1)) return emojis[0:len(emojis) - 1] def overlay(image, emoji, x,", "return emojis[0:len(emojis) - 1] def overlay(image, emoji, x, y, w, h): emoji =", "* (background_mask * (1 / 255.0)) overlay_part = (overlay_img * (1 / 255.0))", "masked out overlay # We convert the images to floating point in range", "(overlay_img * (1 / 255.0)) * (overlay_mask * (1 / 255.0)) # And", "them together, and rescale it back to an 8bit integer image return np.uint8(cv2.addWeighted(face_part,", "int(frame.shape[1] * percent / 100) height = int(frame.shape[0] * percent / 100) dim", "(1 / 255.0)) * (overlay_mask * (1 / 255.0)) # And finally just", "= overlay_t_img[:, :, 3:] # And the alpha plane # Again calculate the", "it back to an 8bit integer image return np.uint8(cv2.addWeighted(face_part, 255.0, overlay_part, 255.0, 0.0))", "h)) try: image[y:y + h, x:x + w] = blend_transparent(image[y:y + h, x:x", "+ h, x:x + w], emoji) except: pass return image def blend_transparent(face_img, overlay_t_img):", "- 1.0 face_part = (face_img * (1 / 255.0)) * (background_mask * (1", "just add them together, and rescale it back to an 8bit integer image", "# We convert the images to floating point in range 0.0 - 1.0", "* (1 / 255.0)) # And finally just add them together, and rescale", "image, and masked out overlay # We convert the images to floating point", "three channel, so we can use them as weights overlay_mask = cv2.cvtColor(overlay_mask, cv2.COLOR_GRAY2BGR)", "h): emoji = cv2.resize(emoji, (w, h)) try: image[y:y + h, x:x + w]", "them as weights overlay_mask = cv2.cvtColor(overlay_mask, cv2.COLOR_GRAY2BGR) background_mask = cv2.cvtColor(background_mask, cv2.COLOR_GRAY2BGR) # Create", "= [] for emoji in range(len(os.listdir(emojis_folder))): print(emoji) emojis.append(cv2.imread(emojis_folder + str(emoji) + '.png', -1))", "/ 255.0)) * (overlay_mask * (1 / 255.0)) # And finally just add", "so we can use them as weights overlay_mask = cv2.cvtColor(overlay_mask, cv2.COLOR_GRAY2BGR) background_mask =", "y, w, h): emoji = cv2.resize(emoji, (w, h)) try: image[y:y + h, x:x", "numpy as np def get_emojis(): emojis_folder = 'emoji/' emojis = [] for emoji", "* (1 / 255.0)) overlay_part = (overlay_img * (1 / 255.0)) * (overlay_mask", "range(len(os.listdir(emojis_folder))): print(emoji) emojis.append(cv2.imread(emojis_folder + str(emoji) + '.png', -1)) return emojis[0:len(emojis) - 1] def", "255.0)) # And finally just add them together, and rescale it back to", "# And finally just add them together, and rescale it back to an", "+ '.png', -1)) return emojis[0:len(emojis) - 1] def overlay(image, emoji, x, y, w,", "percent=75): width = int(frame.shape[1] * percent / 100) height = int(frame.shape[0] * percent", "overlay_mask = cv2.cvtColor(overlay_mask, cv2.COLOR_GRAY2BGR) background_mask = cv2.cvtColor(background_mask, cv2.COLOR_GRAY2BGR) # Create a masked out", "together, and rescale it back to an 8bit integer image return np.uint8(cv2.addWeighted(face_part, 255.0,", "pass return image def blend_transparent(face_img, overlay_t_img): # Split out the transparency mask from", "= 255 - overlay_mask # Turn the masks into three channel, so we", "emojis[0:len(emojis) - 1] def overlay(image, emoji, x, y, w, h): emoji = cv2.resize(emoji,", "8bit integer image return np.uint8(cv2.addWeighted(face_part, 255.0, overlay_part, 255.0, 0.0)) def rescale_frame(frame, percent=75): width", "the inverse mask background_mask = 255 - overlay_mask # Turn the masks into", "out the transparency mask from the colour info overlay_img = overlay_t_img[:, :, :3]", "emojis = [] for emoji in range(len(os.listdir(emojis_folder))): print(emoji) emojis.append(cv2.imread(emojis_folder + str(emoji) + '.png',", "emoji in range(len(os.listdir(emojis_folder))): print(emoji) emojis.append(cv2.imread(emojis_folder + str(emoji) + '.png', -1)) return emojis[0:len(emojis) -", "0.0)) def rescale_frame(frame, percent=75): width = int(frame.shape[1] * percent / 100) height =", "percent / 100) height = int(frame.shape[0] * percent / 100) dim = (width,", "except: pass return image def blend_transparent(face_img, overlay_t_img): # Split out the transparency mask", "overlay_t_img): # Split out the transparency mask from the colour info overlay_img =", "add them together, and rescale it back to an 8bit integer image return", "+ w], emoji) except: pass return image def blend_transparent(face_img, overlay_t_img): # Split out", "overlay_mask = overlay_t_img[:, :, 3:] # And the alpha plane # Again calculate", "And finally just add them together, and rescale it back to an 8bit", "use them as weights overlay_mask = cv2.cvtColor(overlay_mask, cv2.COLOR_GRAY2BGR) background_mask = cv2.cvtColor(background_mask, cv2.COLOR_GRAY2BGR) #", "np.uint8(cv2.addWeighted(face_part, 255.0, overlay_part, 255.0, 0.0)) def rescale_frame(frame, percent=75): width = int(frame.shape[1] * percent", "can use them as weights overlay_mask = cv2.cvtColor(overlay_mask, cv2.COLOR_GRAY2BGR) background_mask = cv2.cvtColor(background_mask, cv2.COLOR_GRAY2BGR)", "rescale it back to an 8bit integer image return np.uint8(cv2.addWeighted(face_part, 255.0, overlay_part, 255.0,", "str(emoji) + '.png', -1)) return emojis[0:len(emojis) - 1] def overlay(image, emoji, x, y,", "BRG planes overlay_mask = overlay_t_img[:, :, 3:] # And the alpha plane #", "blend_transparent(face_img, overlay_t_img): # Split out the transparency mask from the colour info overlay_img", "width = int(frame.shape[1] * percent / 100) height = int(frame.shape[0] * percent /", "1] def overlay(image, emoji, x, y, w, h): emoji = cv2.resize(emoji, (w, h))", "images to floating point in range 0.0 - 1.0 face_part = (face_img *", "integer image return np.uint8(cv2.addWeighted(face_part, 255.0, overlay_part, 255.0, 0.0)) def rescale_frame(frame, percent=75): width =", "range 0.0 - 1.0 face_part = (face_img * (1 / 255.0)) * (background_mask", "emojis_folder = 'emoji/' emojis = [] for emoji in range(len(os.listdir(emojis_folder))): print(emoji) emojis.append(cv2.imread(emojis_folder +", "overlay_mask # Turn the masks into three channel, so we can use them", "rescale_frame(frame, percent=75): width = int(frame.shape[1] * percent / 100) height = int(frame.shape[0] *", "in range 0.0 - 1.0 face_part = (face_img * (1 / 255.0)) *", "the transparency mask from the colour info overlay_img = overlay_t_img[:, :, :3] #", "point in range 0.0 - 1.0 face_part = (face_img * (1 / 255.0))", "image[y:y + h, x:x + w] = blend_transparent(image[y:y + h, x:x + w],", "And the alpha plane # Again calculate the inverse mask background_mask = 255", "def overlay(image, emoji, x, y, w, h): emoji = cv2.resize(emoji, (w, h)) try:", "and rescale it back to an 8bit integer image return np.uint8(cv2.addWeighted(face_part, 255.0, overlay_part,", "face image, and masked out overlay # We convert the images to floating", "Turn the masks into three channel, so we can use them as weights", "emoji, x, y, w, h): emoji = cv2.resize(emoji, (w, h)) try: image[y:y +", "cv2.resize(emoji, (w, h)) try: image[y:y + h, x:x + w] = blend_transparent(image[y:y +", "the alpha plane # Again calculate the inverse mask background_mask = 255 -", "the masks into three channel, so we can use them as weights overlay_mask", "we can use them as weights overlay_mask = cv2.cvtColor(overlay_mask, cv2.COLOR_GRAY2BGR) background_mask = cv2.cvtColor(background_mask,", "= (overlay_img * (1 / 255.0)) * (overlay_mask * (1 / 255.0)) #", "out overlay # We convert the images to floating point in range 0.0", "= int(frame.shape[0] * percent / 100) dim = (width, height) return cv2.resize(frame, dim,", "(face_img * (1 / 255.0)) * (background_mask * (1 / 255.0)) overlay_part =", "# Turn the masks into three channel, so we can use them as", "floating point in range 0.0 - 1.0 face_part = (face_img * (1 /", "- 1] def overlay(image, emoji, x, y, w, h): emoji = cv2.resize(emoji, (w,", "(w, h)) try: image[y:y + h, x:x + w] = blend_transparent(image[y:y + h,", "255 - overlay_mask # Turn the masks into three channel, so we can", "an 8bit integer image return np.uint8(cv2.addWeighted(face_part, 255.0, overlay_part, 255.0, 0.0)) def rescale_frame(frame, percent=75):", "cv2.cvtColor(overlay_mask, cv2.COLOR_GRAY2BGR) background_mask = cv2.cvtColor(background_mask, cv2.COLOR_GRAY2BGR) # Create a masked out face image,", "= cv2.cvtColor(background_mask, cv2.COLOR_GRAY2BGR) # Create a masked out face image, and masked out", "w], emoji) except: pass return image def blend_transparent(face_img, overlay_t_img): # Split out the", "= (face_img * (1 / 255.0)) * (background_mask * (1 / 255.0)) overlay_part", "# And the alpha plane # Again calculate the inverse mask background_mask =", "100) height = int(frame.shape[0] * percent / 100) dim = (width, height) return", "get_emojis(): emojis_folder = 'emoji/' emojis = [] for emoji in range(len(os.listdir(emojis_folder))): print(emoji) emojis.append(cv2.imread(emojis_folder", "os import cv2 import numpy as np def get_emojis(): emojis_folder = 'emoji/' emojis", "overlay_t_img[:, :, :3] # Grab the BRG planes overlay_mask = overlay_t_img[:, :, 3:]", ":, 3:] # And the alpha plane # Again calculate the inverse mask", "def blend_transparent(face_img, overlay_t_img): # Split out the transparency mask from the colour info", "= int(frame.shape[1] * percent / 100) height = int(frame.shape[0] * percent / 100)", "info overlay_img = overlay_t_img[:, :, :3] # Grab the BRG planes overlay_mask =", "Create a masked out face image, and masked out overlay # We convert" ]
[ "<filename>config.py from pathlib import Path ROOT_DIR = Path(__file__).parent.resolve() IMAGE_DIR = ROOT_DIR / 'images'" ]
[ "mDict['uid'] if uid not in visDatas: visDatas[uid] = {'mem_use':[], 'cpu_use':[]} visDatas[uid]['mem_use'].append(mDict['mem_use']) visDatas[uid]['cpu_use'].append(mDict['cpu_use']) print(mDict)", "axCpu = plt.subplot(2,1,2) # colors of lines cols = ['C'+str(i%10) for i in", "for i in range(options.numNodes)] # styles of lines lins = ['-']*10 + ['--']*10", "if need more maxX = 20 while True: axRam.cla() axCpu.cla() for i, uid", "# colors of lines cols = ['C'+str(i%10) for i in range(options.numNodes)] # styles", "s.bind((options.ip, options.port)) s.listen(options.numNodes) # keep main in here to accept connections while True:", "start_new_thread #from sense_hat import SenseHat from optparse import OptionParser import matplotlib.pyplot as plt", "update if need more maxX = 20 while True: axRam.cla() axCpu.cla() for i,", "dest='port', default=5005) parser.add_option('-n', '--numNodes', type='int', dest='numNodes', default=15) parser.add_option('-u', '--update', type='float', dest='update', default=0.2) (options,", "'--port', type='int', dest='port', default=5005) parser.add_option('-n', '--numNodes', type='int', dest='numNodes', default=15) parser.add_option('-u', '--update', type='float', dest='update',", "= plt.subplot(2,1,2) # colors of lines cols = ['C'+str(i%10) for i in range(options.numNodes)]", "start_new_thread(dataStream, (con,)) visDatas = {} # store all data to visualize # continually", "['-.']*10 # manually update if need more maxX = 20 while True: axRam.cla()", "visDatas: visDatas[uid] = {'mem_use':[], 'cpu_use':[]} visDatas[uid]['mem_use'].append(mDict['mem_use']) visDatas[uid]['cpu_use'].append(mDict['cpu_use']) print(mDict) start_new_thread(clientReceiver, ()) plt.ion() # for", "linestyle=lins[i], label=uid) if len(visDatas[uid]['mem_use']) > maxX: visDatas[uid]['mem_use'] = visDatas[uid]['mem_use'][len(visDatas[uid]['mem_use'])-20:] if len(visDatas[uid]['cpu_use']) > maxX:", "options.port)) s.listen(options.numNodes) # keep main in here to accept connections while True: con,", "dest='numNodes', default=15) parser.add_option('-u', '--update', type='float', dest='update', default=0.2) (options, args) = parser.parse_args() #sense =", "data = con.recv(1024).decode('utf-8') if data == '': break mDict = json.loads(data) uid =", "= socket.socket() s.bind((options.ip, options.port)) s.listen(options.numNodes) # keep main in here to accept connections", "con.recv(1024).decode('utf-8') if data == '': break mDict = json.loads(data) uid = mDict['uid'] if", "> maxX: visDatas[uid]['mem_use'] = visDatas[uid]['mem_use'][len(visDatas[uid]['mem_use'])-20:] if len(visDatas[uid]['cpu_use']) > maxX: visDatas[uid]['cpu_use'] = visDatas[uid]['cpu_use'][len(visDatas[uid]['cpu_use'])-20:] axRam.set_title('RAM", "styles of lines lins = ['-']*10 + ['--']*10 + ['-.']*10 # manually update", "break mDict = json.loads(data) uid = mDict['uid'] if uid not in visDatas: visDatas[uid]", "parser.add_option('-n', '--numNodes', type='int', dest='numNodes', default=15) parser.add_option('-u', '--update', type='float', dest='update', default=0.2) (options, args) =", "accept connections while True: con, _ = s.accept() start_new_thread(dataStream, (con,)) visDatas = {}", "from optparse import OptionParser import matplotlib.pyplot as plt import time parser = OptionParser()", "uid not in visDatas: visDatas[uid] = {'mem_use':[], 'cpu_use':[]} visDatas[uid]['mem_use'].append(mDict['mem_use']) visDatas[uid]['cpu_use'].append(mDict['cpu_use']) print(mDict) start_new_thread(clientReceiver, ())", "= visDatas[uid]['mem_use'][len(visDatas[uid]['mem_use'])-20:] if len(visDatas[uid]['cpu_use']) > maxX: visDatas[uid]['cpu_use'] = visDatas[uid]['cpu_use'][len(visDatas[uid]['cpu_use'])-20:] axRam.set_title('RAM Usage of Nodes')", "# temp = sense.get_temperature() def clientReceiver(): # create server s = socket.socket() s.bind((options.ip,", "{} # store all data to visualize # continually stream in data in", "all data to visualize # continually stream in data in separate threads def", "= plt.figure() axRam = plt.subplot(2,1,1) axCpu = plt.subplot(2,1,2) # colors of lines cols", "l-maxX):l], color=cols[i], linestyle=lins[i], label=uid) axCpu.plot(visDatas[uid]['cpu_use'][max(0, l-maxX):l], color=cols[i], linestyle=lins[i], label=uid) if len(visDatas[uid]['mem_use']) > maxX:", "len(visDatas[uid]['cpu_use']) > maxX: visDatas[uid]['cpu_use'] = visDatas[uid]['cpu_use'][len(visDatas[uid]['cpu_use'])-20:] axRam.set_title('RAM Usage of Nodes') axRam.set_ylabel('RAM (GB)') axRam.get_xaxis().set_visible(False)", "enumerate(list(visDatas.keys())): l = len(visDatas[uid]['mem_use']) axRam.plot(visDatas[uid]['mem_use'][max(0, l-maxX):l], color=cols[i], linestyle=lins[i], label=uid) axCpu.plot(visDatas[uid]['cpu_use'][max(0, l-maxX):l], color=cols[i], linestyle=lins[i],", "dest='update', default=0.2) (options, args) = parser.parse_args() #sense = SenseHat() #sense.clear() # temp =", "for i, uid in enumerate(list(visDatas.keys())): l = len(visDatas[uid]['mem_use']) axRam.plot(visDatas[uid]['mem_use'][max(0, l-maxX):l], color=cols[i], linestyle=lins[i], label=uid)", "axRam.legend(loc='upper left') axRam.set_ylim(0,1.05) axCpu.set_title('CPU Usage of Nodes (4 Cores)') axCpu.set_ylabel('CPU %') axCpu.get_xaxis().set_visible(False) axCpu.legend(loc='upper", "temp = sense.get_temperature() def clientReceiver(): # create server s = socket.socket() s.bind((options.ip, options.port))", "manually update if need more maxX = 20 while True: axRam.cla() axCpu.cla() for", "# manually update if need more maxX = 20 while True: axRam.cla() axCpu.cla()", "server s = socket.socket() s.bind((options.ip, options.port)) s.listen(options.numNodes) # keep main in here to", "import SenseHat from optparse import OptionParser import matplotlib.pyplot as plt import time parser", "json from _thread import start_new_thread #from sense_hat import SenseHat from optparse import OptionParser", "while True: data = con.recv(1024).decode('utf-8') if data == '': break mDict = json.loads(data)", "time parser = OptionParser() parser.add_option('-i', '--ip', type='string', dest='ip', default='127.0.0.1') parser.add_option('-p', '--port', type='int', dest='port',", "stream in data in separate threads def dataStream(con): while True: data = con.recv(1024).decode('utf-8')", "= parser.parse_args() #sense = SenseHat() #sense.clear() # temp = sense.get_temperature() def clientReceiver(): #", "plt.figure() axRam = plt.subplot(2,1,1) axCpu = plt.subplot(2,1,2) # colors of lines cols =", "more maxX = 20 while True: axRam.cla() axCpu.cla() for i, uid in enumerate(list(visDatas.keys())):", "socket.socket() s.bind((options.ip, options.port)) s.listen(options.numNodes) # keep main in here to accept connections while", "color=cols[i], linestyle=lins[i], label=uid) if len(visDatas[uid]['mem_use']) > maxX: visDatas[uid]['mem_use'] = visDatas[uid]['mem_use'][len(visDatas[uid]['mem_use'])-20:] if len(visDatas[uid]['cpu_use']) >", "= mDict['uid'] if uid not in visDatas: visDatas[uid] = {'mem_use':[], 'cpu_use':[]} visDatas[uid]['mem_use'].append(mDict['mem_use']) visDatas[uid]['cpu_use'].append(mDict['cpu_use'])", "# create server s = socket.socket() s.bind((options.ip, options.port)) s.listen(options.numNodes) # keep main in", "if data == '': break mDict = json.loads(data) uid = mDict['uid'] if uid", "i, uid in enumerate(list(visDatas.keys())): l = len(visDatas[uid]['mem_use']) axRam.plot(visDatas[uid]['mem_use'][max(0, l-maxX):l], color=cols[i], linestyle=lins[i], label=uid) axCpu.plot(visDatas[uid]['cpu_use'][max(0,", "maxX = 20 while True: axRam.cla() axCpu.cla() for i, uid in enumerate(list(visDatas.keys())): l", "_ = s.accept() start_new_thread(dataStream, (con,)) visDatas = {} # store all data to", "plot # plotting stuff fig = plt.figure() axRam = plt.subplot(2,1,1) axCpu = plt.subplot(2,1,2)", "visDatas[uid]['cpu_use'].append(mDict['cpu_use']) print(mDict) start_new_thread(clientReceiver, ()) plt.ion() # for live update plot # plotting stuff", "True: axRam.cla() axCpu.cla() for i, uid in enumerate(list(visDatas.keys())): l = len(visDatas[uid]['mem_use']) axRam.plot(visDatas[uid]['mem_use'][max(0, l-maxX):l],", "cols = ['C'+str(i%10) for i in range(options.numNodes)] # styles of lines lins =", "sense.get_temperature() def clientReceiver(): # create server s = socket.socket() s.bind((options.ip, options.port)) s.listen(options.numNodes) #", "l = len(visDatas[uid]['mem_use']) axRam.plot(visDatas[uid]['mem_use'][max(0, l-maxX):l], color=cols[i], linestyle=lins[i], label=uid) axCpu.plot(visDatas[uid]['cpu_use'][max(0, l-maxX):l], color=cols[i], linestyle=lins[i], label=uid)", "'cpu_use':[]} visDatas[uid]['mem_use'].append(mDict['mem_use']) visDatas[uid]['cpu_use'].append(mDict['cpu_use']) print(mDict) start_new_thread(clientReceiver, ()) plt.ion() # for live update plot #", "Nodes') axRam.set_ylabel('RAM (GB)') axRam.get_xaxis().set_visible(False) axRam.legend(loc='upper left') axRam.set_ylim(0,1.05) axCpu.set_title('CPU Usage of Nodes (4 Cores)')", "parser.parse_args() #sense = SenseHat() #sense.clear() # temp = sense.get_temperature() def clientReceiver(): # create", "lines lins = ['-']*10 + ['--']*10 + ['-.']*10 # manually update if need", "data in separate threads def dataStream(con): while True: data = con.recv(1024).decode('utf-8') if data", "= SenseHat() #sense.clear() # temp = sense.get_temperature() def clientReceiver(): # create server s", "parser.add_option('-p', '--port', type='int', dest='port', default=5005) parser.add_option('-n', '--numNodes', type='int', dest='numNodes', default=15) parser.add_option('-u', '--update', type='float',", "= OptionParser() parser.add_option('-i', '--ip', type='string', dest='ip', default='127.0.0.1') parser.add_option('-p', '--port', type='int', dest='port', default=5005) parser.add_option('-n',", "default=0.2) (options, args) = parser.parse_args() #sense = SenseHat() #sense.clear() # temp = sense.get_temperature()", "'': break mDict = json.loads(data) uid = mDict['uid'] if uid not in visDatas:", "separate threads def dataStream(con): while True: data = con.recv(1024).decode('utf-8') if data == '':", "not in visDatas: visDatas[uid] = {'mem_use':[], 'cpu_use':[]} visDatas[uid]['mem_use'].append(mDict['mem_use']) visDatas[uid]['cpu_use'].append(mDict['cpu_use']) print(mDict) start_new_thread(clientReceiver, ()) plt.ion()", "of lines cols = ['C'+str(i%10) for i in range(options.numNodes)] # styles of lines", "axRam.set_title('RAM Usage of Nodes') axRam.set_ylabel('RAM (GB)') axRam.get_xaxis().set_visible(False) axRam.legend(loc='upper left') axRam.set_ylim(0,1.05) axCpu.set_title('CPU Usage of", "parser.add_option('-i', '--ip', type='string', dest='ip', default='127.0.0.1') parser.add_option('-p', '--port', type='int', dest='port', default=5005) parser.add_option('-n', '--numNodes', type='int',", "visualize # continually stream in data in separate threads def dataStream(con): while True:", "= sense.get_temperature() def clientReceiver(): # create server s = socket.socket() s.bind((options.ip, options.port)) s.listen(options.numNodes)", "== '': break mDict = json.loads(data) uid = mDict['uid'] if uid not in", "label=uid) axCpu.plot(visDatas[uid]['cpu_use'][max(0, l-maxX):l], color=cols[i], linestyle=lins[i], label=uid) if len(visDatas[uid]['mem_use']) > maxX: visDatas[uid]['mem_use'] = visDatas[uid]['mem_use'][len(visDatas[uid]['mem_use'])-20:]", "here to accept connections while True: con, _ = s.accept() start_new_thread(dataStream, (con,)) visDatas", "print(mDict) start_new_thread(clientReceiver, ()) plt.ion() # for live update plot # plotting stuff fig", "color=cols[i], linestyle=lins[i], label=uid) axCpu.plot(visDatas[uid]['cpu_use'][max(0, l-maxX):l], color=cols[i], linestyle=lins[i], label=uid) if len(visDatas[uid]['mem_use']) > maxX: visDatas[uid]['mem_use']", "if len(visDatas[uid]['cpu_use']) > maxX: visDatas[uid]['cpu_use'] = visDatas[uid]['cpu_use'][len(visDatas[uid]['cpu_use'])-20:] axRam.set_title('RAM Usage of Nodes') axRam.set_ylabel('RAM (GB)')", "type='int', dest='port', default=5005) parser.add_option('-n', '--numNodes', type='int', dest='numNodes', default=15) parser.add_option('-u', '--update', type='float', dest='update', default=0.2)", "colors of lines cols = ['C'+str(i%10) for i in range(options.numNodes)] # styles of", "> maxX: visDatas[uid]['cpu_use'] = visDatas[uid]['cpu_use'][len(visDatas[uid]['cpu_use'])-20:] axRam.set_title('RAM Usage of Nodes') axRam.set_ylabel('RAM (GB)') axRam.get_xaxis().set_visible(False) axRam.legend(loc='upper", "visDatas = {} # store all data to visualize # continually stream in", "if uid not in visDatas: visDatas[uid] = {'mem_use':[], 'cpu_use':[]} visDatas[uid]['mem_use'].append(mDict['mem_use']) visDatas[uid]['cpu_use'].append(mDict['cpu_use']) print(mDict) start_new_thread(clientReceiver,", "in visDatas: visDatas[uid] = {'mem_use':[], 'cpu_use':[]} visDatas[uid]['mem_use'].append(mDict['mem_use']) visDatas[uid]['cpu_use'].append(mDict['cpu_use']) print(mDict) start_new_thread(clientReceiver, ()) plt.ion() #", "uid = mDict['uid'] if uid not in visDatas: visDatas[uid] = {'mem_use':[], 'cpu_use':[]} visDatas[uid]['mem_use'].append(mDict['mem_use'])", "parser.add_option('-u', '--update', type='float', dest='update', default=0.2) (options, args) = parser.parse_args() #sense = SenseHat() #sense.clear()", "import time parser = OptionParser() parser.add_option('-i', '--ip', type='string', dest='ip', default='127.0.0.1') parser.add_option('-p', '--port', type='int',", "start_new_thread(clientReceiver, ()) plt.ion() # for live update plot # plotting stuff fig =", "+ ['-.']*10 # manually update if need more maxX = 20 while True:", "need more maxX = 20 while True: axRam.cla() axCpu.cla() for i, uid in", "data to visualize # continually stream in data in separate threads def dataStream(con):", "lines cols = ['C'+str(i%10) for i in range(options.numNodes)] # styles of lines lins", "= json.loads(data) uid = mDict['uid'] if uid not in visDatas: visDatas[uid] = {'mem_use':[],", "type='int', dest='numNodes', default=15) parser.add_option('-u', '--update', type='float', dest='update', default=0.2) (options, args) = parser.parse_args() #sense", "= s.accept() start_new_thread(dataStream, (con,)) visDatas = {} # store all data to visualize", "if len(visDatas[uid]['mem_use']) > maxX: visDatas[uid]['mem_use'] = visDatas[uid]['mem_use'][len(visDatas[uid]['mem_use'])-20:] if len(visDatas[uid]['cpu_use']) > maxX: visDatas[uid]['cpu_use'] =", "#sense.clear() # temp = sense.get_temperature() def clientReceiver(): # create server s = socket.socket()", "from _thread import start_new_thread #from sense_hat import SenseHat from optparse import OptionParser import", "connections while True: con, _ = s.accept() start_new_thread(dataStream, (con,)) visDatas = {} #", "socket import json from _thread import start_new_thread #from sense_hat import SenseHat from optparse", "SenseHat from optparse import OptionParser import matplotlib.pyplot as plt import time parser =", "clientReceiver(): # create server s = socket.socket() s.bind((options.ip, options.port)) s.listen(options.numNodes) # keep main", "default=15) parser.add_option('-u', '--update', type='float', dest='update', default=0.2) (options, args) = parser.parse_args() #sense = SenseHat()", "= ['-']*10 + ['--']*10 + ['-.']*10 # manually update if need more maxX", "= {} # store all data to visualize # continually stream in data", "(con,)) visDatas = {} # store all data to visualize # continually stream", "OptionParser import matplotlib.pyplot as plt import time parser = OptionParser() parser.add_option('-i', '--ip', type='string',", "args) = parser.parse_args() #sense = SenseHat() #sense.clear() # temp = sense.get_temperature() def clientReceiver():", "to visualize # continually stream in data in separate threads def dataStream(con): while", "update plot # plotting stuff fig = plt.figure() axRam = plt.subplot(2,1,1) axCpu =", "visDatas[uid]['cpu_use'][len(visDatas[uid]['cpu_use'])-20:] axRam.set_title('RAM Usage of Nodes') axRam.set_ylabel('RAM (GB)') axRam.get_xaxis().set_visible(False) axRam.legend(loc='upper left') axRam.set_ylim(0,1.05) axCpu.set_title('CPU Usage", "in separate threads def dataStream(con): while True: data = con.recv(1024).decode('utf-8') if data ==", "axRam.cla() axCpu.cla() for i, uid in enumerate(list(visDatas.keys())): l = len(visDatas[uid]['mem_use']) axRam.plot(visDatas[uid]['mem_use'][max(0, l-maxX):l], color=cols[i],", "'--ip', type='string', dest='ip', default='127.0.0.1') parser.add_option('-p', '--port', type='int', dest='port', default=5005) parser.add_option('-n', '--numNodes', type='int', dest='numNodes',", "SenseHat() #sense.clear() # temp = sense.get_temperature() def clientReceiver(): # create server s =", "['C'+str(i%10) for i in range(options.numNodes)] # styles of lines lins = ['-']*10 +", "= plt.subplot(2,1,1) axCpu = plt.subplot(2,1,2) # colors of lines cols = ['C'+str(i%10) for", "for live update plot # plotting stuff fig = plt.figure() axRam = plt.subplot(2,1,1)", "Usage of Nodes') axRam.set_ylabel('RAM (GB)') axRam.get_xaxis().set_visible(False) axRam.legend(loc='upper left') axRam.set_ylim(0,1.05) axCpu.set_title('CPU Usage of Nodes", "continually stream in data in separate threads def dataStream(con): while True: data =", "axRam = plt.subplot(2,1,1) axCpu = plt.subplot(2,1,2) # colors of lines cols = ['C'+str(i%10)", "label=uid) if len(visDatas[uid]['mem_use']) > maxX: visDatas[uid]['mem_use'] = visDatas[uid]['mem_use'][len(visDatas[uid]['mem_use'])-20:] if len(visDatas[uid]['cpu_use']) > maxX: visDatas[uid]['cpu_use']", "maxX: visDatas[uid]['cpu_use'] = visDatas[uid]['cpu_use'][len(visDatas[uid]['cpu_use'])-20:] axRam.set_title('RAM Usage of Nodes') axRam.set_ylabel('RAM (GB)') axRam.get_xaxis().set_visible(False) axRam.legend(loc='upper left')", "axRam.get_xaxis().set_visible(False) axRam.legend(loc='upper left') axRam.set_ylim(0,1.05) axCpu.set_title('CPU Usage of Nodes (4 Cores)') axCpu.set_ylabel('CPU %') axCpu.get_xaxis().set_visible(False)", "dataStream(con): while True: data = con.recv(1024).decode('utf-8') if data == '': break mDict =", "<gh_stars>0 import socket import json from _thread import start_new_thread #from sense_hat import SenseHat", "# keep main in here to accept connections while True: con, _ =", "con, _ = s.accept() start_new_thread(dataStream, (con,)) visDatas = {} # store all data", "default=5005) parser.add_option('-n', '--numNodes', type='int', dest='numNodes', default=15) parser.add_option('-u', '--update', type='float', dest='update', default=0.2) (options, args)", "mDict = json.loads(data) uid = mDict['uid'] if uid not in visDatas: visDatas[uid] =", "plotting stuff fig = plt.figure() axRam = plt.subplot(2,1,1) axCpu = plt.subplot(2,1,2) # colors", "+ ['--']*10 + ['-.']*10 # manually update if need more maxX = 20", "dest='ip', default='127.0.0.1') parser.add_option('-p', '--port', type='int', dest='port', default=5005) parser.add_option('-n', '--numNodes', type='int', dest='numNodes', default=15) parser.add_option('-u',", "stuff fig = plt.figure() axRam = plt.subplot(2,1,1) axCpu = plt.subplot(2,1,2) # colors of", "# continually stream in data in separate threads def dataStream(con): while True: data", "OptionParser() parser.add_option('-i', '--ip', type='string', dest='ip', default='127.0.0.1') parser.add_option('-p', '--port', type='int', dest='port', default=5005) parser.add_option('-n', '--numNodes',", "{'mem_use':[], 'cpu_use':[]} visDatas[uid]['mem_use'].append(mDict['mem_use']) visDatas[uid]['cpu_use'].append(mDict['cpu_use']) print(mDict) start_new_thread(clientReceiver, ()) plt.ion() # for live update plot", "maxX: visDatas[uid]['mem_use'] = visDatas[uid]['mem_use'][len(visDatas[uid]['mem_use'])-20:] if len(visDatas[uid]['cpu_use']) > maxX: visDatas[uid]['cpu_use'] = visDatas[uid]['cpu_use'][len(visDatas[uid]['cpu_use'])-20:] axRam.set_title('RAM Usage", "def clientReceiver(): # create server s = socket.socket() s.bind((options.ip, options.port)) s.listen(options.numNodes) # keep", "# plotting stuff fig = plt.figure() axRam = plt.subplot(2,1,1) axCpu = plt.subplot(2,1,2) #", "axCpu.plot(visDatas[uid]['cpu_use'][max(0, l-maxX):l], color=cols[i], linestyle=lins[i], label=uid) if len(visDatas[uid]['mem_use']) > maxX: visDatas[uid]['mem_use'] = visDatas[uid]['mem_use'][len(visDatas[uid]['mem_use'])-20:] if", "'--numNodes', type='int', dest='numNodes', default=15) parser.add_option('-u', '--update', type='float', dest='update', default=0.2) (options, args) = parser.parse_args()", "data == '': break mDict = json.loads(data) uid = mDict['uid'] if uid not", "s.listen(options.numNodes) # keep main in here to accept connections while True: con, _", "sense_hat import SenseHat from optparse import OptionParser import matplotlib.pyplot as plt import time", "#sense = SenseHat() #sense.clear() # temp = sense.get_temperature() def clientReceiver(): # create server", "in here to accept connections while True: con, _ = s.accept() start_new_thread(dataStream, (con,))", "= con.recv(1024).decode('utf-8') if data == '': break mDict = json.loads(data) uid = mDict['uid']", "()) plt.ion() # for live update plot # plotting stuff fig = plt.figure()", "= ['C'+str(i%10) for i in range(options.numNodes)] # styles of lines lins = ['-']*10", "axRam.plot(visDatas[uid]['mem_use'][max(0, l-maxX):l], color=cols[i], linestyle=lins[i], label=uid) axCpu.plot(visDatas[uid]['cpu_use'][max(0, l-maxX):l], color=cols[i], linestyle=lins[i], label=uid) if len(visDatas[uid]['mem_use']) >", "Usage of Nodes (4 Cores)') axCpu.set_ylabel('CPU %') axCpu.get_xaxis().set_visible(False) axCpu.legend(loc='upper left') axCpu.set_ylim(0,105) plt.draw() fig.canvas.start_event_loop(options.update)", "default='127.0.0.1') parser.add_option('-p', '--port', type='int', dest='port', default=5005) parser.add_option('-n', '--numNodes', type='int', dest='numNodes', default=15) parser.add_option('-u', '--update',", "parser = OptionParser() parser.add_option('-i', '--ip', type='string', dest='ip', default='127.0.0.1') parser.add_option('-p', '--port', type='int', dest='port', default=5005)", "s.accept() start_new_thread(dataStream, (con,)) visDatas = {} # store all data to visualize #", "plt import time parser = OptionParser() parser.add_option('-i', '--ip', type='string', dest='ip', default='127.0.0.1') parser.add_option('-p', '--port',", "store all data to visualize # continually stream in data in separate threads", "in enumerate(list(visDatas.keys())): l = len(visDatas[uid]['mem_use']) axRam.plot(visDatas[uid]['mem_use'][max(0, l-maxX):l], color=cols[i], linestyle=lins[i], label=uid) axCpu.plot(visDatas[uid]['cpu_use'][max(0, l-maxX):l], color=cols[i],", "= visDatas[uid]['cpu_use'][len(visDatas[uid]['cpu_use'])-20:] axRam.set_title('RAM Usage of Nodes') axRam.set_ylabel('RAM (GB)') axRam.get_xaxis().set_visible(False) axRam.legend(loc='upper left') axRam.set_ylim(0,1.05) axCpu.set_title('CPU", "threads def dataStream(con): while True: data = con.recv(1024).decode('utf-8') if data == '': break", "import json from _thread import start_new_thread #from sense_hat import SenseHat from optparse import", "plt.subplot(2,1,2) # colors of lines cols = ['C'+str(i%10) for i in range(options.numNodes)] #", "True: data = con.recv(1024).decode('utf-8') if data == '': break mDict = json.loads(data) uid", "def dataStream(con): while True: data = con.recv(1024).decode('utf-8') if data == '': break mDict", "optparse import OptionParser import matplotlib.pyplot as plt import time parser = OptionParser() parser.add_option('-i',", "to accept connections while True: con, _ = s.accept() start_new_thread(dataStream, (con,)) visDatas =", "= 20 while True: axRam.cla() axCpu.cla() for i, uid in enumerate(list(visDatas.keys())): l =", "visDatas[uid]['mem_use'] = visDatas[uid]['mem_use'][len(visDatas[uid]['mem_use'])-20:] if len(visDatas[uid]['cpu_use']) > maxX: visDatas[uid]['cpu_use'] = visDatas[uid]['cpu_use'][len(visDatas[uid]['cpu_use'])-20:] axRam.set_title('RAM Usage of", "axCpu.set_title('CPU Usage of Nodes (4 Cores)') axCpu.set_ylabel('CPU %') axCpu.get_xaxis().set_visible(False) axCpu.legend(loc='upper left') axCpu.set_ylim(0,105) plt.draw()", "axCpu.cla() for i, uid in enumerate(list(visDatas.keys())): l = len(visDatas[uid]['mem_use']) axRam.plot(visDatas[uid]['mem_use'][max(0, l-maxX):l], color=cols[i], linestyle=lins[i],", "s = socket.socket() s.bind((options.ip, options.port)) s.listen(options.numNodes) # keep main in here to accept", "in data in separate threads def dataStream(con): while True: data = con.recv(1024).decode('utf-8') if", "(options, args) = parser.parse_args() #sense = SenseHat() #sense.clear() # temp = sense.get_temperature() def", "# store all data to visualize # continually stream in data in separate", "import OptionParser import matplotlib.pyplot as plt import time parser = OptionParser() parser.add_option('-i', '--ip',", "json.loads(data) uid = mDict['uid'] if uid not in visDatas: visDatas[uid] = {'mem_use':[], 'cpu_use':[]}", "linestyle=lins[i], label=uid) axCpu.plot(visDatas[uid]['cpu_use'][max(0, l-maxX):l], color=cols[i], linestyle=lins[i], label=uid) if len(visDatas[uid]['mem_use']) > maxX: visDatas[uid]['mem_use'] =", "_thread import start_new_thread #from sense_hat import SenseHat from optparse import OptionParser import matplotlib.pyplot", "l-maxX):l], color=cols[i], linestyle=lins[i], label=uid) if len(visDatas[uid]['mem_use']) > maxX: visDatas[uid]['mem_use'] = visDatas[uid]['mem_use'][len(visDatas[uid]['mem_use'])-20:] if len(visDatas[uid]['cpu_use'])", "matplotlib.pyplot as plt import time parser = OptionParser() parser.add_option('-i', '--ip', type='string', dest='ip', default='127.0.0.1')", "# for live update plot # plotting stuff fig = plt.figure() axRam =", "['--']*10 + ['-.']*10 # manually update if need more maxX = 20 while", "left') axRam.set_ylim(0,1.05) axCpu.set_title('CPU Usage of Nodes (4 Cores)') axCpu.set_ylabel('CPU %') axCpu.get_xaxis().set_visible(False) axCpu.legend(loc='upper left')", "len(visDatas[uid]['mem_use']) > maxX: visDatas[uid]['mem_use'] = visDatas[uid]['mem_use'][len(visDatas[uid]['mem_use'])-20:] if len(visDatas[uid]['cpu_use']) > maxX: visDatas[uid]['cpu_use'] = visDatas[uid]['cpu_use'][len(visDatas[uid]['cpu_use'])-20:]", "(GB)') axRam.get_xaxis().set_visible(False) axRam.legend(loc='upper left') axRam.set_ylim(0,1.05) axCpu.set_title('CPU Usage of Nodes (4 Cores)') axCpu.set_ylabel('CPU %')", "['-']*10 + ['--']*10 + ['-.']*10 # manually update if need more maxX =", "visDatas[uid]['mem_use'].append(mDict['mem_use']) visDatas[uid]['cpu_use'].append(mDict['cpu_use']) print(mDict) start_new_thread(clientReceiver, ()) plt.ion() # for live update plot # plotting", "20 while True: axRam.cla() axCpu.cla() for i, uid in enumerate(list(visDatas.keys())): l = len(visDatas[uid]['mem_use'])", "of Nodes') axRam.set_ylabel('RAM (GB)') axRam.get_xaxis().set_visible(False) axRam.legend(loc='upper left') axRam.set_ylim(0,1.05) axCpu.set_title('CPU Usage of Nodes (4", "type='string', dest='ip', default='127.0.0.1') parser.add_option('-p', '--port', type='int', dest='port', default=5005) parser.add_option('-n', '--numNodes', type='int', dest='numNodes', default=15)", "uid in enumerate(list(visDatas.keys())): l = len(visDatas[uid]['mem_use']) axRam.plot(visDatas[uid]['mem_use'][max(0, l-maxX):l], color=cols[i], linestyle=lins[i], label=uid) axCpu.plot(visDatas[uid]['cpu_use'][max(0, l-maxX):l],", "create server s = socket.socket() s.bind((options.ip, options.port)) s.listen(options.numNodes) # keep main in here", "while True: axRam.cla() axCpu.cla() for i, uid in enumerate(list(visDatas.keys())): l = len(visDatas[uid]['mem_use']) axRam.plot(visDatas[uid]['mem_use'][max(0,", "plt.ion() # for live update plot # plotting stuff fig = plt.figure() axRam", "main in here to accept connections while True: con, _ = s.accept() start_new_thread(dataStream,", "import matplotlib.pyplot as plt import time parser = OptionParser() parser.add_option('-i', '--ip', type='string', dest='ip',", "import socket import json from _thread import start_new_thread #from sense_hat import SenseHat from", "i in range(options.numNodes)] # styles of lines lins = ['-']*10 + ['--']*10 +", "# styles of lines lins = ['-']*10 + ['--']*10 + ['-.']*10 # manually", "True: con, _ = s.accept() start_new_thread(dataStream, (con,)) visDatas = {} # store all", "lins = ['-']*10 + ['--']*10 + ['-.']*10 # manually update if need more", "axRam.set_ylim(0,1.05) axCpu.set_title('CPU Usage of Nodes (4 Cores)') axCpu.set_ylabel('CPU %') axCpu.get_xaxis().set_visible(False) axCpu.legend(loc='upper left') axCpu.set_ylim(0,105)", "visDatas[uid]['mem_use'][len(visDatas[uid]['mem_use'])-20:] if len(visDatas[uid]['cpu_use']) > maxX: visDatas[uid]['cpu_use'] = visDatas[uid]['cpu_use'][len(visDatas[uid]['cpu_use'])-20:] axRam.set_title('RAM Usage of Nodes') axRam.set_ylabel('RAM", "fig = plt.figure() axRam = plt.subplot(2,1,1) axCpu = plt.subplot(2,1,2) # colors of lines", "= len(visDatas[uid]['mem_use']) axRam.plot(visDatas[uid]['mem_use'][max(0, l-maxX):l], color=cols[i], linestyle=lins[i], label=uid) axCpu.plot(visDatas[uid]['cpu_use'][max(0, l-maxX):l], color=cols[i], linestyle=lins[i], label=uid) if", "#from sense_hat import SenseHat from optparse import OptionParser import matplotlib.pyplot as plt import", "of lines lins = ['-']*10 + ['--']*10 + ['-.']*10 # manually update if", "import start_new_thread #from sense_hat import SenseHat from optparse import OptionParser import matplotlib.pyplot as", "'--update', type='float', dest='update', default=0.2) (options, args) = parser.parse_args() #sense = SenseHat() #sense.clear() #", "live update plot # plotting stuff fig = plt.figure() axRam = plt.subplot(2,1,1) axCpu", "axRam.set_ylabel('RAM (GB)') axRam.get_xaxis().set_visible(False) axRam.legend(loc='upper left') axRam.set_ylim(0,1.05) axCpu.set_title('CPU Usage of Nodes (4 Cores)') axCpu.set_ylabel('CPU", "visDatas[uid] = {'mem_use':[], 'cpu_use':[]} visDatas[uid]['mem_use'].append(mDict['mem_use']) visDatas[uid]['cpu_use'].append(mDict['cpu_use']) print(mDict) start_new_thread(clientReceiver, ()) plt.ion() # for live", "visDatas[uid]['cpu_use'] = visDatas[uid]['cpu_use'][len(visDatas[uid]['cpu_use'])-20:] axRam.set_title('RAM Usage of Nodes') axRam.set_ylabel('RAM (GB)') axRam.get_xaxis().set_visible(False) axRam.legend(loc='upper left') axRam.set_ylim(0,1.05)", "as plt import time parser = OptionParser() parser.add_option('-i', '--ip', type='string', dest='ip', default='127.0.0.1') parser.add_option('-p',", "range(options.numNodes)] # styles of lines lins = ['-']*10 + ['--']*10 + ['-.']*10 #", "in range(options.numNodes)] # styles of lines lins = ['-']*10 + ['--']*10 + ['-.']*10", "= {'mem_use':[], 'cpu_use':[]} visDatas[uid]['mem_use'].append(mDict['mem_use']) visDatas[uid]['cpu_use'].append(mDict['cpu_use']) print(mDict) start_new_thread(clientReceiver, ()) plt.ion() # for live update", "while True: con, _ = s.accept() start_new_thread(dataStream, (con,)) visDatas = {} # store", "plt.subplot(2,1,1) axCpu = plt.subplot(2,1,2) # colors of lines cols = ['C'+str(i%10) for i", "keep main in here to accept connections while True: con, _ = s.accept()", "len(visDatas[uid]['mem_use']) axRam.plot(visDatas[uid]['mem_use'][max(0, l-maxX):l], color=cols[i], linestyle=lins[i], label=uid) axCpu.plot(visDatas[uid]['cpu_use'][max(0, l-maxX):l], color=cols[i], linestyle=lins[i], label=uid) if len(visDatas[uid]['mem_use'])", "type='float', dest='update', default=0.2) (options, args) = parser.parse_args() #sense = SenseHat() #sense.clear() # temp" ]
[ "'this is a test' encoded_message = encoder(message) lyte.say(f' {message} -->encoded--> {encoded_message} -->decoded--> {decoder(encoded_message)}", "if __name__ == '__main__': message = 'this is a test' encoded_message = encoder(message)", "i in range( len(message) ): message[i] = shift( message[i], howMuch= secret_number ) return", "1): return chr(ord(c) + howMuch) def encoder(message): message=list(message) for i in range( len(message)", "howMuch= 1): return chr(ord(c) + howMuch) def encoder(message): message=list(message) for i in range(", "howMuch= secret_number ) return ''.join(message) def decoder(message): message=list(message) for i in range( len(message)", "message[i] = shift( message[i], howMuch= secret_number ) return ''.join(message) def decoder(message): message=list(message) for", "message = 'this is a test' encoded_message = encoder(message) lyte.say(f' {message} -->encoded--> {encoded_message}", "howMuch) def encoder(message): message=list(message) for i in range( len(message) ): message[i] = shift(", "message=list(message) for i in range( len(message) ): message[i] = shift( message[i], howMuch= secret_number", "= 'this is a test' encoded_message = encoder(message) lyte.say(f' {message} -->encoded--> {encoded_message} -->decoded-->", "in range( len(message) ): message[i] = shift(message[i], howMuch= - secret_number ) return ''.join(message)", "4 def shift(c, howMuch= 1): return chr(ord(c) + howMuch) def encoder(message): message=list(message) for", "return chr(ord(c) + howMuch) def encoder(message): message=list(message) for i in range( len(message) ):", "''.join(message) if __name__ == '__main__': message = 'this is a test' encoded_message =", ") return ''.join(message) if __name__ == '__main__': message = 'this is a test'", "message=list(message) for i in range( len(message) ): message[i] = shift(message[i], howMuch= - secret_number", "<filename>FargoNorth.py import lyte secret_number = 4 def shift(c, howMuch= 1): return chr(ord(c) +", "lyte secret_number = 4 def shift(c, howMuch= 1): return chr(ord(c) + howMuch) def", "'__main__': message = 'this is a test' encoded_message = encoder(message) lyte.say(f' {message} -->encoded-->", "i in range( len(message) ): message[i] = shift(message[i], howMuch= - secret_number ) return", "encoder(message): message=list(message) for i in range( len(message) ): message[i] = shift( message[i], howMuch=", "): message[i] = shift( message[i], howMuch= secret_number ) return ''.join(message) def decoder(message): message=list(message)", "+ howMuch) def encoder(message): message=list(message) for i in range( len(message) ): message[i] =", "message[i], howMuch= secret_number ) return ''.join(message) def decoder(message): message=list(message) for i in range(", "= shift( message[i], howMuch= secret_number ) return ''.join(message) def decoder(message): message=list(message) for i", "return ''.join(message) def decoder(message): message=list(message) for i in range( len(message) ): message[i] =", "def encoder(message): message=list(message) for i in range( len(message) ): message[i] = shift( message[i],", "len(message) ): message[i] = shift( message[i], howMuch= secret_number ) return ''.join(message) def decoder(message):", "a test' encoded_message = encoder(message) lyte.say(f' {message} -->encoded--> {encoded_message} -->decoded--> {decoder(encoded_message)} ') lyte.webMe()", "def decoder(message): message=list(message) for i in range( len(message) ): message[i] = shift(message[i], howMuch=", "import lyte secret_number = 4 def shift(c, howMuch= 1): return chr(ord(c) + howMuch)", "in range( len(message) ): message[i] = shift( message[i], howMuch= secret_number ) return ''.join(message)", "message[i] = shift(message[i], howMuch= - secret_number ) return ''.join(message) if __name__ == '__main__':", "chr(ord(c) + howMuch) def encoder(message): message=list(message) for i in range( len(message) ): message[i]", "howMuch= - secret_number ) return ''.join(message) if __name__ == '__main__': message = 'this", "- secret_number ) return ''.join(message) if __name__ == '__main__': message = 'this is", "for i in range( len(message) ): message[i] = shift(message[i], howMuch= - secret_number )", "shift(c, howMuch= 1): return chr(ord(c) + howMuch) def encoder(message): message=list(message) for i in", "decoder(message): message=list(message) for i in range( len(message) ): message[i] = shift(message[i], howMuch= -", "__name__ == '__main__': message = 'this is a test' encoded_message = encoder(message) lyte.say(f'", "): message[i] = shift(message[i], howMuch= - secret_number ) return ''.join(message) if __name__ ==", "= shift(message[i], howMuch= - secret_number ) return ''.join(message) if __name__ == '__main__': message", "range( len(message) ): message[i] = shift( message[i], howMuch= secret_number ) return ''.join(message) def", "shift(message[i], howMuch= - secret_number ) return ''.join(message) if __name__ == '__main__': message =", "secret_number ) return ''.join(message) def decoder(message): message=list(message) for i in range( len(message) ):", "for i in range( len(message) ): message[i] = shift( message[i], howMuch= secret_number )", ") return ''.join(message) def decoder(message): message=list(message) for i in range( len(message) ): message[i]", "return ''.join(message) if __name__ == '__main__': message = 'this is a test' encoded_message", "== '__main__': message = 'this is a test' encoded_message = encoder(message) lyte.say(f' {message}", "shift( message[i], howMuch= secret_number ) return ''.join(message) def decoder(message): message=list(message) for i in", "len(message) ): message[i] = shift(message[i], howMuch= - secret_number ) return ''.join(message) if __name__", "secret_number = 4 def shift(c, howMuch= 1): return chr(ord(c) + howMuch) def encoder(message):", "= 4 def shift(c, howMuch= 1): return chr(ord(c) + howMuch) def encoder(message): message=list(message)", "is a test' encoded_message = encoder(message) lyte.say(f' {message} -->encoded--> {encoded_message} -->decoded--> {decoder(encoded_message)} ')", "range( len(message) ): message[i] = shift(message[i], howMuch= - secret_number ) return ''.join(message) if", "secret_number ) return ''.join(message) if __name__ == '__main__': message = 'this is a", "''.join(message) def decoder(message): message=list(message) for i in range( len(message) ): message[i] = shift(message[i],", "def shift(c, howMuch= 1): return chr(ord(c) + howMuch) def encoder(message): message=list(message) for i" ]
[ "with ExecutorFactory() as ex: f_result = ex.executor(f_ng)() # compare Caffe2 and ngraph results", "KIND, either express or implied. # See the License for the specific language", "test_NHWC2NCHW(): workspace.ResetWorkspace() # NHWC shape = [2, 3, 4, 5] data1 = [float(i)", "Unless required by applicable law or agreed to in writing, software # distributed", "[random.gauss(mu=0, sigma=10) for i in range(np.prod(shape))] net = core.Net(\"net\") net.GivenTensorFill([], \"X\", shape=shape, values=data,", "0.175, 0.475, 0.024, 0.064, 0.175], ] run_all_close_compare_initiated_with_random_gauss('Softmax', shape=shape, data=data, expected=expected) def test_negative(): run_all_close_compare_initiated_with_random_gauss('Negative')", "test_negative(): run_all_close_compare_initiated_with_random_gauss('Negative') def test_sigmoid(): run_all_close_compare_initiated_with_random_gauss('Sigmoid') def test_tanh(): run_all_close_compare_initiated_with_random_gauss('Tanh') def test_exp(): workspace.ResetWorkspace() shape =", "54.59815, 2.71828, 7.3890, 20.08553], [2.71828, 7.3890, 20.08553, 54.59815, 2.71828, 7.3890, 20.08553], ] run_all_close_compare_initiated_with_random_gauss('Exp',", "3., 1., 2., 3., 4., 1., 2., 3. ] expected = [ [0.024,", "ExecutorFactory import numpy as np import random as random def run_all_close_compare_initiated_with_random_gauss(c2_op_name, shape=None, data=None,", "shape=shape, values=data, name=\"X\") getattr(net, c2_op_name)([\"X\"], [\"Y\"], name=\"Y\") # Execute via Caffe2 workspace.RunNetOnce(net) #", "1., 2., 3., 4., 1., 2., 3. ] expected = [ [2.71828, 7.3890,", "Get handle f_ng = importer.get_op_handle(\"Y\") # Execute with ExecutorFactory() as ex: f_result =", "this file except in compliance with the License. # You may obtain a", "[2.71828, 7.3890, 20.08553, 54.59815, 2.71828, 7.3890, 20.08553], [2.71828, 7.3890, 20.08553, 54.59815, 2.71828, 7.3890,", "expected, atol=1e-3, rtol=0, equal_nan=False)) def test_relu(): run_all_close_compare_initiated_with_random_gauss('Relu', shape=[10, 10]) def test_softmax(): shape =", "0.064, 0.175, 0.475, 0.024, 0.064, 0.175], ] run_all_close_compare_initiated_with_random_gauss('Softmax', shape=shape, data=data, expected=expected) def test_negative():", "Execute via Caffe2 workspace.RunNetOnce(net) # Import caffe2 network into ngraph importer = C2Importer()", "def test_negative(): run_all_close_compare_initiated_with_random_gauss('Negative') def test_sigmoid(): run_all_close_compare_initiated_with_random_gauss('Sigmoid') def test_tanh(): run_all_close_compare_initiated_with_random_gauss('Tanh') def test_exp(): workspace.ResetWorkspace() shape", "Copyright 2017-2018 Intel Corporation # # Licensed under the Apache License, Version 2.0", "= [ 1., 2., 3., 4., 1., 2., 3., 1., 2., 3., 4.,", "= [float(i) for i in range(np.prod(shape))] net = core.Net(\"net\") X = net.GivenTensorFill([], [\"X\"],", "ANY KIND, either express or implied. # See the License for the specific", "ngraph.testing import ExecutorFactory import numpy as np import random as random def run_all_close_compare_initiated_with_random_gauss(c2_op_name,", "1., 2., 3., 1., 2., 3., 4., 1., 2., 3. ] expected =", "data = [ 1., 2., 3., 4., 1., 2., 3., 1., 2., 3.,", "name=\"X\") X.NCHW2NHWC([], [\"Y\"], name=\"Y\") # Execute via Caffe2 workspace.RunNetOnce(net) # Import caffe2 network", "range(np.prod(shape))] net = core.Net(\"net\") net.GivenTensorFill([], \"X\", shape=shape, values=data, name=\"X\") getattr(net, c2_op_name)([\"X\"], [\"Y\"], name=\"Y\")", "Execute with ExecutorFactory() as ex: f_result = ex.executor(f_ng)() c2_y = workspace.FetchBlob(\"Y\") # compare", "[ 1., 2., 3., 4., 1., 2., 3., 1., 2., 3., 4., 1.,", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See", "ngraph results assert(np.allclose(f_result, c2_y, atol=1e-4, rtol=0, equal_nan=False)) # compare expected results and ngraph", "[2, 3, 4, 5] data1 = [float(i) for i in range(np.prod(shape))] net =", "= net.GivenTensorFill([], [\"X\"], shape=shape, values=data1, name=\"X\") X.NCHW2NHWC([], [\"Y\"], name=\"Y\") # Execute via Caffe2", "Caffe2 and ngraph results assert(np.array_equal(f_result, workspace.FetchBlob(\"Y\"))) def test_NHWC2NCHW(): workspace.ResetWorkspace() # NHWC shape =", "workspace.ResetWorkspace() # NCHW shape = [2, 3, 4, 5] data1 = [float(i) for", "compare expected results and ngraph results if expected: assert(np.allclose(f_result, expected, atol=1e-3, rtol=0, equal_nan=False))", "expected: assert(np.allclose(f_result, expected, atol=1e-3, rtol=0, equal_nan=False)) def test_relu(): run_all_close_compare_initiated_with_random_gauss('Relu', shape=[10, 10]) def test_softmax():", "7.3890, 20.08553], [2.71828, 7.3890, 20.08553, 54.59815, 2.71828, 7.3890, 20.08553], ] run_all_close_compare_initiated_with_random_gauss('Exp', shape=shape, data=data,", "= [2, 7] data = [ 1., 2., 3., 4., 1., 2., 3.,", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "# Copyright 2017-2018 Intel Corporation # # Licensed under the Apache License, Version", "with ExecutorFactory() as ex: f_result = ex.executor(f_ng)() c2_y = workspace.FetchBlob(\"Y\") # compare Caffe2", "limitations under the License. # ****************************************************************************** from __future__ import print_function from caffe2.python import", "OF ANY KIND, either express or implied. # See the License for the", "if not shape: shape = [2, 7] if not data: data = [random.gauss(mu=0,", "# ****************************************************************************** from __future__ import print_function from caffe2.python import core, workspace from ngraph.frontends.caffe2.c2_importer.importer", "core.Net(\"net\") net.GivenTensorFill([], \"X\", shape=shape, values=data, name=\"X\") getattr(net, c2_op_name)([\"X\"], [\"Y\"], name=\"Y\") # Execute via", "language governing permissions and # limitations under the License. # ****************************************************************************** from __future__", "C2Importer() importer.parse_net_def(net.Proto(), verbose=False) # Get handle f_ng = importer.get_op_handle(\"Y\") # Execute with ExecutorFactory()", "[\"Y\"], name=\"Y\") # Execute via Caffe2 workspace.RunNetOnce(net) # Import caffe2 network into ngraph", "3. ] expected = [ [2.71828, 7.3890, 20.08553, 54.59815, 2.71828, 7.3890, 20.08553], [2.71828,", "54.59815, 2.71828, 7.3890, 20.08553], ] run_all_close_compare_initiated_with_random_gauss('Exp', shape=shape, data=data, expected=expected) def test_NCHW2NHWC(): workspace.ResetWorkspace() #", "core.Net(\"net\") X = net.GivenTensorFill([], [\"X\"], shape=shape, values=data1, name=\"X\") X.NCHW2NHWC([], [\"Y\"], name=\"Y\") # Execute", "shape=None, data=None, expected=None): workspace.ResetWorkspace() if not shape: shape = [2, 7] if not", "random as random def run_all_close_compare_initiated_with_random_gauss(c2_op_name, shape=None, data=None, expected=None): workspace.ResetWorkspace() if not shape: shape", "numpy as np import random as random def run_all_close_compare_initiated_with_random_gauss(c2_op_name, shape=None, data=None, expected=None): workspace.ResetWorkspace()", "results assert(np.allclose(f_result, c2_y, atol=1e-4, rtol=0, equal_nan=False)) # compare expected results and ngraph results", "data = [random.gauss(mu=0, sigma=10) for i in range(np.prod(shape))] net = core.Net(\"net\") net.GivenTensorFill([], \"X\",", "# compare Caffe2 and ngraph results assert(np.array_equal(f_result, workspace.FetchBlob(\"Y\"))) def test_NHWC2NCHW(): workspace.ResetWorkspace() # NHWC", "and ngraph results assert(np.allclose(f_result, c2_y, atol=1e-4, rtol=0, equal_nan=False)) # compare expected results and", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "into ngraph importer = C2Importer() importer.parse_net_def(net.Proto(), verbose=False) # Get handle f_ng = importer.get_op_handle(\"Y\")", "data1 = [float(i) for i in range(np.prod(shape))] net = core.Net(\"net\") X = net.GivenTensorFill([],", "0.475, 0.024, 0.064, 0.175], ] run_all_close_compare_initiated_with_random_gauss('Softmax', shape=shape, data=data, expected=expected) def test_negative(): run_all_close_compare_initiated_with_random_gauss('Negative') def", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "workspace.ResetWorkspace() # NHWC shape = [2, 3, 4, 5] data1 = [float(i) for", "import numpy as np import random as random def run_all_close_compare_initiated_with_random_gauss(c2_op_name, shape=None, data=None, expected=None):", "i in range(np.prod(shape))] net = core.Net(\"net\") net.GivenTensorFill([], \"X\", shape=shape, values=data, name=\"X\") getattr(net, c2_op_name)([\"X\"],", "test_relu(): run_all_close_compare_initiated_with_random_gauss('Relu', shape=[10, 10]) def test_softmax(): shape = [2, 7] data = [", "def test_relu(): run_all_close_compare_initiated_with_random_gauss('Relu', shape=[10, 10]) def test_softmax(): shape = [2, 7] data =", "# Execute with ExecutorFactory() as ex: f_result = ex.executor(f_ng)() c2_y = workspace.FetchBlob(\"Y\") #", "under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "test_tanh(): run_all_close_compare_initiated_with_random_gauss('Tanh') def test_exp(): workspace.ResetWorkspace() shape = [2, 7] data = [ 1.,", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "not shape: shape = [2, 7] if not data: data = [random.gauss(mu=0, sigma=10)", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "ex.executor(f_ng)() c2_y = workspace.FetchBlob(\"Y\") # compare Caffe2 and ngraph results assert(np.allclose(f_result, c2_y, atol=1e-4,", "and ngraph results assert(np.array_equal(f_result, workspace.FetchBlob(\"Y\"))) def test_NHWC2NCHW(): workspace.ResetWorkspace() # NHWC shape = [2,", "net = core.Net(\"net\") X = net.GivenTensorFill([], [\"X\"], shape=shape, values=data1, name=\"X\") X.NCHW2NHWC([], [\"Y\"], name=\"Y\")", "f_ng = importer.get_op_handle(\"Y\") # Execute with ExecutorFactory() as ex: f_result = ex.executor(f_ng)() c2_y", "required by applicable law or agreed to in writing, software # distributed under", "core, workspace from ngraph.frontends.caffe2.c2_importer.importer import C2Importer from ngraph.testing import ExecutorFactory import numpy as", "applicable law or agreed to in writing, software # distributed under the License", "****************************************************************************** from __future__ import print_function from caffe2.python import core, workspace from ngraph.frontends.caffe2.c2_importer.importer import", "sigma=10) for i in range(np.prod(shape))] net = core.Net(\"net\") net.GivenTensorFill([], \"X\", shape=shape, values=data, name=\"X\")", "net.GivenTensorFill([], \"X\", shape=shape, values=data, name=\"X\") getattr(net, c2_op_name)([\"X\"], [\"Y\"], name=\"Y\") # Execute via Caffe2", "or agreed to in writing, software # distributed under the License is distributed", "shape: shape = [2, 7] if not data: data = [random.gauss(mu=0, sigma=10) for", "4, 5] data1 = [float(i) for i in range(np.prod(shape))] net = core.Net(\"net\") X", "values=data1, name=\"X\") X.NCHW2NHWC([], [\"Y\"], name=\"Y\") # Execute via Caffe2 workspace.RunNetOnce(net) # Import caffe2", "7.3890, 20.08553], ] run_all_close_compare_initiated_with_random_gauss('Exp', shape=shape, data=data, expected=expected) def test_NCHW2NHWC(): workspace.ResetWorkspace() # NCHW shape", "CONDITIONS OF ANY KIND, either express or implied. # See the License for", "NCHW shape = [2, 3, 4, 5] data1 = [float(i) for i in", "0.064, 0.175], ] run_all_close_compare_initiated_with_random_gauss('Softmax', shape=shape, data=data, expected=expected) def test_negative(): run_all_close_compare_initiated_with_random_gauss('Negative') def test_sigmoid(): run_all_close_compare_initiated_with_random_gauss('Sigmoid')", "= core.Net(\"net\") net.GivenTensorFill([], \"X\", shape=shape, values=data, name=\"X\") getattr(net, c2_op_name)([\"X\"], [\"Y\"], name=\"Y\") # Execute", "under the Apache License, Version 2.0 (the \"License\"); # you may not use", "writing, software # distributed under the License is distributed on an \"AS IS\"", "results if expected: assert(np.allclose(f_result, expected, atol=1e-3, rtol=0, equal_nan=False)) def test_relu(): run_all_close_compare_initiated_with_random_gauss('Relu', shape=[10, 10])", "You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "0.064, 0.175, 0.475, 0.024, 0.064, 0.175], [0.024, 0.064, 0.175, 0.475, 0.024, 0.064, 0.175],", "range(np.prod(shape))] net = core.Net(\"net\") X = net.GivenTensorFill([], [\"X\"], shape=shape, values=data1, name=\"X\") X.NCHW2NHWC([], [\"Y\"],", "License. # You may obtain a copy of the License at # #", "def test_sigmoid(): run_all_close_compare_initiated_with_random_gauss('Sigmoid') def test_tanh(): run_all_close_compare_initiated_with_random_gauss('Tanh') def test_exp(): workspace.ResetWorkspace() shape = [2, 7]", "shape = [2, 7] if not data: data = [random.gauss(mu=0, sigma=10) for i", "compliance with the License. # You may obtain a copy of the License", "= [ [0.024, 0.064, 0.175, 0.475, 0.024, 0.064, 0.175], [0.024, 0.064, 0.175, 0.475,", "shape = [2, 7] data = [ 1., 2., 3., 4., 1., 2.,", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "and # limitations under the License. # ****************************************************************************** from __future__ import print_function from", "expected=expected) def test_NCHW2NHWC(): workspace.ResetWorkspace() # NCHW shape = [2, 3, 4, 5] data1", "i in range(np.prod(shape))] net = core.Net(\"net\") X = net.GivenTensorFill([], [\"X\"], shape=shape, values=data1, name=\"X\")", "[0.024, 0.064, 0.175, 0.475, 0.024, 0.064, 0.175], ] run_all_close_compare_initiated_with_random_gauss('Softmax', shape=shape, data=data, expected=expected) def", "random def run_all_close_compare_initiated_with_random_gauss(c2_op_name, shape=None, data=None, expected=None): workspace.ResetWorkspace() if not shape: shape = [2,", "importer = C2Importer() importer.parse_net_def(net.Proto(), verbose=False) # Get handle f_ng = importer.get_op_handle(\"Y\") # Execute", "workspace.FetchBlob(\"Y\") # compare Caffe2 and ngraph results assert(np.allclose(f_result, c2_y, atol=1e-4, rtol=0, equal_nan=False)) #", "0.175], [0.024, 0.064, 0.175, 0.475, 0.024, 0.064, 0.175], ] run_all_close_compare_initiated_with_random_gauss('Softmax', shape=shape, data=data, expected=expected)", "not use this file except in compliance with the License. # You may", "run_all_close_compare_initiated_with_random_gauss('Negative') def test_sigmoid(): run_all_close_compare_initiated_with_random_gauss('Sigmoid') def test_tanh(): run_all_close_compare_initiated_with_random_gauss('Tanh') def test_exp(): workspace.ResetWorkspace() shape = [2,", "License, Version 2.0 (the \"License\"); # you may not use this file except", "Corporation # # Licensed under the Apache License, Version 2.0 (the \"License\"); #", "= [2, 7] if not data: data = [random.gauss(mu=0, sigma=10) for i in", "= [random.gauss(mu=0, sigma=10) for i in range(np.prod(shape))] net = core.Net(\"net\") net.GivenTensorFill([], \"X\", shape=shape,", "def test_tanh(): run_all_close_compare_initiated_with_random_gauss('Tanh') def test_exp(): workspace.ResetWorkspace() shape = [2, 7] data = [", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "] run_all_close_compare_initiated_with_random_gauss('Exp', shape=shape, data=data, expected=expected) def test_NCHW2NHWC(): workspace.ResetWorkspace() # NCHW shape = [2,", "via Caffe2 workspace.RunNetOnce(net) # Import caffe2 network into ngraph importer = C2Importer() importer.parse_net_def(net.Proto(),", "0.475, 0.024, 0.064, 0.175], [0.024, 0.064, 0.175, 0.475, 0.024, 0.064, 0.175], ] run_all_close_compare_initiated_with_random_gauss('Softmax',", "License. # ****************************************************************************** from __future__ import print_function from caffe2.python import core, workspace from", "# you may not use this file except in compliance with the License.", "agreed to in writing, software # distributed under the License is distributed on", "2., 3., 4., 1., 2., 3. ] expected = [ [0.024, 0.064, 0.175,", "0.175], ] run_all_close_compare_initiated_with_random_gauss('Softmax', shape=shape, data=data, expected=expected) def test_negative(): run_all_close_compare_initiated_with_random_gauss('Negative') def test_sigmoid(): run_all_close_compare_initiated_with_random_gauss('Sigmoid') def", "test_sigmoid(): run_all_close_compare_initiated_with_random_gauss('Sigmoid') def test_tanh(): run_all_close_compare_initiated_with_random_gauss('Tanh') def test_exp(): workspace.ResetWorkspace() shape = [2, 7] data", "results assert(np.array_equal(f_result, workspace.FetchBlob(\"Y\"))) def test_NHWC2NCHW(): workspace.ResetWorkspace() # NHWC shape = [2, 3, 4,", "1., 2., 3. ] expected = [ [0.024, 0.064, 0.175, 0.475, 0.024, 0.064,", "(the \"License\"); # you may not use this file except in compliance with", "workspace.RunNetOnce(net) # Import caffe2 network into ngraph importer = C2Importer() importer.parse_net_def(net.Proto(), verbose=False) #", "7.3890, 20.08553, 54.59815, 2.71828, 7.3890, 20.08553], ] run_all_close_compare_initiated_with_random_gauss('Exp', shape=shape, data=data, expected=expected) def test_NCHW2NHWC():", "Caffe2 workspace.RunNetOnce(net) # Import caffe2 network into ngraph importer = C2Importer() importer.parse_net_def(net.Proto(), verbose=False)", "importer.get_op_handle(\"Y\") # Execute with ExecutorFactory() as ex: f_result = ex.executor(f_ng)() c2_y = workspace.FetchBlob(\"Y\")", "c2_y, atol=1e-4, rtol=0, equal_nan=False)) # compare expected results and ngraph results if expected:", "# Unless required by applicable law or agreed to in writing, software #", "by applicable law or agreed to in writing, software # distributed under the", "= ex.executor(f_ng)() c2_y = workspace.FetchBlob(\"Y\") # compare Caffe2 and ngraph results assert(np.allclose(f_result, c2_y,", "# compare expected results and ngraph results if expected: assert(np.allclose(f_result, expected, atol=1e-3, rtol=0,", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "****************************************************************************** # Copyright 2017-2018 Intel Corporation # # Licensed under the Apache License,", "4., 1., 2., 3. ] expected = [ [0.024, 0.064, 0.175, 0.475, 0.024,", "expected results and ngraph results if expected: assert(np.allclose(f_result, expected, atol=1e-3, rtol=0, equal_nan=False)) def", "3., 4., 1., 2., 3., 1., 2., 3., 4., 1., 2., 3. ]", "# Execute via Caffe2 workspace.RunNetOnce(net) # Import caffe2 network into ngraph importer =", "[0.024, 0.064, 0.175, 0.475, 0.024, 0.064, 0.175], [0.024, 0.064, 0.175, 0.475, 0.024, 0.064,", "importer.get_op_handle(\"Y\") # Execute with ExecutorFactory() as ex: f_result = ex.executor(f_ng)() # compare Caffe2", "[\"X\"], shape=shape, values=data1, name=\"X\") X.NCHW2NHWC([], [\"Y\"], name=\"Y\") # Execute via Caffe2 workspace.RunNetOnce(net) #", "permissions and # limitations under the License. # ****************************************************************************** from __future__ import print_function", "file except in compliance with the License. # You may obtain a copy", "# Get handle f_ng = importer.get_op_handle(\"Y\") # Execute with ExecutorFactory() as ex: f_result", "7] if not data: data = [random.gauss(mu=0, sigma=10) for i in range(np.prod(shape))] net", "for i in range(np.prod(shape))] net = core.Net(\"net\") X = net.GivenTensorFill([], [\"X\"], shape=shape, values=data1,", "workspace.ResetWorkspace() shape = [2, 7] data = [ 1., 2., 3., 4., 1.,", "workspace.FetchBlob(\"Y\"))) def test_NHWC2NCHW(): workspace.ResetWorkspace() # NHWC shape = [2, 3, 4, 5] data1", "License for the specific language governing permissions and # limitations under the License.", "compare Caffe2 and ngraph results assert(np.allclose(f_result, c2_y, atol=1e-4, rtol=0, equal_nan=False)) # compare expected", "under the License. # ****************************************************************************** from __future__ import print_function from caffe2.python import core,", "verbose=False) # Get handle f_ng = importer.get_op_handle(\"Y\") # Execute with ExecutorFactory() as ex:", "0.064, 0.175], [0.024, 0.064, 0.175, 0.475, 0.024, 0.064, 0.175], ] run_all_close_compare_initiated_with_random_gauss('Softmax', shape=shape, data=data,", "to in writing, software # distributed under the License is distributed on an", "implied. # See the License for the specific language governing permissions and #", "\"License\"); # you may not use this file except in compliance with the", "2.71828, 7.3890, 20.08553], ] run_all_close_compare_initiated_with_random_gauss('Exp', shape=shape, data=data, expected=expected) def test_NCHW2NHWC(): workspace.ResetWorkspace() # NCHW", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "data=None, expected=None): workspace.ResetWorkspace() if not shape: shape = [2, 7] if not data:", "from ngraph.testing import ExecutorFactory import numpy as np import random as random def", "X.NCHW2NHWC([], [\"Y\"], name=\"Y\") # Execute via Caffe2 workspace.RunNetOnce(net) # Import caffe2 network into", "data=data, expected=expected) def test_NCHW2NHWC(): workspace.ResetWorkspace() # NCHW shape = [2, 3, 4, 5]", "0.024, 0.064, 0.175], ] run_all_close_compare_initiated_with_random_gauss('Softmax', shape=shape, data=data, expected=expected) def test_negative(): run_all_close_compare_initiated_with_random_gauss('Negative') def test_sigmoid():", "the License. # ****************************************************************************** from __future__ import print_function from caffe2.python import core, workspace", "or implied. # See the License for the specific language governing permissions and", "Execute with ExecutorFactory() as ex: f_result = ex.executor(f_ng)() # compare Caffe2 and ngraph", "the specific language governing permissions and # limitations under the License. # ******************************************************************************", "C2Importer from ngraph.testing import ExecutorFactory import numpy as np import random as random", "Apache License, Version 2.0 (the \"License\"); # you may not use this file", "OR CONDITIONS OF ANY KIND, either express or implied. # See the License", "may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "assert(np.array_equal(f_result, workspace.FetchBlob(\"Y\"))) def test_NHWC2NCHW(): workspace.ResetWorkspace() # NHWC shape = [2, 3, 4, 5]", "10]) def test_softmax(): shape = [2, 7] data = [ 1., 2., 3.,", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "in writing, software # distributed under the License is distributed on an \"AS", "test_exp(): workspace.ResetWorkspace() shape = [2, 7] data = [ 1., 2., 3., 4.,", "20.08553, 54.59815, 2.71828, 7.3890, 20.08553], ] run_all_close_compare_initiated_with_random_gauss('Exp', shape=shape, data=data, expected=expected) def test_NCHW2NHWC(): workspace.ResetWorkspace()", "] expected = [ [2.71828, 7.3890, 20.08553, 54.59815, 2.71828, 7.3890, 20.08553], [2.71828, 7.3890,", "7.3890, 20.08553, 54.59815, 2.71828, 7.3890, 20.08553], [2.71828, 7.3890, 20.08553, 54.59815, 2.71828, 7.3890, 20.08553],", "# See the License for the specific language governing permissions and # limitations", "the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "import print_function from caffe2.python import core, workspace from ngraph.frontends.caffe2.c2_importer.importer import C2Importer from ngraph.testing", "handle f_ng = importer.get_op_handle(\"Y\") # Execute with ExecutorFactory() as ex: f_result = ex.executor(f_ng)()", "[2, 7] data = [ 1., 2., 3., 4., 1., 2., 3., 1.,", "Import caffe2 network into ngraph importer = C2Importer() importer.parse_net_def(net.Proto(), verbose=False) # Get handle", "net.GivenTensorFill([], [\"X\"], shape=shape, values=data1, name=\"X\") X.NCHW2NHWC([], [\"Y\"], name=\"Y\") # Execute via Caffe2 workspace.RunNetOnce(net)", "7] data = [ 1., 2., 3., 4., 1., 2., 3., 1., 2.,", "2., 3. ] expected = [ [2.71828, 7.3890, 20.08553, 54.59815, 2.71828, 7.3890, 20.08553],", "ExecutorFactory() as ex: f_result = ex.executor(f_ng)() c2_y = workspace.FetchBlob(\"Y\") # compare Caffe2 and", "= workspace.FetchBlob(\"Y\") # compare Caffe2 and ngraph results assert(np.allclose(f_result, c2_y, atol=1e-4, rtol=0, equal_nan=False))", "= ex.executor(f_ng)() # compare Caffe2 and ngraph results assert(np.array_equal(f_result, workspace.FetchBlob(\"Y\"))) def test_NHWC2NCHW(): workspace.ResetWorkspace()", "run_all_close_compare_initiated_with_random_gauss('Tanh') def test_exp(): workspace.ResetWorkspace() shape = [2, 7] data = [ 1., 2.,", "[float(i) for i in range(np.prod(shape))] net = core.Net(\"net\") X = net.GivenTensorFill([], [\"X\"], shape=shape,", "the Apache License, Version 2.0 (the \"License\"); # you may not use this", "importer.parse_net_def(net.Proto(), verbose=False) # Get handle f_ng = importer.get_op_handle(\"Y\") # Execute with ExecutorFactory() as", "you may not use this file except in compliance with the License. #", "3., 4., 1., 2., 3. ] expected = [ [2.71828, 7.3890, 20.08553, 54.59815,", "X = net.GivenTensorFill([], [\"X\"], shape=shape, values=data1, name=\"X\") X.NCHW2NHWC([], [\"Y\"], name=\"Y\") # Execute via", "3., 1., 2., 3., 4., 1., 2., 3. ] expected = [ [2.71828,", "and ngraph results if expected: assert(np.allclose(f_result, expected, atol=1e-3, rtol=0, equal_nan=False)) def test_relu(): run_all_close_compare_initiated_with_random_gauss('Relu',", "assert(np.allclose(f_result, expected, atol=1e-3, rtol=0, equal_nan=False)) def test_relu(): run_all_close_compare_initiated_with_random_gauss('Relu', shape=[10, 10]) def test_softmax(): shape", "20.08553], [2.71828, 7.3890, 20.08553, 54.59815, 2.71828, 7.3890, 20.08553], ] run_all_close_compare_initiated_with_random_gauss('Exp', shape=shape, data=data, expected=expected)", "3, 4, 5] data1 = [float(i) for i in range(np.prod(shape))] net = core.Net(\"net\")", "equal_nan=False)) def test_relu(): run_all_close_compare_initiated_with_random_gauss('Relu', shape=[10, 10]) def test_softmax(): shape = [2, 7] data", "def test_NHWC2NCHW(): workspace.ResetWorkspace() # NHWC shape = [2, 3, 4, 5] data1 =", "20.08553], ] run_all_close_compare_initiated_with_random_gauss('Exp', shape=shape, data=data, expected=expected) def test_NCHW2NHWC(): workspace.ResetWorkspace() # NCHW shape =", "c2_y = workspace.FetchBlob(\"Y\") # compare Caffe2 and ngraph results assert(np.allclose(f_result, c2_y, atol=1e-4, rtol=0,", "from ngraph.frontends.caffe2.c2_importer.importer import C2Importer from ngraph.testing import ExecutorFactory import numpy as np import", "use this file except in compliance with the License. # You may obtain", "def test_softmax(): shape = [2, 7] data = [ 1., 2., 3., 4.,", "in range(np.prod(shape))] net = core.Net(\"net\") X = net.GivenTensorFill([], [\"X\"], shape=shape, values=data1, name=\"X\") X.NCHW2NHWC([],", "net = core.Net(\"net\") net.GivenTensorFill([], \"X\", shape=shape, values=data, name=\"X\") getattr(net, c2_op_name)([\"X\"], [\"Y\"], name=\"Y\") #", "compare Caffe2 and ngraph results assert(np.array_equal(f_result, workspace.FetchBlob(\"Y\"))) def test_NHWC2NCHW(): workspace.ResetWorkspace() # NHWC shape", "equal_nan=False)) # compare expected results and ngraph results if expected: assert(np.allclose(f_result, expected, atol=1e-3,", "1., 2., 3., 4., 1., 2., 3. ] expected = [ [0.024, 0.064,", "# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may", "= [2, 3, 4, 5] data1 = [float(i) for i in range(np.prod(shape))] net", "atol=1e-4, rtol=0, equal_nan=False)) # compare expected results and ngraph results if expected: assert(np.allclose(f_result,", "] expected = [ [0.024, 0.064, 0.175, 0.475, 0.024, 0.064, 0.175], [0.024, 0.064,", "run_all_close_compare_initiated_with_random_gauss(c2_op_name, shape=None, data=None, expected=None): workspace.ResetWorkspace() if not shape: shape = [2, 7] if", "2.0 (the \"License\"); # you may not use this file except in compliance", "4., 1., 2., 3. ] expected = [ [2.71828, 7.3890, 20.08553, 54.59815, 2.71828,", "ngraph results if expected: assert(np.allclose(f_result, expected, atol=1e-3, rtol=0, equal_nan=False)) def test_relu(): run_all_close_compare_initiated_with_random_gauss('Relu', shape=[10,", "# NHWC shape = [2, 3, 4, 5] data1 = [float(i) for i", "for the specific language governing permissions and # limitations under the License. #", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the", "print_function from caffe2.python import core, workspace from ngraph.frontends.caffe2.c2_importer.importer import C2Importer from ngraph.testing import", "1., 2., 3., 4., 1., 2., 3., 1., 2., 3., 4., 1., 2.,", "# # Unless required by applicable law or agreed to in writing, software", "[ [2.71828, 7.3890, 20.08553, 54.59815, 2.71828, 7.3890, 20.08553], [2.71828, 7.3890, 20.08553, 54.59815, 2.71828,", "express or implied. # See the License for the specific language governing permissions", "f_result = ex.executor(f_ng)() # compare Caffe2 and ngraph results assert(np.array_equal(f_result, workspace.FetchBlob(\"Y\"))) def test_NHWC2NCHW():", "as random def run_all_close_compare_initiated_with_random_gauss(c2_op_name, shape=None, data=None, expected=None): workspace.ResetWorkspace() if not shape: shape =", "values=data, name=\"X\") getattr(net, c2_op_name)([\"X\"], [\"Y\"], name=\"Y\") # Execute via Caffe2 workspace.RunNetOnce(net) # Import", "= core.Net(\"net\") X = net.GivenTensorFill([], [\"X\"], shape=shape, values=data1, name=\"X\") X.NCHW2NHWC([], [\"Y\"], name=\"Y\") #", "f_result = ex.executor(f_ng)() c2_y = workspace.FetchBlob(\"Y\") # compare Caffe2 and ngraph results assert(np.allclose(f_result,", "either express or implied. # See the License for the specific language governing", "f_ng = importer.get_op_handle(\"Y\") # Execute with ExecutorFactory() as ex: f_result = ex.executor(f_ng)() #", "def run_all_close_compare_initiated_with_random_gauss(c2_op_name, shape=None, data=None, expected=None): workspace.ResetWorkspace() if not shape: shape = [2, 7]", "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", "results and ngraph results if expected: assert(np.allclose(f_result, expected, atol=1e-3, rtol=0, equal_nan=False)) def test_relu():", "Caffe2 and ngraph results assert(np.allclose(f_result, c2_y, atol=1e-4, rtol=0, equal_nan=False)) # compare expected results", "from __future__ import print_function from caffe2.python import core, workspace from ngraph.frontends.caffe2.c2_importer.importer import C2Importer", "4., 1., 2., 3., 1., 2., 3., 4., 1., 2., 3. ] expected", "specific language governing permissions and # limitations under the License. # ****************************************************************************** from", "expected=None): workspace.ResetWorkspace() if not shape: shape = [2, 7] if not data: data", "the License. # You may obtain a copy of the License at #", "1., 2., 3. ] expected = [ [2.71828, 7.3890, 20.08553, 54.59815, 2.71828, 7.3890,", "test_softmax(): shape = [2, 7] data = [ 1., 2., 3., 4., 1.,", "run_all_close_compare_initiated_with_random_gauss('Relu', shape=[10, 10]) def test_softmax(): shape = [2, 7] data = [ 1.,", "# distributed under the License is distributed on an \"AS IS\" BASIS, #", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "= importer.get_op_handle(\"Y\") # Execute with ExecutorFactory() as ex: f_result = ex.executor(f_ng)() c2_y =", "2017-2018 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the", "as ex: f_result = ex.executor(f_ng)() c2_y = workspace.FetchBlob(\"Y\") # compare Caffe2 and ngraph", "for i in range(np.prod(shape))] net = core.Net(\"net\") net.GivenTensorFill([], \"X\", shape=shape, values=data, name=\"X\") getattr(net,", "np import random as random def run_all_close_compare_initiated_with_random_gauss(c2_op_name, shape=None, data=None, expected=None): workspace.ResetWorkspace() if not", "if expected: assert(np.allclose(f_result, expected, atol=1e-3, rtol=0, equal_nan=False)) def test_relu(): run_all_close_compare_initiated_with_random_gauss('Relu', shape=[10, 10]) def", "data=data, expected=expected) def test_negative(): run_all_close_compare_initiated_with_random_gauss('Negative') def test_sigmoid(): run_all_close_compare_initiated_with_random_gauss('Sigmoid') def test_tanh(): run_all_close_compare_initiated_with_random_gauss('Tanh') def test_exp():", "with the License. # You may obtain a copy of the License at", "5] data1 = [float(i) for i in range(np.prod(shape))] net = core.Net(\"net\") X =", "2., 3., 4., 1., 2., 3. ] expected = [ [2.71828, 7.3890, 20.08553,", "# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you", "0.175, 0.475, 0.024, 0.064, 0.175], [0.024, 0.064, 0.175, 0.475, 0.024, 0.064, 0.175], ]", "[2.71828, 7.3890, 20.08553, 54.59815, 2.71828, 7.3890, 20.08553], ] run_all_close_compare_initiated_with_random_gauss('Exp', shape=shape, data=data, expected=expected) def", "from caffe2.python import core, workspace from ngraph.frontends.caffe2.c2_importer.importer import C2Importer from ngraph.testing import ExecutorFactory", "assert(np.allclose(f_result, c2_y, atol=1e-4, rtol=0, equal_nan=False)) # compare expected results and ngraph results if", "# Execute with ExecutorFactory() as ex: f_result = ex.executor(f_ng)() # compare Caffe2 and", "__future__ import print_function from caffe2.python import core, workspace from ngraph.frontends.caffe2.c2_importer.importer import C2Importer from", "# Import caffe2 network into ngraph importer = C2Importer() importer.parse_net_def(net.Proto(), verbose=False) # Get", "# NCHW shape = [2, 3, 4, 5] data1 = [float(i) for i", "law or agreed to in writing, software # distributed under the License is", "the License for the specific language governing permissions and # limitations under the", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "ngraph importer = C2Importer() importer.parse_net_def(net.Proto(), verbose=False) # Get handle f_ng = importer.get_op_handle(\"Y\") #", "governing permissions and # limitations under the License. # ****************************************************************************** from __future__ import", "# compare Caffe2 and ngraph results assert(np.allclose(f_result, c2_y, atol=1e-4, rtol=0, equal_nan=False)) # compare", "run_all_close_compare_initiated_with_random_gauss('Exp', shape=shape, data=data, expected=expected) def test_NCHW2NHWC(): workspace.ResetWorkspace() # NCHW shape = [2, 3,", "as ex: f_result = ex.executor(f_ng)() # compare Caffe2 and ngraph results assert(np.array_equal(f_result, workspace.FetchBlob(\"Y\")))", "in range(np.prod(shape))] net = core.Net(\"net\") net.GivenTensorFill([], \"X\", shape=shape, values=data, name=\"X\") getattr(net, c2_op_name)([\"X\"], [\"Y\"],", "] run_all_close_compare_initiated_with_random_gauss('Softmax', shape=shape, data=data, expected=expected) def test_negative(): run_all_close_compare_initiated_with_random_gauss('Negative') def test_sigmoid(): run_all_close_compare_initiated_with_random_gauss('Sigmoid') def test_tanh():", "as np import random as random def run_all_close_compare_initiated_with_random_gauss(c2_op_name, shape=None, data=None, expected=None): workspace.ResetWorkspace() if", "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", "shape = [2, 3, 4, 5] data1 = [float(i) for i in range(np.prod(shape))]", "rtol=0, equal_nan=False)) def test_relu(): run_all_close_compare_initiated_with_random_gauss('Relu', shape=[10, 10]) def test_softmax(): shape = [2, 7]", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #", "shape=shape, data=data, expected=expected) def test_negative(): run_all_close_compare_initiated_with_random_gauss('Negative') def test_sigmoid(): run_all_close_compare_initiated_with_random_gauss('Sigmoid') def test_tanh(): run_all_close_compare_initiated_with_random_gauss('Tanh') def", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "NHWC shape = [2, 3, 4, 5] data1 = [float(i) for i in", "rtol=0, equal_nan=False)) # compare expected results and ngraph results if expected: assert(np.allclose(f_result, expected,", "def test_NCHW2NHWC(): workspace.ResetWorkspace() # NCHW shape = [2, 3, 4, 5] data1 =", "run_all_close_compare_initiated_with_random_gauss('Softmax', shape=shape, data=data, expected=expected) def test_negative(): run_all_close_compare_initiated_with_random_gauss('Negative') def test_sigmoid(): run_all_close_compare_initiated_with_random_gauss('Sigmoid') def test_tanh(): run_all_close_compare_initiated_with_random_gauss('Tanh')", "# limitations under the License. # ****************************************************************************** from __future__ import print_function from caffe2.python", "shape=[10, 10]) def test_softmax(): shape = [2, 7] data = [ 1., 2.,", "See the License for the specific language governing permissions and # limitations under", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "import ExecutorFactory import numpy as np import random as random def run_all_close_compare_initiated_with_random_gauss(c2_op_name, shape=None,", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "def test_exp(): workspace.ResetWorkspace() shape = [2, 7] data = [ 1., 2., 3.,", "2., 3., 1., 2., 3., 4., 1., 2., 3. ] expected = [", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", "caffe2 network into ngraph importer = C2Importer() importer.parse_net_def(net.Proto(), verbose=False) # Get handle f_ng", "c2_op_name)([\"X\"], [\"Y\"], name=\"Y\") # Execute via Caffe2 workspace.RunNetOnce(net) # Import caffe2 network into", "= C2Importer() importer.parse_net_def(net.Proto(), verbose=False) # Get handle f_ng = importer.get_op_handle(\"Y\") # Execute with", "ex: f_result = ex.executor(f_ng)() c2_y = workspace.FetchBlob(\"Y\") # compare Caffe2 and ngraph results", "= [ [2.71828, 7.3890, 20.08553, 54.59815, 2.71828, 7.3890, 20.08553], [2.71828, 7.3890, 20.08553, 54.59815,", "if not data: data = [random.gauss(mu=0, sigma=10) for i in range(np.prod(shape))] net =", "import random as random def run_all_close_compare_initiated_with_random_gauss(c2_op_name, shape=None, data=None, expected=None): workspace.ResetWorkspace() if not shape:", "atol=1e-3, rtol=0, equal_nan=False)) def test_relu(): run_all_close_compare_initiated_with_random_gauss('Relu', shape=[10, 10]) def test_softmax(): shape = [2,", "= importer.get_op_handle(\"Y\") # Execute with ExecutorFactory() as ex: f_result = ex.executor(f_ng)() # compare", "ex: f_result = ex.executor(f_ng)() # compare Caffe2 and ngraph results assert(np.array_equal(f_result, workspace.FetchBlob(\"Y\"))) def", "not data: data = [random.gauss(mu=0, sigma=10) for i in range(np.prod(shape))] net = core.Net(\"net\")", "Version 2.0 (the \"License\"); # you may not use this file except in", "except in compliance with the License. # You may obtain a copy of", "ex.executor(f_ng)() # compare Caffe2 and ngraph results assert(np.array_equal(f_result, workspace.FetchBlob(\"Y\"))) def test_NHWC2NCHW(): workspace.ResetWorkspace() #", "ngraph results assert(np.array_equal(f_result, workspace.FetchBlob(\"Y\"))) def test_NHWC2NCHW(): workspace.ResetWorkspace() # NHWC shape = [2, 3,", "[2, 7] if not data: data = [random.gauss(mu=0, sigma=10) for i in range(np.prod(shape))]", "[ [0.024, 0.064, 0.175, 0.475, 0.024, 0.064, 0.175], [0.024, 0.064, 0.175, 0.475, 0.024,", "2.71828, 7.3890, 20.08553], [2.71828, 7.3890, 20.08553, 54.59815, 2.71828, 7.3890, 20.08553], ] run_all_close_compare_initiated_with_random_gauss('Exp', shape=shape,", "# 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", "3., 4., 1., 2., 3. ] expected = [ [0.024, 0.064, 0.175, 0.475,", "data: data = [random.gauss(mu=0, sigma=10) for i in range(np.prod(shape))] net = core.Net(\"net\") net.GivenTensorFill([],", "shape=shape, values=data1, name=\"X\") X.NCHW2NHWC([], [\"Y\"], name=\"Y\") # Execute via Caffe2 workspace.RunNetOnce(net) # Import", "Intel Corporation # # Licensed under the Apache License, Version 2.0 (the \"License\");", "\"X\", shape=shape, values=data, name=\"X\") getattr(net, c2_op_name)([\"X\"], [\"Y\"], name=\"Y\") # Execute via Caffe2 workspace.RunNetOnce(net)", "workspace.ResetWorkspace() if not shape: shape = [2, 7] if not data: data =", "getattr(net, c2_op_name)([\"X\"], [\"Y\"], name=\"Y\") # Execute via Caffe2 workspace.RunNetOnce(net) # Import caffe2 network", "# ****************************************************************************** # Copyright 2017-2018 Intel Corporation # # Licensed under the Apache", "2., 3., 4., 1., 2., 3., 1., 2., 3., 4., 1., 2., 3.", "name=\"X\") getattr(net, c2_op_name)([\"X\"], [\"Y\"], name=\"Y\") # Execute via Caffe2 workspace.RunNetOnce(net) # Import caffe2", "test_NCHW2NHWC(): workspace.ResetWorkspace() # NCHW shape = [2, 3, 4, 5] data1 = [float(i)", "workspace from ngraph.frontends.caffe2.c2_importer.importer import C2Importer from ngraph.testing import ExecutorFactory import numpy as np", "ngraph.frontends.caffe2.c2_importer.importer import C2Importer from ngraph.testing import ExecutorFactory import numpy as np import random", "3. ] expected = [ [0.024, 0.064, 0.175, 0.475, 0.024, 0.064, 0.175], [0.024,", "caffe2.python import core, workspace from ngraph.frontends.caffe2.c2_importer.importer import C2Importer from ngraph.testing import ExecutorFactory import", "import C2Importer from ngraph.testing import ExecutorFactory import numpy as np import random as", "network into ngraph importer = C2Importer() importer.parse_net_def(net.Proto(), verbose=False) # Get handle f_ng =", "run_all_close_compare_initiated_with_random_gauss('Sigmoid') def test_tanh(): run_all_close_compare_initiated_with_random_gauss('Tanh') def test_exp(): workspace.ResetWorkspace() shape = [2, 7] data =", "name=\"Y\") # Execute via Caffe2 workspace.RunNetOnce(net) # Import caffe2 network into ngraph importer", "0.024, 0.064, 0.175], [0.024, 0.064, 0.175, 0.475, 0.024, 0.064, 0.175], ] run_all_close_compare_initiated_with_random_gauss('Softmax', shape=shape,", "expected=expected) def test_negative(): run_all_close_compare_initiated_with_random_gauss('Negative') def test_sigmoid(): run_all_close_compare_initiated_with_random_gauss('Sigmoid') def test_tanh(): run_all_close_compare_initiated_with_random_gauss('Tanh') def test_exp(): workspace.ResetWorkspace()", "expected = [ [0.024, 0.064, 0.175, 0.475, 0.024, 0.064, 0.175], [0.024, 0.064, 0.175,", "shape=shape, data=data, expected=expected) def test_NCHW2NHWC(): workspace.ResetWorkspace() # NCHW shape = [2, 3, 4,", "ExecutorFactory() as ex: f_result = ex.executor(f_ng)() # compare Caffe2 and ngraph results assert(np.array_equal(f_result,", "distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT", "import core, workspace from ngraph.frontends.caffe2.c2_importer.importer import C2Importer from ngraph.testing import ExecutorFactory import numpy", "2., 3. ] expected = [ [0.024, 0.064, 0.175, 0.475, 0.024, 0.064, 0.175],", "expected = [ [2.71828, 7.3890, 20.08553, 54.59815, 2.71828, 7.3890, 20.08553], [2.71828, 7.3890, 20.08553,", "20.08553, 54.59815, 2.71828, 7.3890, 20.08553], [2.71828, 7.3890, 20.08553, 54.59815, 2.71828, 7.3890, 20.08553], ]" ]
[ "dinds.append(0) # if no mixed layer depth found, set it to 0 return", "deps is the depth array depsU is the depth array at U poinnts", "index less <=1 because the # buoyancy frequency is hard to define there", "beta dk[S] ) / e3w temp and sal are the temperature and salinity", "dates = [] for t in np.arange(n2.shape[0]): Fr, c, u_avg = calculate_froude_number(n2[t, ...],", "1d array of mixed layer depths returns the mean mixed layer depth in", "averaging area returns: Frs, cs, u_avgs, dates the Froude number, internal wave speed,", "if no mixed layer depth found, set it to 0 return dinds def", "[] for ii in np.arange(n2.shape[-1]): inds = np.where(n2[:, ii] >= n2_thres) # exlclude", "if no mixed layer depth found, set to 0 else: dinds.append(0) # if", "array with current speeds (shape is depth, x). u must be a masked", "= [] for t in np.arange(n2.shape[0]): Fr, c, u_avg = calculate_froude_number(n2[t, ...], rho[t,", "roll depth axis in rho and drho to first axis # assume e3", "dates def calculate_density(t, s): \"\"\"Caluclates the density given temperature in deg C (t)", "9.81 # calculate average density in upper and lower layers rho_1 = np.zeros((rho.shape[-1]))", "mixed layer depths mlds and dates \"\"\" mlds = [] dates = []", "= calculate_internal_wave_speed(rho, deps, dinds) # calculate depth averaged currents u_avg = depth_averaged_current(u, depsU)", "returns n2, an array of square buoyancy frequency at each point in temp/sal.", "temp/sal arrays returns n2, an array of square buoyancy frequency at each point", "depth is chosen based on the lowest near-surface vertical grid cell where n2", "t*s**1.5 - 1.6546e-6 * t*t*s**1.5 + 4.8314e-4 * s*s ) return rho def", "array (rho) \"\"\" rho = ( 999.842594 + 6.793952e-2 * t - 9.095290e-3", "...], rho[t, ...], u[t, ...], deps, depsU, n2_thres=n2_thres) Frs.append(np.mean(Fr[xmin:xmax+1])) cs.append(np.mean(c[xmin:xmax+1])) u_avgs.append(np.mean(u_avg[xmin:xmax+1])) dates.append(time_origin +", "= [] for ii in np.arange(n2.shape[-1]): inds = np.where(n2[:, ii] >= n2_thres) #", "= 9.81 # calculate average density in upper and lower layers rho_1 =", "'None': dinds = np.argmax(n2, axis=0) else: dinds = [] for ii in np.arange(n2.shape[-1]):", "def froude_time_series(n2, rho, u, deps, depsU, times, time_origin, xmin=300, xmax=700, n2_thres=5e-6): \"\"\"Calculates the", ">= n2_thres A resaonable value for n2_thres is 5e-6. If n2_thres = 'None'", "with dates \"\"\" Frs = [] cs = [] u_avgs = [] dates", "Calculate the squared buoyancy frequency (n2) given temperature and salinity profiles. N2 is", "can be used to calculate the Froude # number in a simple 2D", "is the masked array of buoyancy frequencies with dimensions (depth, x) returns a", "if inds: dinds.append(min(inds)) else: dinds.append(0) # if no mixed layer depth found, set", "4.8314e-4 * s*s ) return rho def calculate_internal_wave_speed(rho, deps, dinds): \"\"\"Calculates the internal", "- rho_r[k, ...]) # Unroll drho drho = np.rollaxis(drho_r, 0, depth_axis+1) rho =", "depths returns the mean mixed layer depth in the defined region \"\"\" mean_md", "each x-position \"\"\" if n2_thres == 'None': dinds = np.argmax(n2, axis=0) else: dinds", "depth found, set to 0 else: dinds.append(0) # if no mixed layer depth", "with dimensions (time, depth, x) deps is the model depth array times is", "as a datetime returns a list of mixed layer depths mlds and dates", "2D system # <NAME>, 2015 import numpy as np import datetime from salishsea_tools.nowcast", "t*t*t*t*s - 5.72466e-3 * s**1.5 + 1.0227e-4 * t*s**1.5 - 1.6546e-6 * t*t*s**1.5", "of depths and dinds is a list of indices that define the mixed", "array at U poinnts returns: Fr, c, u_avg - the Froude number, wave", "u are buoyancy frequency, density and current arrays (shape depth, x) deps is", "buoyancy frequency, density and current arrays (shape time, depth, x) deps is the", "drho = np.rollaxis(drho_r, 0, depth_axis+1) rho = np.rollaxis(rho_r, 0, depth_axis+1) # Define N2", "times, time_origin, xmin=300, xmax=700, n2_thres=5e-6): \"\"\"Calculates the Froude number time series n2, rho,", "t*t*t*s + 5.3875e-9 * t*t*t*t*s - 5.72466e-3 * s**1.5 + 1.0227e-4 * t*s**1.5", "Frs, cs, u_avgs, dates the Froude number, internal wave speed, and depth averaged", "layer. rho is the model density (shape is depth, x), deps is the", "u, deps, depsU, times, time_origin, xmin=300, xmax=700, n2_thres=5e-6): \"\"\"Calculates the Froude number time", "n2 is returned. n2 is the masked array of buoyancy frequencies with dimensions", "temp and sal are the temperature and salinity arrays e3 is an array", "in rho and drho to first axis # assume e3 already has depth", "calculate depth averaged currents u_avg = depth_averaged_current(u, depsU) # Froude numer Fr =", "+ 7.6438e-5 * t*t*s - 8.2467e-7 * t*t*t*s + 5.3875e-9 * t*t*t*t*s -", "in first axis drho_r = np.rollaxis(drho, depth_axis) rho_r = np.rollaxis(rho, depth_axis) for k", "in np.arange(n2.shape[0]): Fr, c, u_avg = calculate_froude_number(n2[t, ...], rho[t, ...], u[t, ...], deps,", "e3, depth_axis=1): \"\"\" Calculate the squared buoyancy frequency (n2) given temperature and salinity", "rho_1 = np.zeros((rho.shape[-1])) rho_2 = np.zeros((rho.shape[-1])) for ind, d in enumerate(dinds): rho_1[ind] =", "squared buoyancy frequency (n2) given temperature and salinity profiles. N2 is set to", "(m/s^2) g = 9.81 # calculate average density in upper and lower layers", "number in a simple 2D system # <NAME>, 2015 import numpy as np", "- 1.6546e-6 * t*t*s**1.5 + 4.8314e-4 * s*s ) return rho def calculate_internal_wave_speed(rho,", "dates = [] for t in np.arange(n2.shape[0]): dinds = find_mixed_depth_indices(n2[t, ...], n2_thres=n2_thres) mld", "(depth, x) returns a list of indices of mixed layer depth cell for", "average_mixed_layer_depth(mixed_depths, xmin, xmax): \"\"\"Averages the mixed layer depths over indices xmin and xmax", "rho = calculate_density(temp, sal) # Density gradient drho = np.zeros(rho.shape) # roll depth", "datetime.timedelta(seconds=times[t])) return mlds, dates def calculate_density(t, s): \"\"\"Caluclates the density given temperature in", "\"\"\" if n2_thres == 'None': dinds = np.argmax(n2, axis=0) else: dinds = []", "s**1.5 + 1.0227e-4 * t*s**1.5 - 1.6546e-6 * t*t*s**1.5 + 4.8314e-4 * s*s", "cs.append(np.mean(c[xmin:xmax+1])) u_avgs.append(np.mean(u_avg[xmin:xmax+1])) dates.append(time_origin + datetime.timedelta(seconds=times[t])) return Frs, cs, u_avgs, dates def calculate_buoyancy_frequency(temp, sal,", "mld_time_series(n2, deps, times, time_origin, xmin=300, xmax=700, n2_thres=5e-6): \"\"\"Calculates the mean mixed layer depth", ") return rho def calculate_internal_wave_speed(rho, deps, dinds): \"\"\"Calculates the internal wave speed c", "numer Fr = np.abs(u_avg)/c return Fr, c, u_avg def froude_time_series(n2, rho, u, deps,", "rho, u, deps, depsU, times, time_origin, xmin=300, xmax=700, n2_thres=5e-6): \"\"\"Calculates the Froude number", "<=1 because the # buoyancy frequency is hard to define there if inds[0].size:", "to first axis # assume e3 already has depth axis in first axis", "current (shape x) \"\"\" u_avg = analyze.depth_average(u, deps, depth_axis=0) return u_avg def calculate_froude_number(n2,", "= find_mixed_depth_indices(n2, n2_thres=n2_thres) # calculate internal wave speed c = calculate_internal_wave_speed(rho, deps, dinds)", "+ 8.24493e-1 * s - 4.0899e-3 * t*s + 7.6438e-5 * t*t*s -", "t*s + 7.6438e-5 * t*t*s - 8.2467e-7 * t*t*t*s + 5.3875e-9 * t*t*t*t*s", "# calculate mixed layer depth h_1 = deps[dinds] # calcuate wave speed c", "averaged currents u_avg = depth_averaged_current(u, depsU) # Froude numer Fr = np.abs(u_avg)/c return", "depth array depsU is the model deps array at U points times is", "depsU is the depth array at U poinnts returns: Fr, c, u_avg -", "Note that NEMO uses a defini tion based on an question of state:", "an array of the vertical scale factors (grid spacing). Use e3w for constistency", "the axis which corresponds to depth in the temp/sal arrays returns n2, an", "depth_axis) rho_r = np.rollaxis(rho, depth_axis) for k in np.arange(1, drho.shape[depth_axis]-1): drho_r[k, ...] =", "an array (rho) \"\"\" rho = ( 999.842594 + 6.793952e-2 * t -", "n2 = g*drho/rho # no negative because depth increases with increasking k return", "\"\"\"Finds the index of the mixed layer depth for each x-position. The mixed", "rho, u are buoyancy frequency, density and current arrays (shape depth, x) deps", "deps array at U points times is the model time_counter array time_origin is", "averaged current for each time associated with dates \"\"\" Frs = [] cs", "+ 1.0227e-4 * t*s**1.5 - 1.6546e-6 * t*t*s**1.5 + 4.8314e-4 * s*s )", "layers dinds = find_mixed_depth_indices(n2, n2_thres=n2_thres) # calculate internal wave speed c = calculate_internal_wave_speed(rho,", "n2_thres = 'None' then the index of the maximum n2 is returned. n2", "near-surface vertical grid cell where n2 >= n2_thres A resaonable value for n2_thres", "t*t + 1.001685e-4 * t*t*t - 1.120083e-6 * t*t*t*t + 6.536332e-9 * t*t*t*t*t", "and salinity arrays e3 is an array of the vertical scale factors (grid", "* t*t*t*s + 5.3875e-9 * t*t*t*t*s - 5.72466e-3 * s**1.5 + 1.0227e-4 *", "for each x-position. The mixed layer depth is chosen based on the lowest", "axis=0) else: dinds = [] for ii in np.arange(n2.shape[-1]): inds = np.where(n2[:, ii]", "wave speed c = np.sqrt(g*(rho_2-rho_1)/rho_2*h_1) return c def depth_averaged_current(u, deps): \"\"\"Calculates the depth", "model deps array at U points times is the model time_counter array time_origin", "to g*drho/dz/rho. Note that NEMO uses a defini tion based on an question", "uses a defini tion based on an question of state: g* (alpha dk[T]", "layer depth in the defined region \"\"\" mean_md = np.mean(mixed_depths[xmin:xmax+1]) return mean_md def", "at U poinnts returns: Fr, c, u_avg - the Froude number, wave speed,", "# Froude numer Fr = np.abs(u_avg)/c return Fr, c, u_avg def froude_time_series(n2, rho,", "depths and dinds is a list of indices that define the mixed layer", "return Fr, c, u_avg def froude_time_series(n2, rho, u, deps, depsU, times, time_origin, xmin=300,", "the averaging area returns: Frs, cs, u_avgs, dates the Froude number, internal wave", "the internal wave speed c = sqrt(g*(rho2-rho1)/rho2*h1) where g is acceleration due to", "the depths averaged current (shape x) \"\"\" u_avg = analyze.depth_average(u, deps, depth_axis=0) return", "calculate density. rho = calculate_density(temp, sal) # Density gradient drho = np.zeros(rho.shape) #", "wave speed, and depth averaged velocity for each x-index \"\"\" # calculate mixed", "np.argmax(n2, axis=0) else: dinds = [] for ii in np.arange(n2.shape[-1]): inds = np.where(n2[:,", "a region defined by xmin and xmax over time n2 is the buoyancy", "depth, x). u must be a masked array deps is the array of", "depsU is the model deps array at U points times is the model", "indices of mixed layer depth cell for each x-position \"\"\" if n2_thres ==", "inds = np.where(n2[:, ii] >= n2_thres) # exlclude first vertical index less <=1", "array of the vertical scale factors (grid spacing). Use e3w for constistency with", "inds = filter(lambda x: x > 1, inds[0]) if inds: dinds.append(min(inds)) else: dinds.append(0)", "mean mixed layer depth in a region defined by xmin and xmax over", "used to calculate the Froude # number in a simple 2D system #", "square buoyancy frequency at each point in temp/sal. \"\"\" # acceleration due to", "is the buoyancy frequency array with dimensions (time, depth, x) deps is the", "depth averaged currents u_avg = depth_averaged_current(u, depsU) # Froude numer Fr = np.abs(u_avg)/c", "NEMO uses a defini tion based on an question of state: g* (alpha", "the model's time_origin as a datetime returns a list of mixed layer depths", "\"\"\"Calculates the internal wave speed c = sqrt(g*(rho2-rho1)/rho2*h1) where g is acceleration due", "set to g*drho/dz/rho. Note that NEMO uses a defini tion based on an", "and dates \"\"\" mlds = [] dates = [] for t in np.arange(n2.shape[0]):", "mixed layer depth h_1 = deps[dinds] # calcuate wave speed c = np.sqrt(g*(rho_2-rho_1)/rho_2*h_1)", "for ind, d in enumerate(dinds): rho_1[ind] = analyze.depth_average(rho[0:d+1, ind], deps[0:d+1], depth_axis=0) rho_2[ind] =", "* s - 4.0899e-3 * t*s + 7.6438e-5 * t*t*s - 8.2467e-7 *", "and depth averaged current for each time associated with dates \"\"\" Frs =", "functions that can be used to calculate the Froude # number in a", "over time n2 is the buoyancy frequency array with dimensions (time, depth, x)", "corresponds to depth in the temp/sal arrays returns n2, an array of square", "g*drho/dz/rho. Note that NEMO uses a defini tion based on an question of", "xmax): \"\"\"Averages the mixed layer depths over indices xmin and xmax mixed_depths is", "returns u_avg, the depths averaged current (shape x) \"\"\" u_avg = analyze.depth_average(u, deps,", "speed c = calculate_internal_wave_speed(rho, deps, dinds) # calculate depth averaged currents u_avg =", "in np.arange(1, drho.shape[depth_axis]-1): drho_r[k, ...] = 1/e3[k, ...]*(rho_r[k+1, ...] - rho_r[k, ...]) #", "4.0899e-3 * t*s + 7.6438e-5 * t*t*s - 8.2467e-7 * t*t*t*s + 5.3875e-9", "(n2) given temperature and salinity profiles. N2 is set to g*drho/dz/rho. Note that", "= 'None' then the index of the maximum n2 is returned. n2 is", "set to 0 else: dinds.append(0) # if no mixed layer depth found, set", "chosen based on the lowest near-surface vertical grid cell where n2 >= n2_thres", "depth_axis defines the axis which corresponds to depth in the temp/sal arrays returns", "based on the lowest near-surface vertical grid cell where n2 >= n2_thres A", "np.arange(1, drho.shape[depth_axis]-1): drho_r[k, ...] = 1/e3[k, ...]*(rho_r[k+1, ...] - rho_r[k, ...]) # Unroll", "\"\"\" mean_md = np.mean(mixed_depths[xmin:xmax+1]) return mean_md def mld_time_series(n2, deps, times, time_origin, xmin=300, xmax=700,", "time_origin as a datetime xmin,xmax define the averaging area returns: Frs, cs, u_avgs,", "is chosen based on the lowest near-surface vertical grid cell where n2 >=", "e3 is an array of the vertical scale factors (grid spacing). Use e3w", "exlclude first vertical index less <=1 because the # buoyancy frequency is hard", "N2 is set to g*drho/dz/rho. Note that NEMO uses a defini tion based", "h1 is thickness of upper layer. rho is the model density (shape is", "the # buoyancy frequency is hard to define there if inds[0].size: inds =", "at each x-index in rho \"\"\" # acceleration due to gravity (m/s^2) g", "xmax over time n2 is the buoyancy frequency array with dimensions (time, depth,", "found, set to 0 else: dinds.append(0) # if no mixed layer depth found,", "time_origin, xmin=300, xmax=700, n2_thres=5e-6): \"\"\"Calculates the mean mixed layer depth in a region", "returns: Fr, c, u_avg - the Froude number, wave speed, and depth averaged", "velocity for each x-index \"\"\" # calculate mixed layers dinds = find_mixed_depth_indices(n2, n2_thres=n2_thres)", "# calculate depth averaged currents u_avg = depth_averaged_current(u, depsU) # Froude numer Fr", "averaged velocity for each x-index \"\"\" # calculate mixed layers dinds = find_mixed_depth_indices(n2,", "x) deps is the model depth array depsU is the model deps array", "n2_thres is 5e-6. If n2_thres = 'None' then the index of the maximum", "5.3875e-9 * t*t*t*t*s - 5.72466e-3 * s**1.5 + 1.0227e-4 * t*s**1.5 - 1.6546e-6", "is density of upper layer and h1 is thickness of upper layer. rho", "wave speed, and depth averaged current for each time associated with dates \"\"\"", "g* (alpha dk[T] + beta dk[S] ) / e3w temp and sal are", "dk[T] + beta dk[S] ) / e3w temp and sal are the temperature", "the model density (shape is depth, x), deps is the array of depths", "u are buoyancy frequency, density and current arrays (shape time, depth, x) deps", "wave speeds at each x-index in rho \"\"\" # acceleration due to gravity", "+ beta dk[S] ) / e3w temp and sal are the temperature and", "t*t*s**1.5 + 4.8314e-4 * s*s ) return rho def calculate_internal_wave_speed(rho, deps, dinds): \"\"\"Calculates", "of mixed layer depths mlds and dates \"\"\" mlds = [] dates =", "return rho def calculate_internal_wave_speed(rho, deps, dinds): \"\"\"Calculates the internal wave speed c =", "index of the mixed layer depth for each x-position. The mixed layer depth", "calculate_density(t, s): \"\"\"Caluclates the density given temperature in deg C (t) and salinity", "(s). returns the density as an array (rho) \"\"\" rho = ( 999.842594", "constistency with NEMO. depth_axis defines the axis which corresponds to depth in the", "n2, rho, u are buoyancy frequency, density and current arrays (shape depth, x)", "# assume e3 already has depth axis in first axis drho_r = np.rollaxis(drho,", "time_origin is the model's time_origin as a datetime returns a list of mixed", "of upper layer. rho is the model density (shape is depth, x), deps", "# calculate internal wave speed c = calculate_internal_wave_speed(rho, deps, dinds) # calculate depth", "* t - 9.095290e-3 * t*t + 1.001685e-4 * t*t*t - 1.120083e-6 *", "mlds and dates \"\"\" mlds = [] dates = [] for t in", "of internal wave speeds at each x-index in rho \"\"\" # acceleration due", "depth, x) deps is the depth array depsU is the depth array at", "dinds) # calculate depth averaged currents u_avg = depth_averaged_current(u, depsU) # Froude numer", "the Froude number, internal wave speed, and depth averaged current for each time", "* t*t*s - 8.2467e-7 * t*t*t*s + 5.3875e-9 * t*t*t*t*s - 5.72466e-3 *", "mixed layer depth found, set it to 0 return dinds def average_mixed_layer_depth(mixed_depths, xmin,", "mixed layer depths over indices xmin and xmax mixed_depths is a 1d array", "dinds.append(min(inds)) else: dinds.append(0) # if no mixed layer depth found, set to 0", "frequencies with dimensions (depth, x) returns a list of indices of mixed layer", "layer, rho1 is density of upper layer and h1 is thickness of upper", "number, wave speed, and depth averaged velocity for each x-index \"\"\" # calculate", "times is the model time_counter array time_origin is the mode's time_origin as a", "import analyze def find_mixed_depth_indices(n2, n2_thres=5e-6): \"\"\"Finds the index of the mixed layer depth", "= analyze.depth_average(rho[d+1:, ind], deps[d+1:], depth_axis=0) # calculate mixed layer depth h_1 = deps[dinds]", "depth_axis=0) return u_avg def calculate_froude_number(n2, rho, u, deps, depsU, n2_thres=5e-6): \"\"\"Calculates the Froude", "0, depth_axis+1) rho = np.rollaxis(rho_r, 0, depth_axis+1) # Define N2 n2 = g*drho/rho", "Froude number n2, rho, u are buoyancy frequency, density and current arrays (shape", "This is a module with functions that can be used to calculate the", "u_avgs, dates def calculate_buoyancy_frequency(temp, sal, e3, depth_axis=1): \"\"\" Calculate the squared buoyancy frequency", "dates \"\"\" Frs = [] cs = [] u_avgs = [] dates =", "mlds, dates def calculate_density(t, s): \"\"\"Caluclates the density given temperature in deg C", "speed, and depth averaged velocity for each x-index \"\"\" # calculate mixed layers", "lowest near-surface vertical grid cell where n2 >= n2_thres A resaonable value for", "dinds is a list of indices that define the mixed layer depth. rho", "are the temperature and salinity arrays e3 is an array of the vertical", "Frs, cs, u_avgs, dates def calculate_buoyancy_frequency(temp, sal, e3, depth_axis=1): \"\"\" Calculate the squared", "frequency (n2) given temperature and salinity profiles. N2 is set to g*drho/dz/rho. Note", "s*s ) return rho def calculate_internal_wave_speed(rho, deps, dinds): \"\"\"Calculates the internal wave speed", "for each x-index \"\"\" # calculate mixed layers dinds = find_mixed_depth_indices(n2, n2_thres=n2_thres) #", "mixed layer depth is chosen based on the lowest near-surface vertical grid cell", "the model time_counter array time_origin is the mode's time_origin as a datetime xmin,xmax", "drho_r[k, ...] = 1/e3[k, ...]*(rho_r[k+1, ...] - rho_r[k, ...]) # Unroll drho drho", "x-position. The mixed layer depth is chosen based on the lowest near-surface vertical", "xmin,xmax define the averaging area returns: Frs, cs, u_avgs, dates the Froude number,", "* t*t*t*t*t + 8.24493e-1 * s - 4.0899e-3 * t*s + 7.6438e-5 *", "time associated with dates \"\"\" Frs = [] cs = [] u_avgs =", "frequency, density and current arrays (shape time, depth, x) deps is the model", "layers rho_1 = np.zeros((rho.shape[-1])) rho_2 = np.zeros((rho.shape[-1])) for ind, d in enumerate(dinds): rho_1[ind]", "is set to g*drho/dz/rho. Note that NEMO uses a defini tion based on", "deps, depsU, n2_thres=n2_thres) Frs.append(np.mean(Fr[xmin:xmax+1])) cs.append(np.mean(c[xmin:xmax+1])) u_avgs.append(np.mean(u_avg[xmin:xmax+1])) dates.append(time_origin + datetime.timedelta(seconds=times[t])) return Frs, cs, u_avgs,", "array time_origin is the mode's time_origin as a datetime xmin,xmax define the averaging", "to depth in the temp/sal arrays returns n2, an array of square buoyancy", "sal are the temperature and salinity arrays e3 is an array of the", "dinds): \"\"\"Calculates the internal wave speed c = sqrt(g*(rho2-rho1)/rho2*h1) where g is acceleration", "of indices of mixed layer depth cell for each x-position \"\"\" if n2_thres", "question of state: g* (alpha dk[T] + beta dk[S] ) / e3w temp", "g = 9.81 # calculate average density in upper and lower layers rho_1", "datetime.timedelta(seconds=times[t])) return Frs, cs, u_avgs, dates def calculate_buoyancy_frequency(temp, sal, e3, depth_axis=1): \"\"\" Calculate", "is depth, x), deps is the array of depths and dinds is a", "x-position \"\"\" if n2_thres == 'None': dinds = np.argmax(n2, axis=0) else: dinds =", "filter(lambda x: x > 1, inds[0]) if inds: dinds.append(min(inds)) else: dinds.append(0) # if", "> 1, inds[0]) if inds: dinds.append(min(inds)) else: dinds.append(0) # if no mixed layer", "the lowest near-surface vertical grid cell where n2 >= n2_thres A resaonable value", "+ 6.536332e-9 * t*t*t*t*t + 8.24493e-1 * s - 4.0899e-3 * t*s +", "c, an array of internal wave speeds at each x-index in rho \"\"\"", "psu (s). returns the density as an array (rho) \"\"\" rho = (", "grid cell where n2 >= n2_thres A resaonable value for n2_thres is 5e-6.", "average_mixed_layer_depth(deps[dinds], xmin, xmax,) mlds.append(mld) dates.append(time_origin + datetime.timedelta(seconds=times[t])) return mlds, dates def calculate_density(t, s):", "- 1.120083e-6 * t*t*t*t + 6.536332e-9 * t*t*t*t*t + 8.24493e-1 * s -", "a masked array deps is the array of depths returns u_avg, the depths", "buoyancy frequency (n2) given temperature and salinity profiles. N2 is set to g*drho/dz/rho.", "\"\"\" mlds = [] dates = [] for t in np.arange(n2.shape[0]): dinds =", "xmin, xmax): \"\"\"Averages the mixed layer depths over indices xmin and xmax mixed_depths", "c def depth_averaged_current(u, deps): \"\"\"Calculates the depth averaged current u is the array", "density as an array (rho) \"\"\" rho = ( 999.842594 + 6.793952e-2 *", "simple 2D system # <NAME>, 2015 import numpy as np import datetime from", "= deps[dinds] # calcuate wave speed c = np.sqrt(g*(rho_2-rho_1)/rho_2*h_1) return c def depth_averaged_current(u,", "layer depth cell for each x-position \"\"\" if n2_thres == 'None': dinds =", "mixed layer depth. rho must be a masked array returns c, an array", "buoyancy frequency, density and current arrays (shape depth, x) deps is the depth", "deps is the model depth array depsU is the model deps array at", "and xmax mixed_depths is a 1d array of mixed layer depths returns the", "of upper layer and h1 is thickness of upper layer. rho is the", "and xmax over time n2 is the buoyancy frequency array with dimensions (time,", "calculate_froude_number(n2[t, ...], rho[t, ...], u[t, ...], deps, depsU, n2_thres=n2_thres) Frs.append(np.mean(Fr[xmin:xmax+1])) cs.append(np.mean(c[xmin:xmax+1])) u_avgs.append(np.mean(u_avg[xmin:xmax+1])) dates.append(time_origin", "frequency array with dimensions (time, depth, x) deps is the model depth array", "0, depth_axis+1) # Define N2 n2 = g*drho/rho # no negative because depth", "by xmin and xmax over time n2 is the buoyancy frequency array with", "= np.rollaxis(drho_r, 0, depth_axis+1) rho = np.rollaxis(rho_r, 0, depth_axis+1) # Define N2 n2", "rho = ( 999.842594 + 6.793952e-2 * t - 9.095290e-3 * t*t +", "Fr, c, u_avg = calculate_froude_number(n2[t, ...], rho[t, ...], u[t, ...], deps, depsU, n2_thres=n2_thres)", "depth found, set it to 0 return dinds def average_mixed_layer_depth(mixed_depths, xmin, xmax): \"\"\"Averages", "t*t*t*t + 6.536332e-9 * t*t*t*t*t + 8.24493e-1 * s - 4.0899e-3 * t*s", "inds[0]) if inds: dinds.append(min(inds)) else: dinds.append(0) # if no mixed layer depth found,", "(time, depth, x) deps is the model depth array times is the model", "list of indices of mixed layer depth cell for each x-position \"\"\" if", "of mixed layer depths returns the mean mixed layer depth in the defined", "the mean mixed layer depth in a region defined by xmin and xmax", "axis # assume e3 already has depth axis in first axis drho_r =", "\"\"\"Calculates the Froude number n2, rho, u are buoyancy frequency, density and current", "rho_r[k, ...]) # Unroll drho drho = np.rollaxis(drho_r, 0, depth_axis+1) rho = np.rollaxis(rho_r,", "deps[d+1:], depth_axis=0) # calculate mixed layer depth h_1 = deps[dinds] # calcuate wave", "np.arange(n2.shape[0]): Fr, c, u_avg = calculate_froude_number(n2[t, ...], rho[t, ...], u[t, ...], deps, depsU,", "(alpha dk[T] + beta dk[S] ) / e3w temp and sal are the", "(grid spacing). Use e3w for constistency with NEMO. depth_axis defines the axis which", "n2_thres=5e-6): \"\"\"Calculates the mean mixed layer depth in a region defined by xmin", "sqrt(g*(rho2-rho1)/rho2*h1) where g is acceleration due to gravity, rho2 is denisty of lower", "for t in np.arange(n2.shape[0]): dinds = find_mixed_depth_indices(n2[t, ...], n2_thres=n2_thres) mld = average_mixed_layer_depth(deps[dinds], xmin,", "return mean_md def mld_time_series(n2, deps, times, time_origin, xmin=300, xmax=700, n2_thres=5e-6): \"\"\"Calculates the mean", "= calculate_density(temp, sal) # Density gradient drho = np.zeros(rho.shape) # roll depth axis", "is a list of indices that define the mixed layer depth. rho must", "deps, depth_axis=0) return u_avg def calculate_froude_number(n2, rho, u, deps, depsU, n2_thres=5e-6): \"\"\"Calculates the", "= calculate_froude_number(n2[t, ...], rho[t, ...], u[t, ...], deps, depsU, n2_thres=n2_thres) Frs.append(np.mean(Fr[xmin:xmax+1])) cs.append(np.mean(c[xmin:xmax+1])) u_avgs.append(np.mean(u_avg[xmin:xmax+1]))", "Fr, c, u_avg - the Froude number, wave speed, and depth averaged velocity", "'None' then the index of the maximum n2 is returned. n2 is the", "else: dinds.append(0) # if no mixed layer depth found, set it to 0", "the buoyancy frequency array with dimensions (time, depth, x) deps is the model", "[] for t in np.arange(n2.shape[0]): dinds = find_mixed_depth_indices(n2[t, ...], n2_thres=n2_thres) mld = average_mixed_layer_depth(deps[dinds],", "depths over indices xmin and xmax mixed_depths is a 1d array of mixed", "rho1 is density of upper layer and h1 is thickness of upper layer.", "rho and drho to first axis # assume e3 already has depth axis", "ii] >= n2_thres) # exlclude first vertical index less <=1 because the #", "9.095290e-3 * t*t + 1.001685e-4 * t*t*t - 1.120083e-6 * t*t*t*t + 6.536332e-9", "system # <NAME>, 2015 import numpy as np import datetime from salishsea_tools.nowcast import", "8.2467e-7 * t*t*t*s + 5.3875e-9 * t*t*t*t*s - 5.72466e-3 * s**1.5 + 1.0227e-4", "first axis # assume e3 already has depth axis in first axis drho_r", "given temperature and salinity profiles. N2 is set to g*drho/dz/rho. Note that NEMO", "and current arrays (shape time, depth, x) deps is the model depth array", "h_1 = deps[dinds] # calcuate wave speed c = np.sqrt(g*(rho_2-rho_1)/rho_2*h_1) return c def", "+ 5.3875e-9 * t*t*t*t*s - 5.72466e-3 * s**1.5 + 1.0227e-4 * t*s**1.5 -", "<NAME>, 2015 import numpy as np import datetime from salishsea_tools.nowcast import analyze def", "for n2_thres is 5e-6. If n2_thres = 'None' then the index of the", "the Froude number time series n2, rho, u are buoyancy frequency, density and", "array of depths returns u_avg, the depths averaged current (shape x) \"\"\" u_avg", "masked array of buoyancy frequencies with dimensions (depth, x) returns a list of", "dinds.append(0) # if no mixed layer depth found, set to 0 else: dinds.append(0)", "8.24493e-1 * s - 4.0899e-3 * t*s + 7.6438e-5 * t*t*s - 8.2467e-7", "n2_thres=n2_thres) # calculate internal wave speed c = calculate_internal_wave_speed(rho, deps, dinds) # calculate", "the density as an array (rho) \"\"\" rho = ( 999.842594 + 6.793952e-2", "masked array deps is the array of depths returns u_avg, the depths averaged", "The mixed layer depth is chosen based on the lowest near-surface vertical grid", "\"\"\"Averages the mixed layer depths over indices xmin and xmax mixed_depths is a", "dates def calculate_buoyancy_frequency(temp, sal, e3, depth_axis=1): \"\"\" Calculate the squared buoyancy frequency (n2)", "numpy as np import datetime from salishsea_tools.nowcast import analyze def find_mixed_depth_indices(n2, n2_thres=5e-6): \"\"\"Finds", "array depsU is the model deps array at U points times is the", "a datetime xmin,xmax define the averaging area returns: Frs, cs, u_avgs, dates the", "(t) and salinity in psu (s). returns the density as an array (rho)", "= [] for t in np.arange(n2.shape[0]): dinds = find_mixed_depth_indices(n2[t, ...], n2_thres=n2_thres) mld =", "the mode's time_origin as a datetime xmin,xmax define the averaging area returns: Frs,", "drho drho = np.rollaxis(drho_r, 0, depth_axis+1) rho = np.rollaxis(rho_r, 0, depth_axis+1) # Define", "returns a list of indices of mixed layer depth cell for each x-position", "in np.arange(n2.shape[0]): dinds = find_mixed_depth_indices(n2[t, ...], n2_thres=n2_thres) mld = average_mixed_layer_depth(deps[dinds], xmin, xmax,) mlds.append(mld)", "deps is the model depth array times is the model time_counter array time_origin", "resaonable value for n2_thres is 5e-6. If n2_thres = 'None' then the index", "[] cs = [] u_avgs = [] dates = [] for t in", "xmax,) mlds.append(mld) dates.append(time_origin + datetime.timedelta(seconds=times[t])) return mlds, dates def calculate_density(t, s): \"\"\"Caluclates the", "is the model deps array at U points times is the model time_counter", "salinity in psu (s). returns the density as an array (rho) \"\"\" rho", "x) deps is the depth array depsU is the depth array at U", "depth_axis+1) rho = np.rollaxis(rho_r, 0, depth_axis+1) # Define N2 n2 = g*drho/rho #", "no mixed layer depth found, set it to 0 return dinds def average_mixed_layer_depth(mixed_depths,", "be a masked array deps is the array of depths returns u_avg, the", "* t*s + 7.6438e-5 * t*t*s - 8.2467e-7 * t*t*t*s + 5.3875e-9 *", "the depth averaged current u is the array with current speeds (shape is", "else: dinds.append(0) # if no mixed layer depth found, set to 0 else:", "in temp/sal. \"\"\" # acceleration due to gravity g = 9.80665 # First", "def calculate_internal_wave_speed(rho, deps, dinds): \"\"\"Calculates the internal wave speed c = sqrt(g*(rho2-rho1)/rho2*h1) where", "sal, e3, depth_axis=1): \"\"\" Calculate the squared buoyancy frequency (n2) given temperature and", "xmax mixed_depths is a 1d array of mixed layer depths returns the mean", "[] for t in np.arange(n2.shape[0]): Fr, c, u_avg = calculate_froude_number(n2[t, ...], rho[t, ...],", "depth axis in rho and drho to first axis # assume e3 already", "is the array of depths and dinds is a list of indices that", "an array of internal wave speeds at each x-index in rho \"\"\" #", "wave speed c = sqrt(g*(rho2-rho1)/rho2*h1) where g is acceleration due to gravity, rho2", "frequency is hard to define there if inds[0].size: inds = filter(lambda x: x", "(shape is depth, x), deps is the array of depths and dinds is", "scale factors (grid spacing). Use e3w for constistency with NEMO. depth_axis defines the", "def mld_time_series(n2, deps, times, time_origin, xmin=300, xmax=700, n2_thres=5e-6): \"\"\"Calculates the mean mixed layer", "t in np.arange(n2.shape[0]): dinds = find_mixed_depth_indices(n2[t, ...], n2_thres=n2_thres) mld = average_mixed_layer_depth(deps[dinds], xmin, xmax,)", "layer depth for each x-position. The mixed layer depth is chosen based on", "= filter(lambda x: x > 1, inds[0]) if inds: dinds.append(min(inds)) else: dinds.append(0) #", "return mlds, dates def calculate_density(t, s): \"\"\"Caluclates the density given temperature in deg", "array of internal wave speeds at each x-index in rho \"\"\" # acceleration", "x: x > 1, inds[0]) if inds: dinds.append(min(inds)) else: dinds.append(0) # if no", "density and current arrays (shape time, depth, x) deps is the model depth", "Unroll drho drho = np.rollaxis(drho_r, 0, depth_axis+1) rho = np.rollaxis(rho_r, 0, depth_axis+1) #", "...] = 1/e3[k, ...]*(rho_r[k+1, ...] - rho_r[k, ...]) # Unroll drho drho =", "value for n2_thres is 5e-6. If n2_thres = 'None' then the index of", "return dinds def average_mixed_layer_depth(mixed_depths, xmin, xmax): \"\"\"Averages the mixed layer depths over indices", "model's time_origin as a datetime returns a list of mixed layer depths mlds", "= np.rollaxis(rho_r, 0, depth_axis+1) # Define N2 n2 = g*drho/rho # no negative", "in enumerate(dinds): rho_1[ind] = analyze.depth_average(rho[0:d+1, ind], deps[0:d+1], depth_axis=0) rho_2[ind] = analyze.depth_average(rho[d+1:, ind], deps[d+1:],", "array of buoyancy frequencies with dimensions (depth, x) returns a list of indices", ") / e3w temp and sal are the temperature and salinity arrays e3", "a list of mixed layer depths mlds and dates \"\"\" mlds = []", "that can be used to calculate the Froude # number in a simple", "and depth averaged velocity for each x-index \"\"\" # calculate mixed layers dinds", "where n2 >= n2_thres A resaonable value for n2_thres is 5e-6. If n2_thres", "= find_mixed_depth_indices(n2[t, ...], n2_thres=n2_thres) mld = average_mixed_layer_depth(deps[dinds], xmin, xmax,) mlds.append(mld) dates.append(time_origin + datetime.timedelta(seconds=times[t]))", "the mixed layer depth. rho must be a masked array returns c, an", "speeds at each x-index in rho \"\"\" # acceleration due to gravity (m/s^2)", "speed, and depth averaged current for each time associated with dates \"\"\" Frs", "layer depth in a region defined by xmin and xmax over time n2", "[] u_avgs = [] dates = [] for t in np.arange(n2.shape[0]): Fr, c,", "datetime from salishsea_tools.nowcast import analyze def find_mixed_depth_indices(n2, n2_thres=5e-6): \"\"\"Finds the index of the", "the masked array of buoyancy frequencies with dimensions (depth, x) returns a list", "acceleration due to gravity, rho2 is denisty of lower layer, rho1 is density", "density of upper layer and h1 is thickness of upper layer. rho is", "be a masked array returns c, an array of internal wave speeds at", "area returns: Frs, cs, u_avgs, dates the Froude number, internal wave speed, and", "...], deps, depsU, n2_thres=n2_thres) Frs.append(np.mean(Fr[xmin:xmax+1])) cs.append(np.mean(c[xmin:xmax+1])) u_avgs.append(np.mean(u_avg[xmin:xmax+1])) dates.append(time_origin + datetime.timedelta(seconds=times[t])) return Frs, cs,", "enumerate(dinds): rho_1[ind] = analyze.depth_average(rho[0:d+1, ind], deps[0:d+1], depth_axis=0) rho_2[ind] = analyze.depth_average(rho[d+1:, ind], deps[d+1:], depth_axis=0)", "u_avg def calculate_froude_number(n2, rho, u, deps, depsU, n2_thres=5e-6): \"\"\"Calculates the Froude number n2,", "...]*(rho_r[k+1, ...] - rho_r[k, ...]) # Unroll drho drho = np.rollaxis(drho_r, 0, depth_axis+1)", "time, depth, x) deps is the model depth array depsU is the model", "be used to calculate the Froude # number in a simple 2D system", "deps, times, time_origin, xmin=300, xmax=700, n2_thres=5e-6): \"\"\"Calculates the mean mixed layer depth in", "depths mlds and dates \"\"\" mlds = [] dates = [] for t", "region defined by xmin and xmax over time n2 is the buoyancy frequency", "returns a list of mixed layer depths mlds and dates \"\"\" mlds =", "each x-index in rho \"\"\" # acceleration due to gravity (m/s^2) g =", "[] dates = [] for t in np.arange(n2.shape[0]): dinds = find_mixed_depth_indices(n2[t, ...], n2_thres=n2_thres)", "layer depth h_1 = deps[dinds] # calcuate wave speed c = np.sqrt(g*(rho_2-rho_1)/rho_2*h_1) return", "depth_averaged_current(u, deps): \"\"\"Calculates the depth averaged current u is the array with current", "depsU) # Froude numer Fr = np.abs(u_avg)/c return Fr, c, u_avg def froude_time_series(n2,", "calculate mixed layer depth h_1 = deps[dinds] # calcuate wave speed c =", "frequency at each point in temp/sal. \"\"\" # acceleration due to gravity g", "mlds = [] dates = [] for t in np.arange(n2.shape[0]): dinds = find_mixed_depth_indices(n2[t,", "x). u must be a masked array deps is the array of depths", "* s*s ) return rho def calculate_internal_wave_speed(rho, deps, dinds): \"\"\"Calculates the internal wave", "Define N2 n2 = g*drho/rho # no negative because depth increases with increasking", "1.120083e-6 * t*t*t*t + 6.536332e-9 * t*t*t*t*t + 8.24493e-1 * s - 4.0899e-3", "* s**1.5 + 1.0227e-4 * t*s**1.5 - 1.6546e-6 * t*t*s**1.5 + 4.8314e-4 *", "temperature and salinity profiles. N2 is set to g*drho/dz/rho. Note that NEMO uses", "6.536332e-9 * t*t*t*t*t + 8.24493e-1 * s - 4.0899e-3 * t*s + 7.6438e-5", "- 9.095290e-3 * t*t + 1.001685e-4 * t*t*t - 1.120083e-6 * t*t*t*t +", "an question of state: g* (alpha dk[T] + beta dk[S] ) / e3w", "in a simple 2D system # <NAME>, 2015 import numpy as np import", "list of indices that define the mixed layer depth. rho must be a", "* t*t*t - 1.120083e-6 * t*t*t*t + 6.536332e-9 * t*t*t*t*t + 8.24493e-1 *", "current arrays (shape time, depth, x) deps is the model depth array depsU", "define the averaging area returns: Frs, cs, u_avgs, dates the Froude number, internal", "ind, d in enumerate(dinds): rho_1[ind] = analyze.depth_average(rho[0:d+1, ind], deps[0:d+1], depth_axis=0) rho_2[ind] = analyze.depth_average(rho[d+1:,", "1, inds[0]) if inds: dinds.append(min(inds)) else: dinds.append(0) # if no mixed layer depth", "xmin and xmax mixed_depths is a 1d array of mixed layer depths returns", "t*t*t*t*t + 8.24493e-1 * s - 4.0899e-3 * t*s + 7.6438e-5 * t*t*s", "mixed layer depths returns the mean mixed layer depth in the defined region", "denisty of lower layer, rho1 is density of upper layer and h1 is", "2015 import numpy as np import datetime from salishsea_tools.nowcast import analyze def find_mixed_depth_indices(n2,", "calculate the Froude # number in a simple 2D system # <NAME>, 2015", "U poinnts returns: Fr, c, u_avg - the Froude number, wave speed, and", "is returned. n2 is the masked array of buoyancy frequencies with dimensions (depth,", "= [] cs = [] u_avgs = [] dates = [] for t", "dimensions (time, depth, x) deps is the model depth array times is the", "in psu (s). returns the density as an array (rho) \"\"\" rho =", "6.793952e-2 * t - 9.095290e-3 * t*t + 1.001685e-4 * t*t*t - 1.120083e-6", "find_mixed_depth_indices(n2, n2_thres=n2_thres) # calculate internal wave speed c = calculate_internal_wave_speed(rho, deps, dinds) #", "a datetime returns a list of mixed layer depths mlds and dates \"\"\"", "Fr, c, u_avg def froude_time_series(n2, rho, u, deps, depsU, times, time_origin, xmin=300, xmax=700,", "a list of indices that define the mixed layer depth. rho must be", "deps, dinds): \"\"\"Calculates the internal wave speed c = sqrt(g*(rho2-rho1)/rho2*h1) where g is", "arrays (shape time, depth, x) deps is the model depth array depsU is", "is acceleration due to gravity, rho2 is denisty of lower layer, rho1 is", "* t*t*s**1.5 + 4.8314e-4 * s*s ) return rho def calculate_internal_wave_speed(rho, deps, dinds):", "dates.append(time_origin + datetime.timedelta(seconds=times[t])) return Frs, cs, u_avgs, dates def calculate_buoyancy_frequency(temp, sal, e3, depth_axis=1):", "depth cell for each x-position \"\"\" if n2_thres == 'None': dinds = np.argmax(n2,", "def find_mixed_depth_indices(n2, n2_thres=5e-6): \"\"\"Finds the index of the mixed layer depth for each", "a list of indices of mixed layer depth cell for each x-position \"\"\"", "arrays returns n2, an array of square buoyancy frequency at each point in", "returned. n2 is the masked array of buoyancy frequencies with dimensions (depth, x)", "frequency, density and current arrays (shape depth, x) deps is the depth array", "calculate average density in upper and lower layers rho_1 = np.zeros((rho.shape[-1])) rho_2 =", "is the array with current speeds (shape is depth, x). u must be", "\"\"\" Frs = [] cs = [] u_avgs = [] dates = []", "due to gravity g = 9.80665 # First calculate density. rho = calculate_density(temp,", "mixed layer depth in a region defined by xmin and xmax over time", "n2_thres A resaonable value for n2_thres is 5e-6. If n2_thres = 'None' then", "ind], deps[d+1:], depth_axis=0) # calculate mixed layer depth h_1 = deps[dinds] # calcuate", "array deps is the array of depths returns u_avg, the depths averaged current", "define there if inds[0].size: inds = filter(lambda x: x > 1, inds[0]) if", "is 5e-6. If n2_thres = 'None' then the index of the maximum n2", "to 0 else: dinds.append(0) # if no mixed layer depth found, set it", "mlds.append(mld) dates.append(time_origin + datetime.timedelta(seconds=times[t])) return mlds, dates def calculate_density(t, s): \"\"\"Caluclates the density", "from salishsea_tools.nowcast import analyze def find_mixed_depth_indices(n2, n2_thres=5e-6): \"\"\"Finds the index of the mixed", "x-index in rho \"\"\" # acceleration due to gravity (m/s^2) g = 9.81", "xmin and xmax over time n2 is the buoyancy frequency array with dimensions", "= depth_averaged_current(u, depsU) # Froude numer Fr = np.abs(u_avg)/c return Fr, c, u_avg", "deps, depsU, times, time_origin, xmin=300, xmax=700, n2_thres=5e-6): \"\"\"Calculates the Froude number time series", "rho[t, ...], u[t, ...], deps, depsU, n2_thres=n2_thres) Frs.append(np.mean(Fr[xmin:xmax+1])) cs.append(np.mean(c[xmin:xmax+1])) u_avgs.append(np.mean(u_avg[xmin:xmax+1])) dates.append(time_origin + datetime.timedelta(seconds=times[t]))", "and salinity profiles. N2 is set to g*drho/dz/rho. Note that NEMO uses a", "of square buoyancy frequency at each point in temp/sal. \"\"\" # acceleration due", "to gravity g = 9.80665 # First calculate density. rho = calculate_density(temp, sal)", "t*t*t - 1.120083e-6 * t*t*t*t + 6.536332e-9 * t*t*t*t*t + 8.24493e-1 * s", "is denisty of lower layer, rho1 is density of upper layer and h1", "is the model density (shape is depth, x), deps is the array of", "is the model's time_origin as a datetime returns a list of mixed layer", "= ( 999.842594 + 6.793952e-2 * t - 9.095290e-3 * t*t + 1.001685e-4", "depths returns u_avg, the depths averaged current (shape x) \"\"\" u_avg = analyze.depth_average(u,", "def average_mixed_layer_depth(mixed_depths, xmin, xmax): \"\"\"Averages the mixed layer depths over indices xmin and", "masked array returns c, an array of internal wave speeds at each x-index", "factors (grid spacing). Use e3w for constistency with NEMO. depth_axis defines the axis", "of depths returns u_avg, the depths averaged current (shape x) \"\"\" u_avg =", "is the depth array depsU is the depth array at U poinnts returns:", "currents u_avg = depth_averaged_current(u, depsU) # Froude numer Fr = np.abs(u_avg)/c return Fr,", "np.rollaxis(rho_r, 0, depth_axis+1) # Define N2 n2 = g*drho/rho # no negative because", "averaged current u is the array with current speeds (shape is depth, x).", "np.arange(n2.shape[0]): dinds = find_mixed_depth_indices(n2[t, ...], n2_thres=n2_thres) mld = average_mixed_layer_depth(deps[dinds], xmin, xmax,) mlds.append(mld) dates.append(time_origin", "salinity profiles. N2 is set to g*drho/dz/rho. Note that NEMO uses a defini", "vertical grid cell where n2 >= n2_thres A resaonable value for n2_thres is", "calculate internal wave speed c = calculate_internal_wave_speed(rho, deps, dinds) # calculate depth averaged", "( 999.842594 + 6.793952e-2 * t - 9.095290e-3 * t*t + 1.001685e-4 *", "n2_thres) # exlclude first vertical index less <=1 because the # buoyancy frequency", "mixed layer depth in the defined region \"\"\" mean_md = np.mean(mixed_depths[xmin:xmax+1]) return mean_md", "point in temp/sal. \"\"\" # acceleration due to gravity g = 9.80665 #", "of the vertical scale factors (grid spacing). Use e3w for constistency with NEMO.", "which corresponds to depth in the temp/sal arrays returns n2, an array of", "\"\"\" # acceleration due to gravity g = 9.80665 # First calculate density.", "depth_axis) for k in np.arange(1, drho.shape[depth_axis]-1): drho_r[k, ...] = 1/e3[k, ...]*(rho_r[k+1, ...] -", "is the depth array at U poinnts returns: Fr, c, u_avg - the", "the Froude number, wave speed, and depth averaged velocity for each x-index \"\"\"", "- 4.0899e-3 * t*s + 7.6438e-5 * t*t*s - 8.2467e-7 * t*t*t*s +", "n2_thres=n2_thres) mld = average_mixed_layer_depth(deps[dinds], xmin, xmax,) mlds.append(mld) dates.append(time_origin + datetime.timedelta(seconds=times[t])) return mlds, dates", "# roll depth axis in rho and drho to first axis # assume", "# Define N2 n2 = g*drho/rho # no negative because depth increases with", "= [] dates = [] for t in np.arange(n2.shape[0]): dinds = find_mixed_depth_indices(n2[t, ...],", "g is acceleration due to gravity, rho2 is denisty of lower layer, rho1", "density. rho = calculate_density(temp, sal) # Density gradient drho = np.zeros(rho.shape) # roll", "u_avgs.append(np.mean(u_avg[xmin:xmax+1])) dates.append(time_origin + datetime.timedelta(seconds=times[t])) return Frs, cs, u_avgs, dates def calculate_buoyancy_frequency(temp, sal, e3,", "the squared buoyancy frequency (n2) given temperature and salinity profiles. N2 is set", "the array of depths and dinds is a list of indices that define", "c, u_avg = calculate_froude_number(n2[t, ...], rho[t, ...], u[t, ...], deps, depsU, n2_thres=n2_thres) Frs.append(np.mean(Fr[xmin:xmax+1]))", "np.zeros((rho.shape[-1])) rho_2 = np.zeros((rho.shape[-1])) for ind, d in enumerate(dinds): rho_1[ind] = analyze.depth_average(rho[0:d+1, ind],", "datetime xmin,xmax define the averaging area returns: Frs, cs, u_avgs, dates the Froude", "the mean mixed layer depth in the defined region \"\"\" mean_md = np.mean(mixed_depths[xmin:xmax+1])", "+ 6.793952e-2 * t - 9.095290e-3 * t*t + 1.001685e-4 * t*t*t -", "mean_md def mld_time_series(n2, deps, times, time_origin, xmin=300, xmax=700, n2_thres=5e-6): \"\"\"Calculates the mean mixed", "the Froude number n2, rho, u are buoyancy frequency, density and current arrays", "xmax=700, n2_thres=5e-6): \"\"\"Calculates the Froude number time series n2, rho, u are buoyancy", "# First calculate density. rho = calculate_density(temp, sal) # Density gradient drho =", "module with functions that can be used to calculate the Froude # number", "layer depths over indices xmin and xmax mixed_depths is a 1d array of", "rho, u are buoyancy frequency, density and current arrays (shape time, depth, x)", "xmax=700, n2_thres=5e-6): \"\"\"Calculates the mean mixed layer depth in a region defined by", "# acceleration due to gravity g = 9.80665 # First calculate density. rho", "e3w temp and sal are the temperature and salinity arrays e3 is an", "= np.zeros(rho.shape) # roll depth axis in rho and drho to first axis", "internal wave speed c = sqrt(g*(rho2-rho1)/rho2*h1) where g is acceleration due to gravity,", "returns the mean mixed layer depth in the defined region \"\"\" mean_md =", "array depsU is the depth array at U poinnts returns: Fr, c, u_avg", "a masked array returns c, an array of internal wave speeds at each", "NEMO. depth_axis defines the axis which corresponds to depth in the temp/sal arrays", "in the defined region \"\"\" mean_md = np.mean(mixed_depths[xmin:xmax+1]) return mean_md def mld_time_series(n2, deps,", "if inds[0].size: inds = filter(lambda x: x > 1, inds[0]) if inds: dinds.append(min(inds))", "t - 9.095290e-3 * t*t + 1.001685e-4 * t*t*t - 1.120083e-6 * t*t*t*t", "...], u[t, ...], deps, depsU, n2_thres=n2_thres) Frs.append(np.mean(Fr[xmin:xmax+1])) cs.append(np.mean(c[xmin:xmax+1])) u_avgs.append(np.mean(u_avg[xmin:xmax+1])) dates.append(time_origin + datetime.timedelta(seconds=times[t])) return", "x > 1, inds[0]) if inds: dinds.append(min(inds)) else: dinds.append(0) # if no mixed", "is the model depth array depsU is the model deps array at U", "on the lowest near-surface vertical grid cell where n2 >= n2_thres A resaonable", "np.where(n2[:, ii] >= n2_thres) # exlclude first vertical index less <=1 because the", "upper layer. rho is the model density (shape is depth, x), deps is", "buoyancy frequency array with dimensions (time, depth, x) deps is the model depth", "number, internal wave speed, and depth averaged current for each time associated with", "array with dimensions (time, depth, x) deps is the model depth array times", "t in np.arange(n2.shape[0]): Fr, c, u_avg = calculate_froude_number(n2[t, ...], rho[t, ...], u[t, ...],", "# Density gradient drho = np.zeros(rho.shape) # roll depth axis in rho and", "cs, u_avgs, dates def calculate_buoyancy_frequency(temp, sal, e3, depth_axis=1): \"\"\" Calculate the squared buoyancy", "to calculate the Froude # number in a simple 2D system # <NAME>,", "to define there if inds[0].size: inds = filter(lambda x: x > 1, inds[0])", "times is the model time_counter array time_origin is the model's time_origin as a", "is hard to define there if inds[0].size: inds = filter(lambda x: x >", "time_origin as a datetime returns a list of mixed layer depths mlds and", "model depth array times is the model time_counter array time_origin is the model's", "for each time associated with dates \"\"\" Frs = [] cs = []", "dinds def average_mixed_layer_depth(mixed_depths, xmin, xmax): \"\"\"Averages the mixed layer depths over indices xmin", "np.zeros((rho.shape[-1])) for ind, d in enumerate(dinds): rho_1[ind] = analyze.depth_average(rho[0:d+1, ind], deps[0:d+1], depth_axis=0) rho_2[ind]", "it to 0 return dinds def average_mixed_layer_depth(mixed_depths, xmin, xmax): \"\"\"Averages the mixed layer", "depths averaged current (shape x) \"\"\" u_avg = analyze.depth_average(u, deps, depth_axis=0) return u_avg", "current arrays (shape depth, x) deps is the depth array depsU is the", "acceleration due to gravity (m/s^2) g = 9.81 # calculate average density in", "depth. rho must be a masked array returns c, an array of internal", "- the Froude number, wave speed, and depth averaged velocity for each x-index", "mixed layer depth for each x-position. The mixed layer depth is chosen based", "speed c = sqrt(g*(rho2-rho1)/rho2*h1) where g is acceleration due to gravity, rho2 is", "for ii in np.arange(n2.shape[-1]): inds = np.where(n2[:, ii] >= n2_thres) # exlclude first", "the array of depths returns u_avg, the depths averaged current (shape x) \"\"\"", "as a datetime xmin,xmax define the averaging area returns: Frs, cs, u_avgs, dates", "axis in first axis drho_r = np.rollaxis(drho, depth_axis) rho_r = np.rollaxis(rho, depth_axis) for", "...]) # Unroll drho drho = np.rollaxis(drho_r, 0, depth_axis+1) rho = np.rollaxis(rho_r, 0,", "first vertical index less <=1 because the # buoyancy frequency is hard to", "depth axis in first axis drho_r = np.rollaxis(drho, depth_axis) rho_r = np.rollaxis(rho, depth_axis)", "of the maximum n2 is returned. n2 is the masked array of buoyancy", "xmin, xmax,) mlds.append(mld) dates.append(time_origin + datetime.timedelta(seconds=times[t])) return mlds, dates def calculate_density(t, s): \"\"\"Caluclates", "(shape time, depth, x) deps is the model depth array depsU is the", "n2_thres=5e-6): \"\"\"Calculates the Froude number n2, rho, u are buoyancy frequency, density and", "mixed layer depth cell for each x-position \"\"\" if n2_thres == 'None': dinds", "np.rollaxis(drho, depth_axis) rho_r = np.rollaxis(rho, depth_axis) for k in np.arange(1, drho.shape[depth_axis]-1): drho_r[k, ...]", "the mixed layer depth for each x-position. The mixed layer depth is chosen", "acceleration due to gravity g = 9.80665 # First calculate density. rho =", "array at U points times is the model time_counter array time_origin is the", "tion based on an question of state: g* (alpha dk[T] + beta dk[S]", "1.0227e-4 * t*s**1.5 - 1.6546e-6 * t*t*s**1.5 + 4.8314e-4 * s*s ) return", "rho is the model density (shape is depth, x), deps is the array", "x) returns a list of indices of mixed layer depth cell for each", "must be a masked array deps is the array of depths returns u_avg,", "= np.rollaxis(rho, depth_axis) for k in np.arange(1, drho.shape[depth_axis]-1): drho_r[k, ...] = 1/e3[k, ...]*(rho_r[k+1,", "deps[dinds] # calcuate wave speed c = np.sqrt(g*(rho_2-rho_1)/rho_2*h_1) return c def depth_averaged_current(u, deps):", "sal) # Density gradient drho = np.zeros(rho.shape) # roll depth axis in rho", "layer depth is chosen based on the lowest near-surface vertical grid cell where", "axis in rho and drho to first axis # assume e3 already has", "a simple 2D system # <NAME>, 2015 import numpy as np import datetime", "with functions that can be used to calculate the Froude # number in", "averaged current (shape x) \"\"\" u_avg = analyze.depth_average(u, deps, depth_axis=0) return u_avg def", "a module with functions that can be used to calculate the Froude #", "list of mixed layer depths mlds and dates \"\"\" mlds = [] dates", "x) deps is the model depth array times is the model time_counter array", "u_avg, the depths averaged current (shape x) \"\"\" u_avg = analyze.depth_average(u, deps, depth_axis=0)", "- 5.72466e-3 * s**1.5 + 1.0227e-4 * t*s**1.5 - 1.6546e-6 * t*t*s**1.5 +", "import datetime from salishsea_tools.nowcast import analyze def find_mixed_depth_indices(n2, n2_thres=5e-6): \"\"\"Finds the index of", "ii in np.arange(n2.shape[-1]): inds = np.where(n2[:, ii] >= n2_thres) # exlclude first vertical", "depth array depsU is the depth array at U poinnts returns: Fr, c,", "the temperature and salinity arrays e3 is an array of the vertical scale", "indices xmin and xmax mixed_depths is a 1d array of mixed layer depths", "layer and h1 is thickness of upper layer. rho is the model density", "of lower layer, rho1 is density of upper layer and h1 is thickness", "array times is the model time_counter array time_origin is the model's time_origin as", "Froude number time series n2, rho, u are buoyancy frequency, density and current", "for each x-position \"\"\" if n2_thres == 'None': dinds = np.argmax(n2, axis=0) else:", "Fr = np.abs(u_avg)/c return Fr, c, u_avg def froude_time_series(n2, rho, u, deps, depsU,", "the mixed layer depths over indices xmin and xmax mixed_depths is a 1d", "on an question of state: g* (alpha dk[T] + beta dk[S] ) /", "import numpy as np import datetime from salishsea_tools.nowcast import analyze def find_mixed_depth_indices(n2, n2_thres=5e-6):", "ind], deps[0:d+1], depth_axis=0) rho_2[ind] = analyze.depth_average(rho[d+1:, ind], deps[d+1:], depth_axis=0) # calculate mixed layer", "depth, x), deps is the array of depths and dinds is a list", "9.80665 # First calculate density. rho = calculate_density(temp, sal) # Density gradient drho", "d in enumerate(dinds): rho_1[ind] = analyze.depth_average(rho[0:d+1, ind], deps[0:d+1], depth_axis=0) rho_2[ind] = analyze.depth_average(rho[d+1:, ind],", "dates.append(time_origin + datetime.timedelta(seconds=times[t])) return mlds, dates def calculate_density(t, s): \"\"\"Caluclates the density given", "# number in a simple 2D system # <NAME>, 2015 import numpy as", "that define the mixed layer depth. rho must be a masked array returns", "region \"\"\" mean_md = np.mean(mixed_depths[xmin:xmax+1]) return mean_md def mld_time_series(n2, deps, times, time_origin, xmin=300,", "\"\"\" u_avg = analyze.depth_average(u, deps, depth_axis=0) return u_avg def calculate_froude_number(n2, rho, u, deps,", "# if no mixed layer depth found, set it to 0 return dinds", "# calculate average density in upper and lower layers rho_1 = np.zeros((rho.shape[-1])) rho_2", "\"\"\" rho = ( 999.842594 + 6.793952e-2 * t - 9.095290e-3 * t*t", "array returns c, an array of internal wave speeds at each x-index in", "rho \"\"\" # acceleration due to gravity (m/s^2) g = 9.81 # calculate", "Froude number, wave speed, and depth averaged velocity for each x-index \"\"\" #", "find_mixed_depth_indices(n2, n2_thres=5e-6): \"\"\"Finds the index of the mixed layer depth for each x-position.", "depth array at U poinnts returns: Fr, c, u_avg - the Froude number,", "np.zeros(rho.shape) # roll depth axis in rho and drho to first axis #", "= np.zeros((rho.shape[-1])) for ind, d in enumerate(dinds): rho_1[ind] = analyze.depth_average(rho[0:d+1, ind], deps[0:d+1], depth_axis=0)", "s - 4.0899e-3 * t*s + 7.6438e-5 * t*t*s - 8.2467e-7 * t*t*t*s", "gradient drho = np.zeros(rho.shape) # roll depth axis in rho and drho to", "the model deps array at U points times is the model time_counter array", "rho def calculate_internal_wave_speed(rho, deps, dinds): \"\"\"Calculates the internal wave speed c = sqrt(g*(rho2-rho1)/rho2*h1)", "0 else: dinds.append(0) # if no mixed layer depth found, set it to", "rho2 is denisty of lower layer, rho1 is density of upper layer and", "layer depths mlds and dates \"\"\" mlds = [] dates = [] for", "and h1 is thickness of upper layer. rho is the model density (shape", "# Unroll drho drho = np.rollaxis(drho_r, 0, depth_axis+1) rho = np.rollaxis(rho_r, 0, depth_axis+1)", "each x-position. The mixed layer depth is chosen based on the lowest near-surface", "in a region defined by xmin and xmax over time n2 is the", "mean mixed layer depth in the defined region \"\"\" mean_md = np.mean(mixed_depths[xmin:xmax+1]) return", "find_mixed_depth_indices(n2[t, ...], n2_thres=n2_thres) mld = average_mixed_layer_depth(deps[dinds], xmin, xmax,) mlds.append(mld) dates.append(time_origin + datetime.timedelta(seconds=times[t])) return", "dk[S] ) / e3w temp and sal are the temperature and salinity arrays", "first axis drho_r = np.rollaxis(drho, depth_axis) rho_r = np.rollaxis(rho, depth_axis) for k in", "n2_thres=5e-6): \"\"\"Calculates the Froude number time series n2, rho, u are buoyancy frequency,", "array time_origin is the model's time_origin as a datetime returns a list of", "inds: dinds.append(min(inds)) else: dinds.append(0) # if no mixed layer depth found, set to", "and current arrays (shape depth, x) deps is the depth array depsU is", "at U points times is the model time_counter array time_origin is the mode's", "cell for each x-position \"\"\" if n2_thres == 'None': dinds = np.argmax(n2, axis=0)", "= np.where(n2[:, ii] >= n2_thres) # exlclude first vertical index less <=1 because", "upper layer and h1 is thickness of upper layer. rho is the model", "salinity arrays e3 is an array of the vertical scale factors (grid spacing).", "analyze.depth_average(rho[d+1:, ind], deps[d+1:], depth_axis=0) # calculate mixed layer depth h_1 = deps[dinds] #", "analyze.depth_average(u, deps, depth_axis=0) return u_avg def calculate_froude_number(n2, rho, u, deps, depsU, n2_thres=5e-6): \"\"\"Calculates", "of mixed layer depth cell for each x-position \"\"\" if n2_thres == 'None':", "n2 is the buoyancy frequency array with dimensions (time, depth, x) deps is", "(shape is depth, x). u must be a masked array deps is the", "for constistency with NEMO. depth_axis defines the axis which corresponds to depth in", "calculate mixed layers dinds = find_mixed_depth_indices(n2, n2_thres=n2_thres) # calculate internal wave speed c", "then the index of the maximum n2 is returned. n2 is the masked", "Froude # number in a simple 2D system # <NAME>, 2015 import numpy", "the temp/sal arrays returns n2, an array of square buoyancy frequency at each", "and drho to first axis # assume e3 already has depth axis in", "u_avg = calculate_froude_number(n2[t, ...], rho[t, ...], u[t, ...], deps, depsU, n2_thres=n2_thres) Frs.append(np.mean(Fr[xmin:xmax+1])) cs.append(np.mean(c[xmin:xmax+1]))", "n2_thres=n2_thres) Frs.append(np.mean(Fr[xmin:xmax+1])) cs.append(np.mean(c[xmin:xmax+1])) u_avgs.append(np.mean(u_avg[xmin:xmax+1])) dates.append(time_origin + datetime.timedelta(seconds=times[t])) return Frs, cs, u_avgs, dates def", "returns the density as an array (rho) \"\"\" rho = ( 999.842594 +", "there if inds[0].size: inds = filter(lambda x: x > 1, inds[0]) if inds:", "is the model time_counter array time_origin is the model's time_origin as a datetime", "each time associated with dates \"\"\" Frs = [] cs = [] u_avgs", "model time_counter array time_origin is the model's time_origin as a datetime returns a", "u_avgs = [] dates = [] for t in np.arange(n2.shape[0]): Fr, c, u_avg", "cs = [] u_avgs = [] dates = [] for t in np.arange(n2.shape[0]):", "u, deps, depsU, n2_thres=5e-6): \"\"\"Calculates the Froude number n2, rho, u are buoyancy", "the depth array at U poinnts returns: Fr, c, u_avg - the Froude", "wave speed c = calculate_internal_wave_speed(rho, deps, dinds) # calculate depth averaged currents u_avg", "are buoyancy frequency, density and current arrays (shape depth, x) deps is the", "is the model time_counter array time_origin is the mode's time_origin as a datetime", "depth array times is the model time_counter array time_origin is the model's time_origin", "* t*t*t*t*s - 5.72466e-3 * s**1.5 + 1.0227e-4 * t*s**1.5 - 1.6546e-6 *", "Frs = [] cs = [] u_avgs = [] dates = [] for", "np.sqrt(g*(rho_2-rho_1)/rho_2*h_1) return c def depth_averaged_current(u, deps): \"\"\"Calculates the depth averaged current u is", "+ 1.001685e-4 * t*t*t - 1.120083e-6 * t*t*t*t + 6.536332e-9 * t*t*t*t*t +", "a defini tion based on an question of state: g* (alpha dk[T] +", "gravity (m/s^2) g = 9.81 # calculate average density in upper and lower", "return c def depth_averaged_current(u, deps): \"\"\"Calculates the depth averaged current u is the", "[] dates = [] for t in np.arange(n2.shape[0]): Fr, c, u_avg = calculate_froude_number(n2[t,", "g = 9.80665 # First calculate density. rho = calculate_density(temp, sal) # Density", "are buoyancy frequency, density and current arrays (shape time, depth, x) deps is", "depth averaged current u is the array with current speeds (shape is depth,", "deps, depsU, n2_thres=5e-6): \"\"\"Calculates the Froude number n2, rho, u are buoyancy frequency,", "depth in the defined region \"\"\" mean_md = np.mean(mixed_depths[xmin:xmax+1]) return mean_md def mld_time_series(n2,", "define the mixed layer depth. rho must be a masked array returns c,", "times, time_origin, xmin=300, xmax=700, n2_thres=5e-6): \"\"\"Calculates the mean mixed layer depth in a", "array of mixed layer depths returns the mean mixed layer depth in the", "the model depth array times is the model time_counter array time_origin is the", "calculate_internal_wave_speed(rho, deps, dinds): \"\"\"Calculates the internal wave speed c = sqrt(g*(rho2-rho1)/rho2*h1) where g", "deps, dinds) # calculate depth averaged currents u_avg = depth_averaged_current(u, depsU) # Froude", "calculate_buoyancy_frequency(temp, sal, e3, depth_axis=1): \"\"\" Calculate the squared buoyancy frequency (n2) given temperature", "= np.argmax(n2, axis=0) else: dinds = [] for ii in np.arange(n2.shape[-1]): inds =", "the maximum n2 is returned. n2 is the masked array of buoyancy frequencies", "dates the Froude number, internal wave speed, and depth averaged current for each", "depth in the temp/sal arrays returns n2, an array of square buoyancy frequency", "calcuate wave speed c = np.sqrt(g*(rho_2-rho_1)/rho_2*h_1) return c def depth_averaged_current(u, deps): \"\"\"Calculates the", "average density in upper and lower layers rho_1 = np.zeros((rho.shape[-1])) rho_2 = np.zeros((rho.shape[-1]))", "drho = np.zeros(rho.shape) # roll depth axis in rho and drho to first", "buoyancy frequency at each point in temp/sal. \"\"\" # acceleration due to gravity", "cell where n2 >= n2_thres A resaonable value for n2_thres is 5e-6. If", "and lower layers rho_1 = np.zeros((rho.shape[-1])) rho_2 = np.zeros((rho.shape[-1])) for ind, d in", "is the model depth array times is the model time_counter array time_origin is", "index of the maximum n2 is returned. n2 is the masked array of", "returns c, an array of internal wave speeds at each x-index in rho", "is the mode's time_origin as a datetime xmin,xmax define the averaging area returns:", "dinds = find_mixed_depth_indices(n2[t, ...], n2_thres=n2_thres) mld = average_mixed_layer_depth(deps[dinds], xmin, xmax,) mlds.append(mld) dates.append(time_origin +", "A resaonable value for n2_thres is 5e-6. If n2_thres = 'None' then the", "= 9.80665 # First calculate density. rho = calculate_density(temp, sal) # Density gradient", "speeds (shape is depth, x). u must be a masked array deps is", "depth_axis+1) # Define N2 n2 = g*drho/rho # no negative because depth increases", "1.001685e-4 * t*t*t - 1.120083e-6 * t*t*t*t + 6.536332e-9 * t*t*t*t*t + 8.24493e-1", "C (t) and salinity in psu (s). returns the density as an array", "Froude number, internal wave speed, and depth averaged current for each time associated", "\"\"\" # acceleration due to gravity (m/s^2) g = 9.81 # calculate average", "less <=1 because the # buoyancy frequency is hard to define there if", "layer depth found, set to 0 else: dinds.append(0) # if no mixed layer", "layer depth found, set it to 0 return dinds def average_mixed_layer_depth(mixed_depths, xmin, xmax):", "depth, x) deps is the model depth array times is the model time_counter", "as an array (rho) \"\"\" rho = ( 999.842594 + 6.793952e-2 * t", "\"\"\"Calculates the depth averaged current u is the array with current speeds (shape", "temp/sal. \"\"\" # acceleration due to gravity g = 9.80665 # First calculate", "Density gradient drho = np.zeros(rho.shape) # roll depth axis in rho and drho", "hard to define there if inds[0].size: inds = filter(lambda x: x > 1,", "rho_2[ind] = analyze.depth_average(rho[d+1:, ind], deps[d+1:], depth_axis=0) # calculate mixed layer depth h_1 =", "mixed_depths is a 1d array of mixed layer depths returns the mean mixed", "n2_thres == 'None': dinds = np.argmax(n2, axis=0) else: dinds = [] for ii", "cs, u_avgs, dates the Froude number, internal wave speed, and depth averaged current", "model time_counter array time_origin is the mode's time_origin as a datetime xmin,xmax define", "0 return dinds def average_mixed_layer_depth(mixed_depths, xmin, xmax): \"\"\"Averages the mixed layer depths over", "# This is a module with functions that can be used to calculate", "depsU, times, time_origin, xmin=300, xmax=700, n2_thres=5e-6): \"\"\"Calculates the Froude number time series n2,", "x-index \"\"\" # calculate mixed layers dinds = find_mixed_depth_indices(n2, n2_thres=n2_thres) # calculate internal", "internal wave speed, and depth averaged current for each time associated with dates", "First calculate density. rho = calculate_density(temp, sal) # Density gradient drho = np.zeros(rho.shape)", "model density (shape is depth, x), deps is the array of depths and", "has depth axis in first axis drho_r = np.rollaxis(drho, depth_axis) rho_r = np.rollaxis(rho,", "density (shape is depth, x), deps is the array of depths and dinds", "np import datetime from salishsea_tools.nowcast import analyze def find_mixed_depth_indices(n2, n2_thres=5e-6): \"\"\"Finds the index", "deps[0:d+1], depth_axis=0) rho_2[ind] = analyze.depth_average(rho[d+1:, ind], deps[d+1:], depth_axis=0) # calculate mixed layer depth", "depth, x) deps is the model depth array depsU is the model deps", "e3 already has depth axis in first axis drho_r = np.rollaxis(drho, depth_axis) rho_r", "dinds = np.argmax(n2, axis=0) else: dinds = [] for ii in np.arange(n2.shape[-1]): inds", "and sal are the temperature and salinity arrays e3 is an array of", "an array of square buoyancy frequency at each point in temp/sal. \"\"\" #", "def depth_averaged_current(u, deps): \"\"\"Calculates the depth averaged current u is the array with", "layer depth. rho must be a masked array returns c, an array of", "lower layer, rho1 is density of upper layer and h1 is thickness of", "time series n2, rho, u are buoyancy frequency, density and current arrays (shape", "np.mean(mixed_depths[xmin:xmax+1]) return mean_md def mld_time_series(n2, deps, times, time_origin, xmin=300, xmax=700, n2_thres=5e-6): \"\"\"Calculates the", "U points times is the model time_counter array time_origin is the mode's time_origin", "time_counter array time_origin is the model's time_origin as a datetime returns a list", "u_avg = depth_averaged_current(u, depsU) # Froude numer Fr = np.abs(u_avg)/c return Fr, c,", "np.rollaxis(rho, depth_axis) for k in np.arange(1, drho.shape[depth_axis]-1): drho_r[k, ...] = 1/e3[k, ...]*(rho_r[k+1, ...]", "t*t*s - 8.2467e-7 * t*t*t*s + 5.3875e-9 * t*t*t*t*s - 5.72466e-3 * s**1.5", "because the # buoyancy frequency is hard to define there if inds[0].size: inds", "x) \"\"\" u_avg = analyze.depth_average(u, deps, depth_axis=0) return u_avg def calculate_froude_number(n2, rho, u,", "mld = average_mixed_layer_depth(deps[dinds], xmin, xmax,) mlds.append(mld) dates.append(time_origin + datetime.timedelta(seconds=times[t])) return mlds, dates def", "current for each time associated with dates \"\"\" Frs = [] cs =", "/ e3w temp and sal are the temperature and salinity arrays e3 is", "froude_time_series(n2, rho, u, deps, depsU, times, time_origin, xmin=300, xmax=700, n2_thres=5e-6): \"\"\"Calculates the Froude", "analyze.depth_average(rho[0:d+1, ind], deps[0:d+1], depth_axis=0) rho_2[ind] = analyze.depth_average(rho[d+1:, ind], deps[d+1:], depth_axis=0) # calculate mixed", "gravity, rho2 is denisty of lower layer, rho1 is density of upper layer", "s): \"\"\"Caluclates the density given temperature in deg C (t) and salinity in", "depsU, n2_thres=n2_thres) Frs.append(np.mean(Fr[xmin:xmax+1])) cs.append(np.mean(c[xmin:xmax+1])) u_avgs.append(np.mean(u_avg[xmin:xmax+1])) dates.append(time_origin + datetime.timedelta(seconds=times[t])) return Frs, cs, u_avgs, dates", "# calcuate wave speed c = np.sqrt(g*(rho_2-rho_1)/rho_2*h_1) return c def depth_averaged_current(u, deps): \"\"\"Calculates", "profiles. N2 is set to g*drho/dz/rho. Note that NEMO uses a defini tion", "n2 >= n2_thres A resaonable value for n2_thres is 5e-6. If n2_thres =", "depth_axis=0) rho_2[ind] = analyze.depth_average(rho[d+1:, ind], deps[d+1:], depth_axis=0) # calculate mixed layer depth h_1", "= np.zeros((rho.shape[-1])) rho_2 = np.zeros((rho.shape[-1])) for ind, d in enumerate(dinds): rho_1[ind] = analyze.depth_average(rho[0:d+1,", "\"\"\"Calculates the Froude number time series n2, rho, u are buoyancy frequency, density", "Frs.append(np.mean(Fr[xmin:xmax+1])) cs.append(np.mean(c[xmin:xmax+1])) u_avgs.append(np.mean(u_avg[xmin:xmax+1])) dates.append(time_origin + datetime.timedelta(seconds=times[t])) return Frs, cs, u_avgs, dates def calculate_buoyancy_frequency(temp,", "of the mixed layer depth for each x-position. The mixed layer depth is", "to gravity (m/s^2) g = 9.81 # calculate average density in upper and", "xmin=300, xmax=700, n2_thres=5e-6): \"\"\"Calculates the Froude number time series n2, rho, u are", "the vertical scale factors (grid spacing). Use e3w for constistency with NEMO. depth_axis", "the index of the mixed layer depth for each x-position. The mixed layer", "# exlclude first vertical index less <=1 because the # buoyancy frequency is", "rho, u, deps, depsU, n2_thres=5e-6): \"\"\"Calculates the Froude number n2, rho, u are", "k in np.arange(1, drho.shape[depth_axis]-1): drho_r[k, ...] = 1/e3[k, ...]*(rho_r[k+1, ...] - rho_r[k, ...])", "depth_averaged_current(u, depsU) # Froude numer Fr = np.abs(u_avg)/c return Fr, c, u_avg def", "5e-6. If n2_thres = 'None' then the index of the maximum n2 is", "assume e3 already has depth axis in first axis drho_r = np.rollaxis(drho, depth_axis)", "drho.shape[depth_axis]-1): drho_r[k, ...] = 1/e3[k, ...]*(rho_r[k+1, ...] - rho_r[k, ...]) # Unroll drho", "is the array of depths returns u_avg, the depths averaged current (shape x)", "inds[0].size: inds = filter(lambda x: x > 1, inds[0]) if inds: dinds.append(min(inds)) else:", "as np import datetime from salishsea_tools.nowcast import analyze def find_mixed_depth_indices(n2, n2_thres=5e-6): \"\"\"Finds the", "n2, rho, u are buoyancy frequency, density and current arrays (shape time, depth,", "depth h_1 = deps[dinds] # calcuate wave speed c = np.sqrt(g*(rho_2-rho_1)/rho_2*h_1) return c", "number n2, rho, u are buoyancy frequency, density and current arrays (shape depth,", "lower layers rho_1 = np.zeros((rho.shape[-1])) rho_2 = np.zeros((rho.shape[-1])) for ind, d in enumerate(dinds):", "c, u_avg - the Froude number, wave speed, and depth averaged velocity for", "u_avg - the Froude number, wave speed, and depth averaged velocity for each", "and dinds is a list of indices that define the mixed layer depth.", "salishsea_tools.nowcast import analyze def find_mixed_depth_indices(n2, n2_thres=5e-6): \"\"\"Finds the index of the mixed layer", "spacing). Use e3w for constistency with NEMO. depth_axis defines the axis which corresponds", "if n2_thres == 'None': dinds = np.argmax(n2, axis=0) else: dinds = [] for", "internal wave speeds at each x-index in rho \"\"\" # acceleration due to", "dinds = [] for ii in np.arange(n2.shape[-1]): inds = np.where(n2[:, ii] >= n2_thres)", "to 0 return dinds def average_mixed_layer_depth(mixed_depths, xmin, xmax): \"\"\"Averages the mixed layer depths", "due to gravity (m/s^2) g = 9.81 # calculate average density in upper", "associated with dates \"\"\" Frs = [] cs = [] u_avgs = []", "with NEMO. depth_axis defines the axis which corresponds to depth in the temp/sal", "buoyancy frequency is hard to define there if inds[0].size: inds = filter(lambda x:", "due to gravity, rho2 is denisty of lower layer, rho1 is density of", "with current speeds (shape is depth, x). u must be a masked array", "the array with current speeds (shape is depth, x). u must be a", "depsU, n2_thres=5e-6): \"\"\"Calculates the Froude number n2, rho, u are buoyancy frequency, density", "* t*s**1.5 - 1.6546e-6 * t*t*s**1.5 + 4.8314e-4 * s*s ) return rho", "datetime returns a list of mixed layer depths mlds and dates \"\"\" mlds", "analyze def find_mixed_depth_indices(n2, n2_thres=5e-6): \"\"\"Finds the index of the mixed layer depth for", "no mixed layer depth found, set to 0 else: dinds.append(0) # if no", "5.72466e-3 * s**1.5 + 1.0227e-4 * t*s**1.5 - 1.6546e-6 * t*t*s**1.5 + 4.8314e-4", "= 1/e3[k, ...]*(rho_r[k+1, ...] - rho_r[k, ...]) # Unroll drho drho = np.rollaxis(drho_r,", "If n2_thres = 'None' then the index of the maximum n2 is returned.", "indices that define the mixed layer depth. rho must be a masked array", "thickness of upper layer. rho is the model density (shape is depth, x),", "mode's time_origin as a datetime xmin,xmax define the averaging area returns: Frs, cs,", "N2 n2 = g*drho/rho # no negative because depth increases with increasking k", "poinnts returns: Fr, c, u_avg - the Froude number, wave speed, and depth", "deps is the array of depths and dinds is a list of indices", "dinds = find_mixed_depth_indices(n2, n2_thres=n2_thres) # calculate internal wave speed c = calculate_internal_wave_speed(rho, deps,", "the defined region \"\"\" mean_md = np.mean(mixed_depths[xmin:xmax+1]) return mean_md def mld_time_series(n2, deps, times,", "999.842594 + 6.793952e-2 * t - 9.095290e-3 * t*t + 1.001685e-4 * t*t*t", "that NEMO uses a defini tion based on an question of state: g*", "in the temp/sal arrays returns n2, an array of square buoyancy frequency at", "Use e3w for constistency with NEMO. depth_axis defines the axis which corresponds to", "points times is the model time_counter array time_origin is the mode's time_origin as", "# buoyancy frequency is hard to define there if inds[0].size: inds = filter(lambda", "depth averaged velocity for each x-index \"\"\" # calculate mixed layers dinds =", "e3w for constistency with NEMO. depth_axis defines the axis which corresponds to depth", "= np.rollaxis(drho, depth_axis) rho_r = np.rollaxis(rho, depth_axis) for k in np.arange(1, drho.shape[depth_axis]-1): drho_r[k,", "deg C (t) and salinity in psu (s). returns the density as an", "the model depth array depsU is the model deps array at U points", "depth for each x-position. The mixed layer depth is chosen based on the", "the index of the maximum n2 is returned. n2 is the masked array", "set it to 0 return dinds def average_mixed_layer_depth(mixed_depths, xmin, xmax): \"\"\"Averages the mixed", "is a module with functions that can be used to calculate the Froude", "mixed layer depth found, set to 0 else: dinds.append(0) # if no mixed", "Froude numer Fr = np.abs(u_avg)/c return Fr, c, u_avg def froude_time_series(n2, rho, u,", "given temperature in deg C (t) and salinity in psu (s). returns the", "= np.abs(u_avg)/c return Fr, c, u_avg def froude_time_series(n2, rho, u, deps, depsU, times,", "and salinity in psu (s). returns the density as an array (rho) \"\"\"", "maximum n2 is returned. n2 is the masked array of buoyancy frequencies with", "def calculate_density(t, s): \"\"\"Caluclates the density given temperature in deg C (t) and", "c, u_avg def froude_time_series(n2, rho, u, deps, depsU, times, time_origin, xmin=300, xmax=700, n2_thres=5e-6):", "vertical index less <=1 because the # buoyancy frequency is hard to define", "# <NAME>, 2015 import numpy as np import datetime from salishsea_tools.nowcast import analyze", "deps is the array of depths returns u_avg, the depths averaged current (shape", "the Froude # number in a simple 2D system # <NAME>, 2015 import", "time_origin is the mode's time_origin as a datetime xmin,xmax define the averaging area", "drho_r = np.rollaxis(drho, depth_axis) rho_r = np.rollaxis(rho, depth_axis) for k in np.arange(1, drho.shape[depth_axis]-1):", "a 1d array of mixed layer depths returns the mean mixed layer depth", "gravity g = 9.80665 # First calculate density. rho = calculate_density(temp, sal) #", "temperature and salinity arrays e3 is an array of the vertical scale factors", "axis which corresponds to depth in the temp/sal arrays returns n2, an array", "u must be a masked array deps is the array of depths returns", "upper and lower layers rho_1 = np.zeros((rho.shape[-1])) rho_2 = np.zeros((rho.shape[-1])) for ind, d", "found, set it to 0 return dinds def average_mixed_layer_depth(mixed_depths, xmin, xmax): \"\"\"Averages the", "7.6438e-5 * t*t*s - 8.2467e-7 * t*t*t*s + 5.3875e-9 * t*t*t*t*s - 5.72466e-3", "each point in temp/sal. \"\"\" # acceleration due to gravity g = 9.80665", "of state: g* (alpha dk[T] + beta dk[S] ) / e3w temp and", "time n2 is the buoyancy frequency array with dimensions (time, depth, x) deps", "\"\"\" # calculate mixed layers dinds = find_mixed_depth_indices(n2, n2_thres=n2_thres) # calculate internal wave", "np.arange(n2.shape[-1]): inds = np.where(n2[:, ii] >= n2_thres) # exlclude first vertical index less", "density given temperature in deg C (t) and salinity in psu (s). returns", "np.abs(u_avg)/c return Fr, c, u_avg def froude_time_series(n2, rho, u, deps, depsU, times, time_origin,", "the density given temperature in deg C (t) and salinity in psu (s).", "layer depths returns the mean mixed layer depth in the defined region \"\"\"", "+ datetime.timedelta(seconds=times[t])) return mlds, dates def calculate_density(t, s): \"\"\"Caluclates the density given temperature", "time_counter array time_origin is the mode's time_origin as a datetime xmin,xmax define the", "= average_mixed_layer_depth(deps[dinds], xmin, xmax,) mlds.append(mld) dates.append(time_origin + datetime.timedelta(seconds=times[t])) return mlds, dates def calculate_density(t,", "depth_axis=1): \"\"\" Calculate the squared buoyancy frequency (n2) given temperature and salinity profiles.", "= np.mean(mixed_depths[xmin:xmax+1]) return mean_md def mld_time_series(n2, deps, times, time_origin, xmin=300, xmax=700, n2_thres=5e-6): \"\"\"Calculates", "calculate_density(temp, sal) # Density gradient drho = np.zeros(rho.shape) # roll depth axis in", "defini tion based on an question of state: g* (alpha dk[T] + beta", "n2 is the masked array of buoyancy frequencies with dimensions (depth, x) returns", "returns: Frs, cs, u_avgs, dates the Froude number, internal wave speed, and depth", "rho must be a masked array returns c, an array of internal wave", "+ datetime.timedelta(seconds=times[t])) return Frs, cs, u_avgs, dates def calculate_buoyancy_frequency(temp, sal, e3, depth_axis=1): \"\"\"", "series n2, rho, u are buoyancy frequency, density and current arrays (shape time,", "density and current arrays (shape depth, x) deps is the depth array depsU", ">= n2_thres) # exlclude first vertical index less <=1 because the # buoyancy", "must be a masked array returns c, an array of internal wave speeds", "return Frs, cs, u_avgs, dates def calculate_buoyancy_frequency(temp, sal, e3, depth_axis=1): \"\"\" Calculate the", "in rho \"\"\" # acceleration due to gravity (m/s^2) g = 9.81 #", "* t*t*t*t + 6.536332e-9 * t*t*t*t*t + 8.24493e-1 * s - 4.0899e-3 *", "def calculate_froude_number(n2, rho, u, deps, depsU, n2_thres=5e-6): \"\"\"Calculates the Froude number n2, rho,", "current u is the array with current speeds (shape is depth, x). u", "the depth array depsU is the depth array at U poinnts returns: Fr,", "is a 1d array of mixed layer depths returns the mean mixed layer", "where g is acceleration due to gravity, rho2 is denisty of lower layer,", "else: dinds = [] for ii in np.arange(n2.shape[-1]): inds = np.where(n2[:, ii] >=", "rho_r = np.rollaxis(rho, depth_axis) for k in np.arange(1, drho.shape[depth_axis]-1): drho_r[k, ...] = 1/e3[k,", "current speeds (shape is depth, x). u must be a masked array deps", "of buoyancy frequencies with dimensions (depth, x) returns a list of indices of", "= sqrt(g*(rho2-rho1)/rho2*h1) where g is acceleration due to gravity, rho2 is denisty of", "mixed layers dinds = find_mixed_depth_indices(n2, n2_thres=n2_thres) # calculate internal wave speed c =", "defines the axis which corresponds to depth in the temp/sal arrays returns n2,", "n2_thres=5e-6): \"\"\"Finds the index of the mixed layer depth for each x-position. The", "n2, an array of square buoyancy frequency at each point in temp/sal. \"\"\"", "(shape depth, x) deps is the depth array depsU is the depth array", "= analyze.depth_average(u, deps, depth_axis=0) return u_avg def calculate_froude_number(n2, rho, u, deps, depsU, n2_thres=5e-6):", "the model time_counter array time_origin is the model's time_origin as a datetime returns", "array of depths and dinds is a list of indices that define the", "of indices that define the mixed layer depth. rho must be a masked", "= np.sqrt(g*(rho_2-rho_1)/rho_2*h_1) return c def depth_averaged_current(u, deps): \"\"\"Calculates the depth averaged current u", "u_avg = analyze.depth_average(u, deps, depth_axis=0) return u_avg def calculate_froude_number(n2, rho, u, deps, depsU,", "rho = np.rollaxis(rho_r, 0, depth_axis+1) # Define N2 n2 = g*drho/rho # no", "# acceleration due to gravity (m/s^2) g = 9.81 # calculate average density", "= [] u_avgs = [] dates = [] for t in np.arange(n2.shape[0]): Fr,", "deps): \"\"\"Calculates the depth averaged current u is the array with current speeds", "u_avg def froude_time_series(n2, rho, u, deps, depsU, times, time_origin, xmin=300, xmax=700, n2_thres=5e-6): \"\"\"Calculates", "(rho) \"\"\" rho = ( 999.842594 + 6.793952e-2 * t - 9.095290e-3 *", "== 'None': dinds = np.argmax(n2, axis=0) else: dinds = [] for ii in", "drho to first axis # assume e3 already has depth axis in first", "u is the array with current speeds (shape is depth, x). u must", "defined by xmin and xmax over time n2 is the buoyancy frequency array", "for t in np.arange(n2.shape[0]): Fr, c, u_avg = calculate_froude_number(n2[t, ...], rho[t, ...], u[t,", "in upper and lower layers rho_1 = np.zeros((rho.shape[-1])) rho_2 = np.zeros((rho.shape[-1])) for ind,", "= analyze.depth_average(rho[0:d+1, ind], deps[0:d+1], depth_axis=0) rho_2[ind] = analyze.depth_average(rho[d+1:, ind], deps[d+1:], depth_axis=0) # calculate", "arrays e3 is an array of the vertical scale factors (grid spacing). Use", "(shape x) \"\"\" u_avg = analyze.depth_average(u, deps, depth_axis=0) return u_avg def calculate_froude_number(n2, rho,", "...], n2_thres=n2_thres) mld = average_mixed_layer_depth(deps[dinds], xmin, xmax,) mlds.append(mld) dates.append(time_origin + datetime.timedelta(seconds=times[t])) return mlds,", "each x-index \"\"\" # calculate mixed layers dinds = find_mixed_depth_indices(n2, n2_thres=n2_thres) # calculate", "c = np.sqrt(g*(rho_2-rho_1)/rho_2*h_1) return c def depth_averaged_current(u, deps): \"\"\"Calculates the depth averaged current", "dimensions (depth, x) returns a list of indices of mixed layer depth cell", "\"\"\"Caluclates the density given temperature in deg C (t) and salinity in psu", "# calculate mixed layers dinds = find_mixed_depth_indices(n2, n2_thres=n2_thres) # calculate internal wave speed", "state: g* (alpha dk[T] + beta dk[S] ) / e3w temp and sal", "return u_avg def calculate_froude_number(n2, rho, u, deps, depsU, n2_thres=5e-6): \"\"\"Calculates the Froude number", "depth_axis=0) # calculate mixed layer depth h_1 = deps[dinds] # calcuate wave speed", "depth averaged current for each time associated with dates \"\"\" Frs = []", "model depth array depsU is the model deps array at U points times", "+ 4.8314e-4 * s*s ) return rho def calculate_internal_wave_speed(rho, deps, dinds): \"\"\"Calculates the", "dates \"\"\" mlds = [] dates = [] for t in np.arange(n2.shape[0]): dinds", "is thickness of upper layer. rho is the model density (shape is depth,", "...] - rho_r[k, ...]) # Unroll drho drho = np.rollaxis(drho_r, 0, depth_axis+1) rho", "for k in np.arange(1, drho.shape[depth_axis]-1): drho_r[k, ...] = 1/e3[k, ...]*(rho_r[k+1, ...] - rho_r[k,", "with dimensions (depth, x) returns a list of indices of mixed layer depth", "vertical scale factors (grid spacing). Use e3w for constistency with NEMO. depth_axis defines", "= g*drho/rho # no negative because depth increases with increasking k return n2", "buoyancy frequencies with dimensions (depth, x) returns a list of indices of mixed", "- 8.2467e-7 * t*t*t*s + 5.3875e-9 * t*t*t*t*s - 5.72466e-3 * s**1.5 +", "number time series n2, rho, u are buoyancy frequency, density and current arrays", "# if no mixed layer depth found, set to 0 else: dinds.append(0) #", "array of square buoyancy frequency at each point in temp/sal. \"\"\" # acceleration", "in np.arange(n2.shape[-1]): inds = np.where(n2[:, ii] >= n2_thres) # exlclude first vertical index", "np.rollaxis(drho_r, 0, depth_axis+1) rho = np.rollaxis(rho_r, 0, depth_axis+1) # Define N2 n2 =", "* t*t + 1.001685e-4 * t*t*t - 1.120083e-6 * t*t*t*t + 6.536332e-9 *", "x), deps is the array of depths and dinds is a list of", "def calculate_buoyancy_frequency(temp, sal, e3, depth_axis=1): \"\"\" Calculate the squared buoyancy frequency (n2) given", "already has depth axis in first axis drho_r = np.rollaxis(drho, depth_axis) rho_r =", "rho_1[ind] = analyze.depth_average(rho[0:d+1, ind], deps[0:d+1], depth_axis=0) rho_2[ind] = analyze.depth_average(rho[d+1:, ind], deps[d+1:], depth_axis=0) #", "arrays (shape depth, x) deps is the depth array depsU is the depth", "is an array of the vertical scale factors (grid spacing). Use e3w for", "depth in a region defined by xmin and xmax over time n2 is", "density in upper and lower layers rho_1 = np.zeros((rho.shape[-1])) rho_2 = np.zeros((rho.shape[-1])) for", "at each point in temp/sal. \"\"\" # acceleration due to gravity g =", "time_origin, xmin=300, xmax=700, n2_thres=5e-6): \"\"\"Calculates the Froude number time series n2, rho, u", "defined region \"\"\" mean_md = np.mean(mixed_depths[xmin:xmax+1]) return mean_md def mld_time_series(n2, deps, times, time_origin,", "temperature in deg C (t) and salinity in psu (s). returns the density", "c = sqrt(g*(rho2-rho1)/rho2*h1) where g is acceleration due to gravity, rho2 is denisty", "to gravity, rho2 is denisty of lower layer, rho1 is density of upper", "over indices xmin and xmax mixed_depths is a 1d array of mixed layer", "= [] dates = [] for t in np.arange(n2.shape[0]): Fr, c, u_avg =", "axis drho_r = np.rollaxis(drho, depth_axis) rho_r = np.rollaxis(rho, depth_axis) for k in np.arange(1,", "1.6546e-6 * t*t*s**1.5 + 4.8314e-4 * s*s ) return rho def calculate_internal_wave_speed(rho, deps,", "speed c = np.sqrt(g*(rho_2-rho_1)/rho_2*h_1) return c def depth_averaged_current(u, deps): \"\"\"Calculates the depth averaged", "u[t, ...], deps, depsU, n2_thres=n2_thres) Frs.append(np.mean(Fr[xmin:xmax+1])) cs.append(np.mean(c[xmin:xmax+1])) u_avgs.append(np.mean(u_avg[xmin:xmax+1])) dates.append(time_origin + datetime.timedelta(seconds=times[t])) return Frs,", "based on an question of state: g* (alpha dk[T] + beta dk[S] )", "c = calculate_internal_wave_speed(rho, deps, dinds) # calculate depth averaged currents u_avg = depth_averaged_current(u,", "calculate_froude_number(n2, rho, u, deps, depsU, n2_thres=5e-6): \"\"\"Calculates the Froude number n2, rho, u", "\"\"\" Calculate the squared buoyancy frequency (n2) given temperature and salinity profiles. N2", "rho_2 = np.zeros((rho.shape[-1])) for ind, d in enumerate(dinds): rho_1[ind] = analyze.depth_average(rho[0:d+1, ind], deps[0:d+1],", "calculate_internal_wave_speed(rho, deps, dinds) # calculate depth averaged currents u_avg = depth_averaged_current(u, depsU) #", "mean_md = np.mean(mixed_depths[xmin:xmax+1]) return mean_md def mld_time_series(n2, deps, times, time_origin, xmin=300, xmax=700, n2_thres=5e-6):", "xmin=300, xmax=700, n2_thres=5e-6): \"\"\"Calculates the mean mixed layer depth in a region defined", "in deg C (t) and salinity in psu (s). returns the density as", "is depth, x). u must be a masked array deps is the array", "internal wave speed c = calculate_internal_wave_speed(rho, deps, dinds) # calculate depth averaged currents", "u_avgs, dates the Froude number, internal wave speed, and depth averaged current for", "\"\"\"Calculates the mean mixed layer depth in a region defined by xmin and", "1/e3[k, ...]*(rho_r[k+1, ...] - rho_r[k, ...]) # Unroll drho drho = np.rollaxis(drho_r, 0," ]
[ "neg_conf_loss total_loss /= (num_pos + tf.to_float(num_neg_batch)) num_pos = tf.where(tf.not_equal(num_pos, 0), num_pos, tf.ones_like(num_pos)) total_loss", "num_boxes, 4 + num_classes + 8). # Returns loss: Loss for prediction, tensor", "softmax loss. # Arguments y_true: Ground truth targets, tensor of shape (?, num_boxes,", "PURPOSE. See the # GNU General Public License for more details. # #", "loss: Loss for prediction, tensor of shape (?,). \"\"\" batch_size = tf.shape(y_true)[0] num_boxes", "by # the Free Software Foundation, either version 3 of the License, or", "of shape (?, num_boxes, num_classes). # Returns softmax_loss: Softmax loss, tensor of shape", "in ground truth are fictitious, y_true[:, :, -8] has 1 if prior should", "shape (?, num_boxes, 4). # Returns l1_loss: L1-smooth loss, tensor of shape (?,", "num_neg = tf.minimum(self.neg_pos_ratio * num_pos, num_boxes - num_pos) pos_num_neg_mask = tf.greater(num_neg, 0) has_min", "confs_end = confs_start + self.num_classes - 1 max_confs = tf.reduce_max(y_pred[:, :, confs_start:confs_end], axis=2)", "pos_conf_loss * self.pos_cost_multiplier + neg_conf_loss total_loss /= (num_pos + tf.to_float(num_neg_batch)) num_pos = tf.where(tf.not_equal(num_pos,", "y_pred[:, :, :4]) # get positives loss num_pos = tf.reduce_sum(y_true[:, :, -8], axis=-1)", "[tf.expand_dims(batch_idx, 2), # tf.expand_dims(indices, 2)]) # neg_conf_loss = tf.gather_nd(conf_loss, full_indices) neg_conf_loss = tf.gather(tf.reshape(conf_loss,", "helper functions. # Arguments num_classes: Number of classes including background. alpha: Weight of", "= -tf.reduce_sum(y_true * tf.log(y_pred), axis=-1) return softmax_loss class MultiboxLoss: \"\"\"Multibox loss with some", "+ tf.reshape(indices, [-1])) # full_indices = tf.concat(2, [tf.expand_dims(batch_idx, 2), # tf.expand_dims(indices, 2)]) #", "= 0.5 * (y_true - y_pred)**2 l1_loss = tf.where(tf.less(abs_loss, 1.0), sq_loss, abs_loss -", "tf.to_int32(num_neg_batch) confs_start = 4 + self.background_label_id + 1 confs_end = confs_start + self.num_classes", "- y_true[:, :, -8]), k=num_neg_batch) batch_idx = tf.expand_dims(tf.range(0, batch_size), 1) batch_idx = tf.tile(batch_idx,", "prior should be penalized or in other words is assigned to some ground", "is assigned to some ground truth box, y_true[:, :, -7:] are all 0.", "Arguments y_true: Ground truth targets, tensor of shape (?, num_boxes, num_classes). y_pred: Predicted", "to some ground truth box, y_true[:, :, -7:] are all 0. y_pred: Predicted", "References https://arxiv.org/abs/1512.02325 \"\"\" def __init__(self, num_classes, alpha=1.0, neg_pos_ratio=3.0, background_label_id=0, negatives_for_hard=100.0, pos_cost_multiplier=1.0): self.pos_cost_multiplier =", "= tf.reduce_sum(neg_conf_loss, axis=1) # loss is sum of positives and negatives total_loss =", "Returns softmax_loss: Softmax loss, tensor of shape (?, num_boxes). \"\"\" y_pred = tf.maximum(tf.minimum(y_pred,", "shape (?, num_boxes). \"\"\" y_pred = tf.maximum(tf.minimum(y_pred, 1 - 1e-15), 1e-15) softmax_loss =", "!= 0: raise Exception('Only 0 as background label id is supported') self.background_label_id =", "pos_loc_loss = tf.reduce_sum(loc_loss * y_true[:, :, -8], axis=1) pos_conf_loss = tf.reduce_sum(conf_loss * y_true[:,", "tf.shape(y_true)[0] num_boxes = tf.to_float(tf.shape(y_true)[1]) # loss for all priors conf_loss = _softmax_loss(y_true[:, :,", "(?, num_boxes, 4 + num_classes + 8). # Returns loss: Loss for prediction,", "of the License, or # any later version. # # This program is", "+ num_classes + 8), priors in ground truth are fictitious, y_true[:, :, -8]", "tf.reduce_sum(l1_loss, -1) def _softmax_loss(y_true, y_pred): \"\"\"Compute softmax loss. # Arguments y_true: Ground truth", "are all 0. y_pred: Predicted logits, tensor of shape (?, num_boxes, 4 +", "should have received a copy of the GNU General Public License # along", "1 if prior should be penalized or in other words is assigned to", "or # any later version. # # This program is distributed in the", "negatives_for_hard def compute_loss(self, y_true, y_pred): \"\"\"Compute mutlibox loss. # Arguments y_true: Ground truth", "y_pred: Predicted logits, tensor of shape (?, num_boxes, num_classes). # Returns softmax_loss: Softmax", "priors in ground truth are fictitious, y_true[:, :, -8] has 1 if prior", "without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR", "_softmax_loss(y_true[:, :, 4:-8], y_pred[:, :, 4:-8]) loc_loss = _l1_smooth_loss(y_true[:, :, :4], y_pred[:, :,", "\"\"\" y_pred = tf.maximum(tf.minimum(y_pred, 1 - 1e-15), 1e-15) softmax_loss = -tf.reduce_sum(y_true * tf.log(y_pred),", "\"\"\"Compute softmax loss. # Arguments y_true: Ground truth targets, tensor of shape (?,", "= tf.reduce_sum(loc_loss * y_true[:, :, -8], axis=1) pos_conf_loss = tf.reduce_sum(conf_loss * y_true[:, :,", "the License, or # any later version. # # This program is distributed", "tf.reduce_sum(y_true[:, :, -8], axis=-1) pos_loc_loss = tf.reduce_sum(loc_loss * y_true[:, :, -8], axis=1) pos_conf_loss", "full_indices) neg_conf_loss = tf.reshape(neg_conf_loss, [batch_size, num_neg_batch]) neg_conf_loss = tf.reduce_sum(neg_conf_loss, axis=1) # loss is", "loss. # Arguments y_true: Ground truth targets, tensor of shape (?, num_boxes, num_classes).", "num_boxes). \"\"\" y_pred = tf.maximum(tf.minimum(y_pred, 1 - 1e-15), 1e-15) softmax_loss = -tf.reduce_sum(y_true *", "tensor of shape (?, num_boxes, 4). # Returns l1_loss: L1-smooth loss, tensor of", "we penalize only confidence here num_neg = tf.minimum(self.neg_pos_ratio * num_pos, num_boxes - num_pos)", "y_pred = tf.maximum(tf.minimum(y_pred, 1 - 1e-15), 1e-15) softmax_loss = -tf.reduce_sum(y_true * tf.log(y_pred), axis=-1)", "loss. # Arguments y_true: Ground truth bounding boxes, tensor of shape (?, num_boxes,", "(1 - y_true[:, :, -8]), k=num_neg_batch) batch_idx = tf.expand_dims(tf.range(0, batch_size), 1) batch_idx =", "as tf def _l1_smooth_loss(y_true, y_pred): \"\"\"Compute L1-smooth loss. # Arguments y_true: Ground truth", "softmax_loss class MultiboxLoss: \"\"\"Multibox loss with some helper functions. # Arguments num_classes: Number", "You should have received a copy of the GNU General Public License #", "training utils. \"\"\" import tensorflow as tf def _l1_smooth_loss(y_true, y_pred): \"\"\"Compute L1-smooth loss.", "This file is part of OpenEM, released under GPLv3. # OpenEM is free", "= _l1_smooth_loss(y_true[:, :, :4], y_pred[:, :, :4]) # get positives loss num_pos =", "background label id is supported') self.background_label_id = background_label_id self.negatives_for_hard = negatives_for_hard def compute_loss(self,", "loss, we penalize only confidence here num_neg = tf.minimum(self.neg_pos_ratio * num_pos, num_boxes -", "y_true[:, :, -8]), k=num_neg_batch) batch_idx = tf.expand_dims(tf.range(0, batch_size), 1) batch_idx = tf.tile(batch_idx, (1,", "details. # # You should have received a copy of the GNU General", "num_pos = tf.where(tf.not_equal(num_pos, 0), num_pos, tf.ones_like(num_pos)) total_loss += (self.alpha * pos_loc_loss) / num_pos", "file is part of OpenEM, released under GPLv3. # OpenEM is free software:", "WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A", "# loss for all priors conf_loss = _softmax_loss(y_true[:, :, 4:-8], y_pred[:, :, 4:-8])", "box, y_true[:, :, -7:] are all 0. y_pred: Predicted logits, tensor of shape", "that it will be useful, # but WITHOUT ANY WARRANTY; without even the", "values=[num_neg, [(1 - has_min) * self.negatives_for_hard]]) num_neg_batch = tf.reduce_min(tf.boolean_mask(num_neg, tf.greater(num_neg, 0))) num_neg_batch =", "\"\"\"SSD training utils. \"\"\" import tensorflow as tf def _l1_smooth_loss(y_true, y_pred): \"\"\"Compute L1-smooth", "num_classes). y_pred: Predicted logits, tensor of shape (?, num_boxes, num_classes). # Returns softmax_loss:", "here num_neg = tf.minimum(self.neg_pos_ratio * num_pos, num_boxes - num_pos) pos_num_neg_mask = tf.greater(num_neg, 0)", "tf.reduce_sum(conf_loss * y_true[:, :, -8], axis=1) # get negatives loss, we penalize only", "the terms of the GNU General Public License as published by # the", "axis=-1) pos_loc_loss = tf.reduce_sum(loc_loss * y_true[:, :, -8], axis=1) pos_conf_loss = tf.reduce_sum(conf_loss *", "bounding boxes, tensor of shape (?, num_boxes, 4). y_pred: Predicted bounding boxes, tensor", "= tf.greater(num_neg, 0) has_min = tf.to_float(tf.reduce_any(pos_num_neg_mask)) num_neg = tf.concat( axis=0, values=[num_neg, [(1 -", "tf.to_float(tf.shape(y_true)[1]) # loss for all priors conf_loss = _softmax_loss(y_true[:, :, 4:-8], y_pred[:, :,", "\"Copyright (C) 2018 CVision AI.\" __license__ = \"GPLv3\" # This file is part", "implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the", "8). # Returns loss: Loss for prediction, tensor of shape (?,). \"\"\" batch_size", "copy of the GNU General Public License # along with OpenEM. If not,", "alpha=1.0, neg_pos_ratio=3.0, background_label_id=0, negatives_for_hard=100.0, pos_cost_multiplier=1.0): self.pos_cost_multiplier = pos_cost_multiplier self.num_classes = num_classes self.alpha =", "or in other words is assigned to some ground truth box, y_true[:, :,", "(?, num_boxes, 4). # Returns l1_loss: L1-smooth loss, tensor of shape (?, num_boxes).", "(?, num_boxes, num_classes). # Returns softmax_loss: Softmax loss, tensor of shape (?, num_boxes).", "the hope that it will be useful, # but WITHOUT ANY WARRANTY; without", "targets, tensor of shape (?, num_boxes, num_classes). y_pred: Predicted logits, tensor of shape", "utils. \"\"\" import tensorflow as tf def _l1_smooth_loss(y_true, y_pred): \"\"\"Compute L1-smooth loss. #", "* self.pos_cost_multiplier + neg_conf_loss total_loss /= (num_pos + tf.to_float(num_neg_batch)) num_pos = tf.where(tf.not_equal(num_pos, 0),", "= tf.concat(2, [tf.expand_dims(batch_idx, 2), # tf.expand_dims(indices, 2)]) # neg_conf_loss = tf.gather_nd(conf_loss, full_indices) neg_conf_loss", "some ground truth box, y_true[:, :, -7:] are all 0. y_pred: Predicted logits,", "Softmax loss, tensor of shape (?, num_boxes). \"\"\" y_pred = tf.maximum(tf.minimum(y_pred, 1 -", "has 1 if prior should be penalized or in other words is assigned", ":, :4]) # get positives loss num_pos = tf.reduce_sum(y_true[:, :, -8], axis=-1) pos_loc_loss", "2018 CVision AI.\" __license__ = \"GPLv3\" # This file is part of OpenEM,", "boxes, tensor of shape (?, num_boxes, 4). y_pred: Predicted bounding boxes, tensor of", "[-1]) * tf.to_int32(num_boxes) + tf.reshape(indices, [-1])) # full_indices = tf.concat(2, [tf.expand_dims(batch_idx, 2), #", "a copy of the GNU General Public License # along with OpenEM. If", "boxes, tensor of shape (?, num_boxes, 4). # Returns l1_loss: L1-smooth loss, tensor", "\"\"\" abs_loss = tf.abs(y_true - y_pred) sq_loss = 0.5 * (y_true - y_pred)**2", "neg_conf_loss = tf.gather(tf.reshape(conf_loss, [-1]), full_indices) neg_conf_loss = tf.reshape(neg_conf_loss, [batch_size, num_neg_batch]) neg_conf_loss = tf.reduce_sum(neg_conf_loss,", "max_confs = tf.reduce_max(y_pred[:, :, confs_start:confs_end], axis=2) _, indices = tf.nn.top_k(max_confs * (1 -", "= tf.gather_nd(conf_loss, full_indices) neg_conf_loss = tf.gather(tf.reshape(conf_loss, [-1]), full_indices) neg_conf_loss = tf.reshape(neg_conf_loss, [batch_size, num_neg_batch])", "# You should have received a copy of the GNU General Public License", "self.alpha = alpha self.neg_pos_ratio = neg_pos_ratio if background_label_id != 0: raise Exception('Only 0", "background_label_id: Id of background label. negatives_for_hard: Number of negative boxes to consider it", "Predicted logits, tensor of shape (?, num_boxes, num_classes). # Returns softmax_loss: Softmax loss,", "self.neg_pos_ratio = neg_pos_ratio if background_label_id != 0: raise Exception('Only 0 as background label", "compute_loss(self, y_true, y_pred): \"\"\"Compute mutlibox loss. # Arguments y_true: Ground truth targets, tensor", "= num_classes self.alpha = alpha self.neg_pos_ratio = neg_pos_ratio if background_label_id != 0: raise", "= alpha self.neg_pos_ratio = neg_pos_ratio if background_label_id != 0: raise Exception('Only 0 as", "return tf.reduce_sum(l1_loss, -1) def _softmax_loss(y_true, y_pred): \"\"\"Compute softmax loss. # Arguments y_true: Ground", "loss with some helper functions. # Arguments num_classes: Number of classes including background.", "(y_true - y_pred)**2 l1_loss = tf.where(tf.less(abs_loss, 1.0), sq_loss, abs_loss - 0.5) return tf.reduce_sum(l1_loss,", "num_classes + 8), priors in ground truth are fictitious, y_true[:, :, -8] has", "softmax_loss: Softmax loss, tensor of shape (?, num_boxes). \"\"\" y_pred = tf.maximum(tf.minimum(y_pred, 1", "version. # # This program is distributed in the hope that it will", "tensor of shape (?, num_boxes, 4 + num_classes + 8), priors in ground", "tf.to_int32(num_boxes) + tf.reshape(indices, [-1])) # full_indices = tf.concat(2, [tf.expand_dims(batch_idx, 2), # tf.expand_dims(indices, 2)])", "= tf.to_int32(num_neg_batch) confs_start = 4 + self.background_label_id + 1 confs_end = confs_start +", "return softmax_loss class MultiboxLoss: \"\"\"Multibox loss with some helper functions. # Arguments num_classes:", "y_true: Ground truth targets, tensor of shape (?, num_boxes, 4 + num_classes +", "A PARTICULAR PURPOSE. See the # GNU General Public License for more details.", "* self.negatives_for_hard]]) num_neg_batch = tf.reduce_min(tf.boolean_mask(num_neg, tf.greater(num_neg, 0))) num_neg_batch = tf.to_int32(num_neg_batch) confs_start = 4", "is supported') self.background_label_id = background_label_id self.negatives_for_hard = negatives_for_hard def compute_loss(self, y_true, y_pred): \"\"\"Compute", "0) has_min = tf.to_float(tf.reduce_any(pos_num_neg_mask)) num_neg = tf.concat( axis=0, values=[num_neg, [(1 - has_min) *", "* tf.log(y_pred), axis=-1) return softmax_loss class MultiboxLoss: \"\"\"Multibox loss with some helper functions.", "num_classes). # Returns softmax_loss: Softmax loss, tensor of shape (?, num_boxes). \"\"\" y_pred", "Arguments y_true: Ground truth targets, tensor of shape (?, num_boxes, 4 + num_classes", "the GNU General Public License # along with OpenEM. If not, see <http://www.gnu.org/licenses/>.", "axis=-1) return softmax_loss class MultiboxLoss: \"\"\"Multibox loss with some helper functions. # Arguments", "General Public License as published by # the Free Software Foundation, either version", "all priors conf_loss = _softmax_loss(y_true[:, :, 4:-8], y_pred[:, :, 4:-8]) loc_loss = _l1_smooth_loss(y_true[:,", "total_loss = pos_conf_loss * self.pos_cost_multiplier + neg_conf_loss total_loss /= (num_pos + tf.to_float(num_neg_batch)) num_pos", "software: you can redistribute it and/or modify # it under the terms of", "(tf.reshape(batch_idx, [-1]) * tf.to_int32(num_boxes) + tf.reshape(indices, [-1])) # full_indices = tf.concat(2, [tf.expand_dims(batch_idx, 2),", "tf.greater(num_neg, 0))) num_neg_batch = tf.to_int32(num_neg_batch) confs_start = 4 + self.background_label_id + 1 confs_end", "alpha: Weight of L1-smooth loss. neg_pos_ratio: Max ratio of negative to positive boxes", "1 - 1e-15), 1e-15) softmax_loss = -tf.reduce_sum(y_true * tf.log(y_pred), axis=-1) return softmax_loss class", "num_pos) pos_num_neg_mask = tf.greater(num_neg, 0) has_min = tf.to_float(tf.reduce_any(pos_num_neg_mask)) num_neg = tf.concat( axis=0, values=[num_neg,", "# GNU General Public License for more details. # # You should have", "of L1-smooth loss. neg_pos_ratio: Max ratio of negative to positive boxes in loss.", "L1-smooth loss, tensor of shape (?, num_boxes). # References https://arxiv.org/abs/1504.08083 \"\"\" abs_loss =", "L1-smooth loss. neg_pos_ratio: Max ratio of negative to positive boxes in loss. background_label_id:", "Ground truth targets, tensor of shape (?, num_boxes, num_classes). y_pred: Predicted logits, tensor", "indices = tf.nn.top_k(max_confs * (1 - y_true[:, :, -8]), k=num_neg_batch) batch_idx = tf.expand_dims(tf.range(0,", "[-1])) # full_indices = tf.concat(2, [tf.expand_dims(batch_idx, 2), # tf.expand_dims(indices, 2)]) # neg_conf_loss =", "targets, tensor of shape (?, num_boxes, 4 + num_classes + 8), priors in", "Ground truth bounding boxes, tensor of shape (?, num_boxes, 4). y_pred: Predicted bounding", "= tf.to_float(tf.reduce_any(pos_num_neg_mask)) num_neg = tf.concat( axis=0, values=[num_neg, [(1 - has_min) * self.negatives_for_hard]]) num_neg_batch", "tensor of shape (?, num_boxes). \"\"\" y_pred = tf.maximum(tf.minimum(y_pred, 1 - 1e-15), 1e-15)", "of shape (?, num_boxes, 4 + num_classes + 8), priors in ground truth", "either version 3 of the License, or # any later version. # #", "it and/or modify # it under the terms of the GNU General Public", "y_pred: Predicted bounding boxes, tensor of shape (?, num_boxes, 4). # Returns l1_loss:", "of classes including background. alpha: Weight of L1-smooth loss. neg_pos_ratio: Max ratio of", "https://arxiv.org/abs/1512.02325 \"\"\" def __init__(self, num_classes, alpha=1.0, neg_pos_ratio=3.0, background_label_id=0, negatives_for_hard=100.0, pos_cost_multiplier=1.0): self.pos_cost_multiplier = pos_cost_multiplier", "0: raise Exception('Only 0 as background label id is supported') self.background_label_id = background_label_id", "received a copy of the GNU General Public License # along with OpenEM.", "# it under the terms of the GNU General Public License as published", "tf.maximum(tf.minimum(y_pred, 1 - 1e-15), 1e-15) softmax_loss = -tf.reduce_sum(y_true * tf.log(y_pred), axis=-1) return softmax_loss", "logits, tensor of shape (?, num_boxes, 4 + num_classes + 8). # Returns", ":, 4:-8]) loc_loss = _l1_smooth_loss(y_true[:, :, :4], y_pred[:, :, :4]) # get positives", "tf.reduce_sum(loc_loss * y_true[:, :, -8], axis=1) pos_conf_loss = tf.reduce_sum(conf_loss * y_true[:, :, -8],", "negatives loss, we penalize only confidence here num_neg = tf.minimum(self.neg_pos_ratio * num_pos, num_boxes", "neg_conf_loss = tf.reshape(neg_conf_loss, [batch_size, num_neg_batch]) neg_conf_loss = tf.reduce_sum(neg_conf_loss, axis=1) # loss is sum", "free software: you can redistribute it and/or modify # it under the terms", "* (y_true - y_pred)**2 l1_loss = tf.where(tf.less(abs_loss, 1.0), sq_loss, abs_loss - 0.5) return", "for prediction, tensor of shape (?,). \"\"\" batch_size = tf.shape(y_true)[0] num_boxes = tf.to_float(tf.shape(y_true)[1])", "full_indices) neg_conf_loss = tf.gather(tf.reshape(conf_loss, [-1]), full_indices) neg_conf_loss = tf.reshape(neg_conf_loss, [batch_size, num_neg_batch]) neg_conf_loss =", "= tf.reduce_min(tf.boolean_mask(num_neg, tf.greater(num_neg, 0))) num_neg_batch = tf.to_int32(num_neg_batch) confs_start = 4 + self.background_label_id +", "for all priors conf_loss = _softmax_loss(y_true[:, :, 4:-8], y_pred[:, :, 4:-8]) loc_loss =", "negative boxes to consider it there is no positive boxes in batch. #", "tf.tile(batch_idx, (1, num_neg_batch)) full_indices = (tf.reshape(batch_idx, [-1]) * tf.to_int32(num_boxes) + tf.reshape(indices, [-1])) #", "__copyright__ = \"Copyright (C) 2018 CVision AI.\" __license__ = \"GPLv3\" # This file", "# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General", "[batch_size, num_neg_batch]) neg_conf_loss = tf.reduce_sum(neg_conf_loss, axis=1) # loss is sum of positives and", "confidence here num_neg = tf.minimum(self.neg_pos_ratio * num_pos, num_boxes - num_pos) pos_num_neg_mask = tf.greater(num_neg,", "get negatives loss, we penalize only confidence here num_neg = tf.minimum(self.neg_pos_ratio * num_pos,", "tf.abs(y_true - y_pred) sq_loss = 0.5 * (y_true - y_pred)**2 l1_loss = tf.where(tf.less(abs_loss,", "batch_idx = tf.expand_dims(tf.range(0, batch_size), 1) batch_idx = tf.tile(batch_idx, (1, num_neg_batch)) full_indices = (tf.reshape(batch_idx,", "= tf.nn.top_k(max_confs * (1 - y_true[:, :, -8]), k=num_neg_batch) batch_idx = tf.expand_dims(tf.range(0, batch_size),", "= tf.reduce_sum(y_true[:, :, -8], axis=-1) pos_loc_loss = tf.reduce_sum(loc_loss * y_true[:, :, -8], axis=1)", "tensor of shape (?, num_boxes, 4 + num_classes + 8). # Returns loss:", "loss for all priors conf_loss = _softmax_loss(y_true[:, :, 4:-8], y_pred[:, :, 4:-8]) loc_loss", "batch_size = tf.shape(y_true)[0] num_boxes = tf.to_float(tf.shape(y_true)[1]) # loss for all priors conf_loss =", "is sum of positives and negatives total_loss = pos_conf_loss * self.pos_cost_multiplier + neg_conf_loss", "tf.concat( axis=0, values=[num_neg, [(1 - has_min) * self.negatives_for_hard]]) num_neg_batch = tf.reduce_min(tf.boolean_mask(num_neg, tf.greater(num_neg, 0)))", "* num_pos, num_boxes - num_pos) pos_num_neg_mask = tf.greater(num_neg, 0) has_min = tf.to_float(tf.reduce_any(pos_num_neg_mask)) num_neg", "priors conf_loss = _softmax_loss(y_true[:, :, 4:-8], y_pred[:, :, 4:-8]) loc_loss = _l1_smooth_loss(y_true[:, :,", "loss num_pos = tf.reduce_sum(y_true[:, :, -8], axis=-1) pos_loc_loss = tf.reduce_sum(loc_loss * y_true[:, :,", "# Arguments num_classes: Number of classes including background. alpha: Weight of L1-smooth loss.", "self.pos_cost_multiplier = pos_cost_multiplier self.num_classes = num_classes self.alpha = alpha self.neg_pos_ratio = neg_pos_ratio if", "functions. # Arguments num_classes: Number of classes including background. alpha: Weight of L1-smooth", "neg_conf_loss = tf.gather_nd(conf_loss, full_indices) neg_conf_loss = tf.gather(tf.reshape(conf_loss, [-1]), full_indices) neg_conf_loss = tf.reshape(neg_conf_loss, [batch_size,", "Id of background label. negatives_for_hard: Number of negative boxes to consider it there", "negative to positive boxes in loss. background_label_id: Id of background label. negatives_for_hard: Number", "self.background_label_id = background_label_id self.negatives_for_hard = negatives_for_hard def compute_loss(self, y_true, y_pred): \"\"\"Compute mutlibox loss.", "shape (?, num_boxes, num_classes). y_pred: Predicted logits, tensor of shape (?, num_boxes, num_classes).", "num_neg_batch)) full_indices = (tf.reshape(batch_idx, [-1]) * tf.to_int32(num_boxes) + tf.reshape(indices, [-1])) # full_indices =", "= (tf.reshape(batch_idx, [-1]) * tf.to_int32(num_boxes) + tf.reshape(indices, [-1])) # full_indices = tf.concat(2, [tf.expand_dims(batch_idx,", "= _softmax_loss(y_true[:, :, 4:-8], y_pred[:, :, 4:-8]) loc_loss = _l1_smooth_loss(y_true[:, :, :4], y_pred[:,", "boxes to consider it there is no positive boxes in batch. # References", "the GNU General Public License as published by # the Free Software Foundation,", "other words is assigned to some ground truth box, y_true[:, :, -7:] are", "= tf.expand_dims(tf.range(0, batch_size), 1) batch_idx = tf.tile(batch_idx, (1, num_neg_batch)) full_indices = (tf.reshape(batch_idx, [-1])", "axis=2) _, indices = tf.nn.top_k(max_confs * (1 - y_true[:, :, -8]), k=num_neg_batch) batch_idx", "tensorflow as tf def _l1_smooth_loss(y_true, y_pred): \"\"\"Compute L1-smooth loss. # Arguments y_true: Ground", "warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #", "# the Free Software Foundation, either version 3 of the License, or #", "+ 8), priors in ground truth are fictitious, y_true[:, :, -8] has 1", "of shape (?,). \"\"\" batch_size = tf.shape(y_true)[0] num_boxes = tf.to_float(tf.shape(y_true)[1]) # loss for", "tensor of shape (?, num_boxes, 4). y_pred: Predicted bounding boxes, tensor of shape", "of background label. negatives_for_hard: Number of negative boxes to consider it there is", "neg_conf_loss = tf.reduce_sum(neg_conf_loss, axis=1) # loss is sum of positives and negatives total_loss", "= tf.gather(tf.reshape(conf_loss, [-1]), full_indices) neg_conf_loss = tf.reshape(neg_conf_loss, [batch_size, num_neg_batch]) neg_conf_loss = tf.reduce_sum(neg_conf_loss, axis=1)", "4:-8]) loc_loss = _l1_smooth_loss(y_true[:, :, :4], y_pred[:, :, :4]) # get positives loss", "num_classes: Number of classes including background. alpha: Weight of L1-smooth loss. neg_pos_ratio: Max", "= negatives_for_hard def compute_loss(self, y_true, y_pred): \"\"\"Compute mutlibox loss. # Arguments y_true: Ground", "some helper functions. # Arguments num_classes: Number of classes including background. alpha: Weight", "tf.reduce_sum(neg_conf_loss, axis=1) # loss is sum of positives and negatives total_loss = pos_conf_loss", "OpenEM. If not, see <http://www.gnu.org/licenses/>. \"\"\"SSD training utils. \"\"\" import tensorflow as tf", "https://arxiv.org/abs/1504.08083 \"\"\" abs_loss = tf.abs(y_true - y_pred) sq_loss = 0.5 * (y_true -", "tensor of shape (?, num_boxes). # References https://arxiv.org/abs/1504.08083 \"\"\" abs_loss = tf.abs(y_true -", "2)]) # neg_conf_loss = tf.gather_nd(conf_loss, full_indices) neg_conf_loss = tf.gather(tf.reshape(conf_loss, [-1]), full_indices) neg_conf_loss =", "(1, num_neg_batch)) full_indices = (tf.reshape(batch_idx, [-1]) * tf.to_int32(num_boxes) + tf.reshape(indices, [-1])) # full_indices", "tensor of shape (?, num_boxes, num_classes). # Returns softmax_loss: Softmax loss, tensor of", "+ num_classes + 8). # Returns loss: Loss for prediction, tensor of shape", ":4], y_pred[:, :, :4]) # get positives loss num_pos = tf.reduce_sum(y_true[:, :, -8],", "* tf.to_int32(num_boxes) + tf.reshape(indices, [-1])) # full_indices = tf.concat(2, [tf.expand_dims(batch_idx, 2), # tf.expand_dims(indices,", "def _l1_smooth_loss(y_true, y_pred): \"\"\"Compute L1-smooth loss. # Arguments y_true: Ground truth bounding boxes,", "= tf.maximum(tf.minimum(y_pred, 1 - 1e-15), 1e-15) softmax_loss = -tf.reduce_sum(y_true * tf.log(y_pred), axis=-1) return", "L1-smooth loss. # Arguments y_true: Ground truth bounding boxes, tensor of shape (?,", "# Returns loss: Loss for prediction, tensor of shape (?,). \"\"\" batch_size =", "it will be useful, # but WITHOUT ANY WARRANTY; without even the implied", "along with OpenEM. If not, see <http://www.gnu.org/licenses/>. \"\"\"SSD training utils. \"\"\" import tensorflow", "if background_label_id != 0: raise Exception('Only 0 as background label id is supported')", "# get negatives loss, we penalize only confidence here num_neg = tf.minimum(self.neg_pos_ratio *", "all 0. y_pred: Predicted logits, tensor of shape (?, num_boxes, 4 + num_classes", "-8]), k=num_neg_batch) batch_idx = tf.expand_dims(tf.range(0, batch_size), 1) batch_idx = tf.tile(batch_idx, (1, num_neg_batch)) full_indices", "tf def _l1_smooth_loss(y_true, y_pred): \"\"\"Compute L1-smooth loss. # Arguments y_true: Ground truth bounding", "= \"Copyright (C) 2018 CVision AI.\" __license__ = \"GPLv3\" # This file is", "ratio of negative to positive boxes in loss. background_label_id: Id of background label.", "tf.expand_dims(indices, 2)]) # neg_conf_loss = tf.gather_nd(conf_loss, full_indices) neg_conf_loss = tf.gather(tf.reshape(conf_loss, [-1]), full_indices) neg_conf_loss", "1 max_confs = tf.reduce_max(y_pred[:, :, confs_start:confs_end], axis=2) _, indices = tf.nn.top_k(max_confs * (1", "penalized or in other words is assigned to some ground truth box, y_true[:,", "General Public License for more details. # # You should have received a", "- 1 max_confs = tf.reduce_max(y_pred[:, :, confs_start:confs_end], axis=2) _, indices = tf.nn.top_k(max_confs *", "\"\"\"Compute L1-smooth loss. # Arguments y_true: Ground truth bounding boxes, tensor of shape", ":, -8] has 1 if prior should be penalized or in other words", "shape (?, num_boxes, 4 + num_classes + 8). # Returns loss: Loss for", "the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See", "Weight of L1-smooth loss. neg_pos_ratio: Max ratio of negative to positive boxes in", "ground truth are fictitious, y_true[:, :, -8] has 1 if prior should be", "tf.reduce_min(tf.boolean_mask(num_neg, tf.greater(num_neg, 0))) num_neg_batch = tf.to_int32(num_neg_batch) confs_start = 4 + self.background_label_id + 1", "axis=1) # loss is sum of positives and negatives total_loss = pos_conf_loss *", "# full_indices = tf.concat(2, [tf.expand_dims(batch_idx, 2), # tf.expand_dims(indices, 2)]) # neg_conf_loss = tf.gather_nd(conf_loss,", "under GPLv3. # OpenEM is free software: you can redistribute it and/or modify", "tf.gather(tf.reshape(conf_loss, [-1]), full_indices) neg_conf_loss = tf.reshape(neg_conf_loss, [batch_size, num_neg_batch]) neg_conf_loss = tf.reduce_sum(neg_conf_loss, axis=1) #", "[-1]), full_indices) neg_conf_loss = tf.reshape(neg_conf_loss, [batch_size, num_neg_batch]) neg_conf_loss = tf.reduce_sum(neg_conf_loss, axis=1) # loss", "import tensorflow as tf def _l1_smooth_loss(y_true, y_pred): \"\"\"Compute L1-smooth loss. # Arguments y_true:", "License # along with OpenEM. If not, see <http://www.gnu.org/licenses/>. \"\"\"SSD training utils. \"\"\"", "num_boxes, num_classes). y_pred: Predicted logits, tensor of shape (?, num_boxes, num_classes). # Returns", "tf.concat(2, [tf.expand_dims(batch_idx, 2), # tf.expand_dims(indices, 2)]) # neg_conf_loss = tf.gather_nd(conf_loss, full_indices) neg_conf_loss =", "truth are fictitious, y_true[:, :, -8] has 1 if prior should be penalized", "Loss for prediction, tensor of shape (?,). \"\"\" batch_size = tf.shape(y_true)[0] num_boxes =", "the # GNU General Public License for more details. # # You should", "no positive boxes in batch. # References https://arxiv.org/abs/1512.02325 \"\"\" def __init__(self, num_classes, alpha=1.0,", "tf.expand_dims(tf.range(0, batch_size), 1) batch_idx = tf.tile(batch_idx, (1, num_neg_batch)) full_indices = (tf.reshape(batch_idx, [-1]) *", "4 + self.background_label_id + 1 confs_end = confs_start + self.num_classes - 1 max_confs", "shape (?, num_boxes, num_classes). # Returns softmax_loss: Softmax loss, tensor of shape (?,", "or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License", "Returns l1_loss: L1-smooth loss, tensor of shape (?, num_boxes). # References https://arxiv.org/abs/1504.08083 \"\"\"", "of negative to positive boxes in loss. background_label_id: Id of background label. negatives_for_hard:", "for more details. # # You should have received a copy of the", "to consider it there is no positive boxes in batch. # References https://arxiv.org/abs/1512.02325", "def __init__(self, num_classes, alpha=1.0, neg_pos_ratio=3.0, background_label_id=0, negatives_for_hard=100.0, pos_cost_multiplier=1.0): self.pos_cost_multiplier = pos_cost_multiplier self.num_classes =", "alpha self.neg_pos_ratio = neg_pos_ratio if background_label_id != 0: raise Exception('Only 0 as background", "= neg_pos_ratio if background_label_id != 0: raise Exception('Only 0 as background label id", "self.background_label_id + 1 confs_end = confs_start + self.num_classes - 1 max_confs = tf.reduce_max(y_pred[:,", "words is assigned to some ground truth box, y_true[:, :, -7:] are all", "If not, see <http://www.gnu.org/licenses/>. \"\"\"SSD training utils. \"\"\" import tensorflow as tf def", "_l1_smooth_loss(y_true[:, :, :4], y_pred[:, :, :4]) # get positives loss num_pos = tf.reduce_sum(y_true[:,", "# Returns l1_loss: L1-smooth loss, tensor of shape (?, num_boxes). # References https://arxiv.org/abs/1504.08083", "3 of the License, or # any later version. # # This program", "more details. # # You should have received a copy of the GNU", "of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU", "loc_loss = _l1_smooth_loss(y_true[:, :, :4], y_pred[:, :, :4]) # get positives loss num_pos", "GNU General Public License for more details. # # You should have received", "under the terms of the GNU General Public License as published by #", "tensor of shape (?, num_boxes, num_classes). y_pred: Predicted logits, tensor of shape (?,", "# along with OpenEM. If not, see <http://www.gnu.org/licenses/>. \"\"\"SSD training utils. \"\"\" import", "y_true[:, :, -8], axis=1) # get negatives loss, we penalize only confidence here", "program is distributed in the hope that it will be useful, # but", "- y_pred)**2 l1_loss = tf.where(tf.less(abs_loss, 1.0), sq_loss, abs_loss - 0.5) return tf.reduce_sum(l1_loss, -1)", "truth targets, tensor of shape (?, num_boxes, 4 + num_classes + 8), priors", "in other words is assigned to some ground truth box, y_true[:, :, -7:]", "background_label_id=0, negatives_for_hard=100.0, pos_cost_multiplier=1.0): self.pos_cost_multiplier = pos_cost_multiplier self.num_classes = num_classes self.alpha = alpha self.neg_pos_ratio", "distributed in the hope that it will be useful, # but WITHOUT ANY", "8), priors in ground truth are fictitious, y_true[:, :, -8] has 1 if", "and negatives total_loss = pos_conf_loss * self.pos_cost_multiplier + neg_conf_loss total_loss /= (num_pos +", "softmax_loss = -tf.reduce_sum(y_true * tf.log(y_pred), axis=-1) return softmax_loss class MultiboxLoss: \"\"\"Multibox loss with", "Predicted bounding boxes, tensor of shape (?, num_boxes, 4). # Returns l1_loss: L1-smooth", "published by # the Free Software Foundation, either version 3 of the License,", "consider it there is no positive boxes in batch. # References https://arxiv.org/abs/1512.02325 \"\"\"", "# References https://arxiv.org/abs/1512.02325 \"\"\" def __init__(self, num_classes, alpha=1.0, neg_pos_ratio=3.0, background_label_id=0, negatives_for_hard=100.0, pos_cost_multiplier=1.0): self.pos_cost_multiplier", "total_loss /= (num_pos + tf.to_float(num_neg_batch)) num_pos = tf.where(tf.not_equal(num_pos, 0), num_pos, tf.ones_like(num_pos)) total_loss +=", "loss is sum of positives and negatives total_loss = pos_conf_loss * self.pos_cost_multiplier +", "prediction, tensor of shape (?,). \"\"\" batch_size = tf.shape(y_true)[0] num_boxes = tf.to_float(tf.shape(y_true)[1]) #", "any later version. # # This program is distributed in the hope that", "def _softmax_loss(y_true, y_pred): \"\"\"Compute softmax loss. # Arguments y_true: Ground truth targets, tensor", "confs_start:confs_end], axis=2) _, indices = tf.nn.top_k(max_confs * (1 - y_true[:, :, -8]), k=num_neg_batch)", "num_neg = tf.concat( axis=0, values=[num_neg, [(1 - has_min) * self.negatives_for_hard]]) num_neg_batch = tf.reduce_min(tf.boolean_mask(num_neg,", "num_neg_batch]) neg_conf_loss = tf.reduce_sum(neg_conf_loss, axis=1) # loss is sum of positives and negatives", "it under the terms of the GNU General Public License as published by", "# Arguments y_true: Ground truth targets, tensor of shape (?, num_boxes, 4 +", "loss, tensor of shape (?, num_boxes). # References https://arxiv.org/abs/1504.08083 \"\"\" abs_loss = tf.abs(y_true", "if prior should be penalized or in other words is assigned to some", "only confidence here num_neg = tf.minimum(self.neg_pos_ratio * num_pos, num_boxes - num_pos) pos_num_neg_mask =", "-8] has 1 if prior should be penalized or in other words is", "0.5) return tf.reduce_sum(l1_loss, -1) def _softmax_loss(y_true, y_pred): \"\"\"Compute softmax loss. # Arguments y_true:", "num_boxes, 4). # Returns l1_loss: L1-smooth loss, tensor of shape (?, num_boxes). #", "in batch. # References https://arxiv.org/abs/1512.02325 \"\"\" def __init__(self, num_classes, alpha=1.0, neg_pos_ratio=3.0, background_label_id=0, negatives_for_hard=100.0,", "you can redistribute it and/or modify # it under the terms of the", "= tf.abs(y_true - y_pred) sq_loss = 0.5 * (y_true - y_pred)**2 l1_loss =", "num_classes, alpha=1.0, neg_pos_ratio=3.0, background_label_id=0, negatives_for_hard=100.0, pos_cost_multiplier=1.0): self.pos_cost_multiplier = pos_cost_multiplier self.num_classes = num_classes self.alpha", "= tf.tile(batch_idx, (1, num_neg_batch)) full_indices = (tf.reshape(batch_idx, [-1]) * tf.to_int32(num_boxes) + tf.reshape(indices, [-1]))", "# OpenEM is free software: you can redistribute it and/or modify # it", "_, indices = tf.nn.top_k(max_confs * (1 - y_true[:, :, -8]), k=num_neg_batch) batch_idx =", "of the GNU General Public License as published by # the Free Software", "self.num_classes - 1 max_confs = tf.reduce_max(y_pred[:, :, confs_start:confs_end], axis=2) _, indices = tf.nn.top_k(max_confs", "k=num_neg_batch) batch_idx = tf.expand_dims(tf.range(0, batch_size), 1) batch_idx = tf.tile(batch_idx, (1, num_neg_batch)) full_indices =", "tf.to_float(num_neg_batch)) num_pos = tf.where(tf.not_equal(num_pos, 0), num_pos, tf.ones_like(num_pos)) total_loss += (self.alpha * pos_loc_loss) /", "Public License as published by # the Free Software Foundation, either version 3", "label id is supported') self.background_label_id = background_label_id self.negatives_for_hard = negatives_for_hard def compute_loss(self, y_true,", "PARTICULAR PURPOSE. See the # GNU General Public License for more details. #", "\"\"\"Compute mutlibox loss. # Arguments y_true: Ground truth targets, tensor of shape (?,", "-8], axis=1) pos_conf_loss = tf.reduce_sum(conf_loss * y_true[:, :, -8], axis=1) # get negatives", "Number of classes including background. alpha: Weight of L1-smooth loss. neg_pos_ratio: Max ratio", "tf.log(y_pred), axis=-1) return softmax_loss class MultiboxLoss: \"\"\"Multibox loss with some helper functions. #", "1 confs_end = confs_start + self.num_classes - 1 max_confs = tf.reduce_max(y_pred[:, :, confs_start:confs_end],", "the Free Software Foundation, either version 3 of the License, or # any", "hope that it will be useful, # but WITHOUT ANY WARRANTY; without even", "as background label id is supported') self.background_label_id = background_label_id self.negatives_for_hard = negatives_for_hard def", "of positives and negatives total_loss = pos_conf_loss * self.pos_cost_multiplier + neg_conf_loss total_loss /=", "# neg_conf_loss = tf.gather_nd(conf_loss, full_indices) neg_conf_loss = tf.gather(tf.reshape(conf_loss, [-1]), full_indices) neg_conf_loss = tf.reshape(neg_conf_loss,", "pos_cost_multiplier=1.0): self.pos_cost_multiplier = pos_cost_multiplier self.num_classes = num_classes self.alpha = alpha self.neg_pos_ratio = neg_pos_ratio", "of shape (?, num_boxes, num_classes). y_pred: Predicted logits, tensor of shape (?, num_boxes,", "positives and negatives total_loss = pos_conf_loss * self.pos_cost_multiplier + neg_conf_loss total_loss /= (num_pos", "be penalized or in other words is assigned to some ground truth box,", "to positive boxes in loss. background_label_id: Id of background label. negatives_for_hard: Number of", "assigned to some ground truth box, y_true[:, :, -7:] are all 0. y_pred:", "it there is no positive boxes in batch. # References https://arxiv.org/abs/1512.02325 \"\"\" def", "= \"GPLv3\" # This file is part of OpenEM, released under GPLv3. #", "# tf.expand_dims(indices, 2)]) # neg_conf_loss = tf.gather_nd(conf_loss, full_indices) neg_conf_loss = tf.gather(tf.reshape(conf_loss, [-1]), full_indices)", "pos_conf_loss = tf.reduce_sum(conf_loss * y_true[:, :, -8], axis=1) # get negatives loss, we", "tf.nn.top_k(max_confs * (1 - y_true[:, :, -8]), k=num_neg_batch) batch_idx = tf.expand_dims(tf.range(0, batch_size), 1)", "2), # tf.expand_dims(indices, 2)]) # neg_conf_loss = tf.gather_nd(conf_loss, full_indices) neg_conf_loss = tf.gather(tf.reshape(conf_loss, [-1]),", "This program is distributed in the hope that it will be useful, #", "including background. alpha: Weight of L1-smooth loss. neg_pos_ratio: Max ratio of negative to", "= tf.minimum(self.neg_pos_ratio * num_pos, num_boxes - num_pos) pos_num_neg_mask = tf.greater(num_neg, 0) has_min =", "useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of #", "raise Exception('Only 0 as background label id is supported') self.background_label_id = background_label_id self.negatives_for_hard", "confs_start + self.num_classes - 1 max_confs = tf.reduce_max(y_pred[:, :, confs_start:confs_end], axis=2) _, indices", "confs_start = 4 + self.background_label_id + 1 confs_end = confs_start + self.num_classes -", "Number of negative boxes to consider it there is no positive boxes in", "y_true: Ground truth bounding boxes, tensor of shape (?, num_boxes, 4). y_pred: Predicted", "full_indices = tf.concat(2, [tf.expand_dims(batch_idx, 2), # tf.expand_dims(indices, 2)]) # neg_conf_loss = tf.gather_nd(conf_loss, full_indices)", "tf.gather_nd(conf_loss, full_indices) neg_conf_loss = tf.gather(tf.reshape(conf_loss, [-1]), full_indices) neg_conf_loss = tf.reshape(neg_conf_loss, [batch_size, num_neg_batch]) neg_conf_loss", "even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", "(?, num_boxes, 4 + num_classes + 8), priors in ground truth are fictitious,", "+ tf.to_float(num_neg_batch)) num_pos = tf.where(tf.not_equal(num_pos, 0), num_pos, tf.ones_like(num_pos)) total_loss += (self.alpha * pos_loc_loss)", "loss, tensor of shape (?, num_boxes). \"\"\" y_pred = tf.maximum(tf.minimum(y_pred, 1 - 1e-15),", "# # This program is distributed in the hope that it will be", "in loss. background_label_id: Id of background label. negatives_for_hard: Number of negative boxes to", "GNU General Public License # along with OpenEM. If not, see <http://www.gnu.org/licenses/>. \"\"\"SSD", "1.0), sq_loss, abs_loss - 0.5) return tf.reduce_sum(l1_loss, -1) def _softmax_loss(y_true, y_pred): \"\"\"Compute softmax", "not, see <http://www.gnu.org/licenses/>. \"\"\"SSD training utils. \"\"\" import tensorflow as tf def _l1_smooth_loss(y_true,", "sq_loss, abs_loss - 0.5) return tf.reduce_sum(l1_loss, -1) def _softmax_loss(y_true, y_pred): \"\"\"Compute softmax loss.", "is no positive boxes in batch. # References https://arxiv.org/abs/1512.02325 \"\"\" def __init__(self, num_classes,", "boxes in batch. # References https://arxiv.org/abs/1512.02325 \"\"\" def __init__(self, num_classes, alpha=1.0, neg_pos_ratio=3.0, background_label_id=0,", "axis=1) pos_conf_loss = tf.reduce_sum(conf_loss * y_true[:, :, -8], axis=1) # get negatives loss,", "num_boxes - num_pos) pos_num_neg_mask = tf.greater(num_neg, 0) has_min = tf.to_float(tf.reduce_any(pos_num_neg_mask)) num_neg = tf.concat(", "be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of", "[(1 - has_min) * self.negatives_for_hard]]) num_neg_batch = tf.reduce_min(tf.boolean_mask(num_neg, tf.greater(num_neg, 0))) num_neg_batch = tf.to_int32(num_neg_batch)", "of shape (?, num_boxes, 4). # Returns l1_loss: L1-smooth loss, tensor of shape", "are fictitious, y_true[:, :, -8] has 1 if prior should be penalized or", "/= (num_pos + tf.to_float(num_neg_batch)) num_pos = tf.where(tf.not_equal(num_pos, 0), num_pos, tf.ones_like(num_pos)) total_loss += (self.alpha", ":, -7:] are all 0. y_pred: Predicted logits, tensor of shape (?, num_boxes,", ":, -8], axis=1) # get negatives loss, we penalize only confidence here num_neg", "Ground truth targets, tensor of shape (?, num_boxes, 4 + num_classes + 8),", "tf.greater(num_neg, 0) has_min = tf.to_float(tf.reduce_any(pos_num_neg_mask)) num_neg = tf.concat( axis=0, values=[num_neg, [(1 - has_min)", ":4]) # get positives loss num_pos = tf.reduce_sum(y_true[:, :, -8], axis=-1) pos_loc_loss =", "see <http://www.gnu.org/licenses/>. \"\"\"SSD training utils. \"\"\" import tensorflow as tf def _l1_smooth_loss(y_true, y_pred):", "# References https://arxiv.org/abs/1504.08083 \"\"\" abs_loss = tf.abs(y_true - y_pred) sq_loss = 0.5 *", "is distributed in the hope that it will be useful, # but WITHOUT", "released under GPLv3. # OpenEM is free software: you can redistribute it and/or", "of shape (?, num_boxes, 4 + num_classes + 8). # Returns loss: Loss", "= tf.reshape(neg_conf_loss, [batch_size, num_neg_batch]) neg_conf_loss = tf.reduce_sum(neg_conf_loss, axis=1) # loss is sum of", "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public", "__license__ = \"GPLv3\" # This file is part of OpenEM, released under GPLv3.", "of the GNU General Public License # along with OpenEM. If not, see", "in the hope that it will be useful, # but WITHOUT ANY WARRANTY;", "neg_pos_ratio: Max ratio of negative to positive boxes in loss. background_label_id: Id of", "num_boxes). # References https://arxiv.org/abs/1504.08083 \"\"\" abs_loss = tf.abs(y_true - y_pred) sq_loss = 0.5", ":, -8]), k=num_neg_batch) batch_idx = tf.expand_dims(tf.range(0, batch_size), 1) batch_idx = tf.tile(batch_idx, (1, num_neg_batch))", "FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for", "pos_num_neg_mask = tf.greater(num_neg, 0) has_min = tf.to_float(tf.reduce_any(pos_num_neg_mask)) num_neg = tf.concat( axis=0, values=[num_neg, [(1", "and/or modify # it under the terms of the GNU General Public License", "should be penalized or in other words is assigned to some ground truth", "(C) 2018 CVision AI.\" __license__ = \"GPLv3\" # This file is part of", "- has_min) * self.negatives_for_hard]]) num_neg_batch = tf.reduce_min(tf.boolean_mask(num_neg, tf.greater(num_neg, 0))) num_neg_batch = tf.to_int32(num_neg_batch) confs_start", "References https://arxiv.org/abs/1504.08083 \"\"\" abs_loss = tf.abs(y_true - y_pred) sq_loss = 0.5 * (y_true", "class MultiboxLoss: \"\"\"Multibox loss with some helper functions. # Arguments num_classes: Number of", "+ self.background_label_id + 1 confs_end = confs_start + self.num_classes - 1 max_confs =", "background_label_id != 0: raise Exception('Only 0 as background label id is supported') self.background_label_id", "sum of positives and negatives total_loss = pos_conf_loss * self.pos_cost_multiplier + neg_conf_loss total_loss", "Max ratio of negative to positive boxes in loss. background_label_id: Id of background", "= tf.concat( axis=0, values=[num_neg, [(1 - has_min) * self.negatives_for_hard]]) num_neg_batch = tf.reduce_min(tf.boolean_mask(num_neg, tf.greater(num_neg,", ":, confs_start:confs_end], axis=2) _, indices = tf.nn.top_k(max_confs * (1 - y_true[:, :, -8]),", "__init__(self, num_classes, alpha=1.0, neg_pos_ratio=3.0, background_label_id=0, negatives_for_hard=100.0, pos_cost_multiplier=1.0): self.pos_cost_multiplier = pos_cost_multiplier self.num_classes = num_classes", "- y_pred) sq_loss = 0.5 * (y_true - y_pred)**2 l1_loss = tf.where(tf.less(abs_loss, 1.0),", "Predicted logits, tensor of shape (?, num_boxes, 4 + num_classes + 8). #", "\"\"\" import tensorflow as tf def _l1_smooth_loss(y_true, y_pred): \"\"\"Compute L1-smooth loss. # Arguments", "id is supported') self.background_label_id = background_label_id self.negatives_for_hard = negatives_for_hard def compute_loss(self, y_true, y_pred):", "mutlibox loss. # Arguments y_true: Ground truth targets, tensor of shape (?, num_boxes,", "0))) num_neg_batch = tf.to_int32(num_neg_batch) confs_start = 4 + self.background_label_id + 1 confs_end =", "tf.where(tf.less(abs_loss, 1.0), sq_loss, abs_loss - 0.5) return tf.reduce_sum(l1_loss, -1) def _softmax_loss(y_true, y_pred): \"\"\"Compute", "pos_cost_multiplier self.num_classes = num_classes self.alpha = alpha self.neg_pos_ratio = neg_pos_ratio if background_label_id !=", "4). # Returns l1_loss: L1-smooth loss, tensor of shape (?, num_boxes). # References", "num_boxes, 4). y_pred: Predicted bounding boxes, tensor of shape (?, num_boxes, 4). #", "MultiboxLoss: \"\"\"Multibox loss with some helper functions. # Arguments num_classes: Number of classes", "* (1 - y_true[:, :, -8]), k=num_neg_batch) batch_idx = tf.expand_dims(tf.range(0, batch_size), 1) batch_idx", "1e-15), 1e-15) softmax_loss = -tf.reduce_sum(y_true * tf.log(y_pred), axis=-1) return softmax_loss class MultiboxLoss: \"\"\"Multibox", "of negative boxes to consider it there is no positive boxes in batch.", "can redistribute it and/or modify # it under the terms of the GNU", "neg_pos_ratio if background_label_id != 0: raise Exception('Only 0 as background label id is", "= 4 + self.background_label_id + 1 confs_end = confs_start + self.num_classes - 1", "# This program is distributed in the hope that it will be useful,", "= tf.shape(y_true)[0] num_boxes = tf.to_float(tf.shape(y_true)[1]) # loss for all priors conf_loss = _softmax_loss(y_true[:,", "but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or", "of shape (?, num_boxes, 4). y_pred: Predicted bounding boxes, tensor of shape (?,", "4). y_pred: Predicted bounding boxes, tensor of shape (?, num_boxes, 4). # Returns", "loss. neg_pos_ratio: Max ratio of negative to positive boxes in loss. background_label_id: Id", "y_pred: Predicted logits, tensor of shape (?, num_boxes, 4 + num_classes + 8).", "part of OpenEM, released under GPLv3. # OpenEM is free software: you can", "Free Software Foundation, either version 3 of the License, or # any later", "positive boxes in loss. background_label_id: Id of background label. negatives_for_hard: Number of negative", "background. alpha: Weight of L1-smooth loss. neg_pos_ratio: Max ratio of negative to positive", "# get positives loss num_pos = tf.reduce_sum(y_true[:, :, -8], axis=-1) pos_loc_loss = tf.reduce_sum(loc_loss", "- num_pos) pos_num_neg_mask = tf.greater(num_neg, 0) has_min = tf.to_float(tf.reduce_any(pos_num_neg_mask)) num_neg = tf.concat( axis=0,", "-1) def _softmax_loss(y_true, y_pred): \"\"\"Compute softmax loss. # Arguments y_true: Ground truth targets,", "truth box, y_true[:, :, -7:] are all 0. y_pred: Predicted logits, tensor of", "* y_true[:, :, -8], axis=1) # get negatives loss, we penalize only confidence", "= background_label_id self.negatives_for_hard = negatives_for_hard def compute_loss(self, y_true, y_pred): \"\"\"Compute mutlibox loss. #", "truth bounding boxes, tensor of shape (?, num_boxes, 4). y_pred: Predicted bounding boxes,", "terms of the GNU General Public License as published by # the Free", "CVision AI.\" __license__ = \"GPLv3\" # This file is part of OpenEM, released", "GNU General Public License as published by # the Free Software Foundation, either", "# Returns softmax_loss: Softmax loss, tensor of shape (?, num_boxes). \"\"\" y_pred =", "<http://www.gnu.org/licenses/>. \"\"\"SSD training utils. \"\"\" import tensorflow as tf def _l1_smooth_loss(y_true, y_pred): \"\"\"Compute", "\"\"\"Multibox loss with some helper functions. # Arguments num_classes: Number of classes including", "License for more details. # # You should have received a copy of", "num_boxes, 4 + num_classes + 8), priors in ground truth are fictitious, y_true[:,", "shape (?, num_boxes, 4 + num_classes + 8), priors in ground truth are", "Arguments y_true: Ground truth bounding boxes, tensor of shape (?, num_boxes, 4). y_pred:", "(?, num_boxes). \"\"\" y_pred = tf.maximum(tf.minimum(y_pred, 1 - 1e-15), 1e-15) softmax_loss = -tf.reduce_sum(y_true", "(num_pos + tf.to_float(num_neg_batch)) num_pos = tf.where(tf.not_equal(num_pos, 0), num_pos, tf.ones_like(num_pos)) total_loss += (self.alpha *", "-tf.reduce_sum(y_true * tf.log(y_pred), axis=-1) return softmax_loss class MultiboxLoss: \"\"\"Multibox loss with some helper", "logits, tensor of shape (?, num_boxes, num_classes). # Returns softmax_loss: Softmax loss, tensor", "redistribute it and/or modify # it under the terms of the GNU General", "= pos_conf_loss * self.pos_cost_multiplier + neg_conf_loss total_loss /= (num_pos + tf.to_float(num_neg_batch)) num_pos =", "modify # it under the terms of the GNU General Public License as", "boxes in loss. background_label_id: Id of background label. negatives_for_hard: Number of negative boxes", "= pos_cost_multiplier self.num_classes = num_classes self.alpha = alpha self.neg_pos_ratio = neg_pos_ratio if background_label_id", "loss. background_label_id: Id of background label. negatives_for_hard: Number of negative boxes to consider", "0 as background label id is supported') self.background_label_id = background_label_id self.negatives_for_hard = negatives_for_hard", "abs_loss - 0.5) return tf.reduce_sum(l1_loss, -1) def _softmax_loss(y_true, y_pred): \"\"\"Compute softmax loss. #", "is part of OpenEM, released under GPLv3. # OpenEM is free software: you", "neg_pos_ratio=3.0, background_label_id=0, negatives_for_hard=100.0, pos_cost_multiplier=1.0): self.pos_cost_multiplier = pos_cost_multiplier self.num_classes = num_classes self.alpha = alpha", "label. negatives_for_hard: Number of negative boxes to consider it there is no positive", "num_pos, num_boxes - num_pos) pos_num_neg_mask = tf.greater(num_neg, 0) has_min = tf.to_float(tf.reduce_any(pos_num_neg_mask)) num_neg =", "y_true[:, :, -7:] are all 0. y_pred: Predicted logits, tensor of shape (?,", ":, 4:-8], y_pred[:, :, 4:-8]) loc_loss = _l1_smooth_loss(y_true[:, :, :4], y_pred[:, :, :4])", "batch_idx = tf.tile(batch_idx, (1, num_neg_batch)) full_indices = (tf.reshape(batch_idx, [-1]) * tf.to_int32(num_boxes) + tf.reshape(indices,", "tf.to_float(tf.reduce_any(pos_num_neg_mask)) num_neg = tf.concat( axis=0, values=[num_neg, [(1 - has_min) * self.negatives_for_hard]]) num_neg_batch =", "there is no positive boxes in batch. # References https://arxiv.org/abs/1512.02325 \"\"\" def __init__(self,", "+ self.num_classes - 1 max_confs = tf.reduce_max(y_pred[:, :, confs_start:confs_end], axis=2) _, indices =", "is free software: you can redistribute it and/or modify # it under the", "num_neg_batch = tf.reduce_min(tf.boolean_mask(num_neg, tf.greater(num_neg, 0))) num_neg_batch = tf.to_int32(num_neg_batch) confs_start = 4 + self.background_label_id", "shape (?, num_boxes, 4). y_pred: Predicted bounding boxes, tensor of shape (?, num_boxes,", "ground truth box, y_true[:, :, -7:] are all 0. y_pred: Predicted logits, tensor", "4 + num_classes + 8). # Returns loss: Loss for prediction, tensor of", "- 0.5) return tf.reduce_sum(l1_loss, -1) def _softmax_loss(y_true, y_pred): \"\"\"Compute softmax loss. # Arguments", "y_true[:, :, -8] has 1 if prior should be penalized or in other", "tensor of shape (?,). \"\"\" batch_size = tf.shape(y_true)[0] num_boxes = tf.to_float(tf.shape(y_true)[1]) # loss", "\"\"\" def __init__(self, num_classes, alpha=1.0, neg_pos_ratio=3.0, background_label_id=0, negatives_for_hard=100.0, pos_cost_multiplier=1.0): self.pos_cost_multiplier = pos_cost_multiplier self.num_classes", "self.negatives_for_hard = negatives_for_hard def compute_loss(self, y_true, y_pred): \"\"\"Compute mutlibox loss. # Arguments y_true:", "loss. # Arguments y_true: Ground truth targets, tensor of shape (?, num_boxes, 4", "y_true: Ground truth targets, tensor of shape (?, num_boxes, num_classes). y_pred: Predicted logits,", ":, :4], y_pred[:, :, :4]) # get positives loss num_pos = tf.reduce_sum(y_true[:, :,", "* y_true[:, :, -8], axis=1) pos_conf_loss = tf.reduce_sum(conf_loss * y_true[:, :, -8], axis=1)", "version 3 of the License, or # any later version. # # This", "penalize only confidence here num_neg = tf.minimum(self.neg_pos_ratio * num_pos, num_boxes - num_pos) pos_num_neg_mask", "abs_loss = tf.abs(y_true - y_pred) sq_loss = 0.5 * (y_true - y_pred)**2 l1_loss", "-8], axis=1) # get negatives loss, we penalize only confidence here num_neg =", "bounding boxes, tensor of shape (?, num_boxes, 4). # Returns l1_loss: L1-smooth loss,", "batch. # References https://arxiv.org/abs/1512.02325 \"\"\" def __init__(self, num_classes, alpha=1.0, neg_pos_ratio=3.0, background_label_id=0, negatives_for_hard=100.0, pos_cost_multiplier=1.0):", "axis=1) # get negatives loss, we penalize only confidence here num_neg = tf.minimum(self.neg_pos_ratio", "4 + num_classes + 8), priors in ground truth are fictitious, y_true[:, :,", "See the # GNU General Public License for more details. # # You", "y_true, y_pred): \"\"\"Compute mutlibox loss. # Arguments y_true: Ground truth targets, tensor of", "tf.minimum(self.neg_pos_ratio * num_pos, num_boxes - num_pos) pos_num_neg_mask = tf.greater(num_neg, 0) has_min = tf.to_float(tf.reduce_any(pos_num_neg_mask))", "has_min) * self.negatives_for_hard]]) num_neg_batch = tf.reduce_min(tf.boolean_mask(num_neg, tf.greater(num_neg, 0))) num_neg_batch = tf.to_int32(num_neg_batch) confs_start =", "y_pred[:, :, 4:-8]) loc_loss = _l1_smooth_loss(y_true[:, :, :4], y_pred[:, :, :4]) # get", ":, -8], axis=1) pos_conf_loss = tf.reduce_sum(conf_loss * y_true[:, :, -8], axis=1) # get", "y_pred): \"\"\"Compute L1-smooth loss. # Arguments y_true: Ground truth bounding boxes, tensor of", "_l1_smooth_loss(y_true, y_pred): \"\"\"Compute L1-smooth loss. # Arguments y_true: Ground truth bounding boxes, tensor", "4:-8], y_pred[:, :, 4:-8]) loc_loss = _l1_smooth_loss(y_true[:, :, :4], y_pred[:, :, :4]) #", "has_min = tf.to_float(tf.reduce_any(pos_num_neg_mask)) num_neg = tf.concat( axis=0, values=[num_neg, [(1 - has_min) * self.negatives_for_hard]])", "tf.where(tf.not_equal(num_pos, 0), num_pos, tf.ones_like(num_pos)) total_loss += (self.alpha * pos_loc_loss) / num_pos return total_loss", "Public License # along with OpenEM. If not, see <http://www.gnu.org/licenses/>. \"\"\"SSD training utils.", "shape (?,). \"\"\" batch_size = tf.shape(y_true)[0] num_boxes = tf.to_float(tf.shape(y_true)[1]) # loss for all", "Returns loss: Loss for prediction, tensor of shape (?,). \"\"\" batch_size = tf.shape(y_true)[0]", "License as published by # the Free Software Foundation, either version 3 of", "_softmax_loss(y_true, y_pred): \"\"\"Compute softmax loss. # Arguments y_true: Ground truth targets, tensor of", "0. y_pred: Predicted logits, tensor of shape (?, num_boxes, 4 + num_classes +", "\"\"\" batch_size = tf.shape(y_true)[0] num_boxes = tf.to_float(tf.shape(y_true)[1]) # loss for all priors conf_loss", "General Public License # along with OpenEM. If not, see <http://www.gnu.org/licenses/>. \"\"\"SSD training", "+ neg_conf_loss total_loss /= (num_pos + tf.to_float(num_neg_batch)) num_pos = tf.where(tf.not_equal(num_pos, 0), num_pos, tf.ones_like(num_pos))", "-8], axis=-1) pos_loc_loss = tf.reduce_sum(loc_loss * y_true[:, :, -8], axis=1) pos_conf_loss = tf.reduce_sum(conf_loss", "as published by # the Free Software Foundation, either version 3 of the", "self.negatives_for_hard]]) num_neg_batch = tf.reduce_min(tf.boolean_mask(num_neg, tf.greater(num_neg, 0))) num_neg_batch = tf.to_int32(num_neg_batch) confs_start = 4 +", "l1_loss: L1-smooth loss, tensor of shape (?, num_boxes). # References https://arxiv.org/abs/1504.08083 \"\"\" abs_loss", "shape (?, num_boxes). # References https://arxiv.org/abs/1504.08083 \"\"\" abs_loss = tf.abs(y_true - y_pred) sq_loss", "l1_loss = tf.where(tf.less(abs_loss, 1.0), sq_loss, abs_loss - 0.5) return tf.reduce_sum(l1_loss, -1) def _softmax_loss(y_true,", "-7:] are all 0. y_pred: Predicted logits, tensor of shape (?, num_boxes, 4", "tf.reduce_max(y_pred[:, :, confs_start:confs_end], axis=2) _, indices = tf.nn.top_k(max_confs * (1 - y_true[:, :,", "with some helper functions. # Arguments num_classes: Number of classes including background. alpha:", "= tf.where(tf.not_equal(num_pos, 0), num_pos, tf.ones_like(num_pos)) total_loss += (self.alpha * pos_loc_loss) / num_pos return", "ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR", "later version. # # This program is distributed in the hope that it", "num_boxes, num_classes). # Returns softmax_loss: Softmax loss, tensor of shape (?, num_boxes). \"\"\"", "y_pred)**2 l1_loss = tf.where(tf.less(abs_loss, 1.0), sq_loss, abs_loss - 0.5) return tf.reduce_sum(l1_loss, -1) def", "of OpenEM, released under GPLv3. # OpenEM is free software: you can redistribute", "+ 1 confs_end = confs_start + self.num_classes - 1 max_confs = tf.reduce_max(y_pred[:, :,", "positives loss num_pos = tf.reduce_sum(y_true[:, :, -8], axis=-1) pos_loc_loss = tf.reduce_sum(loc_loss * y_true[:,", "- 1e-15), 1e-15) softmax_loss = -tf.reduce_sum(y_true * tf.log(y_pred), axis=-1) return softmax_loss class MultiboxLoss:", "(?, num_boxes, 4). y_pred: Predicted bounding boxes, tensor of shape (?, num_boxes, 4).", "OpenEM is free software: you can redistribute it and/or modify # it under", "WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS", "# Arguments y_true: Ground truth targets, tensor of shape (?, num_boxes, num_classes). y_pred:", "# # You should have received a copy of the GNU General Public", "# loss is sum of positives and negatives total_loss = pos_conf_loss * self.pos_cost_multiplier", "negatives_for_hard=100.0, pos_cost_multiplier=1.0): self.pos_cost_multiplier = pos_cost_multiplier self.num_classes = num_classes self.alpha = alpha self.neg_pos_ratio =", "background_label_id self.negatives_for_hard = negatives_for_hard def compute_loss(self, y_true, y_pred): \"\"\"Compute mutlibox loss. # Arguments", "negatives_for_hard: Number of negative boxes to consider it there is no positive boxes", "1e-15) softmax_loss = -tf.reduce_sum(y_true * tf.log(y_pred), axis=-1) return softmax_loss class MultiboxLoss: \"\"\"Multibox loss", "Software Foundation, either version 3 of the License, or # any later version.", "conf_loss = _softmax_loss(y_true[:, :, 4:-8], y_pred[:, :, 4:-8]) loc_loss = _l1_smooth_loss(y_true[:, :, :4],", "FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more", "self.pos_cost_multiplier + neg_conf_loss total_loss /= (num_pos + tf.to_float(num_neg_batch)) num_pos = tf.where(tf.not_equal(num_pos, 0), num_pos,", "# This file is part of OpenEM, released under GPLv3. # OpenEM is", "num_pos = tf.reduce_sum(y_true[:, :, -8], axis=-1) pos_loc_loss = tf.reduce_sum(loc_loss * y_true[:, :, -8],", "have received a copy of the GNU General Public License # along with", "(?,). \"\"\" batch_size = tf.shape(y_true)[0] num_boxes = tf.to_float(tf.shape(y_true)[1]) # loss for all priors", "Arguments num_classes: Number of classes including background. alpha: Weight of L1-smooth loss. neg_pos_ratio:", "of shape (?, num_boxes). # References https://arxiv.org/abs/1504.08083 \"\"\" abs_loss = tf.abs(y_true - y_pred)", "Public License for more details. # # You should have received a copy", "Exception('Only 0 as background label id is supported') self.background_label_id = background_label_id self.negatives_for_hard =", "License, or # any later version. # # This program is distributed in", "negatives total_loss = pos_conf_loss * self.pos_cost_multiplier + neg_conf_loss total_loss /= (num_pos + tf.to_float(num_neg_batch))", ":, -8], axis=-1) pos_loc_loss = tf.reduce_sum(loc_loss * y_true[:, :, -8], axis=1) pos_conf_loss =", "y_pred): \"\"\"Compute mutlibox loss. # Arguments y_true: Ground truth targets, tensor of shape", "axis=0, values=[num_neg, [(1 - has_min) * self.negatives_for_hard]]) num_neg_batch = tf.reduce_min(tf.boolean_mask(num_neg, tf.greater(num_neg, 0))) num_neg_batch", "Foundation, either version 3 of the License, or # any later version. #", "fictitious, y_true[:, :, -8] has 1 if prior should be penalized or in", "y_pred) sq_loss = 0.5 * (y_true - y_pred)**2 l1_loss = tf.where(tf.less(abs_loss, 1.0), sq_loss,", "full_indices = (tf.reshape(batch_idx, [-1]) * tf.to_int32(num_boxes) + tf.reshape(indices, [-1])) # full_indices = tf.concat(2,", "self.num_classes = num_classes self.alpha = alpha self.neg_pos_ratio = neg_pos_ratio if background_label_id != 0:", "0.5 * (y_true - y_pred)**2 l1_loss = tf.where(tf.less(abs_loss, 1.0), sq_loss, abs_loss - 0.5)", "tf.reshape(neg_conf_loss, [batch_size, num_neg_batch]) neg_conf_loss = tf.reduce_sum(neg_conf_loss, axis=1) # loss is sum of positives", "num_neg_batch = tf.to_int32(num_neg_batch) confs_start = 4 + self.background_label_id + 1 confs_end = confs_start", "positive boxes in batch. # References https://arxiv.org/abs/1512.02325 \"\"\" def __init__(self, num_classes, alpha=1.0, neg_pos_ratio=3.0,", "= tf.where(tf.less(abs_loss, 1.0), sq_loss, abs_loss - 0.5) return tf.reduce_sum(l1_loss, -1) def _softmax_loss(y_true, y_pred):", "(?, num_boxes, num_classes). y_pred: Predicted logits, tensor of shape (?, num_boxes, num_classes). #", "of shape (?, num_boxes). \"\"\" y_pred = tf.maximum(tf.minimum(y_pred, 1 - 1e-15), 1e-15) softmax_loss", "(?, num_boxes). # References https://arxiv.org/abs/1504.08083 \"\"\" abs_loss = tf.abs(y_true - y_pred) sq_loss =", "batch_size), 1) batch_idx = tf.tile(batch_idx, (1, num_neg_batch)) full_indices = (tf.reshape(batch_idx, [-1]) * tf.to_int32(num_boxes)", "num_classes + 8). # Returns loss: Loss for prediction, tensor of shape (?,).", "tf.reshape(indices, [-1])) # full_indices = tf.concat(2, [tf.expand_dims(batch_idx, 2), # tf.expand_dims(indices, 2)]) # neg_conf_loss", "1) batch_idx = tf.tile(batch_idx, (1, num_neg_batch)) full_indices = (tf.reshape(batch_idx, [-1]) * tf.to_int32(num_boxes) +", "# any later version. # # This program is distributed in the hope", "= tf.to_float(tf.shape(y_true)[1]) # loss for all priors conf_loss = _softmax_loss(y_true[:, :, 4:-8], y_pred[:,", "get positives loss num_pos = tf.reduce_sum(y_true[:, :, -8], axis=-1) pos_loc_loss = tf.reduce_sum(loc_loss *", "will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty", "GPLv3. # OpenEM is free software: you can redistribute it and/or modify #", "AI.\" __license__ = \"GPLv3\" # This file is part of OpenEM, released under", "background label. negatives_for_hard: Number of negative boxes to consider it there is no", "num_boxes = tf.to_float(tf.shape(y_true)[1]) # loss for all priors conf_loss = _softmax_loss(y_true[:, :, 4:-8],", "\"GPLv3\" # This file is part of OpenEM, released under GPLv3. # OpenEM", "+ 8). # Returns loss: Loss for prediction, tensor of shape (?,). \"\"\"", "truth targets, tensor of shape (?, num_boxes, num_classes). y_pred: Predicted logits, tensor of", "= tf.reduce_sum(conf_loss * y_true[:, :, -8], axis=1) # get negatives loss, we penalize", "def compute_loss(self, y_true, y_pred): \"\"\"Compute mutlibox loss. # Arguments y_true: Ground truth targets,", "y_pred): \"\"\"Compute softmax loss. # Arguments y_true: Ground truth targets, tensor of shape", "supported') self.background_label_id = background_label_id self.negatives_for_hard = negatives_for_hard def compute_loss(self, y_true, y_pred): \"\"\"Compute mutlibox", "y_true[:, :, -8], axis=1) pos_conf_loss = tf.reduce_sum(conf_loss * y_true[:, :, -8], axis=1) #", "num_classes self.alpha = alpha self.neg_pos_ratio = neg_pos_ratio if background_label_id != 0: raise Exception('Only", "# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY", "= tf.reduce_max(y_pred[:, :, confs_start:confs_end], axis=2) _, indices = tf.nn.top_k(max_confs * (1 - y_true[:,", "classes including background. alpha: Weight of L1-smooth loss. neg_pos_ratio: Max ratio of negative", "# Arguments y_true: Ground truth bounding boxes, tensor of shape (?, num_boxes, 4).", "= confs_start + self.num_classes - 1 max_confs = tf.reduce_max(y_pred[:, :, confs_start:confs_end], axis=2) _,", "sq_loss = 0.5 * (y_true - y_pred)**2 l1_loss = tf.where(tf.less(abs_loss, 1.0), sq_loss, abs_loss", "OpenEM, released under GPLv3. # OpenEM is free software: you can redistribute it", "with OpenEM. If not, see <http://www.gnu.org/licenses/>. \"\"\"SSD training utils. \"\"\" import tensorflow as" ]
[ "return self._open_timeout @open_timeout.setter def open_timeout(self, open_timeout): if isinstance(open_timeout, (float, int)): self._open_timeout = open_timeout", "= <PASSWORD> _timeout = None _open_timeout = None _read_timeout = None _default_header =", "tuple): (open_timeout, read_timeout) = self._timeout else: open_timeout = read_timeout = self._timeout if self._open_timeout", "open_timeout = self._open_timeout if self._read_timeout is not None: read_timeout = self._read_timeout if open_timeout", "'basic' username = None password = <PASSWORD> _timeout = None _open_timeout = None", "timeout): if isinstance(timeout, (float, int, tuple)): self._timeout = timeout else: raise ValueError('timeout must", "self._site.username: self.username = self._site.username if self._site.password: self.password = <PASSWORD> @property def auth_type(self): return", "= timeout else: raise ValueError('timeout must be an instance of float, int or", "build_request_headers(self, headers, method): result = {} result.update(self.default_header) result.update(self.http_format_header(method)) result.update(headers) return result def http_format_header(self,", "{} return self._default_header @default_header.setter def default_header(self, default_header): self._default_header = default_header def build_request_headers(self, headers,", "'Accept', 'HEAD': 'Accept', } class Connection(object): _site = None _format = None _auth_type", "def patch(self, path, **kwargs): return self._request('PATCH', path, **kwargs) def put(self, path, **kwargs): return", "int, tuple)): self._timeout = timeout else: raise ValueError('timeout must be an instance of", "requests.auth.HTTPBasicAuth if self._auth_type == 'digest': auth_class = requests.auth.HTTPDigestAuth kwargs['auth'] = auth_class(self.username, self.password) if", "tuple') @property def open_timeout(self): return self._open_timeout @open_timeout.setter def open_timeout(self, open_timeout): if isinstance(open_timeout, (float,", "int)): self._open_timeout = open_timeout else: raise ValueError('open_timeout must be an instance of float", "**kwargs): kwargs['headers'] = self.build_request_headers(kwargs.get('headers', {}), method) if self.username and self.password: if self._auth_type ==", "auth_type(self, auth_type): if auth_type in ['basic', 'digest']: self._auth_type = auth_type else: raise ValueError(\"auth_type", "not None: read_timeout = self._read_timeout if open_timeout or read_timeout: kwargs['timeout'] = (open_timeout, read_timeout)", "port=self._site.port, path=path) response = requests.request(method, url, **kwargs) return response @property def default_header(self): if", "activerest.formats.json_format import requests from furl import furl HTTP_FORMAT_HEADER_NAMES = { 'GET': 'Accept', 'PUT':", "'basic' or 'digest'\") @property def timeout(self): return self._timeout @timeout.setter def timeout(self, timeout): if", "self._read_timeout is not None: read_timeout = self._read_timeout if open_timeout or read_timeout: kwargs['timeout'] =", "if self._timeout is not None: if isinstance(self._timeout, tuple): (open_timeout, read_timeout) = self._timeout else:", "requests.request(method, url, **kwargs) return response @property def default_header(self): if self._default_header: return self._default_header self._default_header", "= None _open_timeout = None _read_timeout = None _default_header = None proxies =", "{ 'GET': 'Accept', 'PUT': 'Content-Type', 'POST': 'Content-Type', 'PATCH': 'Content-Type', 'DELETE': 'Accept', 'HEAD': 'Accept',", "= [] def __init__(self, site, format=activerest.formats.json_format): self.site = site self.format = format @property", "float, int or tuple') @property def open_timeout(self): return self._open_timeout @open_timeout.setter def open_timeout(self, open_timeout):", "path, **kwargs): return self._request('PUT', path, **kwargs) def post(self, path, **kwargs): return self._request('POST', path,", "delete(self, path, **kwargs): return self._request('DELETE', path, **kwargs) def patch(self, path, **kwargs): return self._request('PATCH',", "path, **kwargs) def head(self, path, **kwargs): return self._request('HEAD', path, **kwargs) def _request(self, method,", "= None _default_header = None proxies = None requests = [] def __init__(self,", "instance of float, int or tuple') @property def open_timeout(self): return self._open_timeout @open_timeout.setter def", "if isinstance(timeout, (float, int, tuple)): self._timeout = timeout else: raise ValueError('timeout must be", "def __init__(self, site, format=activerest.formats.json_format): self.site = site self.format = format @property def site(self):", "def auth_type(self, auth_type): if auth_type in ['basic', 'digest']: self._auth_type = auth_type else: raise", "kwargs['auth'] = auth_class(self.username, self.password) if self.proxies: kwargs['proxies'] = self.proxies open_timeout = read_timeout =", "= self._timeout else: open_timeout = read_timeout = self._timeout if self._open_timeout is not None:", "requests from furl import furl HTTP_FORMAT_HEADER_NAMES = { 'GET': 'Accept', 'PUT': 'Content-Type', 'POST':", "def open_timeout(self): return self._open_timeout @open_timeout.setter def open_timeout(self, open_timeout): if isinstance(open_timeout, (float, int)): self._open_timeout", "site else: self._site = furl(site) if self._site.username: self.username = self._site.username if self._site.password: self.password", "self._request('GET', path, **kwargs) def delete(self, path, **kwargs): return self._request('DELETE', path, **kwargs) def patch(self,", "self._read_timeout = read_timeout else: raise ValueError('read_timeout must be an instance of float or", "auth_class(self.username, self.password) if self.proxies: kwargs['proxies'] = self.proxies open_timeout = read_timeout = None if", "= self._timeout if self._open_timeout is not None: open_timeout = self._open_timeout if self._read_timeout is", "self._timeout else: open_timeout = read_timeout = self._timeout if self._open_timeout is not None: open_timeout", "tuple)): self._timeout = timeout else: raise ValueError('timeout must be an instance of float,", "read_timeout) = self._timeout else: open_timeout = read_timeout = self._timeout if self._open_timeout is not", "'HEAD': 'Accept', } class Connection(object): _site = None _format = None _auth_type =", "None: read_timeout = self._read_timeout if open_timeout or read_timeout: kwargs['timeout'] = (open_timeout, read_timeout) url", "put(self, path, **kwargs): return self._request('PUT', path, **kwargs) def post(self, path, **kwargs): return self._request('POST',", "**kwargs): return self._request('GET', path, **kwargs) def delete(self, path, **kwargs): return self._request('DELETE', path, **kwargs)", "def post(self, path, **kwargs): return self._request('POST', path, **kwargs) def head(self, path, **kwargs): return", "be 'basic' or 'digest'\") @property def timeout(self): return self._timeout @timeout.setter def timeout(self, timeout):", "response = requests.request(method, url, **kwargs) return response @property def default_header(self): if self._default_header: return", "float or int') def get(self, path, **kwargs): return self._request('GET', path, **kwargs) def delete(self,", "@timeout.setter def timeout(self, timeout): if isinstance(timeout, (float, int, tuple)): self._timeout = timeout else:", "= site self.format = format @property def site(self): return self._site @site.setter def site(self,", "**kwargs): return self._request('PATCH', path, **kwargs) def put(self, path, **kwargs): return self._request('PUT', path, **kwargs)", "**kwargs) return response @property def default_header(self): if self._default_header: return self._default_header self._default_header = {}", "path, **kwargs): return self._request('GET', path, **kwargs) def delete(self, path, **kwargs): return self._request('DELETE', path,", "int') def get(self, path, **kwargs): return self._request('GET', path, **kwargs) def delete(self, path, **kwargs):", "_read_timeout = None _default_header = None proxies = None requests = [] def", "**kwargs) def _request(self, method, path, **kwargs): kwargs['headers'] = self.build_request_headers(kwargs.get('headers', {}), method) if self.username", "= None requests = [] def __init__(self, site, format=activerest.formats.json_format): self.site = site self.format", "if self._auth_type == 'digest': auth_class = requests.auth.HTTPDigestAuth kwargs['auth'] = auth_class(self.username, self.password) if self.proxies:", "@read_timeout.setter def read_timeout(self, read_timeout): if isinstance(read_timeout, (float, int)): self._read_timeout = read_timeout else: raise", "float or int') @property def read_timeout(self): return self._read_timeout @read_timeout.setter def read_timeout(self, read_timeout): if", "timeout else: raise ValueError('timeout must be an instance of float, int or tuple')", "is not None: open_timeout = self._open_timeout if self._read_timeout is not None: read_timeout =", "def timeout(self, timeout): if isinstance(timeout, (float, int, tuple)): self._timeout = timeout else: raise", "'digest'\") @property def timeout(self): return self._timeout @timeout.setter def timeout(self, timeout): if isinstance(timeout, (float,", "response @property def default_header(self): if self._default_header: return self._default_header self._default_header = {} return self._default_header", "= self._open_timeout if self._read_timeout is not None: read_timeout = self._read_timeout if open_timeout or", "**kwargs) def post(self, path, **kwargs): return self._request('POST', path, **kwargs) def head(self, path, **kwargs):", "**kwargs): return self._request('HEAD', path, **kwargs) def _request(self, method, path, **kwargs): kwargs['headers'] = self.build_request_headers(kwargs.get('headers',", "self._default_header @default_header.setter def default_header(self, default_header): self._default_header = default_header def build_request_headers(self, headers, method): result", "read_timeout = self._timeout if self._open_timeout is not None: open_timeout = self._open_timeout if self._read_timeout", "instance of float or int') @property def read_timeout(self): return self._read_timeout @read_timeout.setter def read_timeout(self,", "@property def timeout(self): return self._timeout @timeout.setter def timeout(self, timeout): if isinstance(timeout, (float, int,", "self._open_timeout @open_timeout.setter def open_timeout(self, open_timeout): if isinstance(open_timeout, (float, int)): self._open_timeout = open_timeout else:", "if self._open_timeout is not None: open_timeout = self._open_timeout if self._read_timeout is not None:", "auth_class = requests.auth.HTTPDigestAuth kwargs['auth'] = auth_class(self.username, self.password) if self.proxies: kwargs['proxies'] = self.proxies open_timeout", "method): result = {} result.update(self.default_header) result.update(self.http_format_header(method)) result.update(headers) return result def http_format_header(self, method): return", "path, **kwargs): return self._request('POST', path, **kwargs) def head(self, path, **kwargs): return self._request('HEAD', path,", "return response @property def default_header(self): if self._default_header: return self._default_header self._default_header = {} return", "self.username and self.password: if self._auth_type == 'basic': auth_class = requests.auth.HTTPBasicAuth if self._auth_type ==", "@open_timeout.setter def open_timeout(self, open_timeout): if isinstance(open_timeout, (float, int)): self._open_timeout = open_timeout else: raise", "self._request('DELETE', path, **kwargs) def patch(self, path, **kwargs): return self._request('PATCH', path, **kwargs) def put(self,", "None _auth_type = 'basic' username = None password = <PASSWORD> _timeout = None", "be an instance of float, int or tuple') @property def open_timeout(self): return self._open_timeout", "def _request(self, method, path, **kwargs): kwargs['headers'] = self.build_request_headers(kwargs.get('headers', {}), method) if self.username and", "self._request('HEAD', path, **kwargs) def _request(self, method, path, **kwargs): kwargs['headers'] = self.build_request_headers(kwargs.get('headers', {}), method)", "open_timeout = read_timeout = self._timeout if self._open_timeout is not None: open_timeout = self._open_timeout", "if self._auth_type == 'basic': auth_class = requests.auth.HTTPBasicAuth if self._auth_type == 'digest': auth_class =", "furl(site) if self._site.username: self.username = self._site.username if self._site.password: self.password = <PASSWORD> @property def", "self._auth_type @auth_type.setter def auth_type(self, auth_type): if auth_type in ['basic', 'digest']: self._auth_type = auth_type", "if self._read_timeout is not None: read_timeout = self._read_timeout if open_timeout or read_timeout: kwargs['timeout']", "if isinstance(open_timeout, (float, int)): self._open_timeout = open_timeout else: raise ValueError('open_timeout must be an", "return self._request('PATCH', path, **kwargs) def put(self, path, **kwargs): return self._request('PUT', path, **kwargs) def", "== 'digest': auth_class = requests.auth.HTTPDigestAuth kwargs['auth'] = auth_class(self.username, self.password) if self.proxies: kwargs['proxies'] =", "def build_request_headers(self, headers, method): result = {} result.update(self.default_header) result.update(self.http_format_header(method)) result.update(headers) return result def", "None _read_timeout = None _default_header = None proxies = None requests = []", "if self._site.username: self.username = self._site.username if self._site.password: self.password = <PASSWORD> @property def auth_type(self):", "self._site = furl(site) if self._site.username: self.username = self._site.username if self._site.password: self.password = <PASSWORD>", "'DELETE': 'Accept', 'HEAD': 'Accept', } class Connection(object): _site = None _format = None", "@property def read_timeout(self): return self._read_timeout @read_timeout.setter def read_timeout(self, read_timeout): if isinstance(read_timeout, (float, int)):", "@default_header.setter def default_header(self, default_header): self._default_header = default_header def build_request_headers(self, headers, method): result =", "None password = <PASSWORD> _timeout = None _open_timeout = None _read_timeout = None", "if self.username and self.password: if self._auth_type == 'basic': auth_class = requests.auth.HTTPBasicAuth if self._auth_type", "default_header def build_request_headers(self, headers, method): result = {} result.update(self.default_header) result.update(self.http_format_header(method)) result.update(headers) return result", "path, **kwargs) def _request(self, method, path, **kwargs): kwargs['headers'] = self.build_request_headers(kwargs.get('headers', {}), method) if", "'PATCH': 'Content-Type', 'DELETE': 'Accept', 'HEAD': 'Accept', } class Connection(object): _site = None _format", "patch(self, path, **kwargs): return self._request('PATCH', path, **kwargs) def put(self, path, **kwargs): return self._request('PUT',", "'Accept', 'PUT': 'Content-Type', 'POST': 'Content-Type', 'PATCH': 'Content-Type', 'DELETE': 'Accept', 'HEAD': 'Accept', } class", "not None: if isinstance(self._timeout, tuple): (open_timeout, read_timeout) = self._timeout else: open_timeout = read_timeout", "self._open_timeout is not None: open_timeout = self._open_timeout if self._read_timeout is not None: read_timeout", "url = furl().set(scheme=self._site.scheme, host=self._site.host, port=self._site.port, path=path) response = requests.request(method, url, **kwargs) return response", "raise ValueError('timeout must be an instance of float, int or tuple') @property def", "self._request('PATCH', path, **kwargs) def put(self, path, **kwargs): return self._request('PUT', path, **kwargs) def post(self,", "(float, int)): self._open_timeout = open_timeout else: raise ValueError('open_timeout must be an instance of", "host=self._site.host, port=self._site.port, path=path) response = requests.request(method, url, **kwargs) return response @property def default_header(self):", "read_timeout): if isinstance(read_timeout, (float, int)): self._read_timeout = read_timeout else: raise ValueError('read_timeout must be", "path, **kwargs): return self._request('HEAD', path, **kwargs) def _request(self, method, path, **kwargs): kwargs['headers'] =", "read_timeout(self, read_timeout): if isinstance(read_timeout, (float, int)): self._read_timeout = read_timeout else: raise ValueError('read_timeout must", "path=path) response = requests.request(method, url, **kwargs) return response @property def default_header(self): if self._default_header:", "is not None: read_timeout = self._read_timeout if open_timeout or read_timeout: kwargs['timeout'] = (open_timeout,", "username = None password = <PASSWORD> _timeout = None _open_timeout = None _read_timeout", "self._timeout is not None: if isinstance(self._timeout, tuple): (open_timeout, read_timeout) = self._timeout else: open_timeout", "return self._default_header self._default_header = {} return self._default_header @default_header.setter def default_header(self, default_header): self._default_header =", "an instance of float, int or tuple') @property def open_timeout(self): return self._open_timeout @open_timeout.setter", "= {} return self._default_header @default_header.setter def default_header(self, default_header): self._default_header = default_header def build_request_headers(self,", "raise ValueError('read_timeout must be an instance of float or int') def get(self, path,", "path, **kwargs) def post(self, path, **kwargs): return self._request('POST', path, **kwargs) def head(self, path,", "= site else: self._site = furl(site) if self._site.username: self.username = self._site.username if self._site.password:", "= format @property def site(self): return self._site @site.setter def site(self, site): if isinstance(self._site,", "isinstance(timeout, (float, int, tuple)): self._timeout = timeout else: raise ValueError('timeout must be an", "default_header): self._default_header = default_header def build_request_headers(self, headers, method): result = {} result.update(self.default_header) result.update(self.http_format_header(method))", "auth_type(self): return self._auth_type @auth_type.setter def auth_type(self, auth_type): if auth_type in ['basic', 'digest']: self._auth_type", "if self._site.password: self.password = <PASSWORD> @property def auth_type(self): return self._auth_type @auth_type.setter def auth_type(self,", "def site(self): return self._site @site.setter def site(self, site): if isinstance(self._site, furl): self._site =", "read_timeout) url = furl().set(scheme=self._site.scheme, host=self._site.host, port=self._site.port, path=path) response = requests.request(method, url, **kwargs) return", "read_timeout else: raise ValueError('read_timeout must be an instance of float or int') def", "self._default_header = default_header def build_request_headers(self, headers, method): result = {} result.update(self.default_header) result.update(self.http_format_header(method)) result.update(headers)", "self._request('PUT', path, **kwargs) def post(self, path, **kwargs): return self._request('POST', path, **kwargs) def head(self,", "'Content-Type', 'PATCH': 'Content-Type', 'DELETE': 'Accept', 'HEAD': 'Accept', } class Connection(object): _site = None", "of float, int or tuple') @property def open_timeout(self): return self._open_timeout @open_timeout.setter def open_timeout(self,", "= 'basic' username = None password = <PASSWORD> _timeout = None _open_timeout =", "of float or int') def get(self, path, **kwargs): return self._request('GET', path, **kwargs) def", "def head(self, path, **kwargs): return self._request('HEAD', path, **kwargs) def _request(self, method, path, **kwargs):", "= furl().set(scheme=self._site.scheme, host=self._site.host, port=self._site.port, path=path) response = requests.request(method, url, **kwargs) return response @property", "self.password: if self._auth_type == 'basic': auth_class = requests.auth.HTTPBasicAuth if self._auth_type == 'digest': auth_class", "or tuple') @property def open_timeout(self): return self._open_timeout @open_timeout.setter def open_timeout(self, open_timeout): if isinstance(open_timeout,", "path, **kwargs): return self._request('PATCH', path, **kwargs) def put(self, path, **kwargs): return self._request('PUT', path,", "== 'basic': auth_class = requests.auth.HTTPBasicAuth if self._auth_type == 'digest': auth_class = requests.auth.HTTPDigestAuth kwargs['auth']", "def get(self, path, **kwargs): return self._request('GET', path, **kwargs) def delete(self, path, **kwargs): return", "@site.setter def site(self, site): if isinstance(self._site, furl): self._site = site else: self._site =", "timeout(self, timeout): if isinstance(timeout, (float, int, tuple)): self._timeout = timeout else: raise ValueError('timeout", "or int') def get(self, path, **kwargs): return self._request('GET', path, **kwargs) def delete(self, path,", "proxies = None requests = [] def __init__(self, site, format=activerest.formats.json_format): self.site = site", "head(self, path, **kwargs): return self._request('HEAD', path, **kwargs) def _request(self, method, path, **kwargs): kwargs['headers']", "None _default_header = None proxies = None requests = [] def __init__(self, site,", "'digest']: self._auth_type = auth_type else: raise ValueError(\"auth_type must be 'basic' or 'digest'\") @property", "and self.password: if self._auth_type == 'basic': auth_class = requests.auth.HTTPBasicAuth if self._auth_type == 'digest':", "furl().set(scheme=self._site.scheme, host=self._site.host, port=self._site.port, path=path) response = requests.request(method, url, **kwargs) return response @property def", "Connection(object): _site = None _format = None _auth_type = 'basic' username = None", "self._timeout = timeout else: raise ValueError('timeout must be an instance of float, int", "get(self, path, **kwargs): return self._request('GET', path, **kwargs) def delete(self, path, **kwargs): return self._request('DELETE',", "self.username = self._site.username if self._site.password: self.password = <PASSWORD> @property def auth_type(self): return self._auth_type", "read_timeout = None if self._timeout is not None: if isinstance(self._timeout, tuple): (open_timeout, read_timeout)", "url, **kwargs) return response @property def default_header(self): if self._default_header: return self._default_header self._default_header =", "def default_header(self, default_header): self._default_header = default_header def build_request_headers(self, headers, method): result = {}", "= requests.request(method, url, **kwargs) return response @property def default_header(self): if self._default_header: return self._default_header", "auth_type): if auth_type in ['basic', 'digest']: self._auth_type = auth_type else: raise ValueError(\"auth_type must", "self._auth_type == 'basic': auth_class = requests.auth.HTTPBasicAuth if self._auth_type == 'digest': auth_class = requests.auth.HTTPDigestAuth", "**kwargs): return self._request('POST', path, **kwargs) def head(self, path, **kwargs): return self._request('HEAD', path, **kwargs)", "= default_header def build_request_headers(self, headers, method): result = {} result.update(self.default_header) result.update(self.http_format_header(method)) result.update(headers) return", "open_timeout = read_timeout = None if self._timeout is not None: if isinstance(self._timeout, tuple):", "instance of float or int') def get(self, path, **kwargs): return self._request('GET', path, **kwargs)", "must be 'basic' or 'digest'\") @property def timeout(self): return self._timeout @timeout.setter def timeout(self,", "None if self._timeout is not None: if isinstance(self._timeout, tuple): (open_timeout, read_timeout) = self._timeout", "post(self, path, **kwargs): return self._request('POST', path, **kwargs) def head(self, path, **kwargs): return self._request('HEAD',", "= open_timeout else: raise ValueError('open_timeout must be an instance of float or int')", "__init__(self, site, format=activerest.formats.json_format): self.site = site self.format = format @property def site(self): return", "format @property def site(self): return self._site @site.setter def site(self, site): if isinstance(self._site, furl):", "else: raise ValueError('read_timeout must be an instance of float or int') def get(self,", "= read_timeout else: raise ValueError('read_timeout must be an instance of float or int')", "if open_timeout or read_timeout: kwargs['timeout'] = (open_timeout, read_timeout) url = furl().set(scheme=self._site.scheme, host=self._site.host, port=self._site.port,", "timeout(self): return self._timeout @timeout.setter def timeout(self, timeout): if isinstance(timeout, (float, int, tuple)): self._timeout", "if self._default_header: return self._default_header self._default_header = {} return self._default_header @default_header.setter def default_header(self, default_header):", "= requests.auth.HTTPDigestAuth kwargs['auth'] = auth_class(self.username, self.password) if self.proxies: kwargs['proxies'] = self.proxies open_timeout =", "ValueError('read_timeout must be an instance of float or int') def get(self, path, **kwargs):", "result = {} result.update(self.default_header) result.update(self.http_format_header(method)) result.update(headers) return result def http_format_header(self, method): return {", "(float, int)): self._read_timeout = read_timeout else: raise ValueError('read_timeout must be an instance of", "def default_header(self): if self._default_header: return self._default_header self._default_header = {} return self._default_header @default_header.setter def", "@property def auth_type(self): return self._auth_type @auth_type.setter def auth_type(self, auth_type): if auth_type in ['basic',", "_auth_type = 'basic' username = None password = <PASSWORD> _timeout = None _open_timeout", "def site(self, site): if isinstance(self._site, furl): self._site = site else: self._site = furl(site)", "return self._request('DELETE', path, **kwargs) def patch(self, path, **kwargs): return self._request('PATCH', path, **kwargs) def", "= None _auth_type = 'basic' username = None password = <PASSWORD> _timeout =", "= read_timeout = self._timeout if self._open_timeout is not None: open_timeout = self._open_timeout if", "= (open_timeout, read_timeout) url = furl().set(scheme=self._site.scheme, host=self._site.host, port=self._site.port, path=path) response = requests.request(method, url,", "self._default_header self._default_header = {} return self._default_header @default_header.setter def default_header(self, default_header): self._default_header = default_header", "['basic', 'digest']: self._auth_type = auth_type else: raise ValueError(\"auth_type must be 'basic' or 'digest'\")", "be an instance of float or int') def get(self, path, **kwargs): return self._request('GET',", "requests = [] def __init__(self, site, format=activerest.formats.json_format): self.site = site self.format = format", "open_timeout): if isinstance(open_timeout, (float, int)): self._open_timeout = open_timeout else: raise ValueError('open_timeout must be", "result.update(self.default_header) result.update(self.http_format_header(method)) result.update(headers) return result def http_format_header(self, method): return { HTTP_FORMAT_HEADER_NAMES[method]: self.format.mime_type(), }", "self._site = site else: self._site = furl(site) if self._site.username: self.username = self._site.username if", "method, path, **kwargs): kwargs['headers'] = self.build_request_headers(kwargs.get('headers', {}), method) if self.username and self.password: if", "return self._request('PUT', path, **kwargs) def post(self, path, **kwargs): return self._request('POST', path, **kwargs) def", "from furl import furl HTTP_FORMAT_HEADER_NAMES = { 'GET': 'Accept', 'PUT': 'Content-Type', 'POST': 'Content-Type',", "import requests from furl import furl HTTP_FORMAT_HEADER_NAMES = { 'GET': 'Accept', 'PUT': 'Content-Type',", "None _open_timeout = None _read_timeout = None _default_header = None proxies = None", "isinstance(read_timeout, (float, int)): self._read_timeout = read_timeout else: raise ValueError('read_timeout must be an instance", "must be an instance of float, int or tuple') @property def open_timeout(self): return", "{} result.update(self.default_header) result.update(self.http_format_header(method)) result.update(headers) return result def http_format_header(self, method): return { HTTP_FORMAT_HEADER_NAMES[method]: self.format.mime_type(),", "path, **kwargs) def patch(self, path, **kwargs): return self._request('PATCH', path, **kwargs) def put(self, path,", "path, **kwargs): kwargs['headers'] = self.build_request_headers(kwargs.get('headers', {}), method) if self.username and self.password: if self._auth_type", "[] def __init__(self, site, format=activerest.formats.json_format): self.site = site self.format = format @property def", "(open_timeout, read_timeout) url = furl().set(scheme=self._site.scheme, host=self._site.host, port=self._site.port, path=path) response = requests.request(method, url, **kwargs)", "self.format = format @property def site(self): return self._site @site.setter def site(self, site): if", "auth_type in ['basic', 'digest']: self._auth_type = auth_type else: raise ValueError(\"auth_type must be 'basic'", "return self._default_header @default_header.setter def default_header(self, default_header): self._default_header = default_header def build_request_headers(self, headers, method):", "or int') @property def read_timeout(self): return self._read_timeout @read_timeout.setter def read_timeout(self, read_timeout): if isinstance(read_timeout,", "return self._site @site.setter def site(self, site): if isinstance(self._site, furl): self._site = site else:", "= { 'GET': 'Accept', 'PUT': 'Content-Type', 'POST': 'Content-Type', 'PATCH': 'Content-Type', 'DELETE': 'Accept', 'HEAD':", "{}), method) if self.username and self.password: if self._auth_type == 'basic': auth_class = requests.auth.HTTPBasicAuth", "open_timeout or read_timeout: kwargs['timeout'] = (open_timeout, read_timeout) url = furl().set(scheme=self._site.scheme, host=self._site.host, port=self._site.port, path=path)", "'GET': 'Accept', 'PUT': 'Content-Type', 'POST': 'Content-Type', 'PATCH': 'Content-Type', 'DELETE': 'Accept', 'HEAD': 'Accept', }", "in ['basic', 'digest']: self._auth_type = auth_type else: raise ValueError(\"auth_type must be 'basic' or", "open_timeout(self): return self._open_timeout @open_timeout.setter def open_timeout(self, open_timeout): if isinstance(open_timeout, (float, int)): self._open_timeout =", "= None _read_timeout = None _default_header = None proxies = None requests =", "must be an instance of float or int') @property def read_timeout(self): return self._read_timeout", "= read_timeout = None if self._timeout is not None: if isinstance(self._timeout, tuple): (open_timeout,", "<PASSWORD> @property def auth_type(self): return self._auth_type @auth_type.setter def auth_type(self, auth_type): if auth_type in", "path, **kwargs) def put(self, path, **kwargs): return self._request('PUT', path, **kwargs) def post(self, path,", "<PASSWORD> _timeout = None _open_timeout = None _read_timeout = None _default_header = None", "'PUT': 'Content-Type', 'POST': 'Content-Type', 'PATCH': 'Content-Type', 'DELETE': 'Accept', 'HEAD': 'Accept', } class Connection(object):", "furl): self._site = site else: self._site = furl(site) if self._site.username: self.username = self._site.username", "int') @property def read_timeout(self): return self._read_timeout @read_timeout.setter def read_timeout(self, read_timeout): if isinstance(read_timeout, (float,", "**kwargs) def delete(self, path, **kwargs): return self._request('DELETE', path, **kwargs) def patch(self, path, **kwargs):", "format=activerest.formats.json_format): self.site = site self.format = format @property def site(self): return self._site @site.setter", "= None if self._timeout is not None: if isinstance(self._timeout, tuple): (open_timeout, read_timeout) =", "else: self._site = furl(site) if self._site.username: self.username = self._site.username if self._site.password: self.password =", "self._read_timeout @read_timeout.setter def read_timeout(self, read_timeout): if isinstance(read_timeout, (float, int)): self._read_timeout = read_timeout else:", "furl HTTP_FORMAT_HEADER_NAMES = { 'GET': 'Accept', 'PUT': 'Content-Type', 'POST': 'Content-Type', 'PATCH': 'Content-Type', 'DELETE':", "None: open_timeout = self._open_timeout if self._read_timeout is not None: read_timeout = self._read_timeout if", "self._site.username if self._site.password: self.password = <PASSWORD> @property def auth_type(self): return self._auth_type @auth_type.setter def", "'POST': 'Content-Type', 'PATCH': 'Content-Type', 'DELETE': 'Accept', 'HEAD': 'Accept', } class Connection(object): _site =", "'Accept', } class Connection(object): _site = None _format = None _auth_type = 'basic'", "= self.proxies open_timeout = read_timeout = None if self._timeout is not None: if", "raise ValueError(\"auth_type must be 'basic' or 'digest'\") @property def timeout(self): return self._timeout @timeout.setter", "**kwargs) def put(self, path, **kwargs): return self._request('PUT', path, **kwargs) def post(self, path, **kwargs):", "return self._timeout @timeout.setter def timeout(self, timeout): if isinstance(timeout, (float, int, tuple)): self._timeout =", "= self.build_request_headers(kwargs.get('headers', {}), method) if self.username and self.password: if self._auth_type == 'basic': auth_class", "@property def site(self): return self._site @site.setter def site(self, site): if isinstance(self._site, furl): self._site", "return self._request('HEAD', path, **kwargs) def _request(self, method, path, **kwargs): kwargs['headers'] = self.build_request_headers(kwargs.get('headers', {}),", "self._request('POST', path, **kwargs) def head(self, path, **kwargs): return self._request('HEAD', path, **kwargs) def _request(self,", "self.password = <PASSWORD> @property def auth_type(self): return self._auth_type @auth_type.setter def auth_type(self, auth_type): if", "self.password) if self.proxies: kwargs['proxies'] = self.proxies open_timeout = read_timeout = None if self._timeout", "or 'digest'\") @property def timeout(self): return self._timeout @timeout.setter def timeout(self, timeout): if isinstance(timeout,", "= self._site.username if self._site.password: self.password = <PASSWORD> @property def auth_type(self): return self._auth_type @auth_type.setter", "'Content-Type', 'POST': 'Content-Type', 'PATCH': 'Content-Type', 'DELETE': 'Accept', 'HEAD': 'Accept', } class Connection(object): _site", "else: raise ValueError(\"auth_type must be 'basic' or 'digest'\") @property def timeout(self): return self._timeout", "self._default_header: return self._default_header self._default_header = {} return self._default_header @default_header.setter def default_header(self, default_header): self._default_header", "**kwargs) def head(self, path, **kwargs): return self._request('HEAD', path, **kwargs) def _request(self, method, path,", "} class Connection(object): _site = None _format = None _auth_type = 'basic' username", "HTTP_FORMAT_HEADER_NAMES = { 'GET': 'Accept', 'PUT': 'Content-Type', 'POST': 'Content-Type', 'PATCH': 'Content-Type', 'DELETE': 'Accept',", "an instance of float or int') def get(self, path, **kwargs): return self._request('GET', path,", "of float or int') @property def read_timeout(self): return self._read_timeout @read_timeout.setter def read_timeout(self, read_timeout):", "self.site = site self.format = format @property def site(self): return self._site @site.setter def", "isinstance(open_timeout, (float, int)): self._open_timeout = open_timeout else: raise ValueError('open_timeout must be an instance", "headers, method): result = {} result.update(self.default_header) result.update(self.http_format_header(method)) result.update(headers) return result def http_format_header(self, method):", "site self.format = format @property def site(self): return self._site @site.setter def site(self, site):", "site(self, site): if isinstance(self._site, furl): self._site = site else: self._site = furl(site) if", "an instance of float or int') @property def read_timeout(self): return self._read_timeout @read_timeout.setter def", "self._default_header = {} return self._default_header @default_header.setter def default_header(self, default_header): self._default_header = default_header def", "isinstance(self._site, furl): self._site = site else: self._site = furl(site) if self._site.username: self.username =", "return self._request('GET', path, **kwargs) def delete(self, path, **kwargs): return self._request('DELETE', path, **kwargs) def", "_request(self, method, path, **kwargs): kwargs['headers'] = self.build_request_headers(kwargs.get('headers', {}), method) if self.username and self.password:", "**kwargs): return self._request('DELETE', path, **kwargs) def patch(self, path, **kwargs): return self._request('PATCH', path, **kwargs)", "= self._read_timeout if open_timeout or read_timeout: kwargs['timeout'] = (open_timeout, read_timeout) url = furl().set(scheme=self._site.scheme,", "return self._request('POST', path, **kwargs) def head(self, path, **kwargs): return self._request('HEAD', path, **kwargs) def", "'digest': auth_class = requests.auth.HTTPDigestAuth kwargs['auth'] = auth_class(self.username, self.password) if self.proxies: kwargs['proxies'] = self.proxies", "= None proxies = None requests = [] def __init__(self, site, format=activerest.formats.json_format): self.site", "return self._auth_type @auth_type.setter def auth_type(self, auth_type): if auth_type in ['basic', 'digest']: self._auth_type =", "= auth_type else: raise ValueError(\"auth_type must be 'basic' or 'digest'\") @property def timeout(self):", "(open_timeout, read_timeout) = self._timeout else: open_timeout = read_timeout = self._timeout if self._open_timeout is", "= furl(site) if self._site.username: self.username = self._site.username if self._site.password: self.password = <PASSWORD> @property", "None: if isinstance(self._timeout, tuple): (open_timeout, read_timeout) = self._timeout else: open_timeout = read_timeout =", "_site = None _format = None _auth_type = 'basic' username = None password", "@auth_type.setter def auth_type(self, auth_type): if auth_type in ['basic', 'digest']: self._auth_type = auth_type else:", "ValueError('open_timeout must be an instance of float or int') @property def read_timeout(self): return", "else: raise ValueError('open_timeout must be an instance of float or int') @property def", "int or tuple') @property def open_timeout(self): return self._open_timeout @open_timeout.setter def open_timeout(self, open_timeout): if", "def read_timeout(self, read_timeout): if isinstance(read_timeout, (float, int)): self._read_timeout = read_timeout else: raise ValueError('read_timeout", "= auth_class(self.username, self.password) if self.proxies: kwargs['proxies'] = self.proxies open_timeout = read_timeout = None", "site): if isinstance(self._site, furl): self._site = site else: self._site = furl(site) if self._site.username:", "read_timeout(self): return self._read_timeout @read_timeout.setter def read_timeout(self, read_timeout): if isinstance(read_timeout, (float, int)): self._read_timeout =", "return self._read_timeout @read_timeout.setter def read_timeout(self, read_timeout): if isinstance(read_timeout, (float, int)): self._read_timeout = read_timeout", "self._timeout @timeout.setter def timeout(self, timeout): if isinstance(timeout, (float, int, tuple)): self._timeout = timeout", "auth_type else: raise ValueError(\"auth_type must be 'basic' or 'digest'\") @property def timeout(self): return", "default_header(self): if self._default_header: return self._default_header self._default_header = {} return self._default_header @default_header.setter def default_header(self,", "site, format=activerest.formats.json_format): self.site = site self.format = format @property def site(self): return self._site", "class Connection(object): _site = None _format = None _auth_type = 'basic' username =", "None proxies = None requests = [] def __init__(self, site, format=activerest.formats.json_format): self.site =", "if isinstance(self._timeout, tuple): (open_timeout, read_timeout) = self._timeout else: open_timeout = read_timeout = self._timeout", "kwargs['timeout'] = (open_timeout, read_timeout) url = furl().set(scheme=self._site.scheme, host=self._site.host, port=self._site.port, path=path) response = requests.request(method,", "site(self): return self._site @site.setter def site(self, site): if isinstance(self._site, furl): self._site = site", "int)): self._read_timeout = read_timeout else: raise ValueError('read_timeout must be an instance of float", "path, **kwargs) def delete(self, path, **kwargs): return self._request('DELETE', path, **kwargs) def patch(self, path,", "_open_timeout = None _read_timeout = None _default_header = None proxies = None requests", "self._auth_type == 'digest': auth_class = requests.auth.HTTPDigestAuth kwargs['auth'] = auth_class(self.username, self.password) if self.proxies: kwargs['proxies']", "path, **kwargs): return self._request('DELETE', path, **kwargs) def patch(self, path, **kwargs): return self._request('PATCH', path,", "def auth_type(self): return self._auth_type @auth_type.setter def auth_type(self, auth_type): if auth_type in ['basic', 'digest']:", "None requests = [] def __init__(self, site, format=activerest.formats.json_format): self.site = site self.format =", "= None _format = None _auth_type = 'basic' username = None password =", "not None: open_timeout = self._open_timeout if self._read_timeout is not None: read_timeout = self._read_timeout", "(float, int, tuple)): self._timeout = timeout else: raise ValueError('timeout must be an instance", "read_timeout: kwargs['timeout'] = (open_timeout, read_timeout) url = furl().set(scheme=self._site.scheme, host=self._site.host, port=self._site.port, path=path) response =", "self._site.password: self.password = <PASSWORD> @property def auth_type(self): return self._auth_type @auth_type.setter def auth_type(self, auth_type):", "is not None: if isinstance(self._timeout, tuple): (open_timeout, read_timeout) = self._timeout else: open_timeout =", "self.build_request_headers(kwargs.get('headers', {}), method) if self.username and self.password: if self._auth_type == 'basic': auth_class =", "None _format = None _auth_type = 'basic' username = None password = <PASSWORD>", "= {} result.update(self.default_header) result.update(self.http_format_header(method)) result.update(headers) return result def http_format_header(self, method): return { HTTP_FORMAT_HEADER_NAMES[method]:", "password = <PASSWORD> _timeout = None _open_timeout = None _read_timeout = None _default_header", "_timeout = None _open_timeout = None _read_timeout = None _default_header = None proxies", "else: open_timeout = read_timeout = self._timeout if self._open_timeout is not None: open_timeout =", "_format = None _auth_type = 'basic' username = None password = <PASSWORD> _timeout", "= requests.auth.HTTPBasicAuth if self._auth_type == 'digest': auth_class = requests.auth.HTTPDigestAuth kwargs['auth'] = auth_class(self.username, self.password)", "method) if self.username and self.password: if self._auth_type == 'basic': auth_class = requests.auth.HTTPBasicAuth if", "'basic': auth_class = requests.auth.HTTPBasicAuth if self._auth_type == 'digest': auth_class = requests.auth.HTTPDigestAuth kwargs['auth'] =", "_default_header = None proxies = None requests = [] def __init__(self, site, format=activerest.formats.json_format):", "self._auth_type = auth_type else: raise ValueError(\"auth_type must be 'basic' or 'digest'\") @property def", "import furl HTTP_FORMAT_HEADER_NAMES = { 'GET': 'Accept', 'PUT': 'Content-Type', 'POST': 'Content-Type', 'PATCH': 'Content-Type',", "def read_timeout(self): return self._read_timeout @read_timeout.setter def read_timeout(self, read_timeout): if isinstance(read_timeout, (float, int)): self._read_timeout", "import activerest.formats.json_format import requests from furl import furl HTTP_FORMAT_HEADER_NAMES = { 'GET': 'Accept',", "if isinstance(self._site, furl): self._site = site else: self._site = furl(site) if self._site.username: self.username", "self._open_timeout if self._read_timeout is not None: read_timeout = self._read_timeout if open_timeout or read_timeout:", "'Content-Type', 'DELETE': 'Accept', 'HEAD': 'Accept', } class Connection(object): _site = None _format =", "self.proxies: kwargs['proxies'] = self.proxies open_timeout = read_timeout = None if self._timeout is not", "default_header(self, default_header): self._default_header = default_header def build_request_headers(self, headers, method): result = {} result.update(self.default_header)", "self.proxies open_timeout = read_timeout = None if self._timeout is not None: if isinstance(self._timeout,", "if self.proxies: kwargs['proxies'] = self.proxies open_timeout = read_timeout = None if self._timeout is", "= <PASSWORD> @property def auth_type(self): return self._auth_type @auth_type.setter def auth_type(self, auth_type): if auth_type", "open_timeout else: raise ValueError('open_timeout must be an instance of float or int') @property", "requests.auth.HTTPDigestAuth kwargs['auth'] = auth_class(self.username, self.password) if self.proxies: kwargs['proxies'] = self.proxies open_timeout = read_timeout", "kwargs['headers'] = self.build_request_headers(kwargs.get('headers', {}), method) if self.username and self.password: if self._auth_type == 'basic':", "if isinstance(read_timeout, (float, int)): self._read_timeout = read_timeout else: raise ValueError('read_timeout must be an", "def put(self, path, **kwargs): return self._request('PUT', path, **kwargs) def post(self, path, **kwargs): return", "**kwargs) def patch(self, path, **kwargs): return self._request('PATCH', path, **kwargs) def put(self, path, **kwargs):", "isinstance(self._timeout, tuple): (open_timeout, read_timeout) = self._timeout else: open_timeout = read_timeout = self._timeout if", "kwargs['proxies'] = self.proxies open_timeout = read_timeout = None if self._timeout is not None:", "ValueError('timeout must be an instance of float, int or tuple') @property def open_timeout(self):", "def timeout(self): return self._timeout @timeout.setter def timeout(self, timeout): if isinstance(timeout, (float, int, tuple)):", "open_timeout(self, open_timeout): if isinstance(open_timeout, (float, int)): self._open_timeout = open_timeout else: raise ValueError('open_timeout must", "read_timeout = self._read_timeout if open_timeout or read_timeout: kwargs['timeout'] = (open_timeout, read_timeout) url =", "self._read_timeout if open_timeout or read_timeout: kwargs['timeout'] = (open_timeout, read_timeout) url = furl().set(scheme=self._site.scheme, host=self._site.host,", "raise ValueError('open_timeout must be an instance of float or int') @property def read_timeout(self):", "else: raise ValueError('timeout must be an instance of float, int or tuple') @property", "@property def default_header(self): if self._default_header: return self._default_header self._default_header = {} return self._default_header @default_header.setter", "= None password = <PASSWORD> _timeout = None _open_timeout = None _read_timeout =", "def open_timeout(self, open_timeout): if isinstance(open_timeout, (float, int)): self._open_timeout = open_timeout else: raise ValueError('open_timeout", "**kwargs): return self._request('PUT', path, **kwargs) def post(self, path, **kwargs): return self._request('POST', path, **kwargs)", "self._open_timeout = open_timeout else: raise ValueError('open_timeout must be an instance of float or", "@property def open_timeout(self): return self._open_timeout @open_timeout.setter def open_timeout(self, open_timeout): if isinstance(open_timeout, (float, int)):", "self._site @site.setter def site(self, site): if isinstance(self._site, furl): self._site = site else: self._site", "def delete(self, path, **kwargs): return self._request('DELETE', path, **kwargs) def patch(self, path, **kwargs): return", "furl import furl HTTP_FORMAT_HEADER_NAMES = { 'GET': 'Accept', 'PUT': 'Content-Type', 'POST': 'Content-Type', 'PATCH':", "self._timeout if self._open_timeout is not None: open_timeout = self._open_timeout if self._read_timeout is not", "ValueError(\"auth_type must be 'basic' or 'digest'\") @property def timeout(self): return self._timeout @timeout.setter def", "auth_class = requests.auth.HTTPBasicAuth if self._auth_type == 'digest': auth_class = requests.auth.HTTPDigestAuth kwargs['auth'] = auth_class(self.username,", "must be an instance of float or int') def get(self, path, **kwargs): return", "or read_timeout: kwargs['timeout'] = (open_timeout, read_timeout) url = furl().set(scheme=self._site.scheme, host=self._site.host, port=self._site.port, path=path) response", "be an instance of float or int') @property def read_timeout(self): return self._read_timeout @read_timeout.setter", "if auth_type in ['basic', 'digest']: self._auth_type = auth_type else: raise ValueError(\"auth_type must be" ]
[ "latvolMod.XSize = size latvolMod.YSize = size latvolMod.ZSize = size latvolMod.DataAtLocation = \"Nodes\" report1", "data = {} addDataMod = addModule(\"CreateScalarFieldDataBasic\") #eval.Operator = 2 #eval.Scalar = i report2", "size latvolMod.DataAtLocation = \"Nodes\" report1 = addModule(\"ReportFieldInfo\") latvolMod.output[0] >> report1.input[0] data = {}", "size = 10 latvolMod.XSize = size latvolMod.YSize = size latvolMod.ZSize = size latvolMod.DataAtLocation", "addDataMod.input[0] addDataMod.output[0] >> show.input.Field view = addModule(\"ViewScene\") show.output[0] >> view.input[0] view.showUI() executeAll() removeModule(view.id)", "show.output[0] >> view.input[0] view.showUI() executeAll() removeModule(view.id) view = addModule(\"ViewScene\") show.output[0] >> view.input[0] view.showUI()", "#eval.Scalar = i report2 = addModule(\"ReportFieldInfo\") addDataMod.output[0] >> report2.input[0] show = addModule(\"ShowField\") latvolMod.output[0]", "= 2 #eval.Scalar = i report2 = addModule(\"ReportFieldInfo\") addDataMod.output[0] >> report2.input[0] show =", "= \"Nodes\" report1 = addModule(\"ReportFieldInfo\") latvolMod.output[0] >> report1.input[0] data = {} addDataMod =", "size latvolMod.YSize = size latvolMod.ZSize = size latvolMod.DataAtLocation = \"Nodes\" report1 = addModule(\"ReportFieldInfo\")", "view = addModule(\"ViewScene\") show.output[0] >> view.input[0] view.showUI() executeAll() removeModule(view.id) view = addModule(\"ViewScene\") show.output[0]", "= 10 latvolMod.XSize = size latvolMod.YSize = size latvolMod.ZSize = size latvolMod.DataAtLocation =", "= addModule(\"ReportFieldInfo\") addDataMod.output[0] >> report2.input[0] show = addModule(\"ShowField\") latvolMod.output[0] >> addDataMod.input[0] addDataMod.output[0] >>", "addModule(\"CreateScalarFieldDataBasic\") #eval.Operator = 2 #eval.Scalar = i report2 = addModule(\"ReportFieldInfo\") addDataMod.output[0] >> report2.input[0]", "size latvolMod.ZSize = size latvolMod.DataAtLocation = \"Nodes\" report1 = addModule(\"ReportFieldInfo\") latvolMod.output[0] >> report1.input[0]", "addDataMod.output[0] >> report2.input[0] show = addModule(\"ShowField\") latvolMod.output[0] >> addDataMod.input[0] addDataMod.output[0] >> show.input.Field view", "report2.input[0] show = addModule(\"ShowField\") latvolMod.output[0] >> addDataMod.input[0] addDataMod.output[0] >> show.input.Field view = addModule(\"ViewScene\")", "addModule(\"ReportFieldInfo\") latvolMod.output[0] >> report1.input[0] data = {} addDataMod = addModule(\"CreateScalarFieldDataBasic\") #eval.Operator = 2", "latvolMod.DataAtLocation = \"Nodes\" report1 = addModule(\"ReportFieldInfo\") latvolMod.output[0] >> report1.input[0] data = {} addDataMod", "latvolMod.output[0] >> addDataMod.input[0] addDataMod.output[0] >> show.input.Field view = addModule(\"ViewScene\") show.output[0] >> view.input[0] view.showUI()", "show = addModule(\"ShowField\") latvolMod.output[0] >> addDataMod.input[0] addDataMod.output[0] >> show.input.Field view = addModule(\"ViewScene\") show.output[0]", "= addModule(\"ReportFieldInfo\") latvolMod.output[0] >> report1.input[0] data = {} addDataMod = addModule(\"CreateScalarFieldDataBasic\") #eval.Operator =", "addModule(\"ViewScene\") show.output[0] >> view.input[0] view.showUI() executeAll() removeModule(view.id) view = addModule(\"ViewScene\") show.output[0] >> view.input[0]", "= {} addDataMod = addModule(\"CreateScalarFieldDataBasic\") #eval.Operator = 2 #eval.Scalar = i report2 =", "= addModule(\"ViewScene\") show.output[0] >> view.input[0] view.showUI() executeAll() removeModule(view.id) view = addModule(\"ViewScene\") show.output[0] >>", "addModule(\"ReportFieldInfo\") addDataMod.output[0] >> report2.input[0] show = addModule(\"ShowField\") latvolMod.output[0] >> addDataMod.input[0] addDataMod.output[0] >> show.input.Field", "2 #eval.Scalar = i report2 = addModule(\"ReportFieldInfo\") addDataMod.output[0] >> report2.input[0] show = addModule(\"ShowField\")", "\"Nodes\" report1 = addModule(\"ReportFieldInfo\") latvolMod.output[0] >> report1.input[0] data = {} addDataMod = addModule(\"CreateScalarFieldDataBasic\")", "latvolMod.output[0] >> report1.input[0] data = {} addDataMod = addModule(\"CreateScalarFieldDataBasic\") #eval.Operator = 2 #eval.Scalar", "addModule(\"ShowField\") latvolMod.output[0] >> addDataMod.input[0] addDataMod.output[0] >> show.input.Field view = addModule(\"ViewScene\") show.output[0] >> view.input[0]", "= size latvolMod.ZSize = size latvolMod.DataAtLocation = \"Nodes\" report1 = addModule(\"ReportFieldInfo\") latvolMod.output[0] >>", "= size latvolMod.DataAtLocation = \"Nodes\" report1 = addModule(\"ReportFieldInfo\") latvolMod.output[0] >> report1.input[0] data =", "= i report2 = addModule(\"ReportFieldInfo\") addDataMod.output[0] >> report2.input[0] show = addModule(\"ShowField\") latvolMod.output[0] >>", "i report2 = addModule(\"ReportFieldInfo\") addDataMod.output[0] >> report2.input[0] show = addModule(\"ShowField\") latvolMod.output[0] >> addDataMod.input[0]", "show.input.Field view = addModule(\"ViewScene\") show.output[0] >> view.input[0] view.showUI() executeAll() removeModule(view.id) view = addModule(\"ViewScene\")", "= addModule(\"CreateLatVol\") size = 10 latvolMod.XSize = size latvolMod.YSize = size latvolMod.ZSize =", "report1 = addModule(\"ReportFieldInfo\") latvolMod.output[0] >> report1.input[0] data = {} addDataMod = addModule(\"CreateScalarFieldDataBasic\") #eval.Operator", "10 latvolMod.XSize = size latvolMod.YSize = size latvolMod.ZSize = size latvolMod.DataAtLocation = \"Nodes\"", "= addModule(\"CreateScalarFieldDataBasic\") #eval.Operator = 2 #eval.Scalar = i report2 = addModule(\"ReportFieldInfo\") addDataMod.output[0] >>", "#eval.Operator = 2 #eval.Scalar = i report2 = addModule(\"ReportFieldInfo\") addDataMod.output[0] >> report2.input[0] show", "addDataMod.output[0] >> show.input.Field view = addModule(\"ViewScene\") show.output[0] >> view.input[0] view.showUI() executeAll() removeModule(view.id) view", "{} addDataMod = addModule(\"CreateScalarFieldDataBasic\") #eval.Operator = 2 #eval.Scalar = i report2 = addModule(\"ReportFieldInfo\")", "view.showUI() executeAll() removeModule(view.id) view = addModule(\"ViewScene\") show.output[0] >> view.input[0] view.showUI() executeAll() #executeAll() #executeAll()", "= addModule(\"ShowField\") latvolMod.output[0] >> addDataMod.input[0] addDataMod.output[0] >> show.input.Field view = addModule(\"ViewScene\") show.output[0] >>", "= size latvolMod.YSize = size latvolMod.ZSize = size latvolMod.DataAtLocation = \"Nodes\" report1 =", ">> addDataMod.input[0] addDataMod.output[0] >> show.input.Field view = addModule(\"ViewScene\") show.output[0] >> view.input[0] view.showUI() executeAll()", "view.input[0] view.showUI() executeAll() removeModule(view.id) view = addModule(\"ViewScene\") show.output[0] >> view.input[0] view.showUI() executeAll() #executeAll()", ">> show.input.Field view = addModule(\"ViewScene\") show.output[0] >> view.input[0] view.showUI() executeAll() removeModule(view.id) view =", "latvolMod.ZSize = size latvolMod.DataAtLocation = \"Nodes\" report1 = addModule(\"ReportFieldInfo\") latvolMod.output[0] >> report1.input[0] data", ">> report1.input[0] data = {} addDataMod = addModule(\"CreateScalarFieldDataBasic\") #eval.Operator = 2 #eval.Scalar =", ">> view.input[0] view.showUI() executeAll() removeModule(view.id) view = addModule(\"ViewScene\") show.output[0] >> view.input[0] view.showUI() executeAll()", "report2 = addModule(\"ReportFieldInfo\") addDataMod.output[0] >> report2.input[0] show = addModule(\"ShowField\") latvolMod.output[0] >> addDataMod.input[0] addDataMod.output[0]", "latvolMod = addModule(\"CreateLatVol\") size = 10 latvolMod.XSize = size latvolMod.YSize = size latvolMod.ZSize", "report1.input[0] data = {} addDataMod = addModule(\"CreateScalarFieldDataBasic\") #eval.Operator = 2 #eval.Scalar = i", "addModule(\"CreateLatVol\") size = 10 latvolMod.XSize = size latvolMod.YSize = size latvolMod.ZSize = size", "addDataMod = addModule(\"CreateScalarFieldDataBasic\") #eval.Operator = 2 #eval.Scalar = i report2 = addModule(\"ReportFieldInfo\") addDataMod.output[0]", ">> report2.input[0] show = addModule(\"ShowField\") latvolMod.output[0] >> addDataMod.input[0] addDataMod.output[0] >> show.input.Field view =", "latvolMod.YSize = size latvolMod.ZSize = size latvolMod.DataAtLocation = \"Nodes\" report1 = addModule(\"ReportFieldInfo\") latvolMod.output[0]" ]
[ "@pytest.fixture() def zonedir_src(): return ZONEDIR_SRC @pytest.fixture() def zonedir(): return ZONEDIR @pytest.fixture(scope='module', params=get_connection_fixture_params()) def", "Bind9ZoneCLI(['bulkpush', *con, '--dir', ZONEDIR_SRC, '--zones', 'public/example.com,private/example.com' ]).run() return connection @pytest.fixture(scope='function') def session_factory(connection): \"\"\"", "connection] Bind9ZoneCLI(['init', *con, '--drop']).run() Bind9ZoneCLI(['bulkpush', *con, '--dir', ZONEDIR_SRC, '--zones', 'public/example.com,private/example.com' ]).run() return connection", "import sessionmaker, scoped_session from bind9zone.cli import Bind9ZoneCLI ZONEDIR_SRC = 'tests/input' ZONEDIR = 'tests/output'", "return connection @pytest.fixture(scope='function') def session_factory(connection): \"\"\" pytest対象モジュールの引数に\"session_factory\"を指定すると、 このfixtureが実行され、データベースの初期化を行った上でSQLAlchemyのscoped_sessionを返します。 1つのモジュール内(pyファイル)から複数回使用された場合でも、データベースの初期化処理が行われるのは 各モジュールあたり最初の一回だけです。 \"\"\" engine =", "行われるのは各モジュールあたり最初の一回だけです。 \"\"\" connection = request.param con = ['--connection', connection] Bind9ZoneCLI(['init', *con, '--drop']).run() Bind9ZoneCLI(['bulkpush',", "ZONEDIR_SRC = 'tests/input' ZONEDIR = 'tests/output' def get_connection_fixture_params(): if os.getenv('TEST_POSTGRES'): return ['sqlite:///tests/db.sqlite3', 'postgresql://postgres:postgres@db/database']", "ZONEDIR = 'tests/output' def get_connection_fixture_params(): if os.getenv('TEST_POSTGRES'): return ['sqlite:///tests/db.sqlite3', 'postgresql://postgres:postgres@db/database'] else: return ['sqlite:///tests/db.sqlite3']", "Bind9ZoneCLI(['init', *con, '--drop']).run() Bind9ZoneCLI(['bulkpush', *con, '--dir', ZONEDIR_SRC, '--zones', 'public/example.com,private/example.com' ]).run() return connection @pytest.fixture(scope='function')", "con = ['--connection', connection] Bind9ZoneCLI(['init', *con, '--drop']).run() Bind9ZoneCLI(['bulkpush', *con, '--dir', ZONEDIR_SRC, '--zones', 'public/example.com,private/example.com'", "pytest対象モジュールの引数に\"session_factory\"を指定すると、 このfixtureが実行され、データベースの初期化を行った上でSQLAlchemyのscoped_sessionを返します。 1つのモジュール内(pyファイル)から複数回使用された場合でも、データベースの初期化処理が行われるのは 各モジュールあたり最初の一回だけです。 \"\"\" engine = create_engine(connection) session_factory = sessionmaker(bind=engine) Session =", "= request.param con = ['--connection', connection] Bind9ZoneCLI(['init', *con, '--drop']).run() Bind9ZoneCLI(['bulkpush', *con, '--dir', ZONEDIR_SRC,", "session_factory(connection): \"\"\" pytest対象モジュールの引数に\"session_factory\"を指定すると、 このfixtureが実行され、データベースの初期化を行った上でSQLAlchemyのscoped_sessionを返します。 1つのモジュール内(pyファイル)から複数回使用された場合でも、データベースの初期化処理が行われるのは 各モジュールあたり最初の一回だけです。 \"\"\" engine = create_engine(connection) session_factory = sessionmaker(bind=engine)", "return ['sqlite:///tests/db.sqlite3', 'postgresql://postgres:postgres@db/database'] else: return ['sqlite:///tests/db.sqlite3'] @pytest.fixture() def zonedir_src(): return ZONEDIR_SRC @pytest.fixture() def", "['sqlite:///tests/db.sqlite3'] @pytest.fixture() def zonedir_src(): return ZONEDIR_SRC @pytest.fixture() def zonedir(): return ZONEDIR @pytest.fixture(scope='module', params=get_connection_fixture_params())", "'postgresql://postgres:postgres@db/database'] else: return ['sqlite:///tests/db.sqlite3'] @pytest.fixture() def zonedir_src(): return ZONEDIR_SRC @pytest.fixture() def zonedir(): return", "params=get_connection_fixture_params()) def connection(request): \"\"\" pytest対象モジュールの引数に\"connection\"を指定すると、 このfixtureが実行され、データベースの初期化を行った上でconnection文字列を返します。 1つのモジュール内(pyファイル)から複数回使用された場合でも、データベースの初期化処理が 行われるのは各モジュールあたり最初の一回だけです。 \"\"\" connection = request.param con", "from sqlalchemy.orm import sessionmaker, scoped_session from bind9zone.cli import Bind9ZoneCLI ZONEDIR_SRC = 'tests/input' ZONEDIR", "zonedir(): return ZONEDIR @pytest.fixture(scope='module', params=get_connection_fixture_params()) def connection(request): \"\"\" pytest対象モジュールの引数に\"connection\"を指定すると、 このfixtureが実行され、データベースの初期化を行った上でconnection文字列を返します。 1つのモジュール内(pyファイル)から複数回使用された場合でも、データベースの初期化処理が 行われるのは各モジュールあたり最初の一回だけです。 \"\"\"", "get_connection_fixture_params(): if os.getenv('TEST_POSTGRES'): return ['sqlite:///tests/db.sqlite3', 'postgresql://postgres:postgres@db/database'] else: return ['sqlite:///tests/db.sqlite3'] @pytest.fixture() def zonedir_src(): return", "\"\"\" pytest対象モジュールの引数に\"connection\"を指定すると、 このfixtureが実行され、データベースの初期化を行った上でconnection文字列を返します。 1つのモジュール内(pyファイル)から複数回使用された場合でも、データベースの初期化処理が 行われるのは各モジュールあたり最初の一回だけです。 \"\"\" connection = request.param con = ['--connection', connection]", "Bind9ZoneCLI ZONEDIR_SRC = 'tests/input' ZONEDIR = 'tests/output' def get_connection_fixture_params(): if os.getenv('TEST_POSTGRES'): return ['sqlite:///tests/db.sqlite3',", "'public/example.com,private/example.com' ]).run() return connection @pytest.fixture(scope='function') def session_factory(connection): \"\"\" pytest対象モジュールの引数に\"session_factory\"を指定すると、 このfixtureが実行され、データベースの初期化を行った上でSQLAlchemyのscoped_sessionを返します。 1つのモジュール内(pyファイル)から複数回使用された場合でも、データベースの初期化処理が行われるのは 各モジュールあたり最初の一回だけです。 \"\"\"", "= ['--connection', connection] Bind9ZoneCLI(['init', *con, '--drop']).run() Bind9ZoneCLI(['bulkpush', *con, '--dir', ZONEDIR_SRC, '--zones', 'public/example.com,private/example.com' ]).run()", "def zonedir_src(): return ZONEDIR_SRC @pytest.fixture() def zonedir(): return ZONEDIR @pytest.fixture(scope='module', params=get_connection_fixture_params()) def connection(request):", "@pytest.fixture(scope='module', params=get_connection_fixture_params()) def connection(request): \"\"\" pytest対象モジュールの引数に\"connection\"を指定すると、 このfixtureが実行され、データベースの初期化を行った上でconnection文字列を返します。 1つのモジュール内(pyファイル)から複数回使用された場合でも、データベースの初期化処理が 行われるのは各モジュールあたり最初の一回だけです。 \"\"\" connection = request.param", "@pytest.fixture(scope='function') def session_factory(connection): \"\"\" pytest対象モジュールの引数に\"session_factory\"を指定すると、 このfixtureが実行され、データベースの初期化を行った上でSQLAlchemyのscoped_sessionを返します。 1つのモジュール内(pyファイル)から複数回使用された場合でも、データベースの初期化処理が行われるのは 各モジュールあたり最初の一回だけです。 \"\"\" engine = create_engine(connection) session_factory", "os from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session from bind9zone.cli import", "create_engine from sqlalchemy.orm import sessionmaker, scoped_session from bind9zone.cli import Bind9ZoneCLI ZONEDIR_SRC = 'tests/input'", "pytest, os from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session from bind9zone.cli", "connection = request.param con = ['--connection', connection] Bind9ZoneCLI(['init', *con, '--drop']).run() Bind9ZoneCLI(['bulkpush', *con, '--dir',", "return ZONEDIR_SRC @pytest.fixture() def zonedir(): return ZONEDIR @pytest.fixture(scope='module', params=get_connection_fixture_params()) def connection(request): \"\"\" pytest対象モジュールの引数に\"connection\"を指定すると、", "\"\"\" connection = request.param con = ['--connection', connection] Bind9ZoneCLI(['init', *con, '--drop']).run() Bind9ZoneCLI(['bulkpush', *con,", "各モジュールあたり最初の一回だけです。 \"\"\" engine = create_engine(connection) session_factory = sessionmaker(bind=engine) Session = scoped_session(session_factory) return Session", "このfixtureが実行され、データベースの初期化を行った上でconnection文字列を返します。 1つのモジュール内(pyファイル)から複数回使用された場合でも、データベースの初期化処理が 行われるのは各モジュールあたり最初の一回だけです。 \"\"\" connection = request.param con = ['--connection', connection] Bind9ZoneCLI(['init', *con,", "@pytest.fixture() def zonedir(): return ZONEDIR @pytest.fixture(scope='module', params=get_connection_fixture_params()) def connection(request): \"\"\" pytest対象モジュールの引数に\"connection\"を指定すると、 このfixtureが実行され、データベースの初期化を行った上でconnection文字列を返します。 1つのモジュール内(pyファイル)から複数回使用された場合でも、データベースの初期化処理が", "sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session from bind9zone.cli import Bind9ZoneCLI ZONEDIR_SRC", "return ['sqlite:///tests/db.sqlite3'] @pytest.fixture() def zonedir_src(): return ZONEDIR_SRC @pytest.fixture() def zonedir(): return ZONEDIR @pytest.fixture(scope='module',", "return ZONEDIR @pytest.fixture(scope='module', params=get_connection_fixture_params()) def connection(request): \"\"\" pytest対象モジュールの引数に\"connection\"を指定すると、 このfixtureが実行され、データベースの初期化を行った上でconnection文字列を返します。 1つのモジュール内(pyファイル)から複数回使用された場合でも、データベースの初期化処理が 行われるのは各モジュールあたり最初の一回だけです。 \"\"\" connection", "ZONEDIR @pytest.fixture(scope='module', params=get_connection_fixture_params()) def connection(request): \"\"\" pytest対象モジュールの引数に\"connection\"を指定すると、 このfixtureが実行され、データベースの初期化を行った上でconnection文字列を返します。 1つのモジュール内(pyファイル)から複数回使用された場合でも、データベースの初期化処理が 行われるのは各モジュールあたり最初の一回だけです。 \"\"\" connection =", "import create_engine from sqlalchemy.orm import sessionmaker, scoped_session from bind9zone.cli import Bind9ZoneCLI ZONEDIR_SRC =", "else: return ['sqlite:///tests/db.sqlite3'] @pytest.fixture() def zonedir_src(): return ZONEDIR_SRC @pytest.fixture() def zonedir(): return ZONEDIR", "'--zones', 'public/example.com,private/example.com' ]).run() return connection @pytest.fixture(scope='function') def session_factory(connection): \"\"\" pytest対象モジュールの引数に\"session_factory\"を指定すると、 このfixtureが実行され、データベースの初期化を行った上でSQLAlchemyのscoped_sessionを返します。 1つのモジュール内(pyファイル)から複数回使用された場合でも、データベースの初期化処理が行われるのは 各モジュールあたり最初の一回だけです。", "*con, '--dir', ZONEDIR_SRC, '--zones', 'public/example.com,private/example.com' ]).run() return connection @pytest.fixture(scope='function') def session_factory(connection): \"\"\" pytest対象モジュールの引数に\"session_factory\"を指定すると、", "bind9zone.cli import Bind9ZoneCLI ZONEDIR_SRC = 'tests/input' ZONEDIR = 'tests/output' def get_connection_fixture_params(): if os.getenv('TEST_POSTGRES'):", "['--connection', connection] Bind9ZoneCLI(['init', *con, '--drop']).run() Bind9ZoneCLI(['bulkpush', *con, '--dir', ZONEDIR_SRC, '--zones', 'public/example.com,private/example.com' ]).run() return", "sqlalchemy.orm import sessionmaker, scoped_session from bind9zone.cli import Bind9ZoneCLI ZONEDIR_SRC = 'tests/input' ZONEDIR =", "]).run() return connection @pytest.fixture(scope='function') def session_factory(connection): \"\"\" pytest対象モジュールの引数に\"session_factory\"を指定すると、 このfixtureが実行され、データベースの初期化を行った上でSQLAlchemyのscoped_sessionを返します。 1つのモジュール内(pyファイル)から複数回使用された場合でも、データベースの初期化処理が行われるのは 各モジュールあたり最初の一回だけです。 \"\"\" engine", "このfixtureが実行され、データベースの初期化を行った上でSQLAlchemyのscoped_sessionを返します。 1つのモジュール内(pyファイル)から複数回使用された場合でも、データベースの初期化処理が行われるのは 各モジュールあたり最初の一回だけです。 \"\"\" engine = create_engine(connection) session_factory = sessionmaker(bind=engine) Session = scoped_session(session_factory)", "connection(request): \"\"\" pytest対象モジュールの引数に\"connection\"を指定すると、 このfixtureが実行され、データベースの初期化を行った上でconnection文字列を返します。 1つのモジュール内(pyファイル)から複数回使用された場合でも、データベースの初期化処理が 行われるのは各モジュールあたり最初の一回だけです。 \"\"\" connection = request.param con = ['--connection',", "from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session from bind9zone.cli import Bind9ZoneCLI", "'--drop']).run() Bind9ZoneCLI(['bulkpush', *con, '--dir', ZONEDIR_SRC, '--zones', 'public/example.com,private/example.com' ]).run() return connection @pytest.fixture(scope='function') def session_factory(connection):", "def zonedir(): return ZONEDIR @pytest.fixture(scope='module', params=get_connection_fixture_params()) def connection(request): \"\"\" pytest対象モジュールの引数に\"connection\"を指定すると、 このfixtureが実行され、データベースの初期化を行った上でconnection文字列を返します。 1つのモジュール内(pyファイル)から複数回使用された場合でも、データベースの初期化処理が 行われるのは各モジュールあたり最初の一回だけです。", "ZONEDIR_SRC @pytest.fixture() def zonedir(): return ZONEDIR @pytest.fixture(scope='module', params=get_connection_fixture_params()) def connection(request): \"\"\" pytest対象モジュールの引数に\"connection\"を指定すると、 このfixtureが実行され、データベースの初期化を行った上でconnection文字列を返します。", "scoped_session from bind9zone.cli import Bind9ZoneCLI ZONEDIR_SRC = 'tests/input' ZONEDIR = 'tests/output' def get_connection_fixture_params():", "1つのモジュール内(pyファイル)から複数回使用された場合でも、データベースの初期化処理が行われるのは 各モジュールあたり最初の一回だけです。 \"\"\" engine = create_engine(connection) session_factory = sessionmaker(bind=engine) Session = scoped_session(session_factory) return", "def get_connection_fixture_params(): if os.getenv('TEST_POSTGRES'): return ['sqlite:///tests/db.sqlite3', 'postgresql://postgres:postgres@db/database'] else: return ['sqlite:///tests/db.sqlite3'] @pytest.fixture() def zonedir_src():", "sessionmaker, scoped_session from bind9zone.cli import Bind9ZoneCLI ZONEDIR_SRC = 'tests/input' ZONEDIR = 'tests/output' def", "'tests/output' def get_connection_fixture_params(): if os.getenv('TEST_POSTGRES'): return ['sqlite:///tests/db.sqlite3', 'postgresql://postgres:postgres@db/database'] else: return ['sqlite:///tests/db.sqlite3'] @pytest.fixture() def", "zonedir_src(): return ZONEDIR_SRC @pytest.fixture() def zonedir(): return ZONEDIR @pytest.fixture(scope='module', params=get_connection_fixture_params()) def connection(request): \"\"\"", "1つのモジュール内(pyファイル)から複数回使用された場合でも、データベースの初期化処理が 行われるのは各モジュールあたり最初の一回だけです。 \"\"\" connection = request.param con = ['--connection', connection] Bind9ZoneCLI(['init', *con, '--drop']).run()", "pytest対象モジュールの引数に\"connection\"を指定すると、 このfixtureが実行され、データベースの初期化を行った上でconnection文字列を返します。 1つのモジュール内(pyファイル)から複数回使用された場合でも、データベースの初期化処理が 行われるのは各モジュールあたり最初の一回だけです。 \"\"\" connection = request.param con = ['--connection', connection] Bind9ZoneCLI(['init',", "import Bind9ZoneCLI ZONEDIR_SRC = 'tests/input' ZONEDIR = 'tests/output' def get_connection_fixture_params(): if os.getenv('TEST_POSTGRES'): return", "\"\"\" pytest対象モジュールの引数に\"session_factory\"を指定すると、 このfixtureが実行され、データベースの初期化を行った上でSQLAlchemyのscoped_sessionを返します。 1つのモジュール内(pyファイル)から複数回使用された場合でも、データベースの初期化処理が行われるのは 各モジュールあたり最初の一回だけです。 \"\"\" engine = create_engine(connection) session_factory = sessionmaker(bind=engine) Session", "import pytest, os from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session from", "def session_factory(connection): \"\"\" pytest対象モジュールの引数に\"session_factory\"を指定すると、 このfixtureが実行され、データベースの初期化を行った上でSQLAlchemyのscoped_sessionを返します。 1つのモジュール内(pyファイル)から複数回使用された場合でも、データベースの初期化処理が行われるのは 各モジュールあたり最初の一回だけです。 \"\"\" engine = create_engine(connection) session_factory =", "<reponame>showtatsu/python-bind9zone import pytest, os from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session", "*con, '--drop']).run() Bind9ZoneCLI(['bulkpush', *con, '--dir', ZONEDIR_SRC, '--zones', 'public/example.com,private/example.com' ]).run() return connection @pytest.fixture(scope='function') def", "ZONEDIR_SRC, '--zones', 'public/example.com,private/example.com' ]).run() return connection @pytest.fixture(scope='function') def session_factory(connection): \"\"\" pytest対象モジュールの引数に\"session_factory\"を指定すると、 このfixtureが実行され、データベースの初期化を行った上でSQLAlchemyのscoped_sessionを返します。 1つのモジュール内(pyファイル)から複数回使用された場合でも、データベースの初期化処理が行われるのは", "from bind9zone.cli import Bind9ZoneCLI ZONEDIR_SRC = 'tests/input' ZONEDIR = 'tests/output' def get_connection_fixture_params(): if", "if os.getenv('TEST_POSTGRES'): return ['sqlite:///tests/db.sqlite3', 'postgresql://postgres:postgres@db/database'] else: return ['sqlite:///tests/db.sqlite3'] @pytest.fixture() def zonedir_src(): return ZONEDIR_SRC", "= 'tests/output' def get_connection_fixture_params(): if os.getenv('TEST_POSTGRES'): return ['sqlite:///tests/db.sqlite3', 'postgresql://postgres:postgres@db/database'] else: return ['sqlite:///tests/db.sqlite3'] @pytest.fixture()", "= 'tests/input' ZONEDIR = 'tests/output' def get_connection_fixture_params(): if os.getenv('TEST_POSTGRES'): return ['sqlite:///tests/db.sqlite3', 'postgresql://postgres:postgres@db/database'] else:", "request.param con = ['--connection', connection] Bind9ZoneCLI(['init', *con, '--drop']).run() Bind9ZoneCLI(['bulkpush', *con, '--dir', ZONEDIR_SRC, '--zones',", "['sqlite:///tests/db.sqlite3', 'postgresql://postgres:postgres@db/database'] else: return ['sqlite:///tests/db.sqlite3'] @pytest.fixture() def zonedir_src(): return ZONEDIR_SRC @pytest.fixture() def zonedir():", "connection @pytest.fixture(scope='function') def session_factory(connection): \"\"\" pytest対象モジュールの引数に\"session_factory\"を指定すると、 このfixtureが実行され、データベースの初期化を行った上でSQLAlchemyのscoped_sessionを返します。 1つのモジュール内(pyファイル)から複数回使用された場合でも、データベースの初期化処理が行われるのは 各モジュールあたり最初の一回だけです。 \"\"\" engine = create_engine(connection)", "'tests/input' ZONEDIR = 'tests/output' def get_connection_fixture_params(): if os.getenv('TEST_POSTGRES'): return ['sqlite:///tests/db.sqlite3', 'postgresql://postgres:postgres@db/database'] else: return", "def connection(request): \"\"\" pytest対象モジュールの引数に\"connection\"を指定すると、 このfixtureが実行され、データベースの初期化を行った上でconnection文字列を返します。 1つのモジュール内(pyファイル)から複数回使用された場合でも、データベースの初期化処理が 行われるのは各モジュールあたり最初の一回だけです。 \"\"\" connection = request.param con =", "os.getenv('TEST_POSTGRES'): return ['sqlite:///tests/db.sqlite3', 'postgresql://postgres:postgres@db/database'] else: return ['sqlite:///tests/db.sqlite3'] @pytest.fixture() def zonedir_src(): return ZONEDIR_SRC @pytest.fixture()", "'--dir', ZONEDIR_SRC, '--zones', 'public/example.com,private/example.com' ]).run() return connection @pytest.fixture(scope='function') def session_factory(connection): \"\"\" pytest対象モジュールの引数に\"session_factory\"を指定すると、 このfixtureが実行され、データベースの初期化を行った上でSQLAlchemyのscoped_sessionを返します。" ]
[ "import os from setuptools import find_packages if __name__ == '__main__': for package in", "if __name__ == '__main__': for package in find_packages(): if '.test' in package: continue", "setuptools import find_packages if __name__ == '__main__': for package in find_packages(): if '.test'", "find_packages if __name__ == '__main__': for package in find_packages(): if '.test' in package:", "'__main__': for package in find_packages(): if '.test' in package: continue os.system(f'cmd /c \"python", "in find_packages(): if '.test' in package: continue os.system(f'cmd /c \"python -m pytest -s", "find_packages(): if '.test' in package: continue os.system(f'cmd /c \"python -m pytest -s {package}/test\"')", "from setuptools import find_packages if __name__ == '__main__': for package in find_packages(): if", "import find_packages if __name__ == '__main__': for package in find_packages(): if '.test' in", "os from setuptools import find_packages if __name__ == '__main__': for package in find_packages():", "== '__main__': for package in find_packages(): if '.test' in package: continue os.system(f'cmd /c", "package in find_packages(): if '.test' in package: continue os.system(f'cmd /c \"python -m pytest", "for package in find_packages(): if '.test' in package: continue os.system(f'cmd /c \"python -m", "__name__ == '__main__': for package in find_packages(): if '.test' in package: continue os.system(f'cmd" ]
[ "= logging.getLogger() logger.setLevel(logging.INFO) smtp_handler = logging.handlers.SMTPHandler(mailhost=('outgoing.mit.edu', 465), fromaddr='<EMAIL>', toaddrs=['<EMAIL>'], subject='Sample Log Mail', credentials=('austinsp','<PASSWORD>'),", "import logging.handlers logger = logging.getLogger() logger.setLevel(logging.INFO) smtp_handler = logging.handlers.SMTPHandler(mailhost=('outgoing.mit.edu', 465), fromaddr='<EMAIL>', toaddrs=['<EMAIL>'], subject='Sample", "= logging.handlers.SMTPHandler(mailhost=('outgoing.mit.edu', 465), fromaddr='<EMAIL>', toaddrs=['<EMAIL>'], subject='Sample Log Mail', credentials=('austinsp','<PASSWORD>'), secure=None) logger.addHandler(smtp_handler) logger.info(\"logger configured\")", "logger = logging.getLogger() logger.setLevel(logging.INFO) smtp_handler = logging.handlers.SMTPHandler(mailhost=('outgoing.mit.edu', 465), fromaddr='<EMAIL>', toaddrs=['<EMAIL>'], subject='Sample Log Mail',", "logging.handlers logger = logging.getLogger() logger.setLevel(logging.INFO) smtp_handler = logging.handlers.SMTPHandler(mailhost=('outgoing.mit.edu', 465), fromaddr='<EMAIL>', toaddrs=['<EMAIL>'], subject='Sample Log", "logging.getLogger() logger.setLevel(logging.INFO) smtp_handler = logging.handlers.SMTPHandler(mailhost=('outgoing.mit.edu', 465), fromaddr='<EMAIL>', toaddrs=['<EMAIL>'], subject='Sample Log Mail', credentials=('austinsp','<PASSWORD>'), secure=None)", "logger.setLevel(logging.INFO) smtp_handler = logging.handlers.SMTPHandler(mailhost=('outgoing.mit.edu', 465), fromaddr='<EMAIL>', toaddrs=['<EMAIL>'], subject='Sample Log Mail', credentials=('austinsp','<PASSWORD>'), secure=None) logger.addHandler(smtp_handler)", "logging.config import logging.handlers logger = logging.getLogger() logger.setLevel(logging.INFO) smtp_handler = logging.handlers.SMTPHandler(mailhost=('outgoing.mit.edu', 465), fromaddr='<EMAIL>', toaddrs=['<EMAIL>'],", "import logging.config import logging.handlers logger = logging.getLogger() logger.setLevel(logging.INFO) smtp_handler = logging.handlers.SMTPHandler(mailhost=('outgoing.mit.edu', 465), fromaddr='<EMAIL>',", "smtp_handler = logging.handlers.SMTPHandler(mailhost=('outgoing.mit.edu', 465), fromaddr='<EMAIL>', toaddrs=['<EMAIL>'], subject='Sample Log Mail', credentials=('austinsp','<PASSWORD>'), secure=None) logger.addHandler(smtp_handler) logger.info(\"logger" ]
[ "self.naucse_urls_to_freeze: while self.logged_calls: yield self.logged_calls.popleft() # Prefer URLs from logged_calls - ideally, cache", "import contextlib from collections import deque from flask import current_app from flask_frozen import", "logger # reverses the following operating from :class:`UrlForLogger` # self.app.url_default_functions.setdefault(None, []).insert(0, logger) app.url_default_functions[None].pop(0)", "# from the base repository. # That means we only yield from urls_to_freeze", "__init__(self, app, urls_to_freeze): super().__init__(app) self.naucse_urls_to_freeze = urls_to_freeze def iter_calls(self): \"\"\"Yield all logged urls", "repository. # That means we only yield from urls_to_freeze # if there are", "# reverses the following operating from :class:`UrlForLogger` # self.app.url_default_functions.setdefault(None, []).insert(0, logger) app.url_default_functions[None].pop(0) class", "That means we only yield from urls_to_freeze # if there are no logged_calls.", "used as the queues are # modified on the go. while self.logged_calls or", "UrlForLogger to the app. The logger is yielded as the context object, so", "__init__(self, app): super().__init__(app) urls_to_freeze = deque() with app.app_context(): app.config['NAUCSE_ABSOLUTE_URLS_TO_FREEZE'] = urls_to_freeze # override", "it can be used to get logged calls. \"\"\" logger = UrlForLogger(app) yield", "UrlForLogger, Freezer def record_url(url): \"\"\"Logs that `url` should be included in the resulting", "from the base repository. # That means we only yield from urls_to_freeze #", "to get logged calls. \"\"\" logger = UrlForLogger(app) yield logger # reverses the", "urls_to_freeze is not None: urls_to_freeze.append(url) class AllLinksLogger(UrlForLogger): \"\"\"Logs ``url_for`` calls, but yields urls", "from flask_frozen import UrlForLogger, Freezer def record_url(url): \"\"\"Logs that `url` should be included", "urls_to_freeze): super().__init__(app) self.naucse_urls_to_freeze = urls_to_freeze def iter_calls(self): \"\"\"Yield all logged urls and links", "import UrlForLogger, Freezer def record_url(url): \"\"\"Logs that `url` should be included in the", "yield from urls_to_freeze # if there are no logged_calls. if self.naucse_urls_to_freeze: yield self.naucse_urls_to_freeze.popleft()", "record_url(url): \"\"\"Logs that `url` should be included in the resulting static site\"\"\" urls_to_freeze", "with app.app_context(): app.config['NAUCSE_ABSOLUTE_URLS_TO_FREEZE'] = urls_to_freeze # override the default url_for_logger with our modified", "there are no logged_calls. if self.naucse_urls_to_freeze: yield self.naucse_urls_to_freeze.popleft() @contextlib.contextmanager def temporary_url_for_logger(app): \"\"\"Context manager", "logged_calls. if self.naucse_urls_to_freeze: yield self.naucse_urls_to_freeze.popleft() @contextlib.contextmanager def temporary_url_for_logger(app): \"\"\"Context manager which temporary adds", "used to get logged calls. \"\"\" logger = UrlForLogger(app) yield logger # reverses", "def __init__(self, app): super().__init__(app) urls_to_freeze = deque() with app.app_context(): app.config['NAUCSE_ABSOLUTE_URLS_TO_FREEZE'] = urls_to_freeze #", "yield logger # reverses the following operating from :class:`UrlForLogger` # self.app.url_default_functions.setdefault(None, []).insert(0, logger)", "new UrlForLogger to the app. The logger is yielded as the context object,", "`url` should be included in the resulting static site\"\"\" urls_to_freeze = current_app.config.get('NAUCSE_ABSOLUTE_URLS_TO_FREEZE') if", "yields urls from ``absolute_urls_to_freeze`` as well. \"\"\" def __init__(self, app, urls_to_freeze): super().__init__(app) self.naucse_urls_to_freeze", "go. while self.logged_calls or self.naucse_urls_to_freeze: while self.logged_calls: yield self.logged_calls.popleft() # Prefer URLs from", "= UrlForLogger(app) yield logger # reverses the following operating from :class:`UrlForLogger` # self.app.url_default_functions.setdefault(None,", "the go. while self.logged_calls or self.naucse_urls_to_freeze: while self.logged_calls: yield self.logged_calls.popleft() # Prefer URLs", "logger is yielded as the context object, so it can be used to", "collections import deque from flask import current_app from flask_frozen import UrlForLogger, Freezer def", "from`` cannot be used as the queues are # modified on the go.", "def __init__(self, app, urls_to_freeze): super().__init__(app) self.naucse_urls_to_freeze = urls_to_freeze def iter_calls(self): \"\"\"Yield all logged", "queues are # modified on the go. while self.logged_calls or self.naucse_urls_to_freeze: while self.logged_calls:", "is populated # from the base repository. # That means we only yield", "content. \"\"\" # Unfortunately, ``yield from`` cannot be used as the queues are", "``yield from`` cannot be used as the queues are # modified on the", "Unfortunately, ``yield from`` cannot be used as the queues are # modified on", "class NaucseFreezer(Freezer): def __init__(self, app): super().__init__(app) urls_to_freeze = deque() with app.app_context(): app.config['NAUCSE_ABSOLUTE_URLS_TO_FREEZE'] =", "yield self.logged_calls.popleft() # Prefer URLs from logged_calls - ideally, cache is populated #", "all logged urls and links parsed from content. \"\"\" # Unfortunately, ``yield from``", "``absolute_urls_to_freeze`` as well. \"\"\" def __init__(self, app, urls_to_freeze): super().__init__(app) self.naucse_urls_to_freeze = urls_to_freeze def", "= urls_to_freeze def iter_calls(self): \"\"\"Yield all logged urls and links parsed from content.", "urls_to_freeze # if there are no logged_calls. if self.naucse_urls_to_freeze: yield self.naucse_urls_to_freeze.popleft() @contextlib.contextmanager def", "if there are no logged_calls. if self.naucse_urls_to_freeze: yield self.naucse_urls_to_freeze.popleft() @contextlib.contextmanager def temporary_url_for_logger(app): \"\"\"Context", "def temporary_url_for_logger(app): \"\"\"Context manager which temporary adds a new UrlForLogger to the app.", "The logger is yielded as the context object, so it can be used", "to the app. The logger is yielded as the context object, so it", "app.app_context(): app.config['NAUCSE_ABSOLUTE_URLS_TO_FREEZE'] = urls_to_freeze # override the default url_for_logger with our modified version", "the following operating from :class:`UrlForLogger` # self.app.url_default_functions.setdefault(None, []).insert(0, logger) app.url_default_functions[None].pop(0) class NaucseFreezer(Freezer): def", "# modified on the go. while self.logged_calls or self.naucse_urls_to_freeze: while self.logged_calls: yield self.logged_calls.popleft()", "manager which temporary adds a new UrlForLogger to the app. The logger is", "flask import current_app from flask_frozen import UrlForLogger, Freezer def record_url(url): \"\"\"Logs that `url`", "urls from ``absolute_urls_to_freeze`` as well. \"\"\" def __init__(self, app, urls_to_freeze): super().__init__(app) self.naucse_urls_to_freeze =", "app. The logger is yielded as the context object, so it can be", "links parsed from content. \"\"\" # Unfortunately, ``yield from`` cannot be used as", "or self.naucse_urls_to_freeze: while self.logged_calls: yield self.logged_calls.popleft() # Prefer URLs from logged_calls - ideally,", "ideally, cache is populated # from the base repository. # That means we", "can be used to get logged calls. \"\"\" logger = UrlForLogger(app) yield logger", "``url_for`` calls, but yields urls from ``absolute_urls_to_freeze`` as well. \"\"\" def __init__(self, app,", "modified on the go. while self.logged_calls or self.naucse_urls_to_freeze: while self.logged_calls: yield self.logged_calls.popleft() #", "yield self.naucse_urls_to_freeze.popleft() @contextlib.contextmanager def temporary_url_for_logger(app): \"\"\"Context manager which temporary adds a new UrlForLogger", "yielded as the context object, so it can be used to get logged", "app.config['NAUCSE_ABSOLUTE_URLS_TO_FREEZE'] = urls_to_freeze # override the default url_for_logger with our modified version self.url_for_logger", "logged urls and links parsed from content. \"\"\" # Unfortunately, ``yield from`` cannot", "that `url` should be included in the resulting static site\"\"\" urls_to_freeze = current_app.config.get('NAUCSE_ABSOLUTE_URLS_TO_FREEZE')", "= current_app.config.get('NAUCSE_ABSOLUTE_URLS_TO_FREEZE') if urls_to_freeze is not None: urls_to_freeze.append(url) class AllLinksLogger(UrlForLogger): \"\"\"Logs ``url_for`` calls,", "get logged calls. \"\"\" logger = UrlForLogger(app) yield logger # reverses the following", "from flask import current_app from flask_frozen import UrlForLogger, Freezer def record_url(url): \"\"\"Logs that", "\"\"\"Logs ``url_for`` calls, but yields urls from ``absolute_urls_to_freeze`` as well. \"\"\" def __init__(self,", "Prefer URLs from logged_calls - ideally, cache is populated # from the base", "only yield from urls_to_freeze # if there are no logged_calls. if self.naucse_urls_to_freeze: yield", "NaucseFreezer(Freezer): def __init__(self, app): super().__init__(app) urls_to_freeze = deque() with app.app_context(): app.config['NAUCSE_ABSOLUTE_URLS_TO_FREEZE'] = urls_to_freeze", "temporary_url_for_logger(app): \"\"\"Context manager which temporary adds a new UrlForLogger to the app. The", ":class:`UrlForLogger` # self.app.url_default_functions.setdefault(None, []).insert(0, logger) app.url_default_functions[None].pop(0) class NaucseFreezer(Freezer): def __init__(self, app): super().__init__(app) urls_to_freeze", "logger) app.url_default_functions[None].pop(0) class NaucseFreezer(Freezer): def __init__(self, app): super().__init__(app) urls_to_freeze = deque() with app.app_context():", "urls_to_freeze = deque() with app.app_context(): app.config['NAUCSE_ABSOLUTE_URLS_TO_FREEZE'] = urls_to_freeze # override the default url_for_logger", "we only yield from urls_to_freeze # if there are no logged_calls. if self.naucse_urls_to_freeze:", "static site\"\"\" urls_to_freeze = current_app.config.get('NAUCSE_ABSOLUTE_URLS_TO_FREEZE') if urls_to_freeze is not None: urls_to_freeze.append(url) class AllLinksLogger(UrlForLogger):", "calls, but yields urls from ``absolute_urls_to_freeze`` as well. \"\"\" def __init__(self, app, urls_to_freeze):", "while self.logged_calls or self.naucse_urls_to_freeze: while self.logged_calls: yield self.logged_calls.popleft() # Prefer URLs from logged_calls", "# if there are no logged_calls. if self.naucse_urls_to_freeze: yield self.naucse_urls_to_freeze.popleft() @contextlib.contextmanager def temporary_url_for_logger(app):", "self.app.url_default_functions.setdefault(None, []).insert(0, logger) app.url_default_functions[None].pop(0) class NaucseFreezer(Freezer): def __init__(self, app): super().__init__(app) urls_to_freeze = deque()", "app, urls_to_freeze): super().__init__(app) self.naucse_urls_to_freeze = urls_to_freeze def iter_calls(self): \"\"\"Yield all logged urls and", "@contextlib.contextmanager def temporary_url_for_logger(app): \"\"\"Context manager which temporary adds a new UrlForLogger to the", "are no logged_calls. if self.naucse_urls_to_freeze: yield self.naucse_urls_to_freeze.popleft() @contextlib.contextmanager def temporary_url_for_logger(app): \"\"\"Context manager which", "is yielded as the context object, so it can be used to get", "the context object, so it can be used to get logged calls. \"\"\"", "but yields urls from ``absolute_urls_to_freeze`` as well. \"\"\" def __init__(self, app, urls_to_freeze): super().__init__(app)", "contextlib from collections import deque from flask import current_app from flask_frozen import UrlForLogger,", "self.naucse_urls_to_freeze.popleft() @contextlib.contextmanager def temporary_url_for_logger(app): \"\"\"Context manager which temporary adds a new UrlForLogger to", "not None: urls_to_freeze.append(url) class AllLinksLogger(UrlForLogger): \"\"\"Logs ``url_for`` calls, but yields urls from ``absolute_urls_to_freeze``", "parsed from content. \"\"\" # Unfortunately, ``yield from`` cannot be used as the", "\"\"\" def __init__(self, app, urls_to_freeze): super().__init__(app) self.naucse_urls_to_freeze = urls_to_freeze def iter_calls(self): \"\"\"Yield all", "app.url_default_functions[None].pop(0) class NaucseFreezer(Freezer): def __init__(self, app): super().__init__(app) urls_to_freeze = deque() with app.app_context(): app.config['NAUCSE_ABSOLUTE_URLS_TO_FREEZE']", "the app. The logger is yielded as the context object, so it can", "deque from flask import current_app from flask_frozen import UrlForLogger, Freezer def record_url(url): \"\"\"Logs", "import deque from flask import current_app from flask_frozen import UrlForLogger, Freezer def record_url(url):", "if urls_to_freeze is not None: urls_to_freeze.append(url) class AllLinksLogger(UrlForLogger): \"\"\"Logs ``url_for`` calls, but yields", "the resulting static site\"\"\" urls_to_freeze = current_app.config.get('NAUCSE_ABSOLUTE_URLS_TO_FREEZE') if urls_to_freeze is not None: urls_to_freeze.append(url)", "# Unfortunately, ``yield from`` cannot be used as the queues are # modified", "is not None: urls_to_freeze.append(url) class AllLinksLogger(UrlForLogger): \"\"\"Logs ``url_for`` calls, but yields urls from", "well. \"\"\" def __init__(self, app, urls_to_freeze): super().__init__(app) self.naucse_urls_to_freeze = urls_to_freeze def iter_calls(self): \"\"\"Yield", "base repository. # That means we only yield from urls_to_freeze # if there", "super().__init__(app) self.naucse_urls_to_freeze = urls_to_freeze def iter_calls(self): \"\"\"Yield all logged urls and links parsed", "iter_calls(self): \"\"\"Yield all logged urls and links parsed from content. \"\"\" # Unfortunately,", "def iter_calls(self): \"\"\"Yield all logged urls and links parsed from content. \"\"\" #", "= deque() with app.app_context(): app.config['NAUCSE_ABSOLUTE_URLS_TO_FREEZE'] = urls_to_freeze # override the default url_for_logger with", "\"\"\"Context manager which temporary adds a new UrlForLogger to the app. The logger", "the base repository. # That means we only yield from urls_to_freeze # if", "def record_url(url): \"\"\"Logs that `url` should be included in the resulting static site\"\"\"", "self.logged_calls: yield self.logged_calls.popleft() # Prefer URLs from logged_calls - ideally, cache is populated", "# Prefer URLs from logged_calls - ideally, cache is populated # from the", "as the queues are # modified on the go. while self.logged_calls or self.naucse_urls_to_freeze:", "which temporary adds a new UrlForLogger to the app. The logger is yielded", "if self.naucse_urls_to_freeze: yield self.naucse_urls_to_freeze.popleft() @contextlib.contextmanager def temporary_url_for_logger(app): \"\"\"Context manager which temporary adds a", "so it can be used to get logged calls. \"\"\" logger = UrlForLogger(app)", "self.naucse_urls_to_freeze = urls_to_freeze def iter_calls(self): \"\"\"Yield all logged urls and links parsed from", "the queues are # modified on the go. while self.logged_calls or self.naucse_urls_to_freeze: while", "flask_frozen import UrlForLogger, Freezer def record_url(url): \"\"\"Logs that `url` should be included in", "app): super().__init__(app) urls_to_freeze = deque() with app.app_context(): app.config['NAUCSE_ABSOLUTE_URLS_TO_FREEZE'] = urls_to_freeze # override the", "# self.app.url_default_functions.setdefault(None, []).insert(0, logger) app.url_default_functions[None].pop(0) class NaucseFreezer(Freezer): def __init__(self, app): super().__init__(app) urls_to_freeze =", "cannot be used as the queues are # modified on the go. while", "adds a new UrlForLogger to the app. The logger is yielded as the", "urls_to_freeze # override the default url_for_logger with our modified version self.url_for_logger = AllLinksLogger(app,", "be included in the resulting static site\"\"\" urls_to_freeze = current_app.config.get('NAUCSE_ABSOLUTE_URLS_TO_FREEZE') if urls_to_freeze is", "should be included in the resulting static site\"\"\" urls_to_freeze = current_app.config.get('NAUCSE_ABSOLUTE_URLS_TO_FREEZE') if urls_to_freeze", "self.logged_calls or self.naucse_urls_to_freeze: while self.logged_calls: yield self.logged_calls.popleft() # Prefer URLs from logged_calls -", "logger = UrlForLogger(app) yield logger # reverses the following operating from :class:`UrlForLogger` #", "# override the default url_for_logger with our modified version self.url_for_logger = AllLinksLogger(app, urls_to_freeze)", "in the resulting static site\"\"\" urls_to_freeze = current_app.config.get('NAUCSE_ABSOLUTE_URLS_TO_FREEZE') if urls_to_freeze is not None:", "AllLinksLogger(UrlForLogger): \"\"\"Logs ``url_for`` calls, but yields urls from ``absolute_urls_to_freeze`` as well. \"\"\" def", "\"\"\" logger = UrlForLogger(app) yield logger # reverses the following operating from :class:`UrlForLogger`", "urls_to_freeze = current_app.config.get('NAUCSE_ABSOLUTE_URLS_TO_FREEZE') if urls_to_freeze is not None: urls_to_freeze.append(url) class AllLinksLogger(UrlForLogger): \"\"\"Logs ``url_for``", "included in the resulting static site\"\"\" urls_to_freeze = current_app.config.get('NAUCSE_ABSOLUTE_URLS_TO_FREEZE') if urls_to_freeze is not", "logged calls. \"\"\" logger = UrlForLogger(app) yield logger # reverses the following operating", "from :class:`UrlForLogger` # self.app.url_default_functions.setdefault(None, []).insert(0, logger) app.url_default_functions[None].pop(0) class NaucseFreezer(Freezer): def __init__(self, app): super().__init__(app)", "deque() with app.app_context(): app.config['NAUCSE_ABSOLUTE_URLS_TO_FREEZE'] = urls_to_freeze # override the default url_for_logger with our", "[]).insert(0, logger) app.url_default_functions[None].pop(0) class NaucseFreezer(Freezer): def __init__(self, app): super().__init__(app) urls_to_freeze = deque() with", "on the go. while self.logged_calls or self.naucse_urls_to_freeze: while self.logged_calls: yield self.logged_calls.popleft() # Prefer", "None: urls_to_freeze.append(url) class AllLinksLogger(UrlForLogger): \"\"\"Logs ``url_for`` calls, but yields urls from ``absolute_urls_to_freeze`` as", "urls_to_freeze def iter_calls(self): \"\"\"Yield all logged urls and links parsed from content. \"\"\"", "as the context object, so it can be used to get logged calls.", "- ideally, cache is populated # from the base repository. # That means", "self.naucse_urls_to_freeze: yield self.naucse_urls_to_freeze.popleft() @contextlib.contextmanager def temporary_url_for_logger(app): \"\"\"Context manager which temporary adds a new", "Freezer def record_url(url): \"\"\"Logs that `url` should be included in the resulting static", "temporary adds a new UrlForLogger to the app. The logger is yielded as", "<reponame>OndSeb/naucse.python.cz<filename>naucse/freezer.py<gh_stars>0 import contextlib from collections import deque from flask import current_app from flask_frozen", "from ``absolute_urls_to_freeze`` as well. \"\"\" def __init__(self, app, urls_to_freeze): super().__init__(app) self.naucse_urls_to_freeze = urls_to_freeze", "from logged_calls - ideally, cache is populated # from the base repository. #", "no logged_calls. if self.naucse_urls_to_freeze: yield self.naucse_urls_to_freeze.popleft() @contextlib.contextmanager def temporary_url_for_logger(app): \"\"\"Context manager which temporary", "UrlForLogger(app) yield logger # reverses the following operating from :class:`UrlForLogger` # self.app.url_default_functions.setdefault(None, []).insert(0,", "\"\"\"Logs that `url` should be included in the resulting static site\"\"\" urls_to_freeze =", "as well. \"\"\" def __init__(self, app, urls_to_freeze): super().__init__(app) self.naucse_urls_to_freeze = urls_to_freeze def iter_calls(self):", "from collections import deque from flask import current_app from flask_frozen import UrlForLogger, Freezer", "and links parsed from content. \"\"\" # Unfortunately, ``yield from`` cannot be used", "resulting static site\"\"\" urls_to_freeze = current_app.config.get('NAUCSE_ABSOLUTE_URLS_TO_FREEZE') if urls_to_freeze is not None: urls_to_freeze.append(url) class", "reverses the following operating from :class:`UrlForLogger` # self.app.url_default_functions.setdefault(None, []).insert(0, logger) app.url_default_functions[None].pop(0) class NaucseFreezer(Freezer):", "cache is populated # from the base repository. # That means we only", "logged_calls - ideally, cache is populated # from the base repository. # That", "object, so it can be used to get logged calls. \"\"\" logger =", "while self.logged_calls: yield self.logged_calls.popleft() # Prefer URLs from logged_calls - ideally, cache is", "urls and links parsed from content. \"\"\" # Unfortunately, ``yield from`` cannot be", "self.logged_calls.popleft() # Prefer URLs from logged_calls - ideally, cache is populated # from", "means we only yield from urls_to_freeze # if there are no logged_calls. if", "class AllLinksLogger(UrlForLogger): \"\"\"Logs ``url_for`` calls, but yields urls from ``absolute_urls_to_freeze`` as well. \"\"\"", "calls. \"\"\" logger = UrlForLogger(app) yield logger # reverses the following operating from", "super().__init__(app) urls_to_freeze = deque() with app.app_context(): app.config['NAUCSE_ABSOLUTE_URLS_TO_FREEZE'] = urls_to_freeze # override the default", "= urls_to_freeze # override the default url_for_logger with our modified version self.url_for_logger =", "following operating from :class:`UrlForLogger` # self.app.url_default_functions.setdefault(None, []).insert(0, logger) app.url_default_functions[None].pop(0) class NaucseFreezer(Freezer): def __init__(self,", "\"\"\" # Unfortunately, ``yield from`` cannot be used as the queues are #", "urls_to_freeze.append(url) class AllLinksLogger(UrlForLogger): \"\"\"Logs ``url_for`` calls, but yields urls from ``absolute_urls_to_freeze`` as well.", "from content. \"\"\" # Unfortunately, ``yield from`` cannot be used as the queues", "from urls_to_freeze # if there are no logged_calls. if self.naucse_urls_to_freeze: yield self.naucse_urls_to_freeze.popleft() @contextlib.contextmanager", "a new UrlForLogger to the app. The logger is yielded as the context", "current_app.config.get('NAUCSE_ABSOLUTE_URLS_TO_FREEZE') if urls_to_freeze is not None: urls_to_freeze.append(url) class AllLinksLogger(UrlForLogger): \"\"\"Logs ``url_for`` calls, but", "context object, so it can be used to get logged calls. \"\"\" logger", "import current_app from flask_frozen import UrlForLogger, Freezer def record_url(url): \"\"\"Logs that `url` should", "populated # from the base repository. # That means we only yield from", "URLs from logged_calls - ideally, cache is populated # from the base repository.", "be used to get logged calls. \"\"\" logger = UrlForLogger(app) yield logger #", "site\"\"\" urls_to_freeze = current_app.config.get('NAUCSE_ABSOLUTE_URLS_TO_FREEZE') if urls_to_freeze is not None: urls_to_freeze.append(url) class AllLinksLogger(UrlForLogger): \"\"\"Logs", "be used as the queues are # modified on the go. while self.logged_calls", "are # modified on the go. while self.logged_calls or self.naucse_urls_to_freeze: while self.logged_calls: yield", "# That means we only yield from urls_to_freeze # if there are no", "\"\"\"Yield all logged urls and links parsed from content. \"\"\" # Unfortunately, ``yield", "current_app from flask_frozen import UrlForLogger, Freezer def record_url(url): \"\"\"Logs that `url` should be", "operating from :class:`UrlForLogger` # self.app.url_default_functions.setdefault(None, []).insert(0, logger) app.url_default_functions[None].pop(0) class NaucseFreezer(Freezer): def __init__(self, app):" ]
[ "neighbour) i += 1 except IndexError: self._relabel(n) i = 0 self.current_neighbhours[n] = i", "return False self.height[n] = 1 + min_neighbour_height return True def _init_preflow(self): excess =", "height = {k: 0 for k in self.flow_network.node_set} self.flow_network.reset() s = self.flow_network.source height[s]", "= height def _get_overflowing_node(self): for n, f in self.excess.items(): if f > 0", "res = self._push(node, neighbour) if res: break if not res: self._relabel(node) node =", "self.height[n2] + 1: return False delta_flow = min(self.excess[n1], cf) try: self.flow_network.increase_flow(n1, n2, delta_flow)", "i = 0 self.current_neighbhours[n] = i def relabel_to_front(self): self._init_preflow() node_list = list(self.flow_network.node_set -", "self.flow_network.node_set} self.flow_network.reset() s = self.flow_network.source height[s] = self.flow_network.total_nodes for n in self.flow_network.get_node_neighbours(s): c", "and residual.get_arc_capacity(n, neighbour) > 0: min_neighbour_height = n_height if self.height[n] > n_height: return", "return n def generic_push_relabel(self): self._init_preflow() node = self._get_overflowing_node() while node is not None:", "= 0 i += 1 except IndexError: break return self.flow_network.get_current_flows() def generic_push_relabel(flow_network): return", "relabel_to_front(self): self._init_preflow() node_list = list(self.flow_network.node_set - {self.flow_network.source, self.flow_network.sink}) i = 0 while True:", "neighbours: n_height = self.height[neighbour] if n_height < min_neighbour_height and residual.get_arc_capacity(n, neighbour) > 0:", "= n_height if self.height[n] > n_height: return False self.height[n] = 1 + min_neighbour_height", "def _discharge(self, n): i = self.current_neighbhours[n] neighbour_list = self.all_neighbours[n] while self.excess[n] > 0:", "neighbour_list = self.all_neighbours[n] while self.excess[n] > 0: try: neighbour = neighbour_list[i] success =", "self._relabel(n) i = 0 self.current_neighbhours[n] = i def relabel_to_front(self): self._init_preflow() node_list = list(self.flow_network.node_set", "for k in self.flow_network.node_set} self.flow_network.reset() s = self.flow_network.source height[s] = self.flow_network.total_nodes for n", "delta_flow = min(self.excess[n1], cf) try: self.flow_network.increase_flow(n1, n2, delta_flow) except KeyError: self.flow_network.decrease_flow(n2, n1, delta_flow)", "+ min_neighbour_height return True def _init_preflow(self): excess = {k: 0 for k in", "all_neighbours[n2].add(n1) self.all_neighbours = {k: list(v) for k, v in all_neighbours.items()} def _push(self, n1,", "n_height: return False self.height[n] = 1 + min_neighbour_height return True def _init_preflow(self): excess", "residual.get_node_neighbours(n) min_neighbour_height = float('inf') for neighbour in neighbours: n_height = self.height[neighbour] if n_height", "return self.flow_network.get_current_flows() def _discharge(self, n): i = self.current_neighbhours[n] neighbour_list = self.all_neighbours[n] while self.excess[n]", "- {self.flow_network.source, self.flow_network.sink}) i = 0 while True: try: n = node_list[i] old_height", "= 0 while True: try: n = node_list[i] old_height = self.height[n] self._discharge(n) if", "+ 1: return False delta_flow = min(self.excess[n1], cf) try: self.flow_network.increase_flow(n1, n2, delta_flow) except", "self._relabel(node) node = self._get_overflowing_node() return self.flow_network.get_current_flows() def _discharge(self, n): i = self.current_neighbhours[n] neighbour_list", "min_neighbour_height return True def _init_preflow(self): excess = {k: 0 for k in self.flow_network.node_set}", "n in self.flow_network.get_node_neighbours(s): c = self.flow_network.get_arc_capacity(s, n) self.flow_network.set_flow(s, n, c) excess[n] = c", "= i def relabel_to_front(self): self._init_preflow() node_list = list(self.flow_network.node_set - {self.flow_network.source, self.flow_network.sink}) i =", "def _push(self, n1, n2): residual = self.flow_network.residual cf = residual.get_arc_capacity(n1, n2) if cf", "self.current_neighbhours = {k: 0 for k in flow_network.node_set} def _init_node_neighbour_lists(self): all_neighbours = defaultdict(set)", "self.height[n1] != self.height[n2] + 1: return False delta_flow = min(self.excess[n1], cf) try: self.flow_network.increase_flow(n1,", "list(self.flow_network.node_set - {self.flow_network.source, self.flow_network.sink}) i = 0 while True: try: n = node_list[i]", "n, f in self.excess.items(): if f > 0 and n != self.flow_network.source and", "self.flow_network.get_node_neighbours(s): c = self.flow_network.get_arc_capacity(s, n) self.flow_network.set_flow(s, n, c) excess[n] = c excess[s] -=", "self.height[n] > n_height: return False self.height[n] = 1 + min_neighbour_height return True def", "f in self.excess.items(): if f > 0 and n != self.flow_network.source and n", "cf <= 0 or self.height[n1] != self.height[n2] + 1: return False delta_flow =", "self._discharge(n) if self.height[n] > old_height: node_list.pop(i) node_list.insert(0, n) i = 0 i +=", "= 1 + min_neighbour_height return True def _init_preflow(self): excess = {k: 0 for", "+= 1 except IndexError: self._relabel(n) i = 0 self.current_neighbhours[n] = i def relabel_to_front(self):", "all_neighbours.items()} def _push(self, n1, n2): residual = self.flow_network.residual cf = residual.get_arc_capacity(n1, n2) if", "self.flow_network.source and n != self.flow_network.sink: return n def generic_push_relabel(self): self._init_preflow() node = self._get_overflowing_node()", "self.flow_network.nodes: all_neighbours[n1].add(n2) all_neighbours[n2].add(n1) self.all_neighbours = {k: list(v) for k, v in all_neighbours.items()} def", "neighbours = residual.get_node_neighbours(n) min_neighbour_height = float('inf') for neighbour in neighbours: n_height = self.height[neighbour]", "self.flow_network.increase_flow(n1, n2, delta_flow) except KeyError: self.flow_network.decrease_flow(n2, n1, delta_flow) self.excess[n1] -= delta_flow self.excess[n2] +=", "for k, v in all_neighbours.items()} def _push(self, n1, n2): residual = self.flow_network.residual cf", "i += 1 except IndexError: break return self.flow_network.get_current_flows() def generic_push_relabel(flow_network): return PushRelabel(flow_network).generic_push_relabel() def", "for k in flow_network.node_set} def _init_node_neighbour_lists(self): all_neighbours = defaultdict(set) for n1, n2 in", "= 'Copyright (c) 2015 Seven Bridges Genomics' from collections import defaultdict class PushRelabel(object):", "not res: self._relabel(node) node = self._get_overflowing_node() return self.flow_network.get_current_flows() def _discharge(self, n): i =", "n def generic_push_relabel(self): self._init_preflow() node = self._get_overflowing_node() while node is not None: res", "cf = residual.get_arc_capacity(n1, n2) if cf <= 0 or self.height[n1] != self.height[n2] +", "self.height[n] > old_height: node_list.pop(i) node_list.insert(0, n) i = 0 i += 1 except", "n1, n2 in self.flow_network.nodes: all_neighbours[n1].add(n2) all_neighbours[n2].add(n1) self.all_neighbours = {k: list(v) for k, v", "__author__ = '<NAME> <<EMAIL>>' __date__ = '30 August 2015' __copyright__ = 'Copyright (c)", "self.flow_network.source height[s] = self.flow_network.total_nodes for n in self.flow_network.get_node_neighbours(s): c = self.flow_network.get_arc_capacity(s, n) self.flow_network.set_flow(s,", "__date__ = '30 August 2015' __copyright__ = 'Copyright (c) 2015 Seven Bridges Genomics'", "= residual.get_arc_capacity(n1, n2) if cf <= 0 or self.height[n1] != self.height[n2] + 1:", "__copyright__ = 'Copyright (c) 2015 Seven Bridges Genomics' from collections import defaultdict class", "self.flow_network.residual neighbours = residual.get_node_neighbours(n) min_neighbour_height = float('inf') for neighbour in neighbours: n_height =", "= excess self.height = height def _get_overflowing_node(self): for n, f in self.excess.items(): if", "self.excess.items(): if f > 0 and n != self.flow_network.source and n != self.flow_network.sink:", "n = node_list[i] old_height = self.height[n] self._discharge(n) if self.height[n] > old_height: node_list.pop(i) node_list.insert(0,", "self.flow_network.sink}) i = 0 while True: try: n = node_list[i] old_height = self.height[n]", "def generic_push_relabel(self): self._init_preflow() node = self._get_overflowing_node() while node is not None: res =", "self.flow_network.residual cf = residual.get_arc_capacity(n1, n2) if cf <= 0 or self.height[n1] != self.height[n2]", "self.excess = {} self._init_node_neighbour_lists() self.current_neighbhours = {k: 0 for k in flow_network.node_set} def", "Bridges Genomics' from collections import defaultdict class PushRelabel(object): def __init__(self, flow_network): self.flow_network =", "k in self.flow_network.node_set} height = {k: 0 for k in self.flow_network.node_set} self.flow_network.reset() s", "is not None: res = False for neighbour in self.flow_network.residual.get_node_neighbours(node): res = self._push(node,", "neighbour in neighbours: n_height = self.height[neighbour] if n_height < min_neighbour_height and residual.get_arc_capacity(n, neighbour)", "_push(self, n1, n2): residual = self.flow_network.residual cf = residual.get_arc_capacity(n1, n2) if cf <=", "min(self.excess[n1], cf) try: self.flow_network.increase_flow(n1, n2, delta_flow) except KeyError: self.flow_network.decrease_flow(n2, n1, delta_flow) self.excess[n1] -=", "c excess[s] -= c self.excess = excess self.height = height def _get_overflowing_node(self): for", "delta_flow return True def _relabel(self, n): residual = self.flow_network.residual neighbours = residual.get_node_neighbours(n) min_neighbour_height", "False for neighbour in self.flow_network.residual.get_node_neighbours(node): res = self._push(node, neighbour) if res: break if", "1 except IndexError: self._relabel(n) i = 0 self.current_neighbhours[n] = i def relabel_to_front(self): self._init_preflow()", "= self.flow_network.get_arc_capacity(s, n) self.flow_network.set_flow(s, n, c) excess[n] = c excess[s] -= c self.excess", "self.flow_network.decrease_flow(n2, n1, delta_flow) self.excess[n1] -= delta_flow self.excess[n2] += delta_flow return True def _relabel(self,", "= {} self.excess = {} self._init_node_neighbour_lists() self.current_neighbhours = {k: 0 for k in", "self._get_overflowing_node() while node is not None: res = False for neighbour in self.flow_network.residual.get_node_neighbours(node):", "n): residual = self.flow_network.residual neighbours = residual.get_node_neighbours(n) min_neighbour_height = float('inf') for neighbour in", "height[s] = self.flow_network.total_nodes for n in self.flow_network.get_node_neighbours(s): c = self.flow_network.get_arc_capacity(s, n) self.flow_network.set_flow(s, n,", "old_height: node_list.pop(i) node_list.insert(0, n) i = 0 i += 1 except IndexError: break", "in neighbours: n_height = self.height[neighbour] if n_height < min_neighbour_height and residual.get_arc_capacity(n, neighbour) >", "try: neighbour = neighbour_list[i] success = self._push(n, neighbour) i += 1 except IndexError:", "node_list.insert(0, n) i = 0 i += 1 except IndexError: break return self.flow_network.get_current_flows()", "_get_overflowing_node(self): for n, f in self.excess.items(): if f > 0 and n !=", "= self.flow_network.total_nodes for n in self.flow_network.get_node_neighbours(s): c = self.flow_network.get_arc_capacity(s, n) self.flow_network.set_flow(s, n, c)", "self._get_overflowing_node() return self.flow_network.get_current_flows() def _discharge(self, n): i = self.current_neighbhours[n] neighbour_list = self.all_neighbours[n] while", "i += 1 except IndexError: self._relabel(n) i = 0 self.current_neighbhours[n] = i def", "Seven Bridges Genomics' from collections import defaultdict class PushRelabel(object): def __init__(self, flow_network): self.flow_network", "= False for neighbour in self.flow_network.residual.get_node_neighbours(node): res = self._push(node, neighbour) if res: break", "= self._get_overflowing_node() return self.flow_network.get_current_flows() def _discharge(self, n): i = self.current_neighbhours[n] neighbour_list = self.all_neighbours[n]", "0 and n != self.flow_network.source and n != self.flow_network.sink: return n def generic_push_relabel(self):", "excess = {k: 0 for k in self.flow_network.node_set} height = {k: 0 for", "self.height[n] self._discharge(n) if self.height[n] > old_height: node_list.pop(i) node_list.insert(0, n) i = 0 i", "min_neighbour_height = n_height if self.height[n] > n_height: return False self.height[n] = 1 +", "residual.get_arc_capacity(n, neighbour) > 0: min_neighbour_height = n_height if self.height[n] > n_height: return False", "self.excess[n] > 0: try: neighbour = neighbour_list[i] success = self._push(n, neighbour) i +=", "self.height = height def _get_overflowing_node(self): for n, f in self.excess.items(): if f >", "True def _init_preflow(self): excess = {k: 0 for k in self.flow_network.node_set} height =", "0: try: neighbour = neighbour_list[i] success = self._push(n, neighbour) i += 1 except", "node_list = list(self.flow_network.node_set - {self.flow_network.source, self.flow_network.sink}) i = 0 while True: try: n", "= {k: 0 for k in self.flow_network.node_set} self.flow_network.reset() s = self.flow_network.source height[s] =", "while True: try: n = node_list[i] old_height = self.height[n] self._discharge(n) if self.height[n] >", "i = 0 while True: try: n = node_list[i] old_height = self.height[n] self._discharge(n)", "c self.excess = excess self.height = height def _get_overflowing_node(self): for n, f in", "if n_height < min_neighbour_height and residual.get_arc_capacity(n, neighbour) > 0: min_neighbour_height = n_height if", "0: min_neighbour_height = n_height if self.height[n] > n_height: return False self.height[n] = 1", "c) excess[n] = c excess[s] -= c self.excess = excess self.height = height", "and n != self.flow_network.source and n != self.flow_network.sink: return n def generic_push_relabel(self): self._init_preflow()", "'30 August 2015' __copyright__ = 'Copyright (c) 2015 Seven Bridges Genomics' from collections", "self.current_neighbhours[n] neighbour_list = self.all_neighbours[n] while self.excess[n] > 0: try: neighbour = neighbour_list[i] success", "= node_list[i] old_height = self.height[n] self._discharge(n) if self.height[n] > old_height: node_list.pop(i) node_list.insert(0, n)", "all_neighbours = defaultdict(set) for n1, n2 in self.flow_network.nodes: all_neighbours[n1].add(n2) all_neighbours[n2].add(n1) self.all_neighbours = {k:", "excess[s] -= c self.excess = excess self.height = height def _get_overflowing_node(self): for n,", "= self.current_neighbhours[n] neighbour_list = self.all_neighbours[n] while self.excess[n] > 0: try: neighbour = neighbour_list[i]", "= flow_network self.height = {} self.excess = {} self._init_node_neighbour_lists() self.current_neighbhours = {k: 0", "k in self.flow_network.node_set} self.flow_network.reset() s = self.flow_network.source height[s] = self.flow_network.total_nodes for n in", "!= self.flow_network.source and n != self.flow_network.sink: return n def generic_push_relabel(self): self._init_preflow() node =", "self.height = {} self.excess = {} self._init_node_neighbour_lists() self.current_neighbhours = {k: 0 for k", "res: self._relabel(node) node = self._get_overflowing_node() return self.flow_network.get_current_flows() def _discharge(self, n): i = self.current_neighbhours[n]", "node = self._get_overflowing_node() while node is not None: res = False for neighbour", "in self.flow_network.node_set} height = {k: 0 for k in self.flow_network.node_set} self.flow_network.reset() s =", "v in all_neighbours.items()} def _push(self, n1, n2): residual = self.flow_network.residual cf = residual.get_arc_capacity(n1,", "= list(self.flow_network.node_set - {self.flow_network.source, self.flow_network.sink}) i = 0 while True: try: n =", "Genomics' from collections import defaultdict class PushRelabel(object): def __init__(self, flow_network): self.flow_network = flow_network", "= neighbour_list[i] success = self._push(n, neighbour) i += 1 except IndexError: self._relabel(n) i", "n): i = self.current_neighbhours[n] neighbour_list = self.all_neighbours[n] while self.excess[n] > 0: try: neighbour", "return True def _init_preflow(self): excess = {k: 0 for k in self.flow_network.node_set} height", "self.flow_network.node_set} height = {k: 0 for k in self.flow_network.node_set} self.flow_network.reset() s = self.flow_network.source", "August 2015' __copyright__ = 'Copyright (c) 2015 Seven Bridges Genomics' from collections import", "self.excess[n1] -= delta_flow self.excess[n2] += delta_flow return True def _relabel(self, n): residual =", "self.current_neighbhours[n] = i def relabel_to_front(self): self._init_preflow() node_list = list(self.flow_network.node_set - {self.flow_network.source, self.flow_network.sink}) i", "= self._push(node, neighbour) if res: break if not res: self._relabel(node) node = self._get_overflowing_node()", "__init__(self, flow_network): self.flow_network = flow_network self.height = {} self.excess = {} self._init_node_neighbour_lists() self.current_neighbhours", "{} self.excess = {} self._init_node_neighbour_lists() self.current_neighbhours = {k: 0 for k in flow_network.node_set}", "1: return False delta_flow = min(self.excess[n1], cf) try: self.flow_network.increase_flow(n1, n2, delta_flow) except KeyError:", "1 + min_neighbour_height return True def _init_preflow(self): excess = {k: 0 for k", "= self.flow_network.residual neighbours = residual.get_node_neighbours(n) min_neighbour_height = float('inf') for neighbour in neighbours: n_height", "i def relabel_to_front(self): self._init_preflow() node_list = list(self.flow_network.node_set - {self.flow_network.source, self.flow_network.sink}) i = 0", "self.flow_network.get_current_flows() def _discharge(self, n): i = self.current_neighbhours[n] neighbour_list = self.all_neighbours[n] while self.excess[n] >", "c = self.flow_network.get_arc_capacity(s, n) self.flow_network.set_flow(s, n, c) excess[n] = c excess[s] -= c", "self.all_neighbours[n] while self.excess[n] > 0: try: neighbour = neighbour_list[i] success = self._push(n, neighbour)", "> 0: min_neighbour_height = n_height if self.height[n] > n_height: return False self.height[n] =", "_relabel(self, n): residual = self.flow_network.residual neighbours = residual.get_node_neighbours(n) min_neighbour_height = float('inf') for neighbour", "except IndexError: break return self.flow_network.get_current_flows() def generic_push_relabel(flow_network): return PushRelabel(flow_network).generic_push_relabel() def relabel_to_front(flow_network): return PushRelabel(flow_network).relabel_to_front()", "= residual.get_node_neighbours(n) min_neighbour_height = float('inf') for neighbour in neighbours: n_height = self.height[neighbour] if", "0 for k in flow_network.node_set} def _init_node_neighbour_lists(self): all_neighbours = defaultdict(set) for n1, n2", "in self.excess.items(): if f > 0 and n != self.flow_network.source and n !=", "residual = self.flow_network.residual cf = residual.get_arc_capacity(n1, n2) if cf <= 0 or self.height[n1]", "delta_flow) except KeyError: self.flow_network.decrease_flow(n2, n1, delta_flow) self.excess[n1] -= delta_flow self.excess[n2] += delta_flow return", "in self.flow_network.nodes: all_neighbours[n1].add(n2) all_neighbours[n2].add(n1) self.all_neighbours = {k: list(v) for k, v in all_neighbours.items()}", "from collections import defaultdict class PushRelabel(object): def __init__(self, flow_network): self.flow_network = flow_network self.height", "self._push(n, neighbour) i += 1 except IndexError: self._relabel(n) i = 0 self.current_neighbhours[n] =", "f > 0 and n != self.flow_network.source and n != self.flow_network.sink: return n", "= {k: 0 for k in flow_network.node_set} def _init_node_neighbour_lists(self): all_neighbours = defaultdict(set) for", "0 or self.height[n1] != self.height[n2] + 1: return False delta_flow = min(self.excess[n1], cf)", "-= c self.excess = excess self.height = height def _get_overflowing_node(self): for n, f", "in self.flow_network.node_set} self.flow_network.reset() s = self.flow_network.source height[s] = self.flow_network.total_nodes for n in self.flow_network.get_node_neighbours(s):", "residual = self.flow_network.residual neighbours = residual.get_node_neighbours(n) min_neighbour_height = float('inf') for neighbour in neighbours:", "n2) if cf <= 0 or self.height[n1] != self.height[n2] + 1: return False", "def _init_preflow(self): excess = {k: 0 for k in self.flow_network.node_set} height = {k:", "if not res: self._relabel(node) node = self._get_overflowing_node() return self.flow_network.get_current_flows() def _discharge(self, n): i", "= min(self.excess[n1], cf) try: self.flow_network.increase_flow(n1, n2, delta_flow) except KeyError: self.flow_network.decrease_flow(n2, n1, delta_flow) self.excess[n1]", "import defaultdict class PushRelabel(object): def __init__(self, flow_network): self.flow_network = flow_network self.height = {}", "= self.flow_network.source height[s] = self.flow_network.total_nodes for n in self.flow_network.get_node_neighbours(s): c = self.flow_network.get_arc_capacity(s, n)", "list(v) for k, v in all_neighbours.items()} def _push(self, n1, n2): residual = self.flow_network.residual", "self.flow_network.sink: return n def generic_push_relabel(self): self._init_preflow() node = self._get_overflowing_node() while node is not", "= '<NAME> <<EMAIL>>' __date__ = '30 August 2015' __copyright__ = 'Copyright (c) 2015", "False delta_flow = min(self.excess[n1], cf) try: self.flow_network.increase_flow(n1, n2, delta_flow) except KeyError: self.flow_network.decrease_flow(n2, n1,", "in self.flow_network.get_node_neighbours(s): c = self.flow_network.get_arc_capacity(s, n) self.flow_network.set_flow(s, n, c) excess[n] = c excess[s]", "= self.height[n] self._discharge(n) if self.height[n] > old_height: node_list.pop(i) node_list.insert(0, n) i = 0", "for n in self.flow_network.get_node_neighbours(s): c = self.flow_network.get_arc_capacity(s, n) self.flow_network.set_flow(s, n, c) excess[n] =", "if res: break if not res: self._relabel(node) node = self._get_overflowing_node() return self.flow_network.get_current_flows() def", "neighbour = neighbour_list[i] success = self._push(n, neighbour) i += 1 except IndexError: self._relabel(n)", "defaultdict(set) for n1, n2 in self.flow_network.nodes: all_neighbours[n1].add(n2) all_neighbours[n2].add(n1) self.all_neighbours = {k: list(v) for", "def _init_node_neighbour_lists(self): all_neighbours = defaultdict(set) for n1, n2 in self.flow_network.nodes: all_neighbours[n1].add(n2) all_neighbours[n2].add(n1) self.all_neighbours", "for neighbour in self.flow_network.residual.get_node_neighbours(node): res = self._push(node, neighbour) if res: break if not", "> 0 and n != self.flow_network.source and n != self.flow_network.sink: return n def", "_discharge(self, n): i = self.current_neighbhours[n] neighbour_list = self.all_neighbours[n] while self.excess[n] > 0: try:", "_init_preflow(self): excess = {k: 0 for k in self.flow_network.node_set} height = {k: 0", "0 for k in self.flow_network.node_set} height = {k: 0 for k in self.flow_network.node_set}", "_init_node_neighbour_lists(self): all_neighbours = defaultdict(set) for n1, n2 in self.flow_network.nodes: all_neighbours[n1].add(n2) all_neighbours[n2].add(n1) self.all_neighbours =", "try: n = node_list[i] old_height = self.height[n] self._discharge(n) if self.height[n] > old_height: node_list.pop(i)", "neighbour) > 0: min_neighbour_height = n_height if self.height[n] > n_height: return False self.height[n]", "0 for k in self.flow_network.node_set} self.flow_network.reset() s = self.flow_network.source height[s] = self.flow_network.total_nodes for", "= defaultdict(set) for n1, n2 in self.flow_network.nodes: all_neighbours[n1].add(n2) all_neighbours[n2].add(n1) self.all_neighbours = {k: list(v)", "self.excess = excess self.height = height def _get_overflowing_node(self): for n, f in self.excess.items():", "for n1, n2 in self.flow_network.nodes: all_neighbours[n1].add(n2) all_neighbours[n2].add(n1) self.all_neighbours = {k: list(v) for k,", "in flow_network.node_set} def _init_node_neighbour_lists(self): all_neighbours = defaultdict(set) for n1, n2 in self.flow_network.nodes: all_neighbours[n1].add(n2)", "= float('inf') for neighbour in neighbours: n_height = self.height[neighbour] if n_height < min_neighbour_height", "IndexError: self._relabel(n) i = 0 self.current_neighbhours[n] = i def relabel_to_front(self): self._init_preflow() node_list =", "self.flow_network = flow_network self.height = {} self.excess = {} self._init_node_neighbour_lists() self.current_neighbhours = {k:", "def __init__(self, flow_network): self.flow_network = flow_network self.height = {} self.excess = {} self._init_node_neighbour_lists()", "node = self._get_overflowing_node() return self.flow_network.get_current_flows() def _discharge(self, n): i = self.current_neighbhours[n] neighbour_list =", "float('inf') for neighbour in neighbours: n_height = self.height[neighbour] if n_height < min_neighbour_height and", "n != self.flow_network.sink: return n def generic_push_relabel(self): self._init_preflow() node = self._get_overflowing_node() while node", "self._init_preflow() node_list = list(self.flow_network.node_set - {self.flow_network.source, self.flow_network.sink}) i = 0 while True: try:", "class PushRelabel(object): def __init__(self, flow_network): self.flow_network = flow_network self.height = {} self.excess =", "flow_network.node_set} def _init_node_neighbour_lists(self): all_neighbours = defaultdict(set) for n1, n2 in self.flow_network.nodes: all_neighbours[n1].add(n2) all_neighbours[n2].add(n1)", "k in flow_network.node_set} def _init_node_neighbour_lists(self): all_neighbours = defaultdict(set) for n1, n2 in self.flow_network.nodes:", "{k: 0 for k in self.flow_network.node_set} height = {k: 0 for k in", "= c excess[s] -= c self.excess = excess self.height = height def _get_overflowing_node(self):", "res = False for neighbour in self.flow_network.residual.get_node_neighbours(node): res = self._push(node, neighbour) if res:", "0 self.current_neighbhours[n] = i def relabel_to_front(self): self._init_preflow() node_list = list(self.flow_network.node_set - {self.flow_network.source, self.flow_network.sink})", "n_height = self.height[neighbour] if n_height < min_neighbour_height and residual.get_arc_capacity(n, neighbour) > 0: min_neighbour_height", "n) self.flow_network.set_flow(s, n, c) excess[n] = c excess[s] -= c self.excess = excess", "= self._push(n, neighbour) i += 1 except IndexError: self._relabel(n) i = 0 self.current_neighbhours[n]", "return False delta_flow = min(self.excess[n1], cf) try: self.flow_network.increase_flow(n1, n2, delta_flow) except KeyError: self.flow_network.decrease_flow(n2,", "node_list[i] old_height = self.height[n] self._discharge(n) if self.height[n] > old_height: node_list.pop(i) node_list.insert(0, n) i", "except IndexError: self._relabel(n) i = 0 self.current_neighbhours[n] = i def relabel_to_front(self): self._init_preflow() node_list", "neighbour_list[i] success = self._push(n, neighbour) i += 1 except IndexError: self._relabel(n) i =", "delta_flow self.excess[n2] += delta_flow return True def _relabel(self, n): residual = self.flow_network.residual neighbours", "= self.flow_network.residual cf = residual.get_arc_capacity(n1, n2) if cf <= 0 or self.height[n1] !=", "i = self.current_neighbhours[n] neighbour_list = self.all_neighbours[n] while self.excess[n] > 0: try: neighbour =", "{k: 0 for k in self.flow_network.node_set} self.flow_network.reset() s = self.flow_network.source height[s] = self.flow_network.total_nodes", "for k in self.flow_network.node_set} height = {k: 0 for k in self.flow_network.node_set} self.flow_network.reset()", "> old_height: node_list.pop(i) node_list.insert(0, n) i = 0 i += 1 except IndexError:", "generic_push_relabel(self): self._init_preflow() node = self._get_overflowing_node() while node is not None: res = False", "not None: res = False for neighbour in self.flow_network.residual.get_node_neighbours(node): res = self._push(node, neighbour)", "= self.height[neighbour] if n_height < min_neighbour_height and residual.get_arc_capacity(n, neighbour) > 0: min_neighbour_height =", "res: break if not res: self._relabel(node) node = self._get_overflowing_node() return self.flow_network.get_current_flows() def _discharge(self,", "n != self.flow_network.source and n != self.flow_network.sink: return n def generic_push_relabel(self): self._init_preflow() node", "KeyError: self.flow_network.decrease_flow(n2, n1, delta_flow) self.excess[n1] -= delta_flow self.excess[n2] += delta_flow return True def", "{} self._init_node_neighbour_lists() self.current_neighbhours = {k: 0 for k in flow_network.node_set} def _init_node_neighbour_lists(self): all_neighbours", "None: res = False for neighbour in self.flow_network.residual.get_node_neighbours(node): res = self._push(node, neighbour) if", "0 i += 1 except IndexError: break return self.flow_network.get_current_flows() def generic_push_relabel(flow_network): return PushRelabel(flow_network).generic_push_relabel()", "= '30 August 2015' __copyright__ = 'Copyright (c) 2015 Seven Bridges Genomics' from", "min_neighbour_height and residual.get_arc_capacity(n, neighbour) > 0: min_neighbour_height = n_height if self.height[n] > n_height:", "True def _relabel(self, n): residual = self.flow_network.residual neighbours = residual.get_node_neighbours(n) min_neighbour_height = float('inf')", "return True def _relabel(self, n): residual = self.flow_network.residual neighbours = residual.get_node_neighbours(n) min_neighbour_height =", "while node is not None: res = False for neighbour in self.flow_network.residual.get_node_neighbours(node): res", "'Copyright (c) 2015 Seven Bridges Genomics' from collections import defaultdict class PushRelabel(object): def", "self.all_neighbours = {k: list(v) for k, v in all_neighbours.items()} def _push(self, n1, n2):", "= {k: 0 for k in self.flow_network.node_set} height = {k: 0 for k", "self.flow_network.set_flow(s, n, c) excess[n] = c excess[s] -= c self.excess = excess self.height", "self.flow_network.residual.get_node_neighbours(node): res = self._push(node, neighbour) if res: break if not res: self._relabel(node) node", "(c) 2015 Seven Bridges Genomics' from collections import defaultdict class PushRelabel(object): def __init__(self,", "i = 0 i += 1 except IndexError: break return self.flow_network.get_current_flows() def generic_push_relabel(flow_network):", "= self.all_neighbours[n] while self.excess[n] > 0: try: neighbour = neighbour_list[i] success = self._push(n,", "= {k: list(v) for k, v in all_neighbours.items()} def _push(self, n1, n2): residual", "while self.excess[n] > 0: try: neighbour = neighbour_list[i] success = self._push(n, neighbour) i", "+= 1 except IndexError: break return self.flow_network.get_current_flows() def generic_push_relabel(flow_network): return PushRelabel(flow_network).generic_push_relabel() def relabel_to_front(flow_network):", "cf) try: self.flow_network.increase_flow(n1, n2, delta_flow) except KeyError: self.flow_network.decrease_flow(n2, n1, delta_flow) self.excess[n1] -= delta_flow", "for n, f in self.excess.items(): if f > 0 and n != self.flow_network.source", "2015 Seven Bridges Genomics' from collections import defaultdict class PushRelabel(object): def __init__(self, flow_network):", "n_height if self.height[n] > n_height: return False self.height[n] = 1 + min_neighbour_height return", "excess[n] = c excess[s] -= c self.excess = excess self.height = height def", "> 0: try: neighbour = neighbour_list[i] success = self._push(n, neighbour) i += 1", "def relabel_to_front(self): self._init_preflow() node_list = list(self.flow_network.node_set - {self.flow_network.source, self.flow_network.sink}) i = 0 while", "neighbour in self.flow_network.residual.get_node_neighbours(node): res = self._push(node, neighbour) if res: break if not res:", "or self.height[n1] != self.height[n2] + 1: return False delta_flow = min(self.excess[n1], cf) try:", "flow_network self.height = {} self.excess = {} self._init_node_neighbour_lists() self.current_neighbhours = {k: 0 for", "!= self.height[n2] + 1: return False delta_flow = min(self.excess[n1], cf) try: self.flow_network.increase_flow(n1, n2,", "if f > 0 and n != self.flow_network.source and n != self.flow_network.sink: return", "and n != self.flow_network.sink: return n def generic_push_relabel(self): self._init_preflow() node = self._get_overflowing_node() while", "{self.flow_network.source, self.flow_network.sink}) i = 0 while True: try: n = node_list[i] old_height =", "2015' __copyright__ = 'Copyright (c) 2015 Seven Bridges Genomics' from collections import defaultdict", "flow_network): self.flow_network = flow_network self.height = {} self.excess = {} self._init_node_neighbour_lists() self.current_neighbhours =", "node is not None: res = False for neighbour in self.flow_network.residual.get_node_neighbours(node): res =", "def _get_overflowing_node(self): for n, f in self.excess.items(): if f > 0 and n", "except KeyError: self.flow_network.decrease_flow(n2, n1, delta_flow) self.excess[n1] -= delta_flow self.excess[n2] += delta_flow return True", "success = self._push(n, neighbour) i += 1 except IndexError: self._relabel(n) i = 0", "self._init_preflow() node = self._get_overflowing_node() while node is not None: res = False for", "<<EMAIL>>' __date__ = '30 August 2015' __copyright__ = 'Copyright (c) 2015 Seven Bridges", "False self.height[n] = 1 + min_neighbour_height return True def _init_preflow(self): excess = {k:", "if self.height[n] > old_height: node_list.pop(i) node_list.insert(0, n) i = 0 i += 1", "-= delta_flow self.excess[n2] += delta_flow return True def _relabel(self, n): residual = self.flow_network.residual", "neighbour) if res: break if not res: self._relabel(node) node = self._get_overflowing_node() return self.flow_network.get_current_flows()", "True: try: n = node_list[i] old_height = self.height[n] self._discharge(n) if self.height[n] > old_height:", "1 except IndexError: break return self.flow_network.get_current_flows() def generic_push_relabel(flow_network): return PushRelabel(flow_network).generic_push_relabel() def relabel_to_front(flow_network): return", "if cf <= 0 or self.height[n1] != self.height[n2] + 1: return False delta_flow", "height def _get_overflowing_node(self): for n, f in self.excess.items(): if f > 0 and", "self.excess[n2] += delta_flow return True def _relabel(self, n): residual = self.flow_network.residual neighbours =", "self.height[neighbour] if n_height < min_neighbour_height and residual.get_arc_capacity(n, neighbour) > 0: min_neighbour_height = n_height", "in self.flow_network.residual.get_node_neighbours(node): res = self._push(node, neighbour) if res: break if not res: self._relabel(node)", "old_height = self.height[n] self._discharge(n) if self.height[n] > old_height: node_list.pop(i) node_list.insert(0, n) i =", "<= 0 or self.height[n1] != self.height[n2] + 1: return False delta_flow = min(self.excess[n1],", "= 0 self.current_neighbhours[n] = i def relabel_to_front(self): self._init_preflow() node_list = list(self.flow_network.node_set - {self.flow_network.source,", "{k: list(v) for k, v in all_neighbours.items()} def _push(self, n1, n2): residual =", "self.flow_network.reset() s = self.flow_network.source height[s] = self.flow_network.total_nodes for n in self.flow_network.get_node_neighbours(s): c =", "{k: 0 for k in flow_network.node_set} def _init_node_neighbour_lists(self): all_neighbours = defaultdict(set) for n1,", "def _relabel(self, n): residual = self.flow_network.residual neighbours = residual.get_node_neighbours(n) min_neighbour_height = float('inf') for", "n_height < min_neighbour_height and residual.get_arc_capacity(n, neighbour) > 0: min_neighbour_height = n_height if self.height[n]", "in all_neighbours.items()} def _push(self, n1, n2): residual = self.flow_network.residual cf = residual.get_arc_capacity(n1, n2)", "min_neighbour_height = float('inf') for neighbour in neighbours: n_height = self.height[neighbour] if n_height <", "n2): residual = self.flow_network.residual cf = residual.get_arc_capacity(n1, n2) if cf <= 0 or", "k, v in all_neighbours.items()} def _push(self, n1, n2): residual = self.flow_network.residual cf =", "self.flow_network.total_nodes for n in self.flow_network.get_node_neighbours(s): c = self.flow_network.get_arc_capacity(s, n) self.flow_network.set_flow(s, n, c) excess[n]", "n1, n2): residual = self.flow_network.residual cf = residual.get_arc_capacity(n1, n2) if cf <= 0", "defaultdict class PushRelabel(object): def __init__(self, flow_network): self.flow_network = flow_network self.height = {} self.excess", "collections import defaultdict class PushRelabel(object): def __init__(self, flow_network): self.flow_network = flow_network self.height =", "0 while True: try: n = node_list[i] old_height = self.height[n] self._discharge(n) if self.height[n]", "n2 in self.flow_network.nodes: all_neighbours[n1].add(n2) all_neighbours[n2].add(n1) self.all_neighbours = {k: list(v) for k, v in", "self.flow_network.get_arc_capacity(s, n) self.flow_network.set_flow(s, n, c) excess[n] = c excess[s] -= c self.excess =", "all_neighbours[n1].add(n2) all_neighbours[n2].add(n1) self.all_neighbours = {k: list(v) for k, v in all_neighbours.items()} def _push(self,", "if self.height[n] > n_height: return False self.height[n] = 1 + min_neighbour_height return True", "> n_height: return False self.height[n] = 1 + min_neighbour_height return True def _init_preflow(self):", "'<NAME> <<EMAIL>>' __date__ = '30 August 2015' __copyright__ = 'Copyright (c) 2015 Seven", "<reponame>JovanCe/mfp<gh_stars>0 __author__ = '<NAME> <<EMAIL>>' __date__ = '30 August 2015' __copyright__ = 'Copyright", "= {} self._init_node_neighbour_lists() self.current_neighbhours = {k: 0 for k in flow_network.node_set} def _init_node_neighbour_lists(self):", "!= self.flow_network.sink: return n def generic_push_relabel(self): self._init_preflow() node = self._get_overflowing_node() while node is", "= self._get_overflowing_node() while node is not None: res = False for neighbour in", "PushRelabel(object): def __init__(self, flow_network): self.flow_network = flow_network self.height = {} self.excess = {}", "n) i = 0 i += 1 except IndexError: break return self.flow_network.get_current_flows() def", "self.height[n] = 1 + min_neighbour_height return True def _init_preflow(self): excess = {k: 0", "break if not res: self._relabel(node) node = self._get_overflowing_node() return self.flow_network.get_current_flows() def _discharge(self, n):", "< min_neighbour_height and residual.get_arc_capacity(n, neighbour) > 0: min_neighbour_height = n_height if self.height[n] >", "residual.get_arc_capacity(n1, n2) if cf <= 0 or self.height[n1] != self.height[n2] + 1: return", "excess self.height = height def _get_overflowing_node(self): for n, f in self.excess.items(): if f", "for neighbour in neighbours: n_height = self.height[neighbour] if n_height < min_neighbour_height and residual.get_arc_capacity(n,", "n, c) excess[n] = c excess[s] -= c self.excess = excess self.height =", "delta_flow) self.excess[n1] -= delta_flow self.excess[n2] += delta_flow return True def _relabel(self, n): residual", "s = self.flow_network.source height[s] = self.flow_network.total_nodes for n in self.flow_network.get_node_neighbours(s): c = self.flow_network.get_arc_capacity(s,", "+= delta_flow return True def _relabel(self, n): residual = self.flow_network.residual neighbours = residual.get_node_neighbours(n)", "n2, delta_flow) except KeyError: self.flow_network.decrease_flow(n2, n1, delta_flow) self.excess[n1] -= delta_flow self.excess[n2] += delta_flow", "self._push(node, neighbour) if res: break if not res: self._relabel(node) node = self._get_overflowing_node() return", "node_list.pop(i) node_list.insert(0, n) i = 0 i += 1 except IndexError: break return", "n1, delta_flow) self.excess[n1] -= delta_flow self.excess[n2] += delta_flow return True def _relabel(self, n):", "try: self.flow_network.increase_flow(n1, n2, delta_flow) except KeyError: self.flow_network.decrease_flow(n2, n1, delta_flow) self.excess[n1] -= delta_flow self.excess[n2]", "self._init_node_neighbour_lists() self.current_neighbhours = {k: 0 for k in flow_network.node_set} def _init_node_neighbour_lists(self): all_neighbours =" ]
[ "taskManagerModule import taskManager import thread import threading import file_operate # import core def", "import taskManager import thread import threading import file_operate # import core def error(code):", "idChannel = int(threading.currentThread().getName()) # taskManager.shareInstance().notify(idChannel, 100 + code) # file_operate.printf('%s Failed at code", "taskManager.shareInstance().notify(idChannel, 100 + code) # file_operate.printf('%s Failed at code %s!' % (idChannel, -100", "int(threading.currentThread().getName()) # taskManager.shareInstance().notify(idChannel, 100 + code) # file_operate.printf('%s Failed at code %s!' %", "taskManager import thread import threading import file_operate # import core def error(code): return", "import thread import threading import file_operate # import core def error(code): return #", "<reponame>game-platform-awaresome/XSdkTools<gh_stars>1-10 #Embedded file name: D:/AnySDK_Package/Env/debug/../script\\error_operate.py # from taskManagerModule import taskManager import thread import", "import file_operate # import core def error(code): return # idChannel = int(threading.currentThread().getName()) #", "threading import file_operate # import core def error(code): return # idChannel = int(threading.currentThread().getName())", "from taskManagerModule import taskManager import thread import threading import file_operate # import core", "core def error(code): return # idChannel = int(threading.currentThread().getName()) # taskManager.shareInstance().notify(idChannel, 100 + code)", "= int(threading.currentThread().getName()) # taskManager.shareInstance().notify(idChannel, 100 + code) # file_operate.printf('%s Failed at code %s!'", "100 + code) # file_operate.printf('%s Failed at code %s!' % (idChannel, -100 -", "return # idChannel = int(threading.currentThread().getName()) # taskManager.shareInstance().notify(idChannel, 100 + code) # file_operate.printf('%s Failed", "# from taskManagerModule import taskManager import thread import threading import file_operate # import", "#Embedded file name: D:/AnySDK_Package/Env/debug/../script\\error_operate.py # from taskManagerModule import taskManager import thread import threading", "file_operate # import core def error(code): return # idChannel = int(threading.currentThread().getName()) # taskManager.shareInstance().notify(idChannel,", "thread import threading import file_operate # import core def error(code): return # idChannel", "# idChannel = int(threading.currentThread().getName()) # taskManager.shareInstance().notify(idChannel, 100 + code) # file_operate.printf('%s Failed at", "def error(code): return # idChannel = int(threading.currentThread().getName()) # taskManager.shareInstance().notify(idChannel, 100 + code) #", "import core def error(code): return # idChannel = int(threading.currentThread().getName()) # taskManager.shareInstance().notify(idChannel, 100 +", "# import core def error(code): return # idChannel = int(threading.currentThread().getName()) # taskManager.shareInstance().notify(idChannel, 100", "file name: D:/AnySDK_Package/Env/debug/../script\\error_operate.py # from taskManagerModule import taskManager import thread import threading import", "# taskManager.shareInstance().notify(idChannel, 100 + code) # file_operate.printf('%s Failed at code %s!' % (idChannel,", "D:/AnySDK_Package/Env/debug/../script\\error_operate.py # from taskManagerModule import taskManager import thread import threading import file_operate #", "error(code): return # idChannel = int(threading.currentThread().getName()) # taskManager.shareInstance().notify(idChannel, 100 + code) # file_operate.printf('%s", "name: D:/AnySDK_Package/Env/debug/../script\\error_operate.py # from taskManagerModule import taskManager import thread import threading import file_operate", "import threading import file_operate # import core def error(code): return # idChannel =", "+ code) # file_operate.printf('%s Failed at code %s!' % (idChannel, -100 - code))" ]
[ "of all excel localisations all_localisations = all_localisations() # list of top level localisations", "'FTP', 'TPO Junction', 'PO', 'FP'] if Bayesian: redistributed = ['FT', 'FTP', 'PO', 'Perisylvian',", "list of localisations to drop minor_locs = [ loc for loc in all_localisations", "drop minor_locs = [ loc for loc in all_localisations if loc not in", "want to keep def top_level_lobes(Bayesian=False): Lobes = ['TL', 'FL', 'CING', 'PL', 'OL', 'INSULA',", "'Perisylvian', 'FT', 'TO', 'TP', 'FTP', 'TPO Junction', 'PO', 'FP'] if Bayesian: redistributed =", "np import pandas as pd from mega_analysis.crosstab.all_localisations import all_localisations # list of all", "'FP'] if Bayesian: redistributed = ['FT', 'FTP', 'PO', 'Perisylvian', 'FP', 'Sub-Callosal Cortex', 'TO',", "= [i for i in Lobes if i not in redistributed] return Lobes", "top_level_lobes(Bayesian=False): Lobes = ['TL', 'FL', 'CING', 'PL', 'OL', 'INSULA', 'Hypothalamus', 'Sub-Callosal Cortex', 'Cerebellum',", "'FP', 'Sub-Callosal Cortex', 'TO', 'TPO Junction', 'TP'] redistributed.append('Cerebellum') Lobes = [i for i", "import pandas as pd from mega_analysis.crosstab.all_localisations import all_localisations # list of all excel", "list of top level localisations we want to keep def top_level_lobes(Bayesian=False): Lobes =", "'TP', 'FTP', 'TPO Junction', 'PO', 'FP'] if Bayesian: redistributed = ['FT', 'FTP', 'PO',", "Bayesian: redistributed = ['FT', 'FTP', 'PO', 'Perisylvian', 'FP', 'Sub-Callosal Cortex', 'TO', 'TPO Junction',", "'Perisylvian', 'FP', 'Sub-Callosal Cortex', 'TO', 'TPO Junction', 'TP'] redistributed.append('Cerebellum') Lobes = [i for", "'PO', 'FP'] if Bayesian: redistributed = ['FT', 'FTP', 'PO', 'Perisylvian', 'FP', 'Sub-Callosal Cortex',", "not in redistributed] return Lobes major_localisations = top_level_lobes() # list of localisations to", "'PO', 'Perisylvian', 'FP', 'Sub-Callosal Cortex', 'TO', 'TPO Junction', 'TP'] redistributed.append('Cerebellum') Lobes = [i", "Cortex', 'TO', 'TPO Junction', 'TP'] redistributed.append('Cerebellum') Lobes = [i for i in Lobes", "minor_locs = [ loc for loc in all_localisations if loc not in major_localisations]", "top level localisations we want to keep def top_level_lobes(Bayesian=False): Lobes = ['TL', 'FL',", "in redistributed] return Lobes major_localisations = top_level_lobes() # list of localisations to drop", "as np import pandas as pd from mega_analysis.crosstab.all_localisations import all_localisations # list of", "Junction', 'PO', 'FP'] if Bayesian: redistributed = ['FT', 'FTP', 'PO', 'Perisylvian', 'FP', 'Sub-Callosal", "loc for loc in all_localisations if loc not in major_localisations] def drop_minor_localisations(df): df_temp", "import all_localisations # list of all excel localisations all_localisations = all_localisations() # list", "redistributed] return Lobes major_localisations = top_level_lobes() # list of localisations to drop minor_locs", "# list of all excel localisations all_localisations = all_localisations() # list of top", "= all_localisations() # list of top level localisations we want to keep def", "'Hypothalamus', 'Sub-Callosal Cortex', 'Cerebellum', 'Perisylvian', 'FT', 'TO', 'TP', 'FTP', 'TPO Junction', 'PO', 'FP']", "localisations all_localisations = all_localisations() # list of top level localisations we want to", "loc not in major_localisations] def drop_minor_localisations(df): df_temp = df.drop(columns=minor_locs, inplace=False, errors='ignore') return df_temp", "all_localisations # list of all excel localisations all_localisations = all_localisations() # list of", "major_localisations = top_level_lobes() # list of localisations to drop minor_locs = [ loc", "all_localisations if loc not in major_localisations] def drop_minor_localisations(df): df_temp = df.drop(columns=minor_locs, inplace=False, errors='ignore')", "i not in redistributed] return Lobes major_localisations = top_level_lobes() # list of localisations", "redistributed = ['FT', 'FTP', 'PO', 'Perisylvian', 'FP', 'Sub-Callosal Cortex', 'TO', 'TPO Junction', 'TP']", "all_localisations() # list of top level localisations we want to keep def top_level_lobes(Bayesian=False):", "'OL', 'INSULA', 'Hypothalamus', 'Sub-Callosal Cortex', 'Cerebellum', 'Perisylvian', 'FT', 'TO', 'TP', 'FTP', 'TPO Junction',", "all excel localisations all_localisations = all_localisations() # list of top level localisations we", "<reponame>thenineteen/Semiology-Visualisation-Tool<filename>mega_analysis/crosstab/lobe_top_level_hierarchy_only.py import numpy as np import pandas as pd from mega_analysis.crosstab.all_localisations import all_localisations", "in Lobes if i not in redistributed] return Lobes major_localisations = top_level_lobes() #", "'TO', 'TP', 'FTP', 'TPO Junction', 'PO', 'FP'] if Bayesian: redistributed = ['FT', 'FTP',", "top_level_lobes() # list of localisations to drop minor_locs = [ loc for loc", "import numpy as np import pandas as pd from mega_analysis.crosstab.all_localisations import all_localisations #", "loc in all_localisations if loc not in major_localisations] def drop_minor_localisations(df): df_temp = df.drop(columns=minor_locs,", "pd from mega_analysis.crosstab.all_localisations import all_localisations # list of all excel localisations all_localisations =", "Lobes = ['TL', 'FL', 'CING', 'PL', 'OL', 'INSULA', 'Hypothalamus', 'Sub-Callosal Cortex', 'Cerebellum', 'Perisylvian',", "'Sub-Callosal Cortex', 'TO', 'TPO Junction', 'TP'] redistributed.append('Cerebellum') Lobes = [i for i in", "return Lobes major_localisations = top_level_lobes() # list of localisations to drop minor_locs =", "in all_localisations if loc not in major_localisations] def drop_minor_localisations(df): df_temp = df.drop(columns=minor_locs, inplace=False,", "for i in Lobes if i not in redistributed] return Lobes major_localisations =", "from mega_analysis.crosstab.all_localisations import all_localisations # list of all excel localisations all_localisations = all_localisations()", "to keep def top_level_lobes(Bayesian=False): Lobes = ['TL', 'FL', 'CING', 'PL', 'OL', 'INSULA', 'Hypothalamus',", "Lobes if i not in redistributed] return Lobes major_localisations = top_level_lobes() # list", "'FT', 'TO', 'TP', 'FTP', 'TPO Junction', 'PO', 'FP'] if Bayesian: redistributed = ['FT',", "'TPO Junction', 'TP'] redistributed.append('Cerebellum') Lobes = [i for i in Lobes if i", "'FTP', 'PO', 'Perisylvian', 'FP', 'Sub-Callosal Cortex', 'TO', 'TPO Junction', 'TP'] redistributed.append('Cerebellum') Lobes =", "# list of localisations to drop minor_locs = [ loc for loc in", "'CING', 'PL', 'OL', 'INSULA', 'Hypothalamus', 'Sub-Callosal Cortex', 'Cerebellum', 'Perisylvian', 'FT', 'TO', 'TP', 'FTP',", "pandas as pd from mega_analysis.crosstab.all_localisations import all_localisations # list of all excel localisations", "list of all excel localisations all_localisations = all_localisations() # list of top level", "'TO', 'TPO Junction', 'TP'] redistributed.append('Cerebellum') Lobes = [i for i in Lobes if", "'INSULA', 'Hypothalamus', 'Sub-Callosal Cortex', 'Cerebellum', 'Perisylvian', 'FT', 'TO', 'TP', 'FTP', 'TPO Junction', 'PO',", "Junction', 'TP'] redistributed.append('Cerebellum') Lobes = [i for i in Lobes if i not", "Lobes major_localisations = top_level_lobes() # list of localisations to drop minor_locs = [", "'PL', 'OL', 'INSULA', 'Hypothalamus', 'Sub-Callosal Cortex', 'Cerebellum', 'Perisylvian', 'FT', 'TO', 'TP', 'FTP', 'TPO", "excel localisations all_localisations = all_localisations() # list of top level localisations we want", "level localisations we want to keep def top_level_lobes(Bayesian=False): Lobes = ['TL', 'FL', 'CING',", "# list of top level localisations we want to keep def top_level_lobes(Bayesian=False): Lobes", "of top level localisations we want to keep def top_level_lobes(Bayesian=False): Lobes = ['TL',", "keep def top_level_lobes(Bayesian=False): Lobes = ['TL', 'FL', 'CING', 'PL', 'OL', 'INSULA', 'Hypothalamus', 'Sub-Callosal", "for loc in all_localisations if loc not in major_localisations] def drop_minor_localisations(df): df_temp =", "all_localisations = all_localisations() # list of top level localisations we want to keep", "'FL', 'CING', 'PL', 'OL', 'INSULA', 'Hypothalamus', 'Sub-Callosal Cortex', 'Cerebellum', 'Perisylvian', 'FT', 'TO', 'TP',", "we want to keep def top_level_lobes(Bayesian=False): Lobes = ['TL', 'FL', 'CING', 'PL', 'OL',", "Cortex', 'Cerebellum', 'Perisylvian', 'FT', 'TO', 'TP', 'FTP', 'TPO Junction', 'PO', 'FP'] if Bayesian:", "localisations to drop minor_locs = [ loc for loc in all_localisations if loc", "[i for i in Lobes if i not in redistributed] return Lobes major_localisations", "= ['TL', 'FL', 'CING', 'PL', 'OL', 'INSULA', 'Hypothalamus', 'Sub-Callosal Cortex', 'Cerebellum', 'Perisylvian', 'FT',", "localisations we want to keep def top_level_lobes(Bayesian=False): Lobes = ['TL', 'FL', 'CING', 'PL',", "mega_analysis.crosstab.all_localisations import all_localisations # list of all excel localisations all_localisations = all_localisations() #", "if Bayesian: redistributed = ['FT', 'FTP', 'PO', 'Perisylvian', 'FP', 'Sub-Callosal Cortex', 'TO', 'TPO", "as pd from mega_analysis.crosstab.all_localisations import all_localisations # list of all excel localisations all_localisations", "= ['FT', 'FTP', 'PO', 'Perisylvian', 'FP', 'Sub-Callosal Cortex', 'TO', 'TPO Junction', 'TP'] redistributed.append('Cerebellum')", "'TPO Junction', 'PO', 'FP'] if Bayesian: redistributed = ['FT', 'FTP', 'PO', 'Perisylvian', 'FP',", "= top_level_lobes() # list of localisations to drop minor_locs = [ loc for", "= [ loc for loc in all_localisations if loc not in major_localisations] def", "def top_level_lobes(Bayesian=False): Lobes = ['TL', 'FL', 'CING', 'PL', 'OL', 'INSULA', 'Hypothalamus', 'Sub-Callosal Cortex',", "if loc not in major_localisations] def drop_minor_localisations(df): df_temp = df.drop(columns=minor_locs, inplace=False, errors='ignore') return", "'Sub-Callosal Cortex', 'Cerebellum', 'Perisylvian', 'FT', 'TO', 'TP', 'FTP', 'TPO Junction', 'PO', 'FP'] if", "'TP'] redistributed.append('Cerebellum') Lobes = [i for i in Lobes if i not in", "if i not in redistributed] return Lobes major_localisations = top_level_lobes() # list of", "i in Lobes if i not in redistributed] return Lobes major_localisations = top_level_lobes()", "of localisations to drop minor_locs = [ loc for loc in all_localisations if", "to drop minor_locs = [ loc for loc in all_localisations if loc not", "numpy as np import pandas as pd from mega_analysis.crosstab.all_localisations import all_localisations # list", "['TL', 'FL', 'CING', 'PL', 'OL', 'INSULA', 'Hypothalamus', 'Sub-Callosal Cortex', 'Cerebellum', 'Perisylvian', 'FT', 'TO',", "redistributed.append('Cerebellum') Lobes = [i for i in Lobes if i not in redistributed]", "Lobes = [i for i in Lobes if i not in redistributed] return", "'Cerebellum', 'Perisylvian', 'FT', 'TO', 'TP', 'FTP', 'TPO Junction', 'PO', 'FP'] if Bayesian: redistributed", "[ loc for loc in all_localisations if loc not in major_localisations] def drop_minor_localisations(df):", "['FT', 'FTP', 'PO', 'Perisylvian', 'FP', 'Sub-Callosal Cortex', 'TO', 'TPO Junction', 'TP'] redistributed.append('Cerebellum') Lobes" ]
[ "# client = ApiClient(adapter=Co2ApiTimeoutAdapter(), timeout=10) # # # when/then # with self.assertRaises(ApiException): #", "-*- coding: utf-8 -*- import unittest class ApiTests(unittest.TestCase): pass # @Mocker() # def", "# @Mocker() # def test_timeout_exception(self, m): # # given # m._adapter = Co2ApiTimeoutAdapter(m._adapter)", "# def test_timeout_exception(self, m): # # given # m._adapter = Co2ApiTimeoutAdapter(m._adapter) # m.register_uri(ANY,", "utf-8 -*- import unittest class ApiTests(unittest.TestCase): pass # @Mocker() # def test_timeout_exception(self, m):", "import unittest class ApiTests(unittest.TestCase): pass # @Mocker() # def test_timeout_exception(self, m): # #", "<gh_stars>1-10 # -*- coding: utf-8 -*- import unittest class ApiTests(unittest.TestCase): pass # @Mocker()", "unittest class ApiTests(unittest.TestCase): pass # @Mocker() # def test_timeout_exception(self, m): # # given", "m._adapter = Co2ApiTimeoutAdapter(m._adapter) # m.register_uri(ANY, ANY, text=self.hanging_callback) # client = ApiClient(adapter=Co2ApiTimeoutAdapter(), timeout=10) #", "def test_timeout_exception(self, m): # # given # m._adapter = Co2ApiTimeoutAdapter(m._adapter) # m.register_uri(ANY, ANY,", "class ApiTests(unittest.TestCase): pass # @Mocker() # def test_timeout_exception(self, m): # # given #", "text=self.hanging_callback) # client = ApiClient(adapter=Co2ApiTimeoutAdapter(), timeout=10) # # # when/then # with self.assertRaises(ApiException):", "# -*- coding: utf-8 -*- import unittest class ApiTests(unittest.TestCase): pass # @Mocker() #", "client = ApiClient(adapter=Co2ApiTimeoutAdapter(), timeout=10) # # # when/then # with self.assertRaises(ApiException): # client.retrieve('GET',", "m.register_uri(ANY, ANY, text=self.hanging_callback) # client = ApiClient(adapter=Co2ApiTimeoutAdapter(), timeout=10) # # # when/then #", "given # m._adapter = Co2ApiTimeoutAdapter(m._adapter) # m.register_uri(ANY, ANY, text=self.hanging_callback) # client = ApiClient(adapter=Co2ApiTimeoutAdapter(),", "# given # m._adapter = Co2ApiTimeoutAdapter(m._adapter) # m.register_uri(ANY, ANY, text=self.hanging_callback) # client =", "coding: utf-8 -*- import unittest class ApiTests(unittest.TestCase): pass # @Mocker() # def test_timeout_exception(self,", "-*- import unittest class ApiTests(unittest.TestCase): pass # @Mocker() # def test_timeout_exception(self, m): #", "test_timeout_exception(self, m): # # given # m._adapter = Co2ApiTimeoutAdapter(m._adapter) # m.register_uri(ANY, ANY, text=self.hanging_callback)", "# m._adapter = Co2ApiTimeoutAdapter(m._adapter) # m.register_uri(ANY, ANY, text=self.hanging_callback) # client = ApiClient(adapter=Co2ApiTimeoutAdapter(), timeout=10)", "m): # # given # m._adapter = Co2ApiTimeoutAdapter(m._adapter) # m.register_uri(ANY, ANY, text=self.hanging_callback) #", "ApiTests(unittest.TestCase): pass # @Mocker() # def test_timeout_exception(self, m): # # given # m._adapter", "= Co2ApiTimeoutAdapter(m._adapter) # m.register_uri(ANY, ANY, text=self.hanging_callback) # client = ApiClient(adapter=Co2ApiTimeoutAdapter(), timeout=10) # #", "= ApiClient(adapter=Co2ApiTimeoutAdapter(), timeout=10) # # # when/then # with self.assertRaises(ApiException): # client.retrieve('GET', f'{BASE_URI}/foobar')", "pass # @Mocker() # def test_timeout_exception(self, m): # # given # m._adapter =", "# # given # m._adapter = Co2ApiTimeoutAdapter(m._adapter) # m.register_uri(ANY, ANY, text=self.hanging_callback) # client", "@Mocker() # def test_timeout_exception(self, m): # # given # m._adapter = Co2ApiTimeoutAdapter(m._adapter) #", "# m.register_uri(ANY, ANY, text=self.hanging_callback) # client = ApiClient(adapter=Co2ApiTimeoutAdapter(), timeout=10) # # # when/then", "ANY, text=self.hanging_callback) # client = ApiClient(adapter=Co2ApiTimeoutAdapter(), timeout=10) # # # when/then # with", "Co2ApiTimeoutAdapter(m._adapter) # m.register_uri(ANY, ANY, text=self.hanging_callback) # client = ApiClient(adapter=Co2ApiTimeoutAdapter(), timeout=10) # # #" ]
[ "obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), self.w.obslog_name.get_text().strip()) self.write_obslog(obslog_path) def load_obslog_cb(self, w): obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), self.w.obslog_name.get_text().strip()) self.load_obslog(obslog_path)", "MS Excel file format The file is rewritten out every time a new", "**Usage** ***Saving the log to a file*** Put in values for the Observation", "= self.fv.get_current_channel() if channel.name != chname: channel = self.fv.get_channel(chname) self.fv.change_channel(chname) channel.switch_name(imname) def select_cb(self,", "= self.fv.get_channel(chname) self.fv.change_channel(chname) channel.switch_name(imname) def select_cb(self, widget, d): res = self.get_selected() if len(res)", "needed in the table d = self.replace_kwds(header.asdict()) # Hack to insure that we", "'FILTER01'), #(\"Filter02\", 'FILTER02'), #(\"Filter03\", 'FILTER03'), (\"RA\", 'RA'), (\"DEC\", 'DEC'), (\"EQUINOX\", 'EQUINOX'), (\"Memo\", 'G_MEMO'),", "obslog_name = self.w.obslog_name.get_text().strip() if len(obslog_name) > 0: obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), obslog_name) self.write_obslog(obslog_path) def", "log ***Adding a memo to one or more log entries*** Write a memo", "self.load_obslog_cb) btns = Widgets.HBox() btns.set_border_width(4) btns.set_spacing(4) btn = Widgets.Button(\"Close\") btn.add_callback('activated', lambda w: self.close())", "#(\"Filter03\", 'FILTER03'), (\"RA\", 'RA'), (\"DEC\", 'DEC'), (\"EQUINOX\", 'EQUINOX'), (\"Memo\", 'G_MEMO'), ] prefs =", "tv vbox.add_widget(tv, stretch=1) tv.add_callback('activated', self.dblclick_cb) tv.add_callback('selected', self.select_cb) self.rpt_columns = self.settings.get('report_columns') tv.setup_table(self.rpt_columns, 1, 'FRAMEID')", "= os.path.join(self.w.obslog_dir.get_text().strip(), self.w.obslog_name.get_text().strip()) self.load_obslog(obslog_path) def get_selected(self): res_dict = self.w.rpt_tbl.get_selected() return res_dict def dblclick_cb(self,", "def write_obslog_cb(self, w): obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), self.w.obslog_name.get_text().strip()) self.write_obslog(obslog_path) def load_obslog_cb(self, w): obslog_path =", "#(\"Filter02\", 'FILTER02'), #(\"Filter03\", 'FILTER03'), (\"RA\", 'RA'), (\"DEC\", 'DEC'), (\"EQUINOX\", 'EQUINOX'), (\"Memo\", 'G_MEMO'), ]", "selected frames') b.add_memo.add_callback('activated', self.add_memo_cb) b.add_memo.set_enabled(False) captions = ((\"Folder:\", 'label', \"obslog_dir\", 'entry', \"Name:\", 'label',", "return self.w.rpt_tbl.set_tree(self.rpt_dict) obslog_name = self.w.obslog_name.get_text().strip() if len(obslog_name) > 0: obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), obslog_name)", "(\"PropId\", 'PROP-ID'), (\"Exp Time\", 'EXPTIME'), (\"Air Mass\", 'AIRMASS'), #(\"Pos Ang\", 'INST-PA'), #(\"Ins Rot\",", "self.w.obslog_name.get_text().strip() if len(obslog_name) > 0: obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), obslog_name) self.write_obslog(obslog_path) def write_obslog(self, filepath):", "import GingaPlugin, AstroImage from ginga.gw import Widgets __all__ = ['ObsLog'] class ObsLog(GingaPlugin.GlobalPlugin): def", "w): obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), self.w.obslog_name.get_text().strip()) self.write_obslog(obslog_path) def load_obslog_cb(self, w): obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), self.w.obslog_name.get_text().strip())", "'combobox', \"Load\", 'button'), ) w, b = Widgets.build_info(captions, orientation='vertical') self.w.update(b) vbox.add_widget(w, stretch=0) obs_log", ") w, b = Widgets.build_info(captions, orientation='vertical') self.w.update(b) vbox.add_widget(w, stretch=0) obs_log = self.settings.get('obslog_name', None)", "def write_obslog(self, filepath): if len(self.rpt_dict) == 0: return try: import pandas as pd", "row in res.values(): frameid = row['FrameID'] d = OrderedDict([(kwd, row.get(col, '')) for col,", "__init__(self, fv): super(ObsLog, self).__init__(fv) self.chname = None self.file_prefixes = [] # columns to", "prefix in self.file_prefixes: if imname.startswith(prefix): accepted = True break if not accepted: return", "None: return # only accepted list of frames accepted = False for prefix", "Widgets __all__ = ['ObsLog'] class ObsLog(GingaPlugin.GlobalPlugin): def __init__(self, fv): super(ObsLog, self).__init__(fv) self.chname =", "pick the right extension: * csv: * xlsx: MS Excel file format The", "'entry', 'Add Memo', 'button'), ) w, b = Widgets.build_info(captions, orientation='vertical') self.w.update(b) vbox.add_widget(w, stretch=0)", "AstroImage from ginga.gw import Widgets __all__ = ['ObsLog'] class ObsLog(GingaPlugin.GlobalPlugin): def __init__(self, fv):", "replace_kwds(self, header): \"\"\"Subclass this method to do munge the data for special reports.\"\"\"", "not self.gui_up: return self.w.rpt_tbl.set_tree(self.rpt_dict) obslog_name = self.w.obslog_name.get_text().strip() if len(obslog_name) > 0: obslog_path =", "image.get_header() # add image to obslog self.fv.gui_do(self.add_to_obslog, header, image) try: self.process_image(chname, header, image)", "self.w.obslog_name.set_text(name + '.' + ext) self.write_obslog_cb(None) def close(self): self.fv.stop_global_plugin(str(self)) return True def __str__(self):", "= True def replace_kwds(self, header): \"\"\"Subclass this method to do munge the data", "csv: * xlsx: MS Excel file format The file is rewritten out every", "obs_log = '' b.obslog_name.set_text(obs_log) b.obslog_name.set_tooltip('File name for observation log') b.obslog_name.add_callback('activated', self.write_obslog_cb) b.obslog_dir.set_text(\"/tmp\") b.obslog_dir.set_tooltip('Folder", "header=True) else: df.to_excel(filepath, index=False, header=True) except Exception as e: self.logger.error(\"Error writing obslog: {}\".format(e),", "Memo', 'button'), ) w, b = Widgets.build_info(captions, orientation='vertical') self.w.update(b) vbox.add_widget(w, stretch=0) b.memo.set_tooltip('Set memo", "(\"EQUINOX\", 'EQUINOX'), (\"Memo\", 'G_MEMO'), ] prefs = self.fv.get_preferences() self.settings = prefs.create_category('plugin_ObsLog') self.settings.add_defaults(sortable=True, color_alternate_rows=True,", "obslog: {}\".format(e), exc_info=True) def write_obslog_cb(self, w): obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), self.w.obslog_name.get_text().strip()) self.write_obslog(obslog_path) def load_obslog_cb(self,", "memo box. Select one or more frames to add the memo to and", "old_ext = os.path.splitext(obslog_name) self.w.obslog_name.set_text(name + '.' + ext) self.write_obslog_cb(None) def close(self): self.fv.stop_global_plugin(str(self)) return", "!= self.chname: return imname = image.get('name', None) if imname is None: return #", "Exception as e: self.logger.error(\"Error loading obslog: {}\".format(e), exc_info=True) def write_obslog_cb(self, w): obslog_path =", "else: df.to_excel(filepath, index=False, header=True) except Exception as e: self.logger.error(\"Error writing obslog: {}\".format(e), exc_info=True)", "#names=col_hdr, index_col=None) self.rpt_dict = OrderedDict({}) res = df.to_dict('index') for row in res.values(): frameid", "btns = Widgets.HBox() btns.set_border_width(4) btns.set_spacing(4) btn = Widgets.Button(\"Close\") btn.add_callback('activated', lambda w: self.close()) btn.set_enabled(False)", "self.update_obslog() def stop(self): self.gui_up = False def process_image(self, chname, header, image): \"\"\"Override this", "file saved will depend on the file extension of the filename; use the", "\"\"\" import os from collections import OrderedDict from ginga import GingaPlugin, AstroImage from", "d = OrderedDict([(kwd, d.get(kwd, '')) for col, kwd in self.rpt_columns]) self.rpt_dict[frameid] = d", "or more log entries*** Write a memo in the memo box. Select one", "holding down CTRL and/or SHIFT keys. ***Displaying an image*** Double-click on a log", "a new entry is added to the log ***Adding a memo to one", "> 0: obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), obslog_name) self.write_obslog(obslog_path) def write_obslog(self, filepath): if len(self.rpt_dict) ==", "= OrderedDict({}) res = df.to_dict('index') for row in res.values(): frameid = row['FrameID'] d", "about holding down CTRL and/or SHIFT keys. ***Displaying an image*** Double-click on a", "the desired order d = OrderedDict([(kwd, d.get(kwd, '')) for col, kwd in self.rpt_columns])", "\"obslog_name\", 'entryset', \"Type\", 'combobox', \"Load\", 'button'), ) w, b = Widgets.build_info(captions, orientation='vertical') self.w.update(b)", "def build_gui(self, container): vbox = Widgets.VBox() vbox.set_border_width(1) vbox.set_spacing(1) tv = Widgets.TreeView(sortable=self.settings.get('sortable'), use_alt_row_color=self.settings.get('color_alternate_rows'), selection='multiple')", "e: self.logger.error(\"Error writing obslog: {}\".format(e), exc_info=True) def load_obslog(self, filepath): try: import pandas as", "res = self.get_selected() if len(res) == 0: self.w.add_memo.set_enabled(False) else: self.w.add_memo.set_enabled(True) def add_memo_cb(self, widget):", "for special reports.\"\"\" d = dict() d.update(header) return d def add_to_obslog(self, header, image):", "self.rpt_dict[frameid] = d self.w.rpt_tbl.set_tree(self.rpt_dict) except Exception as e: self.logger.error(\"Error loading obslog: {}\".format(e), exc_info=True)", "os.path.join(self.w.obslog_dir.get_text().strip(), self.w.obslog_name.get_text().strip()) self.load_obslog(obslog_path) def get_selected(self): res_dict = self.w.rpt_tbl.get_selected() return res_dict def dblclick_cb(self, widget,", "= self.get_selected() if len(res) == 0: self.w.add_memo.set_enabled(False) else: self.w.add_memo.set_enabled(True) def add_memo_cb(self, widget): memo_txt", "Observation Log folder and filename. The format of the file saved will depend", "{}\".format(e), exc_info=True) def load_obslog(self, filepath): try: import pandas as pd except ImportError: self.fv.show_error(\"Please", "kwd in self.rpt_columns]) self.rpt_dict[frameid] = d self.w.rpt_tbl.set_tree(self.rpt_dict) except Exception as e: self.logger.error(\"Error loading", "to a file*** Put in values for the Observation Log folder and filename.", "process_image(self, chname, header, image): \"\"\"Override this method to do something special with the", "image that was double-clicked in the obslog\"\"\" frameid = list(d.keys())[0] info = d[frameid]", "w: self.help()) btns.add_widget(btn, stretch=0) btns.add_widget(Widgets.Label(''), stretch=1) vbox.add_widget(btns, stretch=0) container.add_widget(vbox, stretch=1) self.gui_up = True", "= Widgets.build_info(captions, orientation='vertical') self.w.update(b) vbox.add_widget(w, stretch=0) obs_log = self.settings.get('obslog_name', None) if obs_log is", "usual rules about holding down CTRL and/or SHIFT keys. ***Displaying an image*** Double-click", "set_obslog_format_cb(self, w, idx): ext = w.get_text() obslog_name = self.w.obslog_name.get_text().strip() name, old_ext = os.path.splitext(obslog_name)", "d): \"\"\"Switch to the image that was double-clicked in the obslog\"\"\" frameid =", "munge the data for special reports.\"\"\" d = dict() d.update(header) return d def", "b.obslog_name.set_text(obs_log) b.obslog_name.set_tooltip('File name for observation log') b.obslog_name.add_callback('activated', self.write_obslog_cb) b.obslog_dir.set_text(\"/tmp\") b.obslog_dir.set_tooltip('Folder path for observation", "name for observation log') b.obslog_name.add_callback('activated', self.write_obslog_cb) b.obslog_dir.set_text(\"/tmp\") b.obslog_dir.set_tooltip('Folder path for observation log') b.obslog_dir.add_callback('activated',", "Only one instance can be opened. **Usage** ***Saving the log to a file***", "res = df.to_dict('index') for row in res.values(): frameid = row['FrameID'] d = OrderedDict([(kwd,", "= os.path.join(self.w.obslog_dir.get_text().strip(), obslog_name) self.write_obslog(obslog_path) def write_obslog(self, filepath): if len(self.rpt_dict) == 0: return try:", "= w.get_text() obslog_name = self.w.obslog_name.get_text().strip() name, old_ext = os.path.splitext(obslog_name) self.w.obslog_name.set_text(name + '.' +", "exc_info=True) def write_obslog_cb(self, w): obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), self.w.obslog_name.get_text().strip()) self.write_obslog(obslog_path) def load_obslog_cb(self, w): obslog_path", "(\"UT\", 'UT'), (\"PropId\", 'PROP-ID'), (\"Exp Time\", 'EXPTIME'), (\"Air Mass\", 'AIRMASS'), #(\"Pos Ang\", 'INST-PA'),", "frames accepted = False for prefix in self.file_prefixes: if imname.startswith(prefix): accepted = True", "open-source software licensed under a BSD license. # Please see the file LICENSE.txt", "saving/loading ObsLog\") b.type.add_callback('activated', self.set_obslog_format_cb) b.load.set_tooltip(\"Load a saved ObsLog\") b.load.add_callback('activated', self.load_obslog_cb) btns = Widgets.HBox()", "from collections import OrderedDict from ginga import GingaPlugin, AstroImage from ginga.gw import Widgets", "b.memo.set_tooltip('Set memo for selected frames') b.add_memo.add_callback('activated', self.add_memo_cb) b.add_memo.set_enabled(False) captions = ((\"Folder:\", 'label', \"obslog_dir\",", "res_dict def dblclick_cb(self, widget, d): \"\"\"Switch to the image that was double-clicked in", "table columns = [(\"Obs Mod\", 'OBS-MOD'), (\"Datatype\", 'DATA-TYP'), (\"FrameID\", 'FRAMEID'), (\"Object\", 'OBJECT'), (\"UT\",", "SHIFT keys. ***Displaying an image*** Double-click on a log entry. \"\"\" import os", "return # only accepted list of frames accepted = False for prefix in", "b.type.set_tooltip(\"Format for saving/loading ObsLog\") b.type.add_callback('activated', self.set_obslog_format_cb) b.load.set_tooltip(\"Load a saved ObsLog\") b.load.add_callback('activated', self.load_obslog_cb) btns", "on the file extension of the filename; use the type selector combobox to", "log entries*** Write a memo in the memo box. Select one or more", "widget, d): \"\"\"Switch to the image that was double-clicked in the obslog\"\"\" frameid", "OrderedDict([(kwd, d.get(kwd, '')) for col, kwd in self.rpt_columns]) self.rpt_dict[frameid] = d self.update_obslog() def", "self.w.rpt_tbl.set_tree(self.rpt_dict) obslog_name = self.w.obslog_name.get_text().strip() if len(obslog_name) > 0: obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), obslog_name) self.write_obslog(obslog_path)", "path for observation log') b.obslog_dir.add_callback('activated', self.write_obslog_cb) b.type.insert_alpha(\"csv\") b.type.insert_alpha(\"xlsx\") b.type.set_tooltip(\"Format for saving/loading ObsLog\") b.type.add_callback('activated',", "memo!\") return for key in res.keys(): self.rpt_dict[key]['G_MEMO'] = memo_txt self.w.rpt_tbl.set_tree(self.rpt_dict) def set_obslog_format_cb(self, w,", "e: self.logger.error(\"Failed to process image: {}\".format(e), exc_info=True) def update_obslog(self): if not self.gui_up: return", "in res.values(): frameid = row['FrameID'] d = OrderedDict([(kwd, row.get(col, '')) for col, kwd", "and press the \"Add Memo\" button. Multiple selection follows the usual rules about", "self.rpt_dict[key]['G_MEMO'] = memo_txt self.w.rpt_tbl.set_tree(self.rpt_dict) def set_obslog_format_cb(self, w, idx): ext = w.get_text() obslog_name =", "((\"Folder:\", 'label', \"obslog_dir\", 'entry', \"Name:\", 'label', \"obslog_name\", 'entryset', \"Type\", 'combobox', \"Load\", 'button'), )", "self.settings.load(onError='silent') self.rpt_dict = OrderedDict({}) self.rpt_columns = [] self.fv.add_callback('add-image', self.incoming_data_cb) self.gui_up = False def", "len(res) == 0: self.w.add_memo.set_enabled(False) else: self.w.add_memo.set_enabled(True) def add_memo_cb(self, widget): memo_txt = self.w.memo.get_text().strip() res", "= Widgets.Button(\"Close\") btn.add_callback('activated', lambda w: self.close()) btn.set_enabled(False) btns.add_widget(btn) btn = Widgets.Button(\"Help\") btn.add_callback('activated', lambda", "image) try: self.process_image(chname, header, image) except Exception as e: self.logger.error(\"Failed to process image:", "with the data.\"\"\" pass def incoming_data_cb(self, fv, chname, image, info): if chname !=", "self.fv.gui_do(self.add_to_obslog, header, image) try: self.process_image(chname, header, image) except Exception as e: self.logger.error(\"Failed to", "the log to a file*** Put in values for the Observation Log folder", "= [colname for colname, key in self.rpt_columns] rows = [list(d.values()) for d in", "cache_normalized_images=True) self.settings.load(onError='silent') self.rpt_dict = OrderedDict({}) self.rpt_columns = [] self.fv.add_callback('add-image', self.incoming_data_cb) self.gui_up = False", "write_obslog_cb(self, w): obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), self.w.obslog_name.get_text().strip()) self.write_obslog(obslog_path) def load_obslog_cb(self, w): obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(),", "{}\".format(filepath)) col_hdr = [colname for colname, key in self.rpt_columns] if filepath.endswith('.csv'): df =", "[colname for colname, key in self.rpt_columns] if filepath.endswith('.csv'): df = pd.read_csv(filepath, header=0, #names=col_hdr,", "'')) for col, kwd in self.rpt_columns]) self.rpt_dict[frameid] = d self.w.rpt_tbl.set_tree(self.rpt_dict) except Exception as", "btns.add_widget(Widgets.Label(''), stretch=1) vbox.add_widget(btns, stretch=0) container.add_widget(vbox, stretch=1) self.gui_up = True def replace_kwds(self, header): \"\"\"Subclass", "import pandas as pd except ImportError: self.fv.show_error(\"Please install 'pandas' and \" \"'openpyxl' to", "***Saving the log to a file*** Put in values for the Observation Log", "# replace some kwds as needed in the table d = self.replace_kwds(header.asdict()) #", "see the file LICENSE.txt for details. \"\"\"Observation Log plugin. **Plugin Type: Global** ``ObsLog``", "= [] self.fv.add_callback('add-image', self.incoming_data_cb) self.gui_up = False def build_gui(self, container): vbox = Widgets.VBox()", "time a new entry is added to the log ***Adding a memo to", "# columns to be shown in the table columns = [(\"Obs Mod\", 'OBS-MOD'),", "self.w.add_memo.set_enabled(True) def add_memo_cb(self, widget): memo_txt = self.w.memo.get_text().strip() res = self.get_selected() if len(res) ==", "+ '.' + ext) self.write_obslog_cb(None) def close(self): self.fv.stop_global_plugin(str(self)) return True def __str__(self): return", "ginga import GingaPlugin, AstroImage from ginga.gw import Widgets __all__ = ['ObsLog'] class ObsLog(GingaPlugin.GlobalPlugin):", "else: df = pd.read_excel(filepath, header=0, #names=col_hdr, index_col=None) self.rpt_dict = OrderedDict({}) res = df.to_dict('index')", "selector combobox to pick the right extension: * csv: * xlsx: MS Excel", "Multiple selection follows the usual rules about holding down CTRL and/or SHIFT keys.", "] prefs = self.fv.get_preferences() self.settings = prefs.create_category('plugin_ObsLog') self.settings.add_defaults(sortable=True, color_alternate_rows=True, #max_rows_for_col_resize=5000, report_columns=columns, cache_normalized_images=True) self.settings.load(onError='silent')", "obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), self.w.obslog_name.get_text().strip()) self.load_obslog(obslog_path) def get_selected(self): res_dict = self.w.rpt_tbl.get_selected() return res_dict def", "obs_log is None: obs_log = '' b.obslog_name.set_text(obs_log) b.obslog_name.set_tooltip('File name for observation log') b.obslog_name.add_callback('activated',", "btn.add_callback('activated', lambda w: self.close()) btn.set_enabled(False) btns.add_widget(btn) btn = Widgets.Button(\"Help\") btn.add_callback('activated', lambda w: self.help())", "if filepath.endswith('.csv'): df = pd.read_csv(filepath, header=0, #names=col_hdr, index_col=None) else: df = pd.read_excel(filepath, header=0,", "Widgets.Button(\"Help\") btn.add_callback('activated', lambda w: self.help()) btns.add_widget(btn, stretch=0) btns.add_widget(Widgets.Label(''), stretch=1) vbox.add_widget(btns, stretch=0) container.add_widget(vbox, stretch=1)", "d[frameid] self.view_image(frameid, info) def view_image(self, imname, info): chname = self.chname channel = self.fv.get_current_channel()", "= df.to_dict('index') for row in res.values(): frameid = row['FrameID'] d = OrderedDict([(kwd, row.get(col,", "self.gui_up = False def process_image(self, chname, header, image): \"\"\"Override this method to do", "= Widgets.HBox() btns.set_border_width(4) btns.set_spacing(4) btn = Widgets.Button(\"Close\") btn.add_callback('activated', lambda w: self.close()) btn.set_enabled(False) btns.add_widget(btn)", "try: self.logger.info(\"loading obslog: {}\".format(filepath)) col_hdr = [colname for colname, key in self.rpt_columns] if", "as pd except ImportError: self.fv.show_error(\"Please install 'pandas' and \" \"'openpyxl' to use this", "return try: self.logger.info(\"writing obslog: {}\".format(filepath)) col_hdr = [colname for colname, key in self.rpt_columns]", "in res.keys(): self.rpt_dict[key]['G_MEMO'] = memo_txt self.w.rpt_tbl.set_tree(self.rpt_dict) def set_obslog_format_cb(self, w, idx): ext = w.get_text()", "stretch=0) b.memo.set_tooltip('Set memo for selected frames') b.add_memo.add_callback('activated', self.add_memo_cb) b.add_memo.set_enabled(False) captions = ((\"Folder:\", 'label',", "'label', \"obslog_dir\", 'entry', \"Name:\", 'label', \"obslog_name\", 'entryset', \"Type\", 'combobox', \"Load\", 'button'), ) w,", "self.rpt_dict = OrderedDict({}) self.rpt_columns = [] self.fv.add_callback('add-image', self.incoming_data_cb) self.gui_up = False def build_gui(self,", "frames to add the memo to and press the \"Add Memo\" button. Multiple", "= self.replace_kwds(header.asdict()) # Hack to insure that we get the columns in the", "def process_image(self, chname, header, image): \"\"\"Override this method to do something special with", "b.load.add_callback('activated', self.load_obslog_cb) btns = Widgets.HBox() btns.set_border_width(4) btns.set_spacing(4) btn = Widgets.Button(\"Close\") btn.add_callback('activated', lambda w:", "special with the data.\"\"\" pass def incoming_data_cb(self, fv, chname, image, info): if chname", "frameid = row['FrameID'] d = OrderedDict([(kwd, row.get(col, '')) for col, kwd in self.rpt_columns])", "format The file is rewritten out every time a new entry is added", "self.write_obslog_cb) b.type.insert_alpha(\"csv\") b.type.insert_alpha(\"xlsx\") b.type.set_tooltip(\"Format for saving/loading ObsLog\") b.type.add_callback('activated', self.set_obslog_format_cb) b.load.set_tooltip(\"Load a saved ObsLog\")", "os from collections import OrderedDict from ginga import GingaPlugin, AstroImage from ginga.gw import", "orientation='vertical') self.w.update(b) vbox.add_widget(w, stretch=0) obs_log = self.settings.get('obslog_name', None) if obs_log is None: obs_log", "accepted: return header = image.get_header() # add image to obslog self.fv.gui_do(self.add_to_obslog, header, image)", "= pd.DataFrame(rows, columns=col_hdr) if filepath.endswith('.csv'): df.to_csv(filepath, index=False, header=True) else: df.to_excel(filepath, index=False, header=True) except", "folder and filename. The format of the file saved will depend on the", "This is open-source software licensed under a BSD license. # Please see the", "in self.rpt_columns] if filepath.endswith('.csv'): df = pd.read_csv(filepath, header=0, #names=col_hdr, index_col=None) else: df =", "index_col=None) self.rpt_dict = OrderedDict({}) res = df.to_dict('index') for row in res.values(): frameid =", "as e: self.logger.error(\"Error writing obslog: {}\".format(e), exc_info=True) def load_obslog(self, filepath): try: import pandas", "name, old_ext = os.path.splitext(obslog_name) self.w.obslog_name.set_text(name + '.' + ext) self.write_obslog_cb(None) def close(self): self.fv.stop_global_plugin(str(self))", "LICENSE.txt for details. \"\"\"Observation Log plugin. **Plugin Type: Global** ``ObsLog`` is a global", "new entry is added to the log ***Adding a memo to one or", "if not accepted: return header = image.get_header() # add image to obslog self.fv.gui_do(self.add_to_obslog,", "Mass\", 'AIRMASS'), #(\"Pos Ang\", 'INST-PA'), #(\"Ins Rot\", 'INSROT'), #(\"Foc Val\", 'FOC-VAL'), #(\"Filter01\", 'FILTER01'),", "self.load_obslog(obslog_path) def get_selected(self): res_dict = self.w.rpt_tbl.get_selected() return res_dict def dblclick_cb(self, widget, d): \"\"\"Switch", "double-clicked in the obslog\"\"\" frameid = list(d.keys())[0] info = d[frameid] self.view_image(frameid, info) def", "b.load.set_tooltip(\"Load a saved ObsLog\") b.load.add_callback('activated', self.load_obslog_cb) btns = Widgets.HBox() btns.set_border_width(4) btns.set_spacing(4) btn =", "== 0: self.fv.show_error(\"No frames selected for memo!\") return for key in res.keys(): self.rpt_dict[key]['G_MEMO']", "(\"Object\", 'OBJECT'), (\"UT\", 'UT'), (\"PropId\", 'PROP-ID'), (\"Exp Time\", 'EXPTIME'), (\"Air Mass\", 'AIRMASS'), #(\"Pos", "self.w.rpt_tbl.set_tree(self.rpt_dict) except Exception as e: self.logger.error(\"Error loading obslog: {}\".format(e), exc_info=True) def write_obslog_cb(self, w):", "\"\"\"Switch to the image that was double-clicked in the obslog\"\"\" frameid = list(d.keys())[0]", "the obslog\"\"\" frameid = list(d.keys())[0] info = d[frameid] self.view_image(frameid, info) def view_image(self, imname,", "'UT'), (\"PropId\", 'PROP-ID'), (\"Exp Time\", 'EXPTIME'), (\"Air Mass\", 'AIRMASS'), #(\"Pos Ang\", 'INST-PA'), #(\"Ins", "write_obslog(self, filepath): if len(self.rpt_dict) == 0: return try: import pandas as pd except", "tv = Widgets.TreeView(sortable=self.settings.get('sortable'), use_alt_row_color=self.settings.get('color_alternate_rows'), selection='multiple') self.w.rpt_tbl = tv vbox.add_widget(tv, stretch=1) tv.add_callback('activated', self.dblclick_cb) tv.add_callback('selected',", "build_gui(self, container): vbox = Widgets.VBox() vbox.set_border_width(1) vbox.set_spacing(1) tv = Widgets.TreeView(sortable=self.settings.get('sortable'), use_alt_row_color=self.settings.get('color_alternate_rows'), selection='multiple') self.w.rpt_tbl", "for colname, key in self.rpt_columns] rows = [list(d.values()) for d in self.rpt_dict.values()] df", "image to obslog self.fv.gui_do(self.add_to_obslog, header, image) try: self.process_image(chname, header, image) except Exception as", "Put in values for the Observation Log folder and filename. The format of", "to use this feature\") return try: self.logger.info(\"writing obslog: {}\".format(filepath)) col_hdr = [colname for", "e: self.logger.error(\"Error loading obslog: {}\".format(e), exc_info=True) def write_obslog_cb(self, w): obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), self.w.obslog_name.get_text().strip())", "rewritten out every time a new entry is added to the log ***Adding", "for col, kwd in self.rpt_columns]) self.rpt_dict[frameid] = d self.update_obslog() def stop(self): self.gui_up =", "self.close()) btn.set_enabled(False) btns.add_widget(btn) btn = Widgets.Button(\"Help\") btn.add_callback('activated', lambda w: self.help()) btns.add_widget(btn, stretch=0) btns.add_widget(Widgets.Label(''),", "stretch=0) obs_log = self.settings.get('obslog_name', None) if obs_log is None: obs_log = '' b.obslog_name.set_text(obs_log)", "every time a new entry is added to the log ***Adding a memo", "to do munge the data for special reports.\"\"\" d = dict() d.update(header) return", "b.type.add_callback('activated', self.set_obslog_format_cb) b.load.set_tooltip(\"Load a saved ObsLog\") b.load.add_callback('activated', self.load_obslog_cb) btns = Widgets.HBox() btns.set_border_width(4) btns.set_spacing(4)", "load_obslog_cb(self, w): obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), self.w.obslog_name.get_text().strip()) self.load_obslog(obslog_path) def get_selected(self): res_dict = self.w.rpt_tbl.get_selected() return", "df.to_csv(filepath, index=False, header=True) else: df.to_excel(filepath, index=False, header=True) except Exception as e: self.logger.error(\"Error writing", "df.to_excel(filepath, index=False, header=True) except Exception as e: self.logger.error(\"Error writing obslog: {}\".format(e), exc_info=True) def", "log to a file*** Put in values for the Observation Log folder and", "add_to_obslog(self, header, image): frameid = header['FRAMEID'] # replace some kwds as needed in", "'')) for col, kwd in self.rpt_columns]) self.rpt_dict[frameid] = d self.update_obslog() def stop(self): self.gui_up", "Select one or more frames to add the memo to and press the", "file*** Put in values for the Observation Log folder and filename. The format", "header['FRAMEID'] # replace some kwds as needed in the table d = self.replace_kwds(header.asdict())", "def load_obslog(self, filepath): try: import pandas as pd except ImportError: self.fv.show_error(\"Please install 'pandas'", "OrderedDict from ginga import GingaPlugin, AstroImage from ginga.gw import Widgets __all__ = ['ObsLog']", "b.add_memo.set_enabled(False) captions = ((\"Folder:\", 'label', \"obslog_dir\", 'entry', \"Name:\", 'label', \"obslog_name\", 'entryset', \"Type\", 'combobox',", "use this feature\") return try: self.logger.info(\"writing obslog: {}\".format(filepath)) col_hdr = [colname for colname,", "self.chname: return imname = image.get('name', None) if imname is None: return # only", "out every time a new entry is added to the log ***Adding a", "in the desired order d = OrderedDict([(kwd, d.get(kwd, '')) for col, kwd in", "{}\".format(e), exc_info=True) def update_obslog(self): if not self.gui_up: return self.w.rpt_tbl.set_tree(self.rpt_dict) obslog_name = self.w.obslog_name.get_text().strip() if", "can be opened. **Usage** ***Saving the log to a file*** Put in values", "'DEC'), (\"EQUINOX\", 'EQUINOX'), (\"Memo\", 'G_MEMO'), ] prefs = self.fv.get_preferences() self.settings = prefs.create_category('plugin_ObsLog') self.settings.add_defaults(sortable=True,", "type selector combobox to pick the right extension: * csv: * xlsx: MS", "the Observation Log folder and filename. The format of the file saved will", "self.gui_up = True def replace_kwds(self, header): \"\"\"Subclass this method to do munge the", "return res_dict def dblclick_cb(self, widget, d): \"\"\"Switch to the image that was double-clicked", "the right extension: * csv: * xlsx: MS Excel file format The file", "self.settings = prefs.create_category('plugin_ObsLog') self.settings.add_defaults(sortable=True, color_alternate_rows=True, #max_rows_for_col_resize=5000, report_columns=columns, cache_normalized_images=True) self.settings.load(onError='silent') self.rpt_dict = OrderedDict({}) self.rpt_columns", "self).__init__(fv) self.chname = None self.file_prefixes = [] # columns to be shown in", "= None self.file_prefixes = [] # columns to be shown in the table", "is open-source software licensed under a BSD license. # Please see the file", "added to the log ***Adding a memo to one or more log entries***", "use this feature\") return try: self.logger.info(\"loading obslog: {}\".format(filepath)) col_hdr = [colname for colname,", "and filename. The format of the file saved will depend on the file", "b.obslog_dir.set_tooltip('Folder path for observation log') b.obslog_dir.add_callback('activated', self.write_obslog_cb) b.type.insert_alpha(\"csv\") b.type.insert_alpha(\"xlsx\") b.type.set_tooltip(\"Format for saving/loading ObsLog\")", "[(\"Obs Mod\", 'OBS-MOD'), (\"Datatype\", 'DATA-TYP'), (\"FrameID\", 'FRAMEID'), (\"Object\", 'OBJECT'), (\"UT\", 'UT'), (\"PropId\", 'PROP-ID'),", "'Add Memo', 'button'), ) w, b = Widgets.build_info(captions, orientation='vertical') self.w.update(b) vbox.add_widget(w, stretch=0) b.memo.set_tooltip('Set", "\"obslog_dir\", 'entry', \"Name:\", 'label', \"obslog_name\", 'entryset', \"Type\", 'combobox', \"Load\", 'button'), ) w, b", "= [colname for colname, key in self.rpt_columns] if filepath.endswith('.csv'): df = pd.read_csv(filepath, header=0,", "in values for the Observation Log folder and filename. The format of the", "= header['FRAMEID'] # replace some kwds as needed in the table d =", "for prefix in self.file_prefixes: if imname.startswith(prefix): accepted = True break if not accepted:", "self.rpt_columns]) self.rpt_dict[frameid] = d self.w.rpt_tbl.set_tree(self.rpt_dict) except Exception as e: self.logger.error(\"Error loading obslog: {}\".format(e),", "else: self.w.add_memo.set_enabled(True) def add_memo_cb(self, widget): memo_txt = self.w.memo.get_text().strip() res = self.get_selected() if len(res)", "Excel file format The file is rewritten out every time a new entry", "\"Add Memo\" button. Multiple selection follows the usual rules about holding down CTRL", "self.settings.add_defaults(sortable=True, color_alternate_rows=True, #max_rows_for_col_resize=5000, report_columns=columns, cache_normalized_images=True) self.settings.load(onError='silent') self.rpt_dict = OrderedDict({}) self.rpt_columns = [] self.fv.add_callback('add-image',", "'EXPTIME'), (\"Air Mass\", 'AIRMASS'), #(\"Pos Ang\", 'INST-PA'), #(\"Ins Rot\", 'INSROT'), #(\"Foc Val\", 'FOC-VAL'),", "return d def add_to_obslog(self, header, image): frameid = header['FRAMEID'] # replace some kwds", "len(obslog_name) > 0: obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), obslog_name) self.write_obslog(obslog_path) def write_obslog(self, filepath): if len(self.rpt_dict)", "in self.rpt_dict.values()] df = pd.DataFrame(rows, columns=col_hdr) if filepath.endswith('.csv'): df.to_csv(filepath, index=False, header=True) else: df.to_excel(filepath,", "the \"Add Memo\" button. Multiple selection follows the usual rules about holding down", "'.' + ext) self.write_obslog_cb(None) def close(self): self.fv.stop_global_plugin(str(self)) return True def __str__(self): return 'obslog'", "False for prefix in self.file_prefixes: if imname.startswith(prefix): accepted = True break if not", "to pick the right extension: * csv: * xlsx: MS Excel file format", "this feature\") return try: self.logger.info(\"writing obslog: {}\".format(filepath)) col_hdr = [colname for colname, key", "Exception as e: self.logger.error(\"Error writing obslog: {}\".format(e), exc_info=True) def load_obslog(self, filepath): try: import", "instance can be opened. **Usage** ***Saving the log to a file*** Put in", "obslog: {}\".format(e), exc_info=True) def load_obslog(self, filepath): try: import pandas as pd except ImportError:", "for memo!\") return for key in res.keys(): self.rpt_dict[key]['G_MEMO'] = memo_txt self.w.rpt_tbl.set_tree(self.rpt_dict) def set_obslog_format_cb(self,", "to the image that was double-clicked in the obslog\"\"\" frameid = list(d.keys())[0] info", "return try: self.logger.info(\"loading obslog: {}\".format(filepath)) col_hdr = [colname for colname, key in self.rpt_columns]", "header=0, #names=col_hdr, index_col=None) self.rpt_dict = OrderedDict({}) res = df.to_dict('index') for row in res.values():", "OrderedDict({}) self.rpt_columns = [] self.fv.add_callback('add-image', self.incoming_data_cb) self.gui_up = False def build_gui(self, container): vbox", "observation log') b.obslog_name.add_callback('activated', self.write_obslog_cb) b.obslog_dir.set_text(\"/tmp\") b.obslog_dir.set_tooltip('Folder path for observation log') b.obslog_dir.add_callback('activated', self.write_obslog_cb) b.type.insert_alpha(\"csv\")", "this method to do munge the data for special reports.\"\"\" d = dict()", "= OrderedDict([(kwd, row.get(col, '')) for col, kwd in self.rpt_columns]) self.rpt_dict[frameid] = d self.w.rpt_tbl.set_tree(self.rpt_dict)", "the image that was double-clicked in the obslog\"\"\" frameid = list(d.keys())[0] info =", "def replace_kwds(self, header): \"\"\"Subclass this method to do munge the data for special", "in the obslog\"\"\" frameid = list(d.keys())[0] info = d[frameid] self.view_image(frameid, info) def view_image(self,", "if len(res) == 0: self.w.add_memo.set_enabled(False) else: self.w.add_memo.set_enabled(True) def add_memo_cb(self, widget): memo_txt = self.w.memo.get_text().strip()", "self.fv.show_error(\"No frames selected for memo!\") return for key in res.keys(): self.rpt_dict[key]['G_MEMO'] = memo_txt", "vbox.set_border_width(1) vbox.set_spacing(1) tv = Widgets.TreeView(sortable=self.settings.get('sortable'), use_alt_row_color=self.settings.get('color_alternate_rows'), selection='multiple') self.w.rpt_tbl = tv vbox.add_widget(tv, stretch=1) tv.add_callback('activated',", "'INST-PA'), #(\"Ins Rot\", 'INSROT'), #(\"Foc Val\", 'FOC-VAL'), #(\"Filter01\", 'FILTER01'), #(\"Filter02\", 'FILTER02'), #(\"Filter03\", 'FILTER03'),", "d def add_to_obslog(self, header, image): frameid = header['FRAMEID'] # replace some kwds as", "'RA'), (\"DEC\", 'DEC'), (\"EQUINOX\", 'EQUINOX'), (\"Memo\", 'G_MEMO'), ] prefs = self.fv.get_preferences() self.settings =", "***Displaying an image*** Double-click on a log entry. \"\"\" import os from collections", "header): \"\"\"Subclass this method to do munge the data for special reports.\"\"\" d", "self.chname = None self.file_prefixes = [] # columns to be shown in the", "# Hack to insure that we get the columns in the desired order", "def view_image(self, imname, info): chname = self.chname channel = self.fv.get_current_channel() if channel.name !=", "header=True) except Exception as e: self.logger.error(\"Error writing obslog: {}\".format(e), exc_info=True) def load_obslog(self, filepath):", "an image*** Double-click on a log entry. \"\"\" import os from collections import", "= self.w.obslog_name.get_text().strip() if len(obslog_name) > 0: obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), obslog_name) self.write_obslog(obslog_path) def write_obslog(self,", "== 0: self.w.add_memo.set_enabled(False) else: self.w.add_memo.set_enabled(True) def add_memo_cb(self, widget): memo_txt = self.w.memo.get_text().strip() res =", "ObsLog(GingaPlugin.GlobalPlugin): def __init__(self, fv): super(ObsLog, self).__init__(fv) self.chname = None self.file_prefixes = [] #", "False def process_image(self, chname, header, image): \"\"\"Override this method to do something special", "col, kwd in self.rpt_columns]) self.rpt_dict[frameid] = d self.w.rpt_tbl.set_tree(self.rpt_dict) except Exception as e: self.logger.error(\"Error", "'' b.obslog_name.set_text(obs_log) b.obslog_name.set_tooltip('File name for observation log') b.obslog_name.add_callback('activated', self.write_obslog_cb) b.obslog_dir.set_text(\"/tmp\") b.obslog_dir.set_tooltip('Folder path for", "#(\"Foc Val\", 'FOC-VAL'), #(\"Filter01\", 'FILTER01'), #(\"Filter02\", 'FILTER02'), #(\"Filter03\", 'FILTER03'), (\"RA\", 'RA'), (\"DEC\", 'DEC'),", "colname, key in self.rpt_columns] if filepath.endswith('.csv'): df = pd.read_csv(filepath, header=0, #names=col_hdr, index_col=None) else:", "header, image) try: self.process_image(chname, header, image) except Exception as e: self.logger.error(\"Failed to process", "btns.add_widget(btn) btn = Widgets.Button(\"Help\") btn.add_callback('activated', lambda w: self.help()) btns.add_widget(btn, stretch=0) btns.add_widget(Widgets.Label(''), stretch=1) vbox.add_widget(btns,", "that we get the columns in the desired order d = OrderedDict([(kwd, d.get(kwd,", "channel = self.fv.get_current_channel() if channel.name != chname: channel = self.fv.get_channel(chname) self.fv.change_channel(chname) channel.switch_name(imname) def", "b.obslog_dir.add_callback('activated', self.write_obslog_cb) b.type.insert_alpha(\"csv\") b.type.insert_alpha(\"xlsx\") b.type.set_tooltip(\"Format for saving/loading ObsLog\") b.type.add_callback('activated', self.set_obslog_format_cb) b.load.set_tooltip(\"Load a saved", "self.set_obslog_format_cb) b.load.set_tooltip(\"Load a saved ObsLog\") b.load.add_callback('activated', self.load_obslog_cb) btns = Widgets.HBox() btns.set_border_width(4) btns.set_spacing(4) btn", "obslog_name = self.w.obslog_name.get_text().strip() name, old_ext = os.path.splitext(obslog_name) self.w.obslog_name.set_text(name + '.' + ext) self.write_obslog_cb(None)", "the filename; use the type selector combobox to pick the right extension: *", "= list(d.keys())[0] info = d[frameid] self.view_image(frameid, info) def view_image(self, imname, info): chname =", "self.fv.show_error(\"Please install 'pandas' and \" \"'openpyxl' to use this feature\") return try: self.logger.info(\"writing", "except Exception as e: self.logger.error(\"Error writing obslog: {}\".format(e), exc_info=True) def load_obslog(self, filepath): try:", "= os.path.join(self.w.obslog_dir.get_text().strip(), self.w.obslog_name.get_text().strip()) self.write_obslog(obslog_path) def load_obslog_cb(self, w): obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), self.w.obslog_name.get_text().strip()) self.load_obslog(obslog_path) def", "CTRL and/or SHIFT keys. ***Displaying an image*** Double-click on a log entry. \"\"\"", "\" \"'openpyxl' to use this feature\") return try: self.logger.info(\"writing obslog: {}\".format(filepath)) col_hdr =", "= self.w.obslog_name.get_text().strip() name, old_ext = os.path.splitext(obslog_name) self.w.obslog_name.set_text(name + '.' + ext) self.write_obslog_cb(None) def", "'FOC-VAL'), #(\"Filter01\", 'FILTER01'), #(\"Filter02\", 'FILTER02'), #(\"Filter03\", 'FILTER03'), (\"RA\", 'RA'), (\"DEC\", 'DEC'), (\"EQUINOX\", 'EQUINOX'),", "use_alt_row_color=self.settings.get('color_alternate_rows'), selection='multiple') self.w.rpt_tbl = tv vbox.add_widget(tv, stretch=1) tv.add_callback('activated', self.dblclick_cb) tv.add_callback('selected', self.select_cb) self.rpt_columns =", "d = OrderedDict([(kwd, row.get(col, '')) for col, kwd in self.rpt_columns]) self.rpt_dict[frameid] = d", "as needed in the table d = self.replace_kwds(header.asdict()) # Hack to insure that", "right extension: * csv: * xlsx: MS Excel file format The file is", "def dblclick_cb(self, widget, d): \"\"\"Switch to the image that was double-clicked in the", "self.logger.info(\"writing obslog: {}\".format(filepath)) col_hdr = [colname for colname, key in self.rpt_columns] rows =", "info = d[frameid] self.view_image(frameid, info) def view_image(self, imname, info): chname = self.chname channel", "the memo box. Select one or more frames to add the memo to", "more log entries*** Write a memo in the memo box. Select one or", "\"\"\"Subclass this method to do munge the data for special reports.\"\"\" d =", "for the Observation Log folder and filename. The format of the file saved", "try: import pandas as pd except ImportError: self.fv.show_error(\"Please install 'pandas' and \" \"'openpyxl'", "a memo to one or more log entries*** Write a memo in the", "frames selected for memo!\") return for key in res.keys(): self.rpt_dict[key]['G_MEMO'] = memo_txt self.w.rpt_tbl.set_tree(self.rpt_dict)", "Widgets.Button(\"Close\") btn.add_callback('activated', lambda w: self.close()) btn.set_enabled(False) btns.add_widget(btn) btn = Widgets.Button(\"Help\") btn.add_callback('activated', lambda w:", "the data for special reports.\"\"\" d = dict() d.update(header) return d def add_to_obslog(self,", "self.settings.get('report_columns') tv.setup_table(self.rpt_columns, 1, 'FRAMEID') captions = ((\"Memo:\", 'label', \"memo\", 'entry', 'Add Memo', 'button'),", "info) def view_image(self, imname, info): chname = self.chname channel = self.fv.get_current_channel() if channel.name", "the log ***Adding a memo to one or more log entries*** Write a", "filename; use the type selector combobox to pick the right extension: * csv:", "def __init__(self, fv): super(ObsLog, self).__init__(fv) self.chname = None self.file_prefixes = [] # columns", "lambda w: self.help()) btns.add_widget(btn, stretch=0) btns.add_widget(Widgets.Label(''), stretch=1) vbox.add_widget(btns, stretch=0) container.add_widget(vbox, stretch=1) self.gui_up =", "a global plugin. Only one instance can be opened. **Usage** ***Saving the log", "d = dict() d.update(header) return d def add_to_obslog(self, header, image): frameid = header['FRAMEID']", "feature\") return try: self.logger.info(\"writing obslog: {}\".format(filepath)) col_hdr = [colname for colname, key in", "self.dblclick_cb) tv.add_callback('selected', self.select_cb) self.rpt_columns = self.settings.get('report_columns') tv.setup_table(self.rpt_columns, 1, 'FRAMEID') captions = ((\"Memo:\", 'label',", "the usual rules about holding down CTRL and/or SHIFT keys. ***Displaying an image***", ") w, b = Widgets.build_info(captions, orientation='vertical') self.w.update(b) vbox.add_widget(w, stretch=0) b.memo.set_tooltip('Set memo for selected", "prefs = self.fv.get_preferences() self.settings = prefs.create_category('plugin_ObsLog') self.settings.add_defaults(sortable=True, color_alternate_rows=True, #max_rows_for_col_resize=5000, report_columns=columns, cache_normalized_images=True) self.settings.load(onError='silent') self.rpt_dict", "in self.file_prefixes: if imname.startswith(prefix): accepted = True break if not accepted: return header", "self.logger.error(\"Error writing obslog: {}\".format(e), exc_info=True) def load_obslog(self, filepath): try: import pandas as pd", "#(\"Ins Rot\", 'INSROT'), #(\"Foc Val\", 'FOC-VAL'), #(\"Filter01\", 'FILTER01'), #(\"Filter02\", 'FILTER02'), #(\"Filter03\", 'FILTER03'), (\"RA\",", "(\"Exp Time\", 'EXPTIME'), (\"Air Mass\", 'AIRMASS'), #(\"Pos Ang\", 'INST-PA'), #(\"Ins Rot\", 'INSROT'), #(\"Foc", "order d = OrderedDict([(kwd, d.get(kwd, '')) for col, kwd in self.rpt_columns]) self.rpt_dict[frameid] =", "res = self.get_selected() if len(res) == 0: self.fv.show_error(\"No frames selected for memo!\") return", "== 0: return try: import pandas as pd except ImportError: self.fv.show_error(\"Please install 'pandas'", "of frames accepted = False for prefix in self.file_prefixes: if imname.startswith(prefix): accepted =", "self.rpt_dict = OrderedDict({}) res = df.to_dict('index') for row in res.values(): frameid = row['FrameID']", "exc_info=True) def update_obslog(self): if not self.gui_up: return self.w.rpt_tbl.set_tree(self.rpt_dict) obslog_name = self.w.obslog_name.get_text().strip() if len(obslog_name)", "df = pd.DataFrame(rows, columns=col_hdr) if filepath.endswith('.csv'): df.to_csv(filepath, index=False, header=True) else: df.to_excel(filepath, index=False, header=True)", "res.values(): frameid = row['FrameID'] d = OrderedDict([(kwd, row.get(col, '')) for col, kwd in", "report_columns=columns, cache_normalized_images=True) self.settings.load(onError='silent') self.rpt_dict = OrderedDict({}) self.rpt_columns = [] self.fv.add_callback('add-image', self.incoming_data_cb) self.gui_up =", "reports.\"\"\" d = dict() d.update(header) return d def add_to_obslog(self, header, image): frameid =", "columns in the desired order d = OrderedDict([(kwd, d.get(kwd, '')) for col, kwd", "stop(self): self.gui_up = False def process_image(self, chname, header, image): \"\"\"Override this method to", "True break if not accepted: return header = image.get_header() # add image to", "extension of the filename; use the type selector combobox to pick the right", "\"memo\", 'entry', 'Add Memo', 'button'), ) w, b = Widgets.build_info(captions, orientation='vertical') self.w.update(b) vbox.add_widget(w,", "def stop(self): self.gui_up = False def process_image(self, chname, header, image): \"\"\"Override this method", "os.path.join(self.w.obslog_dir.get_text().strip(), self.w.obslog_name.get_text().strip()) self.write_obslog(obslog_path) def load_obslog_cb(self, w): obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), self.w.obslog_name.get_text().strip()) self.load_obslog(obslog_path) def get_selected(self):", "Time\", 'EXPTIME'), (\"Air Mass\", 'AIRMASS'), #(\"Pos Ang\", 'INST-PA'), #(\"Ins Rot\", 'INSROT'), #(\"Foc Val\",", "obslog\"\"\" frameid = list(d.keys())[0] info = d[frameid] self.view_image(frameid, info) def view_image(self, imname, info):", "that was double-clicked in the obslog\"\"\" frameid = list(d.keys())[0] info = d[frameid] self.view_image(frameid,", "= ((\"Folder:\", 'label', \"obslog_dir\", 'entry', \"Name:\", 'label', \"obslog_name\", 'entryset', \"Type\", 'combobox', \"Load\", 'button'),", "image): frameid = header['FRAMEID'] # replace some kwds as needed in the table", "colname, key in self.rpt_columns] rows = [list(d.values()) for d in self.rpt_dict.values()] df =", "box. Select one or more frames to add the memo to and press", "is a global plugin. Only one instance can be opened. **Usage** ***Saving the", "= [(\"Obs Mod\", 'OBS-MOD'), (\"Datatype\", 'DATA-TYP'), (\"FrameID\", 'FRAMEID'), (\"Object\", 'OBJECT'), (\"UT\", 'UT'), (\"PropId\",", "stretch=1) vbox.add_widget(btns, stretch=0) container.add_widget(vbox, stretch=1) self.gui_up = True def replace_kwds(self, header): \"\"\"Subclass this", "= False def process_image(self, chname, header, image): \"\"\"Override this method to do something", "obslog: {}\".format(filepath)) col_hdr = [colname for colname, key in self.rpt_columns] if filepath.endswith('.csv'): df", "get_selected(self): res_dict = self.w.rpt_tbl.get_selected() return res_dict def dblclick_cb(self, widget, d): \"\"\"Switch to the", "btns.set_border_width(4) btns.set_spacing(4) btn = Widgets.Button(\"Close\") btn.add_callback('activated', lambda w: self.close()) btn.set_enabled(False) btns.add_widget(btn) btn =", "for observation log') b.obslog_name.add_callback('activated', self.write_obslog_cb) b.obslog_dir.set_text(\"/tmp\") b.obslog_dir.set_tooltip('Folder path for observation log') b.obslog_dir.add_callback('activated', self.write_obslog_cb)", "def add_to_obslog(self, header, image): frameid = header['FRAMEID'] # replace some kwds as needed", "memo_txt = self.w.memo.get_text().strip() res = self.get_selected() if len(res) == 0: self.fv.show_error(\"No frames selected", "columns=col_hdr) if filepath.endswith('.csv'): df.to_csv(filepath, index=False, header=True) else: df.to_excel(filepath, index=False, header=True) except Exception as", "orientation='vertical') self.w.update(b) vbox.add_widget(w, stretch=0) b.memo.set_tooltip('Set memo for selected frames') b.add_memo.add_callback('activated', self.add_memo_cb) b.add_memo.set_enabled(False) captions", "log entry. \"\"\" import os from collections import OrderedDict from ginga import GingaPlugin,", "except Exception as e: self.logger.error(\"Error loading obslog: {}\".format(e), exc_info=True) def write_obslog_cb(self, w): obslog_path", "d in self.rpt_dict.values()] df = pd.DataFrame(rows, columns=col_hdr) if filepath.endswith('.csv'): df.to_csv(filepath, index=False, header=True) else:", "ginga.gw import Widgets __all__ = ['ObsLog'] class ObsLog(GingaPlugin.GlobalPlugin): def __init__(self, fv): super(ObsLog, self).__init__(fv)", "self.add_memo_cb) b.add_memo.set_enabled(False) captions = ((\"Folder:\", 'label', \"obslog_dir\", 'entry', \"Name:\", 'label', \"obslog_name\", 'entryset', \"Type\",", "self.gui_up = False def build_gui(self, container): vbox = Widgets.VBox() vbox.set_border_width(1) vbox.set_spacing(1) tv =", "col_hdr = [colname for colname, key in self.rpt_columns] rows = [list(d.values()) for d", "a log entry. \"\"\" import os from collections import OrderedDict from ginga import", "btn = Widgets.Button(\"Close\") btn.add_callback('activated', lambda w: self.close()) btn.set_enabled(False) btns.add_widget(btn) btn = Widgets.Button(\"Help\") btn.add_callback('activated',", "(\"Datatype\", 'DATA-TYP'), (\"FrameID\", 'FRAMEID'), (\"Object\", 'OBJECT'), (\"UT\", 'UT'), (\"PropId\", 'PROP-ID'), (\"Exp Time\", 'EXPTIME'),", "Ang\", 'INST-PA'), #(\"Ins Rot\", 'INSROT'), #(\"Foc Val\", 'FOC-VAL'), #(\"Filter01\", 'FILTER01'), #(\"Filter02\", 'FILTER02'), #(\"Filter03\",", "color_alternate_rows=True, #max_rows_for_col_resize=5000, report_columns=columns, cache_normalized_images=True) self.settings.load(onError='silent') self.rpt_dict = OrderedDict({}) self.rpt_columns = [] self.fv.add_callback('add-image', self.incoming_data_cb)", "keys. ***Displaying an image*** Double-click on a log entry. \"\"\" import os from", "frameid = header['FRAMEID'] # replace some kwds as needed in the table d", "obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), obslog_name) self.write_obslog(obslog_path) def write_obslog(self, filepath): if len(self.rpt_dict) == 0: return", "= [] # columns to be shown in the table columns = [(\"Obs", "def select_cb(self, widget, d): res = self.get_selected() if len(res) == 0: self.w.add_memo.set_enabled(False) else:", "to insure that we get the columns in the desired order d =", "ObsLog\") b.type.add_callback('activated', self.set_obslog_format_cb) b.load.set_tooltip(\"Load a saved ObsLog\") b.load.add_callback('activated', self.load_obslog_cb) btns = Widgets.HBox() btns.set_border_width(4)", "vbox.add_widget(w, stretch=0) obs_log = self.settings.get('obslog_name', None) if obs_log is None: obs_log = ''", "= ((\"Memo:\", 'label', \"memo\", 'entry', 'Add Memo', 'button'), ) w, b = Widgets.build_info(captions,", "the data.\"\"\" pass def incoming_data_cb(self, fv, chname, image, info): if chname != self.chname:", "'EQUINOX'), (\"Memo\", 'G_MEMO'), ] prefs = self.fv.get_preferences() self.settings = prefs.create_category('plugin_ObsLog') self.settings.add_defaults(sortable=True, color_alternate_rows=True, #max_rows_for_col_resize=5000,", "\"\"\"Observation Log plugin. **Plugin Type: Global** ``ObsLog`` is a global plugin. Only one", "plugin. **Plugin Type: Global** ``ObsLog`` is a global plugin. Only one instance can", "loading obslog: {}\".format(e), exc_info=True) def write_obslog_cb(self, w): obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), self.w.obslog_name.get_text().strip()) self.write_obslog(obslog_path) def", "self.rpt_columns] rows = [list(d.values()) for d in self.rpt_dict.values()] df = pd.DataFrame(rows, columns=col_hdr) if", "for key in res.keys(): self.rpt_dict[key]['G_MEMO'] = memo_txt self.w.rpt_tbl.set_tree(self.rpt_dict) def set_obslog_format_cb(self, w, idx): ext", "# This is open-source software licensed under a BSD license. # Please see", "col, kwd in self.rpt_columns]) self.rpt_dict[frameid] = d self.update_obslog() def stop(self): self.gui_up = False", "# Please see the file LICENSE.txt for details. \"\"\"Observation Log plugin. **Plugin Type:", "btn.add_callback('activated', lambda w: self.help()) btns.add_widget(btn, stretch=0) btns.add_widget(Widgets.Label(''), stretch=1) vbox.add_widget(btns, stretch=0) container.add_widget(vbox, stretch=1) self.gui_up", "header, image): \"\"\"Override this method to do something special with the data.\"\"\" pass", "'OBS-MOD'), (\"Datatype\", 'DATA-TYP'), (\"FrameID\", 'FRAMEID'), (\"Object\", 'OBJECT'), (\"UT\", 'UT'), (\"PropId\", 'PROP-ID'), (\"Exp Time\",", "imname, info): chname = self.chname channel = self.fv.get_current_channel() if channel.name != chname: channel", "feature\") return try: self.logger.info(\"loading obslog: {}\".format(filepath)) col_hdr = [colname for colname, key in", "col_hdr = [colname for colname, key in self.rpt_columns] if filepath.endswith('.csv'): df = pd.read_csv(filepath,", "frameid = list(d.keys())[0] info = d[frameid] self.view_image(frameid, info) def view_image(self, imname, info): chname", "btn.set_enabled(False) btns.add_widget(btn) btn = Widgets.Button(\"Help\") btn.add_callback('activated', lambda w: self.help()) btns.add_widget(btn, stretch=0) btns.add_widget(Widgets.Label(''), stretch=1)", "install 'pandas' and \" \"'openpyxl' to use this feature\") return try: self.logger.info(\"loading obslog:", "memo_txt self.w.rpt_tbl.set_tree(self.rpt_dict) def set_obslog_format_cb(self, w, idx): ext = w.get_text() obslog_name = self.w.obslog_name.get_text().strip() name,", "['ObsLog'] class ObsLog(GingaPlugin.GlobalPlugin): def __init__(self, fv): super(ObsLog, self).__init__(fv) self.chname = None self.file_prefixes =", "[] # columns to be shown in the table columns = [(\"Obs Mod\",", "fv): super(ObsLog, self).__init__(fv) self.chname = None self.file_prefixes = [] # columns to be", "'label', \"memo\", 'entry', 'Add Memo', 'button'), ) w, b = Widgets.build_info(captions, orientation='vertical') self.w.update(b)", "Val\", 'FOC-VAL'), #(\"Filter01\", 'FILTER01'), #(\"Filter02\", 'FILTER02'), #(\"Filter03\", 'FILTER03'), (\"RA\", 'RA'), (\"DEC\", 'DEC'), (\"EQUINOX\",", "'FILTER02'), #(\"Filter03\", 'FILTER03'), (\"RA\", 'RA'), (\"DEC\", 'DEC'), (\"EQUINOX\", 'EQUINOX'), (\"Memo\", 'G_MEMO'), ] prefs", "stretch=0) btns.add_widget(Widgets.Label(''), stretch=1) vbox.add_widget(btns, stretch=0) container.add_widget(vbox, stretch=1) self.gui_up = True def replace_kwds(self, header):", "use the type selector combobox to pick the right extension: * csv: *", "tv.setup_table(self.rpt_columns, 1, 'FRAMEID') captions = ((\"Memo:\", 'label', \"memo\", 'entry', 'Add Memo', 'button'), )", "header, image) except Exception as e: self.logger.error(\"Failed to process image: {}\".format(e), exc_info=True) def", "key in self.rpt_columns] rows = [list(d.values()) for d in self.rpt_dict.values()] df = pd.DataFrame(rows,", "down CTRL and/or SHIFT keys. ***Displaying an image*** Double-click on a log entry.", "def get_selected(self): res_dict = self.w.rpt_tbl.get_selected() return res_dict def dblclick_cb(self, widget, d): \"\"\"Switch to", "container.add_widget(vbox, stretch=1) self.gui_up = True def replace_kwds(self, header): \"\"\"Subclass this method to do", "saved will depend on the file extension of the filename; use the type", "file format The file is rewritten out every time a new entry is", "self.fv.add_callback('add-image', self.incoming_data_cb) self.gui_up = False def build_gui(self, container): vbox = Widgets.VBox() vbox.set_border_width(1) vbox.set_spacing(1)", "to do something special with the data.\"\"\" pass def incoming_data_cb(self, fv, chname, image,", "self.fv.show_error(\"Please install 'pandas' and \" \"'openpyxl' to use this feature\") return try: self.logger.info(\"loading", "a file*** Put in values for the Observation Log folder and filename. The", "d.update(header) return d def add_to_obslog(self, header, image): frameid = header['FRAMEID'] # replace some", "= dict() d.update(header) return d def add_to_obslog(self, header, image): frameid = header['FRAMEID'] #", "accepted = True break if not accepted: return header = image.get_header() # add", "os.path.splitext(obslog_name) self.w.obslog_name.set_text(name + '.' + ext) self.write_obslog_cb(None) def close(self): self.fv.stop_global_plugin(str(self)) return True def", "index=False, header=True) except Exception as e: self.logger.error(\"Error writing obslog: {}\".format(e), exc_info=True) def load_obslog(self,", "pd.read_excel(filepath, header=0, #names=col_hdr, index_col=None) self.rpt_dict = OrderedDict({}) res = df.to_dict('index') for row in", "= tv vbox.add_widget(tv, stretch=1) tv.add_callback('activated', self.dblclick_cb) tv.add_callback('selected', self.select_cb) self.rpt_columns = self.settings.get('report_columns') tv.setup_table(self.rpt_columns, 1,", "shown in the table columns = [(\"Obs Mod\", 'OBS-MOD'), (\"Datatype\", 'DATA-TYP'), (\"FrameID\", 'FRAMEID'),", "'FILTER03'), (\"RA\", 'RA'), (\"DEC\", 'DEC'), (\"EQUINOX\", 'EQUINOX'), (\"Memo\", 'G_MEMO'), ] prefs = self.fv.get_preferences()", "to add the memo to and press the \"Add Memo\" button. Multiple selection", "self.rpt_columns]) self.rpt_dict[frameid] = d self.update_obslog() def stop(self): self.gui_up = False def process_image(self, chname,", "obs_log = self.settings.get('obslog_name', None) if obs_log is None: obs_log = '' b.obslog_name.set_text(obs_log) b.obslog_name.set_tooltip('File", "frames') b.add_memo.add_callback('activated', self.add_memo_cb) b.add_memo.set_enabled(False) captions = ((\"Folder:\", 'label', \"obslog_dir\", 'entry', \"Name:\", 'label', \"obslog_name\",", "import OrderedDict from ginga import GingaPlugin, AstroImage from ginga.gw import Widgets __all__ =", "except ImportError: self.fv.show_error(\"Please install 'pandas' and \" \"'openpyxl' to use this feature\") return", "self.file_prefixes = [] # columns to be shown in the table columns =", "image*** Double-click on a log entry. \"\"\" import os from collections import OrderedDict", "True def replace_kwds(self, header): \"\"\"Subclass this method to do munge the data for", "info): if chname != self.chname: return imname = image.get('name', None) if imname is", "pd.read_csv(filepath, header=0, #names=col_hdr, index_col=None) else: df = pd.read_excel(filepath, header=0, #names=col_hdr, index_col=None) self.rpt_dict =", "entry is added to the log ***Adding a memo to one or more", "channel.name != chname: channel = self.fv.get_channel(chname) self.fv.change_channel(chname) channel.switch_name(imname) def select_cb(self, widget, d): res", "\"\"\"Override this method to do something special with the data.\"\"\" pass def incoming_data_cb(self,", "pass def incoming_data_cb(self, fv, chname, image, info): if chname != self.chname: return imname", "is None: return # only accepted list of frames accepted = False for", "Exception as e: self.logger.error(\"Failed to process image: {}\".format(e), exc_info=True) def update_obslog(self): if not", "install 'pandas' and \" \"'openpyxl' to use this feature\") return try: self.logger.info(\"writing obslog:", "= row['FrameID'] d = OrderedDict([(kwd, row.get(col, '')) for col, kwd in self.rpt_columns]) self.rpt_dict[frameid]", "res.keys(): self.rpt_dict[key]['G_MEMO'] = memo_txt self.w.rpt_tbl.set_tree(self.rpt_dict) def set_obslog_format_cb(self, w, idx): ext = w.get_text() obslog_name", "Write a memo in the memo box. Select one or more frames to", "**Plugin Type: Global** ``ObsLog`` is a global plugin. Only one instance can be", "= d self.update_obslog() def stop(self): self.gui_up = False def process_image(self, chname, header, image):", "get the columns in the desired order d = OrderedDict([(kwd, d.get(kwd, '')) for", "self.rpt_columns] if filepath.endswith('.csv'): df = pd.read_csv(filepath, header=0, #names=col_hdr, index_col=None) else: df = pd.read_excel(filepath,", "(\"Air Mass\", 'AIRMASS'), #(\"Pos Ang\", 'INST-PA'), #(\"Ins Rot\", 'INSROT'), #(\"Foc Val\", 'FOC-VAL'), #(\"Filter01\",", "pd.DataFrame(rows, columns=col_hdr) if filepath.endswith('.csv'): df.to_csv(filepath, index=False, header=True) else: df.to_excel(filepath, index=False, header=True) except Exception", "btns.add_widget(btn, stretch=0) btns.add_widget(Widgets.Label(''), stretch=1) vbox.add_widget(btns, stretch=0) container.add_widget(vbox, stretch=1) self.gui_up = True def replace_kwds(self,", "= False for prefix in self.file_prefixes: if imname.startswith(prefix): accepted = True break if", "for colname, key in self.rpt_columns] if filepath.endswith('.csv'): df = pd.read_csv(filepath, header=0, #names=col_hdr, index_col=None)", "more frames to add the memo to and press the \"Add Memo\" button.", "imname.startswith(prefix): accepted = True break if not accepted: return header = image.get_header() #", "key in res.keys(): self.rpt_dict[key]['G_MEMO'] = memo_txt self.w.rpt_tbl.set_tree(self.rpt_dict) def set_obslog_format_cb(self, w, idx): ext =", "ObsLog\") b.load.add_callback('activated', self.load_obslog_cb) btns = Widgets.HBox() btns.set_border_width(4) btns.set_spacing(4) btn = Widgets.Button(\"Close\") btn.add_callback('activated', lambda", "filepath.endswith('.csv'): df = pd.read_csv(filepath, header=0, #names=col_hdr, index_col=None) else: df = pd.read_excel(filepath, header=0, #names=col_hdr,", "def load_obslog_cb(self, w): obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), self.w.obslog_name.get_text().strip()) self.load_obslog(obslog_path) def get_selected(self): res_dict = self.w.rpt_tbl.get_selected()", "some kwds as needed in the table d = self.replace_kwds(header.asdict()) # Hack to", "data for special reports.\"\"\" d = dict() d.update(header) return d def add_to_obslog(self, header,", "self.help()) btns.add_widget(btn, stretch=0) btns.add_widget(Widgets.Label(''), stretch=1) vbox.add_widget(btns, stretch=0) container.add_widget(vbox, stretch=1) self.gui_up = True def", "\"Load\", 'button'), ) w, b = Widgets.build_info(captions, orientation='vertical') self.w.update(b) vbox.add_widget(w, stretch=0) obs_log =", "be opened. **Usage** ***Saving the log to a file*** Put in values for", "= False def build_gui(self, container): vbox = Widgets.VBox() vbox.set_border_width(1) vbox.set_spacing(1) tv = Widgets.TreeView(sortable=self.settings.get('sortable'),", "btn = Widgets.Button(\"Help\") btn.add_callback('activated', lambda w: self.help()) btns.add_widget(btn, stretch=0) btns.add_widget(Widgets.Label(''), stretch=1) vbox.add_widget(btns, stretch=0)", "Widgets.VBox() vbox.set_border_width(1) vbox.set_spacing(1) tv = Widgets.TreeView(sortable=self.settings.get('sortable'), use_alt_row_color=self.settings.get('color_alternate_rows'), selection='multiple') self.w.rpt_tbl = tv vbox.add_widget(tv, stretch=1)", "OrderedDict({}) res = df.to_dict('index') for row in res.values(): frameid = row['FrameID'] d =", "self.rpt_dict.values()] df = pd.DataFrame(rows, columns=col_hdr) if filepath.endswith('.csv'): df.to_csv(filepath, index=False, header=True) else: df.to_excel(filepath, index=False,", "add_memo_cb(self, widget): memo_txt = self.w.memo.get_text().strip() res = self.get_selected() if len(res) == 0: self.fv.show_error(\"No", "'label', \"obslog_name\", 'entryset', \"Type\", 'combobox', \"Load\", 'button'), ) w, b = Widgets.build_info(captions, orientation='vertical')", "obslog: {}\".format(filepath)) col_hdr = [colname for colname, key in self.rpt_columns] rows = [list(d.values())", "the file extension of the filename; use the type selector combobox to pick", "break if not accepted: return header = image.get_header() # add image to obslog", "for selected frames') b.add_memo.add_callback('activated', self.add_memo_cb) b.add_memo.set_enabled(False) captions = ((\"Folder:\", 'label', \"obslog_dir\", 'entry', \"Name:\",", "if filepath.endswith('.csv'): df.to_csv(filepath, index=False, header=True) else: df.to_excel(filepath, index=False, header=True) except Exception as e:", "be shown in the table columns = [(\"Obs Mod\", 'OBS-MOD'), (\"Datatype\", 'DATA-TYP'), (\"FrameID\",", "= Widgets.Button(\"Help\") btn.add_callback('activated', lambda w: self.help()) btns.add_widget(btn, stretch=0) btns.add_widget(Widgets.Label(''), stretch=1) vbox.add_widget(btns, stretch=0) container.add_widget(vbox,", "self.w.obslog_name.get_text().strip()) self.write_obslog(obslog_path) def load_obslog_cb(self, w): obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), self.w.obslog_name.get_text().strip()) self.load_obslog(obslog_path) def get_selected(self): res_dict", "return header = image.get_header() # add image to obslog self.fv.gui_do(self.add_to_obslog, header, image) try:", "kwd in self.rpt_columns]) self.rpt_dict[frameid] = d self.update_obslog() def stop(self): self.gui_up = False def", "os.path.join(self.w.obslog_dir.get_text().strip(), obslog_name) self.write_obslog(obslog_path) def write_obslog(self, filepath): if len(self.rpt_dict) == 0: return try: import", "if imname.startswith(prefix): accepted = True break if not accepted: return header = image.get_header()", "on a log entry. \"\"\" import os from collections import OrderedDict from ginga", "= self.settings.get('report_columns') tv.setup_table(self.rpt_columns, 1, 'FRAMEID') captions = ((\"Memo:\", 'label', \"memo\", 'entry', 'Add Memo',", "image.get('name', None) if imname is None: return # only accepted list of frames", "try: self.process_image(chname, header, image) except Exception as e: self.logger.error(\"Failed to process image: {}\".format(e),", "[colname for colname, key in self.rpt_columns] rows = [list(d.values()) for d in self.rpt_dict.values()]", "'FRAMEID'), (\"Object\", 'OBJECT'), (\"UT\", 'UT'), (\"PropId\", 'PROP-ID'), (\"Exp Time\", 'EXPTIME'), (\"Air Mass\", 'AIRMASS'),", "Please see the file LICENSE.txt for details. \"\"\"Observation Log plugin. **Plugin Type: Global**", "self.get_selected() if len(res) == 0: self.w.add_memo.set_enabled(False) else: self.w.add_memo.set_enabled(True) def add_memo_cb(self, widget): memo_txt =", "something special with the data.\"\"\" pass def incoming_data_cb(self, fv, chname, image, info): if", "self.settings.get('obslog_name', None) if obs_log is None: obs_log = '' b.obslog_name.set_text(obs_log) b.obslog_name.set_tooltip('File name for", "= self.fv.get_preferences() self.settings = prefs.create_category('plugin_ObsLog') self.settings.add_defaults(sortable=True, color_alternate_rows=True, #max_rows_for_col_resize=5000, report_columns=columns, cache_normalized_images=True) self.settings.load(onError='silent') self.rpt_dict =", "d self.w.rpt_tbl.set_tree(self.rpt_dict) except Exception as e: self.logger.error(\"Error loading obslog: {}\".format(e), exc_info=True) def write_obslog_cb(self,", "for details. \"\"\"Observation Log plugin. **Plugin Type: Global** ``ObsLog`` is a global plugin.", "'pandas' and \" \"'openpyxl' to use this feature\") return try: self.logger.info(\"writing obslog: {}\".format(filepath))", "Widgets.HBox() btns.set_border_width(4) btns.set_spacing(4) btn = Widgets.Button(\"Close\") btn.add_callback('activated', lambda w: self.close()) btn.set_enabled(False) btns.add_widget(btn) btn", "(\"FrameID\", 'FRAMEID'), (\"Object\", 'OBJECT'), (\"UT\", 'UT'), (\"PropId\", 'PROP-ID'), (\"Exp Time\", 'EXPTIME'), (\"Air Mass\",", "in self.rpt_columns] rows = [list(d.values()) for d in self.rpt_dict.values()] df = pd.DataFrame(rows, columns=col_hdr)", "self.w.rpt_tbl.get_selected() return res_dict def dblclick_cb(self, widget, d): \"\"\"Switch to the image that was", "if len(res) == 0: self.fv.show_error(\"No frames selected for memo!\") return for key in", "b.add_memo.add_callback('activated', self.add_memo_cb) b.add_memo.set_enabled(False) captions = ((\"Folder:\", 'label', \"obslog_dir\", 'entry', \"Name:\", 'label', \"obslog_name\", 'entryset',", "'button'), ) w, b = Widgets.build_info(captions, orientation='vertical') self.w.update(b) vbox.add_widget(w, stretch=0) obs_log = self.settings.get('obslog_name',", "Widgets.build_info(captions, orientation='vertical') self.w.update(b) vbox.add_widget(w, stretch=0) b.memo.set_tooltip('Set memo for selected frames') b.add_memo.add_callback('activated', self.add_memo_cb) b.add_memo.set_enabled(False)", "for col, kwd in self.rpt_columns]) self.rpt_dict[frameid] = d self.w.rpt_tbl.set_tree(self.rpt_dict) except Exception as e:", "header, image): frameid = header['FRAMEID'] # replace some kwds as needed in the", "def add_memo_cb(self, widget): memo_txt = self.w.memo.get_text().strip() res = self.get_selected() if len(res) == 0:", "Log folder and filename. The format of the file saved will depend on", "to be shown in the table columns = [(\"Obs Mod\", 'OBS-MOD'), (\"Datatype\", 'DATA-TYP'),", "'pandas' and \" \"'openpyxl' to use this feature\") return try: self.logger.info(\"loading obslog: {}\".format(filepath))", "'INSROT'), #(\"Foc Val\", 'FOC-VAL'), #(\"Filter01\", 'FILTER01'), #(\"Filter02\", 'FILTER02'), #(\"Filter03\", 'FILTER03'), (\"RA\", 'RA'), (\"DEC\",", "#names=col_hdr, index_col=None) else: df = pd.read_excel(filepath, header=0, #names=col_hdr, index_col=None) self.rpt_dict = OrderedDict({}) res", "rules about holding down CTRL and/or SHIFT keys. ***Displaying an image*** Double-click on", "widget, d): res = self.get_selected() if len(res) == 0: self.w.add_memo.set_enabled(False) else: self.w.add_memo.set_enabled(True) def", "w.get_text() obslog_name = self.w.obslog_name.get_text().strip() name, old_ext = os.path.splitext(obslog_name) self.w.obslog_name.set_text(name + '.' + ext)", "= self.w.memo.get_text().strip() res = self.get_selected() if len(res) == 0: self.fv.show_error(\"No frames selected for", "def incoming_data_cb(self, fv, chname, image, info): if chname != self.chname: return imname =", "= os.path.splitext(obslog_name) self.w.obslog_name.set_text(name + '.' + ext) self.write_obslog_cb(None) def close(self): self.fv.stop_global_plugin(str(self)) return True", "kwds as needed in the table d = self.replace_kwds(header.asdict()) # Hack to insure", "list(d.keys())[0] info = d[frameid] self.view_image(frameid, info) def view_image(self, imname, info): chname = self.chname", "one or more log entries*** Write a memo in the memo box. Select", "return for key in res.keys(): self.rpt_dict[key]['G_MEMO'] = memo_txt self.w.rpt_tbl.set_tree(self.rpt_dict) def set_obslog_format_cb(self, w, idx):", "= self.settings.get('obslog_name', None) if obs_log is None: obs_log = '' b.obslog_name.set_text(obs_log) b.obslog_name.set_tooltip('File name", "__all__ = ['ObsLog'] class ObsLog(GingaPlugin.GlobalPlugin): def __init__(self, fv): super(ObsLog, self).__init__(fv) self.chname = None", "observation log') b.obslog_dir.add_callback('activated', self.write_obslog_cb) b.type.insert_alpha(\"csv\") b.type.insert_alpha(\"xlsx\") b.type.set_tooltip(\"Format for saving/loading ObsLog\") b.type.add_callback('activated', self.set_obslog_format_cb) b.load.set_tooltip(\"Load", "df.to_dict('index') for row in res.values(): frameid = row['FrameID'] d = OrderedDict([(kwd, row.get(col, ''))", "obslog self.fv.gui_do(self.add_to_obslog, header, image) try: self.process_image(chname, header, image) except Exception as e: self.logger.error(\"Failed", "\"Type\", 'combobox', \"Load\", 'button'), ) w, b = Widgets.build_info(captions, orientation='vertical') self.w.update(b) vbox.add_widget(w, stretch=0)", "self.write_obslog(obslog_path) def write_obslog(self, filepath): if len(self.rpt_dict) == 0: return try: import pandas as", "self.w.rpt_tbl = tv vbox.add_widget(tv, stretch=1) tv.add_callback('activated', self.dblclick_cb) tv.add_callback('selected', self.select_cb) self.rpt_columns = self.settings.get('report_columns') tv.setup_table(self.rpt_columns,", "extension: * csv: * xlsx: MS Excel file format The file is rewritten", "ImportError: self.fv.show_error(\"Please install 'pandas' and \" \"'openpyxl' to use this feature\") return try:", "= self.w.rpt_tbl.get_selected() return res_dict def dblclick_cb(self, widget, d): \"\"\"Switch to the image that", "method to do munge the data for special reports.\"\"\" d = dict() d.update(header)", "idx): ext = w.get_text() obslog_name = self.w.obslog_name.get_text().strip() name, old_ext = os.path.splitext(obslog_name) self.w.obslog_name.set_text(name +", "we get the columns in the desired order d = OrderedDict([(kwd, d.get(kwd, ''))", "details. \"\"\"Observation Log plugin. **Plugin Type: Global** ``ObsLog`` is a global plugin. Only", "memo to and press the \"Add Memo\" button. Multiple selection follows the usual", "captions = ((\"Folder:\", 'label', \"obslog_dir\", 'entry', \"Name:\", 'label', \"obslog_name\", 'entryset', \"Type\", 'combobox', \"Load\",", "pd except ImportError: self.fv.show_error(\"Please install 'pandas' and \" \"'openpyxl' to use this feature\")", "special reports.\"\"\" d = dict() d.update(header) return d def add_to_obslog(self, header, image): frameid", "chname != self.chname: return imname = image.get('name', None) if imname is None: return", "licensed under a BSD license. # Please see the file LICENSE.txt for details.", "in self.rpt_columns]) self.rpt_dict[frameid] = d self.w.rpt_tbl.set_tree(self.rpt_dict) except Exception as e: self.logger.error(\"Error loading obslog:", "#max_rows_for_col_resize=5000, report_columns=columns, cache_normalized_images=True) self.settings.load(onError='silent') self.rpt_dict = OrderedDict({}) self.rpt_columns = [] self.fv.add_callback('add-image', self.incoming_data_cb) self.gui_up", "if chname != self.chname: return imname = image.get('name', None) if imname is None:", "w: self.close()) btn.set_enabled(False) btns.add_widget(btn) btn = Widgets.Button(\"Help\") btn.add_callback('activated', lambda w: self.help()) btns.add_widget(btn, stretch=0)", "try: self.logger.info(\"writing obslog: {}\".format(filepath)) col_hdr = [colname for colname, key in self.rpt_columns] rows", "= image.get('name', None) if imname is None: return # only accepted list of", "to obslog self.fv.gui_do(self.add_to_obslog, header, image) try: self.process_image(chname, header, image) except Exception as e:", "= OrderedDict([(kwd, d.get(kwd, '')) for col, kwd in self.rpt_columns]) self.rpt_dict[frameid] = d self.update_obslog()", "self.get_selected() if len(res) == 0: self.fv.show_error(\"No frames selected for memo!\") return for key", "license. # Please see the file LICENSE.txt for details. \"\"\"Observation Log plugin. **Plugin", "software licensed under a BSD license. # Please see the file LICENSE.txt for", "desired order d = OrderedDict([(kwd, d.get(kwd, '')) for col, kwd in self.rpt_columns]) self.rpt_dict[frameid]", "insure that we get the columns in the desired order d = OrderedDict([(kwd,", "a BSD license. # Please see the file LICENSE.txt for details. \"\"\"Observation Log", "stretch=1) self.gui_up = True def replace_kwds(self, header): \"\"\"Subclass this method to do munge", "info): chname = self.chname channel = self.fv.get_current_channel() if channel.name != chname: channel =", "memo for selected frames') b.add_memo.add_callback('activated', self.add_memo_cb) b.add_memo.set_enabled(False) captions = ((\"Folder:\", 'label', \"obslog_dir\", 'entry',", "imname = image.get('name', None) if imname is None: return # only accepted list", "((\"Memo:\", 'label', \"memo\", 'entry', 'Add Memo', 'button'), ) w, b = Widgets.build_info(captions, orientation='vertical')", "super(ObsLog, self).__init__(fv) self.chname = None self.file_prefixes = [] # columns to be shown", "Rot\", 'INSROT'), #(\"Foc Val\", 'FOC-VAL'), #(\"Filter01\", 'FILTER01'), #(\"Filter02\", 'FILTER02'), #(\"Filter03\", 'FILTER03'), (\"RA\", 'RA'),", "image): \"\"\"Override this method to do something special with the data.\"\"\" pass def", "b.obslog_name.add_callback('activated', self.write_obslog_cb) b.obslog_dir.set_text(\"/tmp\") b.obslog_dir.set_tooltip('Folder path for observation log') b.obslog_dir.add_callback('activated', self.write_obslog_cb) b.type.insert_alpha(\"csv\") b.type.insert_alpha(\"xlsx\") b.type.set_tooltip(\"Format", "table d = self.replace_kwds(header.asdict()) # Hack to insure that we get the columns", "0: return try: import pandas as pd except ImportError: self.fv.show_error(\"Please install 'pandas' and", "format of the file saved will depend on the file extension of the", "the columns in the desired order d = OrderedDict([(kwd, d.get(kwd, '')) for col,", "\"'openpyxl' to use this feature\") return try: self.logger.info(\"loading obslog: {}\".format(filepath)) col_hdr = [colname", "the memo to and press the \"Add Memo\" button. Multiple selection follows the", "index=False, header=True) else: df.to_excel(filepath, index=False, header=True) except Exception as e: self.logger.error(\"Error writing obslog:", "as e: self.logger.error(\"Error loading obslog: {}\".format(e), exc_info=True) def write_obslog_cb(self, w): obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(),", "res_dict = self.w.rpt_tbl.get_selected() return res_dict def dblclick_cb(self, widget, d): \"\"\"Switch to the image", "collections import OrderedDict from ginga import GingaPlugin, AstroImage from ginga.gw import Widgets __all__", "vbox = Widgets.VBox() vbox.set_border_width(1) vbox.set_spacing(1) tv = Widgets.TreeView(sortable=self.settings.get('sortable'), use_alt_row_color=self.settings.get('color_alternate_rows'), selection='multiple') self.w.rpt_tbl = tv", "'button'), ) w, b = Widgets.build_info(captions, orientation='vertical') self.w.update(b) vbox.add_widget(w, stretch=0) b.memo.set_tooltip('Set memo for", "to the log ***Adding a memo to one or more log entries*** Write", "chname = self.chname channel = self.fv.get_current_channel() if channel.name != chname: channel = self.fv.get_channel(chname)", "GingaPlugin, AstroImage from ginga.gw import Widgets __all__ = ['ObsLog'] class ObsLog(GingaPlugin.GlobalPlugin): def __init__(self,", "self.process_image(chname, header, image) except Exception as e: self.logger.error(\"Failed to process image: {}\".format(e), exc_info=True)", "def update_obslog(self): if not self.gui_up: return self.w.rpt_tbl.set_tree(self.rpt_dict) obslog_name = self.w.obslog_name.get_text().strip() if len(obslog_name) >", "if obs_log is None: obs_log = '' b.obslog_name.set_text(obs_log) b.obslog_name.set_tooltip('File name for observation log')", "False def build_gui(self, container): vbox = Widgets.VBox() vbox.set_border_width(1) vbox.set_spacing(1) tv = Widgets.TreeView(sortable=self.settings.get('sortable'), use_alt_row_color=self.settings.get('color_alternate_rows'),", "= ['ObsLog'] class ObsLog(GingaPlugin.GlobalPlugin): def __init__(self, fv): super(ObsLog, self).__init__(fv) self.chname = None self.file_prefixes", "the file saved will depend on the file extension of the filename; use", "0: self.w.add_memo.set_enabled(False) else: self.w.add_memo.set_enabled(True) def add_memo_cb(self, widget): memo_txt = self.w.memo.get_text().strip() res = self.get_selected()", "to one or more log entries*** Write a memo in the memo box.", "'AIRMASS'), #(\"Pos Ang\", 'INST-PA'), #(\"Ins Rot\", 'INSROT'), #(\"Foc Val\", 'FOC-VAL'), #(\"Filter01\", 'FILTER01'), #(\"Filter02\",", "select_cb(self, widget, d): res = self.get_selected() if len(res) == 0: self.w.add_memo.set_enabled(False) else: self.w.add_memo.set_enabled(True)", "key in self.rpt_columns] if filepath.endswith('.csv'): df = pd.read_csv(filepath, header=0, #names=col_hdr, index_col=None) else: df", "(\"DEC\", 'DEC'), (\"EQUINOX\", 'EQUINOX'), (\"Memo\", 'G_MEMO'), ] prefs = self.fv.get_preferences() self.settings = prefs.create_category('plugin_ObsLog')", "the table d = self.replace_kwds(header.asdict()) # Hack to insure that we get the", "'OBJECT'), (\"UT\", 'UT'), (\"PropId\", 'PROP-ID'), (\"Exp Time\", 'EXPTIME'), (\"Air Mass\", 'AIRMASS'), #(\"Pos Ang\",", "exc_info=True) def load_obslog(self, filepath): try: import pandas as pd except ImportError: self.fv.show_error(\"Please install", "in the memo box. Select one or more frames to add the memo", "dblclick_cb(self, widget, d): \"\"\"Switch to the image that was double-clicked in the obslog\"\"\"", "is None: obs_log = '' b.obslog_name.set_text(obs_log) b.obslog_name.set_tooltip('File name for observation log') b.obslog_name.add_callback('activated', self.write_obslog_cb)", "import Widgets __all__ = ['ObsLog'] class ObsLog(GingaPlugin.GlobalPlugin): def __init__(self, fv): super(ObsLog, self).__init__(fv) self.chname", "Memo\" button. Multiple selection follows the usual rules about holding down CTRL and/or", "0: obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), obslog_name) self.write_obslog(obslog_path) def write_obslog(self, filepath): if len(self.rpt_dict) == 0:", "'entry', \"Name:\", 'label', \"obslog_name\", 'entryset', \"Type\", 'combobox', \"Load\", 'button'), ) w, b =", "[list(d.values()) for d in self.rpt_dict.values()] df = pd.DataFrame(rows, columns=col_hdr) if filepath.endswith('.csv'): df.to_csv(filepath, index=False,", "self.fv.get_preferences() self.settings = prefs.create_category('plugin_ObsLog') self.settings.add_defaults(sortable=True, color_alternate_rows=True, #max_rows_for_col_resize=5000, report_columns=columns, cache_normalized_images=True) self.settings.load(onError='silent') self.rpt_dict = OrderedDict({})", "#(\"Filter01\", 'FILTER01'), #(\"Filter02\", 'FILTER02'), #(\"Filter03\", 'FILTER03'), (\"RA\", 'RA'), (\"DEC\", 'DEC'), (\"EQUINOX\", 'EQUINOX'), (\"Memo\",", "vbox.add_widget(w, stretch=0) b.memo.set_tooltip('Set memo for selected frames') b.add_memo.add_callback('activated', self.add_memo_cb) b.add_memo.set_enabled(False) captions = ((\"Folder:\",", "image: {}\".format(e), exc_info=True) def update_obslog(self): if not self.gui_up: return self.w.rpt_tbl.set_tree(self.rpt_dict) obslog_name = self.w.obslog_name.get_text().strip()", "file extension of the filename; use the type selector combobox to pick the", "incoming_data_cb(self, fv, chname, image, info): if chname != self.chname: return imname = image.get('name',", "or more frames to add the memo to and press the \"Add Memo\"", "to process image: {}\".format(e), exc_info=True) def update_obslog(self): if not self.gui_up: return self.w.rpt_tbl.set_tree(self.rpt_dict) obslog_name", "channel.switch_name(imname) def select_cb(self, widget, d): res = self.get_selected() if len(res) == 0: self.w.add_memo.set_enabled(False)", "class ObsLog(GingaPlugin.GlobalPlugin): def __init__(self, fv): super(ObsLog, self).__init__(fv) self.chname = None self.file_prefixes = []", "(\"Memo\", 'G_MEMO'), ] prefs = self.fv.get_preferences() self.settings = prefs.create_category('plugin_ObsLog') self.settings.add_defaults(sortable=True, color_alternate_rows=True, #max_rows_for_col_resize=5000, report_columns=columns,", "self.replace_kwds(header.asdict()) # Hack to insure that we get the columns in the desired", "entry. \"\"\" import os from collections import OrderedDict from ginga import GingaPlugin, AstroImage", "= OrderedDict({}) self.rpt_columns = [] self.fv.add_callback('add-image', self.incoming_data_cb) self.gui_up = False def build_gui(self, container):", "entries*** Write a memo in the memo box. Select one or more frames", "#(\"Pos Ang\", 'INST-PA'), #(\"Ins Rot\", 'INSROT'), #(\"Foc Val\", 'FOC-VAL'), #(\"Filter01\", 'FILTER01'), #(\"Filter02\", 'FILTER02'),", "the file LICENSE.txt for details. \"\"\"Observation Log plugin. **Plugin Type: Global** ``ObsLog`` is", "len(self.rpt_dict) == 0: return try: import pandas as pd except ImportError: self.fv.show_error(\"Please install", "in the table columns = [(\"Obs Mod\", 'OBS-MOD'), (\"Datatype\", 'DATA-TYP'), (\"FrameID\", 'FRAMEID'), (\"Object\",", "global plugin. Only one instance can be opened. **Usage** ***Saving the log to", "BSD license. # Please see the file LICENSE.txt for details. \"\"\"Observation Log plugin.", "Log plugin. **Plugin Type: Global** ``ObsLog`` is a global plugin. Only one instance", "0: self.fv.show_error(\"No frames selected for memo!\") return for key in res.keys(): self.rpt_dict[key]['G_MEMO'] =", "The format of the file saved will depend on the file extension of", "w, idx): ext = w.get_text() obslog_name = self.w.obslog_name.get_text().strip() name, old_ext = os.path.splitext(obslog_name) self.w.obslog_name.set_text(name", "chname, image, info): if chname != self.chname: return imname = image.get('name', None) if", "self.file_prefixes: if imname.startswith(prefix): accepted = True break if not accepted: return header =", "header = image.get_header() # add image to obslog self.fv.gui_do(self.add_to_obslog, header, image) try: self.process_image(chname,", "columns to be shown in the table columns = [(\"Obs Mod\", 'OBS-MOD'), (\"Datatype\",", "= pd.read_csv(filepath, header=0, #names=col_hdr, index_col=None) else: df = pd.read_excel(filepath, header=0, #names=col_hdr, index_col=None) self.rpt_dict", "The file is rewritten out every time a new entry is added to", "= memo_txt self.w.rpt_tbl.set_tree(self.rpt_dict) def set_obslog_format_cb(self, w, idx): ext = w.get_text() obslog_name = self.w.obslog_name.get_text().strip()", "= Widgets.VBox() vbox.set_border_width(1) vbox.set_spacing(1) tv = Widgets.TreeView(sortable=self.settings.get('sortable'), use_alt_row_color=self.settings.get('color_alternate_rows'), selection='multiple') self.w.rpt_tbl = tv vbox.add_widget(tv,", "from ginga.gw import Widgets __all__ = ['ObsLog'] class ObsLog(GingaPlugin.GlobalPlugin): def __init__(self, fv): super(ObsLog,", "lambda w: self.close()) btn.set_enabled(False) btns.add_widget(btn) btn = Widgets.Button(\"Help\") btn.add_callback('activated', lambda w: self.help()) btns.add_widget(btn,", "import os from collections import OrderedDict from ginga import GingaPlugin, AstroImage from ginga.gw", "to and press the \"Add Memo\" button. Multiple selection follows the usual rules", "stretch=1) tv.add_callback('activated', self.dblclick_cb) tv.add_callback('selected', self.select_cb) self.rpt_columns = self.settings.get('report_columns') tv.setup_table(self.rpt_columns, 1, 'FRAMEID') captions =", "self.write_obslog_cb) b.obslog_dir.set_text(\"/tmp\") b.obslog_dir.set_tooltip('Folder path for observation log') b.obslog_dir.add_callback('activated', self.write_obslog_cb) b.type.insert_alpha(\"csv\") b.type.insert_alpha(\"xlsx\") b.type.set_tooltip(\"Format for", "for observation log') b.obslog_dir.add_callback('activated', self.write_obslog_cb) b.type.insert_alpha(\"csv\") b.type.insert_alpha(\"xlsx\") b.type.set_tooltip(\"Format for saving/loading ObsLog\") b.type.add_callback('activated', self.set_obslog_format_cb)", "'PROP-ID'), (\"Exp Time\", 'EXPTIME'), (\"Air Mass\", 'AIRMASS'), #(\"Pos Ang\", 'INST-PA'), #(\"Ins Rot\", 'INSROT'),", "def set_obslog_format_cb(self, w, idx): ext = w.get_text() obslog_name = self.w.obslog_name.get_text().strip() name, old_ext =", "memo to one or more log entries*** Write a memo in the memo", "= Widgets.build_info(captions, orientation='vertical') self.w.update(b) vbox.add_widget(w, stretch=0) b.memo.set_tooltip('Set memo for selected frames') b.add_memo.add_callback('activated', self.add_memo_cb)", "if imname is None: return # only accepted list of frames accepted =", "= self.chname channel = self.fv.get_current_channel() if channel.name != chname: channel = self.fv.get_channel(chname) self.fv.change_channel(chname)", "button. Multiple selection follows the usual rules about holding down CTRL and/or SHIFT", "this method to do something special with the data.\"\"\" pass def incoming_data_cb(self, fv,", "filepath): if len(self.rpt_dict) == 0: return try: import pandas as pd except ImportError:", "vbox.add_widget(btns, stretch=0) container.add_widget(vbox, stretch=1) self.gui_up = True def replace_kwds(self, header): \"\"\"Subclass this method", "saved ObsLog\") b.load.add_callback('activated', self.load_obslog_cb) btns = Widgets.HBox() btns.set_border_width(4) btns.set_spacing(4) btn = Widgets.Button(\"Close\") btn.add_callback('activated',", "view_image(self, imname, info): chname = self.chname channel = self.fv.get_current_channel() if channel.name != chname:", "return imname = image.get('name', None) if imname is None: return # only accepted", "do something special with the data.\"\"\" pass def incoming_data_cb(self, fv, chname, image, info):", "list of frames accepted = False for prefix in self.file_prefixes: if imname.startswith(prefix): accepted", "self.fv.get_current_channel() if channel.name != chname: channel = self.fv.get_channel(chname) self.fv.change_channel(chname) channel.switch_name(imname) def select_cb(self, widget,", "one instance can be opened. **Usage** ***Saving the log to a file*** Put", "row.get(col, '')) for col, kwd in self.rpt_columns]) self.rpt_dict[frameid] = d self.w.rpt_tbl.set_tree(self.rpt_dict) except Exception", "rows = [list(d.values()) for d in self.rpt_dict.values()] df = pd.DataFrame(rows, columns=col_hdr) if filepath.endswith('.csv'):", "for row in res.values(): frameid = row['FrameID'] d = OrderedDict([(kwd, row.get(col, '')) for", "'DATA-TYP'), (\"FrameID\", 'FRAMEID'), (\"Object\", 'OBJECT'), (\"UT\", 'UT'), (\"PropId\", 'PROP-ID'), (\"Exp Time\", 'EXPTIME'), (\"Air", "None self.file_prefixes = [] # columns to be shown in the table columns", "filepath): try: import pandas as pd except ImportError: self.fv.show_error(\"Please install 'pandas' and \"", "Type: Global** ``ObsLog`` is a global plugin. Only one instance can be opened.", "Double-click on a log entry. \"\"\" import os from collections import OrderedDict from", "will depend on the file extension of the filename; use the type selector", "of the filename; use the type selector combobox to pick the right extension:", "columns = [(\"Obs Mod\", 'OBS-MOD'), (\"Datatype\", 'DATA-TYP'), (\"FrameID\", 'FRAMEID'), (\"Object\", 'OBJECT'), (\"UT\", 'UT'),", "b.obslog_dir.set_text(\"/tmp\") b.obslog_dir.set_tooltip('Folder path for observation log') b.obslog_dir.add_callback('activated', self.write_obslog_cb) b.type.insert_alpha(\"csv\") b.type.insert_alpha(\"xlsx\") b.type.set_tooltip(\"Format for saving/loading", "selection follows the usual rules about holding down CTRL and/or SHIFT keys. ***Displaying", "the type selector combobox to pick the right extension: * csv: * xlsx:", "self.w.add_memo.set_enabled(False) else: self.w.add_memo.set_enabled(True) def add_memo_cb(self, widget): memo_txt = self.w.memo.get_text().strip() res = self.get_selected() if", "tv.add_callback('selected', self.select_cb) self.rpt_columns = self.settings.get('report_columns') tv.setup_table(self.rpt_columns, 1, 'FRAMEID') captions = ((\"Memo:\", 'label', \"memo\",", "as e: self.logger.error(\"Failed to process image: {}\".format(e), exc_info=True) def update_obslog(self): if not self.gui_up:", "self.fv.change_channel(chname) channel.switch_name(imname) def select_cb(self, widget, d): res = self.get_selected() if len(res) == 0:", "pandas as pd except ImportError: self.fv.show_error(\"Please install 'pandas' and \" \"'openpyxl' to use", "load_obslog(self, filepath): try: import pandas as pd except ImportError: self.fv.show_error(\"Please install 'pandas' and", "Widgets.TreeView(sortable=self.settings.get('sortable'), use_alt_row_color=self.settings.get('color_alternate_rows'), selection='multiple') self.w.rpt_tbl = tv vbox.add_widget(tv, stretch=1) tv.add_callback('activated', self.dblclick_cb) tv.add_callback('selected', self.select_cb) self.rpt_columns", "OrderedDict([(kwd, row.get(col, '')) for col, kwd in self.rpt_columns]) self.rpt_dict[frameid] = d self.w.rpt_tbl.set_tree(self.rpt_dict) except", "in self.rpt_columns]) self.rpt_dict[frameid] = d self.update_obslog() def stop(self): self.gui_up = False def process_image(self,", "Mod\", 'OBS-MOD'), (\"Datatype\", 'DATA-TYP'), (\"FrameID\", 'FRAMEID'), (\"Object\", 'OBJECT'), (\"UT\", 'UT'), (\"PropId\", 'PROP-ID'), (\"Exp", "self.incoming_data_cb) self.gui_up = False def build_gui(self, container): vbox = Widgets.VBox() vbox.set_border_width(1) vbox.set_spacing(1) tv", "d.get(kwd, '')) for col, kwd in self.rpt_columns]) self.rpt_dict[frameid] = d self.update_obslog() def stop(self):", "index_col=None) else: df = pd.read_excel(filepath, header=0, #names=col_hdr, index_col=None) self.rpt_dict = OrderedDict({}) res =", "self.chname channel = self.fv.get_current_channel() if channel.name != chname: channel = self.fv.get_channel(chname) self.fv.change_channel(chname) channel.switch_name(imname)", "memo in the memo box. Select one or more frames to add the", "from ginga import GingaPlugin, AstroImage from ginga.gw import Widgets __all__ = ['ObsLog'] class", "method to do something special with the data.\"\"\" pass def incoming_data_cb(self, fv, chname,", "vbox.set_spacing(1) tv = Widgets.TreeView(sortable=self.settings.get('sortable'), use_alt_row_color=self.settings.get('color_alternate_rows'), selection='multiple') self.w.rpt_tbl = tv vbox.add_widget(tv, stretch=1) tv.add_callback('activated', self.dblclick_cb)", "= image.get_header() # add image to obslog self.fv.gui_do(self.add_to_obslog, header, image) try: self.process_image(chname, header,", "df = pd.read_csv(filepath, header=0, #names=col_hdr, index_col=None) else: df = pd.read_excel(filepath, header=0, #names=col_hdr, index_col=None)", "of the file saved will depend on the file extension of the filename;", "update_obslog(self): if not self.gui_up: return self.w.rpt_tbl.set_tree(self.rpt_dict) obslog_name = self.w.obslog_name.get_text().strip() if len(obslog_name) > 0:", "selection='multiple') self.w.rpt_tbl = tv vbox.add_widget(tv, stretch=1) tv.add_callback('activated', self.dblclick_cb) tv.add_callback('selected', self.select_cb) self.rpt_columns = self.settings.get('report_columns')", "self.rpt_dict[frameid] = d self.update_obslog() def stop(self): self.gui_up = False def process_image(self, chname, header,", "w): obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), self.w.obslog_name.get_text().strip()) self.load_obslog(obslog_path) def get_selected(self): res_dict = self.w.rpt_tbl.get_selected() return res_dict", "self.w.update(b) vbox.add_widget(w, stretch=0) b.memo.set_tooltip('Set memo for selected frames') b.add_memo.add_callback('activated', self.add_memo_cb) b.add_memo.set_enabled(False) captions =", "Hack to insure that we get the columns in the desired order d", "obslog_name) self.write_obslog(obslog_path) def write_obslog(self, filepath): if len(self.rpt_dict) == 0: return try: import pandas", "captions = ((\"Memo:\", 'label', \"memo\", 'entry', 'Add Memo', 'button'), ) w, b =", "w, b = Widgets.build_info(captions, orientation='vertical') self.w.update(b) vbox.add_widget(w, stretch=0) b.memo.set_tooltip('Set memo for selected frames')", "= d self.w.rpt_tbl.set_tree(self.rpt_dict) except Exception as e: self.logger.error(\"Error loading obslog: {}\".format(e), exc_info=True) def", "``ObsLog`` is a global plugin. Only one instance can be opened. **Usage** ***Saving", "xlsx: MS Excel file format The file is rewritten out every time a", "combobox to pick the right extension: * csv: * xlsx: MS Excel file", "row['FrameID'] d = OrderedDict([(kwd, row.get(col, '')) for col, kwd in self.rpt_columns]) self.rpt_dict[frameid] =", "file is rewritten out every time a new entry is added to the", "self.gui_up: return self.w.rpt_tbl.set_tree(self.rpt_dict) obslog_name = self.w.obslog_name.get_text().strip() if len(obslog_name) > 0: obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(),", "filename. The format of the file saved will depend on the file extension", "b.type.insert_alpha(\"xlsx\") b.type.set_tooltip(\"Format for saving/loading ObsLog\") b.type.add_callback('activated', self.set_obslog_format_cb) b.load.set_tooltip(\"Load a saved ObsLog\") b.load.add_callback('activated', self.load_obslog_cb)", "self.w.obslog_name.get_text().strip() name, old_ext = os.path.splitext(obslog_name) self.w.obslog_name.set_text(name + '.' + ext) self.write_obslog_cb(None) def close(self):", "***Adding a memo to one or more log entries*** Write a memo in", "self.w.memo.get_text().strip() res = self.get_selected() if len(res) == 0: self.fv.show_error(\"No frames selected for memo!\")", "None) if obs_log is None: obs_log = '' b.obslog_name.set_text(obs_log) b.obslog_name.set_tooltip('File name for observation", "the table columns = [(\"Obs Mod\", 'OBS-MOD'), (\"Datatype\", 'DATA-TYP'), (\"FrameID\", 'FRAMEID'), (\"Object\", 'OBJECT'),", "= True break if not accepted: return header = image.get_header() # add image", "press the \"Add Memo\" button. Multiple selection follows the usual rules about holding", "imname is None: return # only accepted list of frames accepted = False", "tv.add_callback('activated', self.dblclick_cb) tv.add_callback('selected', self.select_cb) self.rpt_columns = self.settings.get('report_columns') tv.setup_table(self.rpt_columns, 1, 'FRAMEID') captions = ((\"Memo:\",", "one or more frames to add the memo to and press the \"Add", "b = Widgets.build_info(captions, orientation='vertical') self.w.update(b) vbox.add_widget(w, stretch=0) b.memo.set_tooltip('Set memo for selected frames') b.add_memo.add_callback('activated',", "self.w.rpt_tbl.set_tree(self.rpt_dict) def set_obslog_format_cb(self, w, idx): ext = w.get_text() obslog_name = self.w.obslog_name.get_text().strip() name, old_ext", "\"Name:\", 'label', \"obslog_name\", 'entryset', \"Type\", 'combobox', \"Load\", 'button'), ) w, b = Widgets.build_info(captions,", "{}\".format(filepath)) col_hdr = [colname for colname, key in self.rpt_columns] rows = [list(d.values()) for", "\" \"'openpyxl' to use this feature\") return try: self.logger.info(\"loading obslog: {}\".format(filepath)) col_hdr =", "b.obslog_name.set_tooltip('File name for observation log') b.obslog_name.add_callback('activated', self.write_obslog_cb) b.obslog_dir.set_text(\"/tmp\") b.obslog_dir.set_tooltip('Folder path for observation log')", "channel = self.fv.get_channel(chname) self.fv.change_channel(chname) channel.switch_name(imname) def select_cb(self, widget, d): res = self.get_selected() if", "self.write_obslog(obslog_path) def load_obslog_cb(self, w): obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), self.w.obslog_name.get_text().strip()) self.load_obslog(obslog_path) def get_selected(self): res_dict =", "a saved ObsLog\") b.load.add_callback('activated', self.load_obslog_cb) btns = Widgets.HBox() btns.set_border_width(4) btns.set_spacing(4) btn = Widgets.Button(\"Close\")", "!= chname: channel = self.fv.get_channel(chname) self.fv.change_channel(chname) channel.switch_name(imname) def select_cb(self, widget, d): res =", "is rewritten out every time a new entry is added to the log", "return try: import pandas as pd except ImportError: self.fv.show_error(\"Please install 'pandas' and \"", "chname: channel = self.fv.get_channel(chname) self.fv.change_channel(chname) channel.switch_name(imname) def select_cb(self, widget, d): res = self.get_selected()", "'G_MEMO'), ] prefs = self.fv.get_preferences() self.settings = prefs.create_category('plugin_ObsLog') self.settings.add_defaults(sortable=True, color_alternate_rows=True, #max_rows_for_col_resize=5000, report_columns=columns, cache_normalized_images=True)", "None: obs_log = '' b.obslog_name.set_text(obs_log) b.obslog_name.set_tooltip('File name for observation log') b.obslog_name.add_callback('activated', self.write_obslog_cb) b.obslog_dir.set_text(\"/tmp\")", "None) if imname is None: return # only accepted list of frames accepted", "accepted list of frames accepted = False for prefix in self.file_prefixes: if imname.startswith(prefix):", "container): vbox = Widgets.VBox() vbox.set_border_width(1) vbox.set_spacing(1) tv = Widgets.TreeView(sortable=self.settings.get('sortable'), use_alt_row_color=self.settings.get('color_alternate_rows'), selection='multiple') self.w.rpt_tbl =", "self.logger.info(\"loading obslog: {}\".format(filepath)) col_hdr = [colname for colname, key in self.rpt_columns] if filepath.endswith('.csv'):", "except Exception as e: self.logger.error(\"Failed to process image: {}\".format(e), exc_info=True) def update_obslog(self): if", "file LICENSE.txt for details. \"\"\"Observation Log plugin. **Plugin Type: Global** ``ObsLog`` is a", "btns.set_spacing(4) btn = Widgets.Button(\"Close\") btn.add_callback('activated', lambda w: self.close()) btn.set_enabled(False) btns.add_widget(btn) btn = Widgets.Button(\"Help\")", "* csv: * xlsx: MS Excel file format The file is rewritten out", "'entryset', \"Type\", 'combobox', \"Load\", 'button'), ) w, b = Widgets.build_info(captions, orientation='vertical') self.w.update(b) vbox.add_widget(w,", "d): res = self.get_selected() if len(res) == 0: self.w.add_memo.set_enabled(False) else: self.w.add_memo.set_enabled(True) def add_memo_cb(self,", "add the memo to and press the \"Add Memo\" button. Multiple selection follows", "replace some kwds as needed in the table d = self.replace_kwds(header.asdict()) # Hack", "was double-clicked in the obslog\"\"\" frameid = list(d.keys())[0] info = d[frameid] self.view_image(frameid, info)", "data.\"\"\" pass def incoming_data_cb(self, fv, chname, image, info): if chname != self.chname: return", "writing obslog: {}\".format(e), exc_info=True) def load_obslog(self, filepath): try: import pandas as pd except", "chname, header, image): \"\"\"Override this method to do something special with the data.\"\"\"", "and/or SHIFT keys. ***Displaying an image*** Double-click on a log entry. \"\"\" import", "self.logger.error(\"Failed to process image: {}\".format(e), exc_info=True) def update_obslog(self): if not self.gui_up: return self.w.rpt_tbl.set_tree(self.rpt_dict)", "opened. **Usage** ***Saving the log to a file*** Put in values for the", "log') b.obslog_dir.add_callback('activated', self.write_obslog_cb) b.type.insert_alpha(\"csv\") b.type.insert_alpha(\"xlsx\") b.type.set_tooltip(\"Format for saving/loading ObsLog\") b.type.add_callback('activated', self.set_obslog_format_cb) b.load.set_tooltip(\"Load a", "df = pd.read_excel(filepath, header=0, #names=col_hdr, index_col=None) self.rpt_dict = OrderedDict({}) res = df.to_dict('index') for", "and \" \"'openpyxl' to use this feature\") return try: self.logger.info(\"writing obslog: {}\".format(filepath)) col_hdr", "filepath.endswith('.csv'): df.to_csv(filepath, index=False, header=True) else: df.to_excel(filepath, index=False, header=True) except Exception as e: self.logger.error(\"Error", "in the table d = self.replace_kwds(header.asdict()) # Hack to insure that we get", "w, b = Widgets.build_info(captions, orientation='vertical') self.w.update(b) vbox.add_widget(w, stretch=0) obs_log = self.settings.get('obslog_name', None) if", "Widgets.build_info(captions, orientation='vertical') self.w.update(b) vbox.add_widget(w, stretch=0) obs_log = self.settings.get('obslog_name', None) if obs_log is None:", "for saving/loading ObsLog\") b.type.add_callback('activated', self.set_obslog_format_cb) b.load.set_tooltip(\"Load a saved ObsLog\") b.load.add_callback('activated', self.load_obslog_cb) btns =", "under a BSD license. # Please see the file LICENSE.txt for details. \"\"\"Observation", "{}\".format(e), exc_info=True) def write_obslog_cb(self, w): obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), self.w.obslog_name.get_text().strip()) self.write_obslog(obslog_path) def load_obslog_cb(self, w):", "'FRAMEID') captions = ((\"Memo:\", 'label', \"memo\", 'entry', 'Add Memo', 'button'), ) w, b", "= [list(d.values()) for d in self.rpt_dict.values()] df = pd.DataFrame(rows, columns=col_hdr) if filepath.endswith('.csv'): df.to_csv(filepath,", "image, info): if chname != self.chname: return imname = image.get('name', None) if imname", "stretch=0) container.add_widget(vbox, stretch=1) self.gui_up = True def replace_kwds(self, header): \"\"\"Subclass this method to", "only accepted list of frames accepted = False for prefix in self.file_prefixes: if", "depend on the file extension of the filename; use the type selector combobox", "# add image to obslog self.fv.gui_do(self.add_to_obslog, header, image) try: self.process_image(chname, header, image) except", "header=0, #names=col_hdr, index_col=None) else: df = pd.read_excel(filepath, header=0, #names=col_hdr, index_col=None) self.rpt_dict = OrderedDict({})", "not accepted: return header = image.get_header() # add image to obslog self.fv.gui_do(self.add_to_obslog, header,", "b.type.insert_alpha(\"csv\") b.type.insert_alpha(\"xlsx\") b.type.set_tooltip(\"Format for saving/loading ObsLog\") b.type.add_callback('activated', self.set_obslog_format_cb) b.load.set_tooltip(\"Load a saved ObsLog\") b.load.add_callback('activated',", "(\"RA\", 'RA'), (\"DEC\", 'DEC'), (\"EQUINOX\", 'EQUINOX'), (\"Memo\", 'G_MEMO'), ] prefs = self.fv.get_preferences() self.settings", "Global** ``ObsLog`` is a global plugin. Only one instance can be opened. **Usage**", "to use this feature\") return try: self.logger.info(\"loading obslog: {}\".format(filepath)) col_hdr = [colname for", "self.w.update(b) vbox.add_widget(w, stretch=0) obs_log = self.settings.get('obslog_name', None) if obs_log is None: obs_log =", "do munge the data for special reports.\"\"\" d = dict() d.update(header) return d", "d self.update_obslog() def stop(self): self.gui_up = False def process_image(self, chname, header, image): \"\"\"Override", "= '' b.obslog_name.set_text(obs_log) b.obslog_name.set_tooltip('File name for observation log') b.obslog_name.add_callback('activated', self.write_obslog_cb) b.obslog_dir.set_text(\"/tmp\") b.obslog_dir.set_tooltip('Folder path", "= prefs.create_category('plugin_ObsLog') self.settings.add_defaults(sortable=True, color_alternate_rows=True, #max_rows_for_col_resize=5000, report_columns=columns, cache_normalized_images=True) self.settings.load(onError='silent') self.rpt_dict = OrderedDict({}) self.rpt_columns =", "self.logger.error(\"Error loading obslog: {}\".format(e), exc_info=True) def write_obslog_cb(self, w): obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), self.w.obslog_name.get_text().strip()) self.write_obslog(obslog_path)", "accepted = False for prefix in self.file_prefixes: if imname.startswith(prefix): accepted = True break", "= Widgets.TreeView(sortable=self.settings.get('sortable'), use_alt_row_color=self.settings.get('color_alternate_rows'), selection='multiple') self.w.rpt_tbl = tv vbox.add_widget(tv, stretch=1) tv.add_callback('activated', self.dblclick_cb) tv.add_callback('selected', self.select_cb)", "for d in self.rpt_dict.values()] df = pd.DataFrame(rows, columns=col_hdr) if filepath.endswith('.csv'): df.to_csv(filepath, index=False, header=True)", "is added to the log ***Adding a memo to one or more log", "image) except Exception as e: self.logger.error(\"Failed to process image: {}\".format(e), exc_info=True) def update_obslog(self):", "b = Widgets.build_info(captions, orientation='vertical') self.w.update(b) vbox.add_widget(w, stretch=0) obs_log = self.settings.get('obslog_name', None) if obs_log", "if len(self.rpt_dict) == 0: return try: import pandas as pd except ImportError: self.fv.show_error(\"Please", "if channel.name != chname: channel = self.fv.get_channel(chname) self.fv.change_channel(chname) channel.switch_name(imname) def select_cb(self, widget, d):", "and \" \"'openpyxl' to use this feature\") return try: self.logger.info(\"loading obslog: {}\".format(filepath)) col_hdr", "prefs.create_category('plugin_ObsLog') self.settings.add_defaults(sortable=True, color_alternate_rows=True, #max_rows_for_col_resize=5000, report_columns=columns, cache_normalized_images=True) self.settings.load(onError='silent') self.rpt_dict = OrderedDict({}) self.rpt_columns = []", "d = self.replace_kwds(header.asdict()) # Hack to insure that we get the columns in", "\"'openpyxl' to use this feature\") return try: self.logger.info(\"writing obslog: {}\".format(filepath)) col_hdr = [colname", "= pd.read_excel(filepath, header=0, #names=col_hdr, index_col=None) self.rpt_dict = OrderedDict({}) res = df.to_dict('index') for row", "dict() d.update(header) return d def add_to_obslog(self, header, image): frameid = header['FRAMEID'] # replace", "len(res) == 0: self.fv.show_error(\"No frames selected for memo!\") return for key in res.keys():", "add image to obslog self.fv.gui_do(self.add_to_obslog, header, image) try: self.process_image(chname, header, image) except Exception", "a memo in the memo box. Select one or more frames to add", "if not self.gui_up: return self.w.rpt_tbl.set_tree(self.rpt_dict) obslog_name = self.w.obslog_name.get_text().strip() if len(obslog_name) > 0: obslog_path", "= d[frameid] self.view_image(frameid, info) def view_image(self, imname, info): chname = self.chname channel =", "fv, chname, image, info): if chname != self.chname: return imname = image.get('name', None)", "vbox.add_widget(tv, stretch=1) tv.add_callback('activated', self.dblclick_cb) tv.add_callback('selected', self.select_cb) self.rpt_columns = self.settings.get('report_columns') tv.setup_table(self.rpt_columns, 1, 'FRAMEID') captions", "self.w.obslog_name.get_text().strip()) self.load_obslog(obslog_path) def get_selected(self): res_dict = self.w.rpt_tbl.get_selected() return res_dict def dblclick_cb(self, widget, d):", "1, 'FRAMEID') captions = ((\"Memo:\", 'label', \"memo\", 'entry', 'Add Memo', 'button'), ) w,", "= self.get_selected() if len(res) == 0: self.fv.show_error(\"No frames selected for memo!\") return for", "selected for memo!\") return for key in res.keys(): self.rpt_dict[key]['G_MEMO'] = memo_txt self.w.rpt_tbl.set_tree(self.rpt_dict) def", "log') b.obslog_name.add_callback('activated', self.write_obslog_cb) b.obslog_dir.set_text(\"/tmp\") b.obslog_dir.set_tooltip('Folder path for observation log') b.obslog_dir.add_callback('activated', self.write_obslog_cb) b.type.insert_alpha(\"csv\") b.type.insert_alpha(\"xlsx\")", "ext = w.get_text() obslog_name = self.w.obslog_name.get_text().strip() name, old_ext = os.path.splitext(obslog_name) self.w.obslog_name.set_text(name + '.'", "values for the Observation Log folder and filename. The format of the file", "self.rpt_columns = [] self.fv.add_callback('add-image', self.incoming_data_cb) self.gui_up = False def build_gui(self, container): vbox =", "process image: {}\".format(e), exc_info=True) def update_obslog(self): if not self.gui_up: return self.w.rpt_tbl.set_tree(self.rpt_dict) obslog_name =", "this feature\") return try: self.logger.info(\"loading obslog: {}\".format(filepath)) col_hdr = [colname for colname, key", "self.view_image(frameid, info) def view_image(self, imname, info): chname = self.chname channel = self.fv.get_current_channel() if", "widget): memo_txt = self.w.memo.get_text().strip() res = self.get_selected() if len(res) == 0: self.fv.show_error(\"No frames", "self.rpt_columns = self.settings.get('report_columns') tv.setup_table(self.rpt_columns, 1, 'FRAMEID') captions = ((\"Memo:\", 'label', \"memo\", 'entry', 'Add", "if len(obslog_name) > 0: obslog_path = os.path.join(self.w.obslog_dir.get_text().strip(), obslog_name) self.write_obslog(obslog_path) def write_obslog(self, filepath): if", "[] self.fv.add_callback('add-image', self.incoming_data_cb) self.gui_up = False def build_gui(self, container): vbox = Widgets.VBox() vbox.set_border_width(1)", "# only accepted list of frames accepted = False for prefix in self.file_prefixes:", "self.fv.get_channel(chname) self.fv.change_channel(chname) channel.switch_name(imname) def select_cb(self, widget, d): res = self.get_selected() if len(res) ==", "self.select_cb) self.rpt_columns = self.settings.get('report_columns') tv.setup_table(self.rpt_columns, 1, 'FRAMEID') captions = ((\"Memo:\", 'label', \"memo\", 'entry',", "* xlsx: MS Excel file format The file is rewritten out every time", "plugin. Only one instance can be opened. **Usage** ***Saving the log to a", "follows the usual rules about holding down CTRL and/or SHIFT keys. ***Displaying an" ]
[ "glosses_feats = fh_glosses[\"features\"][:] glosses_feats = torch.tensor(glosses_feats) if torch.cuda.is_available(): glosses_feats = glosses_feats.cuda() # load", "help=\"Retrieve topk nodes for each input sentence.\") p.add_argument('--batch_size', type=int, default=1000) p.add_argument('--visualsem_path', type=str, default=visualsem_path,", "= \"%s/dataset/images/\"%visualsem_path glosses_sentence_bert_path = \"%s/dataset/gloss_files/glosses.en.txt.sentencebert.h5\"%visualsem_path glosses_bnids_path = \"%s/dataset/gloss_files/glosses.en.txt.bnids\"%visualsem_path os.makedirs(\"%s/dataset/gloss_files/\"%visualsem_path, exist_ok=True) p = argparse.ArgumentParser()", "rank_predicted]] if not bnid_pred in bnids_predicted: bnids_predicted.append((bnid_pred,bnid_pred_score)) if len(bnids_predicted)>=topk: break # write top-k", "in the validation set. (See paper for reference)\"\"\") p.add_argument('--input_test', action='store_true', help=\"\"\"Perform retrieval for", "for the glosses in the test set. (See paper for reference)\"\"\") args =", "Output file to write SBERT features for query. batch_size(int): Batch size for Sentence", "visualsem_images_path = \"%s/dataset/images/\"%visualsem_path glosses_sentence_bert_path = \"%s/dataset/gloss_files/glosses.en.txt.sentencebert.h5\"%visualsem_path glosses_bnids_path = \"%s/dataset/gloss_files/glosses.en.txt.bnids\"%visualsem_path os.makedirs(\"%s/dataset/gloss_files/\"%visualsem_path, exist_ok=True) p =", "Sentences to be used for retrieval. \"\"\" n_lines = len(all_sentences) model_name = \"paraphrase-multilingual-mpnet-base-v2\"", "graph.\") p.add_argument('--visualsem_nodes_path', type=str, default=visualsem_nodes_path, help=\"Path to file containing VisualSem nodes.\") p.add_argument('--visualsem_images_path', type=str, default=visualsem_images_path,", "fh_glosses[\"split_idxs\"][:] train_idxs = (glosses_splits==0).nonzero()[0] valid_idxs = (glosses_splits==1).nonzero()[0] test_idxs = (glosses_splits==2).nonzero()[0] # load gloss", "bnids_predicted = [] for rank_predicted in range(topk*10): bnid_pred = glosses_bnids[ ranks[rank_idx,rank_predicted] ] bnid_pred_score", "model_name = \"paraphrase-multilingual-mpnet-base-v2\" model = SentenceTransformer(model_name) with open(out_fname, 'w', encoding='utf8') as fh_out: ranks_predicted", "from_idx+batch_size <= n_lines else n_lines batch_sentences = all_sentences[ from_idx: to_idx ] emb_sentences =", "in tqdm.trange(0,n_lines,batch_size): to_idx = from_idx+batch_size if from_idx+batch_size <= n_lines else n_lines batch_sentences =", "h5py.File(out_fname, 'w') as fh_out: fh_out.create_dataset(\"features\", shape_features, dtype='float32', chunks=(1,768), maxshape=(None, 768), compression=\"gzip\") for from_idx", "import h5py from sentence_transformers import SentenceTransformer, util import numpy import tqdm from itertools", "`extract_glosses_visualsem.py`).\"\"\") p.add_argument('--input_valid', action='store_true', help=\"\"\"Perform retrieval for the glosses in the validation set. (See", "import torch import sys import os import json from collections import defaultdict import", "Number of nodes to retrieve for each input sentence. \"\"\" if os.path.isfile(out_fname): raise", "the glosses in the validation set. (See paper for reference)\"\"\") p.add_argument('--input_test', action='store_true', help=\"\"\"Perform", "for Sentence BERT. all_input_sentences(list[str]): All input sentences loaded from `input_file`. glosses_bnids(list[str]): All gloss", "sbert_out_fname = input_file+\".sentencebert.h5\" if os.path.isfile( sbert_out_fname ): raise Exception(\"File already exists: '%s'. Please", "bnids_predicted.append((bnid_pred,bnid_pred_score)) if len(bnids_predicted)>=topk: break # write top-k predicted BNids for iii, (bnid, score)", "in the test set. (See paper for reference)\"\"\") args = p.parse_args() # load", "args.input_files: print(\"Processing input file: %s ...\"%input_file) sbert_out_fname = input_file+\".sentencebert.h5\" if os.path.isfile( sbert_out_fname ):", "VisualSem nodes.\") p.add_argument('--visualsem_images_path', type=str, default=visualsem_images_path, help=\"Path to directory containing VisualSem images.\") p.add_argument('--glosses_sentence_bert_path', type=str,", "top-k predicted BNids for iii, (bnid, score) in enumerate(bnids_predicted[:topk]): fh_out.write(bnid+\"\\t\"+\"%.4f\"%score) if iii <", "to_idx = from_idx+batch_size if from_idx+batch_size <= n_lines else n_lines batch_sentences = all_sentences[ from_idx:", "p.parse_args() # load all nodes in VisualSem all_bnids = load_visualsem_bnids(args.visualsem_nodes_path, args.visualsem_images_path) gloss_bnids =", "`glosses_feats`. glosses_feats(numpy.array): Numpy array with VisualSem gloss features computed with Sentence BERT. topk(int):", "gloss_bnids, glosses_feats, args.topk) # remove temporary SBERT index created for input file(s) os.remove(", "Numpy array with VisualSem gloss features computed with Sentence BERT. topk(int): Number of", "from collections import defaultdict import h5py from sentence_transformers import SentenceTransformer, util import numpy", "= load_sentences( input_file ) encode_query(sbert_out_fname, args.batch_size, input_sentences) out_fname = input_file+\".bnids\" retrieve_nodes_given_sentences(out_fname, args.batch_size, input_sentences,", "util.pytorch_cos_sim(queries_embs, glosses_feats) scores = scores.cpu().numpy() ranks = numpy.argsort(scores) # sort scores by cosine", "if from_idx+batch_size <= n_lines else n_lines batch_sentences = all_sentences[ from_idx: to_idx ] emb_sentences", "else n_lines batch_sentences = all_sentences[ from_idx: to_idx ] emb_sentences = model.encode(batch_sentences, convert_to_tensor=True) #test_queries(emb_sentences,", "< topk-1: fh_out.write(\"\\t\") else: # iii == topk-1 fh_out.write(\"\\n\") def encode_query(out_fname, batch_size, all_sentences):", "with open(out_fname, 'w', encoding='utf8') as fh_out: ranks_predicted = [] for idxs_ in grouper(batch_size,", "fh_glosses[\"language_idxs\"][:] for input_file in args.input_files: print(\"Processing input file: %s ...\"%input_file) sbert_out_fname = input_file+\".sentencebert.h5\"", "for rank_idx in range(len(idxs[:ranks.shape[0]])): bnids_predicted = [] for rank_predicted in range(topk*10): bnid_pred =", "size for Sentence BERT. all_sentences(list[str]): Sentences to be used for retrieval. \"\"\" n_lines", "sentence. \"\"\" if os.path.isfile(out_fname): raise Exception(\"File already exists: '%s'. Please remove it manually", "containing VisualSem nodes.\") p.add_argument('--visualsem_images_path', type=str, default=visualsem_images_path, help=\"Path to directory containing VisualSem images.\") p.add_argument('--glosses_sentence_bert_path',", "model) fh_out[\"features\"][from_idx:to_idx] = emb_sentences.cpu().numpy() if __name__==\"__main__\": visualsem_path = os.path.dirname(os.path.realpath(__file__)) visualsem_nodes_path = \"%s/dataset/nodes.v2.json\"%visualsem_path visualsem_images_path", "to avoid tampering.\"%out_fname) n_examples = len(all_input_sentences) print(\"Number of input examples to extract BNIDs", "similarity (low to high) ranks = ranks[:,::-1] # sort by cosine similarity (high", "os import json from collections import defaultdict import h5py from sentence_transformers import SentenceTransformer,", "Please remove it manually to avoid tampering.\"%out_fname) n_examples = len(all_input_sentences) print(\"Number of input", "len(all_sentences) model_name = \"paraphrase-multilingual-mpnet-base-v2\" model = SentenceTransformer(model_name) shape_features = (n_lines, 768) with h5py.File(out_fname,", "scores by cosine similarity (low to high) ranks = ranks[:,::-1] # sort by", "rank_predicted in range(topk*10): bnid_pred = glosses_bnids[ ranks[rank_idx,rank_predicted] ] bnid_pred_score = scores[rank_idx, ranks[rank_idx, rank_predicted]]", "\"\"\" out_fname(str): Output file to write retrieved node ids to. batch_size(int): Batch size", "write retrieved node ids to. batch_size(int): Batch size for Sentence BERT. all_input_sentences(list[str]): All", "with h5py.File(out_fname, 'w') as fh_out: fh_out.create_dataset(\"features\", shape_features, dtype='float32', chunks=(1,768), maxshape=(None, 768), compression=\"gzip\") for", "args.topk) # remove temporary SBERT index created for input file(s) os.remove( sbert_out_fname )", "load_bnids, load_visualsem_bnids def retrieve_nodes_given_sentences(out_fname, batch_size, all_input_sentences, glosses_bnids, glosses_feats, topk): \"\"\" out_fname(str): Output file", "all_input_sentences[i] ) queries_embs = model.encode(queries, convert_to_tensor=True) if torch.cuda.is_available(): queries_embs = queries_embs.cuda() scores =", "gloss features computed with Sentence BERT. topk(int): Number of nodes to retrieve for", "if torch.cuda.is_available(): glosses_feats = glosses_feats.cuda() # load train/valid/test gloss splits glosses_splits = fh_glosses[\"split_idxs\"][:]", "a detokenized sentence.\"\"\") p.add_argument('--topk', type=int, default=1, help=\"Retrieve topk nodes for each input sentence.\")", "range(topk*10): bnid_pred = glosses_bnids[ ranks[rank_idx,rank_predicted] ] bnid_pred_score = scores[rank_idx, ranks[rank_idx, rank_predicted]] if not", "features computed with Sentence BERT. topk(int): Number of nodes to retrieve for each", "help=\"Path to directory containing VisualSem images.\") p.add_argument('--glosses_sentence_bert_path', type=str, default=glosses_sentence_bert_path, help=\"\"\"HDF5 file containing glosses", "glosses_feats = glosses_feats.cuda() # load train/valid/test gloss splits glosses_splits = fh_glosses[\"split_idxs\"][:] train_idxs =", "= [] for i in idxs_: if not i is None: idxs.append(i) queries.append(", "'w') as fh_out: fh_out.create_dataset(\"features\", shape_features, dtype='float32', chunks=(1,768), maxshape=(None, 768), compression=\"gzip\") for from_idx in", "# load all nodes in VisualSem all_bnids = load_visualsem_bnids(args.visualsem_nodes_path, args.visualsem_images_path) gloss_bnids = load_bnids(", "to file containing VisualSem nodes.\") p.add_argument('--visualsem_images_path', type=str, default=visualsem_images_path, help=\"Path to directory containing VisualSem", "default=glosses_sentence_bert_path, help=\"\"\"HDF5 file containing glosses index computed with Sentence BERT (computed with `extract_glosses_visualsem.py`).\"\"\")", "topk-1: fh_out.write(\"\\t\") else: # iii == topk-1 fh_out.write(\"\\n\") def encode_query(out_fname, batch_size, all_sentences): \"\"\"", "import SentenceTransformer, util import numpy import tqdm from itertools import zip_longest from utils", "input_file+\".bnids\" retrieve_nodes_given_sentences(out_fname, args.batch_size, input_sentences, gloss_bnids, glosses_feats, args.topk) # remove temporary SBERT index created", "retrieve_nodes_given_sentences(out_fname, args.batch_size, input_sentences, gloss_bnids, glosses_feats, args.topk) # remove temporary SBERT index created for", "gloss language splits language_splits = fh_glosses[\"language_idxs\"][:] for input_file in args.input_files: print(\"Processing input file:", "n_lines batch_sentences = all_sentences[ from_idx: to_idx ] emb_sentences = model.encode(batch_sentences, convert_to_tensor=True) #test_queries(emb_sentences, all_sentences,", "if __name__==\"__main__\": visualsem_path = os.path.dirname(os.path.realpath(__file__)) visualsem_nodes_path = \"%s/dataset/nodes.v2.json\"%visualsem_path visualsem_images_path = \"%s/dataset/images/\"%visualsem_path glosses_sentence_bert_path =", "queries_embs = queries_embs.cuda() scores = util.pytorch_cos_sim(queries_embs, glosses_feats) scores = scores.cpu().numpy() ranks = numpy.argsort(scores)", "type=int, default=1000) p.add_argument('--visualsem_path', type=str, default=visualsem_path, help=\"Path to directory containing VisualSem knowledge graph.\") p.add_argument('--visualsem_nodes_path',", "it manually to avoid tampering.\"%sbert_out_fname) input_sentences = load_sentences( input_file ) encode_query(sbert_out_fname, args.batch_size, input_sentences)", "input_file ) encode_query(sbert_out_fname, args.batch_size, input_sentences) out_fname = input_file+\".bnids\" retrieve_nodes_given_sentences(out_fname, args.batch_size, input_sentences, gloss_bnids, glosses_feats,", "torch.tensor(glosses_feats) if torch.cuda.is_available(): glosses_feats = glosses_feats.cuda() # load train/valid/test gloss splits glosses_splits =", "print(\"Processing input file: %s ...\"%input_file) sbert_out_fname = input_file+\".sentencebert.h5\" if os.path.isfile( sbert_out_fname ): raise", "= glosses_bnids[ ranks[rank_idx,rank_predicted] ] bnid_pred_score = scores[rank_idx, ranks[rank_idx, rank_predicted]] if not bnid_pred in", "= scores.cpu().numpy() ranks = numpy.argsort(scores) # sort scores by cosine similarity (low to", "ranks[:,::-1] # sort by cosine similarity (high to low) for rank_idx in range(len(idxs[:ranks.shape[0]])):", "by cosine similarity (low to high) ranks = ranks[:,::-1] # sort by cosine", "scores[rank_idx, ranks[rank_idx, rank_predicted]] if not bnid_pred in bnids_predicted: bnids_predicted.append((bnid_pred,bnid_pred_score)) if len(bnids_predicted)>=topk: break #", "topk): \"\"\" out_fname(str): Output file to write retrieved node ids to. batch_size(int): Batch", "to high) ranks = ranks[:,::-1] # sort by cosine similarity (high to low)", "maxshape=(None, 768), compression=\"gzip\") for from_idx in tqdm.trange(0,n_lines,batch_size): to_idx = from_idx+batch_size if from_idx+batch_size <=", "gloss_bnids = load_bnids( args.glosses_bnids_path ) gloss_bnids = numpy.array(gloss_bnids, dtype='object') with h5py.File(args.glosses_sentence_bert_path, 'r') as", "SBERT features for query. batch_size(int): Batch size for Sentence BERT. all_sentences(list[str]): Sentences to", "high) ranks = ranks[:,::-1] # sort by cosine similarity (high to low) for", "glosses_splits = fh_glosses[\"split_idxs\"][:] train_idxs = (glosses_splits==0).nonzero()[0] valid_idxs = (glosses_splits==1).nonzero()[0] test_idxs = (glosses_splits==2).nonzero()[0] #", "remove it manually to avoid tampering.\"%out_fname) n_examples = len(all_input_sentences) print(\"Number of input examples", "shape_features = (n_lines, 768) with h5py.File(out_fname, 'w') as fh_out: fh_out.create_dataset(\"features\", shape_features, dtype='float32', chunks=(1,768),", "load_visualsem_bnids def retrieve_nodes_given_sentences(out_fname, batch_size, all_input_sentences, glosses_bnids, glosses_feats, topk): \"\"\" out_fname(str): Output file to", "default=1000) p.add_argument('--visualsem_path', type=str, default=visualsem_path, help=\"Path to directory containing VisualSem knowledge graph.\") p.add_argument('--visualsem_nodes_path', type=str,", "\"\"\" out_fname(str): Output file to write SBERT features for query. batch_size(int): Batch size", "all nodes in VisualSem all_bnids = load_visualsem_bnids(args.visualsem_nodes_path, args.visualsem_images_path) gloss_bnids = load_bnids( args.glosses_bnids_path )", "batch_size(int): Batch size for Sentence BERT. all_input_sentences(list[str]): All input sentences loaded from `input_file`.", "= \"paraphrase-multilingual-mpnet-base-v2\" model = SentenceTransformer(model_name) with open(out_fname, 'w', encoding='utf8') as fh_out: ranks_predicted =", "import argparse import torch import sys import os import json from collections import", "VisualSem images.\") p.add_argument('--glosses_sentence_bert_path', type=str, default=glosses_sentence_bert_path, help=\"\"\"HDF5 file containing glosses index computed with Sentence", "nodes to retrieve for each input sentence. \"\"\" if os.path.isfile(out_fname): raise Exception(\"File already", "temporary SBERT index created for input file(s) os.remove( sbert_out_fname ) print(\"Retrieved glosses: %s\"%out_fname)", "bnid_pred_score = scores[rank_idx, ranks[rank_idx, rank_predicted]] if not bnid_pred in bnids_predicted: bnids_predicted.append((bnid_pred,bnid_pred_score)) if len(bnids_predicted)>=topk:", "n_lines else n_lines batch_sentences = all_sentences[ from_idx: to_idx ] emb_sentences = model.encode(batch_sentences, convert_to_tensor=True)", "Exception(\"File already exists: '%s'. Please remove it manually to avoid tampering.\"%sbert_out_fname) input_sentences =", "load_sentences( input_file ) encode_query(sbert_out_fname, args.batch_size, input_sentences) out_fname = input_file+\".bnids\" retrieve_nodes_given_sentences(out_fname, args.batch_size, input_sentences, gloss_bnids,", "help=\"\"\"Perform retrieval for the glosses in the test set. (See paper for reference)\"\"\")", "visualsem_nodes_path = \"%s/dataset/nodes.v2.json\"%visualsem_path visualsem_images_path = \"%s/dataset/images/\"%visualsem_path glosses_sentence_bert_path = \"%s/dataset/gloss_files/glosses.en.txt.sentencebert.h5\"%visualsem_path glosses_bnids_path = \"%s/dataset/gloss_files/glosses.en.txt.bnids\"%visualsem_path os.makedirs(\"%s/dataset/gloss_files/\"%visualsem_path,", "type=str, default=glosses_bnids_path, help=\"\"\"Text file containing glosses BabelNet ids, one per line (computed with", "score) in enumerate(bnids_predicted[:topk]): fh_out.write(bnid+\"\\t\"+\"%.4f\"%score) if iii < topk-1: fh_out.write(\"\\t\") else: # iii ==", "Output file to write retrieved node ids to. batch_size(int): Batch size for Sentence", "batch_size(int): Batch size for Sentence BERT. all_sentences(list[str]): Sentences to be used for retrieval.", "dtype='float32', chunks=(1,768), maxshape=(None, 768), compression=\"gzip\") for from_idx in tqdm.trange(0,n_lines,batch_size): to_idx = from_idx+batch_size if", "glosses_bnids[ ranks[rank_idx,rank_predicted] ] bnid_pred_score = scores[rank_idx, ranks[rank_idx, rank_predicted]] if not bnid_pred in bnids_predicted:", "input_file+\".sentencebert.h5\" if os.path.isfile( sbert_out_fname ): raise Exception(\"File already exists: '%s'. Please remove it", "grouper, load_sentences, load_bnids, load_visualsem_bnids def retrieve_nodes_given_sentences(out_fname, batch_size, all_input_sentences, glosses_bnids, glosses_feats, topk): \"\"\" out_fname(str):", "= \"%s/dataset/gloss_files/glosses.en.txt.sentencebert.h5\"%visualsem_path glosses_bnids_path = \"%s/dataset/gloss_files/glosses.en.txt.bnids\"%visualsem_path os.makedirs(\"%s/dataset/gloss_files/\"%visualsem_path, exist_ok=True) p = argparse.ArgumentParser() p.add_argument('--input_files', type=str, nargs=\"+\",", "def retrieve_nodes_given_sentences(out_fname, batch_size, all_input_sentences, glosses_bnids, glosses_feats, topk): \"\"\" out_fname(str): Output file to write", "for the glosses in the validation set. (See paper for reference)\"\"\") p.add_argument('--input_test', action='store_true',", "raise Exception(\"File already exists: '%s'. Please remove it manually to avoid tampering.\"%sbert_out_fname) input_sentences", "scores.cpu().numpy() ranks = numpy.argsort(scores) # sort scores by cosine similarity (low to high)", "fh_out: ranks_predicted = [] for idxs_ in grouper(batch_size, range(n_examples)): idxs = [] queries", "= SentenceTransformer(model_name) shape_features = (n_lines, 768) with h5py.File(out_fname, 'w') as fh_out: fh_out.create_dataset(\"features\", shape_features,", "emb_sentences = model.encode(batch_sentences, convert_to_tensor=True) #test_queries(emb_sentences, all_sentences, model) fh_out[\"features\"][from_idx:to_idx] = emb_sentences.cpu().numpy() if __name__==\"__main__\": visualsem_path", "size for Sentence BERT. all_input_sentences(list[str]): All input sentences loaded from `input_file`. glosses_bnids(list[str]): All", "glosses_feats) scores = scores.cpu().numpy() ranks = numpy.argsort(scores) # sort scores by cosine similarity", "scores = util.pytorch_cos_sim(queries_embs, glosses_feats) scores = scores.cpu().numpy() ranks = numpy.argsort(scores) # sort scores", "glosses_bnids_path = \"%s/dataset/gloss_files/glosses.en.txt.bnids\"%visualsem_path os.makedirs(\"%s/dataset/gloss_files/\"%visualsem_path, exist_ok=True) p = argparse.ArgumentParser() p.add_argument('--input_files', type=str, nargs=\"+\", default=[\"example_data/queries.txt\"], help=\"\"\"Input", "utils import grouper, load_sentences, load_bnids, load_visualsem_bnids def retrieve_nodes_given_sentences(out_fname, batch_size, all_input_sentences, glosses_bnids, glosses_feats, topk):", "type=str, default=visualsem_path, help=\"Path to directory containing VisualSem knowledge graph.\") p.add_argument('--visualsem_nodes_path', type=str, default=visualsem_nodes_path, help=\"Path", "p.add_argument('--input_files', type=str, nargs=\"+\", default=[\"example_data/queries.txt\"], help=\"\"\"Input file(s) to use for retrieval. Each line in", "remove temporary SBERT index created for input file(s) os.remove( sbert_out_fname ) print(\"Retrieved glosses:", "dtype='object') with h5py.File(args.glosses_sentence_bert_path, 'r') as fh_glosses: glosses_feats = fh_glosses[\"features\"][:] glosses_feats = torch.tensor(glosses_feats) if", "raise Exception(\"File already exists: '%s'. Please remove it manually to avoid tampering.\"%out_fname) n_examples", "BERT (computed with `extract_glosses_visualsem.py`).\"\"\") p.add_argument('--glosses_bnids_path', type=str, default=glosses_bnids_path, help=\"\"\"Text file containing glosses BabelNet ids,", "for reference)\"\"\") p.add_argument('--input_test', action='store_true', help=\"\"\"Perform retrieval for the glosses in the test set.", "array with VisualSem gloss features computed with Sentence BERT. topk(int): Number of nodes", "n_examples) model_name = \"paraphrase-multilingual-mpnet-base-v2\" model = SentenceTransformer(model_name) with open(out_fname, 'w', encoding='utf8') as fh_out:", "help=\"\"\"HDF5 file containing glosses index computed with Sentence BERT (computed with `extract_glosses_visualsem.py`).\"\"\") p.add_argument('--glosses_bnids_path',", "retrieval for the glosses in the validation set. (See paper for reference)\"\"\") p.add_argument('--input_test',", "enumerate(bnids_predicted[:topk]): fh_out.write(bnid+\"\\t\"+\"%.4f\"%score) if iii < topk-1: fh_out.write(\"\\t\") else: # iii == topk-1 fh_out.write(\"\\n\")", "= \"%s/dataset/nodes.v2.json\"%visualsem_path visualsem_images_path = \"%s/dataset/images/\"%visualsem_path glosses_sentence_bert_path = \"%s/dataset/gloss_files/glosses.en.txt.sentencebert.h5\"%visualsem_path glosses_bnids_path = \"%s/dataset/gloss_files/glosses.en.txt.bnids\"%visualsem_path os.makedirs(\"%s/dataset/gloss_files/\"%visualsem_path, exist_ok=True)", "all_sentences(list[str]): Sentences to be used for retrieval. \"\"\" n_lines = len(all_sentences) model_name =", "tqdm.trange(0,n_lines,batch_size): to_idx = from_idx+batch_size if from_idx+batch_size <= n_lines else n_lines batch_sentences = all_sentences[", "help=\"Path to file containing VisualSem nodes.\") p.add_argument('--visualsem_images_path', type=str, default=visualsem_images_path, help=\"Path to directory containing", "= [] queries = [] for i in idxs_: if not i is", "= glosses_feats.cuda() # load train/valid/test gloss splits glosses_splits = fh_glosses[\"split_idxs\"][:] train_idxs = (glosses_splits==0).nonzero()[0]", "the test set. (See paper for reference)\"\"\") args = p.parse_args() # load all", "default=glosses_bnids_path, help=\"\"\"Text file containing glosses BabelNet ids, one per line (computed with `extract_glosses_visualsem.py`).\"\"\")", "# sort scores by cosine similarity (low to high) ranks = ranks[:,::-1] #", "out_fname(str): Output file to write SBERT features for query. batch_size(int): Batch size for", "p.add_argument('--input_test', action='store_true', help=\"\"\"Perform retrieval for the glosses in the test set. (See paper", "fh_glosses: glosses_feats = fh_glosses[\"features\"][:] glosses_feats = torch.tensor(glosses_feats) if torch.cuda.is_available(): glosses_feats = glosses_feats.cuda() #", "\"%s/dataset/gloss_files/glosses.en.txt.bnids\"%visualsem_path os.makedirs(\"%s/dataset/gloss_files/\"%visualsem_path, exist_ok=True) p = argparse.ArgumentParser() p.add_argument('--input_files', type=str, nargs=\"+\", default=[\"example_data/queries.txt\"], help=\"\"\"Input file(s) to", "p.add_argument('--input_valid', action='store_true', help=\"\"\"Perform retrieval for the glosses in the validation set. (See paper", "torch.cuda.is_available(): glosses_feats = glosses_feats.cuda() # load train/valid/test gloss splits glosses_splits = fh_glosses[\"split_idxs\"][:] train_idxs", "convert_to_tensor=True) #test_queries(emb_sentences, all_sentences, model) fh_out[\"features\"][from_idx:to_idx] = emb_sentences.cpu().numpy() if __name__==\"__main__\": visualsem_path = os.path.dirname(os.path.realpath(__file__)) visualsem_nodes_path", "retrieval for the glosses in the test set. (See paper for reference)\"\"\") args", "paper for reference)\"\"\") args = p.parse_args() # load all nodes in VisualSem all_bnids", "glosses_feats.cuda() # load train/valid/test gloss splits glosses_splits = fh_glosses[\"split_idxs\"][:] train_idxs = (glosses_splits==0).nonzero()[0] valid_idxs", "p.add_argument('--visualsem_images_path', type=str, default=visualsem_images_path, help=\"Path to directory containing VisualSem images.\") p.add_argument('--glosses_sentence_bert_path', type=str, default=glosses_sentence_bert_path, help=\"\"\"HDF5", "all_input_sentences, glosses_bnids, glosses_feats, topk): \"\"\" out_fname(str): Output file to write retrieved node ids", "directory containing VisualSem knowledge graph.\") p.add_argument('--visualsem_nodes_path', type=str, default=visualsem_nodes_path, help=\"Path to file containing VisualSem", "bnid_pred in bnids_predicted: bnids_predicted.append((bnid_pred,bnid_pred_score)) if len(bnids_predicted)>=topk: break # write top-k predicted BNids for", "def encode_query(out_fname, batch_size, all_sentences): \"\"\" out_fname(str): Output file to write SBERT features for", "chunks=(1,768), maxshape=(None, 768), compression=\"gzip\") for from_idx in tqdm.trange(0,n_lines,batch_size): to_idx = from_idx+batch_size if from_idx+batch_size", "== topk-1 fh_out.write(\"\\n\") def encode_query(out_fname, batch_size, all_sentences): \"\"\" out_fname(str): Output file to write", "[] for idxs_ in grouper(batch_size, range(n_examples)): idxs = [] queries = [] for", "with `glosses_feats`. glosses_feats(numpy.array): Numpy array with VisualSem gloss features computed with Sentence BERT.", "itertools import zip_longest from utils import grouper, load_sentences, load_bnids, load_visualsem_bnids def retrieve_nodes_given_sentences(out_fname, batch_size,", "encode_query(out_fname, batch_size, all_sentences): \"\"\" out_fname(str): Output file to write SBERT features for query.", "each input sentence.\") p.add_argument('--batch_size', type=int, default=1000) p.add_argument('--visualsem_path', type=str, default=visualsem_path, help=\"Path to directory containing", "= input_file+\".bnids\" retrieve_nodes_given_sentences(out_fname, args.batch_size, input_sentences, gloss_bnids, glosses_feats, args.topk) # remove temporary SBERT index", "if len(bnids_predicted)>=topk: break # write top-k predicted BNids for iii, (bnid, score) in", "as fh_glosses: glosses_feats = fh_glosses[\"features\"][:] glosses_feats = torch.tensor(glosses_feats) if torch.cuda.is_available(): glosses_feats = glosses_feats.cuda()", "SentenceTransformer(model_name) with open(out_fname, 'w', encoding='utf8') as fh_out: ranks_predicted = [] for idxs_ in", "avoid tampering.\"%out_fname) n_examples = len(all_input_sentences) print(\"Number of input examples to extract BNIDs for:", "it manually to avoid tampering.\"%out_fname) n_examples = len(all_input_sentences) print(\"Number of input examples to", "each input sentence. \"\"\" if os.path.isfile(out_fname): raise Exception(\"File already exists: '%s'. Please remove", "fh_out: fh_out.create_dataset(\"features\", shape_features, dtype='float32', chunks=(1,768), maxshape=(None, 768), compression=\"gzip\") for from_idx in tqdm.trange(0,n_lines,batch_size): to_idx", "BNids loaded from `args.glosses_bnids`. Aligned with `glosses_feats`. glosses_feats(numpy.array): Numpy array with VisualSem gloss", "gloss_bnids = numpy.array(gloss_bnids, dtype='object') with h5py.File(args.glosses_sentence_bert_path, 'r') as fh_glosses: glosses_feats = fh_glosses[\"features\"][:] glosses_feats", "to write SBERT features for query. batch_size(int): Batch size for Sentence BERT. all_sentences(list[str]):", ") gloss_bnids = numpy.array(gloss_bnids, dtype='object') with h5py.File(args.glosses_sentence_bert_path, 'r') as fh_glosses: glosses_feats = fh_glosses[\"features\"][:]", "out_fname(str): Output file to write retrieved node ids to. batch_size(int): Batch size for", "reference)\"\"\") args = p.parse_args() # load all nodes in VisualSem all_bnids = load_visualsem_bnids(args.visualsem_nodes_path,", "file(s) to use for retrieval. Each line in each file should contain a", "for rank_predicted in range(topk*10): bnid_pred = glosses_bnids[ ranks[rank_idx,rank_predicted] ] bnid_pred_score = scores[rank_idx, ranks[rank_idx,", "paper for reference)\"\"\") p.add_argument('--input_test', action='store_true', help=\"\"\"Perform retrieval for the glosses in the test", "if os.path.isfile(out_fname): raise Exception(\"File already exists: '%s'. Please remove it manually to avoid", "retrieve for each input sentence. \"\"\" if os.path.isfile(out_fname): raise Exception(\"File already exists: '%s'.", "set. (See paper for reference)\"\"\") args = p.parse_args() # load all nodes in", "None: idxs.append(i) queries.append( all_input_sentences[i] ) queries_embs = model.encode(queries, convert_to_tensor=True) if torch.cuda.is_available(): queries_embs =", "p = argparse.ArgumentParser() p.add_argument('--input_files', type=str, nargs=\"+\", default=[\"example_data/queries.txt\"], help=\"\"\"Input file(s) to use for retrieval.", "queries.append( all_input_sentences[i] ) queries_embs = model.encode(queries, convert_to_tensor=True) if torch.cuda.is_available(): queries_embs = queries_embs.cuda() scores", "with Sentence BERT. topk(int): Number of nodes to retrieve for each input sentence.", "input sentences loaded from `input_file`. glosses_bnids(list[str]): All gloss BNids loaded from `args.glosses_bnids`. Aligned", "ranks[rank_idx, rank_predicted]] if not bnid_pred in bnids_predicted: bnids_predicted.append((bnid_pred,bnid_pred_score)) if len(bnids_predicted)>=topk: break # write", "numpy.array(gloss_bnids, dtype='object') with h5py.File(args.glosses_sentence_bert_path, 'r') as fh_glosses: glosses_feats = fh_glosses[\"features\"][:] glosses_feats = torch.tensor(glosses_feats)", "ranks = ranks[:,::-1] # sort by cosine similarity (high to low) for rank_idx", "(high to low) for rank_idx in range(len(idxs[:ranks.shape[0]])): bnids_predicted = [] for rank_predicted in", "# remove temporary SBERT index created for input file(s) os.remove( sbert_out_fname ) print(\"Retrieved", "input examples to extract BNIDs for: \", n_examples) model_name = \"paraphrase-multilingual-mpnet-base-v2\" model =", ") queries_embs = model.encode(queries, convert_to_tensor=True) if torch.cuda.is_available(): queries_embs = queries_embs.cuda() scores = util.pytorch_cos_sim(queries_embs,", "All gloss BNids loaded from `args.glosses_bnids`. Aligned with `glosses_feats`. glosses_feats(numpy.array): Numpy array with", "batch_size, all_input_sentences, glosses_bnids, glosses_feats, topk): \"\"\" out_fname(str): Output file to write retrieved node", "print(\"Number of input examples to extract BNIDs for: \", n_examples) model_name = \"paraphrase-multilingual-mpnet-base-v2\"", "i is None: idxs.append(i) queries.append( all_input_sentences[i] ) queries_embs = model.encode(queries, convert_to_tensor=True) if torch.cuda.is_available():", "BERT. all_sentences(list[str]): Sentences to be used for retrieval. \"\"\" n_lines = len(all_sentences) model_name", "line in each file should contain a detokenized sentence.\"\"\") p.add_argument('--topk', type=int, default=1, help=\"Retrieve", "for reference)\"\"\") args = p.parse_args() # load all nodes in VisualSem all_bnids =", "os.path.isfile( sbert_out_fname ): raise Exception(\"File already exists: '%s'. Please remove it manually to", "= len(all_sentences) model_name = \"paraphrase-multilingual-mpnet-base-v2\" model = SentenceTransformer(model_name) shape_features = (n_lines, 768) with", "low) for rank_idx in range(len(idxs[:ranks.shape[0]])): bnids_predicted = [] for rank_predicted in range(topk*10): bnid_pred", "VisualSem all_bnids = load_visualsem_bnids(args.visualsem_nodes_path, args.visualsem_images_path) gloss_bnids = load_bnids( args.glosses_bnids_path ) gloss_bnids = numpy.array(gloss_bnids,", "model.encode(batch_sentences, convert_to_tensor=True) #test_queries(emb_sentences, all_sentences, model) fh_out[\"features\"][from_idx:to_idx] = emb_sentences.cpu().numpy() if __name__==\"__main__\": visualsem_path = os.path.dirname(os.path.realpath(__file__))", "= input_file+\".sentencebert.h5\" if os.path.isfile( sbert_out_fname ): raise Exception(\"File already exists: '%s'. Please remove", "argparse.ArgumentParser() p.add_argument('--input_files', type=str, nargs=\"+\", default=[\"example_data/queries.txt\"], help=\"\"\"Input file(s) to use for retrieval. Each line", "write top-k predicted BNids for iii, (bnid, score) in enumerate(bnids_predicted[:topk]): fh_out.write(bnid+\"\\t\"+\"%.4f\"%score) if iii", "help=\"\"\"Text file containing glosses BabelNet ids, one per line (computed with `extract_glosses_visualsem.py`).\"\"\") p.add_argument('--input_valid',", "(glosses_splits==2).nonzero()[0] # load gloss language splits language_splits = fh_glosses[\"language_idxs\"][:] for input_file in args.input_files:", "from `args.glosses_bnids`. Aligned with `glosses_feats`. glosses_feats(numpy.array): Numpy array with VisualSem gloss features computed", "in grouper(batch_size, range(n_examples)): idxs = [] queries = [] for i in idxs_:", "(See paper for reference)\"\"\") p.add_argument('--input_test', action='store_true', help=\"\"\"Perform retrieval for the glosses in the", "import os import json from collections import defaultdict import h5py from sentence_transformers import", "node ids to. batch_size(int): Batch size for Sentence BERT. all_input_sentences(list[str]): All input sentences", "# sort by cosine similarity (high to low) for rank_idx in range(len(idxs[:ranks.shape[0]])): bnids_predicted", "ranks_predicted = [] for idxs_ in grouper(batch_size, range(n_examples)): idxs = [] queries =", "(n_lines, 768) with h5py.File(out_fname, 'w') as fh_out: fh_out.create_dataset(\"features\", shape_features, dtype='float32', chunks=(1,768), maxshape=(None, 768),", "768), compression=\"gzip\") for from_idx in tqdm.trange(0,n_lines,batch_size): to_idx = from_idx+batch_size if from_idx+batch_size <= n_lines", "shape_features, dtype='float32', chunks=(1,768), maxshape=(None, 768), compression=\"gzip\") for from_idx in tqdm.trange(0,n_lines,batch_size): to_idx = from_idx+batch_size", "rank_idx in range(len(idxs[:ranks.shape[0]])): bnids_predicted = [] for rank_predicted in range(topk*10): bnid_pred = glosses_bnids[", "containing glosses BabelNet ids, one per line (computed with `extract_glosses_visualsem.py`).\"\"\") p.add_argument('--input_valid', action='store_true', help=\"\"\"Perform", "used for retrieval. \"\"\" n_lines = len(all_sentences) model_name = \"paraphrase-multilingual-mpnet-base-v2\" model = SentenceTransformer(model_name)", "`extract_glosses_visualsem.py`).\"\"\") p.add_argument('--glosses_bnids_path', type=str, default=glosses_bnids_path, help=\"\"\"Text file containing glosses BabelNet ids, one per line", "'%s'. Please remove it manually to avoid tampering.\"%sbert_out_fname) input_sentences = load_sentences( input_file )", "file containing VisualSem nodes.\") p.add_argument('--visualsem_images_path', type=str, default=visualsem_images_path, help=\"Path to directory containing VisualSem images.\")", "glosses_feats, topk): \"\"\" out_fname(str): Output file to write retrieved node ids to. batch_size(int):", "not i is None: idxs.append(i) queries.append( all_input_sentences[i] ) queries_embs = model.encode(queries, convert_to_tensor=True) if", "import numpy import tqdm from itertools import zip_longest from utils import grouper, load_sentences,", "queries = [] for i in idxs_: if not i is None: idxs.append(i)", "break # write top-k predicted BNids for iii, (bnid, score) in enumerate(bnids_predicted[:topk]): fh_out.write(bnid+\"\\t\"+\"%.4f\"%score)", "# iii == topk-1 fh_out.write(\"\\n\") def encode_query(out_fname, batch_size, all_sentences): \"\"\" out_fname(str): Output file", "file containing glosses index computed with Sentence BERT (computed with `extract_glosses_visualsem.py`).\"\"\") p.add_argument('--glosses_bnids_path', type=str,", "test set. (See paper for reference)\"\"\") args = p.parse_args() # load all nodes", "fh_glosses[\"features\"][:] glosses_feats = torch.tensor(glosses_feats) if torch.cuda.is_available(): glosses_feats = glosses_feats.cuda() # load train/valid/test gloss", "per line (computed with `extract_glosses_visualsem.py`).\"\"\") p.add_argument('--input_valid', action='store_true', help=\"\"\"Perform retrieval for the glosses in", "in VisualSem all_bnids = load_visualsem_bnids(args.visualsem_nodes_path, args.visualsem_images_path) gloss_bnids = load_bnids( args.glosses_bnids_path ) gloss_bnids =", "sentence.\") p.add_argument('--batch_size', type=int, default=1000) p.add_argument('--visualsem_path', type=str, default=visualsem_path, help=\"Path to directory containing VisualSem knowledge", "help=\"\"\"Input file(s) to use for retrieval. Each line in each file should contain", "os.makedirs(\"%s/dataset/gloss_files/\"%visualsem_path, exist_ok=True) p = argparse.ArgumentParser() p.add_argument('--input_files', type=str, nargs=\"+\", default=[\"example_data/queries.txt\"], help=\"\"\"Input file(s) to use", "remove it manually to avoid tampering.\"%sbert_out_fname) input_sentences = load_sentences( input_file ) encode_query(sbert_out_fname, args.batch_size,", "the glosses in the test set. (See paper for reference)\"\"\") args = p.parse_args()", "= argparse.ArgumentParser() p.add_argument('--input_files', type=str, nargs=\"+\", default=[\"example_data/queries.txt\"], help=\"\"\"Input file(s) to use for retrieval. Each", "loaded from `input_file`. glosses_bnids(list[str]): All gloss BNids loaded from `args.glosses_bnids`. Aligned with `glosses_feats`.", "directory containing VisualSem images.\") p.add_argument('--glosses_sentence_bert_path', type=str, default=glosses_sentence_bert_path, help=\"\"\"HDF5 file containing glosses index computed", "\"%s/dataset/gloss_files/glosses.en.txt.sentencebert.h5\"%visualsem_path glosses_bnids_path = \"%s/dataset/gloss_files/glosses.en.txt.bnids\"%visualsem_path os.makedirs(\"%s/dataset/gloss_files/\"%visualsem_path, exist_ok=True) p = argparse.ArgumentParser() p.add_argument('--input_files', type=str, nargs=\"+\", default=[\"example_data/queries.txt\"],", "cosine similarity (low to high) ranks = ranks[:,::-1] # sort by cosine similarity", "iii, (bnid, score) in enumerate(bnids_predicted[:topk]): fh_out.write(bnid+\"\\t\"+\"%.4f\"%score) if iii < topk-1: fh_out.write(\"\\t\") else: #", "p.add_argument('--topk', type=int, default=1, help=\"Retrieve topk nodes for each input sentence.\") p.add_argument('--batch_size', type=int, default=1000)", "= model.encode(queries, convert_to_tensor=True) if torch.cuda.is_available(): queries_embs = queries_embs.cuda() scores = util.pytorch_cos_sim(queries_embs, glosses_feats) scores", "manually to avoid tampering.\"%sbert_out_fname) input_sentences = load_sentences( input_file ) encode_query(sbert_out_fname, args.batch_size, input_sentences) out_fname", "encode_query(sbert_out_fname, args.batch_size, input_sentences) out_fname = input_file+\".bnids\" retrieve_nodes_given_sentences(out_fname, args.batch_size, input_sentences, gloss_bnids, glosses_feats, args.topk) #", "features for query. batch_size(int): Batch size for Sentence BERT. all_sentences(list[str]): Sentences to be", "# write top-k predicted BNids for iii, (bnid, score) in enumerate(bnids_predicted[:topk]): fh_out.write(bnid+\"\\t\"+\"%.4f\"%score) if", "with `extract_glosses_visualsem.py`).\"\"\") p.add_argument('--input_valid', action='store_true', help=\"\"\"Perform retrieval for the glosses in the validation set.", "not bnid_pred in bnids_predicted: bnids_predicted.append((bnid_pred,bnid_pred_score)) if len(bnids_predicted)>=topk: break # write top-k predicted BNids", "from sentence_transformers import SentenceTransformer, util import numpy import tqdm from itertools import zip_longest", "to retrieve for each input sentence. \"\"\" if os.path.isfile(out_fname): raise Exception(\"File already exists:", "test_idxs = (glosses_splits==2).nonzero()[0] # load gloss language splits language_splits = fh_glosses[\"language_idxs\"][:] for input_file", "glosses_sentence_bert_path = \"%s/dataset/gloss_files/glosses.en.txt.sentencebert.h5\"%visualsem_path glosses_bnids_path = \"%s/dataset/gloss_files/glosses.en.txt.bnids\"%visualsem_path os.makedirs(\"%s/dataset/gloss_files/\"%visualsem_path, exist_ok=True) p = argparse.ArgumentParser() p.add_argument('--input_files', type=str,", "glosses in the validation set. (See paper for reference)\"\"\") p.add_argument('--input_test', action='store_true', help=\"\"\"Perform retrieval", "sbert_out_fname ): raise Exception(\"File already exists: '%s'. Please remove it manually to avoid", "= fh_glosses[\"language_idxs\"][:] for input_file in args.input_files: print(\"Processing input file: %s ...\"%input_file) sbert_out_fname =", "all_sentences[ from_idx: to_idx ] emb_sentences = model.encode(batch_sentences, convert_to_tensor=True) #test_queries(emb_sentences, all_sentences, model) fh_out[\"features\"][from_idx:to_idx] =", "Batch size for Sentence BERT. all_sentences(list[str]): Sentences to be used for retrieval. \"\"\"", "else: # iii == topk-1 fh_out.write(\"\\n\") def encode_query(out_fname, batch_size, all_sentences): \"\"\" out_fname(str): Output", "Batch size for Sentence BERT. all_input_sentences(list[str]): All input sentences loaded from `input_file`. glosses_bnids(list[str]):", "all_sentences): \"\"\" out_fname(str): Output file to write SBERT features for query. batch_size(int): Batch", "(bnid, score) in enumerate(bnids_predicted[:topk]): fh_out.write(bnid+\"\\t\"+\"%.4f\"%score) if iii < topk-1: fh_out.write(\"\\t\") else: # iii", "gloss splits glosses_splits = fh_glosses[\"split_idxs\"][:] train_idxs = (glosses_splits==0).nonzero()[0] valid_idxs = (glosses_splits==1).nonzero()[0] test_idxs =", "sort scores by cosine similarity (low to high) ranks = ranks[:,::-1] # sort", "h5py.File(args.glosses_sentence_bert_path, 'r') as fh_glosses: glosses_feats = fh_glosses[\"features\"][:] glosses_feats = torch.tensor(glosses_feats) if torch.cuda.is_available(): glosses_feats", "ranks[rank_idx,rank_predicted] ] bnid_pred_score = scores[rank_idx, ranks[rank_idx, rank_predicted]] if not bnid_pred in bnids_predicted: bnids_predicted.append((bnid_pred,bnid_pred_score))", "batch_sentences = all_sentences[ from_idx: to_idx ] emb_sentences = model.encode(batch_sentences, convert_to_tensor=True) #test_queries(emb_sentences, all_sentences, model)", "is None: idxs.append(i) queries.append( all_input_sentences[i] ) queries_embs = model.encode(queries, convert_to_tensor=True) if torch.cuda.is_available(): queries_embs", "glosses_feats, args.topk) # remove temporary SBERT index created for input file(s) os.remove( sbert_out_fname", "= [] for rank_predicted in range(topk*10): bnid_pred = glosses_bnids[ ranks[rank_idx,rank_predicted] ] bnid_pred_score =", "(glosses_splits==0).nonzero()[0] valid_idxs = (glosses_splits==1).nonzero()[0] test_idxs = (glosses_splits==2).nonzero()[0] # load gloss language splits language_splits", "to avoid tampering.\"%sbert_out_fname) input_sentences = load_sentences( input_file ) encode_query(sbert_out_fname, args.batch_size, input_sentences) out_fname =", "# load train/valid/test gloss splits glosses_splits = fh_glosses[\"split_idxs\"][:] train_idxs = (glosses_splits==0).nonzero()[0] valid_idxs =", "p.add_argument('--visualsem_nodes_path', type=str, default=visualsem_nodes_path, help=\"Path to file containing VisualSem nodes.\") p.add_argument('--visualsem_images_path', type=str, default=visualsem_images_path, help=\"Path", "util import numpy import tqdm from itertools import zip_longest from utils import grouper,", "input sentence. \"\"\" if os.path.isfile(out_fname): raise Exception(\"File already exists: '%s'. Please remove it", "glosses_feats(numpy.array): Numpy array with VisualSem gloss features computed with Sentence BERT. topk(int): Number", "<= n_lines else n_lines batch_sentences = all_sentences[ from_idx: to_idx ] emb_sentences = model.encode(batch_sentences,", "reference)\"\"\") p.add_argument('--input_test', action='store_true', help=\"\"\"Perform retrieval for the glosses in the test set. (See", "\"\"\" n_lines = len(all_sentences) model_name = \"paraphrase-multilingual-mpnet-base-v2\" model = SentenceTransformer(model_name) shape_features = (n_lines,", "VisualSem knowledge graph.\") p.add_argument('--visualsem_nodes_path', type=str, default=visualsem_nodes_path, help=\"Path to file containing VisualSem nodes.\") p.add_argument('--visualsem_images_path',", "from_idx+batch_size if from_idx+batch_size <= n_lines else n_lines batch_sentences = all_sentences[ from_idx: to_idx ]", "images.\") p.add_argument('--glosses_sentence_bert_path', type=str, default=glosses_sentence_bert_path, help=\"\"\"HDF5 file containing glosses index computed with Sentence BERT", "for idxs_ in grouper(batch_size, range(n_examples)): idxs = [] queries = [] for i", "`args.glosses_bnids`. Aligned with `glosses_feats`. glosses_feats(numpy.array): Numpy array with VisualSem gloss features computed with", "for each input sentence. \"\"\" if os.path.isfile(out_fname): raise Exception(\"File already exists: '%s'. Please", "= util.pytorch_cos_sim(queries_embs, glosses_feats) scores = scores.cpu().numpy() ranks = numpy.argsort(scores) # sort scores by", "examples to extract BNIDs for: \", n_examples) model_name = \"paraphrase-multilingual-mpnet-base-v2\" model = SentenceTransformer(model_name)", "\"paraphrase-multilingual-mpnet-base-v2\" model = SentenceTransformer(model_name) shape_features = (n_lines, 768) with h5py.File(out_fname, 'w') as fh_out:", "all_bnids = load_visualsem_bnids(args.visualsem_nodes_path, args.visualsem_images_path) gloss_bnids = load_bnids( args.glosses_bnids_path ) gloss_bnids = numpy.array(gloss_bnids, dtype='object')", "detokenized sentence.\"\"\") p.add_argument('--topk', type=int, default=1, help=\"Retrieve topk nodes for each input sentence.\") p.add_argument('--batch_size',", "topk-1 fh_out.write(\"\\n\") def encode_query(out_fname, batch_size, all_sentences): \"\"\" out_fname(str): Output file to write SBERT", "knowledge graph.\") p.add_argument('--visualsem_nodes_path', type=str, default=visualsem_nodes_path, help=\"Path to file containing VisualSem nodes.\") p.add_argument('--visualsem_images_path', type=str,", "nargs=\"+\", default=[\"example_data/queries.txt\"], help=\"\"\"Input file(s) to use for retrieval. Each line in each file", "type=str, nargs=\"+\", default=[\"example_data/queries.txt\"], help=\"\"\"Input file(s) to use for retrieval. Each line in each", "already exists: '%s'. Please remove it manually to avoid tampering.\"%out_fname) n_examples = len(all_input_sentences)", "exists: '%s'. Please remove it manually to avoid tampering.\"%out_fname) n_examples = len(all_input_sentences) print(\"Number", "#test_queries(emb_sentences, all_sentences, model) fh_out[\"features\"][from_idx:to_idx] = emb_sentences.cpu().numpy() if __name__==\"__main__\": visualsem_path = os.path.dirname(os.path.realpath(__file__)) visualsem_nodes_path =", "from `input_file`. glosses_bnids(list[str]): All gloss BNids loaded from `args.glosses_bnids`. Aligned with `glosses_feats`. glosses_feats(numpy.array):", "numpy.argsort(scores) # sort scores by cosine similarity (low to high) ranks = ranks[:,::-1]", "= fh_glosses[\"features\"][:] glosses_feats = torch.tensor(glosses_feats) if torch.cuda.is_available(): glosses_feats = glosses_feats.cuda() # load train/valid/test", "for i in idxs_: if not i is None: idxs.append(i) queries.append( all_input_sentences[i] )", "768) with h5py.File(out_fname, 'w') as fh_out: fh_out.create_dataset(\"features\", shape_features, dtype='float32', chunks=(1,768), maxshape=(None, 768), compression=\"gzip\")", "type=str, default=visualsem_nodes_path, help=\"Path to file containing VisualSem nodes.\") p.add_argument('--visualsem_images_path', type=str, default=visualsem_images_path, help=\"Path to", "SentenceTransformer, util import numpy import tqdm from itertools import zip_longest from utils import", "set. (See paper for reference)\"\"\") p.add_argument('--input_test', action='store_true', help=\"\"\"Perform retrieval for the glosses in", "tampering.\"%sbert_out_fname) input_sentences = load_sentences( input_file ) encode_query(sbert_out_fname, args.batch_size, input_sentences) out_fname = input_file+\".bnids\" retrieve_nodes_given_sentences(out_fname,", "= (glosses_splits==2).nonzero()[0] # load gloss language splits language_splits = fh_glosses[\"language_idxs\"][:] for input_file in", "topk nodes for each input sentence.\") p.add_argument('--batch_size', type=int, default=1000) p.add_argument('--visualsem_path', type=str, default=visualsem_path, help=\"Path", "ids to. batch_size(int): Batch size for Sentence BERT. all_input_sentences(list[str]): All input sentences loaded", "retrieved node ids to. batch_size(int): Batch size for Sentence BERT. all_input_sentences(list[str]): All input", "compression=\"gzip\") for from_idx in tqdm.trange(0,n_lines,batch_size): to_idx = from_idx+batch_size if from_idx+batch_size <= n_lines else", "containing glosses index computed with Sentence BERT (computed with `extract_glosses_visualsem.py`).\"\"\") p.add_argument('--glosses_bnids_path', type=str, default=glosses_bnids_path,", "gloss BNids loaded from `args.glosses_bnids`. Aligned with `glosses_feats`. glosses_feats(numpy.array): Numpy array with VisualSem", "if os.path.isfile( sbert_out_fname ): raise Exception(\"File already exists: '%s'. Please remove it manually", "fh_out.write(\"\\t\") else: # iii == topk-1 fh_out.write(\"\\n\") def encode_query(out_fname, batch_size, all_sentences): \"\"\" out_fname(str):", "__name__==\"__main__\": visualsem_path = os.path.dirname(os.path.realpath(__file__)) visualsem_nodes_path = \"%s/dataset/nodes.v2.json\"%visualsem_path visualsem_images_path = \"%s/dataset/images/\"%visualsem_path glosses_sentence_bert_path = \"%s/dataset/gloss_files/glosses.en.txt.sentencebert.h5\"%visualsem_path", "tampering.\"%out_fname) n_examples = len(all_input_sentences) print(\"Number of input examples to extract BNIDs for: \",", "should contain a detokenized sentence.\"\"\") p.add_argument('--topk', type=int, default=1, help=\"Retrieve topk nodes for each", "predicted BNids for iii, (bnid, score) in enumerate(bnids_predicted[:topk]): fh_out.write(bnid+\"\\t\"+\"%.4f\"%score) if iii < topk-1:", "glosses index computed with Sentence BERT (computed with `extract_glosses_visualsem.py`).\"\"\") p.add_argument('--glosses_bnids_path', type=str, default=glosses_bnids_path, help=\"\"\"Text", "index computed with Sentence BERT (computed with `extract_glosses_visualsem.py`).\"\"\") p.add_argument('--glosses_bnids_path', type=str, default=glosses_bnids_path, help=\"\"\"Text file", "load all nodes in VisualSem all_bnids = load_visualsem_bnids(args.visualsem_nodes_path, args.visualsem_images_path) gloss_bnids = load_bnids( args.glosses_bnids_path", "(computed with `extract_glosses_visualsem.py`).\"\"\") p.add_argument('--glosses_bnids_path', type=str, default=glosses_bnids_path, help=\"\"\"Text file containing glosses BabelNet ids, one", "h5py from sentence_transformers import SentenceTransformer, util import numpy import tqdm from itertools import", "[] queries = [] for i in idxs_: if not i is None:", "in range(topk*10): bnid_pred = glosses_bnids[ ranks[rank_idx,rank_predicted] ] bnid_pred_score = scores[rank_idx, ranks[rank_idx, rank_predicted]] if", "= os.path.dirname(os.path.realpath(__file__)) visualsem_nodes_path = \"%s/dataset/nodes.v2.json\"%visualsem_path visualsem_images_path = \"%s/dataset/images/\"%visualsem_path glosses_sentence_bert_path = \"%s/dataset/gloss_files/glosses.en.txt.sentencebert.h5\"%visualsem_path glosses_bnids_path =", "nodes.\") p.add_argument('--visualsem_images_path', type=str, default=visualsem_images_path, help=\"Path to directory containing VisualSem images.\") p.add_argument('--glosses_sentence_bert_path', type=str, default=glosses_sentence_bert_path,", "import sys import os import json from collections import defaultdict import h5py from", "= p.parse_args() # load all nodes in VisualSem all_bnids = load_visualsem_bnids(args.visualsem_nodes_path, args.visualsem_images_path) gloss_bnids", "file containing glosses BabelNet ids, one per line (computed with `extract_glosses_visualsem.py`).\"\"\") p.add_argument('--input_valid', action='store_true',", "if not i is None: idxs.append(i) queries.append( all_input_sentences[i] ) queries_embs = model.encode(queries, convert_to_tensor=True)", "splits language_splits = fh_glosses[\"language_idxs\"][:] for input_file in args.input_files: print(\"Processing input file: %s ...\"%input_file)", "VisualSem gloss features computed with Sentence BERT. topk(int): Number of nodes to retrieve", "action='store_true', help=\"\"\"Perform retrieval for the glosses in the test set. (See paper for", "validation set. (See paper for reference)\"\"\") p.add_argument('--input_test', action='store_true', help=\"\"\"Perform retrieval for the glosses", "be used for retrieval. \"\"\" n_lines = len(all_sentences) model_name = \"paraphrase-multilingual-mpnet-base-v2\" model =", "SentenceTransformer(model_name) shape_features = (n_lines, 768) with h5py.File(out_fname, 'w') as fh_out: fh_out.create_dataset(\"features\", shape_features, dtype='float32',", "by cosine similarity (high to low) for rank_idx in range(len(idxs[:ranks.shape[0]])): bnids_predicted = []", "if iii < topk-1: fh_out.write(\"\\t\") else: # iii == topk-1 fh_out.write(\"\\n\") def encode_query(out_fname,", "to be used for retrieval. \"\"\" n_lines = len(all_sentences) model_name = \"paraphrase-multilingual-mpnet-base-v2\" model", "zip_longest from utils import grouper, load_sentences, load_bnids, load_visualsem_bnids def retrieve_nodes_given_sentences(out_fname, batch_size, all_input_sentences, glosses_bnids,", "exist_ok=True) p = argparse.ArgumentParser() p.add_argument('--input_files', type=str, nargs=\"+\", default=[\"example_data/queries.txt\"], help=\"\"\"Input file(s) to use for", "for each input sentence.\") p.add_argument('--batch_size', type=int, default=1000) p.add_argument('--visualsem_path', type=str, default=visualsem_path, help=\"Path to directory", "to directory containing VisualSem knowledge graph.\") p.add_argument('--visualsem_nodes_path', type=str, default=visualsem_nodes_path, help=\"Path to file containing", "numpy import tqdm from itertools import zip_longest from utils import grouper, load_sentences, load_bnids,", "p.add_argument('--glosses_bnids_path', type=str, default=glosses_bnids_path, help=\"\"\"Text file containing glosses BabelNet ids, one per line (computed", "glosses_bnids, glosses_feats, topk): \"\"\" out_fname(str): Output file to write retrieved node ids to.", "bnids_predicted: bnids_predicted.append((bnid_pred,bnid_pred_score)) if len(bnids_predicted)>=topk: break # write top-k predicted BNids for iii, (bnid,", "\", n_examples) model_name = \"paraphrase-multilingual-mpnet-base-v2\" model = SentenceTransformer(model_name) with open(out_fname, 'w', encoding='utf8') as", "sentences loaded from `input_file`. glosses_bnids(list[str]): All gloss BNids loaded from `args.glosses_bnids`. Aligned with", "argparse import torch import sys import os import json from collections import defaultdict", "batch_size, all_sentences): \"\"\" out_fname(str): Output file to write SBERT features for query. batch_size(int):", "as fh_out: fh_out.create_dataset(\"features\", shape_features, dtype='float32', chunks=(1,768), maxshape=(None, 768), compression=\"gzip\") for from_idx in tqdm.trange(0,n_lines,batch_size):", "each file should contain a detokenized sentence.\"\"\") p.add_argument('--topk', type=int, default=1, help=\"Retrieve topk nodes", "idxs_: if not i is None: idxs.append(i) queries.append( all_input_sentences[i] ) queries_embs = model.encode(queries,", "containing VisualSem images.\") p.add_argument('--glosses_sentence_bert_path', type=str, default=glosses_sentence_bert_path, help=\"\"\"HDF5 file containing glosses index computed with", "for query. batch_size(int): Batch size for Sentence BERT. all_sentences(list[str]): Sentences to be used", "(See paper for reference)\"\"\") args = p.parse_args() # load all nodes in VisualSem", "args.batch_size, input_sentences, gloss_bnids, glosses_feats, args.topk) # remove temporary SBERT index created for input", "model = SentenceTransformer(model_name) with open(out_fname, 'w', encoding='utf8') as fh_out: ranks_predicted = [] for", "in range(len(idxs[:ranks.shape[0]])): bnids_predicted = [] for rank_predicted in range(topk*10): bnid_pred = glosses_bnids[ ranks[rank_idx,rank_predicted]", "valid_idxs = (glosses_splits==1).nonzero()[0] test_idxs = (glosses_splits==2).nonzero()[0] # load gloss language splits language_splits =", "exists: '%s'. Please remove it manually to avoid tampering.\"%sbert_out_fname) input_sentences = load_sentences( input_file", "from utils import grouper, load_sentences, load_bnids, load_visualsem_bnids def retrieve_nodes_given_sentences(out_fname, batch_size, all_input_sentences, glosses_bnids, glosses_feats,", "open(out_fname, 'w', encoding='utf8') as fh_out: ranks_predicted = [] for idxs_ in grouper(batch_size, range(n_examples)):", "default=1, help=\"Retrieve topk nodes for each input sentence.\") p.add_argument('--batch_size', type=int, default=1000) p.add_argument('--visualsem_path', type=str,", "fh_out.write(\"\\n\") def encode_query(out_fname, batch_size, all_sentences): \"\"\" out_fname(str): Output file to write SBERT features", "help=\"Path to directory containing VisualSem knowledge graph.\") p.add_argument('--visualsem_nodes_path', type=str, default=visualsem_nodes_path, help=\"Path to file", "len(bnids_predicted)>=topk: break # write top-k predicted BNids for iii, (bnid, score) in enumerate(bnids_predicted[:topk]):", "sys import os import json from collections import defaultdict import h5py from sentence_transformers", "p.add_argument('--batch_size', type=int, default=1000) p.add_argument('--visualsem_path', type=str, default=visualsem_path, help=\"Path to directory containing VisualSem knowledge graph.\")", "type=str, default=visualsem_images_path, help=\"Path to directory containing VisualSem images.\") p.add_argument('--glosses_sentence_bert_path', type=str, default=glosses_sentence_bert_path, help=\"\"\"HDF5 file", "`input_file`. glosses_bnids(list[str]): All gloss BNids loaded from `args.glosses_bnids`. Aligned with `glosses_feats`. glosses_feats(numpy.array): Numpy", "Sentence BERT. all_input_sentences(list[str]): All input sentences loaded from `input_file`. glosses_bnids(list[str]): All gloss BNids", "topk(int): Number of nodes to retrieve for each input sentence. \"\"\" if os.path.isfile(out_fname):", "from_idx: to_idx ] emb_sentences = model.encode(batch_sentences, convert_to_tensor=True) #test_queries(emb_sentences, all_sentences, model) fh_out[\"features\"][from_idx:to_idx] = emb_sentences.cpu().numpy()", "splits glosses_splits = fh_glosses[\"split_idxs\"][:] train_idxs = (glosses_splits==0).nonzero()[0] valid_idxs = (glosses_splits==1).nonzero()[0] test_idxs = (glosses_splits==2).nonzero()[0]", "input_sentences, gloss_bnids, glosses_feats, args.topk) # remove temporary SBERT index created for input file(s)", "all_input_sentences(list[str]): All input sentences loaded from `input_file`. glosses_bnids(list[str]): All gloss BNids loaded from", "nodes in VisualSem all_bnids = load_visualsem_bnids(args.visualsem_nodes_path, args.visualsem_images_path) gloss_bnids = load_bnids( args.glosses_bnids_path ) gloss_bnids", "p.add_argument('--glosses_sentence_bert_path', type=str, default=glosses_sentence_bert_path, help=\"\"\"HDF5 file containing glosses index computed with Sentence BERT (computed", "for retrieval. \"\"\" n_lines = len(all_sentences) model_name = \"paraphrase-multilingual-mpnet-base-v2\" model = SentenceTransformer(model_name) shape_features", "= emb_sentences.cpu().numpy() if __name__==\"__main__\": visualsem_path = os.path.dirname(os.path.realpath(__file__)) visualsem_nodes_path = \"%s/dataset/nodes.v2.json\"%visualsem_path visualsem_images_path = \"%s/dataset/images/\"%visualsem_path", "in bnids_predicted: bnids_predicted.append((bnid_pred,bnid_pred_score)) if len(bnids_predicted)>=topk: break # write top-k predicted BNids for iii,", "manually to avoid tampering.\"%out_fname) n_examples = len(all_input_sentences) print(\"Number of input examples to extract", "idxs.append(i) queries.append( all_input_sentences[i] ) queries_embs = model.encode(queries, convert_to_tensor=True) if torch.cuda.is_available(): queries_embs = queries_embs.cuda()", "cosine similarity (high to low) for rank_idx in range(len(idxs[:ranks.shape[0]])): bnids_predicted = [] for", "from_idx in tqdm.trange(0,n_lines,batch_size): to_idx = from_idx+batch_size if from_idx+batch_size <= n_lines else n_lines batch_sentences", "type=int, default=1, help=\"Retrieve topk nodes for each input sentence.\") p.add_argument('--batch_size', type=int, default=1000) p.add_argument('--visualsem_path',", "n_lines = len(all_sentences) model_name = \"paraphrase-multilingual-mpnet-base-v2\" model = SentenceTransformer(model_name) shape_features = (n_lines, 768)", "model = SentenceTransformer(model_name) shape_features = (n_lines, 768) with h5py.File(out_fname, 'w') as fh_out: fh_out.create_dataset(\"features\",", "= scores[rank_idx, ranks[rank_idx, rank_predicted]] if not bnid_pred in bnids_predicted: bnids_predicted.append((bnid_pred,bnid_pred_score)) if len(bnids_predicted)>=topk: break", "action='store_true', help=\"\"\"Perform retrieval for the glosses in the validation set. (See paper for", "glosses_feats = torch.tensor(glosses_feats) if torch.cuda.is_available(): glosses_feats = glosses_feats.cuda() # load train/valid/test gloss splits", "): raise Exception(\"File already exists: '%s'. Please remove it manually to avoid tampering.\"%sbert_out_fname)", "ids, one per line (computed with `extract_glosses_visualsem.py`).\"\"\") p.add_argument('--input_valid', action='store_true', help=\"\"\"Perform retrieval for the", "os.path.isfile(out_fname): raise Exception(\"File already exists: '%s'. Please remove it manually to avoid tampering.\"%out_fname)", "= \"paraphrase-multilingual-mpnet-base-v2\" model = SentenceTransformer(model_name) shape_features = (n_lines, 768) with h5py.File(out_fname, 'w') as", "\"paraphrase-multilingual-mpnet-base-v2\" model = SentenceTransformer(model_name) with open(out_fname, 'w', encoding='utf8') as fh_out: ranks_predicted = []", "BNIDs for: \", n_examples) model_name = \"paraphrase-multilingual-mpnet-base-v2\" model = SentenceTransformer(model_name) with open(out_fname, 'w',", "= all_sentences[ from_idx: to_idx ] emb_sentences = model.encode(batch_sentences, convert_to_tensor=True) #test_queries(emb_sentences, all_sentences, model) fh_out[\"features\"][from_idx:to_idx]", "n_examples = len(all_input_sentences) print(\"Number of input examples to extract BNIDs for: \", n_examples)", "ranks = numpy.argsort(scores) # sort scores by cosine similarity (low to high) ranks", "fh_out[\"features\"][from_idx:to_idx] = emb_sentences.cpu().numpy() if __name__==\"__main__\": visualsem_path = os.path.dirname(os.path.realpath(__file__)) visualsem_nodes_path = \"%s/dataset/nodes.v2.json\"%visualsem_path visualsem_images_path =", "similarity (high to low) for rank_idx in range(len(idxs[:ranks.shape[0]])): bnids_predicted = [] for rank_predicted", "= \"%s/dataset/gloss_files/glosses.en.txt.bnids\"%visualsem_path os.makedirs(\"%s/dataset/gloss_files/\"%visualsem_path, exist_ok=True) p = argparse.ArgumentParser() p.add_argument('--input_files', type=str, nargs=\"+\", default=[\"example_data/queries.txt\"], help=\"\"\"Input file(s)", "for input_file in args.input_files: print(\"Processing input file: %s ...\"%input_file) sbert_out_fname = input_file+\".sentencebert.h5\" if", "extract BNIDs for: \", n_examples) model_name = \"paraphrase-multilingual-mpnet-base-v2\" model = SentenceTransformer(model_name) with open(out_fname,", "= [] for idxs_ in grouper(batch_size, range(n_examples)): idxs = [] queries = []", "\"\"\" if os.path.isfile(out_fname): raise Exception(\"File already exists: '%s'. Please remove it manually to", "= SentenceTransformer(model_name) with open(out_fname, 'w', encoding='utf8') as fh_out: ranks_predicted = [] for idxs_", "the validation set. (See paper for reference)\"\"\") p.add_argument('--input_test', action='store_true', help=\"\"\"Perform retrieval for the", "[] for rank_predicted in range(topk*10): bnid_pred = glosses_bnids[ ranks[rank_idx,rank_predicted] ] bnid_pred_score = scores[rank_idx,", "input file: %s ...\"%input_file) sbert_out_fname = input_file+\".sentencebert.h5\" if os.path.isfile( sbert_out_fname ): raise Exception(\"File", "file to write SBERT features for query. batch_size(int): Batch size for Sentence BERT.", "torch.cuda.is_available(): queries_embs = queries_embs.cuda() scores = util.pytorch_cos_sim(queries_embs, glosses_feats) scores = scores.cpu().numpy() ranks =", "args.batch_size, input_sentences) out_fname = input_file+\".bnids\" retrieve_nodes_given_sentences(out_fname, args.batch_size, input_sentences, gloss_bnids, glosses_feats, args.topk) # remove", "= numpy.argsort(scores) # sort scores by cosine similarity (low to high) ranks =", "[] for i in idxs_: if not i is None: idxs.append(i) queries.append( all_input_sentences[i]", "BERT. all_input_sentences(list[str]): All input sentences loaded from `input_file`. glosses_bnids(list[str]): All gloss BNids loaded", "i in idxs_: if not i is None: idxs.append(i) queries.append( all_input_sentences[i] ) queries_embs", "type=str, default=glosses_sentence_bert_path, help=\"\"\"HDF5 file containing glosses index computed with Sentence BERT (computed with", "from itertools import zip_longest from utils import grouper, load_sentences, load_bnids, load_visualsem_bnids def retrieve_nodes_given_sentences(out_fname,", "containing VisualSem knowledge graph.\") p.add_argument('--visualsem_nodes_path', type=str, default=visualsem_nodes_path, help=\"Path to file containing VisualSem nodes.\")", "for Sentence BERT. all_sentences(list[str]): Sentences to be used for retrieval. \"\"\" n_lines =", "model_name = \"paraphrase-multilingual-mpnet-base-v2\" model = SentenceTransformer(model_name) shape_features = (n_lines, 768) with h5py.File(out_fname, 'w')", "to write retrieved node ids to. batch_size(int): Batch size for Sentence BERT. all_input_sentences(list[str]):", "encoding='utf8') as fh_out: ranks_predicted = [] for idxs_ in grouper(batch_size, range(n_examples)): idxs =", "idxs_ in grouper(batch_size, range(n_examples)): idxs = [] queries = [] for i in", "= len(all_input_sentences) print(\"Number of input examples to extract BNIDs for: \", n_examples) model_name", "default=[\"example_data/queries.txt\"], help=\"\"\"Input file(s) to use for retrieval. Each line in each file should", "iii < topk-1: fh_out.write(\"\\t\") else: # iii == topk-1 fh_out.write(\"\\n\") def encode_query(out_fname, batch_size,", "in each file should contain a detokenized sentence.\"\"\") p.add_argument('--topk', type=int, default=1, help=\"Retrieve topk", "with `extract_glosses_visualsem.py`).\"\"\") p.add_argument('--glosses_bnids_path', type=str, default=glosses_bnids_path, help=\"\"\"Text file containing glosses BabelNet ids, one per", "All input sentences loaded from `input_file`. glosses_bnids(list[str]): All gloss BNids loaded from `args.glosses_bnids`.", "nodes for each input sentence.\") p.add_argument('--batch_size', type=int, default=1000) p.add_argument('--visualsem_path', type=str, default=visualsem_path, help=\"Path to", "= load_visualsem_bnids(args.visualsem_nodes_path, args.visualsem_images_path) gloss_bnids = load_bnids( args.glosses_bnids_path ) gloss_bnids = numpy.array(gloss_bnids, dtype='object') with", "# load gloss language splits language_splits = fh_glosses[\"language_idxs\"][:] for input_file in args.input_files: print(\"Processing", "visualsem_path = os.path.dirname(os.path.realpath(__file__)) visualsem_nodes_path = \"%s/dataset/nodes.v2.json\"%visualsem_path visualsem_images_path = \"%s/dataset/images/\"%visualsem_path glosses_sentence_bert_path = \"%s/dataset/gloss_files/glosses.en.txt.sentencebert.h5\"%visualsem_path glosses_bnids_path", "glosses in the test set. (See paper for reference)\"\"\") args = p.parse_args() #", "range(n_examples)): idxs = [] queries = [] for i in idxs_: if not", "BERT. topk(int): Number of nodes to retrieve for each input sentence. \"\"\" if", "train/valid/test gloss splits glosses_splits = fh_glosses[\"split_idxs\"][:] train_idxs = (glosses_splits==0).nonzero()[0] valid_idxs = (glosses_splits==1).nonzero()[0] test_idxs", "import zip_longest from utils import grouper, load_sentences, load_bnids, load_visualsem_bnids def retrieve_nodes_given_sentences(out_fname, batch_size, all_input_sentences,", "train_idxs = (glosses_splits==0).nonzero()[0] valid_idxs = (glosses_splits==1).nonzero()[0] test_idxs = (glosses_splits==2).nonzero()[0] # load gloss language", "Sentence BERT. all_sentences(list[str]): Sentences to be used for retrieval. \"\"\" n_lines = len(all_sentences)", "(low to high) ranks = ranks[:,::-1] # sort by cosine similarity (high to", "file: %s ...\"%input_file) sbert_out_fname = input_file+\".sentencebert.h5\" if os.path.isfile( sbert_out_fname ): raise Exception(\"File already", "model.encode(queries, convert_to_tensor=True) if torch.cuda.is_available(): queries_embs = queries_embs.cuda() scores = util.pytorch_cos_sim(queries_embs, glosses_feats) scores =", "iii == topk-1 fh_out.write(\"\\n\") def encode_query(out_fname, batch_size, all_sentences): \"\"\" out_fname(str): Output file to", "queries_embs = model.encode(queries, convert_to_tensor=True) if torch.cuda.is_available(): queries_embs = queries_embs.cuda() scores = util.pytorch_cos_sim(queries_embs, glosses_feats)", "for iii, (bnid, score) in enumerate(bnids_predicted[:topk]): fh_out.write(bnid+\"\\t\"+\"%.4f\"%score) if iii < topk-1: fh_out.write(\"\\t\") else:", "default=visualsem_path, help=\"Path to directory containing VisualSem knowledge graph.\") p.add_argument('--visualsem_nodes_path', type=str, default=visualsem_nodes_path, help=\"Path to", "= queries_embs.cuda() scores = util.pytorch_cos_sim(queries_embs, glosses_feats) scores = scores.cpu().numpy() ranks = numpy.argsort(scores) #", "in idxs_: if not i is None: idxs.append(i) queries.append( all_input_sentences[i] ) queries_embs =", "default=visualsem_nodes_path, help=\"Path to file containing VisualSem nodes.\") p.add_argument('--visualsem_images_path', type=str, default=visualsem_images_path, help=\"Path to directory", "loaded from `args.glosses_bnids`. Aligned with `glosses_feats`. glosses_feats(numpy.array): Numpy array with VisualSem gloss features", "convert_to_tensor=True) if torch.cuda.is_available(): queries_embs = queries_embs.cuda() scores = util.pytorch_cos_sim(queries_embs, glosses_feats) scores = scores.cpu().numpy()", "if torch.cuda.is_available(): queries_embs = queries_embs.cuda() scores = util.pytorch_cos_sim(queries_embs, glosses_feats) scores = scores.cpu().numpy() ranks", "= ranks[:,::-1] # sort by cosine similarity (high to low) for rank_idx in", "] emb_sentences = model.encode(batch_sentences, convert_to_tensor=True) #test_queries(emb_sentences, all_sentences, model) fh_out[\"features\"][from_idx:to_idx] = emb_sentences.cpu().numpy() if __name__==\"__main__\":", "'w', encoding='utf8') as fh_out: ranks_predicted = [] for idxs_ in grouper(batch_size, range(n_examples)): idxs", "default=visualsem_images_path, help=\"Path to directory containing VisualSem images.\") p.add_argument('--glosses_sentence_bert_path', type=str, default=glosses_sentence_bert_path, help=\"\"\"HDF5 file containing", "import defaultdict import h5py from sentence_transformers import SentenceTransformer, util import numpy import tqdm", "defaultdict import h5py from sentence_transformers import SentenceTransformer, util import numpy import tqdm from", "grouper(batch_size, range(n_examples)): idxs = [] queries = [] for i in idxs_: if", "one per line (computed with `extract_glosses_visualsem.py`).\"\"\") p.add_argument('--input_valid', action='store_true', help=\"\"\"Perform retrieval for the glosses", "of nodes to retrieve for each input sentence. \"\"\" if os.path.isfile(out_fname): raise Exception(\"File", "= (n_lines, 768) with h5py.File(out_fname, 'w') as fh_out: fh_out.create_dataset(\"features\", shape_features, dtype='float32', chunks=(1,768), maxshape=(None,", "scores = scores.cpu().numpy() ranks = numpy.argsort(scores) # sort scores by cosine similarity (low", "with Sentence BERT (computed with `extract_glosses_visualsem.py`).\"\"\") p.add_argument('--glosses_bnids_path', type=str, default=glosses_bnids_path, help=\"\"\"Text file containing glosses", "BabelNet ids, one per line (computed with `extract_glosses_visualsem.py`).\"\"\") p.add_argument('--input_valid', action='store_true', help=\"\"\"Perform retrieval for", "to low) for rank_idx in range(len(idxs[:ranks.shape[0]])): bnids_predicted = [] for rank_predicted in range(topk*10):", "= from_idx+batch_size if from_idx+batch_size <= n_lines else n_lines batch_sentences = all_sentences[ from_idx: to_idx", "input_file in args.input_files: print(\"Processing input file: %s ...\"%input_file) sbert_out_fname = input_file+\".sentencebert.h5\" if os.path.isfile(", "idxs = [] queries = [] for i in idxs_: if not i", "of input examples to extract BNIDs for: \", n_examples) model_name = \"paraphrase-multilingual-mpnet-base-v2\" model", "Sentence BERT. topk(int): Number of nodes to retrieve for each input sentence. \"\"\"", "emb_sentences.cpu().numpy() if __name__==\"__main__\": visualsem_path = os.path.dirname(os.path.realpath(__file__)) visualsem_nodes_path = \"%s/dataset/nodes.v2.json\"%visualsem_path visualsem_images_path = \"%s/dataset/images/\"%visualsem_path glosses_sentence_bert_path", "load_visualsem_bnids(args.visualsem_nodes_path, args.visualsem_images_path) gloss_bnids = load_bnids( args.glosses_bnids_path ) gloss_bnids = numpy.array(gloss_bnids, dtype='object') with h5py.File(args.glosses_sentence_bert_path,", "query. batch_size(int): Batch size for Sentence BERT. all_sentences(list[str]): Sentences to be used for", "args.visualsem_images_path) gloss_bnids = load_bnids( args.glosses_bnids_path ) gloss_bnids = numpy.array(gloss_bnids, dtype='object') with h5py.File(args.glosses_sentence_bert_path, 'r')", "%s ...\"%input_file) sbert_out_fname = input_file+\".sentencebert.h5\" if os.path.isfile( sbert_out_fname ): raise Exception(\"File already exists:", "file to write retrieved node ids to. batch_size(int): Batch size for Sentence BERT.", "BNids for iii, (bnid, score) in enumerate(bnids_predicted[:topk]): fh_out.write(bnid+\"\\t\"+\"%.4f\"%score) if iii < topk-1: fh_out.write(\"\\t\")", "to. batch_size(int): Batch size for Sentence BERT. all_input_sentences(list[str]): All input sentences loaded from", "load_bnids( args.glosses_bnids_path ) gloss_bnids = numpy.array(gloss_bnids, dtype='object') with h5py.File(args.glosses_sentence_bert_path, 'r') as fh_glosses: glosses_feats", "Sentence BERT (computed with `extract_glosses_visualsem.py`).\"\"\") p.add_argument('--glosses_bnids_path', type=str, default=glosses_bnids_path, help=\"\"\"Text file containing glosses BabelNet", "\"%s/dataset/nodes.v2.json\"%visualsem_path visualsem_images_path = \"%s/dataset/images/\"%visualsem_path glosses_sentence_bert_path = \"%s/dataset/gloss_files/glosses.en.txt.sentencebert.h5\"%visualsem_path glosses_bnids_path = \"%s/dataset/gloss_files/glosses.en.txt.bnids\"%visualsem_path os.makedirs(\"%s/dataset/gloss_files/\"%visualsem_path, exist_ok=True) p", "= (glosses_splits==1).nonzero()[0] test_idxs = (glosses_splits==2).nonzero()[0] # load gloss language splits language_splits = fh_glosses[\"language_idxs\"][:]", "os.path.dirname(os.path.realpath(__file__)) visualsem_nodes_path = \"%s/dataset/nodes.v2.json\"%visualsem_path visualsem_images_path = \"%s/dataset/images/\"%visualsem_path glosses_sentence_bert_path = \"%s/dataset/gloss_files/glosses.en.txt.sentencebert.h5\"%visualsem_path glosses_bnids_path = \"%s/dataset/gloss_files/glosses.en.txt.bnids\"%visualsem_path", "as fh_out: ranks_predicted = [] for idxs_ in grouper(batch_size, range(n_examples)): idxs = []", "= numpy.array(gloss_bnids, dtype='object') with h5py.File(args.glosses_sentence_bert_path, 'r') as fh_glosses: glosses_feats = fh_glosses[\"features\"][:] glosses_feats =", "input_sentences) out_fname = input_file+\".bnids\" retrieve_nodes_given_sentences(out_fname, args.batch_size, input_sentences, gloss_bnids, glosses_feats, args.topk) # remove temporary", "already exists: '%s'. Please remove it manually to avoid tampering.\"%sbert_out_fname) input_sentences = load_sentences(", "to use for retrieval. Each line in each file should contain a detokenized", "range(len(idxs[:ranks.shape[0]])): bnids_predicted = [] for rank_predicted in range(topk*10): bnid_pred = glosses_bnids[ ranks[rank_idx,rank_predicted] ]", "avoid tampering.\"%sbert_out_fname) input_sentences = load_sentences( input_file ) encode_query(sbert_out_fname, args.batch_size, input_sentences) out_fname = input_file+\".bnids\"", "(glosses_splits==1).nonzero()[0] test_idxs = (glosses_splits==2).nonzero()[0] # load gloss language splits language_splits = fh_glosses[\"language_idxs\"][:] for", "sentence_transformers import SentenceTransformer, util import numpy import tqdm from itertools import zip_longest from", "input_sentences = load_sentences( input_file ) encode_query(sbert_out_fname, args.batch_size, input_sentences) out_fname = input_file+\".bnids\" retrieve_nodes_given_sentences(out_fname, args.batch_size,", "computed with Sentence BERT. topk(int): Number of nodes to retrieve for each input", "args = p.parse_args() # load all nodes in VisualSem all_bnids = load_visualsem_bnids(args.visualsem_nodes_path, args.visualsem_images_path)", "fh_out.create_dataset(\"features\", shape_features, dtype='float32', chunks=(1,768), maxshape=(None, 768), compression=\"gzip\") for from_idx in tqdm.trange(0,n_lines,batch_size): to_idx =", "load train/valid/test gloss splits glosses_splits = fh_glosses[\"split_idxs\"][:] train_idxs = (glosses_splits==0).nonzero()[0] valid_idxs = (glosses_splits==1).nonzero()[0]", "'%s'. Please remove it manually to avoid tampering.\"%out_fname) n_examples = len(all_input_sentences) print(\"Number of", "load_sentences, load_bnids, load_visualsem_bnids def retrieve_nodes_given_sentences(out_fname, batch_size, all_input_sentences, glosses_bnids, glosses_feats, topk): \"\"\" out_fname(str): Output", "] bnid_pred_score = scores[rank_idx, ranks[rank_idx, rank_predicted]] if not bnid_pred in bnids_predicted: bnids_predicted.append((bnid_pred,bnid_pred_score)) if", ") encode_query(sbert_out_fname, args.batch_size, input_sentences) out_fname = input_file+\".bnids\" retrieve_nodes_given_sentences(out_fname, args.batch_size, input_sentences, gloss_bnids, glosses_feats, args.topk)", "for from_idx in tqdm.trange(0,n_lines,batch_size): to_idx = from_idx+batch_size if from_idx+batch_size <= n_lines else n_lines", "help=\"\"\"Perform retrieval for the glosses in the validation set. (See paper for reference)\"\"\")", "in enumerate(bnids_predicted[:topk]): fh_out.write(bnid+\"\\t\"+\"%.4f\"%score) if iii < topk-1: fh_out.write(\"\\t\") else: # iii == topk-1", "Aligned with `glosses_feats`. glosses_feats(numpy.array): Numpy array with VisualSem gloss features computed with Sentence", "write SBERT features for query. batch_size(int): Batch size for Sentence BERT. all_sentences(list[str]): Sentences", "(computed with `extract_glosses_visualsem.py`).\"\"\") p.add_argument('--input_valid', action='store_true', help=\"\"\"Perform retrieval for the glosses in the validation", "language_splits = fh_glosses[\"language_idxs\"][:] for input_file in args.input_files: print(\"Processing input file: %s ...\"%input_file) sbert_out_fname", "= model.encode(batch_sentences, convert_to_tensor=True) #test_queries(emb_sentences, all_sentences, model) fh_out[\"features\"][from_idx:to_idx] = emb_sentences.cpu().numpy() if __name__==\"__main__\": visualsem_path =", "...\"%input_file) sbert_out_fname = input_file+\".sentencebert.h5\" if os.path.isfile( sbert_out_fname ): raise Exception(\"File already exists: '%s'.", "= torch.tensor(glosses_feats) if torch.cuda.is_available(): glosses_feats = glosses_feats.cuda() # load train/valid/test gloss splits glosses_splits", "tqdm from itertools import zip_longest from utils import grouper, load_sentences, load_bnids, load_visualsem_bnids def", "Please remove it manually to avoid tampering.\"%sbert_out_fname) input_sentences = load_sentences( input_file ) encode_query(sbert_out_fname,", "= load_bnids( args.glosses_bnids_path ) gloss_bnids = numpy.array(gloss_bnids, dtype='object') with h5py.File(args.glosses_sentence_bert_path, 'r') as fh_glosses:", "input sentence.\") p.add_argument('--batch_size', type=int, default=1000) p.add_argument('--visualsem_path', type=str, default=visualsem_path, help=\"Path to directory containing VisualSem", "computed with Sentence BERT (computed with `extract_glosses_visualsem.py`).\"\"\") p.add_argument('--glosses_bnids_path', type=str, default=glosses_bnids_path, help=\"\"\"Text file containing", "sort by cosine similarity (high to low) for rank_idx in range(len(idxs[:ranks.shape[0]])): bnids_predicted =", "p.add_argument('--visualsem_path', type=str, default=visualsem_path, help=\"Path to directory containing VisualSem knowledge graph.\") p.add_argument('--visualsem_nodes_path', type=str, default=visualsem_nodes_path,", "bnid_pred = glosses_bnids[ ranks[rank_idx,rank_predicted] ] bnid_pred_score = scores[rank_idx, ranks[rank_idx, rank_predicted]] if not bnid_pred", "for retrieval. Each line in each file should contain a detokenized sentence.\"\"\") p.add_argument('--topk',", "with VisualSem gloss features computed with Sentence BERT. topk(int): Number of nodes to", "with h5py.File(args.glosses_sentence_bert_path, 'r') as fh_glosses: glosses_feats = fh_glosses[\"features\"][:] glosses_feats = torch.tensor(glosses_feats) if torch.cuda.is_available():", "out_fname = input_file+\".bnids\" retrieve_nodes_given_sentences(out_fname, args.batch_size, input_sentences, gloss_bnids, glosses_feats, args.topk) # remove temporary SBERT", "if not bnid_pred in bnids_predicted: bnids_predicted.append((bnid_pred,bnid_pred_score)) if len(bnids_predicted)>=topk: break # write top-k predicted", "to_idx ] emb_sentences = model.encode(batch_sentences, convert_to_tensor=True) #test_queries(emb_sentences, all_sentences, model) fh_out[\"features\"][from_idx:to_idx] = emb_sentences.cpu().numpy() if", "'r') as fh_glosses: glosses_feats = fh_glosses[\"features\"][:] glosses_feats = torch.tensor(glosses_feats) if torch.cuda.is_available(): glosses_feats =", "retrieve_nodes_given_sentences(out_fname, batch_size, all_input_sentences, glosses_bnids, glosses_feats, topk): \"\"\" out_fname(str): Output file to write retrieved", "use for retrieval. Each line in each file should contain a detokenized sentence.\"\"\")", "file should contain a detokenized sentence.\"\"\") p.add_argument('--topk', type=int, default=1, help=\"Retrieve topk nodes for", "import tqdm from itertools import zip_longest from utils import grouper, load_sentences, load_bnids, load_visualsem_bnids", "fh_out.write(bnid+\"\\t\"+\"%.4f\"%score) if iii < topk-1: fh_out.write(\"\\t\") else: # iii == topk-1 fh_out.write(\"\\n\") def", "import grouper, load_sentences, load_bnids, load_visualsem_bnids def retrieve_nodes_given_sentences(out_fname, batch_size, all_input_sentences, glosses_bnids, glosses_feats, topk): \"\"\"", "= (glosses_splits==0).nonzero()[0] valid_idxs = (glosses_splits==1).nonzero()[0] test_idxs = (glosses_splits==2).nonzero()[0] # load gloss language splits", "all_sentences, model) fh_out[\"features\"][from_idx:to_idx] = emb_sentences.cpu().numpy() if __name__==\"__main__\": visualsem_path = os.path.dirname(os.path.realpath(__file__)) visualsem_nodes_path = \"%s/dataset/nodes.v2.json\"%visualsem_path", "args.glosses_bnids_path ) gloss_bnids = numpy.array(gloss_bnids, dtype='object') with h5py.File(args.glosses_sentence_bert_path, 'r') as fh_glosses: glosses_feats =", "retrieval. \"\"\" n_lines = len(all_sentences) model_name = \"paraphrase-multilingual-mpnet-base-v2\" model = SentenceTransformer(model_name) shape_features =", "language splits language_splits = fh_glosses[\"language_idxs\"][:] for input_file in args.input_files: print(\"Processing input file: %s", "line (computed with `extract_glosses_visualsem.py`).\"\"\") p.add_argument('--input_valid', action='store_true', help=\"\"\"Perform retrieval for the glosses in the", "in args.input_files: print(\"Processing input file: %s ...\"%input_file) sbert_out_fname = input_file+\".sentencebert.h5\" if os.path.isfile( sbert_out_fname", "for: \", n_examples) model_name = \"paraphrase-multilingual-mpnet-base-v2\" model = SentenceTransformer(model_name) with open(out_fname, 'w', encoding='utf8')", "glosses_bnids(list[str]): All gloss BNids loaded from `args.glosses_bnids`. Aligned with `glosses_feats`. glosses_feats(numpy.array): Numpy array", "to extract BNIDs for: \", n_examples) model_name = \"paraphrase-multilingual-mpnet-base-v2\" model = SentenceTransformer(model_name) with", "len(all_input_sentences) print(\"Number of input examples to extract BNIDs for: \", n_examples) model_name =", "collections import defaultdict import h5py from sentence_transformers import SentenceTransformer, util import numpy import", "contain a detokenized sentence.\"\"\") p.add_argument('--topk', type=int, default=1, help=\"Retrieve topk nodes for each input", "sentence.\"\"\") p.add_argument('--topk', type=int, default=1, help=\"Retrieve topk nodes for each input sentence.\") p.add_argument('--batch_size', type=int,", "load gloss language splits language_splits = fh_glosses[\"language_idxs\"][:] for input_file in args.input_files: print(\"Processing input", "torch import sys import os import json from collections import defaultdict import h5py", "retrieval. Each line in each file should contain a detokenized sentence.\"\"\") p.add_argument('--topk', type=int,", "to directory containing VisualSem images.\") p.add_argument('--glosses_sentence_bert_path', type=str, default=glosses_sentence_bert_path, help=\"\"\"HDF5 file containing glosses index", "Exception(\"File already exists: '%s'. Please remove it manually to avoid tampering.\"%out_fname) n_examples =", "= fh_glosses[\"split_idxs\"][:] train_idxs = (glosses_splits==0).nonzero()[0] valid_idxs = (glosses_splits==1).nonzero()[0] test_idxs = (glosses_splits==2).nonzero()[0] # load", "json from collections import defaultdict import h5py from sentence_transformers import SentenceTransformer, util import", "queries_embs.cuda() scores = util.pytorch_cos_sim(queries_embs, glosses_feats) scores = scores.cpu().numpy() ranks = numpy.argsort(scores) # sort", "glosses BabelNet ids, one per line (computed with `extract_glosses_visualsem.py`).\"\"\") p.add_argument('--input_valid', action='store_true', help=\"\"\"Perform retrieval", "Each line in each file should contain a detokenized sentence.\"\"\") p.add_argument('--topk', type=int, default=1,", "import json from collections import defaultdict import h5py from sentence_transformers import SentenceTransformer, util", "\"%s/dataset/images/\"%visualsem_path glosses_sentence_bert_path = \"%s/dataset/gloss_files/glosses.en.txt.sentencebert.h5\"%visualsem_path glosses_bnids_path = \"%s/dataset/gloss_files/glosses.en.txt.bnids\"%visualsem_path os.makedirs(\"%s/dataset/gloss_files/\"%visualsem_path, exist_ok=True) p = argparse.ArgumentParser() p.add_argument('--input_files'," ]
[ "255], [30, 285], ...] y_ind: List[List[int]] = calculate_indexes(10, 235, y, y) # [[0,", ":param cells: Iterable of cells :param nms_threshold: cell iou threshold :return: Iterable of", "is not None: image_base: Tensor = correct_pixel_size(image_base, pixel_size) #model expects pixel size of", "nms_threshold: float) -> List[Cell]: \"\"\" Perforns non maximum supression on the resulting cell", "entire image. :param *str* f: path to image by which to analyze :param", "# Evaluate Deep Learning Model out: Dict[str, Tensor] = model(image.float())[0] scores: Tensor =", "Tensor = image_base[:, x[0]:x[1], y[0]:y[1]].unsqueeze(0) # If the image has nothing in it", "'cuda': warn('CUDA: GPU successfully initialized!', color='green') else: warn('WARNING: GPU not present or CUDA", "faster rcnn detection on the entire image. :param *str* f: path to image", "in cells]) # number of ohc ihc = sum([int(c.type == 'IHC') for c", "cropped regions c, x, y = image_base.shape image_base = torch.cat((torch.zeros((1, x, y), device=device),", "285], ...] y_ind: List[List[int]] = calculate_indexes(10, 235, y, y) # [[0, 255], [30,", "speed for x, y in tqdm(product(x_ind, y_ind), total=total, desc='Detecting: '): # Load and", "computation. ' 'Analysis may be slow.', color='yellow') # Initalize the model... model =", "Iterable of cells \"\"\" # nms to get rid of cells boxes =", "warn('WARNING: Predicted Cochlear Distance is below 4000um. Not sufficient ' 'information to determine", "= c.boxes scores[i] = c.scores ind = torchvision.ops.nms(boxes, scores, nms_threshold) # need to", "curvature is None: warn('WARNING: All three methods to predict hair cell path have", "'information to determine cell frequency.', color='yellow') xml = get_xml(f) if f.endswith('.lif') else None", "c.boxes scores[i] = c.scores ind = torchvision.ops.nms(boxes, scores, nms_threshold) # need to pop", "detection algorithm. Loads arbitrarily large 2d image and performs iterative faster rcnn detection", "product import numpy as np from hcat.lib.explore_lif import get_xml import torchvision.ops import skimage.io", "on the resulting cell predictions :param cells: Iterable of cells :param nms_threshold: cell", "remove a cell if its far away from curve else: curvature, distance, apex", "[30, 285], ...] y_ind: List[List[int]] = calculate_indexes(10, 235, y, y) # [[0, 255],", "as io import os.path from typing import Optional, List, Dict # DOCUMENTED def", "and performs iterative faster rcnn detection on the entire image. :param *str* f:", "c, x, y = image_base.shape image_base = torch.cat((torch.zeros((1, x, y), device=device), image_base), dim=0)", "not c._distance_is_far_away] # remove a cell if its far away from curve else:", "= calculate_indexes(10, 235, y, y) # [[0, 255], [30, 285], ...] total: int", "Tensor] = model(image.float())[0] scores: Tensor = out['scores'].cpu() boxes: Tensor = out['boxes'].cpu() labels: Tensor", "cells = [] add_cell = cells.append # stupid but done for speed for", "tissue... if distance is not None and distance.max() > 4000: for c in", "around zero image_base.sub_(0.5).div_(0.5) if device == 'cuda': warn('CUDA: GPU successfully initialized!', color='green') else:", "3]] += x[0] # center x, center y, width, height centers: Tensor =", "add_cell = cells.append # stupid but done for speed for x, y in", "slow.', color='yellow') # Initalize the model... model = FasterRCNN_from_url(url='https://github.com/buswinka/hcat/blob/master/modelfiles/detection.trch?raw=true', device=device) model.eval() # Initalize", "score in enumerate(scores): if score > cell_detection_threshold: add_cell(Cell(id=cell_id, loc=torch.tensor([0, cx[i], cy[i], 0]), image=None,", "load(f, 'TileScan 1 Merged', verbose=True) # from hcat.lib.utils image_base = image_base[[2, 3],...].max(-1) if", "of cells :param nms_threshold: cell iou threshold :return: Iterable of cells \"\"\" #", "# normalize around zero image_base.sub_(0.5).div_(0.5) if device == 'cuda': warn('CUDA: GPU successfully initialized!',", "dtype = image_base.dtype if dtype is None else dtype scale: int = hcat.lib.utils.get_dtype_offset(dtype)", "load, cochlea_to_xml, correct_pixel_size, scale_to_hair_cell_diameter from hcat.lib.cell import Cell from hcat.lib.cochlea import Cochlea from", "c in enumerate(cells): boxes[i, :] = c.boxes scores[i] = c.scores ind = torchvision.ops.nms(boxes,", "with torch.no_grad(): # Load and preprocess Image image_base = load(f, 'TileScan 1 Merged',", "from hcat.lib.cochlea import Cochlea from hcat.backends.detection import FasterRCNN_from_url from hcat.backends.detection import HairCellFasterRCNN from", "{ohc}\\n IHC: {ihc}' ) max_projection: Tensor = image_base[[1], ...].mul(0.5).add(0.5).unsqueeze(-1).cpu() curvature, distance, apex =", "Tensor = image_base[[1], ...].mul(0.5).add(0.5).unsqueeze(-1).cpu() curvature, distance, apex = predict_curvature(max_projection, cells, curve_path) if curvature", "which to analyze :param *float* cell_detection_threshold: cells below threshold are rejected :param *float*", "out['scores'].cpu() boxes: Tensor = out['boxes'].cpu() labels: Tensor = out['labels'].cpu() # The model output", "np.concatenate((temp, image_base)) / scale * 255 c, x, y = image_base.shape print( f'DONE:", "model.eval() # Initalize curvature detection predict_curvature = hcat.lib.functional.PredictCurvature(erode=3) # Get the indicies for", "cell_id += 1 # some cells may overlap. We remove cells after analysis", "below 4000um. Not sufficient ' 'information to determine cell frequency.', color='yellow') xml =", "remove weird cell ID's for i, c in enumerate(cells): c.id = i+1 #", "cells]) # number of ohc ihc = sum([int(c.type == 'IHC') for c in", "performance.', color='yellow') with torch.no_grad(): # Load and preprocess Image image_base = load(f, 'TileScan", "new shape of: {image_base.shape}') # normalize around zero image_base.sub_(0.5).div_(0.5) if device == 'cuda':", "warn('WARNING: Pixel Size is not set. Defaults to 288.88 nm x/y. ' 'Consider", "= centers[:, 0] cy = centers[:, 1] for i, score in enumerate(scores): if", "for GPU accelerated computation. ' 'Analysis may be slow.', color='yellow') # Initalize the", "regions c, x, y = image_base.shape image_base = torch.cat((torch.zeros((1, x, y), device=device), image_base),", "size of 288.88nm with a new shape of: {image_base.shape}') # normalize around zero", "a lot of tissue... if distance is not None and distance.max() > 4000:", "tensor ind_bool = torch.zeros(len(cells)) ind_bool[ind] = 1 for i, val in enumerate(ind_bool): if", "calculate_indexes(10, 235, y, y) # [[0, 255], [30, 285], ...] total: int =", "to predict hair cell path have failed. Frequency Mapping functionality is ' 'limited.", "List[Cell], nms_threshold: float) -> List[Cell]: \"\"\" Perforns non maximum supression on the resulting", "for speed if image.max() == -1: continue # Evaluate Deep Learning Model out:", "= None, cell_detection_threshold: float = 0.86, dtype=None, nms_threshold: float = 0.2, save_xml=False, save_fig=False,", "c in enumerate(cells): c.id = i+1 # Store in compressible object for further", "skimage.io as io import os.path from typing import Optional, List, Dict # DOCUMENTED", "y) # [[0, 255], [30, 285], ...] total: int = len(x_ind) * len(y_ind)", "GPU successfully initialized!', color='green') else: warn('WARNING: GPU not present or CUDA is not", "iou threshold :return: Iterable of cells \"\"\" # nms to get rid of", "torch from torch import Tensor from tqdm import tqdm from itertools import product", "max value less than 1/3 the scale factor for bit depth. Image Max:", "if not c._distance_is_far_away] # remove a cell if its far away from curve", "Defaults to 288.88 nm x/y. ' 'Consider suplying value for optimal performance.', color='yellow')", "import warn import torch from torch import Tensor from tqdm import tqdm from", "image_base.ndim == 4 else image_base shape = list(image_base.shape) shape[0] = 1 dtype =", "x, y = image_base.shape print( f'DONE: shape: {image_base.shape}, min: {image_base.min()}, max: {image_base.max()}, dtype:", "Learning Model out: Dict[str, Tensor] = model(image.float())[0] scores: Tensor = out['scores'].cpu() boxes: Tensor", "x are flipped. Breaks otherwise. boxes[:, [0, 2]] += y[0] boxes[:, [1, 3]]", "import hcat.lib.functional import hcat.lib.functional as functional from hcat.lib.utils import calculate_indexes, load, cochlea_to_xml, correct_pixel_size,", "image_base)) / scale * 255 c, x, y = image_base.shape print( f'DONE: shape:", "distance, apex = predict_curvature(max_projection, cells, curve_path) if curvature is None: warn('WARNING: All three", "float = 0.2, save_xml=False, save_fig=False, pixel_size=None, cell_diameter=None): \"\"\" 2D hair cell detection algorithm.", "import calculate_indexes, load, cochlea_to_xml, correct_pixel_size, scale_to_hair_cell_diameter from hcat.lib.cell import Cell from hcat.lib.cochlea import", "indicies for evaluating cropped regions c, x, y = image_base.shape image_base = torch.cat((torch.zeros((1,", "on the entire image. :param *str* f: path to image by which to", "otherwise. boxes[:, [0, 2]] += y[0] boxes[:, [1, 3]] += x[0] # center", "import FasterRCNN_from_url from hcat.backends.detection import HairCellFasterRCNN from hcat.lib.utils import warn import torch from", "f is None: warn('ERROR: No File to Analyze... \\nAborting.', color='red') return None if", "y = image_base.shape image_base = torch.cat((torch.zeros((1, x, y), device=device), image_base), dim=0) x_ind: List[List[int]]", "< scale * 0.33: warn(f'WARNING: Image max value less than 1/3 the scale", "centers[:, 0] cy = centers[:, 1] for i, score in enumerate(scores): if score", "not None: image_base: Tensor = scale_to_hair_cell_diameter(image_base, cell_diameter) print(f'Rescaled Image to match pixel size", "to 288.88 nm x/y. ' 'Consider suplying value for optimal performance.', color='yellow') with", "of 288.88nm with a new shape of: {image_base.shape}') # normalize around zero image_base.sub_(0.5).div_(0.5)", "filename=filename, path=f, analysis_type='detect', leica_metadata=xml, im_shape=image_base.shape, cochlear_distance=distance, curvature=curvature, cells=cells, apex=apex) c.write_csv() if save_xml: cochlea_to_xml(c)", "curvature detection predict_curvature = hcat.lib.functional.PredictCurvature(erode=3) # Get the indicies for evaluating cropped regions", "from hcat.lib.utils import calculate_indexes, load, cochlea_to_xml, correct_pixel_size, scale_to_hair_cell_diameter from hcat.lib.cell import Cell from", "hcat.lib.cochlea import Cochlea from hcat.backends.detection import FasterRCNN_from_url from hcat.backends.detection import HairCellFasterRCNN from hcat.lib.utils", "for i, val in enumerate(ind_bool): if val == 0: cells[i] = None return", "color='yellow') with torch.no_grad(): # Load and preprocess Image image_base = load(f, 'TileScan 1", "ID's for i, c in enumerate(cells): c.id = i+1 # Store in compressible", "hcat.lib.cell import Cell from hcat.lib.cochlea import Cochlea from hcat.backends.detection import FasterRCNN_from_url from hcat.backends.detection", "= correct_pixel_size(image_base, pixel_size) #model expects pixel size of 288.88 print(f'Rescaled Image to match", "temp = np.zeros(shape) temp = np.concatenate((temp, image_base)) / scale * 255 c, x,", "image_base: Tensor = scale_to_hair_cell_diameter(image_base, cell_diameter) print(f'Rescaled Image to match pixel size of 288.88nm", "to match pixel size of 288.88nm with a new shape of: {image_base.shape}') #", "hcat.lib.explore_lif import get_xml import torchvision.ops import skimage.io as io import os.path from typing", "pixel_size is not None: image_base: Tensor = correct_pixel_size(image_base, pixel_size) #model expects pixel size", "{ihc}' ) max_projection: Tensor = image_base[[1], ...].mul(0.5).add(0.5).unsqueeze(-1).cpu() curvature, distance, apex = predict_curvature(max_projection, cells,", "dtype=None, nms_threshold: float = 0.2, save_xml=False, save_fig=False, pixel_size=None, cell_diameter=None): \"\"\" 2D hair cell", "hcat.lib.utils import warn import torch from torch import Tensor from tqdm import tqdm", "y, width, height centers: Tensor = torchvision.ops.box_convert(boxes, 'xyxy', 'cxcywh').cpu() cx = centers[:, 0]", "works if there is a lot of tissue... if distance is not None", "torch.no_grad(): # Load and preprocess Image image_base = load(f, 'TileScan 1 Merged', verbose=True)", "has nothing in it we can skip for speed if image.max() == -1:", "import product import numpy as np from hcat.lib.explore_lif import get_xml import torchvision.ops import", "= model(image.float())[0] scores: Tensor = out['scores'].cpu() boxes: Tensor = out['boxes'].cpu() labels: Tensor =", "x) # [[0, 255], [30, 285], ...] y_ind: List[List[int]] = calculate_indexes(10, 235, y,", "image: Tensor = image_base[:, x[0]:x[1], y[0]:y[1]].unsqueeze(0) # If the image has nothing in", "1.5 time Image max.', color='yellow') scale = image_base.max() * 1.5 image_base = torch.from_numpy(image_base.astype(np.uint16)", "object for further use c = Cochlea(mask=None, filename=filename, path=f, analysis_type='detect', leica_metadata=xml, im_shape=image_base.shape, cochlear_distance=distance,", "image has nothing in it we can skip for speed if image.max() ==", "y[0] boxes[:, [1, 3]] += x[0] # center x, center y, width, height", "...] total: int = len(x_ind) * len(y_ind) # Initalize other small things cell_id", "*float* nms_threshold: iou rejection threshold for nms. :return: *Cochlea* object containing data of", "import numpy as np from hcat.lib.explore_lif import get_xml import torchvision.ops import skimage.io as", "Size is not set. Defaults to 288.88 nm x/y. ' 'Consider suplying value", "image_base[[2, 3],...].max(-1) if image_base.ndim == 4 else image_base shape = list(image_base.shape) shape[0] =", "new shape of: {image_base.shape}') elif cell_diameter is not None: image_base: Tensor = scale_to_hair_cell_diameter(image_base,", "_cell_nms(cells: List[Cell], nms_threshold: float) -> List[Cell]: \"\"\" Perforns non maximum supression on the", "f' Scale Factor: {scale}, dtype: {dtype}. Readjusting scale to 1.5 time Image max.',", "os.path from typing import Optional, List, Dict # DOCUMENTED def _detect(f: str, curve_path:", "= torch.zeros(len(cells)) for i, c in enumerate(cells): boxes[i, :] = c.boxes scores[i] =", "ind = torchvision.ops.nms(boxes, scores, nms_threshold) # need to pop off list elements from", "= torch.zeros(len(cells)) ind_bool[ind] = 1 for i, val in enumerate(ind_bool): if val ==", "else image_base shape = list(image_base.shape) shape[0] = 1 dtype = image_base.dtype if dtype", "scores = torch.zeros(len(cells)) for i, c in enumerate(cells): boxes[i, :] = c.boxes scores[i]", "FasterRCNN_from_url(url='https://github.com/buswinka/hcat/blob/master/modelfiles/detection.trch?raw=true', device=device) model.eval() # Initalize curvature detection predict_curvature = hcat.lib.functional.PredictCurvature(erode=3) # Get the", "model output coords with respect to the crop of image_base. We have to", "1.5 image_base = torch.from_numpy(image_base.astype(np.uint16) / scale).to(device) if pixel_size is not None: image_base: Tensor", "val in enumerate(ind_bool): if val == 0: cells[i] = None return [c for", "None and distance.max() > 4000: for c in cells: c.calculate_frequency(curvature[[0, 1], :], distance)", "maximum supression on the resulting cell predictions :param cells: Iterable of cells :param", "from hcat.lib.utils import warn import torch from torch import Tensor from tqdm import", "scale * 0.33: warn(f'WARNING: Image max value less than 1/3 the scale factor", "the scale factor for bit depth. Image Max: {image_base.max()},' f' Scale Factor: {scale},", "filename = os.path.split(f)[-1] # remove weird cell ID's for i, c in enumerate(cells):", "is not set. Defaults to 288.88 nm x/y. ' 'Consider suplying value for", "= load(f, 'TileScan 1 Merged', verbose=True) # from hcat.lib.utils image_base = image_base[[2, 3],...].max(-1)", "= np.concatenate((temp, image_base)) / scale * 255 c, x, y = image_base.shape print(", "predict_curvature(max_projection, cells, curve_path) if curvature is None: warn('WARNING: All three methods to predict", "mask=None, cell_type='OHC' if labels[i] == 1 else 'IHC', boxes=boxes[i, :], scores=scores[i])) cell_id +=", "in enumerate(ind_bool): if val == 0: cells[i] = None return [c for c", "from torch import Tensor from tqdm import tqdm from itertools import product import", "cells after analysis is complete. cells: List[Cell] = _cell_nms(cells, nms_threshold) ohc = sum([int(c.type", "we can skip for speed if image.max() == -1: continue # Evaluate Deep", "not set. Defaults to 288.88 nm x/y. ' 'Consider suplying value for optimal", "if f.endswith('.lif') else None filename = os.path.split(f)[-1] # remove weird cell ID's for", "image_base.shape image_base = torch.cat((torch.zeros((1, x, y), device=device), image_base), dim=0) x_ind: List[List[int]] = calculate_indexes(10,", "model evaluation image: Tensor = image_base[:, x[0]:x[1], y[0]:y[1]].unsqueeze(0) # If the image has", "CUDA is not correctly intialized for GPU accelerated computation. ' 'Analysis may be", "cell_type='OHC' if labels[i] == 1 else 'IHC', boxes=boxes[i, :], scores=scores[i])) cell_id += 1", "= i+1 # Store in compressible object for further use c = Cochlea(mask=None,", "import skimage.io as io import os.path from typing import Optional, List, Dict #", "import Cochlea from hcat.backends.detection import FasterRCNN_from_url from hcat.backends.detection import HairCellFasterRCNN from hcat.lib.utils import", "from typing import Optional, List, Dict # DOCUMENTED def _detect(f: str, curve_path: str", "'Consider suplying value for optimal performance.', color='yellow') with torch.no_grad(): # Load and preprocess", "with a new shape of: {image_base.shape}') elif cell_diameter is not None: image_base: Tensor", "scale_to_hair_cell_diameter from hcat.lib.cell import Cell from hcat.lib.cochlea import Cochlea from hcat.backends.detection import FasterRCNN_from_url", "* 0.33: warn(f'WARNING: Image max value less than 1/3 the scale factor for", "import HairCellFasterRCNN from hcat.lib.utils import warn import torch from torch import Tensor from", "functional from hcat.lib.utils import calculate_indexes, load, cochlea_to_xml, correct_pixel_size, scale_to_hair_cell_diameter from hcat.lib.cell import Cell", "image_base.max() < scale * 0.33: warn(f'WARNING: Image max value less than 1/3 the", "boxes[:, [1, 3]] += x[0] # center x, center y, width, height centers:", ":param *float* cell_detection_threshold: cells below threshold are rejected :param *float* nms_threshold: iou rejection", "0.33: warn(f'WARNING: Image max value less than 1/3 the scale factor for bit", "hcat.lib.functional as functional from hcat.lib.utils import calculate_indexes, load, cochlea_to_xml, correct_pixel_size, scale_to_hair_cell_diameter from hcat.lib.cell", ":param *float* nms_threshold: iou rejection threshold for nms. :return: *Cochlea* object containing data", "torch.zeros(len(cells)) for i, c in enumerate(cells): boxes[i, :] = c.boxes scores[i] = c.scores", "image_base shape = list(image_base.shape) shape[0] = 1 dtype = image_base.dtype if dtype is", "*Cochlea* object containing data of analysis. \"\"\" print('Initializing hair cell detection algorithm...') if", "cell ID's for i, c in enumerate(cells): c.id = i+1 # Store in", "bit depth. Image Max: {image_base.max()},' f' Scale Factor: {scale}, dtype: {dtype}. Readjusting scale", "-> List[Cell]: \"\"\" Perforns non maximum supression on the resulting cell predictions :param", "than 1/3 the scale factor for bit depth. Image Max: {image_base.max()},' f' Scale", "crop for ML model evaluation image: Tensor = image_base[:, x[0]:x[1], y[0]:y[1]].unsqueeze(0) # If", "[[0, 255], [30, 285], ...] total: int = len(x_ind) * len(y_ind) # Initalize", "depth. Image Max: {image_base.max()},' f' Scale Factor: {scale}, dtype: {dtype}. Readjusting scale to", "apex = None, None, None warn('WARNING: Predicted Cochlear Distance is below 4000um. Not", "import Tensor from tqdm import tqdm from itertools import product import numpy as", "...].mul(0.5).add(0.5).unsqueeze(-1).cpu() curvature, distance, apex = predict_curvature(max_projection, cells, curve_path) if curvature is None: warn('WARNING:", "== 'cuda': warn('CUDA: GPU successfully initialized!', color='green') else: warn('WARNING: GPU not present or", "[[0, 255], [30, 285], ...] y_ind: List[List[int]] = calculate_indexes(10, 235, y, y) #", "We remove cells after analysis is complete. cells: List[Cell] = _cell_nms(cells, nms_threshold) ohc", "# some cells may overlap. We remove cells after analysis is complete. cells:", "supression on the resulting cell predictions :param cells: Iterable of cells :param nms_threshold:", "= predict_curvature(max_projection, cells, curve_path) if curvature is None: warn('WARNING: All three methods to", ") max_projection: Tensor = image_base[[1], ...].mul(0.5).add(0.5).unsqueeze(-1).cpu() curvature, distance, apex = predict_curvature(max_projection, cells, curve_path)", "x/y. ' 'Consider suplying value for optimal performance.', color='yellow') with torch.no_grad(): # Load", "print( f'DONE: shape: {image_base.shape}, min: {image_base.min()}, max: {image_base.max()}, dtype: {image_base.dtype}') if image_base.max() <", "{image_base.shape}, min: {image_base.min()}, max: {image_base.max()}, dtype: {image_base.dtype}') if image_base.max() < scale * 0.33:", "c in cells]) # number of ohc ihc = sum([int(c.type == 'IHC') for", "= None, None, None warn('WARNING: Predicted Cochlear Distance is below 4000um. Not sufficient", "image=None, mask=None, cell_type='OHC' if labels[i] == 1 else 'IHC', boxes=boxes[i, :], scores=scores[i])) cell_id", "torch.from_numpy(image_base.astype(np.uint16) / scale).to(device) if pixel_size is not None: image_base: Tensor = correct_pixel_size(image_base, pixel_size)", "None: image_base: Tensor = scale_to_hair_cell_diameter(image_base, cell_diameter) print(f'Rescaled Image to match pixel size of", "pixel_size) #model expects pixel size of 288.88 print(f'Rescaled Image to match pixel size", "image_base = torch.from_numpy(image_base.astype(np.uint16) / scale).to(device) if pixel_size is not None: image_base: Tensor =", "4)) scores = torch.zeros(len(cells)) for i, c in enumerate(cells): boxes[i, :] = c.boxes", "value for optimal performance.', color='yellow') with torch.no_grad(): # Load and preprocess Image image_base", "evaluation image: Tensor = image_base[:, x[0]:x[1], y[0]:y[1]].unsqueeze(0) # If the image has nothing", "No File to Analyze... \\nAborting.', color='red') return None if not pixel_size: warn('WARNING: Pixel", "FasterRCNN_from_url from hcat.backends.detection import HairCellFasterRCNN from hcat.lib.utils import warn import torch from torch", "List, Dict # DOCUMENTED def _detect(f: str, curve_path: str = None, cell_detection_threshold: float", "small things cell_id = 1 cells = [] add_cell = cells.append # stupid", "hair cell path have failed. Frequency Mapping functionality is ' 'limited. Consider Manual", "Image max value less than 1/3 the scale factor for bit depth. Image", ":return: Iterable of cells \"\"\" # nms to get rid of cells boxes", "# from hcat.lib.utils image_base = image_base[[2, 3],...].max(-1) if image_base.ndim == 4 else image_base", "if save_fig: c.make_detect_fig(image_base) print('') return c def _cell_nms(cells: List[Cell], nms_threshold: float) -> List[Cell]:", "*float* cell_detection_threshold: cells below threshold are rejected :param *float* nms_threshold: iou rejection threshold", "c._distance_is_far_away] # remove a cell if its far away from curve else: curvature,", "is not None: image_base: Tensor = scale_to_hair_cell_diameter(image_base, cell_diameter) print(f'Rescaled Image to match pixel", "= 0.86, dtype=None, nms_threshold: float = 0.2, save_xml=False, save_fig=False, pixel_size=None, cell_diameter=None): \"\"\" 2D", "for optimal performance.', color='yellow') with torch.no_grad(): # Load and preprocess Image image_base =", "im_shape=image_base.shape, cochlear_distance=distance, curvature=curvature, cells=cells, apex=apex) c.write_csv() if save_xml: cochlea_to_xml(c) if save_fig: c.make_detect_fig(image_base) print('')", "hcat.lib.functional.PredictCurvature(erode=3) # Get the indicies for evaluating cropped regions c, x, y =", "'xyxy', 'cxcywh').cpu() cx = centers[:, 0] cy = centers[:, 1] for i, score", "center x, center y, width, height centers: Tensor = torchvision.ops.box_convert(boxes, 'xyxy', 'cxcywh').cpu() cx", "1 else 'IHC', boxes=boxes[i, :], scores=scores[i])) cell_id += 1 # some cells may", "= os.path.split(f)[-1] # remove weird cell ID's for i, c in enumerate(cells): c.id", "Merged', verbose=True) # from hcat.lib.utils image_base = image_base[[2, 3],...].max(-1) if image_base.ndim == 4", "shape = list(image_base.shape) shape[0] = 1 dtype = image_base.dtype if dtype is None", "elif cell_diameter is not None: image_base: Tensor = scale_to_hair_cell_diameter(image_base, cell_diameter) print(f'Rescaled Image to", "nothing in it we can skip for speed if image.max() == -1: continue", "1 for i, val in enumerate(ind_bool): if val == 0: cells[i] = None", "= 0.2, save_xml=False, save_fig=False, pixel_size=None, cell_diameter=None): \"\"\" 2D hair cell detection algorithm. Loads", "width, height centers: Tensor = torchvision.ops.box_convert(boxes, 'xyxy', 'cxcywh').cpu() cx = centers[:, 0] cy", "ind_bool[ind] = 1 for i, val in enumerate(ind_bool): if val == 0: cells[i]", "# number of ihc print(f'Total Cells: {len(cells)}\\n OHC: {ohc}\\n IHC: {ihc}' ) max_projection:", "cell_diameter=None): \"\"\" 2D hair cell detection algorithm. Loads arbitrarily large 2d image and", "-1: continue # Evaluate Deep Learning Model out: Dict[str, Tensor] = model(image.float())[0] scores:", "sufficient ' 'information to determine cell frequency.', color='yellow') xml = get_xml(f) if f.endswith('.lif')", "predictions :param cells: Iterable of cells :param nms_threshold: cell iou threshold :return: Iterable", "{image_base.min()}, max: {image_base.max()}, dtype: {image_base.dtype}') if image_base.max() < scale * 0.33: warn(f'WARNING: Image", "an int64 tensor ind_bool = torch.zeros(len(cells)) ind_bool[ind] = 1 for i, val in", "Dict[str, Tensor] = model(image.float())[0] scores: Tensor = out['scores'].cpu() boxes: Tensor = out['boxes'].cpu() labels:", "\"\"\" Perforns non maximum supression on the resulting cell predictions :param cells: Iterable", "it we can skip for speed if image.max() == -1: continue # Evaluate", "be slow.', color='yellow') # Initalize the model... model = FasterRCNN_from_url(url='https://github.com/buswinka/hcat/blob/master/modelfiles/detection.trch?raw=true', device=device) model.eval() #", "pop off list elements from an int64 tensor ind_bool = torch.zeros(len(cells)) ind_bool[ind] =", "suplying value for optimal performance.', color='yellow') with torch.no_grad(): # Load and preprocess Image", "# [[0, 255], [30, 285], ...] total: int = len(x_ind) * len(y_ind) #", "= 1 for i, val in enumerate(ind_bool): if val == 0: cells[i] =", "_cell_nms(cells, nms_threshold) ohc = sum([int(c.type == 'OHC') for c in cells]) # number", "'TileScan 1 Merged', verbose=True) # from hcat.lib.utils image_base = image_base[[2, 3],...].max(-1) if image_base.ndim", "of 288.88 print(f'Rescaled Image to match pixel size of 288.88nm with a new", "float = 0.86, dtype=None, nms_threshold: float = 0.2, save_xml=False, save_fig=False, pixel_size=None, cell_diameter=None): \"\"\"", "can skip for speed if image.max() == -1: continue # Evaluate Deep Learning", "calculate_indexes, load, cochlea_to_xml, correct_pixel_size, scale_to_hair_cell_diameter from hcat.lib.cell import Cell from hcat.lib.cochlea import Cochlea", "y, y) # [[0, 255], [30, 285], ...] total: int = len(x_ind) *", "Load and preprocess Image image_base = load(f, 'TileScan 1 Merged', verbose=True) # from", "cell_detection_threshold: cells below threshold are rejected :param *float* nms_threshold: iou rejection threshold for", "cell frequency.', color='yellow') xml = get_xml(f) if f.endswith('.lif') else None filename = os.path.split(f)[-1]", "image_base[[1], ...].mul(0.5).add(0.5).unsqueeze(-1).cpu() curvature, distance, apex = predict_curvature(max_projection, cells, curve_path) if curvature is None:", "overlap. We remove cells after analysis is complete. cells: List[Cell] = _cell_nms(cells, nms_threshold)", "File to Analyze... \\nAborting.', color='red') return None if not pixel_size: warn('WARNING: Pixel Size", "output coords with respect to the crop of image_base. We have to adjust", "path=f, analysis_type='detect', leica_metadata=xml, im_shape=image_base.shape, cochlear_distance=distance, curvature=curvature, cells=cells, apex=apex) c.write_csv() if save_xml: cochlea_to_xml(c) if", "Evaluate Deep Learning Model out: Dict[str, Tensor] = model(image.float())[0] scores: Tensor = out['scores'].cpu()", "have to adjust # idk why the y and x are flipped. Breaks", "calculate cell's best frequency cells = [c for c in cells if not", "is None: warn('ERROR: No File to Analyze... \\nAborting.', color='red') return None if not", "cells :param nms_threshold: cell iou threshold :return: Iterable of cells \"\"\" # nms", "sum([int(c.type == 'IHC') for c in cells]) # number of ihc print(f'Total Cells:", "dtype is None else dtype scale: int = hcat.lib.utils.get_dtype_offset(dtype) device = 'cuda' if", "== 'IHC') for c in cells]) # number of ihc print(f'Total Cells: {len(cells)}\\n", "Perforns non maximum supression on the resulting cell predictions :param cells: Iterable of", "path have failed. Frequency Mapping functionality is ' 'limited. Consider Manual Calculation.', color='yellow')", "cy = centers[:, 1] for i, score in enumerate(scores): if score > cell_detection_threshold:", "# calculate cell's best frequency cells = [c for c in cells if", "torchvision.ops.box_convert(boxes, 'xyxy', 'cxcywh').cpu() cx = centers[:, 0] cy = centers[:, 1] for i,", "Image image_base = load(f, 'TileScan 1 Merged', verbose=True) # from hcat.lib.utils image_base =", "# center x, center y, width, height centers: Tensor = torchvision.ops.box_convert(boxes, 'xyxy', 'cxcywh').cpu()", "/ scale).to(device) if pixel_size is not None: image_base: Tensor = correct_pixel_size(image_base, pixel_size) #model", "* 255 c, x, y = image_base.shape print( f'DONE: shape: {image_base.shape}, min: {image_base.min()},", "x_ind: List[List[int]] = calculate_indexes(10, 235, x, x) # [[0, 255], [30, 285], ...]", "the indicies for evaluating cropped regions c, x, y = image_base.shape image_base =", "'OHC') for c in cells]) # number of ohc ihc = sum([int(c.type ==", "cell's best frequency cells = [c for c in cells if not c._distance_is_far_away]", "centers: Tensor = torchvision.ops.box_convert(boxes, 'xyxy', 'cxcywh').cpu() cx = centers[:, 0] cy = centers[:,", "some cells may overlap. We remove cells after analysis is complete. cells: List[Cell]", "performs iterative faster rcnn detection on the entire image. :param *str* f: path", "# curvature estimation really only works if there is a lot of tissue...", "number of ohc ihc = sum([int(c.type == 'IHC') for c in cells]) #", "np.zeros(shape) temp = np.concatenate((temp, image_base)) / scale * 255 c, x, y =", "to Analyze... \\nAborting.', color='red') return None if not pixel_size: warn('WARNING: Pixel Size is", "Frequency Mapping functionality is ' 'limited. Consider Manual Calculation.', color='yellow') # curvature estimation", "not None and distance.max() > 4000: for c in cells: c.calculate_frequency(curvature[[0, 1], :],", "is complete. cells: List[Cell] = _cell_nms(cells, nms_threshold) ohc = sum([int(c.type == 'OHC') for", "len(y_ind) # Initalize other small things cell_id = 1 cells = [] add_cell", "other small things cell_id = 1 cells = [] add_cell = cells.append #", "match pixel size of 288.88nm with a new shape of: {image_base.shape}') elif cell_diameter", "List[List[int]] = calculate_indexes(10, 235, y, y) # [[0, 255], [30, 285], ...] total:", "# Initalize curvature detection predict_curvature = hcat.lib.functional.PredictCurvature(erode=3) # Get the indicies for evaluating", "Initalize other small things cell_id = 1 cells = [] add_cell = cells.append", "if pixel_size is not None: image_base: Tensor = correct_pixel_size(image_base, pixel_size) #model expects pixel", "= torch.cat((torch.zeros((1, x, y), device=device), image_base), dim=0) x_ind: List[List[int]] = calculate_indexes(10, 235, x,", "= out['scores'].cpu() boxes: Tensor = out['boxes'].cpu() labels: Tensor = out['labels'].cpu() # The model", "cell_diameter) print(f'Rescaled Image to match pixel size of 288.88nm with a new shape", "Tensor = correct_pixel_size(image_base, pixel_size) #model expects pixel size of 288.88 print(f'Rescaled Image to", "cells=cells, apex=apex) c.write_csv() if save_xml: cochlea_to_xml(c) if save_fig: c.make_detect_fig(image_base) print('') return c def", "warn('ERROR: No File to Analyze... \\nAborting.', color='red') return None if not pixel_size: warn('WARNING:", "288.88 nm x/y. ' 'Consider suplying value for optimal performance.', color='yellow') with torch.no_grad():", "color='red') return None if not pixel_size: warn('WARNING: Pixel Size is not set. Defaults", "in cells if not c._distance_is_far_away] # remove a cell if its far away", "to get rid of cells boxes = torch.zeros((len(cells), 4)) scores = torch.zeros(len(cells)) for", "scores[i] = c.scores ind = torchvision.ops.nms(boxes, scores, nms_threshold) # need to pop off", "in it we can skip for speed if image.max() == -1: continue #", "= sum([int(c.type == 'OHC') for c in cells]) # number of ohc ihc", "curvature, distance, apex = None, None, None warn('WARNING: Predicted Cochlear Distance is below", "y and x are flipped. Breaks otherwise. boxes[:, [0, 2]] += y[0] boxes[:,", "a new shape of: {image_base.shape}') # normalize around zero image_base.sub_(0.5).div_(0.5) if device ==", "nms_threshold: iou rejection threshold for nms. :return: *Cochlea* object containing data of analysis.", "itertools import product import numpy as np from hcat.lib.explore_lif import get_xml import torchvision.ops", "import os.path from typing import Optional, List, Dict # DOCUMENTED def _detect(f: str,", "if image_base.max() < scale * 0.33: warn(f'WARNING: Image max value less than 1/3", "cx[i], cy[i], 0]), image=None, mask=None, cell_type='OHC' if labels[i] == 1 else 'IHC', boxes=boxes[i,", "in cells]) # number of ihc print(f'Total Cells: {len(cells)}\\n OHC: {ohc}\\n IHC: {ihc}'", "OHC: {ohc}\\n IHC: {ihc}' ) max_projection: Tensor = image_base[[1], ...].mul(0.5).add(0.5).unsqueeze(-1).cpu() curvature, distance, apex", "None: warn('WARNING: All three methods to predict hair cell path have failed. Frequency", "enumerate(scores): if score > cell_detection_threshold: add_cell(Cell(id=cell_id, loc=torch.tensor([0, cx[i], cy[i], 0]), image=None, mask=None, cell_type='OHC'", "three methods to predict hair cell path have failed. Frequency Mapping functionality is", "= [c for c in cells if not c._distance_is_far_away] # remove a cell", "warn('WARNING: GPU not present or CUDA is not correctly intialized for GPU accelerated", "i, c in enumerate(cells): c.id = i+1 # Store in compressible object for", ":] = c.boxes scores[i] = c.scores ind = torchvision.ops.nms(boxes, scores, nms_threshold) # need", "for evaluating cropped regions c, x, y = image_base.shape image_base = torch.cat((torch.zeros((1, x,", "temp = np.concatenate((temp, image_base)) / scale * 255 c, x, y = image_base.shape", "to analyze :param *float* cell_detection_threshold: cells below threshold are rejected :param *float* nms_threshold:", "image_base), dim=0) x_ind: List[List[int]] = calculate_indexes(10, 235, x, x) # [[0, 255], [30,", "scores: Tensor = out['scores'].cpu() boxes: Tensor = out['boxes'].cpu() labels: Tensor = out['labels'].cpu() #", "Iterable of cells :param nms_threshold: cell iou threshold :return: Iterable of cells \"\"\"", "str, curve_path: str = None, cell_detection_threshold: float = 0.86, dtype=None, nms_threshold: float =", "for x, y in tqdm(product(x_ind, y_ind), total=total, desc='Detecting: '): # Load and prepare", "enumerate(cells): c.id = i+1 # Store in compressible object for further use c", "frequency cells = [c for c in cells if not c._distance_is_far_away] # remove", "cochlea_to_xml(c) if save_fig: c.make_detect_fig(image_base) print('') return c def _cell_nms(cells: List[Cell], nms_threshold: float) ->", "cell predictions :param cells: Iterable of cells :param nms_threshold: cell iou threshold :return:", "== -1: continue # Evaluate Deep Learning Model out: Dict[str, Tensor] = model(image.float())[0]", "save_fig: c.make_detect_fig(image_base) print('') return c def _cell_nms(cells: List[Cell], nms_threshold: float) -> List[Cell]: \"\"\"", "cell_detection_threshold: float = 0.86, dtype=None, nms_threshold: float = 0.2, save_xml=False, save_fig=False, pixel_size=None, cell_diameter=None):", "away from curve else: curvature, distance, apex = None, None, None warn('WARNING: Predicted", "= [] add_cell = cells.append # stupid but done for speed for x,", "# idk why the y and x are flipped. Breaks otherwise. boxes[:, [0,", "analysis is complete. cells: List[Cell] = _cell_nms(cells, nms_threshold) ohc = sum([int(c.type == 'OHC')", "number of ihc print(f'Total Cells: {len(cells)}\\n OHC: {ohc}\\n IHC: {ihc}' ) max_projection: Tensor", "# Initalize other small things cell_id = 1 cells = [] add_cell =", "0.2, save_xml=False, save_fig=False, pixel_size=None, cell_diameter=None): \"\"\" 2D hair cell detection algorithm. Loads arbitrarily", "out['labels'].cpu() # The model output coords with respect to the crop of image_base.", "# Get the indicies for evaluating cropped regions c, x, y = image_base.shape", "'Analysis may be slow.', color='yellow') # Initalize the model... model = FasterRCNN_from_url(url='https://github.com/buswinka/hcat/blob/master/modelfiles/detection.trch?raw=true', device=device)", "0.86, dtype=None, nms_threshold: float = 0.2, save_xml=False, save_fig=False, pixel_size=None, cell_diameter=None): \"\"\" 2D hair", "rejected :param *float* nms_threshold: iou rejection threshold for nms. :return: *Cochlea* object containing", "f: path to image by which to analyze :param *float* cell_detection_threshold: cells below", "image_base: Tensor = correct_pixel_size(image_base, pixel_size) #model expects pixel size of 288.88 print(f'Rescaled Image", "hcat.backends.detection import HairCellFasterRCNN from hcat.lib.utils import warn import torch from torch import Tensor", "warn import torch from torch import Tensor from tqdm import tqdm from itertools", "time Image max.', color='yellow') scale = image_base.max() * 1.5 image_base = torch.from_numpy(image_base.astype(np.uint16) /", "why the y and x are flipped. Breaks otherwise. boxes[:, [0, 2]] +=", "of analysis. \"\"\" print('Initializing hair cell detection algorithm...') if f is None: warn('ERROR:", "is a lot of tissue... if distance is not None and distance.max() >", "but done for speed for x, y in tqdm(product(x_ind, y_ind), total=total, desc='Detecting: '):", "None else dtype scale: int = hcat.lib.utils.get_dtype_offset(dtype) device = 'cuda' if torch.cuda.is_available() else", "= image_base.max() * 1.5 image_base = torch.from_numpy(image_base.astype(np.uint16) / scale).to(device) if pixel_size is not", "in enumerate(scores): if score > cell_detection_threshold: add_cell(Cell(id=cell_id, loc=torch.tensor([0, cx[i], cy[i], 0]), image=None, mask=None,", "of ohc ihc = sum([int(c.type == 'IHC') for c in cells]) # number", "curvature estimation really only works if there is a lot of tissue... if", "add_cell(Cell(id=cell_id, loc=torch.tensor([0, cx[i], cy[i], 0]), image=None, mask=None, cell_type='OHC' if labels[i] == 1 else", "None: image_base: Tensor = correct_pixel_size(image_base, pixel_size) #model expects pixel size of 288.88 print(f'Rescaled", "correct_pixel_size(image_base, pixel_size) #model expects pixel size of 288.88 print(f'Rescaled Image to match pixel", "by which to analyze :param *float* cell_detection_threshold: cells below threshold are rejected :param", "pixel_size=None, cell_diameter=None): \"\"\" 2D hair cell detection algorithm. Loads arbitrarily large 2d image", "Tensor from tqdm import tqdm from itertools import product import numpy as np", "{dtype}. Readjusting scale to 1.5 time Image max.', color='yellow') scale = image_base.max() *", "hcat.lib.utils image_base = image_base[[2, 3],...].max(-1) if image_base.ndim == 4 else image_base shape =", "1 cells = [] add_cell = cells.append # stupid but done for speed", "scores=scores[i])) cell_id += 1 # some cells may overlap. We remove cells after", "device=device), image_base), dim=0) x_ind: List[List[int]] = calculate_indexes(10, 235, x, x) # [[0, 255],", "hcat.lib.functional import hcat.lib.functional as functional from hcat.lib.utils import calculate_indexes, load, cochlea_to_xml, correct_pixel_size, scale_to_hair_cell_diameter", "x, y), device=device), image_base), dim=0) x_ind: List[List[int]] = calculate_indexes(10, 235, x, x) #", "235, x, x) # [[0, 255], [30, 285], ...] y_ind: List[List[int]] = calculate_indexes(10,", "Factor: {scale}, dtype: {dtype}. Readjusting scale to 1.5 time Image max.', color='yellow') scale", "[c for c in cells if not c._distance_is_far_away] # remove a cell if", "[0, 2]] += y[0] boxes[:, [1, 3]] += x[0] # center x, center", "Image to match pixel size of 288.88nm with a new shape of: {image_base.shape}')", "initialized!', color='green') else: warn('WARNING: GPU not present or CUDA is not correctly intialized", "detection on the entire image. :param *str* f: path to image by which", "Tensor = out['labels'].cpu() # The model output coords with respect to the crop", "tqdm from itertools import product import numpy as np from hcat.lib.explore_lif import get_xml", "for ML model evaluation image: Tensor = image_base[:, x[0]:x[1], y[0]:y[1]].unsqueeze(0) # If the", "= image_base[[1], ...].mul(0.5).add(0.5).unsqueeze(-1).cpu() curvature, distance, apex = predict_curvature(max_projection, cells, curve_path) if curvature is", "1 Merged', verbose=True) # from hcat.lib.utils image_base = image_base[[2, 3],...].max(-1) if image_base.ndim ==", "pixel size of 288.88nm with a new shape of: {image_base.shape}') # normalize around", "warn('CUDA: GPU successfully initialized!', color='green') else: warn('WARNING: GPU not present or CUDA is", "scale = image_base.max() * 1.5 image_base = torch.from_numpy(image_base.astype(np.uint16) / scale).to(device) if pixel_size is", "{image_base.max()}, dtype: {image_base.dtype}') if image_base.max() < scale * 0.33: warn(f'WARNING: Image max value", "score > cell_detection_threshold: add_cell(Cell(id=cell_id, loc=torch.tensor([0, cx[i], cy[i], 0]), image=None, mask=None, cell_type='OHC' if labels[i]", "i+1 # Store in compressible object for further use c = Cochlea(mask=None, filename=filename,", ":], scores=scores[i])) cell_id += 1 # some cells may overlap. We remove cells", "as functional from hcat.lib.utils import calculate_indexes, load, cochlea_to_xml, correct_pixel_size, scale_to_hair_cell_diameter from hcat.lib.cell import", "a cell if its far away from curve else: curvature, distance, apex =", "max: {image_base.max()}, dtype: {image_base.dtype}') if image_base.max() < scale * 0.33: warn(f'WARNING: Image max", "out['boxes'].cpu() labels: Tensor = out['labels'].cpu() # The model output coords with respect to", "image_base.sub_(0.5).div_(0.5) if device == 'cuda': warn('CUDA: GPU successfully initialized!', color='green') else: warn('WARNING: GPU", "use c = Cochlea(mask=None, filename=filename, path=f, analysis_type='detect', leica_metadata=xml, im_shape=image_base.shape, cochlear_distance=distance, curvature=curvature, cells=cells, apex=apex)", "apex = predict_curvature(max_projection, cells, curve_path) if curvature is None: warn('WARNING: All three methods", "else: warn('WARNING: GPU not present or CUDA is not correctly intialized for GPU", "complete. cells: List[Cell] = _cell_nms(cells, nms_threshold) ohc = sum([int(c.type == 'OHC') for c", "\"\"\" # nms to get rid of cells boxes = torch.zeros((len(cells), 4)) scores", "List[List[int]] = calculate_indexes(10, 235, x, x) # [[0, 255], [30, 285], ...] y_ind:", "Mapping functionality is ' 'limited. Consider Manual Calculation.', color='yellow') # curvature estimation really", "'limited. Consider Manual Calculation.', color='yellow') # curvature estimation really only works if there", "threshold :return: Iterable of cells \"\"\" # nms to get rid of cells", "image_base = load(f, 'TileScan 1 Merged', verbose=True) # from hcat.lib.utils image_base = image_base[[2,", "boxes=boxes[i, :], scores=scores[i])) cell_id += 1 # some cells may overlap. We remove", "{scale}, dtype: {dtype}. Readjusting scale to 1.5 time Image max.', color='yellow') scale =", "= scale_to_hair_cell_diameter(image_base, cell_diameter) print(f'Rescaled Image to match pixel size of 288.88nm with a", "further use c = Cochlea(mask=None, filename=filename, path=f, analysis_type='detect', leica_metadata=xml, im_shape=image_base.shape, cochlear_distance=distance, curvature=curvature, cells=cells,", "prepare image crop for ML model evaluation image: Tensor = image_base[:, x[0]:x[1], y[0]:y[1]].unsqueeze(0)", "torch.cat((torch.zeros((1, x, y), device=device), image_base), dim=0) x_ind: List[List[int]] = calculate_indexes(10, 235, x, x)", "compressible object for further use c = Cochlea(mask=None, filename=filename, path=f, analysis_type='detect', leica_metadata=xml, im_shape=image_base.shape,", "for nms. :return: *Cochlea* object containing data of analysis. \"\"\" print('Initializing hair cell", "distance, apex = None, None, None warn('WARNING: Predicted Cochlear Distance is below 4000um.", "+= 1 # some cells may overlap. We remove cells after analysis is", "c.write_csv() if save_xml: cochlea_to_xml(c) if save_fig: c.make_detect_fig(image_base) print('') return c def _cell_nms(cells: List[Cell],", "sum([int(c.type == 'OHC') for c in cells]) # number of ohc ihc =", "if not pixel_size: warn('WARNING: Pixel Size is not set. Defaults to 288.88 nm", "{image_base.shape}') # normalize around zero image_base.sub_(0.5).div_(0.5) if device == 'cuda': warn('CUDA: GPU successfully", "scale * 255 c, x, y = image_base.shape print( f'DONE: shape: {image_base.shape}, min:", "cell_detection_threshold: add_cell(Cell(id=cell_id, loc=torch.tensor([0, cx[i], cy[i], 0]), image=None, mask=None, cell_type='OHC' if labels[i] == 1", "iou rejection threshold for nms. :return: *Cochlea* object containing data of analysis. \"\"\"", "None if not pixel_size: warn('WARNING: Pixel Size is not set. Defaults to 288.88", "if score > cell_detection_threshold: add_cell(Cell(id=cell_id, loc=torch.tensor([0, cx[i], cy[i], 0]), image=None, mask=None, cell_type='OHC' if", "4 else image_base shape = list(image_base.shape) shape[0] = 1 dtype = image_base.dtype if", "its far away from curve else: curvature, distance, apex = None, None, None", "done for speed for x, y in tqdm(product(x_ind, y_ind), total=total, desc='Detecting: '): #", "len(x_ind) * len(y_ind) # Initalize other small things cell_id = 1 cells =", "warn(f'WARNING: Image max value less than 1/3 the scale factor for bit depth.", "Loads arbitrarily large 2d image and performs iterative faster rcnn detection on the", "import Optional, List, Dict # DOCUMENTED def _detect(f: str, curve_path: str = None,", "cells.append # stupid but done for speed for x, y in tqdm(product(x_ind, y_ind),", "ind_bool = torch.zeros(len(cells)) ind_bool[ind] = 1 for i, val in enumerate(ind_bool): if val", "nms. :return: *Cochlea* object containing data of analysis. \"\"\" print('Initializing hair cell detection", "288.88nm with a new shape of: {image_base.shape}') # normalize around zero image_base.sub_(0.5).div_(0.5) if", "color='yellow') xml = get_xml(f) if f.endswith('.lif') else None filename = os.path.split(f)[-1] # remove", "cell path have failed. Frequency Mapping functionality is ' 'limited. Consider Manual Calculation.',", "Cochlea(mask=None, filename=filename, path=f, analysis_type='detect', leica_metadata=xml, im_shape=image_base.shape, cochlear_distance=distance, curvature=curvature, cells=cells, apex=apex) c.write_csv() if save_xml:", "accelerated computation. ' 'Analysis may be slow.', color='yellow') # Initalize the model... model", "xml = get_xml(f) if f.endswith('.lif') else None filename = os.path.split(f)[-1] # remove weird", "2]] += y[0] boxes[:, [1, 3]] += x[0] # center x, center y,", "dtype scale: int = hcat.lib.utils.get_dtype_offset(dtype) device = 'cuda' if torch.cuda.is_available() else 'cpu' temp", "c.id = i+1 # Store in compressible object for further use c =", "# Load and preprocess Image image_base = load(f, 'TileScan 1 Merged', verbose=True) #", "from hcat.backends.detection import FasterRCNN_from_url from hcat.backends.detection import HairCellFasterRCNN from hcat.lib.utils import warn import", "y = image_base.shape print( f'DONE: shape: {image_base.shape}, min: {image_base.min()}, max: {image_base.max()}, dtype: {image_base.dtype}')", "cy[i], 0]), image=None, mask=None, cell_type='OHC' if labels[i] == 1 else 'IHC', boxes=boxes[i, :],", "nms_threshold: float = 0.2, save_xml=False, save_fig=False, pixel_size=None, cell_diameter=None): \"\"\" 2D hair cell detection", "Scale Factor: {scale}, dtype: {dtype}. Readjusting scale to 1.5 time Image max.', color='yellow')", "from itertools import product import numpy as np from hcat.lib.explore_lif import get_xml import", "and preprocess Image image_base = load(f, 'TileScan 1 Merged', verbose=True) # from hcat.lib.utils", "if dtype is None else dtype scale: int = hcat.lib.utils.get_dtype_offset(dtype) device = 'cuda'", "x, center y, width, height centers: Tensor = torchvision.ops.box_convert(boxes, 'xyxy', 'cxcywh').cpu() cx =", "Pixel Size is not set. Defaults to 288.88 nm x/y. ' 'Consider suplying", "None, cell_detection_threshold: float = 0.86, dtype=None, nms_threshold: float = 0.2, save_xml=False, save_fig=False, pixel_size=None,", "image_base[:, x[0]:x[1], y[0]:y[1]].unsqueeze(0) # If the image has nothing in it we can", "[1, 3]] += x[0] # center x, center y, width, height centers: Tensor", "if val == 0: cells[i] = None return [c for c in cells", "* 1.5 image_base = torch.from_numpy(image_base.astype(np.uint16) / scale).to(device) if pixel_size is not None: image_base:", "import tqdm from itertools import product import numpy as np from hcat.lib.explore_lif import", "= out['boxes'].cpu() labels: Tensor = out['labels'].cpu() # The model output coords with respect", "hcat.backends.detection import FasterRCNN_from_url from hcat.backends.detection import HairCellFasterRCNN from hcat.lib.utils import warn import torch", "else dtype scale: int = hcat.lib.utils.get_dtype_offset(dtype) device = 'cuda' if torch.cuda.is_available() else 'cpu'", "of 288.88nm with a new shape of: {image_base.shape}') elif cell_diameter is not None:", "IHC: {ihc}' ) max_projection: Tensor = image_base[[1], ...].mul(0.5).add(0.5).unsqueeze(-1).cpu() curvature, distance, apex = predict_curvature(max_projection,", "hair cell detection algorithm...') if f is None: warn('ERROR: No File to Analyze...", "c.scores ind = torchvision.ops.nms(boxes, scores, nms_threshold) # need to pop off list elements", "distance is not None and distance.max() > 4000: for c in cells: c.calculate_frequency(curvature[[0,", "\"\"\" print('Initializing hair cell detection algorithm...') if f is None: warn('ERROR: No File", "model... model = FasterRCNN_from_url(url='https://github.com/buswinka/hcat/blob/master/modelfiles/detection.trch?raw=true', device=device) model.eval() # Initalize curvature detection predict_curvature = hcat.lib.functional.PredictCurvature(erode=3)", "= 1 cells = [] add_cell = cells.append # stupid but done for", "List[Cell] = _cell_nms(cells, nms_threshold) ohc = sum([int(c.type == 'OHC') for c in cells])", "GPU accelerated computation. ' 'Analysis may be slow.', color='yellow') # Initalize the model...", "> cell_detection_threshold: add_cell(Cell(id=cell_id, loc=torch.tensor([0, cx[i], cy[i], 0]), image=None, mask=None, cell_type='OHC' if labels[i] ==", "torchvision.ops import skimage.io as io import os.path from typing import Optional, List, Dict", "Max: {image_base.max()},' f' Scale Factor: {scale}, dtype: {dtype}. Readjusting scale to 1.5 time", "in enumerate(cells): c.id = i+1 # Store in compressible object for further use", "containing data of analysis. \"\"\" print('Initializing hair cell detection algorithm...') if f is", "print(f'Rescaled Image to match pixel size of 288.88nm with a new shape of:", "shape of: {image_base.shape}') # normalize around zero image_base.sub_(0.5).div_(0.5) if device == 'cuda': warn('CUDA:", "cochlear_distance=distance, curvature=curvature, cells=cells, apex=apex) c.write_csv() if save_xml: cochlea_to_xml(c) if save_fig: c.make_detect_fig(image_base) print('') return", "= cells.append # stupid but done for speed for x, y in tqdm(product(x_ind,", "c.make_detect_fig(image_base) print('') return c def _cell_nms(cells: List[Cell], nms_threshold: float) -> List[Cell]: \"\"\" Perforns", "image_base.max() * 1.5 image_base = torch.from_numpy(image_base.astype(np.uint16) / scale).to(device) if pixel_size is not None:", "are rejected :param *float* nms_threshold: iou rejection threshold for nms. :return: *Cochlea* object", "rejection threshold for nms. :return: *Cochlea* object containing data of analysis. \"\"\" print('Initializing", "y[0]:y[1]].unsqueeze(0) # If the image has nothing in it we can skip for", "color='yellow') # curvature estimation really only works if there is a lot of", "cells: c.calculate_frequency(curvature[[0, 1], :], distance) # calculate cell's best frequency cells = [c", "continue # Evaluate Deep Learning Model out: Dict[str, Tensor] = model(image.float())[0] scores: Tensor", "need to pop off list elements from an int64 tensor ind_bool = torch.zeros(len(cells))", "None filename = os.path.split(f)[-1] # remove weird cell ID's for i, c in", "= image_base.shape print( f'DONE: shape: {image_base.shape}, min: {image_base.min()}, max: {image_base.max()}, dtype: {image_base.dtype}') if", "size of 288.88nm with a new shape of: {image_base.shape}') elif cell_diameter is not", "cochlea_to_xml, correct_pixel_size, scale_to_hair_cell_diameter from hcat.lib.cell import Cell from hcat.lib.cochlea import Cochlea from hcat.backends.detection", "# need to pop off list elements from an int64 tensor ind_bool =", "Image Max: {image_base.max()},' f' Scale Factor: {scale}, dtype: {dtype}. Readjusting scale to 1.5", "= image_base[:, x[0]:x[1], y[0]:y[1]].unsqueeze(0) # If the image has nothing in it we", "below threshold are rejected :param *float* nms_threshold: iou rejection threshold for nms. :return:", "is ' 'limited. Consider Manual Calculation.', color='yellow') # curvature estimation really only works", "else 'cpu' temp = np.zeros(shape) temp = np.concatenate((temp, image_base)) / scale * 255", "of cells boxes = torch.zeros((len(cells), 4)) scores = torch.zeros(len(cells)) for i, c in", "data of analysis. \"\"\" print('Initializing hair cell detection algorithm...') if f is None:", "in tqdm(product(x_ind, y_ind), total=total, desc='Detecting: '): # Load and prepare image crop for", "correctly intialized for GPU accelerated computation. ' 'Analysis may be slow.', color='yellow') #", "with respect to the crop of image_base. We have to adjust # idk", "and x are flipped. Breaks otherwise. boxes[:, [0, 2]] += y[0] boxes[:, [1,", "dim=0) x_ind: List[List[int]] = calculate_indexes(10, 235, x, x) # [[0, 255], [30, 285],", "far away from curve else: curvature, distance, apex = None, None, None warn('WARNING:", "import torchvision.ops import skimage.io as io import os.path from typing import Optional, List,", "4000um. Not sufficient ' 'information to determine cell frequency.', color='yellow') xml = get_xml(f)", "to determine cell frequency.', color='yellow') xml = get_xml(f) if f.endswith('.lif') else None filename", "get_xml import torchvision.ops import skimage.io as io import os.path from typing import Optional,", "failed. Frequency Mapping functionality is ' 'limited. Consider Manual Calculation.', color='yellow') # curvature", "'IHC', boxes=boxes[i, :], scores=scores[i])) cell_id += 1 # some cells may overlap. We", "' 'information to determine cell frequency.', color='yellow') xml = get_xml(f) if f.endswith('.lif') else", "min: {image_base.min()}, max: {image_base.max()}, dtype: {image_base.dtype}') if image_base.max() < scale * 0.33: warn(f'WARNING:", "#model expects pixel size of 288.88 print(f'Rescaled Image to match pixel size of", "GPU not present or CUDA is not correctly intialized for GPU accelerated computation.", "factor for bit depth. Image Max: {image_base.max()},' f' Scale Factor: {scale}, dtype: {dtype}.", "Dict # DOCUMENTED def _detect(f: str, curve_path: str = None, cell_detection_threshold: float =", "for further use c = Cochlea(mask=None, filename=filename, path=f, analysis_type='detect', leica_metadata=xml, im_shape=image_base.shape, cochlear_distance=distance, curvature=curvature,", "image_base = torch.cat((torch.zeros((1, x, y), device=device), image_base), dim=0) x_ind: List[List[int]] = calculate_indexes(10, 235,", "intialized for GPU accelerated computation. ' 'Analysis may be slow.', color='yellow') # Initalize", "of: {image_base.shape}') # normalize around zero image_base.sub_(0.5).div_(0.5) if device == 'cuda': warn('CUDA: GPU", "set. Defaults to 288.88 nm x/y. ' 'Consider suplying value for optimal performance.',", "pixel size of 288.88nm with a new shape of: {image_base.shape}') elif cell_diameter is", "of ihc print(f'Total Cells: {len(cells)}\\n OHC: {ohc}\\n IHC: {ihc}' ) max_projection: Tensor =", "distance) # calculate cell's best frequency cells = [c for c in cells", "max.', color='yellow') scale = image_base.max() * 1.5 image_base = torch.from_numpy(image_base.astype(np.uint16) / scale).to(device) if", "c in cells if not c._distance_is_far_away] # remove a cell if its far", "elements from an int64 tensor ind_bool = torch.zeros(len(cells)) ind_bool[ind] = 1 for i,", "off list elements from an int64 tensor ind_bool = torch.zeros(len(cells)) ind_bool[ind] = 1", "Predicted Cochlear Distance is below 4000um. Not sufficient ' 'information to determine cell", "Initalize curvature detection predict_curvature = hcat.lib.functional.PredictCurvature(erode=3) # Get the indicies for evaluating cropped", "Cell from hcat.lib.cochlea import Cochlea from hcat.backends.detection import FasterRCNN_from_url from hcat.backends.detection import HairCellFasterRCNN", "for i, c in enumerate(cells): c.id = i+1 # Store in compressible object", "numpy as np from hcat.lib.explore_lif import get_xml import torchvision.ops import skimage.io as io", "with a new shape of: {image_base.shape}') # normalize around zero image_base.sub_(0.5).div_(0.5) if device", "{len(cells)}\\n OHC: {ohc}\\n IHC: {ihc}' ) max_projection: Tensor = image_base[[1], ...].mul(0.5).add(0.5).unsqueeze(-1).cpu() curvature, distance,", "from curve else: curvature, distance, apex = None, None, None warn('WARNING: Predicted Cochlear", "not pixel_size: warn('WARNING: Pixel Size is not set. Defaults to 288.88 nm x/y.", "2d image and performs iterative faster rcnn detection on the entire image. :param", "cell_id = 1 cells = [] add_cell = cells.append # stupid but done", "things cell_id = 1 cells = [] add_cell = cells.append # stupid but", "rcnn detection on the entire image. :param *str* f: path to image by", "dtype: {dtype}. Readjusting scale to 1.5 time Image max.', color='yellow') scale = image_base.max()", "Breaks otherwise. boxes[:, [0, 2]] += y[0] boxes[:, [1, 3]] += x[0] #", "there is a lot of tissue... if distance is not None and distance.max()", "is None: warn('WARNING: All three methods to predict hair cell path have failed.", "cell if its far away from curve else: curvature, distance, apex = None,", ":param *str* f: path to image by which to analyze :param *float* cell_detection_threshold:", "== 0: cells[i] = None return [c for c in cells if c]", "np from hcat.lib.explore_lif import get_xml import torchvision.ops import skimage.io as io import os.path", "Distance is below 4000um. Not sufficient ' 'information to determine cell frequency.', color='yellow')", "as np from hcat.lib.explore_lif import get_xml import torchvision.ops import skimage.io as io import", "Image max.', color='yellow') scale = image_base.max() * 1.5 image_base = torch.from_numpy(image_base.astype(np.uint16) / scale).to(device)", "get rid of cells boxes = torch.zeros((len(cells), 4)) scores = torch.zeros(len(cells)) for i,", "not present or CUDA is not correctly intialized for GPU accelerated computation. '", "detection predict_curvature = hcat.lib.functional.PredictCurvature(erode=3) # Get the indicies for evaluating cropped regions c,", "= image_base.shape image_base = torch.cat((torch.zeros((1, x, y), device=device), image_base), dim=0) x_ind: List[List[int]] =", "height centers: Tensor = torchvision.ops.box_convert(boxes, 'xyxy', 'cxcywh').cpu() cx = centers[:, 0] cy =", "from an int64 tensor ind_bool = torch.zeros(len(cells)) ind_bool[ind] = 1 for i, val", "else 'IHC', boxes=boxes[i, :], scores=scores[i])) cell_id += 1 # some cells may overlap.", "nms to get rid of cells boxes = torch.zeros((len(cells), 4)) scores = torch.zeros(len(cells))", "285], ...] total: int = len(x_ind) * len(y_ind) # Initalize other small things", "for speed for x, y in tqdm(product(x_ind, y_ind), total=total, desc='Detecting: '): # Load", "= sum([int(c.type == 'IHC') for c in cells]) # number of ihc print(f'Total", "evaluating cropped regions c, x, y = image_base.shape image_base = torch.cat((torch.zeros((1, x, y),", "methods to predict hair cell path have failed. Frequency Mapping functionality is '", "crop of image_base. We have to adjust # idk why the y and", "torch.cuda.is_available() else 'cpu' temp = np.zeros(shape) temp = np.concatenate((temp, image_base)) / scale *", "DOCUMENTED def _detect(f: str, curve_path: str = None, cell_detection_threshold: float = 0.86, dtype=None,", "255 c, x, y = image_base.shape print( f'DONE: shape: {image_base.shape}, min: {image_base.min()}, max:", "' 'Analysis may be slow.', color='yellow') # Initalize the model... model = FasterRCNN_from_url(url='https://github.com/buswinka/hcat/blob/master/modelfiles/detection.trch?raw=true',", "the y and x are flipped. Breaks otherwise. boxes[:, [0, 2]] += y[0]", "ohc = sum([int(c.type == 'OHC') for c in cells]) # number of ohc", "ihc print(f'Total Cells: {len(cells)}\\n OHC: {ohc}\\n IHC: {ihc}' ) max_projection: Tensor = image_base[[1],", "\\nAborting.', color='red') return None if not pixel_size: warn('WARNING: Pixel Size is not set.", "str = None, cell_detection_threshold: float = 0.86, dtype=None, nms_threshold: float = 0.2, save_xml=False,", "All three methods to predict hair cell path have failed. Frequency Mapping functionality", "boxes = torch.zeros((len(cells), 4)) scores = torch.zeros(len(cells)) for i, c in enumerate(cells): boxes[i,", "labels[i] == 1 else 'IHC', boxes=boxes[i, :], scores=scores[i])) cell_id += 1 # some", "really only works if there is a lot of tissue... if distance is", "' 'limited. Consider Manual Calculation.', color='yellow') # curvature estimation really only works if", "weird cell ID's for i, c in enumerate(cells): c.id = i+1 # Store", "from hcat.backends.detection import HairCellFasterRCNN from hcat.lib.utils import warn import torch from torch import", "expects pixel size of 288.88 print(f'Rescaled Image to match pixel size of 288.88nm", "not None: image_base: Tensor = correct_pixel_size(image_base, pixel_size) #model expects pixel size of 288.88", "# nms to get rid of cells boxes = torch.zeros((len(cells), 4)) scores =", "Cochlear Distance is below 4000um. Not sufficient ' 'information to determine cell frequency.',", "present or CUDA is not correctly intialized for GPU accelerated computation. ' 'Analysis", "to the crop of image_base. We have to adjust # idk why the", "the model... model = FasterRCNN_from_url(url='https://github.com/buswinka/hcat/blob/master/modelfiles/detection.trch?raw=true', device=device) model.eval() # Initalize curvature detection predict_curvature =", "analysis_type='detect', leica_metadata=xml, im_shape=image_base.shape, cochlear_distance=distance, curvature=curvature, cells=cells, apex=apex) c.write_csv() if save_xml: cochlea_to_xml(c) if save_fig:", "Not sufficient ' 'information to determine cell frequency.', color='yellow') xml = get_xml(f) if", "i, val in enumerate(ind_bool): if val == 0: cells[i] = None return [c", "in compressible object for further use c = Cochlea(mask=None, filename=filename, path=f, analysis_type='detect', leica_metadata=xml,", "of: {image_base.shape}') elif cell_diameter is not None: image_base: Tensor = scale_to_hair_cell_diameter(image_base, cell_diameter) print(f'Rescaled", "arbitrarily large 2d image and performs iterative faster rcnn detection on the entire", "and prepare image crop for ML model evaluation image: Tensor = image_base[:, x[0]:x[1],", "None: warn('ERROR: No File to Analyze... \\nAborting.', color='red') return None if not pixel_size:", "verbose=True) # from hcat.lib.utils image_base = image_base[[2, 3],...].max(-1) if image_base.ndim == 4 else", "resulting cell predictions :param cells: Iterable of cells :param nms_threshold: cell iou threshold", "hair cell detection algorithm. Loads arbitrarily large 2d image and performs iterative faster", "is not None and distance.max() > 4000: for c in cells: c.calculate_frequency(curvature[[0, 1],", "None, None warn('WARNING: Predicted Cochlear Distance is below 4000um. Not sufficient ' 'information", "' 'Consider suplying value for optimal performance.', color='yellow') with torch.no_grad(): # Load and", "= c.scores ind = torchvision.ops.nms(boxes, scores, nms_threshold) # need to pop off list", "Manual Calculation.', color='yellow') # curvature estimation really only works if there is a", "i, c in enumerate(cells): boxes[i, :] = c.boxes scores[i] = c.scores ind =", "may be slow.', color='yellow') # Initalize the model... model = FasterRCNN_from_url(url='https://github.com/buswinka/hcat/blob/master/modelfiles/detection.trch?raw=true', device=device) model.eval()", "large 2d image and performs iterative faster rcnn detection on the entire image.", "f'DONE: shape: {image_base.shape}, min: {image_base.min()}, max: {image_base.max()}, dtype: {image_base.dtype}') if image_base.max() < scale", "max_projection: Tensor = image_base[[1], ...].mul(0.5).add(0.5).unsqueeze(-1).cpu() curvature, distance, apex = predict_curvature(max_projection, cells, curve_path) if", "list(image_base.shape) shape[0] = 1 dtype = image_base.dtype if dtype is None else dtype", "color='yellow') # Initalize the model... model = FasterRCNN_from_url(url='https://github.com/buswinka/hcat/blob/master/modelfiles/detection.trch?raw=true', device=device) model.eval() # Initalize curvature", "return c def _cell_nms(cells: List[Cell], nms_threshold: float) -> List[Cell]: \"\"\" Perforns non maximum", "torch.zeros(len(cells)) ind_bool[ind] = 1 for i, val in enumerate(ind_bool): if val == 0:", "predict hair cell path have failed. Frequency Mapping functionality is ' 'limited. Consider", "= len(x_ind) * len(y_ind) # Initalize other small things cell_id = 1 cells", "of tissue... if distance is not None and distance.max() > 4000: for c", ":param nms_threshold: cell iou threshold :return: Iterable of cells \"\"\" # nms to", "from tqdm import tqdm from itertools import product import numpy as np from", "Model out: Dict[str, Tensor] = model(image.float())[0] scores: Tensor = out['scores'].cpu() boxes: Tensor =", "x, x) # [[0, 255], [30, 285], ...] y_ind: List[List[int]] = calculate_indexes(10, 235,", "4000: for c in cells: c.calculate_frequency(curvature[[0, 1], :], distance) # calculate cell's best", "def _cell_nms(cells: List[Cell], nms_threshold: float) -> List[Cell]: \"\"\" Perforns non maximum supression on", "i, score in enumerate(scores): if score > cell_detection_threshold: add_cell(Cell(id=cell_id, loc=torch.tensor([0, cx[i], cy[i], 0]),", "print(f'Total Cells: {len(cells)}\\n OHC: {ohc}\\n IHC: {ihc}' ) max_projection: Tensor = image_base[[1], ...].mul(0.5).add(0.5).unsqueeze(-1).cpu()", "* len(y_ind) # Initalize other small things cell_id = 1 cells = []", "int = hcat.lib.utils.get_dtype_offset(dtype) device = 'cuda' if torch.cuda.is_available() else 'cpu' temp = np.zeros(shape)", "iterative faster rcnn detection on the entire image. :param *str* f: path to", "print('Initializing hair cell detection algorithm...') if f is None: warn('ERROR: No File to", "nms_threshold) ohc = sum([int(c.type == 'OHC') for c in cells]) # number of", "0]), image=None, mask=None, cell_type='OHC' if labels[i] == 1 else 'IHC', boxes=boxes[i, :], scores=scores[i]))", "f.endswith('.lif') else None filename = os.path.split(f)[-1] # remove weird cell ID's for i,", "enumerate(cells): boxes[i, :] = c.boxes scores[i] = c.scores ind = torchvision.ops.nms(boxes, scores, nms_threshold)", "is not correctly intialized for GPU accelerated computation. ' 'Analysis may be slow.',", "{image_base.max()},' f' Scale Factor: {scale}, dtype: {dtype}. Readjusting scale to 1.5 time Image", "enumerate(ind_bool): if val == 0: cells[i] = None return [c for c in", "total: int = len(x_ind) * len(y_ind) # Initalize other small things cell_id =", "cell detection algorithm. Loads arbitrarily large 2d image and performs iterative faster rcnn", "in enumerate(cells): boxes[i, :] = c.boxes scores[i] = c.scores ind = torchvision.ops.nms(boxes, scores,", "val == 0: cells[i] = None return [c for c in cells if", "leica_metadata=xml, im_shape=image_base.shape, cochlear_distance=distance, curvature=curvature, cells=cells, apex=apex) c.write_csv() if save_xml: cochlea_to_xml(c) if save_fig: c.make_detect_fig(image_base)", "the resulting cell predictions :param cells: Iterable of cells :param nms_threshold: cell iou", "if distance is not None and distance.max() > 4000: for c in cells:", "lot of tissue... if distance is not None and distance.max() > 4000: for", "+= x[0] # center x, center y, width, height centers: Tensor = torchvision.ops.box_convert(boxes,", "color='green') else: warn('WARNING: GPU not present or CUDA is not correctly intialized for", "coords with respect to the crop of image_base. We have to adjust #", "warn('WARNING: All three methods to predict hair cell path have failed. Frequency Mapping", "predict_curvature = hcat.lib.functional.PredictCurvature(erode=3) # Get the indicies for evaluating cropped regions c, x,", "/ scale * 255 c, x, y = image_base.shape print( f'DONE: shape: {image_base.shape},", "pixel size of 288.88 print(f'Rescaled Image to match pixel size of 288.88nm with", "to match pixel size of 288.88nm with a new shape of: {image_base.shape}') elif", "zero image_base.sub_(0.5).div_(0.5) if device == 'cuda': warn('CUDA: GPU successfully initialized!', color='green') else: warn('WARNING:", "We have to adjust # idk why the y and x are flipped.", "centers[:, 1] for i, score in enumerate(scores): if score > cell_detection_threshold: add_cell(Cell(id=cell_id, loc=torch.tensor([0,", "if there is a lot of tissue... if distance is not None and", "scale to 1.5 time Image max.', color='yellow') scale = image_base.max() * 1.5 image_base", "= torchvision.ops.nms(boxes, scores, nms_threshold) # need to pop off list elements from an", "center y, width, height centers: Tensor = torchvision.ops.box_convert(boxes, 'xyxy', 'cxcywh').cpu() cx = centers[:,", "have failed. Frequency Mapping functionality is ' 'limited. Consider Manual Calculation.', color='yellow') #", "if torch.cuda.is_available() else 'cpu' temp = np.zeros(shape) temp = np.concatenate((temp, image_base)) / scale", "image_base. We have to adjust # idk why the y and x are", "estimation really only works if there is a lot of tissue... if distance", "= Cochlea(mask=None, filename=filename, path=f, analysis_type='detect', leica_metadata=xml, im_shape=image_base.shape, cochlear_distance=distance, curvature=curvature, cells=cells, apex=apex) c.write_csv() if", "preprocess Image image_base = load(f, 'TileScan 1 Merged', verbose=True) # from hcat.lib.utils image_base", "cells: List[Cell] = _cell_nms(cells, nms_threshold) ohc = sum([int(c.type == 'OHC') for c in", "x, y in tqdm(product(x_ind, y_ind), total=total, desc='Detecting: '): # Load and prepare image", "235, y, y) # [[0, 255], [30, 285], ...] total: int = len(x_ind)", "if device == 'cuda': warn('CUDA: GPU successfully initialized!', color='green') else: warn('WARNING: GPU not", "...] y_ind: List[List[int]] = calculate_indexes(10, 235, y, y) # [[0, 255], [30, 285],", "for c in cells]) # number of ihc print(f'Total Cells: {len(cells)}\\n OHC: {ohc}\\n", "= torch.zeros((len(cells), 4)) scores = torch.zeros(len(cells)) for i, c in enumerate(cells): boxes[i, :]", "{image_base.shape}') elif cell_diameter is not None: image_base: Tensor = scale_to_hair_cell_diameter(image_base, cell_diameter) print(f'Rescaled Image", "Get the indicies for evaluating cropped regions c, x, y = image_base.shape image_base", "Calculation.', color='yellow') # curvature estimation really only works if there is a lot", "Initalize the model... model = FasterRCNN_from_url(url='https://github.com/buswinka/hcat/blob/master/modelfiles/detection.trch?raw=true', device=device) model.eval() # Initalize curvature detection predict_curvature", "if image.max() == -1: continue # Evaluate Deep Learning Model out: Dict[str, Tensor]", "cx = centers[:, 0] cy = centers[:, 1] for i, score in enumerate(scores):", "ML model evaluation image: Tensor = image_base[:, x[0]:x[1], y[0]:y[1]].unsqueeze(0) # If the image", "functionality is ' 'limited. Consider Manual Calculation.', color='yellow') # curvature estimation really only", "== 4 else image_base shape = list(image_base.shape) shape[0] = 1 dtype = image_base.dtype", "if curvature is None: warn('WARNING: All three methods to predict hair cell path", "and distance.max() > 4000: for c in cells: c.calculate_frequency(curvature[[0, 1], :], distance) #", "typing import Optional, List, Dict # DOCUMENTED def _detect(f: str, curve_path: str =", "Cochlea from hcat.backends.detection import FasterRCNN_from_url from hcat.backends.detection import HairCellFasterRCNN from hcat.lib.utils import warn", "'IHC') for c in cells]) # number of ihc print(f'Total Cells: {len(cells)}\\n OHC:", "desc='Detecting: '): # Load and prepare image crop for ML model evaluation image:", "device = 'cuda' if torch.cuda.is_available() else 'cpu' temp = np.zeros(shape) temp = np.concatenate((temp,", "cells]) # number of ihc print(f'Total Cells: {len(cells)}\\n OHC: {ohc}\\n IHC: {ihc}' )", "3],...].max(-1) if image_base.ndim == 4 else image_base shape = list(image_base.shape) shape[0] = 1", "save_xml=False, save_fig=False, pixel_size=None, cell_diameter=None): \"\"\" 2D hair cell detection algorithm. Loads arbitrarily large", "torch import Tensor from tqdm import tqdm from itertools import product import numpy", "analysis. \"\"\" print('Initializing hair cell detection algorithm...') if f is None: warn('ERROR: No", "algorithm...') if f is None: warn('ERROR: No File to Analyze... \\nAborting.', color='red') return", "skip for speed if image.max() == -1: continue # Evaluate Deep Learning Model", "Store in compressible object for further use c = Cochlea(mask=None, filename=filename, path=f, analysis_type='detect',", "color='yellow') scale = image_base.max() * 1.5 image_base = torch.from_numpy(image_base.astype(np.uint16) / scale).to(device) if pixel_size", "to adjust # idk why the y and x are flipped. Breaks otherwise.", "import torch from torch import Tensor from tqdm import tqdm from itertools import", "boxes[i, :] = c.boxes scores[i] = c.scores ind = torchvision.ops.nms(boxes, scores, nms_threshold) #", "x, y = image_base.shape image_base = torch.cat((torch.zeros((1, x, y), device=device), image_base), dim=0) x_ind:", "1], :], distance) # calculate cell's best frequency cells = [c for c", "'): # Load and prepare image crop for ML model evaluation image: Tensor", "rid of cells boxes = torch.zeros((len(cells), 4)) scores = torch.zeros(len(cells)) for i, c", "value less than 1/3 the scale factor for bit depth. Image Max: {image_base.max()},'", "total=total, desc='Detecting: '): # Load and prepare image crop for ML model evaluation", "# Load and prepare image crop for ML model evaluation image: Tensor =", "curve_path) if curvature is None: warn('WARNING: All three methods to predict hair cell", "cell_diameter is not None: image_base: Tensor = scale_to_hair_cell_diameter(image_base, cell_diameter) print(f'Rescaled Image to match", "= 1 dtype = image_base.dtype if dtype is None else dtype scale: int", "save_fig=False, pixel_size=None, cell_diameter=None): \"\"\" 2D hair cell detection algorithm. Loads arbitrarily large 2d", "{image_base.dtype}') if image_base.max() < scale * 0.33: warn(f'WARNING: Image max value less than", "ohc ihc = sum([int(c.type == 'IHC') for c in cells]) # number of", "image. :param *str* f: path to image by which to analyze :param *float*", "hcat.lib.utils.get_dtype_offset(dtype) device = 'cuda' if torch.cuda.is_available() else 'cpu' temp = np.zeros(shape) temp =", "boxes[:, [0, 2]] += y[0] boxes[:, [1, 3]] += x[0] # center x,", "None, None, None warn('WARNING: Predicted Cochlear Distance is below 4000um. Not sufficient '", "# number of ohc ihc = sum([int(c.type == 'IHC') for c in cells])", "288.88nm with a new shape of: {image_base.shape}') elif cell_diameter is not None: image_base:", "match pixel size of 288.88nm with a new shape of: {image_base.shape}') # normalize", "== 'OHC') for c in cells]) # number of ohc ihc = sum([int(c.type", "detection algorithm...') if f is None: warn('ERROR: No File to Analyze... \\nAborting.', color='red')", "to 1.5 time Image max.', color='yellow') scale = image_base.max() * 1.5 image_base =", "Readjusting scale to 1.5 time Image max.', color='yellow') scale = image_base.max() * 1.5", "= _cell_nms(cells, nms_threshold) ohc = sum([int(c.type == 'OHC') for c in cells]) #", "torchvision.ops.nms(boxes, scores, nms_threshold) # need to pop off list elements from an int64", "from hcat.lib.utils image_base = image_base[[2, 3],...].max(-1) if image_base.ndim == 4 else image_base shape", "# remove a cell if its far away from curve else: curvature, distance,", "# stupid but done for speed for x, y in tqdm(product(x_ind, y_ind), total=total,", "0] cy = centers[:, 1] for i, score in enumerate(scores): if score >", "# If the image has nothing in it we can skip for speed", "c = Cochlea(mask=None, filename=filename, path=f, analysis_type='detect', leica_metadata=xml, im_shape=image_base.shape, cochlear_distance=distance, curvature=curvature, cells=cells, apex=apex) c.write_csv()", "Optional, List, Dict # DOCUMENTED def _detect(f: str, curve_path: str = None, cell_detection_threshold:", "if image_base.ndim == 4 else image_base shape = list(image_base.shape) shape[0] = 1 dtype", "only works if there is a lot of tissue... if distance is not", "The model output coords with respect to the crop of image_base. We have", "'cpu' temp = np.zeros(shape) temp = np.concatenate((temp, image_base)) / scale * 255 c,", "for bit depth. Image Max: {image_base.max()},' f' Scale Factor: {scale}, dtype: {dtype}. Readjusting", "of cells \"\"\" # nms to get rid of cells boxes = torch.zeros((len(cells),", "image crop for ML model evaluation image: Tensor = image_base[:, x[0]:x[1], y[0]:y[1]].unsqueeze(0) #", "image.max() == -1: continue # Evaluate Deep Learning Model out: Dict[str, Tensor] =", "curve else: curvature, distance, apex = None, None, None warn('WARNING: Predicted Cochlear Distance", "Cells: {len(cells)}\\n OHC: {ohc}\\n IHC: {ihc}' ) max_projection: Tensor = image_base[[1], ...].mul(0.5).add(0.5).unsqueeze(-1).cpu() curvature,", "= get_xml(f) if f.endswith('.lif') else None filename = os.path.split(f)[-1] # remove weird cell", "optimal performance.', color='yellow') with torch.no_grad(): # Load and preprocess Image image_base = load(f,", "model = FasterRCNN_from_url(url='https://github.com/buswinka/hcat/blob/master/modelfiles/detection.trch?raw=true', device=device) model.eval() # Initalize curvature detection predict_curvature = hcat.lib.functional.PredictCurvature(erode=3) #", "[] add_cell = cells.append # stupid but done for speed for x, y", "if its far away from curve else: curvature, distance, apex = None, None,", "image and performs iterative faster rcnn detection on the entire image. :param *str*", "Tensor = scale_to_hair_cell_diameter(image_base, cell_diameter) print(f'Rescaled Image to match pixel size of 288.88nm with", "c def _cell_nms(cells: List[Cell], nms_threshold: float) -> List[Cell]: \"\"\" Perforns non maximum supression", "from hcat.lib.cell import Cell from hcat.lib.cochlea import Cochlea from hcat.backends.detection import FasterRCNN_from_url from", "shape of: {image_base.shape}') elif cell_diameter is not None: image_base: Tensor = scale_to_hair_cell_diameter(image_base, cell_diameter)", "scores, nms_threshold) # need to pop off list elements from an int64 tensor", "print('') return c def _cell_nms(cells: List[Cell], nms_threshold: float) -> List[Cell]: \"\"\" Perforns non", "Consider Manual Calculation.', color='yellow') # curvature estimation really only works if there is", "'cxcywh').cpu() cx = centers[:, 0] cy = centers[:, 1] for i, score in", "in cells: c.calculate_frequency(curvature[[0, 1], :], distance) # calculate cell's best frequency cells =", "threshold for nms. :return: *Cochlea* object containing data of analysis. \"\"\" print('Initializing hair", "frequency.', color='yellow') xml = get_xml(f) if f.endswith('.lif') else None filename = os.path.split(f)[-1] #", "# Store in compressible object for further use c = Cochlea(mask=None, filename=filename, path=f,", "If the image has nothing in it we can skip for speed if", "# DOCUMENTED def _detect(f: str, curve_path: str = None, cell_detection_threshold: float = 0.86,", "[30, 285], ...] total: int = len(x_ind) * len(y_ind) # Initalize other small", "from hcat.lib.explore_lif import get_xml import torchvision.ops import skimage.io as io import os.path from", "threshold are rejected :param *float* nms_threshold: iou rejection threshold for nms. :return: *Cochlea*", "x[0]:x[1], y[0]:y[1]].unsqueeze(0) # If the image has nothing in it we can skip", "return None if not pixel_size: warn('WARNING: Pixel Size is not set. Defaults to", "*str* f: path to image by which to analyze :param *float* cell_detection_threshold: cells", "import Cell from hcat.lib.cochlea import Cochlea from hcat.backends.detection import FasterRCNN_from_url from hcat.backends.detection import", "int = len(x_ind) * len(y_ind) # Initalize other small things cell_id = 1", "2D hair cell detection algorithm. Loads arbitrarily large 2d image and performs iterative", "Tensor = torchvision.ops.box_convert(boxes, 'xyxy', 'cxcywh').cpu() cx = centers[:, 0] cy = centers[:, 1]", "os.path.split(f)[-1] # remove weird cell ID's for i, c in enumerate(cells): c.id =", "if save_xml: cochlea_to_xml(c) if save_fig: c.make_detect_fig(image_base) print('') return c def _cell_nms(cells: List[Cell], nms_threshold:", "curvature=curvature, cells=cells, apex=apex) c.write_csv() if save_xml: cochlea_to_xml(c) if save_fig: c.make_detect_fig(image_base) print('') return c", "y_ind: List[List[int]] = calculate_indexes(10, 235, y, y) # [[0, 255], [30, 285], ...]", "Deep Learning Model out: Dict[str, Tensor] = model(image.float())[0] scores: Tensor = out['scores'].cpu() boxes:", "after analysis is complete. cells: List[Cell] = _cell_nms(cells, nms_threshold) ohc = sum([int(c.type ==", "Tensor = out['scores'].cpu() boxes: Tensor = out['boxes'].cpu() labels: Tensor = out['labels'].cpu() # The", "not correctly intialized for GPU accelerated computation. ' 'Analysis may be slow.', color='yellow')", "shape: {image_base.shape}, min: {image_base.min()}, max: {image_base.max()}, dtype: {image_base.dtype}') if image_base.max() < scale *", "1 dtype = image_base.dtype if dtype is None else dtype scale: int =", "curvature, distance, apex = predict_curvature(max_projection, cells, curve_path) if curvature is None: warn('WARNING: All", "image_base = image_base[[2, 3],...].max(-1) if image_base.ndim == 4 else image_base shape = list(image_base.shape)", "if f is None: warn('ERROR: No File to Analyze... \\nAborting.', color='red') return None", "or CUDA is not correctly intialized for GPU accelerated computation. ' 'Analysis may", "= image_base[[2, 3],...].max(-1) if image_base.ndim == 4 else image_base shape = list(image_base.shape) shape[0]", "nms_threshold) # need to pop off list elements from an int64 tensor ind_bool", "HairCellFasterRCNN from hcat.lib.utils import warn import torch from torch import Tensor from tqdm", "None warn('WARNING: Predicted Cochlear Distance is below 4000um. Not sufficient ' 'information to", "cells if not c._distance_is_far_away] # remove a cell if its far away from", "are flipped. Breaks otherwise. boxes[:, [0, 2]] += y[0] boxes[:, [1, 3]] +=", "non maximum supression on the resulting cell predictions :param cells: Iterable of cells", "ihc = sum([int(c.type == 'IHC') for c in cells]) # number of ihc", "successfully initialized!', color='green') else: warn('WARNING: GPU not present or CUDA is not correctly", "nm x/y. ' 'Consider suplying value for optimal performance.', color='yellow') with torch.no_grad(): #", "1] for i, score in enumerate(scores): if score > cell_detection_threshold: add_cell(Cell(id=cell_id, loc=torch.tensor([0, cx[i],", "else: curvature, distance, apex = None, None, None warn('WARNING: Predicted Cochlear Distance is", "scale: int = hcat.lib.utils.get_dtype_offset(dtype) device = 'cuda' if torch.cuda.is_available() else 'cpu' temp =", "scale factor for bit depth. Image Max: {image_base.max()},' f' Scale Factor: {scale}, dtype:", "scale_to_hair_cell_diameter(image_base, cell_diameter) print(f'Rescaled Image to match pixel size of 288.88nm with a new", "cells: Iterable of cells :param nms_threshold: cell iou threshold :return: Iterable of cells", "288.88 print(f'Rescaled Image to match pixel size of 288.88nm with a new shape", "object containing data of analysis. \"\"\" print('Initializing hair cell detection algorithm...') if f", "device == 'cuda': warn('CUDA: GPU successfully initialized!', color='green') else: warn('WARNING: GPU not present", "= hcat.lib.utils.get_dtype_offset(dtype) device = 'cuda' if torch.cuda.is_available() else 'cpu' temp = np.zeros(shape) temp", "stupid but done for speed for x, y in tqdm(product(x_ind, y_ind), total=total, desc='Detecting:", "= centers[:, 1] for i, score in enumerate(scores): if score > cell_detection_threshold: add_cell(Cell(id=cell_id,", "= 'cuda' if torch.cuda.is_available() else 'cpu' temp = np.zeros(shape) temp = np.concatenate((temp, image_base))", "_detect(f: str, curve_path: str = None, cell_detection_threshold: float = 0.86, dtype=None, nms_threshold: float", "+= y[0] boxes[:, [1, 3]] += x[0] # center x, center y, width,", "save_xml: cochlea_to_xml(c) if save_fig: c.make_detect_fig(image_base) print('') return c def _cell_nms(cells: List[Cell], nms_threshold: float)", "analyze :param *float* cell_detection_threshold: cells below threshold are rejected :param *float* nms_threshold: iou", "x[0] # center x, center y, width, height centers: Tensor = torchvision.ops.box_convert(boxes, 'xyxy',", "pixel_size: warn('WARNING: Pixel Size is not set. Defaults to 288.88 nm x/y. '", "hcat.lib.utils import calculate_indexes, load, cochlea_to_xml, correct_pixel_size, scale_to_hair_cell_diameter from hcat.lib.cell import Cell from hcat.lib.cochlea", "curve_path: str = None, cell_detection_threshold: float = 0.86, dtype=None, nms_threshold: float = 0.2,", "path to image by which to analyze :param *float* cell_detection_threshold: cells below threshold", "calculate_indexes(10, 235, x, x) # [[0, 255], [30, 285], ...] y_ind: List[List[int]] =", "Load and prepare image crop for ML model evaluation image: Tensor = image_base[:,", "device=device) model.eval() # Initalize curvature detection predict_curvature = hcat.lib.functional.PredictCurvature(erode=3) # Get the indicies", "def _detect(f: str, curve_path: str = None, cell_detection_threshold: float = 0.86, dtype=None, nms_threshold:", "1/3 the scale factor for bit depth. Image Max: {image_base.max()},' f' Scale Factor:", "boxes: Tensor = out['boxes'].cpu() labels: Tensor = out['labels'].cpu() # The model output coords", "normalize around zero image_base.sub_(0.5).div_(0.5) if device == 'cuda': warn('CUDA: GPU successfully initialized!', color='green')", "scale).to(device) if pixel_size is not None: image_base: Tensor = correct_pixel_size(image_base, pixel_size) #model expects", "determine cell frequency.', color='yellow') xml = get_xml(f) if f.endswith('.lif') else None filename =", "= image_base.dtype if dtype is None else dtype scale: int = hcat.lib.utils.get_dtype_offset(dtype) device", "# Initalize the model... model = FasterRCNN_from_url(url='https://github.com/buswinka/hcat/blob/master/modelfiles/detection.trch?raw=true', device=device) model.eval() # Initalize curvature detection", "\"\"\" 2D hair cell detection algorithm. Loads arbitrarily large 2d image and performs", "size of 288.88 print(f'Rescaled Image to match pixel size of 288.88nm with a", "y_ind), total=total, desc='Detecting: '): # Load and prepare image crop for ML model", "= out['labels'].cpu() # The model output coords with respect to the crop of", "loc=torch.tensor([0, cx[i], cy[i], 0]), image=None, mask=None, cell_type='OHC' if labels[i] == 1 else 'IHC',", "nms_threshold: cell iou threshold :return: Iterable of cells \"\"\" # nms to get", "apex=apex) c.write_csv() if save_xml: cochlea_to_xml(c) if save_fig: c.make_detect_fig(image_base) print('') return c def _cell_nms(cells:", "Tensor = out['boxes'].cpu() labels: Tensor = out['labels'].cpu() # The model output coords with", "for i, c in enumerate(cells): boxes[i, :] = c.boxes scores[i] = c.scores ind", "y), device=device), image_base), dim=0) x_ind: List[List[int]] = calculate_indexes(10, 235, x, x) # [[0,", "cells below threshold are rejected :param *float* nms_threshold: iou rejection threshold for nms.", "c, x, y = image_base.shape print( f'DONE: shape: {image_base.shape}, min: {image_base.min()}, max: {image_base.max()},", "out: Dict[str, Tensor] = model(image.float())[0] scores: Tensor = out['scores'].cpu() boxes: Tensor = out['boxes'].cpu()", "c in cells: c.calculate_frequency(curvature[[0, 1], :], distance) # calculate cell's best frequency cells", "is below 4000um. Not sufficient ' 'information to determine cell frequency.', color='yellow') xml", "255], [30, 285], ...] total: int = len(x_ind) * len(y_ind) # Initalize other", "= list(image_base.shape) shape[0] = 1 dtype = image_base.dtype if dtype is None else", "y in tqdm(product(x_ind, y_ind), total=total, desc='Detecting: '): # Load and prepare image crop", "cells may overlap. We remove cells after analysis is complete. cells: List[Cell] =", "'cuda' if torch.cuda.is_available() else 'cpu' temp = np.zeros(shape) temp = np.concatenate((temp, image_base)) /", "cell iou threshold :return: Iterable of cells \"\"\" # nms to get rid", "flipped. Breaks otherwise. boxes[:, [0, 2]] += y[0] boxes[:, [1, 3]] += x[0]", ":return: *Cochlea* object containing data of analysis. \"\"\" print('Initializing hair cell detection algorithm...')", "1 # some cells may overlap. We remove cells after analysis is complete.", "for c in cells if not c._distance_is_far_away] # remove a cell if its", "cells = [c for c in cells if not c._distance_is_far_away] # remove a", "cells boxes = torch.zeros((len(cells), 4)) scores = torch.zeros(len(cells)) for i, c in enumerate(cells):", "int64 tensor ind_bool = torch.zeros(len(cells)) ind_bool[ind] = 1 for i, val in enumerate(ind_bool):", "= FasterRCNN_from_url(url='https://github.com/buswinka/hcat/blob/master/modelfiles/detection.trch?raw=true', device=device) model.eval() # Initalize curvature detection predict_curvature = hcat.lib.functional.PredictCurvature(erode=3) # Get", "algorithm. Loads arbitrarily large 2d image and performs iterative faster rcnn detection on", "Analyze... \\nAborting.', color='red') return None if not pixel_size: warn('WARNING: Pixel Size is not", "idk why the y and x are flipped. Breaks otherwise. boxes[:, [0, 2]]", "for c in cells: c.calculate_frequency(curvature[[0, 1], :], distance) # calculate cell's best frequency", "else None filename = os.path.split(f)[-1] # remove weird cell ID's for i, c", "float) -> List[Cell]: \"\"\" Perforns non maximum supression on the resulting cell predictions", "is None else dtype scale: int = hcat.lib.utils.get_dtype_offset(dtype) device = 'cuda' if torch.cuda.is_available()", "shape[0] = 1 dtype = image_base.dtype if dtype is None else dtype scale:", "distance.max() > 4000: for c in cells: c.calculate_frequency(curvature[[0, 1], :], distance) # calculate", "import hcat.lib.functional as functional from hcat.lib.utils import calculate_indexes, load, cochlea_to_xml, correct_pixel_size, scale_to_hair_cell_diameter from", "= np.zeros(shape) temp = np.concatenate((temp, image_base)) / scale * 255 c, x, y", "speed if image.max() == -1: continue # Evaluate Deep Learning Model out: Dict[str,", "c.calculate_frequency(curvature[[0, 1], :], distance) # calculate cell's best frequency cells = [c for", "import get_xml import torchvision.ops import skimage.io as io import os.path from typing import", "to image by which to analyze :param *float* cell_detection_threshold: cells below threshold are", "c in cells]) # number of ihc print(f'Total Cells: {len(cells)}\\n OHC: {ohc}\\n IHC:", "image_base.dtype if dtype is None else dtype scale: int = hcat.lib.utils.get_dtype_offset(dtype) device =", "image_base.shape print( f'DONE: shape: {image_base.shape}, min: {image_base.min()}, max: {image_base.max()}, dtype: {image_base.dtype}') if image_base.max()", "List[Cell]: \"\"\" Perforns non maximum supression on the resulting cell predictions :param cells:", "the crop of image_base. We have to adjust # idk why the y", "cells, curve_path) if curvature is None: warn('WARNING: All three methods to predict hair", "= hcat.lib.functional.PredictCurvature(erode=3) # Get the indicies for evaluating cropped regions c, x, y", "# The model output coords with respect to the crop of image_base. We", "a new shape of: {image_base.shape}') elif cell_diameter is not None: image_base: Tensor =", "# remove weird cell ID's for i, c in enumerate(cells): c.id = i+1", "less than 1/3 the scale factor for bit depth. Image Max: {image_base.max()},' f'", "== 1 else 'IHC', boxes=boxes[i, :], scores=scores[i])) cell_id += 1 # some cells", "get_xml(f) if f.endswith('.lif') else None filename = os.path.split(f)[-1] # remove weird cell ID's", "list elements from an int64 tensor ind_bool = torch.zeros(len(cells)) ind_bool[ind] = 1 for", "the image has nothing in it we can skip for speed if image.max()", "> 4000: for c in cells: c.calculate_frequency(curvature[[0, 1], :], distance) # calculate cell's", "tqdm(product(x_ind, y_ind), total=total, desc='Detecting: '): # Load and prepare image crop for ML", "cells \"\"\" # nms to get rid of cells boxes = torch.zeros((len(cells), 4))", "to pop off list elements from an int64 tensor ind_bool = torch.zeros(len(cells)) ind_bool[ind]", "labels: Tensor = out['labels'].cpu() # The model output coords with respect to the", "= calculate_indexes(10, 235, x, x) # [[0, 255], [30, 285], ...] y_ind: List[List[int]]", "if labels[i] == 1 else 'IHC', boxes=boxes[i, :], scores=scores[i])) cell_id += 1 #", "dtype: {image_base.dtype}') if image_base.max() < scale * 0.33: warn(f'WARNING: Image max value less", "for c in cells]) # number of ohc ihc = sum([int(c.type == 'IHC')", "best frequency cells = [c for c in cells if not c._distance_is_far_away] #", "may overlap. We remove cells after analysis is complete. cells: List[Cell] = _cell_nms(cells,", "of image_base. We have to adjust # idk why the y and x", "cell detection algorithm...') if f is None: warn('ERROR: No File to Analyze... \\nAborting.',", "torch.zeros((len(cells), 4)) scores = torch.zeros(len(cells)) for i, c in enumerate(cells): boxes[i, :] =", "io import os.path from typing import Optional, List, Dict # DOCUMENTED def _detect(f:", "adjust # idk why the y and x are flipped. Breaks otherwise. boxes[:,", ":], distance) # calculate cell's best frequency cells = [c for c in", "the entire image. :param *str* f: path to image by which to analyze", "correct_pixel_size, scale_to_hair_cell_diameter from hcat.lib.cell import Cell from hcat.lib.cochlea import Cochlea from hcat.backends.detection import", "tqdm import tqdm from itertools import product import numpy as np from hcat.lib.explore_lif", "respect to the crop of image_base. We have to adjust # idk why", "# [[0, 255], [30, 285], ...] y_ind: List[List[int]] = calculate_indexes(10, 235, y, y)", "= torchvision.ops.box_convert(boxes, 'xyxy', 'cxcywh').cpu() cx = centers[:, 0] cy = centers[:, 1] for", "model(image.float())[0] scores: Tensor = out['scores'].cpu() boxes: Tensor = out['boxes'].cpu() labels: Tensor = out['labels'].cpu()", "for i, score in enumerate(scores): if score > cell_detection_threshold: add_cell(Cell(id=cell_id, loc=torch.tensor([0, cx[i], cy[i],", "remove cells after analysis is complete. cells: List[Cell] = _cell_nms(cells, nms_threshold) ohc =", "image by which to analyze :param *float* cell_detection_threshold: cells below threshold are rejected", "= torch.from_numpy(image_base.astype(np.uint16) / scale).to(device) if pixel_size is not None: image_base: Tensor = correct_pixel_size(image_base," ]
[ "userver.object.gateway import Gateway, Location from utils.errors import KeyDuplicateError, PatchError from .forms.form_gateway import AddGatewayForm,", "{} for key, value in add_gateway.errors.items(): errors[key] = value[0] return Response(status=406, response=json.dumps({\"errors\": errors}))", "add_gateway): mac_addr = add_gateway['mac_addr'].data name = add_gateway['name'].data platform = add_gateway['platform'].data freq_plan = add_gateway['freq_plan'].data", ":param user: :param gateway: :return: \"\"\" gateway.get_pull_info() @api.route(root + 'gateways/<gateway_id>', methods=['GET', 'DELETE', 'PATCH',", "= [] gateways = Gateway.query.filter_by(user_id=user.id) for gateway in gateways: dict = gateway.obj_to_dict() gateways_list.append(dict)", "try: gateway = import_gateway(user, add_gateway) gateway.save() new_gateway = Gateway.query.get(gateway.id) return Response(status=201, response=json.dumps(new_gateway.obj_to_dict())) except", "= AddGatewayForm(formdata) if add_gateway.validate(): try: gateway = import_gateway(user, add_gateway) gateway.save() new_gateway = Gateway.query.get(gateway.id)", "Gateway.query.get(gateway.id) return Response(status=201, response=json.dumps(new_gateway.obj_to_dict())) except KeyDuplicateError as error: errors = {'mac_addr': str(error)} return", "as error: errors = {'mac_addr': str(error)} return Response(status=406, response=json.dumps({\"errors\": errors})) except AssertionError as", "return Response(status=406, response=json.dumps({\"errors\": errors})) @api.route(root + 'gateways/<gateway_id>/pull_info', methods=['GET']) @require_basic_or_oauth @gateway_belong_to_user def gateway_pull_info(user, gateway):", "user: :param gateway: :return: \"\"\" gateway.get_pull_info() @api.route(root + 'gateways/<gateway_id>', methods=['GET', 'DELETE', 'PATCH', 'POST'])", "json.dumps(gateway.obj_to_dict()), 200 except (AssertionError, PatchError, ValueError) as error: return json.dumps({'errors': str(error)}), 406 elif", "204 else: return 'Unknown cmd %s ' % formdata['cmd'], 406 else: return '',", "freq_plan = add_gateway['freq_plan'].data model = add_gateway['model'].data location = Location(add_gateway['longitude'].data, add_gateway['latitude'].data, add_gateway['altitude'].data) return Gateway(user.id,", "errors[key] = value[0] return Response(status=406, response=json.dumps({\"errors\": errors})) @api.route(root + 'gateways/<gateway_id>/pull_info', methods=['GET']) @require_basic_or_oauth @gateway_belong_to_user", "Gateway, Location from utils.errors import KeyDuplicateError, PatchError from .forms.form_gateway import AddGatewayForm, PatchGateway from", "request.method == 'PATCH': try: formdata = get_formdata_from_json_or_form(request) PatchGateway.patch(gateway, formdata) return json.dumps(gateway.obj_to_dict()), 200 except", "200 elif request.method == 'POST': formdata = get_formdata_from_json_or_form(request) if formdata and formdata.get('cmd') is", "else: return '', 406 def import_gateway(user, add_gateway): mac_addr = add_gateway['mac_addr'].data name = add_gateway['name'].data", "+ 'gateways/<gateway_id>/pull_info', methods=['GET']) @require_basic_or_oauth @gateway_belong_to_user def gateway_pull_info(user, gateway): \"\"\" :param user: :param gateway:", "'DELETE', 'PATCH', 'POST']) @require_basic_or_oauth @gateway_belong_to_user def gateway(user, gateway): if request.method == 'GET': return", "not None: if formdata['cmd'] == 'restart': gateway.send_restart_request() return '', 204 else: return 'Unknown", "for gateway in gateways: dict = gateway.obj_to_dict() gateways_list.append(dict) data = json.dumps(gateways_list) return Response(status=200,", "gateways_list.append(dict) data = json.dumps(gateways_list) return Response(status=200, response=data) elif request.method == 'POST': formdata =", "add_gateway = AddGatewayForm(formdata) if add_gateway.validate(): try: gateway = import_gateway(user, add_gateway) gateway.save() new_gateway =", "add_gateway) gateway.save() new_gateway = Gateway.query.get(gateway.id) return Response(status=201, response=json.dumps(new_gateway.obj_to_dict())) except KeyDuplicateError as error: errors", "formdata = get_formdata_from_json_or_form(request) if formdata and formdata.get('cmd') is not None: if formdata['cmd'] ==", "KeyDuplicateError as error: errors = {'mac_addr': str(error)} return Response(status=406, response=json.dumps({\"errors\": errors})) except AssertionError", "return '', 406 def import_gateway(user, add_gateway): mac_addr = add_gateway['mac_addr'].data name = add_gateway['name'].data platform", "in gateways: dict = gateway.obj_to_dict() gateways_list.append(dict) data = json.dumps(gateways_list) return Response(status=200, response=data) elif", "'', 406 def import_gateway(user, add_gateway): mac_addr = add_gateway['mac_addr'].data name = add_gateway['name'].data platform =", "errors = {'mac_addr': str(error)} return Response(status=406, response=json.dumps({\"errors\": errors})) except AssertionError as error: return", "PatchError from .forms.form_gateway import AddGatewayForm, PatchGateway from flask import request, Response from .forms", "@api.route(root + 'gateways', methods=['GET', 'POST']) @require_basic_or_oauth def gateways(user): if request.method == 'GET': gateways_list", "if formdata and formdata.get('cmd') is not None: if formdata['cmd'] == 'restart': gateway.send_restart_request() return", "AssertionError as error: return Response(status=406, response=json.dumps({\"errors\": {\"other\": str(error)}})) else: errors = {} for", "'POST': formdata = get_formdata_from_json_or_form(request) if formdata and formdata.get('cmd') is not None: if formdata['cmd']", "PatchGateway from flask import request, Response from .forms import get_formdata_from_json_or_form @api.route(root + 'gateways',", "Response(status=406, response=json.dumps({\"errors\": errors})) @api.route(root + 'gateways/<gateway_id>/pull_info', methods=['GET']) @require_basic_or_oauth @gateway_belong_to_user def gateway_pull_info(user, gateway): \"\"\"", "Response from .forms import get_formdata_from_json_or_form @api.route(root + 'gateways', methods=['GET', 'POST']) @require_basic_or_oauth def gateways(user):", "response=json.dumps({\"errors\": errors})) except AssertionError as error: return Response(status=406, response=json.dumps({\"errors\": {\"other\": str(error)}})) else: errors", "'GET': return Response(status=200, response=json.dumps(gateway.obj_to_dict())) elif request.method == 'PATCH': try: formdata = get_formdata_from_json_or_form(request) PatchGateway.patch(gateway,", "Gateway.query.filter_by(user_id=user.id) for gateway in gateways: dict = gateway.obj_to_dict() gateways_list.append(dict) data = json.dumps(gateways_list) return", "return Response(status=406, response=json.dumps({\"errors\": {\"other\": str(error)}})) else: errors = {} for key, value in", "= Gateway.query.get(gateway.id) return Response(status=201, response=json.dumps(new_gateway.obj_to_dict())) except KeyDuplicateError as error: errors = {'mac_addr': str(error)}", "root from .decorators import gateway_belong_to_user, require_basic_or_oauth from userver.object.gateway import Gateway, Location from utils.errors", "AddGatewayForm(formdata) if add_gateway.validate(): try: gateway = import_gateway(user, add_gateway) gateway.save() new_gateway = Gateway.query.get(gateway.id) return", "{\"other\": str(error)}})) else: errors = {} for key, value in add_gateway.errors.items(): errors[key] =", "Response(status=200, response=json.dumps(gateway.obj_to_dict())) elif request.method == 'PATCH': try: formdata = get_formdata_from_json_or_form(request) PatchGateway.patch(gateway, formdata) return", "return '', 204 else: return 'Unknown cmd %s ' % formdata['cmd'], 406 else:", "= add_gateway['mac_addr'].data name = add_gateway['name'].data platform = add_gateway['platform'].data freq_plan = add_gateway['freq_plan'].data model =", "406 elif request.method == 'DELETE': gateway.delete() return json.dumps({'success': True}), 200 elif request.method ==", "gateway.delete() return json.dumps({'success': True}), 200 elif request.method == 'POST': formdata = get_formdata_from_json_or_form(request) if", "gateway_belong_to_user, require_basic_or_oauth from userver.object.gateway import Gateway, Location from utils.errors import KeyDuplicateError, PatchError from", "'Unknown cmd %s ' % formdata['cmd'], 406 else: return '', 406 def import_gateway(user,", "gateway.save() new_gateway = Gateway.query.get(gateway.id) return Response(status=201, response=json.dumps(new_gateway.obj_to_dict())) except KeyDuplicateError as error: errors =", "import request, Response from .forms import get_formdata_from_json_or_form @api.route(root + 'gateways', methods=['GET', 'POST']) @require_basic_or_oauth", "dict = gateway.obj_to_dict() gateways_list.append(dict) data = json.dumps(gateways_list) return Response(status=200, response=data) elif request.method ==", "gateway): if request.method == 'GET': return Response(status=200, response=json.dumps(gateway.obj_to_dict())) elif request.method == 'PATCH': try:", "gateway.get_pull_info() @api.route(root + 'gateways/<gateway_id>', methods=['GET', 'DELETE', 'PATCH', 'POST']) @require_basic_or_oauth @gateway_belong_to_user def gateway(user, gateway):", "\"\"\" gateway.get_pull_info() @api.route(root + 'gateways/<gateway_id>', methods=['GET', 'DELETE', 'PATCH', 'POST']) @require_basic_or_oauth @gateway_belong_to_user def gateway(user,", "import Gateway, Location from utils.errors import KeyDuplicateError, PatchError from .forms.form_gateway import AddGatewayForm, PatchGateway", "= Gateway.query.filter_by(user_id=user.id) for gateway in gateways: dict = gateway.obj_to_dict() gateways_list.append(dict) data = json.dumps(gateways_list)", "elif request.method == 'PATCH': try: formdata = get_formdata_from_json_or_form(request) PatchGateway.patch(gateway, formdata) return json.dumps(gateway.obj_to_dict()), 200", "'POST']) @require_basic_or_oauth @gateway_belong_to_user def gateway(user, gateway): if request.method == 'GET': return Response(status=200, response=json.dumps(gateway.obj_to_dict()))", "= add_gateway['platform'].data freq_plan = add_gateway['freq_plan'].data model = add_gateway['model'].data location = Location(add_gateway['longitude'].data, add_gateway['latitude'].data, add_gateway['altitude'].data)", "from .decorators import gateway_belong_to_user, require_basic_or_oauth from userver.object.gateway import Gateway, Location from utils.errors import", "request.method == 'GET': gateways_list = [] gateways = Gateway.query.filter_by(user_id=user.id) for gateway in gateways:", "methods=['GET', 'DELETE', 'PATCH', 'POST']) @require_basic_or_oauth @gateway_belong_to_user def gateway(user, gateway): if request.method == 'GET':", "platform = add_gateway['platform'].data freq_plan = add_gateway['freq_plan'].data model = add_gateway['model'].data location = Location(add_gateway['longitude'].data, add_gateway['latitude'].data,", "'GET': gateways_list = [] gateways = Gateway.query.filter_by(user_id=user.id) for gateway in gateways: dict =", "return Response(status=200, response=json.dumps(gateway.obj_to_dict())) elif request.method == 'PATCH': try: formdata = get_formdata_from_json_or_form(request) PatchGateway.patch(gateway, formdata)", "and formdata.get('cmd') is not None: if formdata['cmd'] == 'restart': gateway.send_restart_request() return '', 204", "== 'GET': gateways_list = [] gateways = Gateway.query.filter_by(user_id=user.id) for gateway in gateways: dict", "gateway in gateways: dict = gateway.obj_to_dict() gateways_list.append(dict) data = json.dumps(gateways_list) return Response(status=200, response=data)", "new_gateway = Gateway.query.get(gateway.id) return Response(status=201, response=json.dumps(new_gateway.obj_to_dict())) except KeyDuplicateError as error: errors = {'mac_addr':", "'gateways/<gateway_id>/pull_info', methods=['GET']) @require_basic_or_oauth @gateway_belong_to_user def gateway_pull_info(user, gateway): \"\"\" :param user: :param gateway: :return:", "def gateway(user, gateway): if request.method == 'GET': return Response(status=200, response=json.dumps(gateway.obj_to_dict())) elif request.method ==", "if formdata['cmd'] == 'restart': gateway.send_restart_request() return '', 204 else: return 'Unknown cmd %s", "def import_gateway(user, add_gateway): mac_addr = add_gateway['mac_addr'].data name = add_gateway['name'].data platform = add_gateway['platform'].data freq_plan", "None: if formdata['cmd'] == 'restart': gateway.send_restart_request() return '', 204 else: return 'Unknown cmd", "key, value in add_gateway.errors.items(): errors[key] = value[0] return Response(status=406, response=json.dumps({\"errors\": errors})) @api.route(root +", "elif request.method == 'DELETE': gateway.delete() return json.dumps({'success': True}), 200 elif request.method == 'POST':", "as error: return Response(status=406, response=json.dumps({\"errors\": {\"other\": str(error)}})) else: errors = {} for key,", "== 'restart': gateway.send_restart_request() return '', 204 else: return 'Unknown cmd %s ' %", "from .forms.form_gateway import AddGatewayForm, PatchGateway from flask import request, Response from .forms import", "'POST']) @require_basic_or_oauth def gateways(user): if request.method == 'GET': gateways_list = [] gateways =", ".decorators import gateway_belong_to_user, require_basic_or_oauth from userver.object.gateway import Gateway, Location from utils.errors import KeyDuplicateError,", "\"\"\" :param user: :param gateway: :return: \"\"\" gateway.get_pull_info() @api.route(root + 'gateways/<gateway_id>', methods=['GET', 'DELETE',", "error: return Response(status=406, response=json.dumps({\"errors\": {\"other\": str(error)}})) else: errors = {} for key, value", "import KeyDuplicateError, PatchError from .forms.form_gateway import AddGatewayForm, PatchGateway from flask import request, Response", "str(error)} return Response(status=406, response=json.dumps({\"errors\": errors})) except AssertionError as error: return Response(status=406, response=json.dumps({\"errors\": {\"other\":", "errors = {} for key, value in add_gateway.errors.items(): errors[key] = value[0] return Response(status=406,", "errors})) @api.route(root + 'gateways/<gateway_id>/pull_info', methods=['GET']) @require_basic_or_oauth @gateway_belong_to_user def gateway_pull_info(user, gateway): \"\"\" :param user:", "except (AssertionError, PatchError, ValueError) as error: return json.dumps({'errors': str(error)}), 406 elif request.method ==", "add_gateway['freq_plan'].data model = add_gateway['model'].data location = Location(add_gateway['longitude'].data, add_gateway['latitude'].data, add_gateway['altitude'].data) return Gateway(user.id, mac_addr, name,", "= {} for key, value in add_gateway.errors.items(): errors[key] = value[0] return Response(status=406, response=json.dumps({\"errors\":", "formdata and formdata.get('cmd') is not None: if formdata['cmd'] == 'restart': gateway.send_restart_request() return '',", "api, root from .decorators import gateway_belong_to_user, require_basic_or_oauth from userver.object.gateway import Gateway, Location from", ".forms import get_formdata_from_json_or_form @api.route(root + 'gateways', methods=['GET', 'POST']) @require_basic_or_oauth def gateways(user): if request.method", "406 def import_gateway(user, add_gateway): mac_addr = add_gateway['mac_addr'].data name = add_gateway['name'].data platform = add_gateway['platform'].data", "add_gateway.validate(): try: gateway = import_gateway(user, add_gateway) gateway.save() new_gateway = Gateway.query.get(gateway.id) return Response(status=201, response=json.dumps(new_gateway.obj_to_dict()))", "elif request.method == 'POST': formdata = get_formdata_from_json_or_form(request) if formdata and formdata.get('cmd') is not", "value in add_gateway.errors.items(): errors[key] = value[0] return Response(status=406, response=json.dumps({\"errors\": errors})) @api.route(root + 'gateways/<gateway_id>/pull_info',", "formdata = get_formdata_from_json_or_form(request) PatchGateway.patch(gateway, formdata) return json.dumps(gateway.obj_to_dict()), 200 except (AssertionError, PatchError, ValueError) as", "200 except (AssertionError, PatchError, ValueError) as error: return json.dumps({'errors': str(error)}), 406 elif request.method", "utils.errors import KeyDuplicateError, PatchError from .forms.form_gateway import AddGatewayForm, PatchGateway from flask import request,", "Location from utils.errors import KeyDuplicateError, PatchError from .forms.form_gateway import AddGatewayForm, PatchGateway from flask", "value[0] return Response(status=406, response=json.dumps({\"errors\": errors})) @api.route(root + 'gateways/<gateway_id>/pull_info', methods=['GET']) @require_basic_or_oauth @gateway_belong_to_user def gateway_pull_info(user,", "= add_gateway['name'].data platform = add_gateway['platform'].data freq_plan = add_gateway['freq_plan'].data model = add_gateway['model'].data location =", "flask import request, Response from .forms import get_formdata_from_json_or_form @api.route(root + 'gateways', methods=['GET', 'POST'])", "methods=['GET', 'POST']) @require_basic_or_oauth def gateways(user): if request.method == 'GET': gateways_list = [] gateways", "return json.dumps(gateway.obj_to_dict()), 200 except (AssertionError, PatchError, ValueError) as error: return json.dumps({'errors': str(error)}), 406", "from .forms import get_formdata_from_json_or_form @api.route(root + 'gateways', methods=['GET', 'POST']) @require_basic_or_oauth def gateways(user): if", "PatchError, ValueError) as error: return json.dumps({'errors': str(error)}), 406 elif request.method == 'DELETE': gateway.delete()", "@require_basic_or_oauth @gateway_belong_to_user def gateway(user, gateway): if request.method == 'GET': return Response(status=200, response=json.dumps(gateway.obj_to_dict())) elif", "'gateways', methods=['GET', 'POST']) @require_basic_or_oauth def gateways(user): if request.method == 'GET': gateways_list = []", "json from . import api, root from .decorators import gateway_belong_to_user, require_basic_or_oauth from userver.object.gateway", ".forms.form_gateway import AddGatewayForm, PatchGateway from flask import request, Response from .forms import get_formdata_from_json_or_form", "= {'mac_addr': str(error)} return Response(status=406, response=json.dumps({\"errors\": errors})) except AssertionError as error: return Response(status=406,", "gateway(user, gateway): if request.method == 'GET': return Response(status=200, response=json.dumps(gateway.obj_to_dict())) elif request.method == 'PATCH':", "gateways_list = [] gateways = Gateway.query.filter_by(user_id=user.id) for gateway in gateways: dict = gateway.obj_to_dict()", "406 else: return '', 406 def import_gateway(user, add_gateway): mac_addr = add_gateway['mac_addr'].data name =", "= get_formdata_from_json_or_form(request) add_gateway = AddGatewayForm(formdata) if add_gateway.validate(): try: gateway = import_gateway(user, add_gateway) gateway.save()", "== 'GET': return Response(status=200, response=json.dumps(gateway.obj_to_dict())) elif request.method == 'PATCH': try: formdata = get_formdata_from_json_or_form(request)", "model = add_gateway['model'].data location = Location(add_gateway['longitude'].data, add_gateway['latitude'].data, add_gateway['altitude'].data) return Gateway(user.id, mac_addr, name, platform,", "location = Location(add_gateway['longitude'].data, add_gateway['latitude'].data, add_gateway['altitude'].data) return Gateway(user.id, mac_addr, name, platform, model, freq_plan=freq_plan, location=location)", "KeyDuplicateError, PatchError from .forms.form_gateway import AddGatewayForm, PatchGateway from flask import request, Response from", "except AssertionError as error: return Response(status=406, response=json.dumps({\"errors\": {\"other\": str(error)}})) else: errors = {}", "try: formdata = get_formdata_from_json_or_form(request) PatchGateway.patch(gateway, formdata) return json.dumps(gateway.obj_to_dict()), 200 except (AssertionError, PatchError, ValueError)", "json.dumps({'errors': str(error)}), 406 elif request.method == 'DELETE': gateway.delete() return json.dumps({'success': True}), 200 elif", "response=json.dumps({\"errors\": errors})) @api.route(root + 'gateways/<gateway_id>/pull_info', methods=['GET']) @require_basic_or_oauth @gateway_belong_to_user def gateway_pull_info(user, gateway): \"\"\" :param", "request.method == 'GET': return Response(status=200, response=json.dumps(gateway.obj_to_dict())) elif request.method == 'PATCH': try: formdata =", "name = add_gateway['name'].data platform = add_gateway['platform'].data freq_plan = add_gateway['freq_plan'].data model = add_gateway['model'].data location", "formdata['cmd'], 406 else: return '', 406 def import_gateway(user, add_gateway): mac_addr = add_gateway['mac_addr'].data name", "return json.dumps({'errors': str(error)}), 406 elif request.method == 'DELETE': gateway.delete() return json.dumps({'success': True}), 200", "formdata.get('cmd') is not None: if formdata['cmd'] == 'restart': gateway.send_restart_request() return '', 204 else:", "str(error)}})) else: errors = {} for key, value in add_gateway.errors.items(): errors[key] = value[0]", "import json from . import api, root from .decorators import gateway_belong_to_user, require_basic_or_oauth from", "' % formdata['cmd'], 406 else: return '', 406 def import_gateway(user, add_gateway): mac_addr =", "= add_gateway['model'].data location = Location(add_gateway['longitude'].data, add_gateway['latitude'].data, add_gateway['altitude'].data) return Gateway(user.id, mac_addr, name, platform, model,", "cmd %s ' % formdata['cmd'], 406 else: return '', 406 def import_gateway(user, add_gateway):", "require_basic_or_oauth from userver.object.gateway import Gateway, Location from utils.errors import KeyDuplicateError, PatchError from .forms.form_gateway", "= get_formdata_from_json_or_form(request) if formdata and formdata.get('cmd') is not None: if formdata['cmd'] == 'restart':", "= gateway.obj_to_dict() gateways_list.append(dict) data = json.dumps(gateways_list) return Response(status=200, response=data) elif request.method == 'POST':", "error: return json.dumps({'errors': str(error)}), 406 elif request.method == 'DELETE': gateway.delete() return json.dumps({'success': True}),", "True}), 200 elif request.method == 'POST': formdata = get_formdata_from_json_or_form(request) if formdata and formdata.get('cmd')", "from flask import request, Response from .forms import get_formdata_from_json_or_form @api.route(root + 'gateways', methods=['GET',", "Response(status=406, response=json.dumps({\"errors\": {\"other\": str(error)}})) else: errors = {} for key, value in add_gateway.errors.items():", "== 'DELETE': gateway.delete() return json.dumps({'success': True}), 200 elif request.method == 'POST': formdata =", "else: return 'Unknown cmd %s ' % formdata['cmd'], 406 else: return '', 406", "== 'POST': formdata = get_formdata_from_json_or_form(request) if formdata and formdata.get('cmd') is not None: if", "json.dumps({'success': True}), 200 elif request.method == 'POST': formdata = get_formdata_from_json_or_form(request) if formdata and", "import gateway_belong_to_user, require_basic_or_oauth from userver.object.gateway import Gateway, Location from utils.errors import KeyDuplicateError, PatchError", "gateway): \"\"\" :param user: :param gateway: :return: \"\"\" gateway.get_pull_info() @api.route(root + 'gateways/<gateway_id>', methods=['GET',", "is not None: if formdata['cmd'] == 'restart': gateway.send_restart_request() return '', 204 else: return", "add_gateway['mac_addr'].data name = add_gateway['name'].data platform = add_gateway['platform'].data freq_plan = add_gateway['freq_plan'].data model = add_gateway['model'].data", "add_gateway['name'].data platform = add_gateway['platform'].data freq_plan = add_gateway['freq_plan'].data model = add_gateway['model'].data location = Location(add_gateway['longitude'].data,", "'gateways/<gateway_id>', methods=['GET', 'DELETE', 'PATCH', 'POST']) @require_basic_or_oauth @gateway_belong_to_user def gateway(user, gateway): if request.method ==", "def gateways(user): if request.method == 'GET': gateways_list = [] gateways = Gateway.query.filter_by(user_id=user.id) for", "gateway = import_gateway(user, add_gateway) gateway.save() new_gateway = Gateway.query.get(gateway.id) return Response(status=201, response=json.dumps(new_gateway.obj_to_dict())) except KeyDuplicateError", "request.method == 'DELETE': gateway.delete() return json.dumps({'success': True}), 200 elif request.method == 'POST': formdata", "return json.dumps({'success': True}), 200 elif request.method == 'POST': formdata = get_formdata_from_json_or_form(request) if formdata", "except KeyDuplicateError as error: errors = {'mac_addr': str(error)} return Response(status=406, response=json.dumps({\"errors\": errors})) except", "@require_basic_or_oauth def gateways(user): if request.method == 'GET': gateways_list = [] gateways = Gateway.query.filter_by(user_id=user.id)", "formdata['cmd'] == 'restart': gateway.send_restart_request() return '', 204 else: return 'Unknown cmd %s '", "{'mac_addr': str(error)} return Response(status=406, response=json.dumps({\"errors\": errors})) except AssertionError as error: return Response(status=406, response=json.dumps({\"errors\":", "% formdata['cmd'], 406 else: return '', 406 def import_gateway(user, add_gateway): mac_addr = add_gateway['mac_addr'].data", "return Response(status=406, response=json.dumps({\"errors\": errors})) except AssertionError as error: return Response(status=406, response=json.dumps({\"errors\": {\"other\": str(error)}}))", "return 'Unknown cmd %s ' % formdata['cmd'], 406 else: return '', 406 def", "import_gateway(user, add_gateway) gateway.save() new_gateway = Gateway.query.get(gateway.id) return Response(status=201, response=json.dumps(new_gateway.obj_to_dict())) except KeyDuplicateError as error:", "add_gateway['model'].data location = Location(add_gateway['longitude'].data, add_gateway['latitude'].data, add_gateway['altitude'].data) return Gateway(user.id, mac_addr, name, platform, model, freq_plan=freq_plan,", "'POST': formdata = get_formdata_from_json_or_form(request) add_gateway = AddGatewayForm(formdata) if add_gateway.validate(): try: gateway = import_gateway(user,", "get_formdata_from_json_or_form @api.route(root + 'gateways', methods=['GET', 'POST']) @require_basic_or_oauth def gateways(user): if request.method == 'GET':", "if add_gateway.validate(): try: gateway = import_gateway(user, add_gateway) gateway.save() new_gateway = Gateway.query.get(gateway.id) return Response(status=201,", ":param gateway: :return: \"\"\" gateway.get_pull_info() @api.route(root + 'gateways/<gateway_id>', methods=['GET', 'DELETE', 'PATCH', 'POST']) @require_basic_or_oauth", "request, Response from .forms import get_formdata_from_json_or_form @api.route(root + 'gateways', methods=['GET', 'POST']) @require_basic_or_oauth def", "gateway.send_restart_request() return '', 204 else: return 'Unknown cmd %s ' % formdata['cmd'], 406", "ValueError) as error: return json.dumps({'errors': str(error)}), 406 elif request.method == 'DELETE': gateway.delete() return", "for key, value in add_gateway.errors.items(): errors[key] = value[0] return Response(status=406, response=json.dumps({\"errors\": errors})) @api.route(root", "Response(status=200, response=data) elif request.method == 'POST': formdata = get_formdata_from_json_or_form(request) add_gateway = AddGatewayForm(formdata) if", "@gateway_belong_to_user def gateway(user, gateway): if request.method == 'GET': return Response(status=200, response=json.dumps(gateway.obj_to_dict())) elif request.method", "+ 'gateways', methods=['GET', 'POST']) @require_basic_or_oauth def gateways(user): if request.method == 'GET': gateways_list =", "import_gateway(user, add_gateway): mac_addr = add_gateway['mac_addr'].data name = add_gateway['name'].data platform = add_gateway['platform'].data freq_plan =", "json.dumps(gateways_list) return Response(status=200, response=data) elif request.method == 'POST': formdata = get_formdata_from_json_or_form(request) add_gateway =", "get_formdata_from_json_or_form(request) add_gateway = AddGatewayForm(formdata) if add_gateway.validate(): try: gateway = import_gateway(user, add_gateway) gateway.save() new_gateway", "@gateway_belong_to_user def gateway_pull_info(user, gateway): \"\"\" :param user: :param gateway: :return: \"\"\" gateway.get_pull_info() @api.route(root", "from userver.object.gateway import Gateway, Location from utils.errors import KeyDuplicateError, PatchError from .forms.form_gateway import", "import api, root from .decorators import gateway_belong_to_user, require_basic_or_oauth from userver.object.gateway import Gateway, Location", "data = json.dumps(gateways_list) return Response(status=200, response=data) elif request.method == 'POST': formdata = get_formdata_from_json_or_form(request)", "(AssertionError, PatchError, ValueError) as error: return json.dumps({'errors': str(error)}), 406 elif request.method == 'DELETE':", "response=json.dumps({\"errors\": {\"other\": str(error)}})) else: errors = {} for key, value in add_gateway.errors.items(): errors[key]", "'', 204 else: return 'Unknown cmd %s ' % formdata['cmd'], 406 else: return", "add_gateway.errors.items(): errors[key] = value[0] return Response(status=406, response=json.dumps({\"errors\": errors})) @api.route(root + 'gateways/<gateway_id>/pull_info', methods=['GET']) @require_basic_or_oauth", "@api.route(root + 'gateways/<gateway_id>', methods=['GET', 'DELETE', 'PATCH', 'POST']) @require_basic_or_oauth @gateway_belong_to_user def gateway(user, gateway): if", "@require_basic_or_oauth @gateway_belong_to_user def gateway_pull_info(user, gateway): \"\"\" :param user: :param gateway: :return: \"\"\" gateway.get_pull_info()", "from . import api, root from .decorators import gateway_belong_to_user, require_basic_or_oauth from userver.object.gateway import", "return Response(status=200, response=data) elif request.method == 'POST': formdata = get_formdata_from_json_or_form(request) add_gateway = AddGatewayForm(formdata)", "response=json.dumps(gateway.obj_to_dict())) elif request.method == 'PATCH': try: formdata = get_formdata_from_json_or_form(request) PatchGateway.patch(gateway, formdata) return json.dumps(gateway.obj_to_dict()),", "if request.method == 'GET': gateways_list = [] gateways = Gateway.query.filter_by(user_id=user.id) for gateway in", "gateways: dict = gateway.obj_to_dict() gateways_list.append(dict) data = json.dumps(gateways_list) return Response(status=200, response=data) elif request.method", "gateway: :return: \"\"\" gateway.get_pull_info() @api.route(root + 'gateways/<gateway_id>', methods=['GET', 'DELETE', 'PATCH', 'POST']) @require_basic_or_oauth @gateway_belong_to_user", "= get_formdata_from_json_or_form(request) PatchGateway.patch(gateway, formdata) return json.dumps(gateway.obj_to_dict()), 200 except (AssertionError, PatchError, ValueError) as error:", "import AddGatewayForm, PatchGateway from flask import request, Response from .forms import get_formdata_from_json_or_form @api.route(root", "gateway.obj_to_dict() gateways_list.append(dict) data = json.dumps(gateways_list) return Response(status=200, response=data) elif request.method == 'POST': formdata", ". import api, root from .decorators import gateway_belong_to_user, require_basic_or_oauth from userver.object.gateway import Gateway,", "elif request.method == 'POST': formdata = get_formdata_from_json_or_form(request) add_gateway = AddGatewayForm(formdata) if add_gateway.validate(): try:", "error: errors = {'mac_addr': str(error)} return Response(status=406, response=json.dumps({\"errors\": errors})) except AssertionError as error:", ":return: \"\"\" gateway.get_pull_info() @api.route(root + 'gateways/<gateway_id>', methods=['GET', 'DELETE', 'PATCH', 'POST']) @require_basic_or_oauth @gateway_belong_to_user def", "get_formdata_from_json_or_form(request) if formdata and formdata.get('cmd') is not None: if formdata['cmd'] == 'restart': gateway.send_restart_request()", "= json.dumps(gateways_list) return Response(status=200, response=data) elif request.method == 'POST': formdata = get_formdata_from_json_or_form(request) add_gateway", "mac_addr = add_gateway['mac_addr'].data name = add_gateway['name'].data platform = add_gateway['platform'].data freq_plan = add_gateway['freq_plan'].data model", "response=json.dumps(new_gateway.obj_to_dict())) except KeyDuplicateError as error: errors = {'mac_addr': str(error)} return Response(status=406, response=json.dumps({\"errors\": errors}))", "formdata) return json.dumps(gateway.obj_to_dict()), 200 except (AssertionError, PatchError, ValueError) as error: return json.dumps({'errors': str(error)}),", "[] gateways = Gateway.query.filter_by(user_id=user.id) for gateway in gateways: dict = gateway.obj_to_dict() gateways_list.append(dict) data", "response=data) elif request.method == 'POST': formdata = get_formdata_from_json_or_form(request) add_gateway = AddGatewayForm(formdata) if add_gateway.validate():", "errors})) except AssertionError as error: return Response(status=406, response=json.dumps({\"errors\": {\"other\": str(error)}})) else: errors =", "@api.route(root + 'gateways/<gateway_id>/pull_info', methods=['GET']) @require_basic_or_oauth @gateway_belong_to_user def gateway_pull_info(user, gateway): \"\"\" :param user: :param", "== 'PATCH': try: formdata = get_formdata_from_json_or_form(request) PatchGateway.patch(gateway, formdata) return json.dumps(gateway.obj_to_dict()), 200 except (AssertionError,", "PatchGateway.patch(gateway, formdata) return json.dumps(gateway.obj_to_dict()), 200 except (AssertionError, PatchError, ValueError) as error: return json.dumps({'errors':", "%s ' % formdata['cmd'], 406 else: return '', 406 def import_gateway(user, add_gateway): mac_addr", "import get_formdata_from_json_or_form @api.route(root + 'gateways', methods=['GET', 'POST']) @require_basic_or_oauth def gateways(user): if request.method ==", "= add_gateway['freq_plan'].data model = add_gateway['model'].data location = Location(add_gateway['longitude'].data, add_gateway['latitude'].data, add_gateway['altitude'].data) return Gateway(user.id, mac_addr,", "AddGatewayForm, PatchGateway from flask import request, Response from .forms import get_formdata_from_json_or_form @api.route(root +", "'PATCH': try: formdata = get_formdata_from_json_or_form(request) PatchGateway.patch(gateway, formdata) return json.dumps(gateway.obj_to_dict()), 200 except (AssertionError, PatchError,", "as error: return json.dumps({'errors': str(error)}), 406 elif request.method == 'DELETE': gateway.delete() return json.dumps({'success':", "Response(status=406, response=json.dumps({\"errors\": errors})) except AssertionError as error: return Response(status=406, response=json.dumps({\"errors\": {\"other\": str(error)}})) else:", "else: errors = {} for key, value in add_gateway.errors.items(): errors[key] = value[0] return", "in add_gateway.errors.items(): errors[key] = value[0] return Response(status=406, response=json.dumps({\"errors\": errors})) @api.route(root + 'gateways/<gateway_id>/pull_info', methods=['GET'])", "if request.method == 'GET': return Response(status=200, response=json.dumps(gateway.obj_to_dict())) elif request.method == 'PATCH': try: formdata", "== 'POST': formdata = get_formdata_from_json_or_form(request) add_gateway = AddGatewayForm(formdata) if add_gateway.validate(): try: gateway =", "def gateway_pull_info(user, gateway): \"\"\" :param user: :param gateway: :return: \"\"\" gateway.get_pull_info() @api.route(root +", "Response(status=201, response=json.dumps(new_gateway.obj_to_dict())) except KeyDuplicateError as error: errors = {'mac_addr': str(error)} return Response(status=406, response=json.dumps({\"errors\":", "+ 'gateways/<gateway_id>', methods=['GET', 'DELETE', 'PATCH', 'POST']) @require_basic_or_oauth @gateway_belong_to_user def gateway(user, gateway): if request.method", "'DELETE': gateway.delete() return json.dumps({'success': True}), 200 elif request.method == 'POST': formdata = get_formdata_from_json_or_form(request)", "add_gateway['platform'].data freq_plan = add_gateway['freq_plan'].data model = add_gateway['model'].data location = Location(add_gateway['longitude'].data, add_gateway['latitude'].data, add_gateway['altitude'].data) return", "request.method == 'POST': formdata = get_formdata_from_json_or_form(request) add_gateway = AddGatewayForm(formdata) if add_gateway.validate(): try: gateway", "return Response(status=201, response=json.dumps(new_gateway.obj_to_dict())) except KeyDuplicateError as error: errors = {'mac_addr': str(error)} return Response(status=406,", "gateway_pull_info(user, gateway): \"\"\" :param user: :param gateway: :return: \"\"\" gateway.get_pull_info() @api.route(root + 'gateways/<gateway_id>',", "= import_gateway(user, add_gateway) gateway.save() new_gateway = Gateway.query.get(gateway.id) return Response(status=201, response=json.dumps(new_gateway.obj_to_dict())) except KeyDuplicateError as", "= value[0] return Response(status=406, response=json.dumps({\"errors\": errors})) @api.route(root + 'gateways/<gateway_id>/pull_info', methods=['GET']) @require_basic_or_oauth @gateway_belong_to_user def", "formdata = get_formdata_from_json_or_form(request) add_gateway = AddGatewayForm(formdata) if add_gateway.validate(): try: gateway = import_gateway(user, add_gateway)", "gateways = Gateway.query.filter_by(user_id=user.id) for gateway in gateways: dict = gateway.obj_to_dict() gateways_list.append(dict) data =", "str(error)}), 406 elif request.method == 'DELETE': gateway.delete() return json.dumps({'success': True}), 200 elif request.method", "'restart': gateway.send_restart_request() return '', 204 else: return 'Unknown cmd %s ' % formdata['cmd'],", "'PATCH', 'POST']) @require_basic_or_oauth @gateway_belong_to_user def gateway(user, gateway): if request.method == 'GET': return Response(status=200,", "gateways(user): if request.method == 'GET': gateways_list = [] gateways = Gateway.query.filter_by(user_id=user.id) for gateway", "from utils.errors import KeyDuplicateError, PatchError from .forms.form_gateway import AddGatewayForm, PatchGateway from flask import", "request.method == 'POST': formdata = get_formdata_from_json_or_form(request) if formdata and formdata.get('cmd') is not None:", "get_formdata_from_json_or_form(request) PatchGateway.patch(gateway, formdata) return json.dumps(gateway.obj_to_dict()), 200 except (AssertionError, PatchError, ValueError) as error: return", "methods=['GET']) @require_basic_or_oauth @gateway_belong_to_user def gateway_pull_info(user, gateway): \"\"\" :param user: :param gateway: :return: \"\"\"" ]
[ "'ReadControlPanel' ToFirstPuckAndGrabFirstPuck = 'ToFirstPuckAndGrabFirstPuck' ToFirstCornerAndReleaseFirstPuck = 'ToFirstCornerAndReleaseFirstPuck' ToSecondPuckAndGrabSecondPuck = 'ToSecondPuckAndGrabSecondPuck' ToSecondCornerAndReleaseSecondPuck = 'ToSecondCornerAndReleaseSecondPuck'", "'ToControlPanel' ReadControlPanel = 'ReadControlPanel' ToFirstPuckAndGrabFirstPuck = 'ToFirstPuckAndGrabFirstPuck' ToFirstCornerAndReleaseFirstPuck = 'ToFirstCornerAndReleaseFirstPuck' ToSecondPuckAndGrabSecondPuck = 'ToSecondPuckAndGrabSecondPuck'", "Enum import rospy from std_msgs.msg import String class Step(Enum): CycleNotStarted = 'CycleNotStarted' CycleReadyInWaitingMode", "class Step(Enum): CycleNotStarted = 'CycleNotStarted' CycleReadyInWaitingMode = 'CycleReadyInWaitingMode' CycleStarted = 'CycleStarted' ToResistanceStation =", "String class Step(Enum): CycleNotStarted = 'CycleNotStarted' CycleReadyInWaitingMode = 'CycleReadyInWaitingMode' CycleStarted = 'CycleStarted' ToResistanceStation", "ToResistanceStation = 'ToResistanceStation' ReadResistance = 'ReadResistance' ToControlPanel = 'ToControlPanel' ReadControlPanel = 'ReadControlPanel' ToFirstPuckAndGrabFirstPuck", "import Enum import rospy from std_msgs.msg import String class Step(Enum): CycleNotStarted = 'CycleNotStarted'", "std_msgs.msg import String class Step(Enum): CycleNotStarted = 'CycleNotStarted' CycleReadyInWaitingMode = 'CycleReadyInWaitingMode' CycleStarted =", "'ToResistanceStation' ReadResistance = 'ReadResistance' ToControlPanel = 'ToControlPanel' ReadControlPanel = 'ReadControlPanel' ToFirstPuckAndGrabFirstPuck = 'ToFirstPuckAndGrabFirstPuck'", "ToFirstCornerAndReleaseFirstPuck = 'ToFirstCornerAndReleaseFirstPuck' ToSecondPuckAndGrabSecondPuck = 'ToSecondPuckAndGrabSecondPuck' ToSecondCornerAndReleaseSecondPuck = 'ToSecondCornerAndReleaseSecondPuck' ToThirdPuckAndGrabThirdPuck = 'ToThirdPuckAndGrabThirdPuck' ToThirdCornerAndReleaseThirdPuck", "= 'ToResistanceStation' ReadResistance = 'ReadResistance' ToControlPanel = 'ToControlPanel' ReadControlPanel = 'ReadControlPanel' ToFirstPuckAndGrabFirstPuck =", "Step(Enum): CycleNotStarted = 'CycleNotStarted' CycleReadyInWaitingMode = 'CycleReadyInWaitingMode' CycleStarted = 'CycleStarted' ToResistanceStation = 'ToResistanceStation'", "import random from enum import Enum import rospy from std_msgs.msg import String class", "'CycleReadyInWaitingMode' CycleStarted = 'CycleStarted' ToResistanceStation = 'ToResistanceStation' ReadResistance = 'ReadResistance' ToControlPanel = 'ToControlPanel'", "'CycleStarted' ToResistanceStation = 'ToResistanceStation' ReadResistance = 'ReadResistance' ToControlPanel = 'ToControlPanel' ReadControlPanel = 'ReadControlPanel'", "pub.publish(step) if __name__ == '__main__': rospy.init_node('mock_current_step', anonymous=True) current_step_publisher = rospy.Publisher('current_step', String, queue_size=10) mock_current_step(current_step_publisher)", "CycleReadyInWaitingMode = 'CycleReadyInWaitingMode' CycleStarted = 'CycleStarted' ToResistanceStation = 'ToResistanceStation' ReadResistance = 'ReadResistance' ToControlPanel", "'ToThirdPuckAndGrabThirdPuck' ToThirdCornerAndReleaseThirdPuck = 'ToThirdCornerAndReleaseThirdPuck' ToSquareCenter = 'ToSquareCenter' CycleEndedAndRedLedOn = 'CycleEndedAndRedLedOn' def create_current_step(): return", "mock_current_step(pub, step=create_current_step()): rospy.loginfo('Mocking current_step: {}'.format(step)) pub.publish(step) if __name__ == '__main__': rospy.init_node('mock_current_step', anonymous=True) current_step_publisher", "ToControlPanel = 'ToControlPanel' ReadControlPanel = 'ReadControlPanel' ToFirstPuckAndGrabFirstPuck = 'ToFirstPuckAndGrabFirstPuck' ToFirstCornerAndReleaseFirstPuck = 'ToFirstCornerAndReleaseFirstPuck' ToSecondPuckAndGrabSecondPuck", "'CycleEndedAndRedLedOn' def create_current_step(): return random.choice(list(Step)).name def mock_current_step(pub, step=create_current_step()): rospy.loginfo('Mocking current_step: {}'.format(step)) pub.publish(step) if", "def create_current_step(): return random.choice(list(Step)).name def mock_current_step(pub, step=create_current_step()): rospy.loginfo('Mocking current_step: {}'.format(step)) pub.publish(step) if __name__", "import rospy from std_msgs.msg import String class Step(Enum): CycleNotStarted = 'CycleNotStarted' CycleReadyInWaitingMode =", "= 'ToSecondCornerAndReleaseSecondPuck' ToThirdPuckAndGrabThirdPuck = 'ToThirdPuckAndGrabThirdPuck' ToThirdCornerAndReleaseThirdPuck = 'ToThirdCornerAndReleaseThirdPuck' ToSquareCenter = 'ToSquareCenter' CycleEndedAndRedLedOn =", "rospy.loginfo('Mocking current_step: {}'.format(step)) pub.publish(step) if __name__ == '__main__': rospy.init_node('mock_current_step', anonymous=True) current_step_publisher = rospy.Publisher('current_step',", "step=create_current_step()): rospy.loginfo('Mocking current_step: {}'.format(step)) pub.publish(step) if __name__ == '__main__': rospy.init_node('mock_current_step', anonymous=True) current_step_publisher =", "return random.choice(list(Step)).name def mock_current_step(pub, step=create_current_step()): rospy.loginfo('Mocking current_step: {}'.format(step)) pub.publish(step) if __name__ == '__main__':", "def mock_current_step(pub, step=create_current_step()): rospy.loginfo('Mocking current_step: {}'.format(step)) pub.publish(step) if __name__ == '__main__': rospy.init_node('mock_current_step', anonymous=True)", "enum import Enum import rospy from std_msgs.msg import String class Step(Enum): CycleNotStarted =", "ToSecondCornerAndReleaseSecondPuck = 'ToSecondCornerAndReleaseSecondPuck' ToThirdPuckAndGrabThirdPuck = 'ToThirdPuckAndGrabThirdPuck' ToThirdCornerAndReleaseThirdPuck = 'ToThirdCornerAndReleaseThirdPuck' ToSquareCenter = 'ToSquareCenter' CycleEndedAndRedLedOn", "<gh_stars>0 import random from enum import Enum import rospy from std_msgs.msg import String", "= 'ToFirstCornerAndReleaseFirstPuck' ToSecondPuckAndGrabSecondPuck = 'ToSecondPuckAndGrabSecondPuck' ToSecondCornerAndReleaseSecondPuck = 'ToSecondCornerAndReleaseSecondPuck' ToThirdPuckAndGrabThirdPuck = 'ToThirdPuckAndGrabThirdPuck' ToThirdCornerAndReleaseThirdPuck =", "'ToFirstCornerAndReleaseFirstPuck' ToSecondPuckAndGrabSecondPuck = 'ToSecondPuckAndGrabSecondPuck' ToSecondCornerAndReleaseSecondPuck = 'ToSecondCornerAndReleaseSecondPuck' ToThirdPuckAndGrabThirdPuck = 'ToThirdPuckAndGrabThirdPuck' ToThirdCornerAndReleaseThirdPuck = 'ToThirdCornerAndReleaseThirdPuck'", "'ToThirdCornerAndReleaseThirdPuck' ToSquareCenter = 'ToSquareCenter' CycleEndedAndRedLedOn = 'CycleEndedAndRedLedOn' def create_current_step(): return random.choice(list(Step)).name def mock_current_step(pub,", "'ReadResistance' ToControlPanel = 'ToControlPanel' ReadControlPanel = 'ReadControlPanel' ToFirstPuckAndGrabFirstPuck = 'ToFirstPuckAndGrabFirstPuck' ToFirstCornerAndReleaseFirstPuck = 'ToFirstCornerAndReleaseFirstPuck'", "rospy from std_msgs.msg import String class Step(Enum): CycleNotStarted = 'CycleNotStarted' CycleReadyInWaitingMode = 'CycleReadyInWaitingMode'", "= 'CycleEndedAndRedLedOn' def create_current_step(): return random.choice(list(Step)).name def mock_current_step(pub, step=create_current_step()): rospy.loginfo('Mocking current_step: {}'.format(step)) pub.publish(step)", "from enum import Enum import rospy from std_msgs.msg import String class Step(Enum): CycleNotStarted", "= 'ReadResistance' ToControlPanel = 'ToControlPanel' ReadControlPanel = 'ReadControlPanel' ToFirstPuckAndGrabFirstPuck = 'ToFirstPuckAndGrabFirstPuck' ToFirstCornerAndReleaseFirstPuck =", "= 'ToSquareCenter' CycleEndedAndRedLedOn = 'CycleEndedAndRedLedOn' def create_current_step(): return random.choice(list(Step)).name def mock_current_step(pub, step=create_current_step()): rospy.loginfo('Mocking", "= 'ToControlPanel' ReadControlPanel = 'ReadControlPanel' ToFirstPuckAndGrabFirstPuck = 'ToFirstPuckAndGrabFirstPuck' ToFirstCornerAndReleaseFirstPuck = 'ToFirstCornerAndReleaseFirstPuck' ToSecondPuckAndGrabSecondPuck =", "from std_msgs.msg import String class Step(Enum): CycleNotStarted = 'CycleNotStarted' CycleReadyInWaitingMode = 'CycleReadyInWaitingMode' CycleStarted", "= 'ToThirdCornerAndReleaseThirdPuck' ToSquareCenter = 'ToSquareCenter' CycleEndedAndRedLedOn = 'CycleEndedAndRedLedOn' def create_current_step(): return random.choice(list(Step)).name def", "= 'CycleNotStarted' CycleReadyInWaitingMode = 'CycleReadyInWaitingMode' CycleStarted = 'CycleStarted' ToResistanceStation = 'ToResistanceStation' ReadResistance =", "ReadResistance = 'ReadResistance' ToControlPanel = 'ToControlPanel' ReadControlPanel = 'ReadControlPanel' ToFirstPuckAndGrabFirstPuck = 'ToFirstPuckAndGrabFirstPuck' ToFirstCornerAndReleaseFirstPuck", "= 'ReadControlPanel' ToFirstPuckAndGrabFirstPuck = 'ToFirstPuckAndGrabFirstPuck' ToFirstCornerAndReleaseFirstPuck = 'ToFirstCornerAndReleaseFirstPuck' ToSecondPuckAndGrabSecondPuck = 'ToSecondPuckAndGrabSecondPuck' ToSecondCornerAndReleaseSecondPuck =", "create_current_step(): return random.choice(list(Step)).name def mock_current_step(pub, step=create_current_step()): rospy.loginfo('Mocking current_step: {}'.format(step)) pub.publish(step) if __name__ ==", "random from enum import Enum import rospy from std_msgs.msg import String class Step(Enum):", "'CycleNotStarted' CycleReadyInWaitingMode = 'CycleReadyInWaitingMode' CycleStarted = 'CycleStarted' ToResistanceStation = 'ToResistanceStation' ReadResistance = 'ReadResistance'", "ToFirstPuckAndGrabFirstPuck = 'ToFirstPuckAndGrabFirstPuck' ToFirstCornerAndReleaseFirstPuck = 'ToFirstCornerAndReleaseFirstPuck' ToSecondPuckAndGrabSecondPuck = 'ToSecondPuckAndGrabSecondPuck' ToSecondCornerAndReleaseSecondPuck = 'ToSecondCornerAndReleaseSecondPuck' ToThirdPuckAndGrabThirdPuck", "= 'CycleStarted' ToResistanceStation = 'ToResistanceStation' ReadResistance = 'ReadResistance' ToControlPanel = 'ToControlPanel' ReadControlPanel =", "ReadControlPanel = 'ReadControlPanel' ToFirstPuckAndGrabFirstPuck = 'ToFirstPuckAndGrabFirstPuck' ToFirstCornerAndReleaseFirstPuck = 'ToFirstCornerAndReleaseFirstPuck' ToSecondPuckAndGrabSecondPuck = 'ToSecondPuckAndGrabSecondPuck' ToSecondCornerAndReleaseSecondPuck", "current_step: {}'.format(step)) pub.publish(step) if __name__ == '__main__': rospy.init_node('mock_current_step', anonymous=True) current_step_publisher = rospy.Publisher('current_step', String,", "= 'ToSecondPuckAndGrabSecondPuck' ToSecondCornerAndReleaseSecondPuck = 'ToSecondCornerAndReleaseSecondPuck' ToThirdPuckAndGrabThirdPuck = 'ToThirdPuckAndGrabThirdPuck' ToThirdCornerAndReleaseThirdPuck = 'ToThirdCornerAndReleaseThirdPuck' ToSquareCenter =", "= 'ToFirstPuckAndGrabFirstPuck' ToFirstCornerAndReleaseFirstPuck = 'ToFirstCornerAndReleaseFirstPuck' ToSecondPuckAndGrabSecondPuck = 'ToSecondPuckAndGrabSecondPuck' ToSecondCornerAndReleaseSecondPuck = 'ToSecondCornerAndReleaseSecondPuck' ToThirdPuckAndGrabThirdPuck =", "CycleEndedAndRedLedOn = 'CycleEndedAndRedLedOn' def create_current_step(): return random.choice(list(Step)).name def mock_current_step(pub, step=create_current_step()): rospy.loginfo('Mocking current_step: {}'.format(step))", "CycleStarted = 'CycleStarted' ToResistanceStation = 'ToResistanceStation' ReadResistance = 'ReadResistance' ToControlPanel = 'ToControlPanel' ReadControlPanel", "CycleNotStarted = 'CycleNotStarted' CycleReadyInWaitingMode = 'CycleReadyInWaitingMode' CycleStarted = 'CycleStarted' ToResistanceStation = 'ToResistanceStation' ReadResistance", "'ToFirstPuckAndGrabFirstPuck' ToFirstCornerAndReleaseFirstPuck = 'ToFirstCornerAndReleaseFirstPuck' ToSecondPuckAndGrabSecondPuck = 'ToSecondPuckAndGrabSecondPuck' ToSecondCornerAndReleaseSecondPuck = 'ToSecondCornerAndReleaseSecondPuck' ToThirdPuckAndGrabThirdPuck = 'ToThirdPuckAndGrabThirdPuck'", "'ToSecondPuckAndGrabSecondPuck' ToSecondCornerAndReleaseSecondPuck = 'ToSecondCornerAndReleaseSecondPuck' ToThirdPuckAndGrabThirdPuck = 'ToThirdPuckAndGrabThirdPuck' ToThirdCornerAndReleaseThirdPuck = 'ToThirdCornerAndReleaseThirdPuck' ToSquareCenter = 'ToSquareCenter'", "random.choice(list(Step)).name def mock_current_step(pub, step=create_current_step()): rospy.loginfo('Mocking current_step: {}'.format(step)) pub.publish(step) if __name__ == '__main__': rospy.init_node('mock_current_step',", "import String class Step(Enum): CycleNotStarted = 'CycleNotStarted' CycleReadyInWaitingMode = 'CycleReadyInWaitingMode' CycleStarted = 'CycleStarted'", "= 'CycleReadyInWaitingMode' CycleStarted = 'CycleStarted' ToResistanceStation = 'ToResistanceStation' ReadResistance = 'ReadResistance' ToControlPanel =", "ToThirdPuckAndGrabThirdPuck = 'ToThirdPuckAndGrabThirdPuck' ToThirdCornerAndReleaseThirdPuck = 'ToThirdCornerAndReleaseThirdPuck' ToSquareCenter = 'ToSquareCenter' CycleEndedAndRedLedOn = 'CycleEndedAndRedLedOn' def", "{}'.format(step)) pub.publish(step) if __name__ == '__main__': rospy.init_node('mock_current_step', anonymous=True) current_step_publisher = rospy.Publisher('current_step', String, queue_size=10)", "'ToSecondCornerAndReleaseSecondPuck' ToThirdPuckAndGrabThirdPuck = 'ToThirdPuckAndGrabThirdPuck' ToThirdCornerAndReleaseThirdPuck = 'ToThirdCornerAndReleaseThirdPuck' ToSquareCenter = 'ToSquareCenter' CycleEndedAndRedLedOn = 'CycleEndedAndRedLedOn'", "ToThirdCornerAndReleaseThirdPuck = 'ToThirdCornerAndReleaseThirdPuck' ToSquareCenter = 'ToSquareCenter' CycleEndedAndRedLedOn = 'CycleEndedAndRedLedOn' def create_current_step(): return random.choice(list(Step)).name", "ToSquareCenter = 'ToSquareCenter' CycleEndedAndRedLedOn = 'CycleEndedAndRedLedOn' def create_current_step(): return random.choice(list(Step)).name def mock_current_step(pub, step=create_current_step()):", "'ToSquareCenter' CycleEndedAndRedLedOn = 'CycleEndedAndRedLedOn' def create_current_step(): return random.choice(list(Step)).name def mock_current_step(pub, step=create_current_step()): rospy.loginfo('Mocking current_step:", "= 'ToThirdPuckAndGrabThirdPuck' ToThirdCornerAndReleaseThirdPuck = 'ToThirdCornerAndReleaseThirdPuck' ToSquareCenter = 'ToSquareCenter' CycleEndedAndRedLedOn = 'CycleEndedAndRedLedOn' def create_current_step():", "ToSecondPuckAndGrabSecondPuck = 'ToSecondPuckAndGrabSecondPuck' ToSecondCornerAndReleaseSecondPuck = 'ToSecondCornerAndReleaseSecondPuck' ToThirdPuckAndGrabThirdPuck = 'ToThirdPuckAndGrabThirdPuck' ToThirdCornerAndReleaseThirdPuck = 'ToThirdCornerAndReleaseThirdPuck' ToSquareCenter" ]
[ "ALMAClassifier from .glm import LinearRegression, LogisticRegression, Perceptron from .pa import PAClassifier, PARegressor from", "import LinearRegression, LogisticRegression, Perceptron from .pa import PAClassifier, PARegressor from .softmax import SoftmaxRegression", ".softmax import SoftmaxRegression __all__ = [ \"ALMAClassifier\", \"LinearRegression\", \"LogisticRegression\", \"PAClassifier\", \"PARegressor\", \"Perceptron\", \"SoftmaxRegression\",", "import PAClassifier, PARegressor from .softmax import SoftmaxRegression __all__ = [ \"ALMAClassifier\", \"LinearRegression\", \"LogisticRegression\",", "Perceptron from .pa import PAClassifier, PARegressor from .softmax import SoftmaxRegression __all__ = [", "import ALMAClassifier from .glm import LinearRegression, LogisticRegression, Perceptron from .pa import PAClassifier, PARegressor", "from .pa import PAClassifier, PARegressor from .softmax import SoftmaxRegression __all__ = [ \"ALMAClassifier\",", "from .alma import ALMAClassifier from .glm import LinearRegression, LogisticRegression, Perceptron from .pa import", ".alma import ALMAClassifier from .glm import LinearRegression, LogisticRegression, Perceptron from .pa import PAClassifier,", "LogisticRegression, Perceptron from .pa import PAClassifier, PARegressor from .softmax import SoftmaxRegression __all__ =", ".pa import PAClassifier, PARegressor from .softmax import SoftmaxRegression __all__ = [ \"ALMAClassifier\", \"LinearRegression\",", "PAClassifier, PARegressor from .softmax import SoftmaxRegression __all__ = [ \"ALMAClassifier\", \"LinearRegression\", \"LogisticRegression\", \"PAClassifier\",", ".glm import LinearRegression, LogisticRegression, Perceptron from .pa import PAClassifier, PARegressor from .softmax import", "import SoftmaxRegression __all__ = [ \"ALMAClassifier\", \"LinearRegression\", \"LogisticRegression\", \"PAClassifier\", \"PARegressor\", \"Perceptron\", \"SoftmaxRegression\", ]", "from .softmax import SoftmaxRegression __all__ = [ \"ALMAClassifier\", \"LinearRegression\", \"LogisticRegression\", \"PAClassifier\", \"PARegressor\", \"Perceptron\",", "LinearRegression, LogisticRegression, Perceptron from .pa import PAClassifier, PARegressor from .softmax import SoftmaxRegression __all__", "\"\"\"Linear models.\"\"\" from .alma import ALMAClassifier from .glm import LinearRegression, LogisticRegression, Perceptron from", "from .glm import LinearRegression, LogisticRegression, Perceptron from .pa import PAClassifier, PARegressor from .softmax", "PARegressor from .softmax import SoftmaxRegression __all__ = [ \"ALMAClassifier\", \"LinearRegression\", \"LogisticRegression\", \"PAClassifier\", \"PARegressor\",", "models.\"\"\" from .alma import ALMAClassifier from .glm import LinearRegression, LogisticRegression, Perceptron from .pa" ]
[]
[ "import * from tkinter import ttk import mysql.connector import sqlalchemy import json import", "Entry(entry_screen, textvariable = Pressure).place(x=140, y=122) # Label for displaying entry status[success/failed] Label(entry_screen, text", "StringVar() # Creating layout of Data Entry Form Label(entry_screen, width=\"300\", text=\"Please enter details", "(recorddate, temperature, pressure , CreatedBy) try: # executing the sql command Epi_con.execute(sql, data)", "y=82) # Pressure Label Label(entry_screen, text = \"Pressure * \").place(x=20, y=120) # Pressure", "temperature = Temperature.get() pressure = Pressure.get() recorddate = (dt.date.today()).strftime('%Y-%m-%d') CreatedBy = getpass.getuser() #", "recorddate = (dt.date.today()).strftime('%Y-%m-%d') CreatedBy = getpass.getuser() # applying empty validation if temperature ==", "entry form def entry(): # getting form data temperature = Temperature.get() pressure =", "data = (recorddate, temperature, pressure , CreatedBy) try: # executing the sql command", "IntVar() RecordDate = StringVar() CreatedBy = StringVar() message = StringVar() # Creating layout", "\"\"\" data = (recorddate, temperature, pressure , CreatedBy) try: # executing the sql", "displaying entry status[success/failed] Label(entry_screen, text = \"\", textvariable=message).place(x=95, y=240) # Submit Button Button(entry_screen,", "entry(): # getting form data temperature = Temperature.get() pressure = Pressure.get() recorddate =", "%s) \"\"\" data = (recorddate, temperature, pressure , CreatedBy) try: # executing the", "width of screen entry_screen.geometry(\"400x270\") # declaring variable global message global RecordDate global Temperature", "dependencies from tkinter import * from tkinter import ttk import mysql.connector import sqlalchemy", "Pressure = IntVar() RecordDate = StringVar() CreatedBy = StringVar() message = StringVar() #", "message = StringVar() # Creating layout of Data Entry Form Label(entry_screen, width=\"300\", text=\"Please", "form data temperature = Temperature.get() pressure = Pressure.get() recorddate = (dt.date.today()).strftime('%Y-%m-%d') CreatedBy =", "Temperature textbox Entry(entry_screen, textvariable= Temperature).place(x=140, y=82) # Pressure Label Label(entry_screen, text = \"Pressure", "empty validation if temperature == '' or pressure =='' or recorddate == ''", "or recorddate == '' or CreatedBy == '': message.set(\"fill the empty field!!!\") else:", "\").place(x=20, y=80) # Temperature textbox Entry(entry_screen, textvariable= Temperature).place(x=140, y=82) # Pressure Label Label(entry_screen,", "Create connection object to Epi Epi_con = engine.connect() # Preparing SQL query to", "global RecordDate global Temperature global Pressure global CreatedBy Temperature = IntVar() Pressure =", "VALUES (%s, %s, %s, %s) \"\"\" data = (recorddate, temperature, pressure , CreatedBy)", "Entry Form\") # setting height and width of screen entry_screen.geometry(\"400x270\") # declaring variable", "message.set(\"Data Stored successfully\") #def read(): #def update(): #def delete(): #def dbsetup(): # defining", "layout of Data Entry Form Label(entry_screen, width=\"300\", text=\"Please enter details below\", bg=\"blue\", fg=\"white\").pack()", "echo=False) # Defining entry form def entry(): # getting form data temperature =", "textbox Entry(entry_screen, textvariable= Temperature).place(x=140, y=82) # Pressure Label Label(entry_screen, text = \"Pressure *", "'': message.set(\"fill the empty field!!!\") else: # Create connection object to Epi Epi_con", "from tkinter import * from tkinter import ttk import mysql.connector import sqlalchemy import", "'' or CreatedBy == '': message.set(\"fill the empty field!!!\") else: # Create connection", "Temperature = IntVar() Pressure = IntVar() RecordDate = StringVar() CreatedBy = StringVar() message", "# Pressure textbox Entry(entry_screen, textvariable = Pressure).place(x=140, y=122) # Label for displaying entry", "y=210) Button(entry_screen, text=\"Update\", width=10, height=1, bg=\"gray\", command=entry).place(x=205, y=210) Button(entry_screen, text=\"Delete\", width=10, height=1, bg=\"gray\",", "data) # commit changes in database Epi_con.commit() except: message.set(\"Data Stored successfully\") #def read():", "Label Label(entry_screen, text = \"Pressure * \").place(x=20, y=120) # Pressure textbox Entry(entry_screen, textvariable", "\"Temperature * \").place(x=20, y=80) # Temperature textbox Entry(entry_screen, textvariable= Temperature).place(x=140, y=82) # Pressure", "Button(entry_screen, text=\"Update\", width=10, height=1, bg=\"gray\", command=entry).place(x=205, y=210) Button(entry_screen, text=\"Delete\", width=10, height=1, bg=\"gray\", command=entry).place(x=305,", "textvariable = Pressure).place(x=140, y=122) # Label for displaying entry status[success/failed] Label(entry_screen, text =", "Data Entry Form Label(entry_screen, width=\"300\", text=\"Please enter details below\", bg=\"blue\", fg=\"white\").pack() # Temperature", "height=1, bg=\"gray\", command=entry).place(x=105, y=210) Button(entry_screen, text=\"Update\", width=10, height=1, bg=\"gray\", command=entry).place(x=205, y=210) Button(entry_screen, text=\"Delete\",", "\"\"\"INSERT INTO crudexample (RecordDate, Temperature, Pressure,CreatedBy) VALUES (%s, %s, %s, %s) \"\"\" data", "# Import dependencies from tkinter import * from tkinter import ttk import mysql.connector", "# Submit Button Button(entry_screen, text=\"Submit\", width=10, height=1, bg=\"gray\", command=entry).place(x=105, y=210) Button(entry_screen, text=\"Update\", width=10,", "from tkinter import ttk import mysql.connector import sqlalchemy import json import datetime as", "Epi_con.commit() except: message.set(\"Data Stored successfully\") #def read(): #def update(): #def delete(): #def dbsetup():", "#def dbsetup(): # defining Registration form function def Entryform(): global entry_screen entry_screen =", "empty field!!!\") else: # Create connection object to Epi Epi_con = engine.connect() #", "Stored successfully\") #def read(): #def update(): #def delete(): #def dbsetup(): # defining Registration", "details below\", bg=\"blue\", fg=\"white\").pack() # Temperature Label Label(entry_screen, text= \"Temperature * \").place(x=20, y=80)", "# Label for displaying entry status[success/failed] Label(entry_screen, text = \"\", textvariable=message).place(x=95, y=240) #", "Epi_con.execute(sql, data) # commit changes in database Epi_con.commit() except: message.set(\"Data Stored successfully\") #def", "= (recorddate, temperature, pressure , CreatedBy) try: # executing the sql command Epi_con.execute(sql,", "in database Epi_con.commit() except: message.set(\"Data Stored successfully\") #def read(): #def update(): #def delete():", "entry_screen entry_screen = Tk() # Setting title of screen entry_screen.title(\"Data Entry Form\") #", "#def delete(): #def dbsetup(): # defining Registration form function def Entryform(): global entry_screen", "pressure , CreatedBy) try: # executing the sql command Epi_con.execute(sql, data) # commit", "sql command Epi_con.execute(sql, data) # commit changes in database Epi_con.commit() except: message.set(\"Data Stored", "Form\") # setting height and width of screen entry_screen.geometry(\"400x270\") # declaring variable global", "for displaying entry status[success/failed] Label(entry_screen, text = \"\", textvariable=message).place(x=95, y=240) # Submit Button", "Button(entry_screen, text=\"Submit\", width=10, height=1, bg=\"gray\", command=entry).place(x=105, y=210) Button(entry_screen, text=\"Update\", width=10, height=1, bg=\"gray\", command=entry).place(x=205,", "width=10, height=1, bg=\"gray\", command=entry).place(x=205, y=210) Button(entry_screen, text=\"Delete\", width=10, height=1, bg=\"gray\", command=entry).place(x=305, y=210) entry_screen.mainloop()", "param = json.load(config) # Establishing engine engine = sqlalchemy.create_engine('mysql+mysqlconnector://{0}:{1}@{2}/{3}'. format(param['Teletron'][0]['user'], param['Teletron'][0]['password'], param['Teletron'][0]['host'], param['Teletron'][0]['database']),", "query to INSERT a record into the database. sql = \"\"\"INSERT INTO crudexample", "connection object to Epi Epi_con = engine.connect() # Preparing SQL query to INSERT", "temperature, pressure , CreatedBy) try: # executing the sql command Epi_con.execute(sql, data) #", "database. sql = \"\"\"INSERT INTO crudexample (RecordDate, Temperature, Pressure,CreatedBy) VALUES (%s, %s, %s,", "(%s, %s, %s, %s) \"\"\" data = (recorddate, temperature, pressure , CreatedBy) try:", "entry status[success/failed] Label(entry_screen, text = \"\", textvariable=message).place(x=95, y=240) # Submit Button Button(entry_screen, text=\"Submit\",", "= \"\", textvariable=message).place(x=95, y=240) # Submit Button Button(entry_screen, text=\"Submit\", width=10, height=1, bg=\"gray\", command=entry).place(x=105,", "dbsetup(): # defining Registration form function def Entryform(): global entry_screen entry_screen = Tk()", "Label(entry_screen, width=\"300\", text=\"Please enter details below\", bg=\"blue\", fg=\"white\").pack() # Temperature Label Label(entry_screen, text=", "y=120) # Pressure textbox Entry(entry_screen, textvariable = Pressure).place(x=140, y=122) # Label for displaying", "tkinter import ttk import mysql.connector import sqlalchemy import json import datetime as dt", "defining Registration form function def Entryform(): global entry_screen entry_screen = Tk() # Setting", "= Temperature.get() pressure = Pressure.get() recorddate = (dt.date.today()).strftime('%Y-%m-%d') CreatedBy = getpass.getuser() # applying", "executing the sql command Epi_con.execute(sql, data) # commit changes in database Epi_con.commit() except:", "= \"Pressure * \").place(x=20, y=120) # Pressure textbox Entry(entry_screen, textvariable = Pressure).place(x=140, y=122)", "height and width of screen entry_screen.geometry(\"400x270\") # declaring variable global message global RecordDate", "Tk() # Setting title of screen entry_screen.title(\"Data Entry Form\") # setting height and", "Form Label(entry_screen, width=\"300\", text=\"Please enter details below\", bg=\"blue\", fg=\"white\").pack() # Temperature Label Label(entry_screen,", "Button Button(entry_screen, text=\"Submit\", width=10, height=1, bg=\"gray\", command=entry).place(x=105, y=210) Button(entry_screen, text=\"Update\", width=10, height=1, bg=\"gray\",", "try: # executing the sql command Epi_con.execute(sql, data) # commit changes in database", "param['Teletron'][0]['host'], param['Teletron'][0]['database']), echo=False) # Defining entry form def entry(): # getting form data", "import sqlalchemy import json import datetime as dt import getpass import mysql with", "%s, %s) \"\"\" data = (recorddate, temperature, pressure , CreatedBy) try: # executing", "command=entry).place(x=105, y=210) Button(entry_screen, text=\"Update\", width=10, height=1, bg=\"gray\", command=entry).place(x=205, y=210) Button(entry_screen, text=\"Delete\", width=10, height=1,", "textbox Entry(entry_screen, textvariable = Pressure).place(x=140, y=122) # Label for displaying entry status[success/failed] Label(entry_screen,", "Label(entry_screen, text = \"\", textvariable=message).place(x=95, y=240) # Submit Button Button(entry_screen, text=\"Submit\", width=10, height=1,", "as dt import getpass import mysql with open(\"parameters/config.json\") as config: param = json.load(config)", "of screen entry_screen.geometry(\"400x270\") # declaring variable global message global RecordDate global Temperature global", "text = \"Pressure * \").place(x=20, y=120) # Pressure textbox Entry(entry_screen, textvariable = Pressure).place(x=140,", "Button(entry_screen, text=\"Delete\", width=10, height=1, bg=\"gray\", command=entry).place(x=305, y=210) entry_screen.mainloop() # calling function entry form", "dt import getpass import mysql with open(\"parameters/config.json\") as config: param = json.load(config) #", "global Pressure global CreatedBy Temperature = IntVar() Pressure = IntVar() RecordDate = StringVar()", "if temperature == '' or pressure =='' or recorddate == '' or CreatedBy", "sqlalchemy import json import datetime as dt import getpass import mysql with open(\"parameters/config.json\")", "global entry_screen entry_screen = Tk() # Setting title of screen entry_screen.title(\"Data Entry Form\")", "except: message.set(\"Data Stored successfully\") #def read(): #def update(): #def delete(): #def dbsetup(): #", "Label(entry_screen, text= \"Temperature * \").place(x=20, y=80) # Temperature textbox Entry(entry_screen, textvariable= Temperature).place(x=140, y=82)", "Pressure).place(x=140, y=122) # Label for displaying entry status[success/failed] Label(entry_screen, text = \"\", textvariable=message).place(x=95,", "Pressure textbox Entry(entry_screen, textvariable = Pressure).place(x=140, y=122) # Label for displaying entry status[success/failed]", "text=\"Delete\", width=10, height=1, bg=\"gray\", command=entry).place(x=305, y=210) entry_screen.mainloop() # calling function entry form Entryform()", "= json.load(config) # Establishing engine engine = sqlalchemy.create_engine('mysql+mysqlconnector://{0}:{1}@{2}/{3}'. format(param['Teletron'][0]['user'], param['Teletron'][0]['password'], param['Teletron'][0]['host'], param['Teletron'][0]['database']), echo=False)", "\"\", textvariable=message).place(x=95, y=240) # Submit Button Button(entry_screen, text=\"Submit\", width=10, height=1, bg=\"gray\", command=entry).place(x=105, y=210)", "getpass import mysql with open(\"parameters/config.json\") as config: param = json.load(config) # Establishing engine", "= Tk() # Setting title of screen entry_screen.title(\"Data Entry Form\") # setting height", "below\", bg=\"blue\", fg=\"white\").pack() # Temperature Label Label(entry_screen, text= \"Temperature * \").place(x=20, y=80) #", "= IntVar() Pressure = IntVar() RecordDate = StringVar() CreatedBy = StringVar() message =", "pressure =='' or recorddate == '' or CreatedBy == '': message.set(\"fill the empty", "changes in database Epi_con.commit() except: message.set(\"Data Stored successfully\") #def read(): #def update(): #def", "ttk import mysql.connector import sqlalchemy import json import datetime as dt import getpass", "# applying empty validation if temperature == '' or pressure =='' or recorddate", "engine engine = sqlalchemy.create_engine('mysql+mysqlconnector://{0}:{1}@{2}/{3}'. format(param['Teletron'][0]['user'], param['Teletron'][0]['password'], param['Teletron'][0]['host'], param['Teletron'][0]['database']), echo=False) # Defining entry form", "CreatedBy) try: # executing the sql command Epi_con.execute(sql, data) # commit changes in", "a record into the database. sql = \"\"\"INSERT INTO crudexample (RecordDate, Temperature, Pressure,CreatedBy)", "= getpass.getuser() # applying empty validation if temperature == '' or pressure ==''", "the database. sql = \"\"\"INSERT INTO crudexample (RecordDate, Temperature, Pressure,CreatedBy) VALUES (%s, %s,", "width=\"300\", text=\"Please enter details below\", bg=\"blue\", fg=\"white\").pack() # Temperature Label Label(entry_screen, text= \"Temperature", "screen entry_screen.title(\"Data Entry Form\") # setting height and width of screen entry_screen.geometry(\"400x270\") #", "# Temperature Label Label(entry_screen, text= \"Temperature * \").place(x=20, y=80) # Temperature textbox Entry(entry_screen,", "read(): #def update(): #def delete(): #def dbsetup(): # defining Registration form function def", "screen entry_screen.geometry(\"400x270\") # declaring variable global message global RecordDate global Temperature global Pressure", "y=210) Button(entry_screen, text=\"Delete\", width=10, height=1, bg=\"gray\", command=entry).place(x=305, y=210) entry_screen.mainloop() # calling function entry", "#def update(): #def delete(): #def dbsetup(): # defining Registration form function def Entryform():", "Creating layout of Data Entry Form Label(entry_screen, width=\"300\", text=\"Please enter details below\", bg=\"blue\",", "the sql command Epi_con.execute(sql, data) # commit changes in database Epi_con.commit() except: message.set(\"Data", "Pressure.get() recorddate = (dt.date.today()).strftime('%Y-%m-%d') CreatedBy = getpass.getuser() # applying empty validation if temperature", "== '' or pressure =='' or recorddate == '' or CreatedBy == '':", "* from tkinter import ttk import mysql.connector import sqlalchemy import json import datetime", "entry_screen = Tk() # Setting title of screen entry_screen.title(\"Data Entry Form\") # setting", "Label(entry_screen, text = \"Pressure * \").place(x=20, y=120) # Pressure textbox Entry(entry_screen, textvariable =", "def Entryform(): global entry_screen entry_screen = Tk() # Setting title of screen entry_screen.title(\"Data", "command Epi_con.execute(sql, data) # commit changes in database Epi_con.commit() except: message.set(\"Data Stored successfully\")", "format(param['Teletron'][0]['user'], param['Teletron'][0]['password'], param['Teletron'][0]['host'], param['Teletron'][0]['database']), echo=False) # Defining entry form def entry(): # getting", "Entry Form Label(entry_screen, width=\"300\", text=\"Please enter details below\", bg=\"blue\", fg=\"white\").pack() # Temperature Label", "Temperature).place(x=140, y=82) # Pressure Label Label(entry_screen, text = \"Pressure * \").place(x=20, y=120) #", "# Setting title of screen entry_screen.title(\"Data Entry Form\") # setting height and width", "= sqlalchemy.create_engine('mysql+mysqlconnector://{0}:{1}@{2}/{3}'. format(param['Teletron'][0]['user'], param['Teletron'][0]['password'], param['Teletron'][0]['host'], param['Teletron'][0]['database']), echo=False) # Defining entry form def entry():", "text = \"\", textvariable=message).place(x=95, y=240) # Submit Button Button(entry_screen, text=\"Submit\", width=10, height=1, bg=\"gray\",", "height=1, bg=\"gray\", command=entry).place(x=205, y=210) Button(entry_screen, text=\"Delete\", width=10, height=1, bg=\"gray\", command=entry).place(x=305, y=210) entry_screen.mainloop() #", "getpass.getuser() # applying empty validation if temperature == '' or pressure =='' or", "update(): #def delete(): #def dbsetup(): # defining Registration form function def Entryform(): global", "global Temperature global Pressure global CreatedBy Temperature = IntVar() Pressure = IntVar() RecordDate", "import mysql with open(\"parameters/config.json\") as config: param = json.load(config) # Establishing engine engine", "y=122) # Label for displaying entry status[success/failed] Label(entry_screen, text = \"\", textvariable=message).place(x=95, y=240)", "* \").place(x=20, y=120) # Pressure textbox Entry(entry_screen, textvariable = Pressure).place(x=140, y=122) # Label", "Setting title of screen entry_screen.title(\"Data Entry Form\") # setting height and width of", "open(\"parameters/config.json\") as config: param = json.load(config) # Establishing engine engine = sqlalchemy.create_engine('mysql+mysqlconnector://{0}:{1}@{2}/{3}'. format(param['Teletron'][0]['user'],", "validation if temperature == '' or pressure =='' or recorddate == '' or", "=='' or recorddate == '' or CreatedBy == '': message.set(\"fill the empty field!!!\")", "or CreatedBy == '': message.set(\"fill the empty field!!!\") else: # Create connection object", "CreatedBy == '': message.set(\"fill the empty field!!!\") else: # Create connection object to", "object to Epi Epi_con = engine.connect() # Preparing SQL query to INSERT a", "bg=\"blue\", fg=\"white\").pack() # Temperature Label Label(entry_screen, text= \"Temperature * \").place(x=20, y=80) # Temperature", "Pressure Label Label(entry_screen, text = \"Pressure * \").place(x=20, y=120) # Pressure textbox Entry(entry_screen,", "text=\"Update\", width=10, height=1, bg=\"gray\", command=entry).place(x=205, y=210) Button(entry_screen, text=\"Delete\", width=10, height=1, bg=\"gray\", command=entry).place(x=305, y=210)", "form function def Entryform(): global entry_screen entry_screen = Tk() # Setting title of", "(RecordDate, Temperature, Pressure,CreatedBy) VALUES (%s, %s, %s, %s) \"\"\" data = (recorddate, temperature,", "as config: param = json.load(config) # Establishing engine engine = sqlalchemy.create_engine('mysql+mysqlconnector://{0}:{1}@{2}/{3}'. format(param['Teletron'][0]['user'], param['Teletron'][0]['password'],", "\").place(x=20, y=120) # Pressure textbox Entry(entry_screen, textvariable = Pressure).place(x=140, y=122) # Label for", "Registration form function def Entryform(): global entry_screen entry_screen = Tk() # Setting title", "Entryform(): global entry_screen entry_screen = Tk() # Setting title of screen entry_screen.title(\"Data Entry", "pressure = Pressure.get() recorddate = (dt.date.today()).strftime('%Y-%m-%d') CreatedBy = getpass.getuser() # applying empty validation", "field!!!\") else: # Create connection object to Epi Epi_con = engine.connect() # Preparing", "# commit changes in database Epi_con.commit() except: message.set(\"Data Stored successfully\") #def read(): #def", "#def read(): #def update(): #def delete(): #def dbsetup(): # defining Registration form function", "= IntVar() RecordDate = StringVar() CreatedBy = StringVar() message = StringVar() # Creating", "text=\"Please enter details below\", bg=\"blue\", fg=\"white\").pack() # Temperature Label Label(entry_screen, text= \"Temperature *", "\"Pressure * \").place(x=20, y=120) # Pressure textbox Entry(entry_screen, textvariable = Pressure).place(x=140, y=122) #", "of Data Entry Form Label(entry_screen, width=\"300\", text=\"Please enter details below\", bg=\"blue\", fg=\"white\").pack() #", "Temperature, Pressure,CreatedBy) VALUES (%s, %s, %s, %s) \"\"\" data = (recorddate, temperature, pressure", "entry_screen.title(\"Data Entry Form\") # setting height and width of screen entry_screen.geometry(\"400x270\") # declaring", "datetime as dt import getpass import mysql with open(\"parameters/config.json\") as config: param =", "CreatedBy = StringVar() message = StringVar() # Creating layout of Data Entry Form", "SQL query to INSERT a record into the database. sql = \"\"\"INSERT INTO", "json import datetime as dt import getpass import mysql with open(\"parameters/config.json\") as config:", "StringVar() CreatedBy = StringVar() message = StringVar() # Creating layout of Data Entry", "INTO crudexample (RecordDate, Temperature, Pressure,CreatedBy) VALUES (%s, %s, %s, %s) \"\"\" data =", "'' or pressure =='' or recorddate == '' or CreatedBy == '': message.set(\"fill", "import ttk import mysql.connector import sqlalchemy import json import datetime as dt import", "sql = \"\"\"INSERT INTO crudexample (RecordDate, Temperature, Pressure,CreatedBy) VALUES (%s, %s, %s, %s)", ", CreatedBy) try: # executing the sql command Epi_con.execute(sql, data) # commit changes", "RecordDate global Temperature global Pressure global CreatedBy Temperature = IntVar() Pressure = IntVar()", "tkinter import * from tkinter import ttk import mysql.connector import sqlalchemy import json", "# Preparing SQL query to INSERT a record into the database. sql =", "text=\"Submit\", width=10, height=1, bg=\"gray\", command=entry).place(x=105, y=210) Button(entry_screen, text=\"Update\", width=10, height=1, bg=\"gray\", command=entry).place(x=205, y=210)", "RecordDate = StringVar() CreatedBy = StringVar() message = StringVar() # Creating layout of", "%s, %s, %s) \"\"\" data = (recorddate, temperature, pressure , CreatedBy) try: #", "mysql.connector import sqlalchemy import json import datetime as dt import getpass import mysql", "status[success/failed] Label(entry_screen, text = \"\", textvariable=message).place(x=95, y=240) # Submit Button Button(entry_screen, text=\"Submit\", width=10,", "function def Entryform(): global entry_screen entry_screen = Tk() # Setting title of screen", "# getting form data temperature = Temperature.get() pressure = Pressure.get() recorddate = (dt.date.today()).strftime('%Y-%m-%d')", "engine = sqlalchemy.create_engine('mysql+mysqlconnector://{0}:{1}@{2}/{3}'. format(param['Teletron'][0]['user'], param['Teletron'][0]['password'], param['Teletron'][0]['host'], param['Teletron'][0]['database']), echo=False) # Defining entry form def", "temperature == '' or pressure =='' or recorddate == '' or CreatedBy ==", "and width of screen entry_screen.geometry(\"400x270\") # declaring variable global message global RecordDate global", "message global RecordDate global Temperature global Pressure global CreatedBy Temperature = IntVar() Pressure", "Pressure global CreatedBy Temperature = IntVar() Pressure = IntVar() RecordDate = StringVar() CreatedBy", "bg=\"gray\", command=entry).place(x=205, y=210) Button(entry_screen, text=\"Delete\", width=10, height=1, bg=\"gray\", command=entry).place(x=305, y=210) entry_screen.mainloop() # calling", "title of screen entry_screen.title(\"Data Entry Form\") # setting height and width of screen", "getting form data temperature = Temperature.get() pressure = Pressure.get() recorddate = (dt.date.today()).strftime('%Y-%m-%d') CreatedBy", "= engine.connect() # Preparing SQL query to INSERT a record into the database.", "global message global RecordDate global Temperature global Pressure global CreatedBy Temperature = IntVar()", "# Creating layout of Data Entry Form Label(entry_screen, width=\"300\", text=\"Please enter details below\",", "import datetime as dt import getpass import mysql with open(\"parameters/config.json\") as config: param", "# Create connection object to Epi Epi_con = engine.connect() # Preparing SQL query", "# defining Registration form function def Entryform(): global entry_screen entry_screen = Tk() #", "fg=\"white\").pack() # Temperature Label Label(entry_screen, text= \"Temperature * \").place(x=20, y=80) # Temperature textbox", "json.load(config) # Establishing engine engine = sqlalchemy.create_engine('mysql+mysqlconnector://{0}:{1}@{2}/{3}'. format(param['Teletron'][0]['user'], param['Teletron'][0]['password'], param['Teletron'][0]['host'], param['Teletron'][0]['database']), echo=False) #", "into the database. sql = \"\"\"INSERT INTO crudexample (RecordDate, Temperature, Pressure,CreatedBy) VALUES (%s,", "variable global message global RecordDate global Temperature global Pressure global CreatedBy Temperature =", "textvariable=message).place(x=95, y=240) # Submit Button Button(entry_screen, text=\"Submit\", width=10, height=1, bg=\"gray\", command=entry).place(x=105, y=210) Button(entry_screen,", "CreatedBy Temperature = IntVar() Pressure = IntVar() RecordDate = StringVar() CreatedBy = StringVar()", "to INSERT a record into the database. sql = \"\"\"INSERT INTO crudexample (RecordDate,", "= (dt.date.today()).strftime('%Y-%m-%d') CreatedBy = getpass.getuser() # applying empty validation if temperature == ''", "# Temperature textbox Entry(entry_screen, textvariable= Temperature).place(x=140, y=82) # Pressure Label Label(entry_screen, text =", "Submit Button Button(entry_screen, text=\"Submit\", width=10, height=1, bg=\"gray\", command=entry).place(x=105, y=210) Button(entry_screen, text=\"Update\", width=10, height=1,", "# Pressure Label Label(entry_screen, text = \"Pressure * \").place(x=20, y=120) # Pressure textbox", "else: # Create connection object to Epi Epi_con = engine.connect() # Preparing SQL", "Epi Epi_con = engine.connect() # Preparing SQL query to INSERT a record into", "mysql with open(\"parameters/config.json\") as config: param = json.load(config) # Establishing engine engine =", "global CreatedBy Temperature = IntVar() Pressure = IntVar() RecordDate = StringVar() CreatedBy =", "def entry(): # getting form data temperature = Temperature.get() pressure = Pressure.get() recorddate", "import getpass import mysql with open(\"parameters/config.json\") as config: param = json.load(config) # Establishing", "== '': message.set(\"fill the empty field!!!\") else: # Create connection object to Epi", "StringVar() message = StringVar() # Creating layout of Data Entry Form Label(entry_screen, width=\"300\",", "Temperature global Pressure global CreatedBy Temperature = IntVar() Pressure = IntVar() RecordDate =", "Epi_con = engine.connect() # Preparing SQL query to INSERT a record into the", "of screen entry_screen.title(\"Data Entry Form\") # setting height and width of screen entry_screen.geometry(\"400x270\")", "Establishing engine engine = sqlalchemy.create_engine('mysql+mysqlconnector://{0}:{1}@{2}/{3}'. format(param['Teletron'][0]['user'], param['Teletron'][0]['password'], param['Teletron'][0]['host'], param['Teletron'][0]['database']), echo=False) # Defining entry", "y=240) # Submit Button Button(entry_screen, text=\"Submit\", width=10, height=1, bg=\"gray\", command=entry).place(x=105, y=210) Button(entry_screen, text=\"Update\",", "# setting height and width of screen entry_screen.geometry(\"400x270\") # declaring variable global message", "<filename>GUI.py # Import dependencies from tkinter import * from tkinter import ttk import", "Label for displaying entry status[success/failed] Label(entry_screen, text = \"\", textvariable=message).place(x=95, y=240) # Submit", "record into the database. sql = \"\"\"INSERT INTO crudexample (RecordDate, Temperature, Pressure,CreatedBy) VALUES", "param['Teletron'][0]['password'], param['Teletron'][0]['host'], param['Teletron'][0]['database']), echo=False) # Defining entry form def entry(): # getting form", "(dt.date.today()).strftime('%Y-%m-%d') CreatedBy = getpass.getuser() # applying empty validation if temperature == '' or", "to Epi Epi_con = engine.connect() # Preparing SQL query to INSERT a record", "commit changes in database Epi_con.commit() except: message.set(\"Data Stored successfully\") #def read(): #def update():", "crudexample (RecordDate, Temperature, Pressure,CreatedBy) VALUES (%s, %s, %s, %s) \"\"\" data = (recorddate,", "# Establishing engine engine = sqlalchemy.create_engine('mysql+mysqlconnector://{0}:{1}@{2}/{3}'. format(param['Teletron'][0]['user'], param['Teletron'][0]['password'], param['Teletron'][0]['host'], param['Teletron'][0]['database']), echo=False) # Defining", "== '' or CreatedBy == '': message.set(\"fill the empty field!!!\") else: # Create", "form def entry(): # getting form data temperature = Temperature.get() pressure = Pressure.get()", "entry_screen.geometry(\"400x270\") # declaring variable global message global RecordDate global Temperature global Pressure global", "Entry(entry_screen, textvariable= Temperature).place(x=140, y=82) # Pressure Label Label(entry_screen, text = \"Pressure * \").place(x=20,", "message.set(\"fill the empty field!!!\") else: # Create connection object to Epi Epi_con =", "Temperature Label Label(entry_screen, text= \"Temperature * \").place(x=20, y=80) # Temperature textbox Entry(entry_screen, textvariable=", "engine.connect() # Preparing SQL query to INSERT a record into the database. sql", "Label Label(entry_screen, text= \"Temperature * \").place(x=20, y=80) # Temperature textbox Entry(entry_screen, textvariable= Temperature).place(x=140,", "= \"\"\"INSERT INTO crudexample (RecordDate, Temperature, Pressure,CreatedBy) VALUES (%s, %s, %s, %s) \"\"\"", "Defining entry form def entry(): # getting form data temperature = Temperature.get() pressure", "width=10, height=1, bg=\"gray\", command=entry).place(x=105, y=210) Button(entry_screen, text=\"Update\", width=10, height=1, bg=\"gray\", command=entry).place(x=205, y=210) Button(entry_screen,", "= StringVar() message = StringVar() # Creating layout of Data Entry Form Label(entry_screen,", "the empty field!!!\") else: # Create connection object to Epi Epi_con = engine.connect()", "INSERT a record into the database. sql = \"\"\"INSERT INTO crudexample (RecordDate, Temperature,", "textvariable= Temperature).place(x=140, y=82) # Pressure Label Label(entry_screen, text = \"Pressure * \").place(x=20, y=120)", "# Defining entry form def entry(): # getting form data temperature = Temperature.get()", "applying empty validation if temperature == '' or pressure =='' or recorddate ==", "param['Teletron'][0]['database']), echo=False) # Defining entry form def entry(): # getting form data temperature", "CreatedBy = getpass.getuser() # applying empty validation if temperature == '' or pressure", "Preparing SQL query to INSERT a record into the database. sql = \"\"\"INSERT", "declaring variable global message global RecordDate global Temperature global Pressure global CreatedBy Temperature", "bg=\"gray\", command=entry).place(x=105, y=210) Button(entry_screen, text=\"Update\", width=10, height=1, bg=\"gray\", command=entry).place(x=205, y=210) Button(entry_screen, text=\"Delete\", width=10,", "sqlalchemy.create_engine('mysql+mysqlconnector://{0}:{1}@{2}/{3}'. format(param['Teletron'][0]['user'], param['Teletron'][0]['password'], param['Teletron'][0]['host'], param['Teletron'][0]['database']), echo=False) # Defining entry form def entry(): #", "data temperature = Temperature.get() pressure = Pressure.get() recorddate = (dt.date.today()).strftime('%Y-%m-%d') CreatedBy = getpass.getuser()", "= StringVar() # Creating layout of Data Entry Form Label(entry_screen, width=\"300\", text=\"Please enter", "command=entry).place(x=205, y=210) Button(entry_screen, text=\"Delete\", width=10, height=1, bg=\"gray\", command=entry).place(x=305, y=210) entry_screen.mainloop() # calling function", "= Pressure.get() recorddate = (dt.date.today()).strftime('%Y-%m-%d') CreatedBy = getpass.getuser() # applying empty validation if", "import mysql.connector import sqlalchemy import json import datetime as dt import getpass import", "successfully\") #def read(): #def update(): #def delete(): #def dbsetup(): # defining Registration form", "= StringVar() CreatedBy = StringVar() message = StringVar() # Creating layout of Data", "text= \"Temperature * \").place(x=20, y=80) # Temperature textbox Entry(entry_screen, textvariable= Temperature).place(x=140, y=82) #", "enter details below\", bg=\"blue\", fg=\"white\").pack() # Temperature Label Label(entry_screen, text= \"Temperature * \").place(x=20,", "setting height and width of screen entry_screen.geometry(\"400x270\") # declaring variable global message global", "= Pressure).place(x=140, y=122) # Label for displaying entry status[success/failed] Label(entry_screen, text = \"\",", "import json import datetime as dt import getpass import mysql with open(\"parameters/config.json\") as", "recorddate == '' or CreatedBy == '': message.set(\"fill the empty field!!!\") else: #", "config: param = json.load(config) # Establishing engine engine = sqlalchemy.create_engine('mysql+mysqlconnector://{0}:{1}@{2}/{3}'. format(param['Teletron'][0]['user'], param['Teletron'][0]['password'], param['Teletron'][0]['host'],", "Pressure,CreatedBy) VALUES (%s, %s, %s, %s) \"\"\" data = (recorddate, temperature, pressure ,", "or pressure =='' or recorddate == '' or CreatedBy == '': message.set(\"fill the", "database Epi_con.commit() except: message.set(\"Data Stored successfully\") #def read(): #def update(): #def delete(): #def", "# declaring variable global message global RecordDate global Temperature global Pressure global CreatedBy", "delete(): #def dbsetup(): # defining Registration form function def Entryform(): global entry_screen entry_screen", "Temperature.get() pressure = Pressure.get() recorddate = (dt.date.today()).strftime('%Y-%m-%d') CreatedBy = getpass.getuser() # applying empty", "Import dependencies from tkinter import * from tkinter import ttk import mysql.connector import", "# executing the sql command Epi_con.execute(sql, data) # commit changes in database Epi_con.commit()", "* \").place(x=20, y=80) # Temperature textbox Entry(entry_screen, textvariable= Temperature).place(x=140, y=82) # Pressure Label", "IntVar() Pressure = IntVar() RecordDate = StringVar() CreatedBy = StringVar() message = StringVar()", "y=80) # Temperature textbox Entry(entry_screen, textvariable= Temperature).place(x=140, y=82) # Pressure Label Label(entry_screen, text", "with open(\"parameters/config.json\") as config: param = json.load(config) # Establishing engine engine = sqlalchemy.create_engine('mysql+mysqlconnector://{0}:{1}@{2}/{3}'." ]
[ "LatestNew class ProductAdmin(admin.ModelAdmin): list_display = ('name','price','created_at') list_links = ('id', 'name') list_filter = ('name','price','created_at')", "Register your models here. from . models import Product, New, About, LatestNew class", "portfolio # Register your models here. from . models import Product, New, About,", "your models here. from . models import Product, New, About, LatestNew class ProductAdmin(admin.ModelAdmin):", "'name') list_filter = ('name','price','created_at') search_fields = ('name','price') ordering =('name','price','created_at') class NewAdmin(admin.ModelAdmin): list_display=('title','time') list_filter=('title','time')", "ordering =('name','price','created_at') class NewAdmin(admin.ModelAdmin): list_display=('title','time') list_filter=('title','time') search_fields = ('title','time') admin.site.register(Product, ProductAdmin) admin.site.register(New, NewAdmin)", "('id', 'name') list_filter = ('name','price','created_at') search_fields = ('name','price') ordering =('name','price','created_at') class NewAdmin(admin.ModelAdmin): list_display=('title','time')", "from . models import Product, New, About, LatestNew class ProductAdmin(admin.ModelAdmin): list_display = ('name','price','created_at')", "class ProductAdmin(admin.ModelAdmin): list_display = ('name','price','created_at') list_links = ('id', 'name') list_filter = ('name','price','created_at') search_fields", "admin from products.views import portfolio # Register your models here. from . models", "from django.contrib import admin from products.views import portfolio # Register your models here.", "models here. from . models import Product, New, About, LatestNew class ProductAdmin(admin.ModelAdmin): list_display", "import admin from products.views import portfolio # Register your models here. from .", "= ('id', 'name') list_filter = ('name','price','created_at') search_fields = ('name','price') ordering =('name','price','created_at') class NewAdmin(admin.ModelAdmin):", "import Product, New, About, LatestNew class ProductAdmin(admin.ModelAdmin): list_display = ('name','price','created_at') list_links = ('id',", "Product, New, About, LatestNew class ProductAdmin(admin.ModelAdmin): list_display = ('name','price','created_at') list_links = ('id', 'name')", "New, About, LatestNew class ProductAdmin(admin.ModelAdmin): list_display = ('name','price','created_at') list_links = ('id', 'name') list_filter", "list_display = ('name','price','created_at') list_links = ('id', 'name') list_filter = ('name','price','created_at') search_fields = ('name','price')", "from products.views import portfolio # Register your models here. from . models import", "= ('name','price','created_at') search_fields = ('name','price') ordering =('name','price','created_at') class NewAdmin(admin.ModelAdmin): list_display=('title','time') list_filter=('title','time') search_fields =", "products.views import portfolio # Register your models here. from . models import Product,", "list_filter = ('name','price','created_at') search_fields = ('name','price') ordering =('name','price','created_at') class NewAdmin(admin.ModelAdmin): list_display=('title','time') list_filter=('title','time') search_fields", ". models import Product, New, About, LatestNew class ProductAdmin(admin.ModelAdmin): list_display = ('name','price','created_at') list_links", "models import Product, New, About, LatestNew class ProductAdmin(admin.ModelAdmin): list_display = ('name','price','created_at') list_links =", "('name','price','created_at') search_fields = ('name','price') ordering =('name','price','created_at') class NewAdmin(admin.ModelAdmin): list_display=('title','time') list_filter=('title','time') search_fields = ('title','time')", "= ('name','price','created_at') list_links = ('id', 'name') list_filter = ('name','price','created_at') search_fields = ('name','price') ordering", "('name','price') ordering =('name','price','created_at') class NewAdmin(admin.ModelAdmin): list_display=('title','time') list_filter=('title','time') search_fields = ('title','time') admin.site.register(Product, ProductAdmin) admin.site.register(New,", "=('name','price','created_at') class NewAdmin(admin.ModelAdmin): list_display=('title','time') list_filter=('title','time') search_fields = ('title','time') admin.site.register(Product, ProductAdmin) admin.site.register(New, NewAdmin) admin.site.register(LatestNew)", "django.contrib import admin from products.views import portfolio # Register your models here. from", "About, LatestNew class ProductAdmin(admin.ModelAdmin): list_display = ('name','price','created_at') list_links = ('id', 'name') list_filter =", "ProductAdmin(admin.ModelAdmin): list_display = ('name','price','created_at') list_links = ('id', 'name') list_filter = ('name','price','created_at') search_fields =", "class NewAdmin(admin.ModelAdmin): list_display=('title','time') list_filter=('title','time') search_fields = ('title','time') admin.site.register(Product, ProductAdmin) admin.site.register(New, NewAdmin) admin.site.register(LatestNew) admin.site.register(About)", "here. from . models import Product, New, About, LatestNew class ProductAdmin(admin.ModelAdmin): list_display =", "= ('name','price') ordering =('name','price','created_at') class NewAdmin(admin.ModelAdmin): list_display=('title','time') list_filter=('title','time') search_fields = ('title','time') admin.site.register(Product, ProductAdmin)", "('name','price','created_at') list_links = ('id', 'name') list_filter = ('name','price','created_at') search_fields = ('name','price') ordering =('name','price','created_at')", "import portfolio # Register your models here. from . models import Product, New,", "search_fields = ('name','price') ordering =('name','price','created_at') class NewAdmin(admin.ModelAdmin): list_display=('title','time') list_filter=('title','time') search_fields = ('title','time') admin.site.register(Product,", "# Register your models here. from . models import Product, New, About, LatestNew", "list_links = ('id', 'name') list_filter = ('name','price','created_at') search_fields = ('name','price') ordering =('name','price','created_at') class" ]
[ "'I-time', 'O'] result = [self.id2tag[id] for id in paths[0]] # entities_result = #", "= tf_ad.text.viterbi_decode( logit[:text_len], self.model.transition_params ) paths.append(viterbi_path) # path[0] = tag in sentence #", "= tf.train.Checkpoint(optimizer=self.optimizer, model=self.model) ckpt.restore(tf.train.latest_checkpoint(self.checkpoint_path)) article_id = 0 counter = 0 results = []", "results[ [\"start_position\", \"end_position\", \"entity_text\", \"entity_type\"] ] article_ids = pd.Series([i] * len(result), name=\"article_id\") df", "[{'begin': 0, 'end': 3, 'words': '賈伯斯', 'type': 'name'}, # {'begin': 4, 'end': 6,", "zip(logits, text_lens): viterbi_path, _ = tf_ad.text.viterbi_decode( logit[:text_len], self.model.transition_params ) paths.append(viterbi_path) # path[0] =", "import dataclass from program.utils.write_output_file import format_result from program.abstracts.abstract_ner_predictor import NerPredictor @dataclass class BilstmCrfPredictor(NerPredictor):", "\"end_position\", \"entity_text\", \"entity_type\"] ] article_ids = pd.Series([i] * len(result), name=\"article_id\") df = df.append(pd.concat([article_ids,", "tag in sentence # = [18, 19, 19, 1, 26, 27, 1] #", "self.model.transition_params ) paths.append(viterbi_path) # path[0] = tag in sentence # = [18, 19,", "# = [[1445 33 1878 826 1949 1510 112]] dataset = tf.keras.preprocessing.sequence.pad_sequences( [[self.voc2id.get(char,", "class BilstmCrfPredictor(NerPredictor): def __post_init__(self): vocab_file_path = self.model_data_path + \"vocab_file.txt\" tag_file_path = self.model_data_path +", "* len(result), name=\"article_id\") df = df.append(pd.concat([article_ids, results], axis=1), ignore_index=True) df.to_csv(self.output_path + \"output.tsv\", sep=\"\\t\",", "= BilstmCrfModel( hidden_num=self.hidden_nums, vocab_size=len(self.voc2id), label_size=len(self.tag2id), embedding_size=self.embedding_size, ) self.optimizer = tf.keras.optimizers.Adam(self.learning_rate) def predict_sentence(self, sentence):", "in paths[0]] # entities_result = # [{'begin': 0, 'end': 3, 'words': '賈伯斯', 'type':", "= 0 results = [] result = [] for testset in self.test_X: prediction", "counter if prediction: for pred in prediction: pred[\"begin\"] += counter pred[\"end\"] += counter", "\"\"\" titles = { \"end\": \"end_position\", \"begin\": \"start_position\", \"words\": \"entity_text\", \"type\": \"entity_type\", }", "\"entity_type\", } df = pd.DataFrame() for i, result in enumerate(self.results): results = pd.DataFrame(result).rename(columns=titles)", ") self.optimizer = tf.keras.optimizers.Adam(self.learning_rate) def predict_sentence(self, sentence): \"\"\" predict single sentence. Input: Raw", "1510 112]] dataset = tf.keras.preprocessing.sequence.pad_sequences( [[self.voc2id.get(char, 0) for char in sentence]], padding=\"post\" )", "'type': 'name'}, # {'begin': 4, 'end': 6, 'words': '七號', 'type': 'time'}] entities_result =", "program.abstracts.abstract_ner_predictor import NerPredictor @dataclass class BilstmCrfPredictor(NerPredictor): def __post_init__(self): vocab_file_path = self.model_data_path + \"vocab_file.txt\"", "pd.Series([i] * len(result), name=\"article_id\") df = df.append(pd.concat([article_ids, results], axis=1), ignore_index=True) df.to_csv(self.output_path + \"output.tsv\",", "test_X_path, test_mapping_path ) self.model = BilstmCrfModel( hidden_num=self.hidden_nums, vocab_size=len(self.voc2id), label_size=len(self.tag2id), embedding_size=self.embedding_size, ) self.optimizer =", "self.test_mapping[article_id]: results.append(result) article_id += 1 counter = 0 result = [] self.results =", "\"\"\" # dataset = encode sentence # = [[1445 33 1878 826 1949", "in self.test_X: prediction = self.predict_sentence(testset) # predict_pos + counter if prediction: for pred", "results: [ [ {'begin': 170, 'end': 174, 'words': '1100', 'type': 'med_exam'}, {'begin': 245,", "in zip(logits, text_lens): viterbi_path, _ = tf_ad.text.viterbi_decode( logit[:text_len], self.model.transition_params ) paths.append(viterbi_path) # path[0]", "= results[ [\"start_position\", \"end_position\", \"entity_text\", \"entity_type\"] ] article_ids = pd.Series([i] * len(result), name=\"article_id\")", "+ \"test_mapping.pkl\" self.test_X, self.test_mapping = GeneralDataPreprocessor.loadTestArrays( test_X_path, test_mapping_path ) self.model = BilstmCrfModel( hidden_num=self.hidden_nums,", "result) return entities_result def predict(self): # restore model ckpt = tf.train.Checkpoint(optimizer=self.optimizer, model=self.model) ckpt.restore(tf.train.latest_checkpoint(self.checkpoint_path))", "# [{'begin': 0, 'end': 3, 'words': '賈伯斯', 'type': 'name'}, # {'begin': 4, 'end':", "'I-name', 'I-name', 'O', 'B-time', 'I-time', 'O'] result = [self.id2tag[id] for id in paths[0]]", "ckpt.restore(tf.train.latest_checkpoint(self.checkpoint_path)) article_id = 0 counter = 0 results = [] result = []", "# result = ['B-name', 'I-name', 'I-name', 'O', 'B-time', 'I-time', 'O'] result = [self.id2tag[id]", "] \"\"\" titles = { \"end\": \"end_position\", \"begin\": \"start_position\", \"words\": \"entity_text\", \"type\": \"entity_type\",", "1 counter = 0 result = [] self.results = results def output(self): \"\"\"", "def output(self): \"\"\" results: [ [ {'begin': 170, 'end': 174, 'words': '1100', 'type':", "text string \"\"\" # dataset = encode sentence # = [[1445 33 1878", "249, 'words': '1145', 'type': 'med_exam'}, ... ] ] \"\"\" titles = { \"end\":", "from program.utils.write_output_file import format_result from program.abstracts.abstract_ner_predictor import NerPredictor @dataclass class BilstmCrfPredictor(NerPredictor): def __post_init__(self):", "'words': '1145', 'type': 'med_exam'}, ... ] ] \"\"\" titles = { \"end\": \"end_position\",", "= pd.Series([i] * len(result), name=\"article_id\") df = df.append(pd.concat([article_ids, results], axis=1), ignore_index=True) df.to_csv(self.output_path +", "counter += len(testset) if counter == self.test_mapping[article_id]: results.append(result) article_id += 1 counter =", "27, 1] # result = ['B-name', 'I-name', 'I-name', 'O', 'B-time', 'I-time', 'O'] result", "[] for logit, text_len in zip(logits, text_lens): viterbi_path, _ = tf_ad.text.viterbi_decode( logit[:text_len], self.model.transition_params", "\"type\": \"entity_type\", } df = pd.DataFrame() for i, result in enumerate(self.results): results =", "read_vocab from dataclasses import dataclass from program.utils.write_output_file import format_result from program.abstracts.abstract_ner_predictor import NerPredictor", "format_result from program.abstracts.abstract_ner_predictor import NerPredictor @dataclass class BilstmCrfPredictor(NerPredictor): def __post_init__(self): vocab_file_path = self.model_data_path", "4, 'end': 6, 'words': '七號', 'type': 'time'}] entities_result = format_result(list(sentence), result) return entities_result", "article_id += 1 counter = 0 result = [] self.results = results def", "dataset = encode sentence # = [[1445 33 1878 826 1949 1510 112]]", "[18, 19, 19, 1, 26, 27, 1] # result = ['B-name', 'I-name', 'I-name',", "string \"\"\" # dataset = encode sentence # = [[1445 33 1878 826", "sentence. Input: Raw text string \"\"\" # dataset = encode sentence # =", "\"test_mapping.pkl\" self.test_X, self.test_mapping = GeneralDataPreprocessor.loadTestArrays( test_X_path, test_mapping_path ) self.model = BilstmCrfModel( hidden_num=self.hidden_nums, vocab_size=len(self.voc2id),", "words, predict_distrib) # text_lens = [7] logits, text_lens = self.model.predict(dataset) paths = []", "'words': '賈伯斯', 'type': 'name'}, # {'begin': 4, 'end': 6, 'words': '七號', 'type': 'time'}]", "= self.model_data_path + \"test_X.pkl\" test_mapping_path = self.model_data_path + \"test_mapping.pkl\" self.test_X, self.test_mapping = GeneralDataPreprocessor.loadTestArrays(", "[7] logits, text_lens = self.model.predict(dataset) paths = [] for logit, text_len in zip(logits,", "sentence # = [18, 19, 19, 1, 26, 27, 1] # result =", "# entities_result = # [{'begin': 0, 'end': 3, 'words': '賈伯斯', 'type': 'name'}, #", "(sentence, words, predict_distrib) # text_lens = [7] logits, text_lens = self.model.predict(dataset) paths =", "if counter == self.test_mapping[article_id]: results.append(result) article_id += 1 counter = 0 result =", "in enumerate(self.results): results = pd.DataFrame(result).rename(columns=titles) results = results[ [\"start_position\", \"end_position\", \"entity_text\", \"entity_type\"] ]", "result = [] self.results = results def output(self): \"\"\" results: [ [ {'begin':", "import tensorflow as tf import tensorflow_addons as tf_ad from program.utils.tokenization import read_vocab from", "counter result.append(pred) counter += len(testset) if counter == self.test_mapping[article_id]: results.append(result) article_id += 1", "= pd.DataFrame(result).rename(columns=titles) results = results[ [\"start_position\", \"end_position\", \"entity_text\", \"entity_type\"] ] article_ids = pd.Series([i]", "+ \"vocab_file.txt\" tag_file_path = self.model_data_path + \"tag.txt\" self.voc2id, self.id2voc = read_vocab(vocab_file_path) self.tag2id, self.id2tag", "paths = [] for logit, text_len in zip(logits, text_lens): viterbi_path, _ = tf_ad.text.viterbi_decode(", "= [] for logit, text_len in zip(logits, text_lens): viterbi_path, _ = tf_ad.text.viterbi_decode( logit[:text_len],", "# dataset = encode sentence # = [[1445 33 1878 826 1949 1510", "label_size=len(self.tag2id), embedding_size=self.embedding_size, ) self.optimizer = tf.keras.optimizers.Adam(self.learning_rate) def predict_sentence(self, sentence): \"\"\" predict single sentence.", "# text_lens = [7] logits, text_lens = self.model.predict(dataset) paths = [] for logit,", "'I-name', 'O', 'B-time', 'I-time', 'O'] result = [self.id2tag[id] for id in paths[0]] #", "Input: Raw text string \"\"\" # dataset = encode sentence # = [[1445", "= read_vocab(vocab_file_path) self.tag2id, self.id2tag = read_vocab(tag_file_path) test_X_path = self.model_data_path + \"test_X.pkl\" test_mapping_path =", "char in sentence]], padding=\"post\" ) # logits = (1, 7, 28) = (sentence,", "+= counter pred[\"end\"] += counter result.append(pred) counter += len(testset) if counter == self.test_mapping[article_id]:", "dataset = tf.keras.preprocessing.sequence.pad_sequences( [[self.voc2id.get(char, 0) for char in sentence]], padding=\"post\" ) # logits", "hidden_num=self.hidden_nums, vocab_size=len(self.voc2id), label_size=len(self.tag2id), embedding_size=self.embedding_size, ) self.optimizer = tf.keras.optimizers.Adam(self.learning_rate) def predict_sentence(self, sentence): \"\"\" predict", "predict_sentence(self, sentence): \"\"\" predict single sentence. Input: Raw text string \"\"\" # dataset", "= 0 result = [] self.results = results def output(self): \"\"\" results: [", "'end': 249, 'words': '1145', 'type': 'med_exam'}, ... ] ] \"\"\" titles = {", "_ = tf_ad.text.viterbi_decode( logit[:text_len], self.model.transition_params ) paths.append(viterbi_path) # path[0] = tag in sentence", "[ {'begin': 170, 'end': 174, 'words': '1100', 'type': 'med_exam'}, {'begin': 245, 'end': 249,", "single sentence. Input: Raw text string \"\"\" # dataset = encode sentence #", "+= len(testset) if counter == self.test_mapping[article_id]: results.append(result) article_id += 1 counter = 0", "in sentence]], padding=\"post\" ) # logits = (1, 7, 28) = (sentence, words,", "for i, result in enumerate(self.results): results = pd.DataFrame(result).rename(columns=titles) results = results[ [\"start_position\", \"end_position\",", "counter = 0 result = [] self.results = results def output(self): \"\"\" results:", "\"\"\" results: [ [ {'begin': 170, 'end': 174, 'words': '1100', 'type': 'med_exam'}, {'begin':", "pd import tensorflow as tf import tensorflow_addons as tf_ad from program.utils.tokenization import read_vocab", "embedding_size=self.embedding_size, ) self.optimizer = tf.keras.optimizers.Adam(self.learning_rate) def predict_sentence(self, sentence): \"\"\" predict single sentence. Input:", "tf.keras.preprocessing.sequence.pad_sequences( [[self.voc2id.get(char, 0) for char in sentence]], padding=\"post\" ) # logits = (1,", "text_len in zip(logits, text_lens): viterbi_path, _ = tf_ad.text.viterbi_decode( logit[:text_len], self.model.transition_params ) paths.append(viterbi_path) #", "__post_init__(self): vocab_file_path = self.model_data_path + \"vocab_file.txt\" tag_file_path = self.model_data_path + \"tag.txt\" self.voc2id, self.id2voc", "import format_result from program.abstracts.abstract_ner_predictor import NerPredictor @dataclass class BilstmCrfPredictor(NerPredictor): def __post_init__(self): vocab_file_path =", "return entities_result def predict(self): # restore model ckpt = tf.train.Checkpoint(optimizer=self.optimizer, model=self.model) ckpt.restore(tf.train.latest_checkpoint(self.checkpoint_path)) article_id", "0) for char in sentence]], padding=\"post\" ) # logits = (1, 7, 28)", "'time'}] entities_result = format_result(list(sentence), result) return entities_result def predict(self): # restore model ckpt", "'med_exam'}, {'begin': 245, 'end': 249, 'words': '1145', 'type': 'med_exam'}, ... ] ] \"\"\"", "'end': 6, 'words': '七號', 'type': 'time'}] entities_result = format_result(list(sentence), result) return entities_result def", "self.test_mapping = GeneralDataPreprocessor.loadTestArrays( test_X_path, test_mapping_path ) self.model = BilstmCrfModel( hidden_num=self.hidden_nums, vocab_size=len(self.voc2id), label_size=len(self.tag2id), embedding_size=self.embedding_size,", "= tf.keras.optimizers.Adam(self.learning_rate) def predict_sentence(self, sentence): \"\"\" predict single sentence. Input: Raw text string", "= tf.keras.preprocessing.sequence.pad_sequences( [[self.voc2id.get(char, 0) for char in sentence]], padding=\"post\" ) # logits =", "= [] self.results = results def output(self): \"\"\" results: [ [ {'begin': 170,", "pred in prediction: pred[\"begin\"] += counter pred[\"end\"] += counter result.append(pred) counter += len(testset)", "28) = (sentence, words, predict_distrib) # text_lens = [7] logits, text_lens = self.model.predict(dataset)", "\"begin\": \"start_position\", \"words\": \"entity_text\", \"type\": \"entity_type\", } df = pd.DataFrame() for i, result", "= format_result(list(sentence), result) return entities_result def predict(self): # restore model ckpt = tf.train.Checkpoint(optimizer=self.optimizer,", "... ] ] \"\"\" titles = { \"end\": \"end_position\", \"begin\": \"start_position\", \"words\": \"entity_text\",", ") self.model = BilstmCrfModel( hidden_num=self.hidden_nums, vocab_size=len(self.voc2id), label_size=len(self.tag2id), embedding_size=self.embedding_size, ) self.optimizer = tf.keras.optimizers.Adam(self.learning_rate) def", "6, 'words': '七號', 'type': 'time'}] entities_result = format_result(list(sentence), result) return entities_result def predict(self):", "[] result = [] for testset in self.test_X: prediction = self.predict_sentence(testset) # predict_pos", "\"end_position\", \"begin\": \"start_position\", \"words\": \"entity_text\", \"type\": \"entity_type\", } df = pd.DataFrame() for i,", "test_mapping_path ) self.model = BilstmCrfModel( hidden_num=self.hidden_nums, vocab_size=len(self.voc2id), label_size=len(self.tag2id), embedding_size=self.embedding_size, ) self.optimizer = tf.keras.optimizers.Adam(self.learning_rate)", "prediction: pred[\"begin\"] += counter pred[\"end\"] += counter result.append(pred) counter += len(testset) if counter", "program.utils.write_output_file import format_result from program.abstracts.abstract_ner_predictor import NerPredictor @dataclass class BilstmCrfPredictor(NerPredictor): def __post_init__(self): vocab_file_path", "vocab_size=len(self.voc2id), label_size=len(self.tag2id), embedding_size=self.embedding_size, ) self.optimizer = tf.keras.optimizers.Adam(self.learning_rate) def predict_sentence(self, sentence): \"\"\" predict single", "'type': 'med_exam'}, ... ] ] \"\"\" titles = { \"end\": \"end_position\", \"begin\": \"start_position\",", "[] for testset in self.test_X: prediction = self.predict_sentence(testset) # predict_pos + counter if", "} df = pd.DataFrame() for i, result in enumerate(self.results): results = pd.DataFrame(result).rename(columns=titles) results", "test_mapping_path = self.model_data_path + \"test_mapping.pkl\" self.test_X, self.test_mapping = GeneralDataPreprocessor.loadTestArrays( test_X_path, test_mapping_path ) self.model", "in sentence # = [18, 19, 19, 1, 26, 27, 1] # result", "+ counter if prediction: for pred in prediction: pred[\"begin\"] += counter pred[\"end\"] +=", "pred[\"begin\"] += counter pred[\"end\"] += counter result.append(pred) counter += len(testset) if counter ==", "tf.train.Checkpoint(optimizer=self.optimizer, model=self.model) ckpt.restore(tf.train.latest_checkpoint(self.checkpoint_path)) article_id = 0 counter = 0 results = [] result", "26, 27, 1] # result = ['B-name', 'I-name', 'I-name', 'O', 'B-time', 'I-time', 'O']", "id in paths[0]] # entities_result = # [{'begin': 0, 'end': 3, 'words': '賈伯斯',", "vocab_file_path = self.model_data_path + \"vocab_file.txt\" tag_file_path = self.model_data_path + \"tag.txt\" self.voc2id, self.id2voc =", "results = pd.DataFrame(result).rename(columns=titles) results = results[ [\"start_position\", \"end_position\", \"entity_text\", \"entity_type\"] ] article_ids =", "enumerate(self.results): results = pd.DataFrame(result).rename(columns=titles) results = results[ [\"start_position\", \"end_position\", \"entity_text\", \"entity_type\"] ] article_ids", "self.model_data_path + \"test_X.pkl\" test_mapping_path = self.model_data_path + \"test_mapping.pkl\" self.test_X, self.test_mapping = GeneralDataPreprocessor.loadTestArrays( test_X_path,", "'O', 'B-time', 'I-time', 'O'] result = [self.id2tag[id] for id in paths[0]] # entities_result", "prediction = self.predict_sentence(testset) # predict_pos + counter if prediction: for pred in prediction:", "GeneralDataPreprocessor import pandas as pd import tensorflow as tf import tensorflow_addons as tf_ad", "[] self.results = results def output(self): \"\"\" results: [ [ {'begin': 170, 'end':", "] ] \"\"\" titles = { \"end\": \"end_position\", \"begin\": \"start_position\", \"words\": \"entity_text\", \"type\":", "logit, text_len in zip(logits, text_lens): viterbi_path, _ = tf_ad.text.viterbi_decode( logit[:text_len], self.model.transition_params ) paths.append(viterbi_path)", "program.data_process.data_preprocessor import GeneralDataPreprocessor import pandas as pd import tensorflow as tf import tensorflow_addons", "from program.utils.tokenization import read_vocab from dataclasses import dataclass from program.utils.write_output_file import format_result from", "# restore model ckpt = tf.train.Checkpoint(optimizer=self.optimizer, model=self.model) ckpt.restore(tf.train.latest_checkpoint(self.checkpoint_path)) article_id = 0 counter =", "def predict(self): # restore model ckpt = tf.train.Checkpoint(optimizer=self.optimizer, model=self.model) ckpt.restore(tf.train.latest_checkpoint(self.checkpoint_path)) article_id = 0", "'B-time', 'I-time', 'O'] result = [self.id2tag[id] for id in paths[0]] # entities_result =", "def predict_sentence(self, sentence): \"\"\" predict single sentence. Input: Raw text string \"\"\" #", "= results def output(self): \"\"\" results: [ [ {'begin': 170, 'end': 174, 'words':", "text_lens = self.model.predict(dataset) paths = [] for logit, text_len in zip(logits, text_lens): viterbi_path,", "len(testset) if counter == self.test_mapping[article_id]: results.append(result) article_id += 1 counter = 0 result", "result = ['B-name', 'I-name', 'I-name', 'O', 'B-time', 'I-time', 'O'] result = [self.id2tag[id] for", "\"entity_type\"] ] article_ids = pd.Series([i] * len(result), name=\"article_id\") df = df.append(pd.concat([article_ids, results], axis=1),", "result in enumerate(self.results): results = pd.DataFrame(result).rename(columns=titles) results = results[ [\"start_position\", \"end_position\", \"entity_text\", \"entity_type\"]", "170, 'end': 174, 'words': '1100', 'type': 'med_exam'}, {'begin': 245, 'end': 249, 'words': '1145',", "'end': 174, 'words': '1100', 'type': 'med_exam'}, {'begin': 245, 'end': 249, 'words': '1145', 'type':", "tf.keras.optimizers.Adam(self.learning_rate) def predict_sentence(self, sentence): \"\"\" predict single sentence. Input: Raw text string \"\"\"", "'end': 3, 'words': '賈伯斯', 'type': 'name'}, # {'begin': 4, 'end': 6, 'words': '七號',", "Raw text string \"\"\" # dataset = encode sentence # = [[1445 33", "= self.model_data_path + \"test_mapping.pkl\" self.test_X, self.test_mapping = GeneralDataPreprocessor.loadTestArrays( test_X_path, test_mapping_path ) self.model =", "0 counter = 0 results = [] result = [] for testset in", "= self.model_data_path + \"vocab_file.txt\" tag_file_path = self.model_data_path + \"tag.txt\" self.voc2id, self.id2voc = read_vocab(vocab_file_path)", "(1, 7, 28) = (sentence, words, predict_distrib) # text_lens = [7] logits, text_lens", "in prediction: pred[\"begin\"] += counter pred[\"end\"] += counter result.append(pred) counter += len(testset) if", "tensorflow as tf import tensorflow_addons as tf_ad from program.utils.tokenization import read_vocab from dataclasses", "from program.data_process.data_preprocessor import GeneralDataPreprocessor import pandas as pd import tensorflow as tf import", "self.test_X, self.test_mapping = GeneralDataPreprocessor.loadTestArrays( test_X_path, test_mapping_path ) self.model = BilstmCrfModel( hidden_num=self.hidden_nums, vocab_size=len(self.voc2id), label_size=len(self.tag2id),", "= read_vocab(tag_file_path) test_X_path = self.model_data_path + \"test_X.pkl\" test_mapping_path = self.model_data_path + \"test_mapping.pkl\" self.test_X,", "sentence): \"\"\" predict single sentence. Input: Raw text string \"\"\" # dataset =", "= [] result = [] for testset in self.test_X: prediction = self.predict_sentence(testset) #", "{ \"end\": \"end_position\", \"begin\": \"start_position\", \"words\": \"entity_text\", \"type\": \"entity_type\", } df = pd.DataFrame()", "{'begin': 170, 'end': 174, 'words': '1100', 'type': 'med_exam'}, {'begin': 245, 'end': 249, 'words':", "# predict_pos + counter if prediction: for pred in prediction: pred[\"begin\"] += counter", "NerPredictor @dataclass class BilstmCrfPredictor(NerPredictor): def __post_init__(self): vocab_file_path = self.model_data_path + \"vocab_file.txt\" tag_file_path =", "import tensorflow_addons as tf_ad from program.utils.tokenization import read_vocab from dataclasses import dataclass from", "= [7] logits, text_lens = self.model.predict(dataset) paths = [] for logit, text_len in", "= self.model_data_path + \"tag.txt\" self.voc2id, self.id2voc = read_vocab(vocab_file_path) self.tag2id, self.id2tag = read_vocab(tag_file_path) test_X_path", "import BilstmCrfModel from program.data_process.data_preprocessor import GeneralDataPreprocessor import pandas as pd import tensorflow as", "1, 26, 27, 1] # result = ['B-name', 'I-name', 'I-name', 'O', 'B-time', 'I-time',", "112]] dataset = tf.keras.preprocessing.sequence.pad_sequences( [[self.voc2id.get(char, 0) for char in sentence]], padding=\"post\" ) #", ") # logits = (1, 7, 28) = (sentence, words, predict_distrib) # text_lens", "results = results[ [\"start_position\", \"end_position\", \"entity_text\", \"entity_type\"] ] article_ids = pd.Series([i] * len(result),", "results = [] result = [] for testset in self.test_X: prediction = self.predict_sentence(testset)", "text_lens = [7] logits, text_lens = self.model.predict(dataset) paths = [] for logit, text_len", "174, 'words': '1100', 'type': 'med_exam'}, {'begin': 245, 'end': 249, 'words': '1145', 'type': 'med_exam'},", "0 results = [] result = [] for testset in self.test_X: prediction =", "import GeneralDataPreprocessor import pandas as pd import tensorflow as tf import tensorflow_addons as", "for char in sentence]], padding=\"post\" ) # logits = (1, 7, 28) =", "results def output(self): \"\"\" results: [ [ {'begin': 170, 'end': 174, 'words': '1100',", "self.results = results def output(self): \"\"\" results: [ [ {'begin': 170, 'end': 174,", "] article_ids = pd.Series([i] * len(result), name=\"article_id\") df = df.append(pd.concat([article_ids, results], axis=1), ignore_index=True)", "import read_vocab from dataclasses import dataclass from program.utils.write_output_file import format_result from program.abstracts.abstract_ner_predictor import", "= (sentence, words, predict_distrib) # text_lens = [7] logits, text_lens = self.model.predict(dataset) paths", "\"tag.txt\" self.voc2id, self.id2voc = read_vocab(vocab_file_path) self.tag2id, self.id2tag = read_vocab(tag_file_path) test_X_path = self.model_data_path +", "'1100', 'type': 'med_exam'}, {'begin': 245, 'end': 249, 'words': '1145', 'type': 'med_exam'}, ... ]", "\"entity_text\", \"type\": \"entity_type\", } df = pd.DataFrame() for i, result in enumerate(self.results): results", "\"entity_text\", \"entity_type\"] ] article_ids = pd.Series([i] * len(result), name=\"article_id\") df = df.append(pd.concat([article_ids, results],", "@dataclass class BilstmCrfPredictor(NerPredictor): def __post_init__(self): vocab_file_path = self.model_data_path + \"vocab_file.txt\" tag_file_path = self.model_data_path", "{'begin': 4, 'end': 6, 'words': '七號', 'type': 'time'}] entities_result = format_result(list(sentence), result) return", "\"end\": \"end_position\", \"begin\": \"start_position\", \"words\": \"entity_text\", \"type\": \"entity_type\", } df = pd.DataFrame() for", "from program.abstracts.abstract_ner_predictor import NerPredictor @dataclass class BilstmCrfPredictor(NerPredictor): def __post_init__(self): vocab_file_path = self.model_data_path +", "= # [{'begin': 0, 'end': 3, 'words': '賈伯斯', 'type': 'name'}, # {'begin': 4,", "== self.test_mapping[article_id]: results.append(result) article_id += 1 counter = 0 result = [] self.results", "\"test_X.pkl\" test_mapping_path = self.model_data_path + \"test_mapping.pkl\" self.test_X, self.test_mapping = GeneralDataPreprocessor.loadTestArrays( test_X_path, test_mapping_path )", "245, 'end': 249, 'words': '1145', 'type': 'med_exam'}, ... ] ] \"\"\" titles =", "for testset in self.test_X: prediction = self.predict_sentence(testset) # predict_pos + counter if prediction:", "= [18, 19, 19, 1, 26, 27, 1] # result = ['B-name', 'I-name',", "\"vocab_file.txt\" tag_file_path = self.model_data_path + \"tag.txt\" self.voc2id, self.id2voc = read_vocab(vocab_file_path) self.tag2id, self.id2tag =", "19, 1, 26, 27, 1] # result = ['B-name', 'I-name', 'I-name', 'O', 'B-time',", "# logits = (1, 7, 28) = (sentence, words, predict_distrib) # text_lens =", "826 1949 1510 112]] dataset = tf.keras.preprocessing.sequence.pad_sequences( [[self.voc2id.get(char, 0) for char in sentence]],", "testset in self.test_X: prediction = self.predict_sentence(testset) # predict_pos + counter if prediction: for", "entities_result def predict(self): # restore model ckpt = tf.train.Checkpoint(optimizer=self.optimizer, model=self.model) ckpt.restore(tf.train.latest_checkpoint(self.checkpoint_path)) article_id =", "\"start_position\", \"words\": \"entity_text\", \"type\": \"entity_type\", } df = pd.DataFrame() for i, result in", "for id in paths[0]] # entities_result = # [{'begin': 0, 'end': 3, 'words':", "= pd.DataFrame() for i, result in enumerate(self.results): results = pd.DataFrame(result).rename(columns=titles) results = results[", "import NerPredictor @dataclass class BilstmCrfPredictor(NerPredictor): def __post_init__(self): vocab_file_path = self.model_data_path + \"vocab_file.txt\" tag_file_path", "output(self): \"\"\" results: [ [ {'begin': 170, 'end': 174, 'words': '1100', 'type': 'med_exam'},", "pandas as pd import tensorflow as tf import tensorflow_addons as tf_ad from program.utils.tokenization", "0, 'end': 3, 'words': '賈伯斯', 'type': 'name'}, # {'begin': 4, 'end': 6, 'words':", "[\"start_position\", \"end_position\", \"entity_text\", \"entity_type\"] ] article_ids = pd.Series([i] * len(result), name=\"article_id\") df =", "from dataclasses import dataclass from program.utils.write_output_file import format_result from program.abstracts.abstract_ner_predictor import NerPredictor @dataclass", "7, 28) = (sentence, words, predict_distrib) # text_lens = [7] logits, text_lens =", "model ckpt = tf.train.Checkpoint(optimizer=self.optimizer, model=self.model) ckpt.restore(tf.train.latest_checkpoint(self.checkpoint_path)) article_id = 0 counter = 0 results", "counter pred[\"end\"] += counter result.append(pred) counter += len(testset) if counter == self.test_mapping[article_id]: results.append(result)", "test_X_path = self.model_data_path + \"test_X.pkl\" test_mapping_path = self.model_data_path + \"test_mapping.pkl\" self.test_X, self.test_mapping =", "as tf_ad from program.utils.tokenization import read_vocab from dataclasses import dataclass from program.utils.write_output_file import", "3, 'words': '賈伯斯', 'type': 'name'}, # {'begin': 4, 'end': 6, 'words': '七號', 'type':", "BilstmCrfModel from program.data_process.data_preprocessor import GeneralDataPreprocessor import pandas as pd import tensorflow as tf", "len(result), name=\"article_id\") df = df.append(pd.concat([article_ids, results], axis=1), ignore_index=True) df.to_csv(self.output_path + \"output.tsv\", sep=\"\\t\", index=False)", "+ \"tag.txt\" self.voc2id, self.id2voc = read_vocab(vocab_file_path) self.tag2id, self.id2tag = read_vocab(tag_file_path) test_X_path = self.model_data_path", "self.test_X: prediction = self.predict_sentence(testset) # predict_pos + counter if prediction: for pred in", "article_id = 0 counter = 0 results = [] result = [] for", "tensorflow_addons as tf_ad from program.utils.tokenization import read_vocab from dataclasses import dataclass from program.utils.write_output_file", "as tf import tensorflow_addons as tf_ad from program.utils.tokenization import read_vocab from dataclasses import", "entities_result = # [{'begin': 0, 'end': 3, 'words': '賈伯斯', 'type': 'name'}, # {'begin':", "= self.model.predict(dataset) paths = [] for logit, text_len in zip(logits, text_lens): viterbi_path, _", "+= counter result.append(pred) counter += len(testset) if counter == self.test_mapping[article_id]: results.append(result) article_id +=", "[self.id2tag[id] for id in paths[0]] # entities_result = # [{'begin': 0, 'end': 3,", "self.optimizer = tf.keras.optimizers.Adam(self.learning_rate) def predict_sentence(self, sentence): \"\"\" predict single sentence. Input: Raw text", "'words': '七號', 'type': 'time'}] entities_result = format_result(list(sentence), result) return entities_result def predict(self): #", "self.tag2id, self.id2tag = read_vocab(tag_file_path) test_X_path = self.model_data_path + \"test_X.pkl\" test_mapping_path = self.model_data_path +", "+ \"test_X.pkl\" test_mapping_path = self.model_data_path + \"test_mapping.pkl\" self.test_X, self.test_mapping = GeneralDataPreprocessor.loadTestArrays( test_X_path, test_mapping_path", "+= 1 counter = 0 result = [] self.results = results def output(self):", "= [self.id2tag[id] for id in paths[0]] # entities_result = # [{'begin': 0, 'end':", "result = [] for testset in self.test_X: prediction = self.predict_sentence(testset) # predict_pos +", "= 0 counter = 0 results = [] result = [] for testset", "paths[0]] # entities_result = # [{'begin': 0, 'end': 3, 'words': '賈伯斯', 'type': 'name'},", "df = pd.DataFrame() for i, result in enumerate(self.results): results = pd.DataFrame(result).rename(columns=titles) results =", "results.append(result) article_id += 1 counter = 0 result = [] self.results = results", "BilstmCrfPredictor(NerPredictor): def __post_init__(self): vocab_file_path = self.model_data_path + \"vocab_file.txt\" tag_file_path = self.model_data_path + \"tag.txt\"", "read_vocab(tag_file_path) test_X_path = self.model_data_path + \"test_X.pkl\" test_mapping_path = self.model_data_path + \"test_mapping.pkl\" self.test_X, self.test_mapping", "self.model_data_path + \"vocab_file.txt\" tag_file_path = self.model_data_path + \"tag.txt\" self.voc2id, self.id2voc = read_vocab(vocab_file_path) self.tag2id,", "[[1445 33 1878 826 1949 1510 112]] dataset = tf.keras.preprocessing.sequence.pad_sequences( [[self.voc2id.get(char, 0) for", "# path[0] = tag in sentence # = [18, 19, 19, 1, 26,", "titles = { \"end\": \"end_position\", \"begin\": \"start_position\", \"words\": \"entity_text\", \"type\": \"entity_type\", } df", "dataclasses import dataclass from program.utils.write_output_file import format_result from program.abstracts.abstract_ner_predictor import NerPredictor @dataclass class", "'type': 'med_exam'}, {'begin': 245, 'end': 249, 'words': '1145', 'type': 'med_exam'}, ... ] ]", "pd.DataFrame() for i, result in enumerate(self.results): results = pd.DataFrame(result).rename(columns=titles) results = results[ [\"start_position\",", "logits = (1, 7, 28) = (sentence, words, predict_distrib) # text_lens = [7]", "GeneralDataPreprocessor.loadTestArrays( test_X_path, test_mapping_path ) self.model = BilstmCrfModel( hidden_num=self.hidden_nums, vocab_size=len(self.voc2id), label_size=len(self.tag2id), embedding_size=self.embedding_size, ) self.optimizer", "\"words\": \"entity_text\", \"type\": \"entity_type\", } df = pd.DataFrame() for i, result in enumerate(self.results):", "read_vocab(vocab_file_path) self.tag2id, self.id2tag = read_vocab(tag_file_path) test_X_path = self.model_data_path + \"test_X.pkl\" test_mapping_path = self.model_data_path", "logits, text_lens = self.model.predict(dataset) paths = [] for logit, text_len in zip(logits, text_lens):", "counter = 0 results = [] result = [] for testset in self.test_X:", "predict_pos + counter if prediction: for pred in prediction: pred[\"begin\"] += counter pred[\"end\"]", "= ['B-name', 'I-name', 'I-name', 'O', 'B-time', 'I-time', 'O'] result = [self.id2tag[id] for id", "# = [18, 19, 19, 1, 26, 27, 1] # result = ['B-name',", "dataclass from program.utils.write_output_file import format_result from program.abstracts.abstract_ner_predictor import NerPredictor @dataclass class BilstmCrfPredictor(NerPredictor): def", "self.id2voc = read_vocab(vocab_file_path) self.tag2id, self.id2tag = read_vocab(tag_file_path) test_X_path = self.model_data_path + \"test_X.pkl\" test_mapping_path", "{'begin': 245, 'end': 249, 'words': '1145', 'type': 'med_exam'}, ... ] ] \"\"\" titles", "import pandas as pd import tensorflow as tf import tensorflow_addons as tf_ad from", "BilstmCrfModel( hidden_num=self.hidden_nums, vocab_size=len(self.voc2id), label_size=len(self.tag2id), embedding_size=self.embedding_size, ) self.optimizer = tf.keras.optimizers.Adam(self.learning_rate) def predict_sentence(self, sentence): \"\"\"", "article_ids = pd.Series([i] * len(result), name=\"article_id\") df = df.append(pd.concat([article_ids, results], axis=1), ignore_index=True) df.to_csv(self.output_path", "self.predict_sentence(testset) # predict_pos + counter if prediction: for pred in prediction: pred[\"begin\"] +=", "prediction: for pred in prediction: pred[\"begin\"] += counter pred[\"end\"] += counter result.append(pred) counter", "19, 19, 1, 26, 27, 1] # result = ['B-name', 'I-name', 'I-name', 'O',", "[[self.voc2id.get(char, 0) for char in sentence]], padding=\"post\" ) # logits = (1, 7,", "<filename>program/predictor/predictor_bilstm_crf.py<gh_stars>1-10 from program.models.model_bilstm_crf import BilstmCrfModel from program.data_process.data_preprocessor import GeneralDataPreprocessor import pandas as pd", "if prediction: for pred in prediction: pred[\"begin\"] += counter pred[\"end\"] += counter result.append(pred)", "'words': '1100', 'type': 'med_exam'}, {'begin': 245, 'end': 249, 'words': '1145', 'type': 'med_exam'}, ...", "self.voc2id, self.id2voc = read_vocab(vocab_file_path) self.tag2id, self.id2tag = read_vocab(tag_file_path) test_X_path = self.model_data_path + \"test_X.pkl\"", "sentence]], padding=\"post\" ) # logits = (1, 7, 28) = (sentence, words, predict_distrib)", "padding=\"post\" ) # logits = (1, 7, 28) = (sentence, words, predict_distrib) #", "predict single sentence. Input: Raw text string \"\"\" # dataset = encode sentence", "tf import tensorflow_addons as tf_ad from program.utils.tokenization import read_vocab from dataclasses import dataclass", "33 1878 826 1949 1510 112]] dataset = tf.keras.preprocessing.sequence.pad_sequences( [[self.voc2id.get(char, 0) for char", "'name'}, # {'begin': 4, 'end': 6, 'words': '七號', 'type': 'time'}] entities_result = format_result(list(sentence),", "encode sentence # = [[1445 33 1878 826 1949 1510 112]] dataset =", "model=self.model) ckpt.restore(tf.train.latest_checkpoint(self.checkpoint_path)) article_id = 0 counter = 0 results = [] result =", "'七號', 'type': 'time'}] entities_result = format_result(list(sentence), result) return entities_result def predict(self): # restore", "restore model ckpt = tf.train.Checkpoint(optimizer=self.optimizer, model=self.model) ckpt.restore(tf.train.latest_checkpoint(self.checkpoint_path)) article_id = 0 counter = 0", "= GeneralDataPreprocessor.loadTestArrays( test_X_path, test_mapping_path ) self.model = BilstmCrfModel( hidden_num=self.hidden_nums, vocab_size=len(self.voc2id), label_size=len(self.tag2id), embedding_size=self.embedding_size, )", "paths.append(viterbi_path) # path[0] = tag in sentence # = [18, 19, 19, 1,", "self.model.predict(dataset) paths = [] for logit, text_len in zip(logits, text_lens): viterbi_path, _ =", "pd.DataFrame(result).rename(columns=titles) results = results[ [\"start_position\", \"end_position\", \"entity_text\", \"entity_type\"] ] article_ids = pd.Series([i] *", "tag_file_path = self.model_data_path + \"tag.txt\" self.voc2id, self.id2voc = read_vocab(vocab_file_path) self.tag2id, self.id2tag = read_vocab(tag_file_path)", "logit[:text_len], self.model.transition_params ) paths.append(viterbi_path) # path[0] = tag in sentence # = [18,", "['B-name', 'I-name', 'I-name', 'O', 'B-time', 'I-time', 'O'] result = [self.id2tag[id] for id in", "tf_ad from program.utils.tokenization import read_vocab from dataclasses import dataclass from program.utils.write_output_file import format_result", "program.models.model_bilstm_crf import BilstmCrfModel from program.data_process.data_preprocessor import GeneralDataPreprocessor import pandas as pd import tensorflow", "result = [self.id2tag[id] for id in paths[0]] # entities_result = # [{'begin': 0,", "i, result in enumerate(self.results): results = pd.DataFrame(result).rename(columns=titles) results = results[ [\"start_position\", \"end_position\", \"entity_text\",", "format_result(list(sentence), result) return entities_result def predict(self): # restore model ckpt = tf.train.Checkpoint(optimizer=self.optimizer, model=self.model)", "= self.predict_sentence(testset) # predict_pos + counter if prediction: for pred in prediction: pred[\"begin\"]", "text_lens): viterbi_path, _ = tf_ad.text.viterbi_decode( logit[:text_len], self.model.transition_params ) paths.append(viterbi_path) # path[0] = tag", "for pred in prediction: pred[\"begin\"] += counter pred[\"end\"] += counter result.append(pred) counter +=", "pred[\"end\"] += counter result.append(pred) counter += len(testset) if counter == self.test_mapping[article_id]: results.append(result) article_id", "self.model_data_path + \"test_mapping.pkl\" self.test_X, self.test_mapping = GeneralDataPreprocessor.loadTestArrays( test_X_path, test_mapping_path ) self.model = BilstmCrfModel(", "ckpt = tf.train.Checkpoint(optimizer=self.optimizer, model=self.model) ckpt.restore(tf.train.latest_checkpoint(self.checkpoint_path)) article_id = 0 counter = 0 results =", "1878 826 1949 1510 112]] dataset = tf.keras.preprocessing.sequence.pad_sequences( [[self.voc2id.get(char, 0) for char in", "result.append(pred) counter += len(testset) if counter == self.test_mapping[article_id]: results.append(result) article_id += 1 counter", "self.id2tag = read_vocab(tag_file_path) test_X_path = self.model_data_path + \"test_X.pkl\" test_mapping_path = self.model_data_path + \"test_mapping.pkl\"", "viterbi_path, _ = tf_ad.text.viterbi_decode( logit[:text_len], self.model.transition_params ) paths.append(viterbi_path) # path[0] = tag in", "self.model_data_path + \"tag.txt\" self.voc2id, self.id2voc = read_vocab(vocab_file_path) self.tag2id, self.id2tag = read_vocab(tag_file_path) test_X_path =", "predict_distrib) # text_lens = [7] logits, text_lens = self.model.predict(dataset) paths = [] for", "for logit, text_len in zip(logits, text_lens): viterbi_path, _ = tf_ad.text.viterbi_decode( logit[:text_len], self.model.transition_params )", "def __post_init__(self): vocab_file_path = self.model_data_path + \"vocab_file.txt\" tag_file_path = self.model_data_path + \"tag.txt\" self.voc2id,", "[ [ {'begin': 170, 'end': 174, 'words': '1100', 'type': 'med_exam'}, {'begin': 245, 'end':", "= (1, 7, 28) = (sentence, words, predict_distrib) # text_lens = [7] logits,", "'O'] result = [self.id2tag[id] for id in paths[0]] # entities_result = # [{'begin':", "'med_exam'}, ... ] ] \"\"\" titles = { \"end\": \"end_position\", \"begin\": \"start_position\", \"words\":", "= tag in sentence # = [18, 19, 19, 1, 26, 27, 1]", "'賈伯斯', 'type': 'name'}, # {'begin': 4, 'end': 6, 'words': '七號', 'type': 'time'}] entities_result", "entities_result = format_result(list(sentence), result) return entities_result def predict(self): # restore model ckpt =", "predict(self): # restore model ckpt = tf.train.Checkpoint(optimizer=self.optimizer, model=self.model) ckpt.restore(tf.train.latest_checkpoint(self.checkpoint_path)) article_id = 0 counter", "'type': 'time'}] entities_result = format_result(list(sentence), result) return entities_result def predict(self): # restore model", "self.model = BilstmCrfModel( hidden_num=self.hidden_nums, vocab_size=len(self.voc2id), label_size=len(self.tag2id), embedding_size=self.embedding_size, ) self.optimizer = tf.keras.optimizers.Adam(self.learning_rate) def predict_sentence(self,", "= encode sentence # = [[1445 33 1878 826 1949 1510 112]] dataset", "1949 1510 112]] dataset = tf.keras.preprocessing.sequence.pad_sequences( [[self.voc2id.get(char, 0) for char in sentence]], padding=\"post\"", "from program.models.model_bilstm_crf import BilstmCrfModel from program.data_process.data_preprocessor import GeneralDataPreprocessor import pandas as pd import", "0 result = [] self.results = results def output(self): \"\"\" results: [ [", "sentence # = [[1445 33 1878 826 1949 1510 112]] dataset = tf.keras.preprocessing.sequence.pad_sequences(", "# {'begin': 4, 'end': 6, 'words': '七號', 'type': 'time'}] entities_result = format_result(list(sentence), result)", "program.utils.tokenization import read_vocab from dataclasses import dataclass from program.utils.write_output_file import format_result from program.abstracts.abstract_ner_predictor", ") paths.append(viterbi_path) # path[0] = tag in sentence # = [18, 19, 19,", "= [] for testset in self.test_X: prediction = self.predict_sentence(testset) # predict_pos + counter", "'1145', 'type': 'med_exam'}, ... ] ] \"\"\" titles = { \"end\": \"end_position\", \"begin\":", "1] # result = ['B-name', 'I-name', 'I-name', 'O', 'B-time', 'I-time', 'O'] result =", "= { \"end\": \"end_position\", \"begin\": \"start_position\", \"words\": \"entity_text\", \"type\": \"entity_type\", } df =", "counter == self.test_mapping[article_id]: results.append(result) article_id += 1 counter = 0 result = []", "as pd import tensorflow as tf import tensorflow_addons as tf_ad from program.utils.tokenization import", "= [[1445 33 1878 826 1949 1510 112]] dataset = tf.keras.preprocessing.sequence.pad_sequences( [[self.voc2id.get(char, 0)", "tf_ad.text.viterbi_decode( logit[:text_len], self.model.transition_params ) paths.append(viterbi_path) # path[0] = tag in sentence # =", "\"\"\" predict single sentence. Input: Raw text string \"\"\" # dataset = encode", "path[0] = tag in sentence # = [18, 19, 19, 1, 26, 27," ]